From 197870a731f18dd9759e9cc97dfd298fda773251 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 16 Sep 2008 18:05:53 +0200 Subject: Remove remaining embedded JavaScript support. --- source4/configure.ac | 1 - source4/lib/appweb/README | 6 - source4/lib/appweb/config.m4 | 1 - source4/lib/appweb/config.mk | 25 - source4/lib/appweb/ejs-2.0/.bashrc | 153 - source4/lib/appweb/ejs-2.0/.exrc | 1 - source4/lib/appweb/ejs-2.0/.ignore | 57 - source4/lib/appweb/ejs-2.0/.loginrc | 218 - source4/lib/appweb/ejs-2.0/ejs/.ignore | 2 - source4/lib/appweb/ejs-2.0/ejs/Makefile | 61 - source4/lib/appweb/ejs-2.0/ejs/classes/.ignore | 1 - source4/lib/appweb/ejs-2.0/ejs/classes/Makefile | 21 - source4/lib/appweb/ejs-2.0/ejs/classes/ejsArray.c | 167 - source4/lib/appweb/ejs-2.0/ejs/classes/ejsDate.c | 197 - source4/lib/appweb/ejs-2.0/ejs/classes/ejsError.c | 140 - source4/lib/appweb/ejs-2.0/ejs/classes/ejsObject.c | 588 --- .../appweb/ejs-2.0/ejs/classes/ejsStndClasses.c | 144 - source4/lib/appweb/ejs-2.0/ejs/classes/ejsString.c | 381 -- source4/lib/appweb/ejs-2.0/ejs/classes/ejsXml.c | 1327 ------ source4/lib/appweb/ejs-2.0/ejs/ejs.c | 1378 ------ source4/lib/appweb/ejs-2.0/ejs/ejs.h | 849 ---- source4/lib/appweb/ejs-2.0/ejs/ejsClass.c | 273 -- source4/lib/appweb/ejs-2.0/ejs/ejsCmd.c | 468 -- source4/lib/appweb/ejs-2.0/ejs/ejsGarbage.c | 1214 ------ source4/lib/appweb/ejs-2.0/ejs/ejsLex.c | 1033 ----- source4/lib/appweb/ejs-2.0/ejs/ejsParser.c | 4514 -------------------- source4/lib/appweb/ejs-2.0/ejs/ejsVar.c | 4033 ----------------- source4/lib/appweb/ejs-2.0/ejs/ejsVar.h | 1091 ----- source4/lib/appweb/ejs-2.0/ejs/lib/event.js | 141 - source4/lib/appweb/ejs-2.0/ejs/lib/global.js | 34 - source4/lib/appweb/ejs-2.0/ejs/lib/startup.js | 15 - source4/lib/appweb/ejs-2.0/ejs/lib/timer.js | 158 - source4/lib/appweb/ejs-2.0/ejs/system/.ignore | 1 - source4/lib/appweb/ejs-2.0/ejs/system/Makefile | 27 - source4/lib/appweb/ejs-2.0/ejs/system/README.TXT | 63 - source4/lib/appweb/ejs-2.0/ejs/system/UNIX/.ignore | 1 - .../lib/appweb/ejs-2.0/ejs/system/UNIX/Makefile | 21 - .../lib/appweb/ejs-2.0/ejs/system/UNIX/ejsFile.c | 98 - .../appweb/ejs-2.0/ejs/system/UNIX/ejsFileSystem.c | 454 -- .../lib/appweb/ejs-2.0/ejs/system/UNIX/ejsHTTP.c | 488 --- source4/lib/appweb/ejs-2.0/ejs/system/WIN/.ignore | 1 - source4/lib/appweb/ejs-2.0/ejs/system/WIN/Makefile | 21 - .../lib/appweb/ejs-2.0/ejs/system/WIN/ejsFile.c | 98 - .../appweb/ejs-2.0/ejs/system/WIN/ejsFileSystem.c | 456 -- .../lib/appweb/ejs-2.0/ejs/system/WIN/ejsHTTP.c | 488 --- source4/lib/appweb/ejs-2.0/ejs/system/ejsGC.c | 326 -- source4/lib/appweb/ejs-2.0/ejs/system/ejsGlobal.c | 785 ---- source4/lib/appweb/ejs-2.0/ejs/system/ejsSystem.c | 112 - .../lib/appweb/ejs-2.0/ejs/system/ejsSystemApp.c | 49 - .../lib/appweb/ejs-2.0/ejs/system/ejsSystemDebug.c | 60 - .../lib/appweb/ejs-2.0/ejs/system/ejsSystemLog.c | 163 - .../appweb/ejs-2.0/ejs/system/ejsSystemMemory.c | 174 - source4/lib/appweb/ejs-2.0/exml/Makefile | 42 - source4/lib/appweb/ejs-2.0/exml/exml.h | 94 - source4/lib/appweb/ejs-2.0/exml/exmlParser.c | 752 ---- source4/lib/appweb/ejs-2.0/exml/files | 1 - source4/lib/appweb/ejs-2.0/mpr/Makefile | 41 - source4/lib/appweb/ejs-2.0/mpr/UNIX/Makefile | 16 - source4/lib/appweb/ejs-2.0/mpr/UNIX/mprFile.c | 86 - source4/lib/appweb/ejs-2.0/mpr/UNIX/mprPlatform.c | 218 - source4/lib/appweb/ejs-2.0/mpr/UNIX/mprTime.c | 163 - source4/lib/appweb/ejs-2.0/mpr/VXWORKS/Makefile | 16 - source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprFile.c | 85 - .../lib/appweb/ejs-2.0/mpr/VXWORKS/mprPlatform.c | 191 - source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprTime.c | 163 - source4/lib/appweb/ejs-2.0/mpr/WIN/Makefile | 16 - source4/lib/appweb/ejs-2.0/mpr/WIN/mprFile.c | 123 - source4/lib/appweb/ejs-2.0/mpr/WIN/mprPlatform.c | 378 -- source4/lib/appweb/ejs-2.0/mpr/WIN/mprTime.c | 192 - source4/lib/appweb/ejs-2.0/mpr/files | 14 - source4/lib/appweb/ejs-2.0/mpr/mpr.c | 340 -- source4/lib/appweb/ejs-2.0/mpr/mpr.h | 1027 ----- source4/lib/appweb/ejs-2.0/mpr/mprAlloc.c | 1775 -------- source4/lib/appweb/ejs-2.0/mpr/mprArray.c | 385 -- source4/lib/appweb/ejs-2.0/mpr/mprBuf.c | 535 --- source4/lib/appweb/ejs-2.0/mpr/mprGenFile.c | 336 -- source4/lib/appweb/ejs-2.0/mpr/mprGenTime.c | 195 - source4/lib/appweb/ejs-2.0/mpr/mprLock.c | 266 -- source4/lib/appweb/ejs-2.0/mpr/mprLog.c | 602 --- source4/lib/appweb/ejs-2.0/mpr/mprOs.h | 707 --- source4/lib/appweb/ejs-2.0/mpr/mprPrintf.c | 924 ---- source4/lib/appweb/ejs-2.0/mpr/mprString.c | 733 ---- source4/lib/appweb/ejs-2.0/mpr/mprSymbol.c | 279 -- source4/lib/appweb/ejs-2.0/mpr/mprUnix.h | 105 - source4/lib/appweb/ejs/config.h | 141 - source4/lib/appweb/ejs/ejs.h | 136 - source4/lib/appweb/ejs/ejsInternal.h | 295 -- source4/lib/appweb/ejs/ejsLex.c | 923 ---- source4/lib/appweb/ejs/ejsLib.c | 1090 ----- source4/lib/appweb/ejs/ejsParser.c | 2436 ----------- source4/lib/appweb/ejs/ejsProcs.c | 704 --- source4/lib/appweb/esp/esp.c | 1042 ----- source4/lib/appweb/esp/esp.h | 277 -- source4/lib/appweb/esp/espEnv.h | 128 - source4/lib/appweb/esp/espProcs.c | 249 -- source4/lib/appweb/mpr/miniMpr.c | 522 --- source4/lib/appweb/mpr/miniMpr.h | 301 -- source4/lib/appweb/mpr/var.c | 2215 ---------- source4/lib/appweb/mpr/var.h | 487 --- source4/main.mk | 2 - source4/pidl/lib/Parse/Pidl/Samba4/EJS.pm | 874 ---- source4/pidl/pidl | 14 +- source4/scripting/ejs/config.mk | 63 - source4/scripting/ejs/mprutil.c | 494 --- source4/scripting/ejs/smbcalls.c | 220 - source4/scripting/ejs/smbcalls.h | 42 - source4/scripting/ejs/smbcalls_auth.c | 243 -- source4/scripting/ejs/smbcalls_config.c | 228 - source4/scripting/ejs/smbcalls_creds.c | 275 -- source4/scripting/ejs/smbcalls_ldb.c | 772 ---- source4/scripting/ejs/smbcalls_options.c | 193 - source4/scripting/ejs/smbcalls_string.c | 529 --- source4/scripting/ejs/smbcalls_sys.c | 494 --- source4/scripting/ejs/smbscript.c | 129 - source4/web_server/config.mk | 1 + 115 files changed, 2 insertions(+), 48895 deletions(-) delete mode 100644 source4/lib/appweb/README delete mode 100644 source4/lib/appweb/config.m4 delete mode 100644 source4/lib/appweb/config.mk delete mode 100644 source4/lib/appweb/ejs-2.0/.bashrc delete mode 100644 source4/lib/appweb/ejs-2.0/.exrc delete mode 100644 source4/lib/appweb/ejs-2.0/.ignore delete mode 100644 source4/lib/appweb/ejs-2.0/.loginrc delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/.ignore delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/Makefile delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/classes/.ignore delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/classes/Makefile delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/classes/ejsArray.c delete mode 100755 source4/lib/appweb/ejs-2.0/ejs/classes/ejsDate.c delete mode 100755 source4/lib/appweb/ejs-2.0/ejs/classes/ejsError.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/classes/ejsObject.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/classes/ejsStndClasses.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/classes/ejsString.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/classes/ejsXml.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/ejs.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/ejs.h delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/ejsClass.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/ejsCmd.c delete mode 100755 source4/lib/appweb/ejs-2.0/ejs/ejsGarbage.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/ejsLex.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/ejsParser.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/ejsVar.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/ejsVar.h delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/lib/event.js delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/lib/global.js delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/lib/startup.js delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/lib/timer.js delete mode 100755 source4/lib/appweb/ejs-2.0/ejs/system/.ignore delete mode 100755 source4/lib/appweb/ejs-2.0/ejs/system/Makefile delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/system/README.TXT delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/system/UNIX/.ignore delete mode 100755 source4/lib/appweb/ejs-2.0/ejs/system/UNIX/Makefile delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/system/UNIX/ejsFile.c delete mode 100755 source4/lib/appweb/ejs-2.0/ejs/system/UNIX/ejsFileSystem.c delete mode 100755 source4/lib/appweb/ejs-2.0/ejs/system/UNIX/ejsHTTP.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/system/WIN/.ignore delete mode 100755 source4/lib/appweb/ejs-2.0/ejs/system/WIN/Makefile delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/system/WIN/ejsFile.c delete mode 100755 source4/lib/appweb/ejs-2.0/ejs/system/WIN/ejsFileSystem.c delete mode 100755 source4/lib/appweb/ejs-2.0/ejs/system/WIN/ejsHTTP.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/system/ejsGC.c delete mode 100755 source4/lib/appweb/ejs-2.0/ejs/system/ejsGlobal.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/system/ejsSystem.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemApp.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemDebug.c delete mode 100644 source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemLog.c delete mode 100755 source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemMemory.c delete mode 100644 source4/lib/appweb/ejs-2.0/exml/Makefile delete mode 100644 source4/lib/appweb/ejs-2.0/exml/exml.h delete mode 100644 source4/lib/appweb/ejs-2.0/exml/exmlParser.c delete mode 100644 source4/lib/appweb/ejs-2.0/exml/files delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/Makefile delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/UNIX/Makefile delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/UNIX/mprFile.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/UNIX/mprPlatform.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/UNIX/mprTime.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/VXWORKS/Makefile delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprFile.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprPlatform.c delete mode 100755 source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprTime.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/WIN/Makefile delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/WIN/mprFile.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/WIN/mprPlatform.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/WIN/mprTime.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/files delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mpr.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mpr.h delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mprAlloc.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mprArray.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mprBuf.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mprGenFile.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mprGenTime.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mprLock.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mprLog.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mprOs.h delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mprPrintf.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mprString.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mprSymbol.c delete mode 100644 source4/lib/appweb/ejs-2.0/mpr/mprUnix.h delete mode 100644 source4/lib/appweb/ejs/config.h delete mode 100644 source4/lib/appweb/ejs/ejs.h delete mode 100644 source4/lib/appweb/ejs/ejsInternal.h delete mode 100644 source4/lib/appweb/ejs/ejsLex.c delete mode 100644 source4/lib/appweb/ejs/ejsLib.c delete mode 100644 source4/lib/appweb/ejs/ejsParser.c delete mode 100644 source4/lib/appweb/ejs/ejsProcs.c delete mode 100644 source4/lib/appweb/esp/esp.c delete mode 100644 source4/lib/appweb/esp/esp.h delete mode 100644 source4/lib/appweb/esp/espEnv.h delete mode 100644 source4/lib/appweb/esp/espProcs.c delete mode 100644 source4/lib/appweb/mpr/miniMpr.c delete mode 100644 source4/lib/appweb/mpr/miniMpr.h delete mode 100644 source4/lib/appweb/mpr/var.c delete mode 100644 source4/lib/appweb/mpr/var.h delete mode 100644 source4/pidl/lib/Parse/Pidl/Samba4/EJS.pm delete mode 100644 source4/scripting/ejs/config.mk delete mode 100644 source4/scripting/ejs/mprutil.c delete mode 100644 source4/scripting/ejs/smbcalls.c delete mode 100644 source4/scripting/ejs/smbcalls.h delete mode 100644 source4/scripting/ejs/smbcalls_auth.c delete mode 100644 source4/scripting/ejs/smbcalls_config.c delete mode 100644 source4/scripting/ejs/smbcalls_creds.c delete mode 100644 source4/scripting/ejs/smbcalls_ldb.c delete mode 100644 source4/scripting/ejs/smbcalls_options.c delete mode 100644 source4/scripting/ejs/smbcalls_string.c delete mode 100644 source4/scripting/ejs/smbcalls_sys.c delete mode 100644 source4/scripting/ejs/smbscript.c diff --git a/source4/configure.ac b/source4/configure.ac index d03092c6b6..cfae02bb6c 100644 --- a/source4/configure.ac +++ b/source4/configure.ac @@ -104,7 +104,6 @@ m4_include(lib/nss_wrapper/config.m4) m4_include(auth/config.m4) m4_include(kdc/config.m4) m4_include(ntvfs/sysdep/config.m4) -m4_include(lib/appweb/config.m4) m4_include(nsswitch/config.m4) ################################################# diff --git a/source4/lib/appweb/README b/source4/lib/appweb/README deleted file mode 100644 index bdc943446b..0000000000 --- a/source4/lib/appweb/README +++ /dev/null @@ -1,6 +0,0 @@ -The lib/appweb directory is a partial import of the appweb ejs and esp -code from http://www.appwebserver.org/ - -Many thanks to the mbedthis people, and especially Michael O'Brien for -his assistance in getting this code integrated into Samba4. - diff --git a/source4/lib/appweb/config.m4 b/source4/lib/appweb/config.m4 deleted file mode 100644 index 69b4048c4a..0000000000 --- a/source4/lib/appweb/config.m4 +++ /dev/null @@ -1 +0,0 @@ -AC_CHECK_HEADERS(math.h) diff --git a/source4/lib/appweb/config.mk b/source4/lib/appweb/config.mk deleted file mode 100644 index 4d27b69fb5..0000000000 --- a/source4/lib/appweb/config.mk +++ /dev/null @@ -1,25 +0,0 @@ -####################### -# Start SUBSYSTEM MPR -[SUBSYSTEM::MPR] -# End SUBSYSTEM MPR -####################### - -MPR_OBJ_FILES = $(addprefix $(appwebsrcdir)/mpr/, miniMpr.o var.o) - -####################### -# Start SUBSYSTEM EJS -[SUBSYSTEM::EJS] -PUBLIC_DEPENDENCIES = MPR -# End SUBSYSTEM EJS -####################### - -EJS_OBJ_FILES = $(addprefix $(appwebsrcdir)/ejs/, ejsLib.o ejsLex.o ejsParser.o ejsProcs.o) - -####################### -# Start SUBSYSTEM ESP -[SUBSYSTEM::ESP] -PUBLIC_DEPENDENCIES = EJS -# End SUBSYSTEM ESP -####################### - -ESP_OBJ_FILES = $(addprefix $(appwebsrcdir)/esp/, esp.o espProcs.o) diff --git a/source4/lib/appweb/ejs-2.0/.bashrc b/source4/lib/appweb/ejs-2.0/.bashrc deleted file mode 100644 index c05ee0e6e8..0000000000 --- a/source4/lib/appweb/ejs-2.0/.bashrc +++ /dev/null @@ -1,153 +0,0 @@ -# -# .bashrc -- Login shell startup script for windows using Mbedthis winTools -# -# Copyright (c) Mbedthis Software, 2003-2005. All Rights Reserved. -# - -TERM=ansi -# -# Set the desired .NET Framework -# -# FRAMEWORK=v1.0.3705 -FRAMEWORK=v1.1.4322 -# FRAMEWORK=v2.0.40607 - -# -# Set the desired Microsoft C Compiler version -# -# PREFERRED_CC=VS2005 -# PREFERRED_CC=VS2003 -# PREFERRED_CC=VS.NET -PREFERRED_CC=VS6 - -# -# Set to 1 if VXWORKS support is required -# -# VXWORKS=1 - -HOME=`pwd` -if [ ! -x winTools -o ! -x winTools/cygpath.exe ] -then - echo "Can't find build tools. Install build tools in $HOME/winTools" -fi - -ROOT=`winTools/cygpath -u $HOMEDRIVE` -: ${ROOT:=C:/} -APPWEB_PATH="${HOME}/bin/DEBUG:${HOME}/bin/RELEASE:${HOME}/bin:${HOME}/winTools" -CDPATH=".:${HOME}:${HOME}/http:${HOME}/http/modules:${HOME}/packages" -PS1="$ " - -export CDPATH INCLUDE LIB LIBPATH PATH PS1 TERM - -echo -e "\n\n###################################################" -echo "Mbedthis AppWeb, Cygwin build tools." -echo "Using compiler: $PREFERRED_CC, .NET framework: $FRAMEWORK" -echo -e "###################################################" - -################################################################################ - -# -# Setup for Visual Studio and SDK -# -if [ $PREFERRED_CC == "VS2005" ] -then - # - # Visual Studio .NET 2005 defines. - # - CYNET="${ROOT}/Program Files/Microsoft Visual Studio 8" - DOSNET="C:/Program Files/Microsoft Visual Studio 8" - PATH="$APPWEB_PATH:$CYNET/Common7/IDE:$CYNET/VC/BIN:$CYNET/VC/VCPackages:$CYNET/Common7/Tools:$CYNET/Common7/Tools/bin:$CYNET/SDK/v2.0/bin:`cygpath -W`/Microsoft.NET/Framework/v2.0.40607:$CYNET/SDK/v2.0/bin:$PATH" - INCLUDE="$DOSNET/VC/ATLMFC/INCLUDE;$DOSNET/VC/INCLUDE;$DOSNET/VC/PlatformSDK/include;$DOSNET/SDK/v2.0/include;$INCLUDE" - LIB="$DOSNET/VC/ATLMFC/LIB;$DOSNET/VC/LIB;$DOSNET/VC/PlatformSDK/lib;$DOSNET/SDK/v2.0/lib;$LIB" - LIBPATH=c:/WINDOWS/Microsoft.NET/Framework/$FRAMEWORK -fi - -if [ $PREFERRED_CC == "VS2003" ] -then - # - # Visual Studio .NET 2003 defines. - # - CYNET="${ROOT}/Program Files/Microsoft Visual Studio .NET 2003" - DOSNET="C:/Program Files/Microsoft Visual Studio .NET 2003" - PATH="$APPWEB_PATH:$CYNET/Common7/IDE:$CYNET/VC7/BIN:$CYNET/Common7/Tools:$CYNET/Common7/Tools/bin/prerelease:$CYNET/Common7/Tools/bin:$CYNET/FrameworkSDK/bin:${ROOT}/WINDOWS/Microsoft.NET/Framework/$FRAMEWORK:$CYNET/SDK/v1.1/bin:$PATH" - INCLUDE="$DOSNET/VC7/ATLMFC/INCLUDE;$DOSNET/VC7/INCLUDE;$DOSNET/VC7/PlatformSDK/include/prerelease;$DOSNET/VC7/PlatformSDK/include;$DOSNET/FrameworkSDK/include;$INCLUDE" - LIB="$DOSNET/VC7/ATLMFC/LIB;$DOSNET/VC7/LIB;$DOSNET/VC7/PlatformSDK/lib/prerelease;$DOSNET/VC7/PlatformSDK/lib;$DOSNET/FrameworkSDK/lib;$LIB" -fi - - -if [ $PREFERRED_CC == "VS.NET" ] -then - # - # Visual Studio .NET defines. - # - CYNET="${ROOT}/Program Files/Microsoft Visual Studio .NET" - DOSNET="C:/Program Files/Microsoft Visual Studio .NET" - PATH="$APPWEB_PATH:$CYNET/Common7/IDE:$CYNET/VC7/BIN:$CYNET/Common7/Tools:$CYNET/Common7/Tools/bin/prerelease:$CYNET/Common7/Tools/bin:$CYNET/FrameworkSDK/bin:${ROOT}/WINDOWS/Microsoft.NET/Framework/$FRAMEWORK:$CYNET/SDK/v1.0/bin:$PATH" - INCLUDE="$DOSNET/VC7/ATLMFC/INCLUDE;$DOSNET/VC7/INCLUDE;$DOSNET/VC7/PlatformSDK/include/prerelease;$DOSNET/VC7/PlatformSDK/include;$DOSNET/FrameworkSDK/include;$INCLUDE" - LIB="$DOSNET/VC7/ATLMFC/LIB;$DOSNET/VC7/LIB;$DOSNET/VC7/PlatformSDK/lib/prerelease;$DOSNET/VC7/PlatformSDK/lib;$DOSNET/FrameworkSDK/lib;$LIB" -fi - - -if [ $PREFERRED_CC == "VS6" ] -then - # Visual Studio 6 defines. - # - CYNET="${ROOT}/Program Files/Microsoft Visual Studio" - DOSNET="C:/Program Files/Microsoft Visual Studio" - PATH="$APPWEB_PATH:$CYNET/Common/MSDev98/bin:$CYNET/VC98/BIN:$CYNET/Common/IDE:$CYNET/Common/Tools/WinNT:$CYNET/Common/Tools:$PATH" - INCLUDE="$DOSNET/VC98/ATLMFC/INCLUDE;$DOSNET/VC98/INCLUDE;$DOSNET/VC98/MFC/INCLUDE;$INCLUDE" - LIB="$DOSNET/VC98/LIB;$DOSNET/VC98/MFC/LIB;$LIB" -fi - -if [ $VXWORKS ] -then - # - # Required by VxWorks - # - WIND_BASE=C:/tornado - WIND_HOST_TYPE=x86-win32 - WIND_REGISTRY=coalsack - WIND_LMHOST=coalsack - BLD_VX_HOST=i386-wrs-vxworks - VX_TOOLS=`cygpath $WIND_BASE`/host/$WIND_HOST_TYPE - export WIND_BASE WIND_HOST_TYPE WIND_REGISTRY WIND_LMHOST BLD_VX_HOST - - # - # Use cygwin make and tools by preference - # - PATH="$APPWEB_PATH:$VX_TOOLS/bin:$PATH" -fi - -# -# Make required directories for CYGWIN -# -if [ ! -x /bin/bash.exe ] -then - DIR=`cygpath -w "$HOME/winTools"` - echo -e "\nCreating /bin" - echo Mounting \"${DIR}\" as /bin - mount -f -b "$DIR" /bin -fi - -if [ ! -x /tmp ] -then - mkdir -p tmp - DIR=`cygpath -w "$HOME/tmp"` - echo -e "\nCreating /tmp" - echo Mounting \"${DIR}\" as /tmp - mount -f -b "$DIR" /tmp -fi -echo - -################################################################################ -# -# Do a bit of validation -# -type cl 2>/dev/null >/dev/null -if [ $? -ne 0 ] -then - echo "Can't find compiler: cl. Check WIN/bashrc settings for PATH" -fi -set -o vi - -################################################################################ diff --git a/source4/lib/appweb/ejs-2.0/.exrc b/source4/lib/appweb/ejs-2.0/.exrc deleted file mode 100644 index dd37846529..0000000000 --- a/source4/lib/appweb/ejs-2.0/.exrc +++ /dev/null @@ -1 +0,0 @@ -set ts=4 sw=4 diff --git a/source4/lib/appweb/ejs-2.0/.ignore b/source4/lib/appweb/ejs-2.0/.ignore deleted file mode 100644 index 866f06c6c1..0000000000 --- a/source4/lib/appweb/ejs-2.0/.ignore +++ /dev/null @@ -1,57 +0,0 @@ -*.class -*.dll -*.exe -*.exp -*.jar -*.lib -*.lnk -*.map -*.new -*.old -*.pdb -*.res -*.sln -*.suo -*.sym -*.tmp -*.sav -.ICEauthority -.bash_history -.changes -.cvsignore -.esd_auth -.fonts.cache-1 -.viminfo -make.dep -thumbs.db -vc70.pdb -*.ncb -*.opt -*.idb -*.pch -*.dep -*.aps -all -tmp -make.vars -sh.vars -config.make -config.h -config.sh -configure -make.os -.firstBuild -.viminfo -.ssh -_viminfo -buildConfig.h -buildConfig.make -buildConfig.sh -.ccache -appWeb.kdev* -subversion -.vimrc -.subversion -.ignore -njs -msvc diff --git a/source4/lib/appweb/ejs-2.0/.loginrc b/source4/lib/appweb/ejs-2.0/.loginrc deleted file mode 100644 index 90b76a2ad0..0000000000 --- a/source4/lib/appweb/ejs-2.0/.loginrc +++ /dev/null @@ -1,218 +0,0 @@ -# -# .loginrc -- Michael's login shell startup script (used only for Windows) -# -# NOTE: this should not be distributed with releases. -# -# Copyright (c) Mbedthis Software, 2003-2005. All Rights Reserved. -# -HOME=`pwd` - -TERM=ansi -CYROOT=/cygdrive/c -JDK="/cygdrive/c/program files/java/jdk1.5.0_07/bin" -H=$CYROOT -R=usr/svn/appWeb/main -CDPATH=".:${H}/usr/svn/appWeb:${H}/${R}/http:${H}/${R}/http/modules:${H}/${R}:${H}/usr/svn/appWeb/releases:${H}/usr/svn/packages:${H}/usr/svn/bling/player/trunk:${H}/usr/svn/bling/player/trunk/src:${H}/usr/svn/bling/player/trunk/appdir:${H}/usr/svn:${H}:${H}/usr/svn:${H}/usr" -APPWEB_PATH="${H}/${R}/bin/DEBUG:${H}/${R}/bin/RELEASE:${H}/${R}/bin:${H}/usr/bin" -PATH="${H}/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:$PATH:${H}/tcl/bin:${JDK}" - -CLASSPATH="c:/usr/svn/j/ggperf" -PS1='`cygpath -m $PWD`> ' -SVN_EDITOR=C:/cygwin/bin/vim.exe - -umask 022 - -export TERM CDPATH INCLUDE LIB LIBPATH PATH PS1 SVN_EDITOR MSCL CLASSPATH - -################################################################################ -# -# Set the dev environment PATH and other critical environment variables -# - -# export BLD_ALTERNATE_CONFIG=WIN/buildConfig - -# -# Desired .NET Framework -# -# FRAMEWORK=v1.0.3705 -# FRAMEWORK=v1.1.4322 -FRAMEWORK=v2.0.50727 - -# -# Desired C Compiler -# -# MSCL=VS2005 -# MSCL=VS2003 -# MSCL=VS.NET -MSCL=VS6 -VXWORKS=1 - -echo "Using compiler: $MSCL, .NET framework: $FRAMEWORK" - -# -# Setup for Visual Studio and SDK -# -if [ $MSCL == "VS2005" ] -then - # - # Visual Studio .NET 2005 defines. - # - CYNET="$H/Program Files/Microsoft Visual Studio 8" - DOSNET="C:/Program Files/Microsoft Visual Studio 8" - PATH="$APPWEB_PATH:$CYNET/Common7/IDE:$CYNET/VC/BIN:$CYNET/VC/VCPackages:$CYNET/Common7/Tools:$CYNET/Common7/Tools/bin:$CYNET/SDK/v2.0/bin:$CYROOT/WINDOWS/Microsoft.NET/Framework/v2.0.40607:$CYNET/SDK/v2.0/bin:$PATH" - INCLUDE="$DOSNET/VC/ATLMFC/INCLUDE;$DOSNET/VC/INCLUDE;$DOSNET/VC/PlatformSDK/include;$DOSNET/SDK/v2.0/include;$INCLUDE" - LIB="$DOSNET/VC/ATLMFC/LIB;$DOSNET/VC/LIB;$DOSNET/VC/PlatformSDK/lib;$DOSNET/SDK/v2.0/lib;$LIB" - LIBPATH=c:/WINDOWS/Microsoft.NET/Framework/$FRAMEWORK - - # MOB -- old - # PATH="$APPWEB_PATH:$CYNET/Common7/IDE:$CYNET/VC/BIN:$CYNET/Common7/Tools:$CYNET/Common7/Tools/bin/prerelease:$CYNET/Common7/Tools/bin:$CYNET/FrameworkSDK/bin:$H/WINDOWS/Microsoft.NET/Framework/$FRAMEWORK:$PATH" - # INCLUDE="$DOSNET/VC/ATLMFC/INCLUDE;$DOSNET/VC/INCLUDE;$DOSNET/VC/PlatformSDK/include/prerelease;$DOSNET/VC/PlatformSDK/include;$DOSNET/FrameworkSDK/include;$INCLUDE" - # LIB="$DOSNET/VC/ATLMFC/LIB;$DOSNET/VC/LIB;$DOSNET/VC/PlatformSDK/lib/prerelease;$DOSNET/VC/PlatformSDK/lib;$DOSNET/FrameworkSDK/lib;$LIB" -fi - -if [ $MSCL == "VS2003" ] -then - # - # Visual Studio .NET 2003 defines. - # - CYNET="$H/Program Files/Microsoft Visual Studio .NET 2003" - DOSNET="C:/Program Files/Microsoft Visual Studio .NET 2003" - PATH="$APPWEB_PATH:$CYNET/Common7/IDE:$CYNET/VC7/BIN:$CYNET/Common7/Tools:$CYNET/Common7/Tools/bin/prerelease:$CYNET/Common7/Tools/bin:$CYNET/FrameworkSDK/bin:$H/WINDOWS/Microsoft.NET/Framework/$FRAMEWORK:$CYNET/SDK/v1.1/bin:$PATH" - INCLUDE="$DOSNET/VC7/ATLMFC/INCLUDE;$DOSNET/VC7/INCLUDE;$DOSNET/VC7/PlatformSDK/include/prerelease;$DOSNET/VC7/PlatformSDK/include;$DOSNET/FrameworkSDK/include;$INCLUDE" - LIB="$DOSNET/VC7/ATLMFC/LIB;$DOSNET/VC7/LIB;$DOSNET/VC7/PlatformSDK/lib/prerelease;$DOSNET/VC7/PlatformSDK/lib;$DOSNET/FrameworkSDK/lib;$LIB" -fi - - -if [ $MSCL == "VS.NET" ] -then - # - # Visual Studio .NET defines. - # - CYNET="$H/Program Files/Microsoft Visual Studio .NET" - DOSNET="C:/Program Files/Microsoft Visual Studio .NET" - PATH="$APPWEB_PATH:$CYNET/Common7/IDE:$CYNET/VC7/BIN:$CYNET/Common7/Tools:$CYNET/Common7/Tools/bin/prerelease:$CYNET/Common7/Tools/bin:$CYNET/FrameworkSDK/bin:$H/WINDOWS/Microsoft.NET/Framework/$FRAMEWORK:$CYNET/SDK/v1.0/bin:$PATH" - INCLUDE="$DOSNET/VC7/ATLMFC/INCLUDE;$DOSNET/VC7/INCLUDE;$DOSNET/VC7/PlatformSDK/include/prerelease;$DOSNET/VC7/PlatformSDK/include;$DOSNET/FrameworkSDK/include;$INCLUDE" - LIB="$DOSNET/VC7/ATLMFC/LIB;$DOSNET/VC7/LIB;$DOSNET/VC7/PlatformSDK/lib/prerelease;$DOSNET/VC7/PlatformSDK/lib;$DOSNET/FrameworkSDK/lib;$LIB" -fi - - -if [ $MSCL == "VS6" ] -then - # Visual Studio 6 defines. - # - CYNET="$H/Program Files/Microsoft Visual Studio" - DOSNET="C:/Program Files/Microsoft Visual Studio" - PATH="$APPWEB_PATH:$CYNET/Common/MSDev98/bin:$CYNET/VC98/BIN:$CYNET/Common/IDE:$CYNET/Common/Tools/WinNT:$CYNET/Common/Tools:$PATH" - # OLD PATH="$APPWEB_PATH:$CYNET/Common/IDE:$CYNET/VC98/BIN:$CYNET/Common/MSDev98/bin:$CYNET/Common/Tools:$CYNET/Common/Tools/bin/prerelease:$CYNET/Common/Tools/bin:$CYNET/FrameworkSDK/bin:$H/WINDOWS/Microsoft.NET/Framework/$FRAMEWORK:$PATH" - INCLUDE="$DOSNET/VC98/ATLMFC/INCLUDE;$DOSNET/VC98/INCLUDE;$DOSNET/VC98/MFC/INCLUDE;$INCLUDE" - LIB="$DOSNET/VC98/LIB;$DOSNET/VC98/MFC/LIB;$LIB" -fi - -if [ $VXWORKS ] -then - # - # Required by VxWorks - # - WIND_BASE=C:/tornado - WIND_HOST_TYPE=x86-win32 - WIND_REGISTRY=coalsack - WIND_LMHOST=coalsack - BLD_VX_HOST=i386-wrs-vxworks - export WIND_BASE WIND_HOST_TYPE WIND_REGISTRY WIND_LMHOST BLD_VX_HOST - - VX_TOOLS=`cygpath $WIND_BASE`/host/$WIND_HOST_TYPE - # - # Use cygwin make and tools by preference - # - PATH="$APPWEB_PATH:$PATH:$VX_TOOLS/bin" -fi - -# -# Make required directories for CYGWIN -# -if [ ! -x /bin/bash.exe ] -then - DIR=`cygpath -w "$HOME/winTools"` - echo -e "\nCreating /bin" - echo Mounting \"${DIR}\" as /bin - mount -f -b "$DIR" /bin -fi - -if [ ! -x /tmp ] -then - mkdir -p tmp - DIR=`cygpath -w "$HOME/tmp"` - echo -e "\nCreating /tmp" - echo Mounting \"${DIR}\" as /tmp - mount -f -b "$DIR" /tmp -fi -echo - - -################################################################################ -# -# Do a bit of validation (MOB -- extend) -# -type cl 2>/dev/null >/dev/null -if [ $? -ne 0 ] -then - echo "Can't find compiler: cl. Check WIN/bashrc settings for PATH" -fi - -################################################################################ -# -# Some convenient functions -# -pvi () { - - pattern=$1 - shift - files=$* - if [ -z "${files}" ] - then - files='*.c *.cpp *.h Makefile *.html *.aspx *.cs' - fi - vi -c "/${pattern}" $(grep -l "${pattern}" ${files}) -} - -################################################################################ - -g() { - pattern=$1 - shift - files=$* - if [ -z "${files}" ] - then - files=`echo *.c *.cpp *.h Makefile *.html *.aspx *.cs` - fi - eval grep "${pattern}" ${files} -} - -################################################################################ - -usedvi() { - pvi $1 $HOME/mr/*.c $HOME/mr/*.h $HOME/mr/WIN/*.c $HOME/lib/*/*.c -} - -################################################################################ - -alias ls='ls -CF $*' -alias lc='ls -CF $*' -alias lr='ls -R $*' -alias xwin='startxwin.sh' -alias htmlview='"C:/Program Files/Internet Explorer/iexplore.exe" $*' -set -o vi - -if [ `uname -o` = "Cygwin" ] -then - alias vim='"C:/Program Files/vim/vim64/vim.exe" $*' - alias gvim='"C:/Program Files/vim/vim64/gvim.exe" $*' -fi - -brew() { - "C:/Program Files/BREW SDK v2.1.3/Bin/BREW_Emulator.exe" -} - -js() { - cscript /nologo $* -} diff --git a/source4/lib/appweb/ejs-2.0/ejs/.ignore b/source4/lib/appweb/ejs-2.0/ejs/.ignore deleted file mode 100644 index 47f4ac63b2..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/.ignore +++ /dev/null @@ -1,2 +0,0 @@ -ejs -future diff --git a/source4/lib/appweb/ejs-2.0/ejs/Makefile b/source4/lib/appweb/ejs-2.0/ejs/Makefile deleted file mode 100644 index ea6be8c401..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -# -# Makefile for Embedded Javascript (EJS) -# -# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. -# - -# -# Ejs may be linked into shared handlers so we must build the objects both -# shared and static if --shared was specified to configure. -# -COMPILE := *.c -EXPORT_OBJECTS := yes -PRE_DIRS := classes system db -MAKE_IFLAGS := -I../mpr -I../exml - -include make.dep - -ifeq ($(BLD_PRODUCT),ejs) -POST_DIRS := package -endif - -ifeq ($(BLD_FEATURE_TEST),1) -POST_DIRS += test -endif - -ifeq ($(BLD_FEATURE_EJS_DB),1) -LIBS += sqlite -endif - -TARGETS += $(BLD_BIN_DIR)/libejs$(BLD_LIB) -TARGETS += $(BLD_BIN_DIR)/ejs$(BLD_EXE) - -ifeq ($(BLD_FEATURE_EJS),1) -compileExtra: $(TARGETS) -endif - -$(BLD_BIN_DIR)/libejs$(BLD_LIB): files \ - $(shell BLD_OBJ=$(BLD_OBJ) \; BLD_OBJ_DIR=$(BLD_OBJ_DIR) \; \ - eval echo `cat files`) - @bld --library $(BLD_BIN_DIR)/libejs \ - --objectsDir $(BLD_OBJ_DIR) --objectList files \ - --libs "exml mpr $(LIBS)" - -$(BLD_BIN_DIR)/ejs$(BLD_EXE): $(BLD_BIN_DIR)/libejs$(BLD_LIB) \ - $(BLD_BIN_DIR)/libmpr$(BLD_LIB) \ - $(BLD_BIN_DIR)/libejs$(BLD_LIB) $(FILES) - @bld --executable $(BLD_BIN_DIR)/ejs$(BLD_EXE) \ - --rpath "$(BLD_PREFIX)/bin" \ - --preferStatic --smartLibs "ejs exml mpr $(LIBS)" \ - --objectsDir $(BLD_OBJ_DIR) \ - --objects "$(BLD_OBJ_DIR)/ejsCmd$(BLD_OBJ)" - -cleanExtra: - @echo "rm -f $(TARGETS)" | $(BLDOUT) - @rm -f $(TARGETS) - @rm -f $(BLD_BIN_DIR)/libejs.* - -## Local variables: -## tab-width: 4 -## End: -## vim: tw=78 sw=4 ts=4 diff --git a/source4/lib/appweb/ejs-2.0/ejs/classes/.ignore b/source4/lib/appweb/ejs-2.0/ejs/classes/.ignore deleted file mode 100644 index fb5a29031e..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/classes/.ignore +++ /dev/null @@ -1 +0,0 @@ -.updated diff --git a/source4/lib/appweb/ejs-2.0/ejs/classes/Makefile b/source4/lib/appweb/ejs-2.0/ejs/classes/Makefile deleted file mode 100644 index ce12bb3829..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/classes/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -# -# Makefile to build the EJS Classes -# -# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. -# - -COMPILE := *.c -EXPORT_OBJECTS := yes -MAKE_IFLAGS := -I.. -I../../mpr -I../../exml - -include make.dep - -compileExtra: .updated - -.updated: $(FILES) - @touch .updated - -## Local variables: -## tab-width: 4 -## End: -## vim: tw=78 sw=4 ts=4 diff --git a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsArray.c b/source4/lib/appweb/ejs-2.0/ejs/classes/ejsArray.c deleted file mode 100644 index feb64b1aa8..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsArray.c +++ /dev/null @@ -1,167 +0,0 @@ -/* - * @file ejsArray.c - * @brief Array class - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if BLD_FEATURE_EJS - -/************************************ Code ************************************/ - -int ejsDefineArrayClass(Ejs *ep) -{ - if (ejsDefineClass(ep, "Array", "Object", ejsArrayConstructor) == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - return 0; -} - -/******************************************************************************/ -/* - * Routine to create the base array type - */ - -EjsVar *ejsCreateArrayInternal(EJS_LOC_DEC(ep, loc), int size) -{ - EjsProperty *pp; - EjsVar *obj, *vp; - - /* MOB -- need to supply hash size -- max(size, 503)); */ - - obj = ejsCreateSimpleObjInternal(EJS_LOC_PASS(ep, loc), "Array"); - if (obj == 0) { - mprAssert(0); - return obj; - } - obj->isArray = 1; - - /* MOB -- call constructor here and replace this code */ - - pp = ejsSetPropertyToInteger(ep, obj, "length", size); - ejsMakePropertyEnumerable(pp, 0); - - vp = ejsGetVarPtr(pp); - vp->isArrayLength = 1; - - return obj; -} - -/******************************************************************************/ - -EjsVar *ejsAddArrayElt(Ejs *ep, EjsVar *op, EjsVar *element, - EjsCopyDepth copyDepth) -{ - EjsProperty *pp; - EjsVar *vp; - char idx[16]; - int length; - - mprAssert(op->isArray); - - length = ejsGetPropertyAsInteger(ep, op, "length"); - - mprItoa(idx, sizeof(idx), length); - pp = ejsCreateProperty(ep, op, idx); - vp = ejsGetVarPtr(pp); - - ejsWriteVar(ep, vp, element, copyDepth); - - ejsSetPropertyToInteger(ep, op, "length", length + 1); - - return vp; -} - -/******************************************************************************/ -/* - * Constructor - */ - -int ejsArrayConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - EjsProperty *pp; - EjsVar *vp; - char idx[16]; - int i, max; - - thisObj->isArray = 1; - max = 0; - - if (argc > 0) { - if (argc == 1 && ejsVarIsNumber(argv[0])) { - /* - * x = new Array(size); - */ - max = (int) ejsVarToInteger(argv[0]); - - } else { - /* - * x = new Array(element0, element1, ..., elementN): - */ - max = argc; - for (i = 0; i < max; i++) { - mprItoa(idx, sizeof(idx), i); - pp = ejsCreateSimpleProperty(ep, thisObj, idx); - vp = ejsGetVarPtr(pp); - ejsWriteVar(ep, vp, argv[i], EJS_SHALLOW_COPY); - } - } - } - - pp = ejsCreateSimpleProperty(ep, thisObj, "length"); - ejsMakePropertyEnumerable(pp, 0); - vp = ejsGetVarPtr(pp); - ejsWriteVarAsInteger(ep, vp, max); - vp->isArrayLength = 1; - - return 0; -} - -/******************************************************************************/ - -#else -void ejsArrayDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsDate.c b/source4/lib/appweb/ejs-2.0/ejs/classes/ejsDate.c deleted file mode 100755 index 096316a822..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsDate.c +++ /dev/null @@ -1,197 +0,0 @@ -/* - * @file ejsStndClasses.c - * @brief EJS support methods - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if BLD_FEATURE_EJS && 0 - -/******************************************************************************/ -/* - * Date constructor - - * - * Date(); - * Date(milliseconds); - * Date(dateString); - * Date(year, month, date); - * Date(year, month, date, hour, minute, second); - */ - -int ejsDateConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - return 0; -} - -/******************************************************************************/ - -static int load(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - const char *fileName; - XmlState *parser; - Exml *xp; - MprFile *file; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ep, EJS_ARG_ERROR, "Bad args. Usage: load(fileName);"); - return -1; - } - fileName = argv[0]->string; - - /* FUTURE -- not romable - Need rom code in MPR not MprServices - */ - file = mprOpen(ep, fileName, O_RDONLY, 0664); - if (file == 0) { - ejsError(ep, EJS_IO_ERROR, "Can't open: %s", fileName); - return -1; - } - - xp = initParser(ep, thisObj, fileName); - parser = exmlGetParseArg(xp); - - exmlSetInputStream(xp, readFileData, (void*) file); - - if (exmlParse(xp) < 0) { - if (! ejsGotException(ep)) { - ejsError(ep, EJS_IO_ERROR, "Can't parse XML file: %s\nDetails %s", - fileName, exmlGetErrorMsg(xp)); - } - termParser(xp); - mprClose(file); - return -1; - } - - ejsSetReturnValue(ep, parser->nodeStack[0].obj); - - termParser(xp); - mprClose(file); - - return 0; -} - -/******************************************************************************/ - -int ejsDefineDateClass(Ejs *ep) -{ - EjsVar *dateClass; - - dateClass = ejsDefineClass(ep, "Date", "Object", ejsDateConstructor); - if (dateClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - ejsDefineCMethod(ep, dateClass, "getDate", xxxProc, EJS_NO_LOCAL); - - /* Returns "Friday" or 4 ? */ - ejsDefineCMethod(ep, dateClass, "getDay", xxxProc, EJS_NO_LOCAL); - - ejsDefineCMethod(ep, dateClass, "getMonth", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "getFullYear", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "getYear", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "getHours", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "getMinutes", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "getSeconds", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "getMilliseconds", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "getTime", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "getTimeZoneOffset", xxxProc, EJS_NO_LOCAL); - - ejsDefineCMethod(ep, dateClass, "parse", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "setDate", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "setMonth", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "setFullYear", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "setYear", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "setMinutes", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "setSeconds", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "setMilliseconds", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "setTime", xxxProc, EJS_NO_LOCAL); - - ejsDefineCMethod(ep, dateClass, "toString", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "toGMTString", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "toUTCString", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "toLocaleString", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "UTC", xxxProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, dateClass, "valueOf", xxxProc, EJS_NO_LOCAL); - /* - UTC: getUTCDate, getUTCDay, getUTCMonth, getUTCFullYear, getUTCHours, - getUTCMinutes, getUTCSeconds, getUTCMilliseconds - setUTCDate, setUTCDay, setUTCMonth, setUTCFullYear, setUTCHours, - setUTCMinutes, setUTCSeconds, setUTCMilliseconds - */ - - return ejsObjHasErrors(dateClass) ? MPR_ERR_CANT_INITIALIZE : 0; -} - -/******************************************************************************/ -/* - Time is since 1970/01/01 GMT - - Normal: Fri Feb 10 2006 05:06:44 GMT-0800 (Pacific Standard Time) - UTC: Sat, 11 Feb 2006 05:06:44 GMT - - // Using without New - - println(Date()); - - var myDate = new Date(); - myDate.setFullYear(2010, 0, 14); - - var today = new Date(); - - if (myDate > today) { - } else { - } - - - X=Date() should be equivalent to X=(new Date()).toString() - - */ -/******************************************************************************/ - -#else -void ejsStndClassesDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsError.c b/source4/lib/appweb/ejs-2.0/ejs/classes/ejsError.c deleted file mode 100755 index 99445afc7c..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsError.c +++ /dev/null @@ -1,140 +0,0 @@ -/* - * @file ejsError.c - * @brief Error class - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if BLD_FEATURE_EJS - -/************************************ Code ************************************/ -/* - * Parse the args and return the message. Convert non-string args using - * .toString. - */ - -static char *getMessage(Ejs *ep, int argc, EjsVar **argv) -{ - if (argc == 0) { - return ""; - - } else if (argc == 1) { - if (! ejsVarIsString(argv[0])) { - if (ejsRunMethod(ep, argv[0], "toString", 0) < 0) { - return 0; - } - return ep->result->string; - - } else { - return argv[0]->string; - } - - } else { - /* Don't call ejsError here or it will go recursive. */ - return 0; - } -} - - -/******************************************************************************/ -/* - * Error Constructor and also used for constructor for sub classes. - * - * Usage: new Error([message]) - */ - -int ejsErrorCons(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - char *msg, *stack; - - msg = getMessage(ep, argc, argv); - if (msg == 0) { - return -1; - } - - ejsSetPropertyToString(ep, thisObj, "name", ejsGetBaseClassName(thisObj)); - ejsSetPropertyToString(ep, thisObj, "message", msg); - - ejsSetPropertyToUndefined(ep, thisObj, "stack"); - - stack = ejsFormatStack(ep); - if (stack) { - ejsSetPropertyToString(ep, thisObj, "stack", stack); - mprFree(stack); - } - - if (ejsObjHasErrors(thisObj)) { - return -1; - } - - return 0; -} - -/******************************************************************************/ - -int ejsDefineErrorClasses(Ejs *ep) -{ - if (ejsDefineClass(ep, "Error", "Object", ejsErrorCons) == 0 || - ejsDefineClass(ep, "AssertError", "Error", ejsErrorCons) == 0 || - ejsDefineClass(ep, "EvalError", "Error", ejsErrorCons) == 0 || - ejsDefineClass(ep, "InternalError", "Error", ejsErrorCons) == 0 || - ejsDefineClass(ep, "IOError", "Error", ejsErrorCons) == 0 || - ejsDefineClass(ep, "MemoryError", "Error", ejsErrorCons) == 0 || - ejsDefineClass(ep, "RangeError", "Error", ejsErrorCons) == 0 || - ejsDefineClass(ep, "ReferenceError", "Error", ejsErrorCons) == 0 || - ejsDefineClass(ep, "SyntaxError", "Error", ejsErrorCons) == 0 || - ejsDefineClass(ep, "TypeError", "Error", ejsErrorCons) == 0) { - - return MPR_ERR_CANT_INITIALIZE; - } - return 0; -} - -/******************************************************************************/ - -#else -void ejsErrorDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsObject.c b/source4/lib/appweb/ejs-2.0/ejs/classes/ejsObject.c deleted file mode 100644 index 4f2e23beb2..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsObject.c +++ /dev/null @@ -1,588 +0,0 @@ -/* - * @file ejsObject.c - * @brief Object class - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if BLD_FEATURE_EJS - -/****************************** Forward Declarations **************************/ -/* - * Support routines - */ - -static void formatVar(Ejs *ep, MprBuf *bp, EjsVar *vp); - -/******************************************************************************/ -/* - * Routine to create an object of the desired class. Class name may - * contain "." - * - * The created object will be a stand-alone class NOT entered into the - * properties of any other object. Callers must do this if required. ClassName - * may contain "." and is interpreted relative to "obj" if supplied. - * - * Note: this does not call the constructors for the various objects and base - * classes. - */ - -EjsVar *ejsCreateSimpleObjInternal(EJS_LOC_DEC(ep, loc), const char *className) -{ - EjsVar *baseClass; - - if (className && *className) { - baseClass = ejsGetClass(ep, 0, className); - if (baseClass == 0) { - mprError(ep, MPR_LOC, "Can't find base class %s", className); - return 0; - } - } else { - baseClass = 0; - } - - return ejsCreateSimpleObjUsingClassInt(EJS_LOC_PASS(ep, loc), - baseClass); -} - -/******************************************************************************/ -/* - * Create an object based upon the specified base class object. It will be a - * stand-alone class not entered into the properties of any other object. - * Callers must do this if required. - * - * Note: this does not call the constructors for the various objects and base - * classes. - */ - -EjsVar *ejsCreateSimpleObjUsingClassInt(EJS_LOC_DEC(ep, loc), - EjsVar *baseClass) -{ - EjsVar *vp; - - mprAssert(baseClass); - - if (baseClass == 0) { - mprError(ep, MPR_LOC, "Missing base class\n"); - return 0; - } - - vp = ejsCreateObjVarInternal(EJS_LOC_PASS(ep, loc)); - if (vp == 0) { - return vp; - } - - ejsSetBaseClass(vp, baseClass); - - /* - * This makes all internal method accesses faster - * NOTE: this code is duplicated in ejsCreateSimpleClass - */ - mprAssert(vp->objectState); - vp->objectState->methods = baseClass->objectState->methods; - - return vp; -} - -/******************************************************************************/ - -void ejsSetMethods(Ejs *ep, EjsVar *op) -{ - op->objectState->methods = ep->global->objectState->methods; -} - -/******************************************************************************/ -/******************************** Internal Methods ****************************/ -/******************************************************************************/ - -static EjsVar *createObjProperty(Ejs *ep, EjsVar *obj, const char *property) -{ - return ejsGetVarPtr(ejsCreateSimpleProperty(ep, obj, property)); -} - -/******************************************************************************/ - -static int deleteObjProperty(Ejs *ep, EjsVar *obj, const char *property) -{ - return ejsDeleteProperty(ep, obj, property); -} - -/******************************************************************************/ - -static EjsVar *getObjProperty(Ejs *ep, EjsVar *obj, const char *property) -{ - return ejsGetVarPtr(ejsGetSimpleProperty(ep, obj, property)); -} - -/******************************************************************************/ -/* - * Set the value of a property. Create if it does not exist - */ - -static EjsVar *setObjProperty(Ejs *ep, EjsVar *obj, const char *property, - const EjsVar *value) -{ - EjsProperty *pp; - EjsVar *vp; - - pp = ejsCreateSimpleProperty(ep, obj, property); - if (pp == 0) { - mprAssert(pp); - return 0; - } - vp = ejsGetVarPtr(pp); - if (ejsWriteVar(ep, vp, value, EJS_SHALLOW_COPY) < 0) { - mprAssert(0); - return 0; - } - return ejsGetVarPtr(pp); -} - -/******************************************************************************/ -/*********************************** Constructors *****************************/ -/******************************************************************************/ -#if UNUSED -/* - * Object constructor. We don't use this for speed. Think very carefully if - * you add an object constructor. - */ - -int ejsObjectConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - return 0; -} - -#endif -/******************************************************************************/ -/******************************** Visible Methods *****************************/ -/******************************************************************************/ - -static int cloneMethod(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int copyDepth; - - copyDepth = EJS_DEEP_COPY; - - if (argc == 1 && ejsVarToBoolean(argv[0])) { - copyDepth = EJS_RECURSIVE_DEEP_COPY; - } - - ejsWriteVar(ep, ep->result, thisObj, copyDepth); - - return 0; -} - -/******************************************************************************/ - -static int toStringMethod(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - MprBuf *bp; - int saveMaxDepth, saveDepth, saveFlags; - - saveMaxDepth = ep->maxDepth; - - if (argc >= 1) { - ep->maxDepth = ejsVarToInteger(argv[0]); - } else if (ep->maxDepth == 0) { - ep->maxDepth = MAXINT; - } - - saveFlags = ep->flags; - if (argc >= 2) { - if (ejsVarToBoolean(argv[1])) { - ep->flags |= EJS_FLAGS_ENUM_HIDDEN; - } - } - if (argc == 3) { - if (ejsVarToBoolean(argv[2])) { - ep->flags |= EJS_FLAGS_ENUM_BASE; - } - } - - bp = mprCreateBuf(ep, 0, 0); - - saveDepth = ep->depth; - - formatVar(ep, bp, thisObj); - - ep->depth = saveDepth; - ep->maxDepth = saveMaxDepth; - - mprAddNullToBuf(bp); - - ejsWriteVarAsString(ep, ep->result, mprGetBufStart(bp)); - mprFree(bp); - - ep->flags = saveFlags; - - return 0; -} - -/******************************************************************************/ - -static int valueOfMethod(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 0) { - mprAssert(0); - return -1; - } - - switch (thisObj->type) { - default: - case EJS_TYPE_UNDEFINED: - case EJS_TYPE_NULL: - case EJS_TYPE_CMETHOD: - case EJS_TYPE_OBJECT: - case EJS_TYPE_METHOD: - case EJS_TYPE_STRING_CMETHOD: - ejsWriteVar(ep, ep->result, thisObj, EJS_SHALLOW_COPY); - break; - - case EJS_TYPE_STRING: - ejsWriteVarAsInteger(ep, ep->result, atoi(thisObj->string)); - break; - - case EJS_TYPE_BOOL: - case EJS_TYPE_INT: -#if BLD_FEATURE_INT64 - case EJS_TYPE_INT64: -#endif -#if BLD_FEATURE_FLOATING_POINT - case EJS_TYPE_FLOAT: -#endif - ejsWriteVar(ep, ep->result, thisObj, EJS_SHALLOW_COPY); - break; - } - return 0; -} - -/******************************************************************************/ - -static int hashGetAccessor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsSetReturnValueToInteger(ejs, (int) thisObj->objectState); - return 0; -} - -/******************************************************************************/ - -static int classGetAccessor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (thisObj->objectState == 0 || thisObj->objectState->baseClass == 0) { - ejsSetReturnValueToString(ejs, "object"); - } else { - ejsSetReturnValueToString(ejs, - thisObj->objectState->baseClass->objectState->className); - } - return 0; -} - -/******************************************************************************/ -/* - * Format an object. Called recursively to format properties and contained - * objects. - */ - -static void formatVar(Ejs *ep, MprBuf *bp, EjsVar *vp) -{ - EjsProperty *pp, *first; - EjsVar *propVar, *baseClass; - char *buf, *value; - int i; - - if (vp->type == EJS_TYPE_OBJECT) { - if (!vp->objectState->visited) { - - mprPutStringToBuf(bp, vp->isArray ? "[\n" : "{\n"); - - ep->depth++; - vp->objectState->visited = 1; - - if (ep->depth <= ep->maxDepth) { - first = ejsGetFirstProperty(vp, EJS_ENUM_ALL); - - if (ep->flags & EJS_FLAGS_ENUM_BASE) { - baseClass = vp->objectState->baseClass; - if (baseClass) { - for (i = 0; i < ep->depth; i++) { - mprPutStringToBuf(bp, " "); - } - mprPutStringToBuf(bp, baseClass->objectState->objName); - mprPutStringToBuf(bp, ": /* Base Class */ "); - if (baseClass->objectState == vp->objectState) { - value = "this"; - } else if (ejsRunMethodCmd(ep, baseClass, "toString", - "%d", ep->maxDepth) < 0) { - value = "[object Object]"; - } else { - mprAssert(ejsVarIsString(ep->result)); - value = ep->result->string; - } - mprPutStringToBuf(bp, value); - if (first) { - mprPutStringToBuf(bp, ",\n"); - } - } - } - - pp = first; - while (pp) { - if (! pp->dontEnumerate || - ep->flags & EJS_FLAGS_ENUM_HIDDEN) { - for (i = 0; i < ep->depth; i++) { - mprPutStringToBuf(bp, " "); - } - - if (! vp->isArray) { - mprPutStringToBuf(bp, pp->name); - mprPutStringToBuf(bp, ": "); - } - - propVar = ejsGetVarPtr(pp); - if (propVar->type == EJS_TYPE_OBJECT) { - if (pp->var.objectState == vp->objectState) { - value = "this"; - } else if (ejsRunMethodCmd(ep, propVar, - "toString", "%d", ep->maxDepth) < 0) { - value = "[object Object]"; - } else { - mprAssert(ejsVarIsString(ep->result)); - value = ep->result->string; - } - mprPutStringToBuf(bp, value); - - } else { - formatVar(ep, bp, &pp->var); - } - - pp = ejsGetNextProperty(pp, EJS_ENUM_ALL); - if (pp) { - mprPutStringToBuf(bp, ",\n"); - } - } else { - pp = ejsGetNextProperty(pp, EJS_ENUM_ALL); - } - } - } - vp->objectState->visited = 0; - - mprPutCharToBuf(bp, '\n'); - - ep->depth--; - for (i = 0; i < ep->depth; i++) { - mprPutStringToBuf(bp, " "); - } - mprPutCharToBuf(bp, vp->isArray ? ']' : '}'); - } - - } else if (vp->type == EJS_TYPE_METHOD) { - - mprPutStringToBuf(bp, "function ("); - for (i = 0; i < vp->method.args->length; i++) { - mprPutStringToBuf(bp, vp->method.args->items[i]); - if ((i + 1) < vp->method.args->length) { - mprPutStringToBuf(bp, ", "); - } - } - mprPutStringToBuf(bp, ") {"); - mprPutStringToBuf(bp, vp->method.body); - for (i = 0; i < ep->depth; i++) { - mprPutStringToBuf(bp, " "); - } - mprPutStringToBuf(bp, "}"); - - } else { - - if (vp->type == EJS_TYPE_STRING) { - mprPutCharToBuf(bp, '\"'); - } - - /* - * We don't use ejsVarToString for arrays, objects and strings. - * This is because ejsVarToString does not call "obj.toString" - * and it is not required for strings. - * MOB - rc - */ - buf = ejsVarToString(ep, vp); - mprPutStringToBuf(bp, buf); - - if (vp->type == EJS_TYPE_STRING) { - mprPutCharToBuf(bp, '\"'); - } - } -} - -/******************************************************************************/ -/* - * mixin code. Blends code at the "thisObj" level. - */ - -static int mixinMethod(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - EjsProperty *pp; - char *buf; - int fid, i, rc; - - mprAssert(argv); - - /* - * Create a variable scope block set to the current object - */ - rc = 0; - fid = ejsSetBlock(ep, thisObj); - - for (i = 0; i < argc; i++) { - - if (ejsVarIsString(argv[i])) { - rc = ejsEvalScript(ep, argv[i]->string, 0); - - } else if (ejsVarIsObject(argv[i])) { - - /* MOB -- OPT. When we have proper scope chains, we should just - refer to the module and not copy */ - pp = ejsGetFirstProperty(argv[i], EJS_ENUM_ALL); - while (pp) { - ejsSetProperty(ep, thisObj, pp->name, ejsGetVarPtr(pp)); - pp = ejsGetNextProperty(pp, EJS_ENUM_ALL); - } - - } else { - /* MOB - rc */ - buf = ejsVarToString(ep, argv[i]); - rc = ejsEvalScript(ep, buf, 0); - - } - if (rc < 0) { - ejsCloseBlock(ep, fid); - return -1; - } - } - ejsCloseBlock(ep, fid); - return 0; -} - -/******************************************************************************/ -/* - * Create the object class - */ - -int ejsDefineObjectClass(Ejs *ep) -{ - EjsMethods *methods; - EjsProperty *objectProp, *protoProp; - EjsVar *op, *globalClass; - - /* - * Must specially hand-craft the object class as it is the base class - * of all objects. - */ - op = ejsCreateObjVar(ep); - if (op == 0) { - return MPR_ERR_CANT_CREATE; - } - ejsSetClassName(ep, op, "Object"); - - /* - * Don't use a constructor for objects for speed - */ - ejsMakeClassNoConstructor(op); - - /* - * MOB -- should mark properties as public / private and class or instance. - */ - ejsDefineCMethod(ep, op, "clone", cloneMethod, EJS_NO_LOCAL); - ejsDefineCMethod(ep, op, "toString", toStringMethod, EJS_NO_LOCAL); - ejsDefineCMethod(ep, op, "valueOf", valueOfMethod, EJS_NO_LOCAL); - ejsDefineCMethod(ep, op, "mixin", mixinMethod, EJS_NO_LOCAL); - - ejsDefineCAccessors(ep, op, "hash", hashGetAccessor, 0, EJS_NO_LOCAL); - ejsDefineCAccessors(ep, op, "baseClass", classGetAccessor, 0, EJS_NO_LOCAL); - - /* - * MOB -- make this an accessor - */ - protoProp = ejsSetProperty(ep, op, "prototype", op); - if (protoProp == 0) { - ejsFreeVar(ep, op); - return MPR_ERR_CANT_CREATE; - } - - /* - * Setup the internal methods. Most classes will never override these. - * The XML class will. We rely on talloc to free internal. Use "ep" as - * the parent as we need "methods" to live while the interpreter lives. - */ - methods = mprAllocTypeZeroed(ep, EjsMethods); - op->objectState->methods = methods; - - methods->createProperty = createObjProperty; - methods->deleteProperty = deleteObjProperty; - methods->getProperty = getObjProperty; - methods->setProperty = setObjProperty; - - objectProp = ejsSetPropertyAndFree(ep, ep->global, "Object", op); - - /* - * Change the global class to use Object's methods - */ - globalClass = ep->service->globalClass; - globalClass->objectState->methods = methods; - globalClass->objectState->baseClass = ejsGetVarPtr(protoProp); - - ep->objectClass = ejsGetVarPtr(objectProp); - - if (ejsObjHasErrors(ejsGetVarPtr(objectProp))) { - ejsFreeVar(ep, op); - return MPR_ERR_CANT_CREATE; - } - return 0; -} - -/******************************************************************************/ - -#else -void ejsObjectDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsStndClasses.c b/source4/lib/appweb/ejs-2.0/ejs/classes/ejsStndClasses.c deleted file mode 100644 index fd6cda7813..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsStndClasses.c +++ /dev/null @@ -1,144 +0,0 @@ -/* - * @file ejsStndClasses.c - * @brief EJS support methods - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if BLD_FEATURE_EJS - -/******************************************************************************/ -/******************************* Function Class *******************************/ -/******************************************************************************/ - -int ejsDefineFunctionClass(Ejs *ep) -{ - if (ejsDefineClass(ep, "Function", "Object", ejsFunctionConstructor) == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - return 0; -} - -/******************************************************************************/ -/* - * Function constructor - */ - -int ejsFunctionConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int rc; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsArgError(ep, "Usage: Function(\"function (arg) { script };\");"); - } - - rc = ejsEvalScript(ep, argv[0]->string, 0); - - /* - * Note: this will convert the object into a method. It will cease to be - * an object. - */ - if (rc == 0 && ejsVarIsMethod(ep->result)) { - /* - * Must make thisObj collectable. - */ - ejsMakeObjPermanent(thisObj, 0); - ejsMakeObjLive(thisObj, 1); - mprAssert(ejsObjIsCollectable(thisObj)); - ejsWriteVar(ep, thisObj, ep->result, EJS_SHALLOW_COPY); - } - return rc; -} - -/******************************************************************************/ -/******************************* Boolean Class ********************************/ -/******************************************************************************/ - -int ejsDefineBooleanClass(Ejs *ep) -{ - if (ejsDefineClass(ep, "Boolean", "Object", ejsBooleanConstructor) == 0){ - return MPR_ERR_CANT_INITIALIZE; - } - return 0; -} - -/******************************************************************************/ -/* - * Boolean constructor - */ - -int ejsBooleanConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - return 0; -} - -/******************************************************************************/ -/******************************** Number Class ********************************/ -/******************************************************************************/ - -int ejsDefineNumberClass(Ejs *ep) -{ - if (ejsDefineClass(ep, "Number", "Object", ejsNumberConstructor) == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - return 0; -} - -/******************************************************************************/ -/* - * Number constructor - */ - -int ejsNumberConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - return 0; -} - -/******************************************************************************/ - -#else -void ejsStndClassesDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsString.c b/source4/lib/appweb/ejs-2.0/ejs/classes/ejsString.c deleted file mode 100644 index 2339650361..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsString.c +++ /dev/null @@ -1,381 +0,0 @@ -/* - * @file ejsString.c - * @brief EJScript string class - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if BLD_FEATURE_EJS -/******************************************************************************/ -/*********************************** Constructors *****************************/ -/******************************************************************************/ -/* - * String constructor. - */ - -int ejsStringConstructor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - char *str; - - if (argc == 0) { - ejsSetReturnValueToString(ejs, ""); - - } else if (argc == 1) { - /* MOB -- rc */ - str = ejsVarToString(ejs, argv[0]); - ejsSetReturnValueToString(ejs, str); - - } else { - ejsArgError(ejs, "usage: String([var])"); - return -1; - } - - return 0; -} - -/******************************************************************************/ -/******************************** Visible Methods *****************************/ -/******************************************************************************/ -/* - * Return a string containing the character at a given index - * - * String string.charAt(Number) - */ - -static int charAt(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - EjsNum num; - char buf[2]; - - if (argc != 1) { - ejsArgError(ejs, "usage: charAt(integer)"); - return -1; - } - - num = ejsVarToNumber(argv[0]); - if (num < 0 || num >= thisObj->length) { - ejsError(ejs, EJS_RANGE_ERROR, "Bad index"); - return -1; - } - - mprAssert(ejsVarIsString(thisObj)); - - buf[0] = argv[0]->string[num]; - buf[1] = '\0'; - ejsSetReturnValueToString(ejs, buf); - - return 0; -} - -/******************************************************************************/ -/* - * Return an integer containing the character at a given index - * - * Number string.charCodeAt(Number) - */ - -static EjsNum charCodeAt(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - EjsNum num; - - if (argc != 1) { - ejsArgError(ejs, "usage: charCodeAt(integer)"); - return -1; - } - - num = ejsVarToNumber(argv[0]); - if (num < 0 || num >= thisObj->length) { - ejsError(ejs, EJS_RANGE_ERROR, "Bad index"); - return -1; - } - ejsSetReturnValueToNumber(ejs, (EjsNum) argv[0]->string[num]); - - return 0; -} - -/******************************************************************************/ -/* - * Catenate - * - * String string.catenate(var, ...) - */ - -static int concat(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int i; - - if (argc == 0) { - ejsArgError(ejs, "usage: concat(String, ...)"); - return -1; - } - - mprAssert(ejsVarIsString(thisObj)); - - for (i = 0; i < argc; i++) { - if (ejsStrcat(ejs, thisObj, argv[i]) < 0) { - ejsMemoryError(ejs); - return -1; - } - } - ejsSetReturnValue(ejs, thisObj); - return 0; -} - -/******************************************************************************/ -/* - * Return the position of the first occurance of a substring - * - * Number string.indexOf(String subString [, Number start]) - */ - -static int indexOf(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - char *pat, *s1, *s2, *origin; - int start, i; - - if (argc == 0 || argc > 2) { - ejsArgError(ejs, "usage: indexOf(String [, Number])"); - return -1; - } - - pat = ejsVarToString(ejs, argv[0]); - - if (argc == 2) { - start = ejsVarToNumber(argv[1]); - if (start > thisObj->length) { - start = thisObj->length; - } - } else { - start = 0; - } - - i = start; - for (origin = &thisObj->string[i]; i < thisObj->length; i++, origin++) { - s1 = origin; - for (s2 = pat; *s1 && *s2; s1++, s2++) { - if (*s1 != *s2) { - break; - } - } - if (*s2 == '\0') { - ejsSetReturnValueToNumber(ejs, (EjsNum) (origin - thisObj->string)); - } - } - - ejsSetReturnValueToNumber(ejs, (EjsNum) -1); - return 0; -} - -/******************************************************************************/ -/* - * Return the position of the last occurance of a substring - * - * Number string.lastIndexOf(String subString [, Number start]) - */ - -static int lastIndexOf(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - char *pat, *s1, *s2, *origin; - int start; - - if (argc == 0 || argc > 2) { - ejsArgError(ejs, "usage: indexOf(String [, Number])"); - return -1; - } - - pat = ejsVarToString(ejs, argv[0]); - - if (argc == 2) { - start = ejsVarToNumber(argv[1]); - if (start > thisObj->length) { - start = thisObj->length; - } - } else { - start = 0; - } - - origin = &thisObj->string[thisObj->length - 1]; - for (; origin >= &thisObj->string[start]; origin--) { - - s1 = origin; - for (s2 = pat; *s1 && *s2; s1++, s2++) { - if (*s1 != *s2) { - break; - } - } - if (*s2 == '\0') { - ejsSetReturnValueToNumber(ejs, (EjsNum) (origin - thisObj->string)); - } - } - - ejsSetReturnValueToNumber(ejs, (EjsNum) -1); - return 0; -} - -/******************************************************************************/ -/* - * Return a substring - * - * Number string.slice(Number start, Number end) - */ - -static int slice(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - EjsNum start, end; - - if (argc != 2) { - ejsArgError(ejs, "usage: slice(Number, Number)"); - return -1; - } - - start = ejsVarToNumber(argv[0]); - end = ejsVarToNumber(argv[1]); - if (start < 0 || start >= thisObj->length) { - ejsError(ejs, EJS_RANGE_ERROR, "Bad start index"); - return-1; - } - if (end < 0 || end >= thisObj->length) { - ejsError(ejs, EJS_RANGE_ERROR, "Bad end index"); - return -1; - } - - mprAssert(ejsVarIsString(thisObj)); - - ejsSetReturnValueToBinaryString(ejs, (uchar*) &thisObj->string[start], - end - start); - - return 0; -} - -/******************************************************************************/ -/* - * Split a string - * - * Number string.split(String delimiter [, Number limit]) - */ - -static int split(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - EjsVar *array, *vp; - char *delim, *last, *cp; - int len, limit, alloc; - - if (argc == 0 || argc > 2) { - ejsArgError(ejs, "usage: split(String [, Number])"); - return -1; - } - - delim = ejsVarToStringEx(ejs, argv[0], &alloc); - - limit = ejsVarToNumber(argv[1]); - - array = ejsCreateArray(ejs, 0); - - len = strlen(delim); - - last = thisObj->string; - for (cp = last; *cp; cp++) { - if (*cp == *delim && strncmp(cp, delim, len) == 0) { - if (cp > last) { - vp = ejsCreateBinaryStringVar(ejs, (uchar*) last, (cp - last)); - ejsAddArrayElt(ejs, array, vp, EJS_SHALLOW_COPY); - ejsFreeVar(ejs, vp); - } - } - } - - ejsSetReturnValue(ejs, array); - ejsFreeVar(ejs, array); - - if (alloc) { - mprFree(delim); - } - - return 0; -} - -/******************************************************************************/ -/* - * Create the object class - */ - -int ejsDefineStringClass(Ejs *ejs) -{ - EjsVar *sc; - - sc = ejsDefineClass(ejs, "String", "Object", ejsStringConstructor); - if (sc == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - ejsDefineCMethod(ejs, sc, "charAt", charAt, EJS_NO_LOCAL); - ejsDefineCMethod(ejs, sc, "charCodeAt", charCodeAt, EJS_NO_LOCAL); - ejsDefineCMethod(ejs, sc, "concat", concat, EJS_NO_LOCAL); - ejsDefineCMethod(ejs, sc, "indexOf", indexOf, EJS_NO_LOCAL); - ejsDefineCMethod(ejs, sc, "lastIndexOf", lastIndexOf, EJS_NO_LOCAL); - ejsDefineCMethod(ejs, sc, "slice", slice, EJS_NO_LOCAL); - ejsDefineCMethod(ejs, sc, "split", split, EJS_NO_LOCAL); -#if UNUSED - ejsDefineCMethod(ejs, sc, "match", match, EJS_NO_LOCAL); - ejsDefineCMethod(ejs, sc, "replace", replace, EJS_NO_LOCAL); - ejsDefineCMethod(ejs, sc, "search", search, EJS_NO_LOCAL); - ejsDefineCMethod(ejs, sc, "substring", substring, EJS_NO_LOCAL); - // MOB bad name - ejsDefineCMethod(ejs, sc, "substr", substr, EJS_NO_LOCAL); - ejsDefineCMethod(ejs, sc, "toLowerCase", toLowerCase, EJS_NO_LOCAL); - ejsDefineCMethod(ejs, sc, "toUpperCase", toUpperCase, EJS_NO_LOCAL); - - // Static method - ejsDefineCMethod(ejs, sc, "fromCharCode", fromCharCode, 0, EJS_NO_LOCAL); -#endif - - if (ejsObjHasErrors(sc)) { - ejsFreeVar(ejs, sc); - return MPR_ERR_CANT_CREATE; - } - return 0; -} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsXml.c b/source4/lib/appweb/ejs-2.0/ejs/classes/ejsXml.c deleted file mode 100644 index a2ef8d1390..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/classes/ejsXml.c +++ /dev/null @@ -1,1327 +0,0 @@ -/* - * @file ejsXml.c - * @brief E4X XML support - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/************************************ Doc *************************************/ -/* - * Javascript class definition - * - * class XML { - * public XML(); - * public XML(string xmlString); // ""); - Operators: - var prices = order..price; - var urgentItems = order.item(@level == "rush"); - var itemAttrs = order.item[0].@*; # @ for attributes - XML Literals - order.customer.address = -
..... - {zipCode} Where {var} is a JS var - ... Also for attributes -
- Omit namespaces - Example: - var html = ; - html.head.title = "My title"; - head.body@bgcolor = "#e4e4e4"; -*/ - -/********************************** Includes **********************************/ - -#include "ejs.h" -#include "exml.h" - -/************************************ Data ************************************/ -#if BLD_FEATURE_EJS_E4X - -/* - * Per tag state - */ -typedef struct XmlTagState { - EjsVar *obj; - EjsVar *attributes; - EjsVar *comments; -} XmlTagState; - -/* - * Parser state - */ -typedef struct XmlState { - Ejs *ep; - EjsVar *xmlClass; - EjsVar *xmlListClass; - XmlTagState nodeStack[E4X_MAX_NODE_DEPTH]; - int topOfStack; - long inputSize; - long inputPos; - const char *inputBuf; - const char *fileName; -} XmlState; - -/****************************** Forward Declarations **************************/ -/* - * XML methods - */ -static int text(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int name(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int load(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int save(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int toString(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int valueOf(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); - -/* MOB -- temp */ -static int getList(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int setText(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); - -#if FUTURE -static int length(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int toXmlString(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); - -static int appendChild(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int attributes(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int child(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int children(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int comments(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int decendants(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int elements(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int insertChildAfter(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int insertChildBefore(Ejs *ep, EjsVar *thisObj, int argc, - EjsVar **argv); -static int replace(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int setName(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -static int text(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv); -#endif - -/* - * Internal methods - */ -static EjsVar *createXmlProperty(Ejs *ep, EjsVar *obj, const char *property); -static int deleteXmlProperty(Ejs *ep, EjsVar *obj, const char *property); -static EjsVar *getXmlProperty(Ejs *ep, EjsVar *obj, const char *property); -static EjsVar *setXmlProperty(Ejs *ep, EjsVar *obj, const char *property, - const EjsVar *value); -static int loadXmlString(Ejs *ep, EjsVar *thisObj, const char *xmlString); - -/* - * XMLList methods - */ -static EjsVar *createXmlListProperty(Ejs *ep, EjsVar *obj, - const char *property); -static int deleteXmlListProperty(Ejs *ep, EjsVar *obj, - const char *property); -static EjsVar *getXmlListProperty(Ejs *ep, EjsVar *obj, const char *property); -static EjsVar *setXmlListProperty(Ejs *ep, EjsVar *obj, const char *property, - const EjsVar *value); - -/* - * Misc - */ -static int readFileData(Exml *xp, void *data, char *buf, int size); -static int readStringData(Exml *xp, void *data, char *buf, int size); -static int parserHandler(Exml *xp, int state, const char *tagName, - const char *attName, const char *value); -static void termParser(Exml *xp); -static Exml *initParser(Ejs *ep, EjsVar *thisObj, const char *fileName); -static int getNumElements(EjsVar *obj); -static int getText(MprBuf *buf, EjsVar *obj); -static int xmlToString(Ejs *ep, MprBuf *buf, EjsVar *obj, int indentLevel); -static void indent(MprBuf *bp, int level); -static char *cleanTagName(char *name); - -/******************************************************************************/ -/* - * Define the E4X classes (XML, XMLList) - */ - -int ejsDefineXmlClasses(Ejs *ep) -{ - EjsMethods *methods; - EjsVar *xmlClass, *xmlListClass; - - /* - * Create the XML class - */ - xmlClass = ejsDefineClass(ep, "XML", "Object", ejsXmlConstructor); - if (xmlClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - /* - * Define the XML class methods - */ - ejsDefineCMethod(ep, xmlClass, "text", text, EJS_NO_LOCAL); - ejsDefineCMethod(ep, xmlClass, "name", name, EJS_NO_LOCAL); - ejsDefineCMethod(ep, xmlClass, "load", load, EJS_NO_LOCAL); - ejsDefineCMethod(ep, xmlClass, "save", save, EJS_NO_LOCAL); - ejsDefineCMethod(ep, xmlClass, "toString", toString, EJS_NO_LOCAL); - ejsDefineCMethod(ep, xmlClass, "valueOf", valueOf, EJS_NO_LOCAL); - -/* MOB -- temporary only */ - ejsDefineCMethod(ep, xmlClass, "getList", getList, EJS_NO_LOCAL); - ejsDefineCMethod(ep, xmlClass, "setText", setText, EJS_NO_LOCAL); - - /* - * Setup the XML internal methods. - */ - methods = mprAllocTypeZeroed(ep, EjsMethods); - xmlClass->objectState->methods = methods; - - methods->createProperty = createXmlProperty; - methods->deleteProperty = deleteXmlProperty; - methods->getProperty = getXmlProperty; - methods->setProperty = setXmlProperty; - - /* - * Create the XMLList class - */ - xmlListClass = ejsDefineClass(ep, "XMLList", "Array", - ejsXmlListConstructor); - - /* - * Define the XMLList class methods - */ - - /* - * Setup the XML internal methods. - */ - methods = mprAllocTypeZeroed(ep, EjsMethods); - xmlListClass->objectState->methods = methods; - - methods->createProperty = createXmlListProperty; - methods->deleteProperty = deleteXmlListProperty; - methods->getProperty = getXmlListProperty; - methods->setProperty = setXmlListProperty; - - /* MOB -- need to complete xmlListClass */ - - return (ejsObjHasErrors(xmlClass) || ejsObjHasErrors(xmlListClass)) - ? MPR_ERR_CANT_INITIALIZE : 0; - return 0; -} - -/******************************************************************************/ -/* - * Routine to create an XML object using a default constructor - */ - -EjsVar *ejsCreateXml(Ejs *ep) -{ - EjsVar *op; - - op = ejsCreateSimpleObj(ep, "XML"); - if (op == 0) { - mprAssert(op); - return op; - } - ejsSetVarName(ep, op, "xmlNode"); - - /* - * Invoke class constructors manually (for speed and space) - */ - if (ejsXmlConstructor(ep, op, 0, 0) < 0) { - mprFree(op); - mprAssert(0); - return 0; - } - return op; -} - -/******************************************************************************/ -/* - * XML constructor - */ - -int ejsXmlConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - EjsVar *vp; - const char *str; - - ejsSetVarFlags(thisObj, EJS_XML_FLAGS_ELEMENT); - - if (argc == 1) { - vp = argv[0]; - - if (ejsVarIsObject(vp)) { - /* Convert DOM to XML. Not implemented */; - - } else if (ejsVarIsString(vp)) { - str = vp->string; - if (str == 0) { - return 0; - } - if (*str == '<') { - /* XML Literal */ - return loadXmlString(ep, thisObj, str); - - } else { - /* Load from file */ - return load(ep, thisObj, argc, argv); - } - } else { - ejsError(ep, EJS_TYPE_ERROR, "Bad type passed to XML constructor"); - return -1; - } - } - return 0; -} - -/******************************************************************************/ -/* - * Routine to create an XMLList object - */ - -EjsVar *ejsCreateXmlList(Ejs *ep) -{ - EjsVar *op; - - /* Sanity limit for size of hash table */ - - op = ejsCreateSimpleObj(ep, "XMLList"); - if (op == 0) { - mprAssert(0); - return op; - } - if (ejsArrayConstructor(ep, op, 0, 0) < 0 || - ejsXmlConstructor(ep, op, 0, 0) < 0) { - mprFree(op); - mprAssert(0); - return 0; - } - return op; -} - -/******************************************************************************/ -/* - * XMLList constructor - */ - -int ejsXmlListConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - // ejsSetVarFlags(vp, EJS_XML_FLAGS_ELEMENT); - return 0; -} - -/******************************************************************************/ -/******************************** Internal Methods ****************************/ -/******************************************************************************/ - -static EjsVar *createXmlProperty(Ejs *ep, EjsVar *obj, const char *property) -{ - return ejsGetVarPtr(ejsCreateSimpleProperty(ep, obj, property)); -} - -/******************************************************************************/ - -static int deleteXmlProperty(Ejs *ep, EjsVar *obj, const char *property) -{ - return ejsDeleteProperty(ep, obj, property); -} - -/******************************************************************************/ -/* MOB -- need ep as an arg */ -static EjsVar *getXmlProperty(Ejs *ep, EjsVar *obj, const char *property) -{ -#if NEW - EjsVar *lp; - - lp = ejsCreateXmlList(ep); - if (isdigit(*property)) { - /* MOB -- where do we store these. Do we need them ? */ - lp->targetObject = obj - lp->targetProperty = property - return getXmlListProperty(lp, property); - } - - /* What about a simple elment. Should it not return the text */ - - if (*property == '@') { - ap = ejsGetFirstProperty(obj, EJS_ENUM_ALL); - while (ap) { - vp = ejsGetVarPtr(ap); - /* MOB -- are attributes unique ? */ - if (vp->flags & EJS_XML_FLAGS_ATTRIBUTE && - strcmp(property, ap->name) == 0) { - ejsAppendXml(lp, vp); - } - ap = ejsGetNexttProperty(ap, EJS_ENUM_ALL); - } - } else { - while (ap) { - vp = ejsGetVarPtr(ap); - /* MOB -- are attributes unique ? */ - if (vp->flags & EJS_XML_FLAGS_ELEMENT && - strcmp(property, ap->name) == 0) { - ejsAppendXml(lp, vp); - } - ap = ejsGetNexttProperty(ap, EJS_ENUM_ALL); - } - } - return l; - - // Must always return XML or XMLList event for comments and attributes -#endif - return ejsGetVarPtr(ejsGetSimpleProperty(ep, obj, property)); -} - -/******************************************************************************/ - -static EjsVar *setXmlProperty(Ejs *ep, EjsVar *obj, const char *property, - const EjsVar *value) -{ - EjsProperty *pp; - EjsVar *vp; - - pp = ejsCreateSimpleProperty(ep, obj, property); - if (pp == 0) { - /* Should never happen */ - mprAssert(pp); - return 0; - } - vp = ejsGetVarPtr(pp); - if (ejsWriteVar(ep, vp, value, EJS_SHALLOW_COPY) < 0) { - return 0; - } - return ejsGetVarPtr(pp); -} - -/******************************************************************************/ -/* - NEW - -static EjsVar *setXmlProperty(Ejs *ep, EjsVar *op, const char *property, - EjsVar *value) -{ - - if ((value->objectState->baseClass != XML && - value->objectState->baseClass != XMLList) || - value->string[0] != '<') { - ejsVarToString(luevalue.toString(); - ejsRunMethod(ep, value, "toString", 0); - value = ejsDupVar(ep->result); - - } else { - value = ejsDupVar(value); - } - - if (isdigit(*property)) { - // ERROR -- reserved for future versions - return 0; - } - - if (*property == '@') { - if (op->objectState->baseClass == XMLList) { - if (op->obj.LENGTH_PROPERTY == 0) { - c = ""; - } else { - // Catenate all result of toString on all elts in list - } - } else { - c = c.toString(); - } - // Replace existing attribute of same name or insert - return; - } - for (i = op->obj.LENGTH - 1; i >= 0; i--) { - // Delete item of same name - } - if (not Found) { - Append new Xml object - - set [[name]], [[class]] == "element" - } - - mprFree(value); -} - - */ -/******************************************************************************/ -/************************************ Methods *********************************/ -/******************************************************************************/ - -static int load(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - const char *fileName; - XmlState *parser; - Exml *xp; - MprFile *file; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ep, EJS_ARG_ERROR, "Bad args. Usage: load(fileName);"); - return -1; - } - fileName = argv[0]->string; - - /* MOB -- not romable - Need rom code in MPR not MprServices - */ - file = mprOpen(ep, fileName, O_RDONLY, 0664); - if (file == 0) { - ejsError(ep, EJS_IO_ERROR, "Can't open: %s", fileName); - return -1; - } - - /* MOB -- should we empty thisObj of all existing properties ? */ - - xp = initParser(ep, thisObj, fileName); - parser = exmlGetParseArg(xp); - - exmlSetInputStream(xp, readFileData, (void*) file); - - if (exmlParse(xp) < 0) { - if (! ejsGotException(ep)) { - ejsError(ep, EJS_IO_ERROR, "Can't parse XML file: %s\nDetails %s", - fileName, exmlGetErrorMsg(xp)); - } - termParser(xp); - mprClose(file); - return -1; - } - - ejsSetReturnValue(ep, parser->nodeStack[0].obj); - - termParser(xp); - mprClose(file); - - return 0; -} - -/******************************************************************************/ - -static int loadXmlString(Ejs *ep, EjsVar *thisObj, const char *xmlString) -{ - XmlState *parser; - Exml *xp; - - xp = initParser(ep, thisObj, "string"); - parser = exmlGetParseArg(xp); - - parser->inputBuf = xmlString; - parser->inputSize = strlen(xmlString); - - exmlSetInputStream(xp, readStringData, (void*) 0); - - if (exmlParse(xp) < 0) { - if (! ejsGotException(ep)) { - ejsError(ep, EJS_IO_ERROR, "Can't parse XML string\nError %s", - exmlGetErrorMsg(xp)); - } - termParser(xp); - return -1; - } - - ejsSetReturnValue(ep, parser->nodeStack[0].obj); - - termParser(xp); - - return 0; -} - -/******************************************************************************/ - -static int text(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - EjsVar *vp; - - vp = ejsGetVarPtr(ejsGetSimpleProperty(ep, thisObj, E4X_TEXT_PROPERTY)); - if (vp == 0) { - ejsSetReturnValueToString(ep, ""); - return 0; - } - ejsSetReturnValue(ep, vp); - return 0; -} - -/******************************************************************************/ -/* - * Return the tag name - */ - -static int name(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - EjsVar *vp; - - vp = ejsGetVarPtr(ejsGetSimpleProperty(ep, thisObj, E4X_TAG_NAME_PROPERTY)); - if (vp == 0) { - ejsSetReturnValueToString(ep, ""); - return 0; - } - ejsSetReturnValue(ep, vp); -#if UNDEFINED - char *name; - /* MOB -- not ideal as we can't guarantee thisObj is a property */ - name = ejsGetPropertyPtr(thisObj)->name; - if (name == 0) { - name = ""; - } - ejsSetReturnValueToString(ep, name); -#endif - return 0; -} - -/******************************************************************************/ -/* MOB -- temporary only */ - -static int setText(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 1) { - ejsArgError(ep, "usage: setText(string)"); - } - - ejsSetProperty(ep, thisObj, E4X_TEXT_PROPERTY, argv[0]); - ejsSetReturnValue(ep, argv[0]); - return 0; -} - -/******************************************************************************/ - -static Exml *initParser(Ejs *ep, EjsVar *thisObj, const char *fileName) -{ - XmlState *parser; - Exml *xp; - - xp = exmlOpen(ep, 512, E4X_BUF_MAX); - mprAssert(xp); - - /* - * Create the parser stack - */ - parser = mprAllocTypeZeroed(ep, XmlState); - parser->ep = ep; - parser->nodeStack[0].obj = thisObj; - parser->xmlClass = ejsGetClass(ep, 0, "XML"); - parser->xmlListClass = ejsGetClass(ep, 0, "XMLList"); - parser->fileName = fileName; - - exmlSetParseArg(xp, parser); - exmlSetParserHandler(xp, parserHandler); - - return xp; -} - -/******************************************************************************/ - -static void termParser(Exml *xp) -{ - mprFree(exmlGetParseArg(xp)); - exmlClose(xp); -} - -/******************************************************************************/ -/* - * XML parsing callback. Called for each elt and attribute/value pair. - * For speed, we handcraft the object model here rather than calling - * putXmlProperty. - * - * "" parseHandler(efd, , EXML_COMMENT); - * "" parseHandler(efd, , EXML_ELT_DEFINED); - * "" parseHandler(efd, , EXML_SOLO_ELT_DEFINED); - * " ...<" parseHandler(efd, , EXML_ELT_DATA); - * "..." parseHandler(efd, , EXML_END_ELT); - * - * Note: we recurse on every new nested elt. - */ - -static int parserHandler(Exml *xp, int state, const char *tagName, - const char *attName, const char *value) -{ - XmlState *parser; - XmlTagState *tos; - EjsVar *currentNode, *vp, *tagNode, *parent, *vpx; - EjsProperty *pp; - Ejs *ep; - char *name; - - parser = (XmlState*) xp->parseArg; - ep = parser->ep; - tos = &parser->nodeStack[parser->topOfStack]; - currentNode = tos->obj; - - mprAssert(state >= 0); - mprAssert(tagName && *tagName); - - switch (state) { - case EXML_PI: - /* - * By using a property name with a leading space, we can store - * non-user-visible processing instructions as regular properties. - */ - pp = ejsCreateSimpleNonUniqueProperty(ep, currentNode, E4X_PI_PROPERTY); - ejsMakePropertyEnumerable(pp, 1); - vp = ejsGetVarPtr(pp); - ejsWriteVarAsString(ep, vp, value); - ejsSetVarFlags(vp, EJS_XML_FLAGS_PI); - break; - - case EXML_COMMENT: - /* - * By using a property name with a leading space, we can store - * non- user-visible comments as regular properties. - */ - pp = ejsCreateSimpleNonUniqueProperty(ep, currentNode, - E4X_COMMENT_PROPERTY); - ejsMakePropertyEnumerable(pp, 1); - vp = ejsGetVarPtr(pp); - ejsWriteVarAsString(ep, vp, value); - ejsSetVarFlags(vp, EJS_XML_FLAGS_COMMENT); - break; - - case EXML_NEW_ELT: - if (parser->topOfStack > E4X_MAX_NODE_DEPTH) { - ejsError(ep, EJS_IO_ERROR, - "XML nodes nested too deeply in %s at line %d", - parser->fileName, exmlGetLineNumber(xp)); - return MPR_ERR_BAD_SYNTAX; - } - - name = mprStrdup(xp, tagName); - if (name == 0) { - return MPR_ERR_MEMORY; - } - - if (cleanTagName(name) < 0) { - ejsError(ep, EJS_TYPE_ERROR, "Bad XML tag name in %s at %d", - parser->fileName, exmlGetLineNumber(xp)); - mprFree(name); - return MPR_ERR_BAD_SYNTAX; - } - - pp = ejsCreateSimpleNonUniqueProperty(ep, currentNode, name); - ejsMakePropertyEnumerable(pp, 1); - - tagNode = ejsGetVarPtr(pp); - - /* MOB -- OPT */ - vpx = ejsCreateXml(ep); - vp = ejsWriteVar(ep, tagNode, vpx, EJS_SHALLOW_COPY); - ejsMakeObjLive(vp, 1); - ejsFreeVar(ep, vpx); - - /* MOB -- return code */ - pp = ejsSetPropertyToString(ep, vp, E4X_TAG_NAME_PROPERTY, name); - ejsMakePropertyEnumerable(pp, 0); - - ejsSetVarFlags(vp, EJS_XML_FLAGS_ELEMENT); - ejsMakePropertyEnumerable(ejsGetPropertyPtr(vp), 1); - - tos = &parser->nodeStack[++(parser->topOfStack)]; - currentNode = tos->obj = vp; - tos->attributes = 0; - tos->comments = 0; - mprFree(name); - break; - - case EXML_NEW_ATT: - if (mprAllocSprintf(MPR_LOC_ARGS(xp), &name, 0, "@%s", attName) < 0) { - return MPR_ERR_MEMORY; - } - pp = ejsCreateProperty(ep, currentNode, name); - ejsMakePropertyEnumerable(pp, 1); - - vp = ejsGetVarPtr(pp); - ejsWriteVarAsString(ep, vp, value); - ejsSetVarFlags(vp, EJS_XML_FLAGS_ATTRIBUTE); - mprFree(name); - break; - - case EXML_SOLO_ELT_DEFINED: - parser->topOfStack--; - mprAssert(parser->topOfStack >= 0); - tos = &parser->nodeStack[parser->topOfStack]; - break; - - case EXML_ELT_DEFINED: - if (parser->topOfStack > 0) { - parent = parser->nodeStack[parser->topOfStack - 1].obj; - ejsSetProperty(ep, currentNode, E4X_PARENT_PROPERTY, parent); - } - break; - - case EXML_ELT_DATA: - case EXML_CDATA: - pp = ejsCreateSimpleNonUniqueProperty(ep, currentNode, - E4X_TEXT_PROPERTY); - ejsMakePropertyEnumerable(pp, 1); - vp = ejsGetVarPtr(pp); - ejsWriteVarAsString(ep, vp, value); - ejsSetVarFlags(vp, EJS_XML_FLAGS_TEXT); - break; - - case EXML_END_ELT: - /* - * This is the closing element in a pair "...". - * Pop the stack frame off the elt stack - */ - parser->topOfStack--; - mprAssert(parser->topOfStack >= 0); - tos = &parser->nodeStack[parser->topOfStack]; - break; - - default: - ejsError(ep, EJS_IO_ERROR, "XML error in %s at %d\nDetails %s", - parser->fileName, exmlGetLineNumber(xp), exmlGetErrorMsg(xp)); - mprAssert(0); - return MPR_ERR_BAD_SYNTAX; - } - return 0; -} - -/******************************************************************************/ - -static char *cleanTagName(char *name) -{ - char *cp; - - for (cp = name; *cp; cp++) { - if (*cp == ':') { - *cp = '_'; - } else if (!isalnum(*cp) && *cp != '_' && *cp != '$' && *cp != '@') { - return 0; - } - } - return name; -} - -/******************************************************************************/ - -static int readFileData(Exml *xp, void *data, char *buf, int size) -{ - mprAssert(xp); - mprAssert(data); - mprAssert(buf); - mprAssert(size > 0); - - return mprRead((MprFile*) data, buf, size); -} - -/******************************************************************************/ - -static int readStringData(Exml *xp, void *data, char *buf, int size) -{ - XmlState *parser; - int rc, len; - - mprAssert(xp); - mprAssert(buf); - mprAssert(size > 0); - - parser = (XmlState*) xp->parseArg; - - if (parser->inputPos < parser->inputSize) { - len = min(size, (parser->inputSize - parser->inputPos)); - rc = mprMemcpy(buf, size, &parser->inputBuf[parser->inputPos], len); - parser->inputPos += len; - return rc; - } - return 0; -} - -/******************************************************************************/ - -static int save(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - const char *fileName; - MprBuf *buf; - MprFile *file; - int bytes, len; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ep, EJS_ARG_ERROR, "Bad args. Usage: save(fileName);"); - return -1; - } - fileName = argv[0]->string; - - /* MOB -- not romable - Need rom code in MPR not MprServices - */ - - /* - * Convert to a string - */ - buf = mprCreateBuf(ep, E4X_BUF_SIZE, E4X_BUF_MAX); - if (xmlToString(ep, buf, thisObj, -1) < 0) { - mprFree(buf); - return -1; - } - - file = mprOpen(ep, fileName, - O_CREAT | O_TRUNC | O_WRONLY | O_TEXT, 0664); - if (file == 0) { - ejsError(ep, EJS_IO_ERROR, "Can't open: %s, %d", fileName, - mprGetOsError()); - return -1; - } - - len = mprGetBufLength(buf); - bytes = mprWrite(file, buf->start, len); - if (bytes != len) { - ejsError(ep, EJS_IO_ERROR, "Can't write to: %s", fileName); - mprClose(file); - return -1; - } - mprWrite(file, "\n", 1); - mprFree(buf); - - mprClose(file); - - return 0; -} - -/******************************************************************************/ - -static int toString(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - MprBuf *buf; - - buf = mprCreateBuf(ep, E4X_BUF_SIZE, E4X_BUF_MAX); - - if (xmlToString(ep, buf, thisObj, -1) < 0) { - mprFree(buf); - return -1; - } - ejsWriteVarAsString(ep, ep->result, (char*) buf->start); - - mprFree(buf); - - return 0; -} - -/******************************************************************************/ -/* MOB -- need to support XMLList */ - -static int xmlToString(Ejs *ep, MprBuf *buf, EjsVar *obj, int indentLevel) -{ - EjsProperty *pp; - EjsVar *vp; - char *varBuf; - int endTag, sawElements; - - if (indentLevel < 0) { - mprPutStringToBuf(buf, ""); - } - - switch (obj->type) { - case EJS_TYPE_STRING: - if (obj->flags & EJS_XML_FLAGS_ATTRIBUTE) { - mprPutFmtStringToBuf(buf, " %s=\"%s\"", - &ejsGetPropertyPtr(obj)->name[1], obj->string); - /* No new line */ - - } else if (obj->flags & EJS_XML_FLAGS_COMMENT) { - mprPutCharToBuf(buf, '\n'); - indent(buf, indentLevel); - mprPutFmtStringToBuf(buf, "", obj->string); - - } else if (obj->flags & EJS_XML_FLAGS_TEXT) { - mprPutStringToBuf(buf, obj->string); - - } else { -// indent(buf, indentLevel); - mprPutStringToBuf(buf, obj->string); -// mprPutCharToBuf(buf, '\n'); - } - break; - - default: - /* Primitive types come here */ - indent(buf, indentLevel); - /* MOB -- rc */ - varBuf = ejsVarToString(ep, obj); - mprPutStringToBuf(buf, varBuf); - break; - - case EJS_TYPE_OBJECT: - if (obj->objectState->baseClass == ejsGetClass(ep, 0, "XML")) { - if (!obj->objectState->visited) { - obj->objectState->visited = 1; - - /* MOB -- opt. Flags would be quicker */ - if (strcmp(ejsGetPropertyPtr(obj)->name, - E4X_PARENT_PROPERTY) == 0) { - return 0; - } - /* - * MOB -- short term fix for tags with no body but with - * attributes - */ - if (getNumElements(obj) == 0 && 0) { - /* - * XML element is simple with no elements, so return just - * the text. - */ - if (getText(buf, obj) < 0) { - ejsError(ep, EJS_IO_ERROR, - "XML is to big to convert to a string"); - obj->objectState->visited = 0; - return -1; - } - - } else if (obj->flags & (EJS_XML_FLAGS_ELEMENT)) { - /* - * XML object is complex (has elements) so return full XML - * content. - */ - mprPutCharToBuf(buf, '\n'); - indent(buf, indentLevel); - - /* - * When called from toString, obj is not a property - */ - if (indentLevel >= 0) { - mprPutFmtStringToBuf(buf, "<%s", - ejsGetPropertyPtr(obj)->name); - endTag = 0; - - } else { - endTag = 1; - } - - sawElements = 0; - pp = ejsGetFirstProperty(obj, 0); - while (pp) { - vp = ejsGetVarPtr(pp); - - if (! (vp->flags & EJS_XML_FLAGS_ATTRIBUTE)) { - if (endTag == 0) { - endTag++; - mprPutStringToBuf(buf, ">"); - } - } - if (vp->flags & EJS_XML_FLAGS_ELEMENT) { - if (strcmp(ejsGetPropertyPtr(vp)->name, - E4X_PARENT_PROPERTY) != 0) { - sawElements++; - } - } - - if (xmlToString(ep, buf, ejsGetVarPtr(pp), - indentLevel + 1) < 0){ - return -1; - } - - pp = ejsGetNextProperty(pp, 0); - } - if (indentLevel >= 0) { - if (sawElements) { - mprPutCharToBuf(buf, '\n'); - indent(buf, indentLevel); - } - mprPutFmtStringToBuf(buf, "", - ejsGetPropertyPtr(obj)->name); - } - } - obj->objectState->visited = 0; - } - return 0; - } - - if (obj->objectState->baseClass == ejsGetClass(ep, 0, "XMLList")) { - indent(buf, indentLevel); - /* MOB -- TBD */ - return 0; - } - - /* - * All other objects. Allow other objects to override toString - */ - if (ejsRunMethod(ep, obj->objectState->baseClass, "toString", - 0) < 0) { - return -1; - } - if (ejsVarIsString(ep->result)) { - indent(buf, indentLevel); - mprPutStringToBuf(buf, obj->string); - } - break; - } - return 0; -} - -/******************************************************************************/ - -static void indent(MprBuf *bp, int level) -{ - int i; - - for (i = 0; i < level; i++) { - mprPutCharToBuf(bp, '\t'); - } -} - -/******************************************************************************/ - -static int valueOf(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 0) { - mprAssert(0); - return -1; - } - - switch (thisObj->type) { - default: - case EJS_TYPE_UNDEFINED: - case EJS_TYPE_NULL: - case EJS_TYPE_CMETHOD: - case EJS_TYPE_OBJECT: - case EJS_TYPE_METHOD: - case EJS_TYPE_STRING_CMETHOD: - ejsWriteVar(ep, ep->result, thisObj, EJS_SHALLOW_COPY); - break; - - case EJS_TYPE_STRING: - ejsWriteVarAsInteger(ep, ep->result, atoi(thisObj->string)); - break; - - case EJS_TYPE_BOOL: - case EJS_TYPE_INT: -#if BLD_FEATURE_INT64 - case EJS_TYPE_INT64: -#endif -#if BLD_FEATURE_FLOATING_POINT - case EJS_TYPE_FLOAT: -#endif - ejsWriteVar(ep, ep->result, thisObj, EJS_SHALLOW_COPY); - break; - } - return 0; -} - -/******************************************************************************/ - -static int getList(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - const char *nodeName; - EjsProperty *pp; - EjsVar *list, *vp; - - if (argc != 1) { - nodeName = 0; - } else { - nodeName = argv[0]->string; - } - - list = ejsCreateArray(ep, 0); - - pp = ejsGetFirstProperty(thisObj, EJS_ENUM_ALL); - while (pp) { - vp = ejsGetVarPtr(pp); - if (vp->type == EJS_TYPE_OBJECT) { - if (strcmp(ejsGetPropertyPtr(vp)->name, E4X_PARENT_PROPERTY) != 0) { - if (vp->flags & EJS_XML_FLAGS_ELEMENT && - (nodeName == 0 || strcmp(nodeName, pp->name) == 0)) { - ejsAddArrayElt(ep, list, vp, EJS_SHALLOW_COPY); - } - } - } - pp = ejsGetNextProperty(pp, EJS_ENUM_ALL); - } - - ejsSetReturnValueAndFree(ep, list); - return 0; -} - -/******************************************************************************/ - -static int getNumElements(EjsVar *obj) -{ - EjsProperty *pp; - int count; - - count = 0; - pp = ejsGetFirstProperty(obj, EJS_ENUM_ALL); - while (pp) { - if (ejsGetVarPtr(pp)->flags & EJS_XML_FLAGS_ELEMENT) { - count++; - } - pp = ejsGetNextProperty(pp, EJS_ENUM_ALL); - } - return count; -} - -/******************************************************************************/ -/* MOB - This needs to be a public method */ - -static int getText(MprBuf *buf, EjsVar *obj) -{ - EjsProperty *pp; - EjsVar *vp; - - pp = ejsGetFirstProperty(obj, EJS_ENUM_ALL); - while (pp) { - vp = ejsGetVarPtr(pp); - if (vp->flags & EJS_XML_FLAGS_TEXT) { - /* MOB -- should test for overflow */ - mprPutStringToBuf(buf, vp->string); - } - pp = ejsGetNextProperty(pp, EJS_ENUM_ALL); - } - return 0; -} - -/******************************************************************************/ -/******************************************************************************/ -/******************************** Internal Methods ****************************/ -/******************************************************************************/ - -static EjsVar *createXmlListProperty(Ejs *ep, EjsVar *obj, const char *property) -{ - return ejsGetVarPtr(ejsCreateProperty(ep, obj, property)); -} - -/******************************************************************************/ - -static int deleteXmlListProperty(Ejs *ep, EjsVar *obj, const char *property) -{ - return ejsDeleteProperty(ep, obj, property); -} - -/******************************************************************************/ - -static EjsVar *getXmlListProperty(Ejs *ep, EjsVar *obj, const char *property) -{ - // Must always return XML or XMLList event for comments and attributes - return ejsGetVarPtr(ejsGetSimpleProperty(ep, obj, property)); -} - -/******************************************************************************/ - -static EjsVar *setXmlListProperty(Ejs *ep, EjsVar *obj, const char *property, - const EjsVar *value) -{ - EjsProperty *pp; - EjsVar *vp; - - pp = ejsGetSimpleProperty(ep, obj, property); - if (pp == 0) { - mprAssert(pp); - return 0; - } - vp = ejsGetVarPtr(pp); - if (ejsWriteVar(ep, vp, value, EJS_SHALLOW_COPY) < 0){ - mprAssert(0); - return 0; - } - return ejsGetVarPtr(pp); -} - -/******************************************************************************/ -/* - NEW - -static EjsVar *putXmlListProperty(EjsVar *op, const char *property, - EjsVar *value) -{ - - if ((value->objectState->baseClass != XML && - value->objectState->baseClass != XMLList) || - value->string[0] != '<') { - c = value.toString(); - } else { - value = ejsDupVar(value); - ?? - } - if (isdigit(*property)) { - // ERROR - return 0; - } - if (*property == '@') { - if (op->objectState->baseClass == XMLList) { - if (op->obj.LENGTH_PROPERTY == 0) { - c = ""; - } else { - // Catenate all result of toString on all elts in list - } - } else { - c = c.toString(); - } - // Replace existing attribute of same name or insert - return; - } - for (i = op->obj.LENGTH - 1; i >= 0; i--) { - // Delete item of same name - } - if (not Found) { - Append new Xml object - - set [[name]], [[class]] == "element" - } -} - - */ - -/******************************************************************************/ -#else -void ejs4xDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS_E4X */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/ejs.c b/source4/lib/appweb/ejs-2.0/ejs/ejs.c deleted file mode 100644 index 0fcc6f0545..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/ejs.c +++ /dev/null @@ -1,1378 +0,0 @@ -/* - * @file ejs.c - * @brief Embedded JavaScript (EJS) - * @overview Main module interface logic. - * @remarks The initialization code must be run single-threaded. Includes: - * ejsOpen, ejsClose. - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if BLD_FEATURE_EJS - -/************************************* Code ***********************************/ -/* - * Initialize the EJS subsystem - */ - -EjsService *ejsOpenService(MprCtx ctx) -{ - EjsService *service; - Ejs *interp; - - service = mprAllocTypeZeroed(ctx, EjsService); - if (service == 0) { - mprError(ctx, MPR_LOC, "Can't allocate service memory"); - return 0; - } - - interp = ejsCreateInterp(service, 0, 0, 0, 1); - if (interp == 0) { - mprError(ctx, MPR_LOC, "Can't create master interpreter"); - mprFree(service); - return 0; - } - service->master = interp; - - /* - * Restore the default GC settings for the master interpreter. - * ejsCreateInterp will have initialized them. - */ - ejsGCInit(interp, EJS_DEFAULT_OBJ_INC, EJS_DEFAULT_PROP_INC, - EJS_DEFAULT_VAR_INC, EJS_DEFAULT_STR_INC); - - /* - * Save the default interpreter and global class for all to access - * MOB -- don't store these. Store the service - */ - mprSetKeyValue(interp, "ejsMaster", interp); - mprSetKeyValue(interp, "ejsGlobalClass", interp->global); - - /* - * Once the Object class is created, this routine will also make the - * Global class a subclass of Object. - */ - if (ejsDefineObjectClass(interp) < 0) { - mprError(ctx, MPR_LOC, "Can't define EJS object class"); - mprFree(service); - return 0; - } - - /* - * Create all the standard classes - */ - if (ejsDefineStandardClasses(interp) < 0) { - mprError(ctx, MPR_LOC, "Can't define EJS standard classes"); - mprFree(service); - return 0; - } - - if (ejsDefineSystemClasses(interp) < 0) { - mprError(ctx, MPR_LOC, "Can't define EJS system classes"); - mprFree(service); - return 0; - } - - if (ejsCreateObjectModel(interp) < 0) { - mprError(ctx, MPR_LOC, "Can't create EJS object model"); - mprFree(service); - return 0; - } - -#if UNUSED && BLD_FEATURE_ALLOC_STATS -{ - EjsVar v; - mprLog(ctx, 0, "Obj %d, Var %d, Prop %d\n", sizeof(EjsObj), sizeof(EjsVar), - sizeof(EjsProperty)); - mprLog(ctx, 0, "GCLink %d\n", sizeof(EjsGCLink)); - mprLog(ctx, 0, "objectState %d\n", (uint) &v.objectState - (uint) &v); -} -#endif - - return service; -} - -/******************************************************************************/ -/* - * Close down the EJS Service - */ - -void ejsCloseService(EjsService *sp, bool doStats) -{ - Ejs *ep; - - mprAssert(sp); - - ep = sp->master; - mprAssert(ep); - - ejsTermSystemClasses(ep); - - if (ep) { - ejsFreeVar(ep, sp->globalClass); - -#if BLD_FEATURE_ALLOC_STATS - if (doStats) { - mprLog(sp, 0, "GC Statistics for the Global Interpreter"); - } -#endif - ejsDestroyInterp(ep, doStats); - } - - mprRemoveKeyValue(sp, "ejsMaster"); - mprRemoveKeyValue(sp, "ejsGlobalClass"); - - mprFree(sp); -} - -/******************************************************************************/ - -Ejs *ejsGetMasterInterp(EjsService *sp) -{ - return sp->master; -} - -/******************************************************************************/ -#if BLD_FEATURE_MULTITHREAD - -int ejsSetServiceLocks(EjsService *sp, EjsLockFn lock, EjsUnlockFn unlock, - void *data) -{ - mprAssert(sp); - - sp->lock = lock; - sp->unlock = unlock; - sp->lockData = data; - return 0; -} - -#endif -/******************************************************************************/ -/* - * Create and initialize an EJS interpreter. Interpreters have a global object - * that has the service global class set as a base class. This way, it - * inherits all the desired global properties, methods and classes. - * - * The primary and alternate handles are provided to C methods depending on - * the flags provided when the C methods are defined. The global variable - * (optionally) defines a predefined global variable space. - */ - -Ejs *ejsCreateInterp(EjsService *sp, void *primaryHandle, void *altHandle, - EjsVar *global, bool useOwnSlab) -{ - EjsProperty *pp; - EjsVar *baseClass; - Ejs *ep; - - ep = mprAllocTypeZeroed(sp, Ejs); - if (ep == 0) { - mprAssert(0); - return ep; - } - - ep->stkPtr = &ep->stack[EJS_MAX_STACK]; - - ep->service = sp; - ep->primaryHandle = primaryHandle; - ep->altHandle = altHandle; - - if (sp->master) { - ep->objectClass = sp->master->objectClass; - } - - if (useOwnSlab) { - ep->slabs = (EjsSlab*) mprAllocZeroed(ep, sizeof(EjsSlab) * - EJS_SLAB_MAX); - ep->slabAllocContext = ep; - - } else { - ep->slabs = sp->master->slabs; - ep->slabAllocContext = sp->master; - ep->flags |= EJS_FLAGS_SHARED_SLAB; - } - - ep->frames = mprCreateItemArray(ep, EJS_INC_FRAMES, EJS_MAX_FRAMES); - if (ep->frames == 0) { - mprFree(ep); - return 0; - } - - ejsGCInit(ep, EJS_OBJ_INC, EJS_PROP_INC, EJS_VAR_INC, EJS_STR_INC); - - if (sp->globalClass == 0) { - /* - * Only do this for the Global interpreter. Create a global class - * (prototype) object. This is base class from which all global - * spaces will inherit. - */ - sp->globalClass = ejsCreateObjVar(ep); - if (sp->globalClass == 0) { - mprFree(ep); - return 0; - } - ejsSetClassName(ep, sp->globalClass, "Global"); - global = sp->globalClass; - } - - if (global) { - /* - * The default interpreter uses the Global class as its global - * space. - */ - ep->global = ejsDupVar(ep, global, EJS_SHALLOW_COPY); - if (ep->global == 0) { - mprFree(ep); - return 0; - } - if (ep->global->objectState != sp->globalClass->objectState) { - ejsSetBaseClass(ep->global, sp->globalClass); - } - - } else { - /* - * Use the global class as our global so we can find the object class - */ - baseClass = ejsGetClass(ep, sp->globalClass, "Object"); - if (baseClass) { - ep->global = ejsCreateSimpleObjUsingClass(ep, baseClass); - if (ep->global == 0) { - mprFree(ep); - return 0; - } - - /* - * Override the base class and set to the master Global class - */ - ejsSetBaseClass(ep->global, sp->globalClass); - - } else { - ep->global = ejsCreateObjVar(ep); - } - } - - /* - * The "global" variable points to the global space - */ - pp = ejsSetProperty(ep, ep->global, "global", ep->global); - if (pp == 0) { - mprFree(ep); - return 0; - } - ejsMakePropertyEnumerable(pp, 0); - - /* - * The "Global" variable points to the Global class - */ - pp = ejsSetProperty(ep, ep->global, "Global", sp->globalClass); - if (pp == 0) { - mprFree(ep); - return 0; - } - ejsMakePropertyEnumerable(pp, 0); - - ep->local = ejsDupVar(ep, ep->global, EJS_SHALLOW_COPY); - if (ep->frames == 0 || ep->global == 0 || ep->local == 0) { - mprFree(ep); - return 0; - } - ejsSetVarName(ep, ep->local, "topLevelLocal"); - - if (mprAddItem(ep->frames, ep->global) < 0 || - mprAddItem(ep->frames, ep->local) < 0) { - mprFree(ep); - return 0; - } - - ep->result = ejsCreateUndefinedVar(ep); - if (ep->result == 0) { - mprFree(ep); - return 0; - } - - return ep; -} - -/******************************************************************************/ -/* - * Close an EJS interpreter - */ - -void ejsDestroyInterp(Ejs *ep, bool doStats) -{ - ejsCleanInterp(ep, doStats); - - mprFree(ep); -} - -/******************************************************************************/ -/* - * Clean an EJS interpreter of all allocated variables, but DONT destroy. - * We use this rather than DestroyInterp so we delay freeing the Ejs struct - * until after the service is closed. - */ - -void ejsCleanInterp(Ejs *ep, bool doStats) -{ - int i; - - if (ep->global) { - ejsDeleteProperty(ep, ep->local, "global"); - ejsDeleteProperty(ep, ep->global, "global"); - ep->global = 0; - } - if (ep->local) { - ejsFreeVar(ep, ep->local); - ep->local = 0; - } - if (ep->global) { - ejsFreeVar(ep, ep->global); - ep->global = 0; - } - if (ep->result) { - ejsFreeVar(ep, ep->result); - ep->result = 0; - } - if (ep->castAlloc && ep->castTemp) { - mprFree(ep->castTemp); - ep->castTemp = 0; - } - if (ep->frames) { - for (i = ep->frames->length - 1; i >= 0; i--) { - mprRemoveItemByIndex(ep->frames, i); - } - mprFree(ep->frames); - ep->frames = 0; - } - - if (doStats) { - -#if BLD_FEATURE_ALLOC_STATS - mprLog(ep, 0, " "); - mprLog(ep, 0, "GC Statistics for Interpreter (0x%X)", (uint) ep); -#endif - - /* - * Cleanup before printing the alloc report - */ - ejsSetGCDebugLevel(ep, 3); - ejsCollectGarbage(ep, -1); - -#if BLD_DEBUG - /* - * If we are the master, dump objects - */ - if (ep->service->master == ep) { - ejsDumpObjects(ep); - } -#endif - -#if BLD_FEATURE_ALLOC_STATS - /* - * Print an alloc report. 1 == do leak report - */ - ejsPrintAllocReport(ep, 1); -#endif - - } else { - /* - * Must collect garbage here incase sharing interpreters with the - * master. If we don't, the mprFree later in DestroyInterp will free - * all memory and when the master does GC --> crash. - */ - ejsCollectGarbage(ep, -1); - } -} - -/******************************************************************************/ -/* - * Evaluate an EJS script file. This will evaluate the script at the current - * context. Ie. if inside a function, declarations will be local. - */ - -int ejsEvalFile(Ejs *ep, const char *path, EjsVar *result) -{ - MprFile *file; - MprFileInfo info; - char *script; - char *saveFileName; - int rc; - - mprAssert(path && *path); - - if ((file = mprOpen(ep, path, O_RDONLY | O_BINARY, 0666)) == 0) { - ejsError(ep, EJS_IO_ERROR, "Can't open %s", path); - return -1; - } - - if (mprGetFileInfo(ep, path, &info) < 0) { - ejsError(ep, EJS_IO_ERROR, "Can't get file info for %s", path); - goto error; - } - - if ((script = (char*) mprAlloc(ep, info.size + 1)) == NULL) { - ejsError(ep, "MemoryError", "Cant malloc %d", (int) info.size); - goto error; - } - - if (mprRead(file, script, info.size) != (int) info.size) { - mprFree(script); - ejsError(ep, EJS_IO_ERROR, "Error reading %s", path); - goto error; - } - mprClose(file); - script[info.size] = '\0'; - - saveFileName = ep->fileName; - ep->fileName = mprStrdup(ep, path); - - rc = ejsEvalScript(ep, script, result); - mprFree(script); - - mprFree(ep->fileName); - ep->fileName = saveFileName; - - return rc; - -/* - * Error return - */ -error: - mprClose(file); - return -1; -} - -/******************************************************************************/ -/* - * Create a new variable scope block. This pushes the old local frame down - * the stack and creates a new local variables frame. - */ - -int ejsOpenBlock(Ejs *ep) -{ - EjsProperty *pp; - int fid; - - ep->local = ejsCreateSimpleObj(ep, "Object"); - ejsSetVarName(ep, ep->local, "local"); - - if (ep->local == 0) { - ejsMemoryError(ep); - return -1; - } - - if (ep->frames->length > EJS_MAX_FRAMES && !ep->gotException) { - ejsError(ep, EJS_RANGE_ERROR, "Recursion too deep: Max depth %d", - EJS_MAX_FRAMES); - return -1; - } - - /* - * Must add to frames before ejsSetProperty which will make the object live - */ - fid = mprAddItem(ep->frames, ep->local); - if (fid < 0) { - ejsMemoryError(ep); - return -1; - } - - /* Self reference */ - pp = ejsSetProperty(ep, ep->local, "local", ep->local); - ejsMakePropertyEnumerable(pp, 0); - - return fid; -} - -/******************************************************************************/ -/* - * Set a new variable scope block. This pushes the old local frame down - * the stack and creates a new local variables frame. - */ - -int ejsSetBlock(Ejs *ep, EjsVar *local) -{ - ep->local = ejsDupVar(ep, local, EJS_SHALLOW_COPY); - ejsMakeObjPermanent(ep->local, 1); - return mprAddItem(ep->frames, ep->local); -} - -/******************************************************************************/ -/* - * Close a variable scope block opened via ejsOpenBlock. Pop back the old - * local variables frame. - */ - -int ejsCloseBlock(Ejs *ep, int fid) -{ - mprAssert(ep->local >= 0); - mprAssert(fid >= 0); - - mprAssert(ep->local == (EjsVar*) mprGetItem(ep->frames, fid)); - - if (ep->local) { - /* Allow GC */ - ejsMakeObjPermanent(ep->local, 0); - ejsFreeVar(ep, ep->local); - } - - mprRemoveItemByIndex(ep->frames, fid); - - ep->local = (EjsVar*) mprGetItem(ep->frames, - mprGetItemCount(ep->frames) - 1); - - return 0; -} - -/******************************************************************************/ -/* - * Create a new variable scope block and evaluate a script. All frames - * created during this context will be automatically deleted when complete. - * vp is optional. i.e. created local variables will be discarded - * when this routine returns. - */ - -int ejsEvalBlock(Ejs *ep, char *script, EjsVar *vp) -{ - int rc, fid; - - mprAssert(script); - - fid = ejsOpenBlock(ep); - if (fid < 0) { - return fid; - } - - rc = ejsEvalScript(ep, script, vp); - - ejsCloseBlock(ep, fid); - - return rc; -} - -/******************************************************************************/ -/* - * Parse and evaluate a EJS. The script is evaluated at the current context. - * Return the result in *vp. The result is "owned" by EJ and the caller - * must not free it. Returns -1 on errors and zero for success. - */ - -int ejsEvalScript(Ejs *ep, const char *script, EjsVar *vp) -{ - int state; - - ejsClearVar(ep, ep->result); - ep->gotException = 0; - - if (script == 0) { - return 0; - } - - /* - * Allocate a new evaluation block, and save the old one - */ - if (ejsLexOpenScript(ep, script) < 0) { - return MPR_ERR_MEMORY; - } - - /* - * Do the actual parsing and evaluation - */ - ep->scriptStatus = 0; - - do { - state = ejsParse(ep, EJS_STATE_BEGIN, EJS_FLAGS_EXE); - - if (state == EJS_STATE_RET) { - state = EJS_STATE_EOF; - } - } while (state != EJS_STATE_EOF && state != EJS_STATE_ERR); - - ejsLexCloseScript(ep); - - if (state == EJS_STATE_ERR) { - return -1; - } - - if (vp) { - /* Caller must not free. */ - *vp = *ep->result; - } - - return ep->scriptStatus; -} - -/******************************************************************************/ - -void ejsSetFileName(Ejs *ep, const char *fileName) -{ - mprFree(ep->fileName); - ep->fileName = mprStrdup(ep, fileName); -} - -/******************************************************************************/ -/* - * Format the stack backtrace - */ - -char *ejsFormatStack(Ejs* ep) -{ - EjsInput *ip; - char *errbuf; - int frame, len; - - mprAssert(ep); - - ip = ep->input; - - errbuf = 0; - - len = 0; - frame = 0; - while (ip && frame < EJS_MAX_BACKTRACE) { - char *traceLine, *newErrbuf, *line; - for (line = ip->line; *line && isspace(*line); line++) { - ; - } - mprAllocSprintf(MPR_LOC_ARGS(ep), &traceLine, MPR_MAX_STRING, - " [%02d] %s, %s, line %d -> %s\n", - frame++, - ip->fileName ? ip->fileName : "script", - ip->procName ? ip->procName: "global", - ip->lineNumber, line); - if (traceLine == 0) { - break; - } - newErrbuf = mprRealloc(ep, errbuf, len + strlen(traceLine) + 1); - if (newErrbuf == NULL) { - break; - } - errbuf = newErrbuf; - memcpy(&errbuf[len], traceLine, strlen(traceLine) + 1); - len += strlen(traceLine); - mprFree(traceLine); - ip = ip->next; - } - return errbuf; -} - -/******************************************************************************/ -/* - * Internal use method to set the error message - * - * Error, ArgError, AssertError, IOError, MemoryError, RangeError, - * ReferenceError, SyntaxError, TypeError, MemoryError - */ - -void ejsError(Ejs* ep, const char *errorType, const char* fmt, ...) -{ - va_list fmtArgs; - EjsVar *error; - char *msg, *stack; - - va_start(fmtArgs, fmt); - mprAllocVsprintf(MPR_LOC_ARGS(ep), &msg, MPR_MAX_STRING, fmt, fmtArgs); - va_end(fmtArgs); - - /* - * Create a new Error exception object. If bad error type, default to - * "Error" - */ - if (ejsGetClass(ep, 0, errorType) == 0) { - errorType = "Error"; - } - ep->gotException = 1; - - error = ejsCreateObj(ep, 0, errorType, msg); - if (error == 0) { - return; - } - mprFree(msg); - - stack = ejsFormatStack(ep); - ejsSetPropertyToString(ep, error, "stack", stack); - mprFree(stack); - - ejsWriteVar(ep, ep->result, error, EJS_SHALLOW_COPY); - ejsFreeVar(ep, error); -} - -/******************************************************************************/ - -void ejsSyntaxError(Ejs *ep, const char *msg) -{ - if (msg == 0) { - msg = " "; - } - ejsError(ep, EJS_SYNTAX_ERROR, msg); -} - -/******************************************************************************/ - -void ejsMemoryError(Ejs *ep) -{ - ejsError(ep, EJS_MEMORY_ERROR, "Memory allocation error"); -} - -/******************************************************************************/ - -void ejsArgError(Ejs *ep, const char *msg) -{ - mprAssert(msg && *msg); - - ejsError(ep, EJS_ARG_ERROR, msg); -} - -/******************************************************************************/ - -void ejsInternalError(Ejs *ep, const char *msg) -{ - mprAssert(msg && *msg); - - ejsError(ep, EJS_INTERNAL_ERROR, msg); -} - -/******************************************************************************/ -/* - * Public routine to set the error message. Caller MUST NOT free. - */ - -char *ejsGetErrorMsg(Ejs *ep) -{ - EjsVar *error; - const char *message, *stack, *name; - char *buf; - - error = ep->result; - - if (! ejsVarIsObject(error)) { - name = message = stack = 0; - } else { - name = ejsGetPropertyAsString(ep, error, "name"); - message = ejsGetPropertyAsString(ep, error, "message"); - stack = ejsGetPropertyAsString(ep, error, "stack"); - } - if (name == 0 || message == 0) { - buf = mprStrdup(ep, "Unspecified execution error\n"); - } else { - mprAllocSprintf(MPR_LOC_ARGS(ep), &buf, 0, - "%s Exception: %s\nStack:\n%s\n", - name, message, stack ? stack : " " ); - } - mprFree(ep->errorMsg); - ep->errorMsg = buf; - return buf; -} - -/******************************************************************************/ -/* - * Get the current line number - */ - -int ejsGetLineNumber(Ejs *ep) -{ - if (ep->input == 0) { - return -1; - } - return ep->input->lineNumber; -} - -/******************************************************************************/ -/* - * Return the local object - */ - -EjsVar *ejsGetLocalObj(Ejs *ep) -{ - return ep->local; -} - -/******************************************************************************/ -/* - * Return the global object - */ - -EjsVar *ejsGetGlobalObj(Ejs *ep) -{ - return ep->global; -} - -/******************************************************************************/ -/* - * Set the expression return value - */ - -void ejsSetReturnValue(Ejs *ep, EjsVar *vp) -{ - mprAssert(ep); - mprAssert(vp); - - if (vp == 0) { - return; - } - ejsWriteVar(ep, ep->result, vp, EJS_SHALLOW_COPY); -} - -/******************************************************************************/ -/* - * Set the expression return value and free the arg. - */ - -void ejsSetReturnValueAndFree(Ejs *ep, EjsVar *vp) -{ - mprAssert(ep); - mprAssert(vp); - - ejsWriteVar(ep, ep->result, vp, EJS_SHALLOW_COPY); - ejsFreeVar(ep, vp); -} - -/******************************************************************************/ -/* - * Set the expression return value to a string value. - */ - -void ejsSetReturnValueToString(Ejs *ep, const char *value) -{ - mprAssert(ep); - mprAssert(value); - - ejsWriteVarAsString(ep, ep->result, value); -} - -/******************************************************************************/ -/* - * Set the expression return value to a binary string value. - */ - -void ejsSetReturnValueToBinaryString(Ejs *ep, const uchar *value, int len) -{ - mprAssert(ep); - mprAssert(value); - - ejsWriteVarAsBinaryString(ep, ep->result, value, len); -} - -/******************************************************************************/ -/* - * Set the expression return value to a integer value. - */ - -void ejsSetReturnValueToInteger(Ejs *ep, int value) -{ - mprAssert(ep); - - ejsWriteVarAsInteger(ep, ep->result, value); -} - -/******************************************************************************/ -/* - * Set the expression return value to an EjsNum value. - */ - -void ejsSetReturnValueToNumber(Ejs *ep, EjsNum value) -{ - mprAssert(ep); - - ejsWriteVarAsNumber(ep, ep->result, value); -} - -/******************************************************************************/ -/* - * Set the expression return value to a boolean value. - */ - -void ejsSetReturnValueToBoolean(Ejs *ep, int value) -{ - mprAssert(ep); - - ejsWriteVarAsBoolean(ep, ep->result, value); -} - -/******************************************************************************/ -/* - * Set the expression return value to a boolean value. - */ - -void ejsSetReturnValueToUndefined(Ejs *ep) -{ - mprAssert(ep); - - ejsWriteVarAsUndefined(ep, ep->result); -} - -/******************************************************************************/ -/* - * Get the expression return value - */ - -EjsVar *ejsGetReturnValue(Ejs *ep) -{ - mprAssert(ep); - - return ep->result; -} - -/******************************************************************************/ - -void *ejsGetUserData(Ejs *ep) -{ - mprAssert(ep); - - return ep->userData; -} - -/******************************************************************************/ -/* - * Get a variable given a full variable spec possibly containing "." or "[]". - */ - -EjsVar *ejsGetVar(Ejs *ep, const char *fullName) -{ - mprAssert(ep); - mprAssert(fullName && *fullName); - - return ejsFindProperty(ep, 0, 0, ep->global, ep->local, fullName, 0); -} - -/******************************************************************************/ -/* - * Get a string var given a full variable spec possibly containing "." or "[]". - */ - -const char *ejsGetStr(Ejs *ep, const char *fullName, const char *defaultValue) -{ - EjsVar *vp; - - mprAssert(fullName && *fullName); - - vp = ejsFindProperty(ep, 0, 0, ep->global, ep->local, fullName, 0); - if (vp == 0 || !ejsVarIsString(vp)) { - return defaultValue; - } - /* MOB -- what about VarToStr */ - return vp->string; -} - -/******************************************************************************/ -/* - * Get an int var given a full variable spec possibly containing "." or "[]". - */ - -int ejsGetInt(Ejs *ep, const char *fullName, int defaultValue) -{ - EjsVar *vp; - - mprAssert(ep); - mprAssert(fullName && *fullName); - - vp = ejsFindProperty(ep, 0, 0, ep->global, ep->local, fullName, 0); - if (vp == 0 || !ejsVarIsInteger(vp)) { - return defaultValue; - } - /* MOB -- should use VarToInt */ - return vp->integer; -} - -/******************************************************************************/ -/* - * Get an bool var given a full variable spec possibly containing "." or "[]". - */ - -int ejsGetBool(Ejs *ep, const char *fullName, int defaultValue) -{ - EjsVar *vp; - - mprAssert(ep); - mprAssert(fullName && *fullName); - - vp = ejsFindProperty(ep, 0, 0, ep->global, ep->local, fullName, 0); - if (vp == 0 || !ejsVarIsBoolean(vp)) { - return defaultValue; - } - /* MOB -- should use VarToBool */ - return vp->boolean; -} - -/******************************************************************************/ -/* - * Set a variable that may be an arbitrarily complex object or array reference. - * Will always define in the top most variable frame. - */ - -int ejsSetVar(Ejs *ep, const char *fullName, const EjsVar *value) -{ - EjsVar *vp; - - mprAssert(fullName && *fullName); - - vp = ejsFindProperty(ep, 0, 0, ep->global, ep->local, fullName, 1); - if (vp == 0) { - return MPR_ERR_CANT_CREATE; - } - - if (ejsWriteVar(ep, vp, value, EJS_SHALLOW_COPY) == 0) { - return MPR_ERR_CANT_WRITE; - } - - return 0; -} - -/******************************************************************************/ -/* - * Set a variable that may be an arbitrarily complex object or array reference. - * Will always define in the top most variable frame. - */ - -int ejsSetStr(Ejs *ep, const char *fullName, const char *value) -{ - EjsVar *vp; - - mprAssert(fullName && *fullName); - - vp = ejsFindProperty(ep, 0, 0, ep->global, ep->local, fullName, 1); - if (vp == 0) { - return MPR_ERR_CANT_CREATE; - } - - if (ejsWriteVarAsString(ep, vp, value) == 0) { - return MPR_ERR_CANT_WRITE; - } - - return 0; -} - -/******************************************************************************/ -/* - * Set a variable that may be an arbitrarily complex object or array reference. - * Will always define in the top most variable frame. - */ - -int ejsSetInt(Ejs *ep, const char *fullName, int value) -{ - EjsVar *vp; - - mprAssert(fullName && *fullName); - - vp = ejsFindProperty(ep, 0, 0, ep->global, ep->local, fullName, 1); - if (vp == 0) { - return MPR_ERR_CANT_CREATE; - } - - /* Can't fail */ - ejsWriteVarAsInteger(ep, vp, value); - - return 0; -} - -/******************************************************************************/ -/* - * Set a variable that may be an arbitrarily complex object or array reference. - * Will always define in the top most variable frame. - */ - -int ejsSetBool(Ejs *ep, const char *fullName, bool value) -{ - EjsVar *vp; - - mprAssert(fullName && *fullName); - - vp = ejsFindProperty(ep, 0, 0, ep->global, ep->local, fullName, 1); - if (vp == 0) { - return MPR_ERR_CANT_CREATE; - } - - /* Can't fail */ - ejsWriteVarAsBoolean(ep, vp, value); - - return 0; -} - -/******************************************************************************/ -/* - * Set a variable that may be an arbitrarily complex object or array reference. - * Will always define in the top most variable frame. Free the value passed in. - */ - -int ejsSetVarAndFree(Ejs *ep, const char *fullName, EjsVar *value) -{ - EjsVar *vp; - - mprAssert(fullName && *fullName); - - vp = ejsFindProperty(ep, 0, 0, ep->global, ep->local, fullName, 1); - if (vp == 0) { - return MPR_ERR_CANT_CREATE; - } - - if (ejsWriteVar(ep, vp, value, EJS_SHALLOW_COPY) == 0) { - ejsFreeVar(ep, value); - return MPR_ERR_CANT_WRITE; - } - - ejsFreeVar(ep, value); - return 0; -} - -/******************************************************************************/ -/* - * Delete a variable - */ - -int ejsDeleteVar(Ejs *ep, const char *fullName) -{ - EjsVar *vp; - EjsVar *obj; - char *propertyName; - - vp = ejsFindProperty(ep, &obj, &propertyName, ep->global, ep->local, - fullName, 0); - if (vp == 0) { - return -1; - } - - mprAssert(propertyName); - mprAssert(propertyName); - - return ejsDeleteProperty(ep, obj, propertyName); -} - -/******************************************************************************/ -/* - * Utility routine to crack JavaScript arguments. Return the number of args - * seen. This routine only supports %s and %d type args. - * - * Typical usage: - * - * if (ejsParseArgs(argc, argv, "%s %d", &name, &age) < 2) { - * // Insufficient args - * return -1; - * } - */ - -int ejsParseArgs(int argc, char **argv, const char *fmt, ...) -{ - va_list vargs; - const char *cp; - char **sp, *s; - int *bp, *ip, argn; - - va_start(vargs, fmt); - - if (argv == 0) { - return 0; - } - - for (argn = 0, cp = fmt; cp && *cp && argn < argc && argv[argn]; ) { - if (*cp++ != '%') { - continue; - } - - s = argv[argn]; - switch (*cp) { - case 'b': - bp = va_arg(vargs, int*); - if (bp) { - if (strcmp(s, "true") == 0 || s[0] == '1') { - *bp = 1; - } else { - *bp = 0; - } - } else { - *bp = 0; - } - break; - - case 'd': - ip = va_arg(vargs, int*); - *ip = atoi(s); - break; - - case 's': - sp = va_arg(vargs, char**); - *sp = s; - break; - - default: - mprAssert(0); - } - argn++; - } - - va_end(vargs); - return argn; -} - -/******************************************************************************/ -/* - * Define the standard classes - */ - -int ejsDefineStandardClasses(Ejs *master) -{ - if (ejsDefineArrayClass(master) != 0 || - ejsDefineBooleanClass(master) != 0 || - ejsDefineErrorClasses(master) != 0 || - ejsDefineFunctionClass(master) != 0 || - ejsDefineNumberClass(master) != 0 || -#if FUTURE - ejsDefineDateClass(master) != 0 || -#endif -#if BLD_FEATURE_EJS_E4X - ejsDefineXmlClasses(master) != 0 || -#endif -#if BLD_FEATURE_EJS_DB && NOT_HERE - ejsDefineDbClasses(master) != 0 || -#endif - ejsDefineStringClass(master) != 0) { - return MPR_ERR_MEMORY; - } - return 0; -} - -/******************************************************************************/ -/* - * Define the EJS System Object Model - */ - -int ejsDefineSystemClasses(Ejs *master) -{ - if (ejsDefineSystemClass(master) != 0 || - ejsDefineAppClass(master) != 0 || - ejsDefineMemoryClass(master) != 0 || - ejsDefineLogClass(master) != 0 || - ejsDefineDebugClass(master) != 0 || - ejsDefineGCClass(master) != 0 || - ejsDefineFileSystemClass(master) != 0 || -#if BREW - ejsDefineFileClass(master) != 0 || - ejsDefineHTTPClass(master) != 0 || -#endif - ejsDefineGlobalProperties(master) != 0) { - return MPR_ERR_MEMORY; - } - return 0; -} - -/******************************************************************************/ -/* - * Terminate the system object model and classes - */ - -int ejsTermSystemClasses(Ejs *master) -{ -#if BREW - ejsTermHTTPClass(master); -#endif - return 0; -} - -/******************************************************************************/ -/* - * Define the EJS object model - */ - -int ejsCreateObjectModel(Ejs *ejs) -{ - EjsProperty *pp; - - pp = ejsSetPropertyToNewObj(ejs, ejs->global, "system", "System", 0); - if (pp == 0) { - return MPR_ERR_MEMORY; - } - - if (ejsSetPropertyToNewObj(ejs, ejsGetVarPtr(pp), "app", "System.App", - 0) == 0) { - return MPR_ERR_MEMORY; - } - return 0; -} - -/******************************************************************************/ - -void ejsTrace(Ejs *ep, const char *fmt, ...) -{ - va_list args; - char buf[MPR_MAX_LOG_STRING]; - int len; - - va_start(args, fmt); - len = mprVsprintf(buf, sizeof(buf) - 1, fmt, args); - va_end(args); - - mprLog(ep, 0, buf, len); - - va_end(args); -} - -/******************************************************************************/ - -bool ejsGotException(Ejs *ep) -{ - return (bool) ep->gotException; -} - -/******************************************************************************/ - -void ejsSetPrimaryHandle(Ejs *ep, void *primaryHandle) -{ - mprAssert(ep); - - ep->primaryHandle = primaryHandle; -} - -/******************************************************************************/ - -void ejsSetAlternateHandle(Ejs *ep, void *alternateHandle) -{ - mprAssert(ep); - - ep->altHandle = alternateHandle; -} - -/******************************************************************************/ - -#else -void ejsDummy() {} - -#endif /* BLD_FEATURE_EJS */ - -/******************************************************************************/ -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/ejs.h b/source4/lib/appweb/ejs-2.0/ejs/ejs.h deleted file mode 100644 index a926446524..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/ejs.h +++ /dev/null @@ -1,849 +0,0 @@ -/* - * ejs.h - EJScript Language (ECMAScript) header. - */ - -/********************************* Copyright **********************************/ -/* - * @copy default.g - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * Portions Copyright (c) GoAhead Software, 1995-2000. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#ifndef _h_EJS -#define _h_EJS 1 - -#include "mpr.h" -#include "ejsVar.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/********************************* Prototypes *********************************/ -/* - * Constants - */ -#if BLD_FEATURE_SQUEEZE - #define EJS_GC_WORK_QUOTA 160 /* Allocations required before - garbage colllection */ - - #define EJS_PARSE_INCR 256 /* Growth factor */ - #define EJS_MAX_RECURSE 25 /* Sanity for maximum recursion */ - #define EJS_SMALL_OBJ_HASH_SIZE 11 /* Small object hash size */ - #define EJS_LIST_INCR 8 /* Growth increment for lists */ - #define EJS_MAX_BACKTRACE 10 /* Recursion limit for assert */ - -#else - #define EJS_GC_WORK_QUOTA 500 - - #define EJS_PARSE_INCR 1024 - #define EJS_MAX_RECURSE 100 - #define EJS_SMALL_OBJ_HASH_SIZE 11 - #define EJS_LIST_INCR 16 - #define EJS_MAX_BACKTRACE 25 - -#endif - -/* - * Allocation increments for the default interpreter - */ -#define EJS_DEFAULT_VAR_INC 8 /* Var allocation increment */ -#define EJS_DEFAULT_PROP_INC 96 /* Property allocation increment */ -#define EJS_DEFAULT_OBJ_INC 24 /* Object allocation increment */ -#define EJS_DEFAULT_STR_INC 64 /* Object allocation increment */ - -#define EJS_MIN_TIME_FOR_GC 300 /**< Need 1/3 sec for GC */ -#define EJS_GC_MIN_WORK_QUOTA 50 /**< Min to stop thrashing */ - -/* - * Allocation increments for all non-default interpreters - */ -#define EJS_VAR_INC 32 -#define EJS_PROP_INC 64 -#define EJS_OBJ_INC 64 -#define EJS_STR_INC 64 - -#define EJS_INC_FRAMES 8 /* Frame stack increment */ -#define EJS_MAX_FRAMES 64 /* Max frame stack */ - -/* - * Lexical analyser tokens - */ -#define EJS_TOK_ERR -1 /* Any error */ -#define EJS_TOK_LPAREN 1 /* ( */ -#define EJS_TOK_RPAREN 2 /* ) */ -#define EJS_TOK_IF 3 /* if */ -#define EJS_TOK_ELSE 4 /* else */ -#define EJS_TOK_LBRACE 5 /* { */ -#define EJS_TOK_RBRACE 6 /* } */ -#define EJS_TOK_LOGICAL 7 /* ||, &&, ! */ -#define EJS_TOK_EXPR 8 /* +, -, /, % */ -#define EJS_TOK_SEMI 9 /* ; */ -#define EJS_TOK_LITERAL 10 /* literal string */ -#define EJS_TOK_METHOD_NAME 11 /* methodName( */ -#define EJS_TOK_NEWLINE 12 /* newline white space */ -#define EJS_TOK_ID 13 /* Identifier */ -#define EJS_TOK_EOF 14 /* End of script */ -#define EJS_TOK_COMMA 15 /* Comma */ -#define EJS_TOK_VAR 16 /* var */ -#define EJS_TOK_ASSIGNMENT 17 /* = */ -#define EJS_TOK_FOR 18 /* for */ -#define EJS_TOK_INC_DEC 19 /* ++, -- */ -#define EJS_TOK_RETURN 20 /* return */ -#define EJS_TOK_PERIOD 21 /* . */ -#define EJS_TOK_LBRACKET 22 /* [ */ -#define EJS_TOK_RBRACKET 23 /* ] */ -#define EJS_TOK_NEW 24 /* new */ -#define EJS_TOK_DELETE 25 /* delete */ -#define EJS_TOK_IN 26 /* in */ -#define EJS_TOK_FUNCTION 27 /* function */ -#define EJS_TOK_NUMBER 28 /* Number */ -#define EJS_TOK_CLASS 29 /* class */ -#define EJS_TOK_EXTENDS 30 /* extends */ -#define EJS_TOK_PUBLIC 31 /* public */ -#define EJS_TOK_PRIVATE 32 /* private */ -#define EJS_TOK_PROTECTED 33 /* private */ -#define EJS_TOK_TRY 34 /* try */ -#define EJS_TOK_CATCH 35 /* catch */ -#define EJS_TOK_FINALLY 36 /* finally */ -#define EJS_TOK_THROW 37 /* throw */ -#define EJS_TOK_COLON 38 /* : */ -#define EJS_TOK_GET 39 /* get */ -#define EJS_TOK_SET 40 /* set */ -#define EJS_TOK_MODULE 41 /* module */ -#define EJS_TOK_EACH 42 /* each */ - -/* - * Expression operators - */ -#define EJS_EXPR_LESS 1 /* < */ -#define EJS_EXPR_LESSEQ 2 /* <= */ -#define EJS_EXPR_GREATER 3 /* > */ -#define EJS_EXPR_GREATEREQ 4 /* >= */ -#define EJS_EXPR_EQ 5 /* == */ -#define EJS_EXPR_NOTEQ 6 /* != */ -#define EJS_EXPR_PLUS 7 /* + */ -#define EJS_EXPR_MINUS 8 /* - */ -#define EJS_EXPR_DIV 9 /* / */ -#define EJS_EXPR_MOD 10 /* % */ -#define EJS_EXPR_LSHIFT 11 /* << */ -#define EJS_EXPR_RSHIFT 12 /* >> */ -#define EJS_EXPR_MUL 13 /* * */ -#define EJS_EXPR_ASSIGNMENT 14 /* = */ -#define EJS_EXPR_INC 15 /* ++ */ -#define EJS_EXPR_DEC 16 /* -- */ -#define EJS_EXPR_BOOL_COMP 17 /* ! */ - -/* - * Conditional operators - */ -#define EJS_COND_AND 1 /* && */ -#define EJS_COND_OR 2 /* || */ -#define EJS_COND_NOT 3 /* ! */ - -/** - * EJ Parsing States. Error and Return are be negative. - */ -#define EJS_STATE_ERR -1 /**< Error state */ -#define EJS_STATE_RET -2 /**< Return statement */ -#define EJS_STATE_EOF -3 /**< End of file */ -#define EJS_STATE_COND 2 /* Parsing a conditional stmt */ -#define EJS_STATE_COND_DONE 3 -#define EJS_STATE_RELEXP 4 /* Parsing a relational expr */ -#define EJS_STATE_RELEXP_DONE 5 -#define EJS_STATE_EXPR 6 /* Parsing an expression */ -#define EJS_STATE_EXPR_DONE 7 -#define EJS_STATE_STMT 8 /* Parsing General statement */ -#define EJS_STATE_STMT_DONE 9 -#define EJS_STATE_STMT_BLOCK_DONE 10 /* End of block "}" */ -#define EJS_STATE_ARG_LIST 11 /* Method arg list */ -#define EJS_STATE_ARG_LIST_DONE 12 -#define EJS_STATE_DEC_LIST 16 /* Declaration list */ -#define EJS_STATE_DEC_LIST_DONE 17 -#define EJS_STATE_DEC 18 /* Declaration statement */ -#define EJS_STATE_DEC_DONE 19 - -#define EJS_STATE_BEGIN EJS_STATE_STMT - -/* - * General parsing flags. - */ -#define EJS_FLAGS_EXE 0x1 /* Execute statements */ -#define EJS_FLAGS_LOCAL 0x2 /* Get local vars only */ -#define EJS_FLAGS_GLOBAL 0x4 /* Get global vars only */ -#define EJS_FLAGS_CREATE 0x8 /* Create var */ -#define EJS_FLAGS_ASSIGNMENT 0x10 /* In assignment stmt */ -#define EJS_FLAGS_DELETE 0x20 /* Deleting a variable */ -#define EJS_FLAGS_NEW 0x80 /* In a new stmt() */ -#define EJS_FLAGS_EXIT 0x100 /* Must exit */ -#define EJS_FLAGS_LHS 0x200 /* Left-hand-side of assignment */ -#define EJS_FLAGS_FORIN 0x400 /* In "for (v in ..." */ -#define EJS_FLAGS_CLASS_DEC 0x800 /* "class name [extends] name " */ -#define EJS_FLAGS_TRY 0x2000 /* In a try {} block */ -#define EJS_FLAGS_CATCH 0x4000 /* "catch (variable)" */ -#define EJS_FLAGS_DONT_GC 0x8000 /* Don't garbage collect */ -#define EJS_FLAGS_NO_ARGS 0x10000 /* Accessors don't use args */ -#define EJS_FLAGS_ENUM_HIDDEN 0x20000 /* Enumerate hidden fields */ -#define EJS_FLAGS_ENUM_BASE 0x40000 /* Enumerate base classes */ -#define EJS_FLAGS_TRACE_ARGS 0x80000 /* Support for printv */ -#define EJS_FLAGS_SHARED_SLAB 0x100000/* Using a shared slab */ - -/* - * Exceptions - */ -#define EJS_ARG_ERROR "ArgError" /**< Method argument error */ -#define EJS_ASSERT_ERROR "AssertError" /**< Assertion error */ -#define EJS_EVAL_ERROR "EvalError" /**< General evalation error */ -#define EJS_INTERNAL_ERROR "InternalError" /**< Internal error */ -#define EJS_IO_ERROR "IOError" /**< IO or data error */ -#define EJS_MEMORY_ERROR "MemoryError" /**< Memory allocation error */ -#define EJS_RANGE_ERROR "RangeError" /**< Data out of range (div by 0) */ -#define EJS_REFERENCE_ERROR "ReferenceError"/**< Object or property reference */ -#define EJS_SYNTAX_ERROR "SyntaxError" /**< Javascript syntax error */ -#define EJS_TYPE_ERROR "TypeError" /**< Wrong type supplied */ - -/* - * E4X - */ -#if BLD_FEATURE_EJS_E4X -#if BLD_FEATURE_SQUEEZE -#define E4X_BUF_SIZE 512 /* Initial buffer size for tokens */ -#define E4X_BUF_MAX (32 * 1024) /* Max size for tokens */ -#define E4X_MAX_NODE_DEPTH 24 /* Max nesting of tags */ -#else -#define E4X_BUF_SIZE 4096 -#define E4X_BUF_MAX (128 * 1024) -#define E4X_MAX_NODE_DEPTH 128 -#endif - -#define E4X_MAX_ELT_SIZE (E4X_BUF_MAX-1) -#define E4X_TEXT_PROPERTY "-txt" -#define E4X_TAG_NAME_PROPERTY "-tag" -#define E4X_COMMENT_PROPERTY "-com" -#define E4X_ATTRIBUTES_PROPERTY "-att" -#define E4X_PI_PROPERTY "-pi" -#define E4X_PARENT_PROPERTY "-parent" -#endif - -#if BLD_FEATURE_MULTITHREAD -/** - * Multithreaded lock function - */ -typedef void (*EjsLockFn)(void *lockData); -/** - * Multithreaded unlock function - */ -typedef void (*EjsUnlockFn)(void *lockData); -#endif - -/* - * Token limits - */ -#define EJS_MAX_LINE 128 /* Maximum input line buffer */ -#define EJS_MAX_TOKEN 640 /* Max input parse token */ -#define EJS_TOKEN_STACK 3 /* Put back token stack */ - -/* - * Putback token - */ - -typedef struct EjsToken { - char tokbuf[EJS_MAX_TOKEN]; - int tid; /* Token ID */ -} EjsToken; - -/* - * EJ evaluation block structure - */ -typedef struct EjsInput { - EjsToken putBack[EJS_TOKEN_STACK]; /* Put back token stack */ - int putBackIndex; /* Top of stack index */ - char line[EJS_MAX_LINE]; /* Current line */ - char *fileName; /* File or script name */ - int lineLength; /* Current line length */ - int lineNumber; /* Parse line number */ - int lineColumn; /* Column in line */ - struct EjsInput *next; /* Used for backtraces */ - const char *procName; /* Gives name in backtrace */ - const char *script; /* Input script for parsing */ - char *scriptServp; /* Next token in the script */ - int scriptSize; /* Length of script */ - char tokbuf[EJS_MAX_TOKEN]; /* Current token */ - int tid; /* Token ID */ - char *tokEndp; /* Pointer past end of token */ - char *tokServp; /* Pointer to next token char */ - struct EjsInput *nextInput; /* Free list of input structs */ -} EjsInput; - -/* - * Method call structure - */ -typedef struct EjsProc { - MprArray *args; /* Args for method */ - EjsVar *fn; /* Method definition */ - char *procName; /* Method name */ -} EjsProc; - - -/** - * @overview EJScript Service structure - * @description The EJScript service manages the overall language runtime. It - * is the factory that creates interpreter instances via ejsCreateInterp. - * The EJScript service creates a master interpreter that holds the - * standard language classes and properties. When user interpreters are - * created, they reference (without copying) the master interpreter to - * gain access to the standard classes and types. - * @stability Prototype. - * @library libejs. - * @see ejsOpenService, ejsCloseService, ejsCreateInterp, ejsDestoryInterp - */ -typedef struct EjsService { - EjsVar *globalClass; /* Global class */ - struct Ejs *master; /* Master Interp inherited by all */ -#if BLD_FEATURE_MULTITHREAD - EjsLockFn lock; - EjsUnlockFn unlock; - void *lockData; -#endif -} EjsService; - - -/* - * Memory statistics - */ -typedef struct EjsMemStats { - uint maxMem; - uint usedMem; -} EjsMemStats; - - -/* - * Garbage collection block alignment - */ -#define EJS_ALLOC_ALIGN(ptr) \ - (((ptr) + sizeof(void*) - 1) & ~(sizeof(void*) - 1)) - -/* - * Default GC tune factors - */ -#define EJS_GC_START_THRESHOLD (32 * 1024) - -/* - * The Garbage collector is a generational collector. It ages blocks and - * optimizes the mark / sweep algorithm to focus on new and recent blocks - */ -typedef enum EjsGeneration { - EJS_GEN_NEW = 0, - EJS_GEN_RECENT_1 = 1, - EJS_GEN_RECENT_2 = 2, - EJS_GEN_OLD = 3, - EJS_GEN_PERMANENT = 4, - EJS_GEN_MAX = 5, -} EjsGeneration; - -/* - * Garbage collector control - */ -typedef struct EjsGC { - bool enable; - bool enableDemandCollect; - bool enableIdleCollect; - /* - * maxMemory should be set to be 95% of the real max memory limit - */ - uint maxMemory; /* Above this, Throw Memory exception. */ - int workQuota; /* Quota of work before GC */ - int workDone; /* Count of allocations */ - int degraded; /* Have exceeded maxMemory */ - - /* - * Debug Levels 0-N (increases verbosity) - * 1 -- Sweep and collection count - * 2 -- Trace objects deleted - * 3 -- Trace objects marked - * 4 -- Print alloc report when needing a demand allocation - * - */ - int debugLevel; /* In debug mode */ - int collecting; /* Running garbage collection */ - uint collectionCount; /* Number of times GC ran */ -#if BLD_DEBUG - int gcIndent; /* Indent formatting */ - int objectsInUse; /* Objects currently reachable */ - int propertiesInUse; /* Properties currently reachable */ -#endif -} EjsGC; - -/* - * Slab memory allocation - */ -typedef struct EjsSlab { - uint allocIncrement; /* Growth increment in slab */ - uint size; /* Size of allocations */ - EjsGCLink freeList; /* Free list (only next ptr is used) */ - EjsObj *lastRecentBlock; /* Saved for GC age generations phase */ - EjsGCLink allocList[EJS_GEN_MAX]; /* Allocated block list */ - -#if BLD_FEATURE_ALLOC_STATS - uint totalAlloc; /* Total count of allocation calls */ - uint freeCount; /* Number of blocks on the slab freelist */ - uint allocCount; /* Number of allocated blocks */ - uint peakAllocated; /* Peak allocated */ - uint peakFree; /* Peak on the free list */ - uint totalReclaimed; /* Total blocks reclaimed on sweeps */ - uint totalSweeps; /* Total sweeps */ -#endif -} EjsSlab; - - -/** - * @overview EJ interpreter control structure. - * @description EJ allocates one control structure per active interpreter. - * The \ref ejsCreateInterp routine creates the Ejs structure and returns - * a reference to be used in subsequent EJ API calls. - * @stability Prototype. - * @library libejs. - * @see ejsCreateInterp, ejsDestroyInterp, ejsOpenService - */ -struct Ejs { - void *altHandle; /* Alternate callback handle */ - bool castAlloc; /* True if castTemp is allocated */ - char *castTemp; /* Temporary string for casting */ - char *currentClass; /* Current class name */ - EjsVar *currentObj; /* Ptr to current object */ - EjsVar *thisObject; /* Ptr to current "this" */ - EjsProperty *currentProperty; /* Ptr to current property */ - EjsGC gc; /* Garbage collector control */ - char *errorMsg; /* Error message */ - char *fileName; /* File or script name */ - int lineNumber; /* File line number */ - int scriptStatus; /* Status to exit() */ - int flags; /* Flags */ - MprArray *frames; /* List of variable frames */ - EjsVar *global; /* Global object */ - EjsVar *objectClass; /* Object class */ - int gotException; /* Exception thrown */ - EjsInput *input; /* Input evaluation block */ - int depth; /* Recursion depth */ - EjsVar *local; /* Local object */ - int maxDepth; /* Maximum depth for formatting */ - void *primaryHandle; /* primary callback handle */ - EjsProc *proc; /* Current method */ - int recurseCount; /* Recursion counter */ - EjsVar *result; /* Variable result */ - int tid; /* Current token id */ - char *token; /* Pointer to token string */ - EjsVar tokenNumber; /* Parsed number */ - EjsService *service; /* Service object */ - void *userData; /* Method user data */ - - EjsSlab *slabs; /* Memory allocation slabs */ - MprCtx slabAllocContext; /* Allocation context */ - EjsInput *inputList; /* Free list of input structs */ - -#if BLD_FEATURE_MULTITHREAD - EjsLockFn lock; /* Lock method */ - EjsUnlockFn unlock; /* Unlock method */ - void *lockData; /* Lock data argument */ -#endif -#define EJS_MAX_STACK (10 * 1024) - char stack[EJS_MAX_STACK]; /* Local variable stack */ - char *stkPtr; /* Local variable stack ptr */ - void *inputMarker; /* Recurse protection */ -}; - - -typedef struct EjsModule -{ - int dummy; -} EjsModule; - - -/* - * Method callback when using Alternate handles. GaCompat uses these and - * passes the web server request structure via the altHandle. - */ -typedef void *EjsHandle; -typedef int (*EjsAltCMethod)(Ejs *ejs, EjsHandle altHandle, - EjsVar *thisObj, int argc, EjsVar **argv); -typedef int (*EjsAltStringCMethod)(Ejs *ejs, EjsHandle altHandle, - EjsVar *thisObj, int argc, char **argv); - - -/* - * API Constants - */ -#define EJS_USE_OWN_SLAB 1 - -/******************************** Internal API ********************************/ -/* - * Ejs Lex - */ -extern int ejsLexOpenScript(Ejs *ejs, const char *script); -extern void ejsLexCloseScript(Ejs *ejs); -extern int ejsInitInputState(EjsInput *ip); -extern void ejsLexSaveInputState(Ejs *ejs, EjsInput* state); -extern void ejsLexFreeInputState(Ejs *ejs, EjsInput* state); -extern void ejsLexRestoreInputState(Ejs *ejs, EjsInput* state); -extern int ejsLexGetToken(Ejs *ejs, int state); -extern void ejsLexPutbackToken(Ejs *ejs, int tid, char *string); - -/* - * Parsing - */ -extern int ejsParse(Ejs *ejs, int state, int flags); -extern int ejsGetFlags(Ejs *ejs); - -/* - * Create variable scope blocks - */ -extern int ejsOpenBlock(Ejs *ejs); -extern int ejsSetBlock(Ejs *ejs, EjsVar *local); -extern int ejsCloseBlock(Ejs *ejs, int vid); -extern int ejsEvalBlock(Ejs *ejs, char *script, EjsVar *vp); -extern void ejsSetFileName(Ejs *ejs, const char *fileName); - -/* - * Class definitions - */ -extern EjsVar *ejsCreateSimpleClass(Ejs *ejs, EjsVar *baseClass, - const char *className); -extern int ejsDefineObjectClass(Ejs *ejs); -extern int ejsDefineArrayClass(Ejs *ejs); -extern int ejsDefineBooleanClass(Ejs *ejs); -extern int ejsDefineErrorClasses(Ejs *ejs); -extern int ejsDefineFileClass(Ejs *ejs); -extern int ejsDefineFileSystemClass(Ejs *ejs); -extern int ejsDefineHTTPClass(Ejs *ejs); -extern int ejsDefineFunctionClass(Ejs *ejs); -extern int ejsDefineNumberClass(Ejs *ejs); -extern int ejsDefineStringClass(Ejs *ejs); -extern int ejsDefineDateClass(Ejs *ejs); -extern int ejsDefineStandardClasses(Ejs *ejs); - -#if BLD_FEATURE_EJS_E4X -extern int ejsDefineXmlClasses(Ejs *ejs); -extern EjsVar *ejsCreateXml(Ejs *ejs); -#endif - -#if BLD_FEATURE_EJS_DB -extern int ejsDefineDbClasses(Ejs *ejs); -#endif - -/* - * System class definitions - */ -extern int ejsDefineSystemClasses(Ejs *ejs); -extern int ejsDefineSystemClass(Ejs *ejs); -extern int ejsDefineAppClass(Ejs *ejs); -extern int ejsDefineDebugClass(Ejs *ejs); -extern int ejsDefineLogClass(Ejs *ejs); -extern int ejsDefineMemoryClass(Ejs *ejs); -extern int ejsDefineGCClass(Ejs *ejs); -extern int ejsDefineGlobalProperties(Ejs *ejs); - -extern int ejsTermSystemClasses(Ejs *ejs); -extern void ejsTermHTTPClass(Ejs *ejs); - -extern int ejsCreateObjectModel(Ejs *ejs); - -/* - * Class constructors - */ -extern int ejsArrayConstructor(Ejs *ejs, EjsVar *thisObj, int argc, - EjsVar **argv); -extern int ejsXmlConstructor(Ejs *ejs, EjsVar *thisObj, int argc, - EjsVar **argv); -extern int ejsXmlListConstructor(Ejs *ejs, EjsVar *thisObj, int argc, - EjsVar **argv); -extern int ejsBooleanConstructor(Ejs *ejs, EjsVar *thisObj, int argc, - EjsVar **agv); -extern int ejsFunctionConstructor(Ejs *ejs, EjsVar *thisObj, int argc, - EjsVar **agv); -extern int ejsNumberConstructor(Ejs *ejs, EjsVar *thisObj, int argc, - EjsVar **argv); -extern int ejsStringConstructor(Ejs *ejs, EjsVar *thisObj, int argc, - EjsVar **argv); -extern int ejsDateConstructor(Ejs *ejs, EjsVar *thisObj, - int argc, EjsVar **argv); - -/* - * Garbage collection - */ -extern void ejsGCInit(Ejs *ejs, int objInc, int propInc, int varInc, - int strInc); -extern int ejsIsTimeForGC(Ejs *ep, int timeTillNextEvent); - -extern bool ejsSetGCDebugLevel(Ejs *ep, int debugLevel); -extern void ejsSweepAll(Ejs *ep); - -extern EjsObj *ejsAllocObj(EJS_LOC_DEC(ejs, loc)); -extern EjsProperty *ejsAllocProperty(EJS_LOC_DEC(ejs, loc)); -extern EjsVar *ejsAllocVar(EJS_LOC_DEC(ejs, loc)); -extern void ejsFree(Ejs *ejs, void *ptr, int slabIndex); - -extern int ejsCollectGarbage(Ejs *ejs, int slabIndex); -extern int ejsIncrementalCollectGarbage(Ejs *ejs); - -#if BLD_DEBUG -extern void ejsDumpObjects(Ejs *ejs); -#endif - -#if BLD_FEATURE_ALLOC_STATS -extern void ejsPrintAllocReport(Ejs *ejs, bool printLeakReport); -#endif - -extern void ejsCleanInterp(Ejs *ejs, bool doStats); -extern void ejsSetInternalMethods(Ejs *ejs, EjsVar *op); -extern void ejsSetPrimaryHandle(Ejs *ep, void *primaryHandle); -extern void ejsSetAlternateHandle(Ejs *ep, void *alternateHandle); -extern void *ejsGetUserData(Ejs *ejs); - -/* - * Could possibly make these routines public - */ - -extern int ejsSetGCMaxMemory(Ejs *ep, uint maxMemory); -extern uint ejsGetUsedMemory(Ejs *ejs); -extern uint ejsGetAllocatedMemory(Ejs *ejs); -extern uint ejsGetAvailableMemory(Ejs *ejs); -extern char *ejsFormatStack(Ejs* ep);; - -/********************************* Prototypes *********************************/ -#if BLD_FEATURE_MULTITHREAD -extern int ejsSetServiceLocks(EjsService *sp, EjsLockFn lock, - EjsUnlockFn unlock, void *data); -#endif - -/* - * Ejs service and interpreter management - */ -extern EjsService *ejsOpenService(MprCtx ctx); -extern void ejsCloseService(EjsService *sp, bool doStats); - -extern Ejs *ejsCreateInterp(EjsService *sp, void *primaryHandle, - void *altHandle, EjsVar *global, bool useOwnSlab); -extern void ejsDestroyInterp(Ejs *ejs, bool doStats); - -extern Ejs *ejsGetMasterInterp(EjsService *sp); -extern EjsVar *ejsGetGlobalClass(Ejs *ejs); - -/* - * Module support - */ -extern EjsModule *ejsCreateModule(const char *name, const char *version, - int (*start)(EjsModule*), int (*stop)(EjsModule*)); - -/* - * Native Objects - */ - -void ejsSetNativeData(EjsVar *obj, void *data); -void ejsSetNativeHelpers(Ejs *ejs, EjsVar *nativeClass, - int (*createInstance)(Ejs *ejs, EjsVar *thisObj, int argc, - EjsVar **argv), - void (*disposeInstance)(Ejs *ejs, EjsVar *thisObj), - bool (*hasProperty)(Ejs *ejs, EjsVar *thisObj, const char *prop), - int (*deleteProperty)(Ejs *ejs, EjsVar *thisObj, const char *prop), - int (*getProperty)(Ejs *ejs, EjsVar *thisObj, const char *prop, - EjsVar *dest), - int (*setProperty)(Ejs *ejs, EjsVar *thisObj, const char *prop, - EjsVar *value), - int (*doOperator)(Ejs *ejs, EjsVar *thisObj, EjsOp *op, EjsVar - *result, EjsVar *lhs, EjsVar *rhs, int *code) - ); - -/* - * Evaluation methods - */ -extern int ejsEvalFile(Ejs *ejs, const char *path, EjsVar *result); -extern int ejsEvalScript(Ejs *ejs, const char *script, EjsVar *result); -extern int ejsRunMethod(Ejs *ejs, EjsVar *obj, - const char *methodName, MprArray *args); -extern int ejsRunMethodCmd(Ejs *ejs, EjsVar *obj, - const char *methodName, const char *cmdFmt, ...); -extern EjsVar *ejsGetReturnValue(Ejs *ejs); - -extern EjsVar *ejsGetLocalObj(Ejs *ejs); -extern EjsVar *ejsGetGlobalObj(Ejs *ejs); - -/* - * Define a class in the specified interpreter. If used with the default - * interpeter, then the class is defined for all interpreters. - */ -extern EjsVar *ejsDefineClass(Ejs *ejs, const char *className, - const char *extends, EjsCMethod constructor); -extern EjsVar *ejsGetClass(Ejs *ejs, EjsVar *parentClass, - const char *className); - -extern const char *ejsGetClassName(EjsVar *obj); -extern const char *ejsGetBaseClassName(EjsVar *obj); - -extern bool ejsIsSubClass(EjsVar *target, EjsVar *baseClass); -extern EjsVar *ejsGetBaseClass(EjsVar *obj); -extern void ejsSetBaseClass(EjsVar *obj, EjsVar *baseClass); - - -#define ejsCreateSimpleObj(ejs, className) \ - ejsCreateSimpleObjInternal(EJS_LOC_ARGS(ejs), className) -extern EjsVar *ejsCreateSimpleObjInternal(EJS_LOC_DEC(ejs, loc), - const char *className); - -#define ejsCreateSimpleObjUsingClass(ejs, baseClass) \ - ejsCreateSimpleObjUsingClassInt(EJS_LOC_ARGS(ejs), \ - baseClass) -extern EjsVar *ejsCreateSimpleObjUsingClassInt(EJS_LOC_DEC(ejs, loc), - EjsVar *baseClass); - -/* - * This will create an object and call all required constructors - */ -extern EjsVar *ejsCreateObj(Ejs *ejs, EjsVar *obj, - const char *className, const char *constructorArgs); - -#define ejsCreateObjUsingArgv(ejs, obj, className, args) \ - ejsCreateObjUsingArgvInternal(EJS_LOC_ARGS(ejs), obj, \ - className, args) -extern EjsVar *ejsCreateObjUsingArgvInternal(EJS_LOC_DEC(ejs, loc), - EjsVar *obj, const char *className, MprArray *args); - -#define ejsCreateArray(ejs, size) \ - ejsCreateArrayInternal(EJS_LOC_ARGS(ejs), size) -extern EjsVar *ejsCreateArrayInternal(EJS_LOC_DEC(ejs, loc), - int size); - -/* - * Array methods. MOB -- need other array methods - */ -/* MOB -- spell out element */ -extern EjsVar *ejsAddArrayElt(Ejs *ejs, EjsVar *op, EjsVar *element, - EjsCopyDepth copyDepth); -/* - * Required: Array methods - * - array = obj.getMethods(); - array = obj.getProperties(); - - array.property.isPublic(); - array.property.isPrivate(); - array.property.isMethod(); - array.property.isEnumerable(); - array.property.isReadOnly(); - array.property.allowsNonUnique(); - array.property.getParent(); -*/ - -/* MOB -- should we have an API that takes a EjsCopyDepth */ -extern void ejsSetReturnValue(Ejs *ejs, EjsVar *vp); -extern void ejsSetReturnValueAndFree(Ejs *ejs, EjsVar *vp); -extern void ejsSetReturnValueToBoolean(Ejs *ejs, bool value); -extern void ejsSetReturnValueToBinaryString(Ejs *ejs, - const uchar *value, int len); -extern void ejsSetReturnValueToInteger(Ejs *ejs, int value); -extern void ejsSetReturnValueToNumber(Ejs *ejs, EjsNum value); -extern void ejsSetReturnValueToString(Ejs *ejs, const char *value); -extern void ejsSetReturnValueToUndefined(Ejs *ejs); - -/* - * Variable access and control. The fullName arg can contain "[]" and "." - */ -extern bool ejsGetBool(Ejs *ejs, const char *fullName, bool defaultValue); -extern int ejsGetInt(Ejs *ejs, const char *fullName, int defaultValue); -extern const char *ejsGetStr(Ejs *ejs, const char *fullName, - const char *defaultValue); -extern EjsVar *ejsGetVar(Ejs *ejs, const char *fullName); - -extern int ejsSetBool(Ejs *ejs, const char *fullName, bool value); -extern int ejsSetInt(Ejs *ejs, const char *fullName, int value); -extern int ejsSetStr(Ejs *ejs, const char *fullName, const char *value); -extern int ejsSetVar(Ejs *ejs, const char *fullName, const EjsVar *value); -extern int ejsSetVarAndFree(Ejs *ejs, const char *fullName, EjsVar *value); - -extern int ejsDeleteVar(Ejs *ejs, const char *fullName); - -/* - * Error handling - */ -extern void ejsError(Ejs *ejs, const char *errorType, const char *fmt, - ...) PRINTF_ATTRIBUTE(3,4); -/* MOB -- this should take no arguments */ -extern void ejsArgError(Ejs *ejs, const char *msg); -extern void ejsInternalError(Ejs *ejs, const char *msg); -extern void ejsMemoryError(Ejs *ejs); -extern void ejsSyntaxError(Ejs *ejs, const char *msg); - -/* - * Utility methods - */ -extern int ejsParseArgs(int argc, char **argv, const char *fmt, ...); - -extern void ejsExit(Ejs *ejs, int status); -extern bool ejsIsExiting(Ejs *ejs); -extern void ejsClearExiting(Ejs *ejs); - -extern bool ejsGotException(Ejs *ejs); - -/* MOB -- rename Method to Function */ -extern void ejsFreeMethodArgs(Ejs *ep, MprArray *args); -extern int ejsStrcat(Ejs *ep, EjsVar *dest, EjsVar *src); - -/* - * Debugging routines - */ -extern char *ejsGetErrorMsg(Ejs *ejs); -extern int ejsGetLineNumber(Ejs *ejs); -extern void ejsTrace(Ejs *ejs, const char *fmt, ...); - -/* - * Multithreaded lock routines - */ -#if BLD_FEATURE_MULTITHREAD -#define ejsLock(sp) if (sp->lock) { (sp->lock)(sp->lockData); } else -#define ejsUnlock(sp) if (sp->unlock) { (sp->unlock)(sp->lockData); } else -#else -#define ejsLock(sp) -#define ejsUnlock(sp) -#endif - -#ifdef __cplusplus -} -#endif -#endif /* _h_EJS */ - -/*****************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/ejsClass.c b/source4/lib/appweb/ejs-2.0/ejs/ejsClass.c deleted file mode 100644 index 58609adf3f..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/ejsClass.c +++ /dev/null @@ -1,273 +0,0 @@ -/* - * @file ejsClass.c - * @brief EJS class support - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************* Includes ***********************************/ - -#include "ejs.h" - -#if BLD_FEATURE_EJS - -/************************************ Code ************************************/ -/* - * Internal API - * - * Routine to create a simple class object. This routine will create a - * stand-alone class object. Callers must insert this into the relevant - * "global" object for name resolution. From these class objects, instance - * objects may be created via the javascript "new" command. - * - * Users should use ejsDefineClass - */ - -EjsVar *ejsCreateSimpleClass(Ejs *ep, EjsVar *baseClass, const char *className) -{ - EjsProperty *pp; - EjsVar *classObj; - - /* - * Create an instance of an Object to act as the static class object - */ - classObj = ejsCreateSimpleObjUsingClass(ep, baseClass); - if (classObj == 0) { - mprAssert(classObj); - return 0; - } - ejsSetClassName(ep, classObj, className); - - /* - * Set the propotype property to point to this class. - * Note: this is a self reference so the alive bit will not be turned on. - */ - pp = ejsSetProperty(ep, classObj, "prototype", classObj); - ejsMakePropertyEnumerable(pp, 0); - - return classObj; -} - -/******************************************************************************/ -/* - * Define a class in the given interpreter. If parentClass is specified, the - * class is defined in the parent. Otherwise, the class will be defined - * locally/globally. ClassName and extends are full variable specs - * (may contain ".") - */ - -EjsVar *ejsDefineClass(Ejs *ep, const char *className, const char *extends, - EjsCMethod constructor) -{ - EjsVar *parentClass, *classObj, *baseClass, *vp; - char *name; - char *cp; - - /* - * If the className is a qualified name (with "."), then get the - * parent class name. - */ - name = mprStrdup(ep, className); - cp = strrchr(name, '.'); - if (cp != 0) { - *cp++ = '\0'; - className = cp; - parentClass = ejsFindProperty(ep, 0, 0, ep->global, ep->local, name, 0); - if (parentClass == 0 || parentClass->type != EJS_TYPE_OBJECT) { - mprError(ep, MPR_LOC, "Can't find class's parent class %s", name); - mprFree(name); - return 0; - } - - } else { - /* - * Simple class name without a "." so create the class locally - * if a local scope exists, otherwise globally. - */ - parentClass = (ep->local) ? ep->local : ep->global; - } - - if (parentClass == 0) { - mprError(ep, MPR_LOC, "Can't find parent class"); - mprFree(name); - return 0; - } - - /* OPT should use function that doesn't parse [] . */ - baseClass = ejsGetClass(ep, 0, extends); - if (baseClass == 0) { - mprAssert(baseClass); - mprFree(name); - return 0; - } - - classObj = ejsCreateSimpleClass(ep, baseClass, className); - if (classObj == 0) { - mprAssert(classObj); - mprFree(name); - return 0; - } - - if (constructor) { - ejsDefineCMethod(ep, classObj, className, constructor, 0); - } - - ejsSetPropertyAndFree(ep, parentClass, className, classObj); - - vp = ejsGetPropertyAsVar(ep, parentClass, className); - mprFree(name); - - return vp; -} - -/******************************************************************************/ -/* - * Find a class and return the property defining the class. ClassName may - * contain "." and is interpreted relative to obj. Obj is typically some - * parent object, ep->local or ep->global. If obj is null, then the global - * space is used. - */ - -EjsVar *ejsGetClass(Ejs *ep, EjsVar *obj, const char *className) -{ - EjsVar *vp; - - mprAssert(ep); - - /* - * Search first for a constructor of the name of class - * global may not be defined yet. - */ - if (obj) { - vp = ejsFindProperty(ep, 0, 0, obj, 0, className, 0); - - } else { - mprAssert(ep->global); - vp = ejsFindProperty(ep, 0, 0, ep->global, ep->local, className, 0); - } - if (vp == 0 || vp->type != EJS_TYPE_OBJECT) { - return 0; - } - - /* - * Return a reference to the prototype (self) reference. This - * ensures that even if "obj" is deleted, this reference will remain - * usable. - */ - return ejsGetPropertyAsVar(ep, vp, "prototype"); -} - -/******************************************************************************/ -/* - * Return the class name of a class or object - */ - -const char *ejsGetClassName(EjsVar *vp) -{ - EjsObj *obj; - - mprAssert(vp); - mprAssert(vp->type == EJS_TYPE_OBJECT); - mprAssert(vp->objectState->baseClass); - - if (vp == 0 || !ejsVarIsObject(vp)) { - return 0; - } - obj = vp->objectState; - - return obj->className; -} - -/******************************************************************************/ -/* - * Return the class name of an objects underlying class - * If called on an object, it returns the base class. - * If called on a class, it returns the base class for the class. - */ - -const char *ejsGetBaseClassName(EjsVar *vp) -{ - EjsObj *obj; - - mprAssert(vp); - mprAssert(vp->type == EJS_TYPE_OBJECT); - mprAssert(vp->objectState->baseClass); - - if (vp == 0 || !ejsVarIsObject(vp)) { - return 0; - } - obj = vp->objectState; - if (obj->baseClass == 0) { - return 0; - } - mprAssert(obj->baseClass->objectState); - - return obj->baseClass->objectState->className; -} - -/******************************************************************************/ - -EjsVar *ejsGetBaseClass(EjsVar *vp) -{ - if (vp == 0 || !ejsVarIsObject(vp) || vp->objectState == 0) { - mprAssert(0); - return 0; - } - return vp->objectState->baseClass; -} - -/******************************************************************************/ - -void ejsSetBaseClass(EjsVar *vp, EjsVar *baseClass) -{ - if (vp == 0 || !ejsVarIsObject(vp) || vp->objectState == 0) { - mprAssert(0); - return; - } - vp->objectState->baseClass = baseClass; -} - -/******************************************************************************/ - -#else -void ejsProcsDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/ejsCmd.c b/source4/lib/appweb/ejs-2.0/ejs/ejsCmd.c deleted file mode 100644 index 74b57de4d0..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/ejsCmd.c +++ /dev/null @@ -1,468 +0,0 @@ -/* - * @file ejsCmd.c - * @brief Embedded JavaScript (EJS) command line program. - * @overview - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if BLD_FEATURE_EJS && !BREW - -/************************************ Defines *********************************/ - -#define EJS_MAX_CMD_LINE (16 * 1024) -#define EJS_MAX_SCRIPT (4 * 1024 * 1024) -#define EJS_MAX_RESULT_SIZE (4 * 1024 * 1024) -#define EJS_PROMPT "ejs> " - -/****************************** Forward Declarations **************************/ - -static int parseFile(EjsService *ejsService, Ejs *ejs, const char *fileName, - const char *testName, MprFile *testLogFile); -static int ifConsole(); - -static int interactiveUse(MprApp *app, Ejs *ejs, FILE *input, - char *fileName); -static char *readCmd(MprApp *app, FILE *input); - -static int memoryFailure(MprApp *app, uint size, uint total, bool granted); - -static int isConsole = 0; -static int traceCmds = 0; -static int stats = 0; -static int verbose = 0; - -/************************************ Main ************************************/ - -int main(int argc, char *argv[]) -{ - MprApp *app; - const char *programName; - MprFile *testLogFile; - EjsService *ejsService; - Ejs *ejs; - char *commandLine; - const char *testName; - char *argp, *cmd, *testLog; - int i, rc, nextArg, err, len, firstArg, iterations, debugLevel; - - app = mprInit(memoryFailure); - - isConsole = ifConsole(); - programName = mprGetBaseName(argv[0]); - debugLevel = 0; - - ejsService = ejsOpenService(app); - if (ejsService == 0) { - mprError(app, MPR_LOC, "Can't initialize the EJS service."); - return -1; - } - - err = 0; - iterations = 1; - stats = 0; - testLog = getenv("TEST_LOG"); - testLogFile = 0; - testName = 0; - - for (nextArg = 1; nextArg < argc; nextArg++) { - argp = argv[nextArg]; - if (*argp != '-') { - break; - } - if (strcmp(argp, "--debug") == 0) { - if (nextArg >= argc) { - err++; - } else { - debugLevel = atoi(argv[++nextArg]); - } - - } else if (strcmp(argp, "--stats") == 0) { - stats++; - - } else if (strcmp(argp, "--trace") == 0) { - traceCmds++; - - } else if (strcmp(argp, "--iterations") == 0) { - if (nextArg >= argc) { - err++; - } else { - iterations = atoi(argv[++nextArg]); - } - - } else if (strcmp(argp, "--log") == 0) { - /* Get file to log test results to when using ejs as a test shell */ - if (nextArg >= argc) { - err++; - } else { - testLog = argv[++nextArg]; - } - - } else if (strcmp(argp, "--testName") == 0) { - if (nextArg >= argc) { - err++; - } else { - testName = argv[++nextArg]; - } - - } else if (strcmp(argp, "-v") == 0) { - verbose++; - - } else if (strcmp(argp, "-vv") == 0) { - verbose += 2; - - } else if (strcmp(argp, "--verbose") == 0) { - verbose += 2; - - } else { - err++; - break; - } - if (err) { - mprErrorPrintf(app, - "Usage: %s [options] files... or\n" - " %s < file or\n" - " %s or\n" - " Switches:\n" - " --iterations num # Number of iterations to eval file\n" - " --stats # Output stats on exit\n" - " --testName name # Set the test name", - programName, programName, programName); - return -1; - } - } - - if (testName) { - i = 0; - commandLine = 0; - len = mprAllocStrcat(MPR_LOC_ARGS(app), &commandLine, 0, " ", - mprGetBaseName(argv[i++]), NULL); - for (; i < argc; i++) { - len = mprReallocStrcat(MPR_LOC_ARGS(app), &commandLine, 0, len, - " ", argv[i], NULL); - } - mprPrintf(app, " %s\n", commandLine); - } - if (testLog) { - testLogFile = mprOpen(app, testLog, - O_CREAT | O_APPEND | O_WRONLY | O_TEXT, 0664); - if (testLogFile == 0) { - mprError(app, MPR_LOC, "Can't open %s", testLog); - return MPR_ERR_CANT_OPEN; - } - mprFprintf(testLogFile, "\n %s\n", commandLine); - } - - ejs = ejsCreateInterp(ejsService, 0, 0, 0, 0); - if (ejs == 0) { - mprError(app, MPR_LOC, "Can't create EJS interpreter"); - ejsCloseService(ejsService, stats); - if (testLogFile) { - mprClose(testLogFile); - } - mprTerm(app, stats); - exit(-1); - } - - if (debugLevel > 0) { - ejsSetGCDebugLevel(ejs, debugLevel); - } - - rc = 0; - - if (nextArg < argc) { - /* - * Process files supplied on the command line - */ - firstArg = nextArg; - for (i = 0; i < iterations; i++) { - for (nextArg = firstArg; nextArg < argc; nextArg++) { - rc = parseFile(ejsService, ejs, argv[nextArg], testName, - testLogFile); - if (rc < 0) { - return rc; - } - } - } - if (testName) { - if (verbose == 1) { - mprPrintf(app, "\n"); - } - if (verbose <= 1) { - mprPrintf(app, " # PASSED all tests for \"%s\"\n", testName); - } - } - - } else if (! isConsole) { - /* - * Read a script from stdin - */ - cmd = readCmd(app, stdin); - - ejsSetFileName(ejs, "stdin"); - - rc = ejsEvalScript(ejs, cmd, 0); - if (rc < 0) { - mprPrintf(app, "ejs: Error: %s\n", ejsGetErrorMsg(ejs)); - } - mprFree(cmd); - - } else { - /* - * Interactive use. Read commands from the command line. - */ - rc = interactiveUse(app, ejs, stdin, "stdin"); - } - - /* - * Cleanup. Do stats if required. - */ - if (ejs) { - ejsCleanInterp(ejs, 0); - ejsCleanInterp(ejs->service->master, 0); - ejsDestroyInterp(ejs, 0); - } - - ejsCloseService(ejsService, stats); - - if (testLogFile) { - mprClose(testLogFile); - } - - mprTerm(app, stats); - return rc; -} - -/******************************************************************************/ - -static int parseFile(EjsService *ejsService, Ejs *ejs, const char *fileName, - const char *testName, MprFile *testLogFile) -{ - int rc; - - if (testName && verbose == 1) { - mprPrintf(ejs, "."); - } - if (verbose > 1) { - mprPrintf(ejs, "File: %s\n", fileName); - } - - rc = ejsEvalFile(ejs, fileName, 0); - - if (testName) { - char fileBuf[MPR_MAX_FNAME], *cp; - mprStrcpy(fileBuf, sizeof(fileBuf), fileName); - if ((cp = strstr(fileBuf, ".ejs")) != 0) { - *cp = '\0'; - } - if (rc == 0) { - if (verbose > 1) { - mprPrintf(ejs, " # PASSED test \"%s.%s\"\n", testName, - fileBuf); - } - if (testLogFile) { - mprFprintf(testLogFile, " # PASSED test \"%s.%s\"\n", - testName, fileBuf); - } - - } else { - - mprPrintf(ejs, "FAILED test \"%s.%s\"\nDetails: %s\n", - testName, fileBuf, ejsGetErrorMsg(ejs)); - - if (testLogFile) { - mprFprintf(testLogFile, - "FAILED test \"%s.%s\"\nDetails: %s\n", - testName, fileBuf, ejsGetErrorMsg(ejs)); - } - } - } else if (rc < 0) { - mprPrintf(ejs, "ejs: %sIn file \"%s\"\n", - ejsGetErrorMsg(ejs), fileName); - } - return rc; -} - -/******************************************************************************/ - -static char *readCmd(MprApp *app, FILE *input) -{ - char line[EJS_MAX_CMD_LINE]; - char *cmd; - int len, cmdLen; - - cmd = 0; - cmdLen = 0; - - line[sizeof(line) - 1] = '\0'; - - while (1) { - - if (fgets(line, sizeof(line) - 1, input) == NULL) { - break; - } - - len = strlen(line); - - if (line[len - 1] == '\\') { - line[len - 1] = '\0'; - } - cmdLen = mprReallocStrcat(MPR_LOC_ARGS(app), &cmd, EJS_MAX_SCRIPT, - cmdLen, 0, line, NULL); - } - return cmd; -} - -/******************************************************************************/ - -static int interactiveUse(MprApp *app, Ejs *ejs, FILE *input, char *fileName) -{ - EjsVar result; - char line[EJS_MAX_CMD_LINE]; - char *cmd, *buf; - int len, cmdLen, rc; - - cmd = 0; - cmdLen = 0; - - line[sizeof(line) - 1] = '\0'; - - ejsSetFileName(ejs, "console"); - - while (! ejsIsExiting(ejs)) { - - if (isConsole) { - write(1, EJS_PROMPT, strlen(EJS_PROMPT)); - } - - if (fgets(line, sizeof(line) - 1, input) == NULL) { - break; - } - - len = strlen(line); - while (len > 0 && - (line[len - 1] == '\n' || line[len - 1] == '\r')) { - len--; - line[len] = '\0'; - } - - if (line[len - 1] == '\\') { - line[len - 1] = '\0'; - cmdLen = mprReallocStrcat(MPR_LOC_ARGS(app), &cmd, EJS_MAX_SCRIPT, - cmdLen, 0, line, NULL); - - } else { - - cmdLen = mprReallocStrcat(MPR_LOC_ARGS(app), &cmd, EJS_MAX_SCRIPT, - cmdLen, 0, line, NULL); - - - if (traceCmds) { - mprPrintf(ejs, "# %s\n", cmd); - } - - if (cmd[0] == 0x4 || cmd[0] == 0x26 || strcmp(cmd, "quit") == 0) { - ejsExit(ejs, 0); - - } else if ((rc = ejsEvalScript(ejs, cmd, &result)) < 0) { - - mprPrintf(app, "ejs: Error: %s\n", ejsGetErrorMsg(ejs)); - - if (! isConsole) { - return rc; - } - - } else { - if (isConsole || traceCmds) { - buf = ejsVarToString(ejs, &result); - mprPrintf(ejs, "%s\n", buf); - } - } - mprFree(cmd); - cmd = 0; - cmdLen = 0; - } - } - return 0; -} - -/******************************************************************************/ - -static int ifConsole() -{ -#if WIN - INPUT_RECORD irec[1]; - int records = 0; - - if (PeekConsoleInput(GetStdHandle(STD_INPUT_HANDLE), irec, 1, - &records) != 0) { - return 1; - } -#else - return isatty(0); -#endif - return 0; -} - -/******************************************************************************/ - -static int memoryFailure(MprApp *app, uint size, uint total, bool granted) -{ - if (!granted) { - mprPrintf(app, "Can't allocate memory block of size %d\n", size); - mprPrintf(app, "Total memory used %d\n", total); - exit(255); - } - mprPrintf(app, "Memory request for %d bytes exceeds memory red-line\n", - size); - mprPrintf(app, "Total memory used %d\n", total); - return 0; -} - -/******************************************************************************/ - -#else -void ejsCmdLineDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/ejsGarbage.c b/source4/lib/appweb/ejs-2.0/ejs/ejsGarbage.c deleted file mode 100755 index 264da05721..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/ejsGarbage.c +++ /dev/null @@ -1,1214 +0,0 @@ -/* - * @file ejsGarbage.c - * @brief EJS Garbage collector. - * @overview This implements a generational mark and sweep collection scheme. - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if BLD_FEATURE_EJS - -/****************************** Forward Declarations **************************/ - -static void mark(Ejs *ep); -static void markObjByVar(Ejs *ep, EjsVar *op); -static void markObj(EjsObj *obj); -static void markPerm(Ejs *ep, uint gen); -static int sweep(Ejs *ep, uint gen); -static EjsGCLink *ejsAlloc(EJS_LOC_DEC(ep, loc), int slabIndex); -static void ejsGracefulDegrade(Ejs *ep); -static void resetMarks(Ejs *ep, EjsSlab *slab); - -#if FUTURE -static void ageGenerations(Ejs *ep); -#endif - -#if BLD_DEBUG && (!BREW || BREW_SIMULATOR) -uint breakAddr; -#endif - -/************************************* Code ***********************************/ - -void ejsGCInit(Ejs *ep, int objInc, int propInc, int varInc, int strInc) -{ - EjsSlab *slab; - - if (ep->service && ep->service->globalClass) { - ep->service->globalClass->objectState->gcMarked = 1; - } - - slab = &ep->slabs[EJS_SLAB_OBJ]; - slab->allocIncrement = objInc; - slab->size = EJS_ALLOC_ALIGN(sizeof(EjsObj)); - - slab = &ep->slabs[EJS_SLAB_PROPERTY]; - slab->allocIncrement = propInc; - slab->size = EJS_ALLOC_ALIGN(sizeof(EjsProperty)); - - slab = &ep->slabs[EJS_SLAB_VAR]; - slab->allocIncrement = varInc; - slab->size = EJS_ALLOC_ALIGN(sizeof(EjsVar)); - - /* - * Initialize GC. - * Enable GC both idle and demand collections. - * Set no limits and garbage collect if the slabs are - * empty and we have used more than the THRESHOLD of ram. - */ - ep->gc.debugLevel = 0; - ep->gc.enable = 1; - ep->gc.enableIdleCollect = 1; - ep->gc.enableDemandCollect = 1; - ep->gc.workQuota = EJS_GC_WORK_QUOTA; - ep->gc.maxMemory = 0; -} - - -/******************************************************************************/ -#if BLD_FEATURE_ALLOC_STATS - -void ejsPrintAllocReport(Ejs *ep, bool printLeakReport) -{ - EjsSlab *slab; - char *name; - int slabIndex, isObj; - - for (slabIndex = 0; slabIndex < EJS_SLAB_MAX; slabIndex++) { - slab = &ep->slabs[slabIndex]; - if (slabIndex == EJS_SLAB_VAR) { - name = "var"; - } else if (slabIndex == EJS_SLAB_PROPERTY) { - name = "prop"; - } else { - name = "obj"; - } - mprLog(ep, 0, " "); - mprLog(ep, 0, " GC \"%s\" local slab", name); - mprLog(ep, 0, " Total blocks %14d", - slab->allocCount + slab->freeCount); - mprLog(ep, 0, " Block size %14d", slab->size); - mprLog(ep, 0, " Slab RAM allocated %14d", - (slab->allocCount + slab->freeCount) * slab->size); - mprLog(ep, 0, " Slab RAM in use %14d", - slab->allocCount * slab->size); - mprLog(ep, 0, " Blocks in use %14d", slab->allocCount); - mprLog(ep, 0, " Free blocks %14d", slab->freeCount); - mprLog(ep, 0, " Peak allocated %14d", slab->peakAllocated); - mprLog(ep, 0, " Peak free %14d", slab->peakFree); - mprLog(ep, 0, " Total allocations %14d", slab->totalAlloc); - mprLog(ep, 0, " Total blocks reclaimed %14d", slab->totalReclaimed); - mprLog(ep, 0, " Total sweeps %14d", slab->totalSweeps); - mprLog(ep, 0, " Allocation inc %14d", slab->allocIncrement); - } - - mprLog(ep, 0, " "); - mprLog(ep, 0, " Total EJS memory in use %10d", ejsGetUsedMemory(ep)); - mprLog(ep, 0, " Total EJS memory allocated %10d", - ejsGetAllocatedMemory(ep)); - - if (printLeakReport) { - mprLog(ep, 0, " "); - for (slabIndex = 0; slabIndex < EJS_SLAB_MAX; slabIndex++) { - int size; - - slab = &ep->slabs[slabIndex]; - - isObj = 0; - mprLog(ep, 0, " "); - if (slabIndex == EJS_SLAB_VAR) { - name = "var"; - size = sizeof(EjsVar); - } else if (slabIndex == EJS_SLAB_PROPERTY) { - name = "prop"; - size = sizeof(EjsProperty); - } else { - name = "obj"; - size = sizeof(EjsObj); - isObj++; - } -#if BLD_FEATURE_ALLOC_LEAK_TRACK -{ - EjsGCLink *lp; - EjsObj *obj; - int count; - - mprLog(ep, 0, "EJS Leak Report for \"%s\"", name); - count = 0; - - for (lp = slab->allocList[0].next; lp; lp = lp->next) { - mprLog(ep, 0, " %-20s %10d", lp->allocatedBy, size); - if (isObj) { - obj = (EjsObj*) lp; - mprLog(ep, 0, " %-20s %10d %s %s", - lp->allocatedBy, size, - obj->permanent ? "permanent" : "", - obj->alive ? "alive" : "" - ); - } else { - mprLog(ep, 0, " %-20s %10d", lp->allocatedBy, - size); - } - count++; - } - mprLog(ep, 0, " Total blocks %14d", count); -} -#endif - } - mprLog(ep, 0, " "); - } -} - -#endif -/******************************************************************************/ -/* - * Slab allocator - */ - -static EjsGCLink *ejsAlloc(EJS_LOC_DEC(ep, loc), int slabIndex) -{ - EjsSlab *slab; - EjsGCLink *block; - EjsGC *gc; - uint allocatedMemory; - int i; - - mprStackCheck(ep); - - if (slabIndex < 0 || slabIndex >= EJS_SLAB_MAX) { - mprAssert(0); - return 0; - } - - /* - * See if the slab has some free blocks - */ - slab = &ep->slabs[slabIndex]; - if ((block = slab->freeList.next) == 0) { - - allocatedMemory = ejsGetAllocatedMemory(ep); - gc = &ep->gc; - - /* - * No blocks available. If demand collection is enabled, try - * to garbage collect first. We collect if we have done a good - * work quota or we are over the max memory limit. - */ - if (slabIndex != EJS_SLAB_VAR && - ep->gc.enable && ep->gc.enableDemandCollect) { - if ((ep->gc.workDone > ep->gc.workQuota) || - (gc->maxMemory > 0 && allocatedMemory > gc->maxMemory)) { - -#if DEBUG_USE_ONLY - if (ep->gc.debugLevel > 0) { - mprLog(ep, 0, "Need GC, EJS RAM %d, MPR RAM %d\n", - allocatedMemory, mprGetAllocatedMemory(ep)); - if (ep->gc.debugLevel > 4) { - ejsPrintAllocReport(ep, 0); - } - } -#endif - if (ejsCollectGarbage(ep, slabIndex) == 0) { - block = slab->freeList.next; - } - } - } - - if (block == 0) { - if (gc->maxMemory > 0 && allocatedMemory > gc->maxMemory) { - /* - * We are above the max memory limit. We will fail this - * memory allocation, but allow subsequent allocations to - * permit error recovery. We gracefully degrade by setting - * slab chunk sizes to 1. This minimizes real memory - * consumption. This allows us to create - * an exception block to be created by upper layers. - */ - if (! gc->degraded) { - ejsGracefulDegrade(ep); - return 0; - } - } - - /* - * Still non available, so allocate more memory for a set of blocks - * OPT -- should bypass mprAlloc. Need mprMalloc. - */ - block = mprAlloc(ep->slabAllocContext, - slab->size * slab->allocIncrement); - if (block == 0) { - /* - * Now we're in trouble. We should really never get here - * as the graceful degrade will have signaled a memory - * allocation failure. - */ - mprAssert(block != 0); - return 0; - } - - /* - * Chain all the blocks together onto the slab free list - */ - for (i = slab->allocIncrement - 1; i >= 0; i--) { - block->next = slab->freeList.next; -#if BLD_DEBUG - block->magic = EJS_MAGIC_FREE; -#endif - slab->freeList.next = block; - block = (EjsGCLink*) ((char*) block + slab->size); - } - - block = slab->freeList.next; - -#if BLD_FEATURE_ALLOC_STATS - slab->freeCount += slab->allocIncrement; - if (slab->freeCount > slab->peakFree) { - slab->peakFree = slab->freeCount; - } -#endif - } - } - - /* - * We use block to point to the user data in the block. We only - * store the magic number (if debug). No other data is stored in the - * user block. - */ -#if BLD_DEBUG - mprAssert(block->magic == EJS_MAGIC_FREE); -#endif - - /* - * Remove from the free list - */ - slab->freeList.next = block->next; - - /* - * Zero block - */ - memset(block, 0, slab->size); - -#if BLD_DEBUG - block->magic = EJS_MAGIC; -#endif - -#if BLD_FEATURE_ALLOC_STATS - slab->totalAlloc++; - if (++slab->allocCount > slab->peakAllocated) { - slab->peakAllocated = slab->allocCount; - } - slab->freeCount--; -#endif - -#if BLD_DEBUG && (!BREW || BREW_SIMULATOR) - if ((uint) block == breakAddr) { - mprBreakpoint(MPR_LOC, "Watched Block"); - } -#endif - return block; -} - - -/******************************************************************************/ - -EjsObj *ejsAllocObj(EJS_LOC_DEC(ep, loc)) -{ - EjsObj *obj; - EjsSlab *slab; - - obj = (EjsObj*) ejsAlloc(EJS_LOC_PASS(ep, loc), EJS_SLAB_OBJ); - - /* - * Add to the allocated block list for the New generation. - */ - if (obj) { - slab = &ep->slabs[EJS_SLAB_OBJ]; - obj->gc.next = slab->allocList[EJS_GEN_NEW].next; - -#if BLD_FEATURE_ALLOC_LEAK_TRACK - obj->gc.allocatedBy = loc; -#endif - - obj->ejs = ep; - slab->allocList[EJS_GEN_NEW].next = (EjsGCLink*) obj; - - ep->gc.workDone++; - } - - return obj; -} - - -/******************************************************************************/ - -EjsProperty *ejsAllocProperty(EJS_LOC_DEC(ep, loc)) -{ - EjsProperty *prop; - - prop = (EjsProperty*) ejsAlloc(EJS_LOC_PASS(ep, loc), EJS_SLAB_PROPERTY); - mprAssert(prop); - - if (prop) { - prop->var.type = EJS_TYPE_NULL; - prop->var.isProperty = 1; -#if BLD_FEATURE_ALLOC_LEAK_TRACK - prop->var.gc.allocatedBy = loc; -#endif - } - return prop; -} - - -/******************************************************************************/ - -EjsVar *ejsAllocVar(EJS_LOC_DEC(ep, loc)) -{ - EjsVar *vp; - - vp = (EjsVar*) ejsAlloc(EJS_LOC_PASS(ep, loc), EJS_SLAB_VAR); - mprAssert(vp); - - if (vp) { -#if BLD_FEATURE_ALLOC_LEAK_TRACK - EjsSlab *slab; - vp->gc.allocatedBy = loc; - slab = &ep->slabs[EJS_SLAB_VAR]; - vp->gc.next = slab->allocList[EJS_GEN_NEW].next; - slab->allocList[EJS_GEN_NEW].next = (EjsGCLink*) vp; -#endif -#if BLD_DEBUG - vp->propertyName = 0; -#endif - } - return vp; -} - - -/******************************************************************************/ -/* - * Return the block back to the relevant slab - */ - -void ejsFree(Ejs *ep, void *ptr, int slabIndex) -{ - EjsSlab *slab; - EjsGCLink *block; - - mprAssert(ep); - mprAssert(ptr); - - if (slabIndex < 0 || slabIndex >= EJS_SLAB_MAX) { - mprAssert(slabIndex >= 0 && slabIndex < EJS_SLAB_MAX); - return; - } - slab = &ep->slabs[slabIndex]; - -#if BLD_FEATURE_ALLOC_LEAK_TRACK - if (slabIndex == EJS_SLAB_VAR) { - EjsVar *vp, *np, *prev; - - /* - * Remove the block rom the alloc list. WARNING: this is slow - * and should not be used in production code. - */ - vp = (EjsVar*) ptr; - prev = 0; - for (np = (EjsVar*) slab->allocList[0].next; np; - np = (EjsVar*) np->gc.next) { - if (vp == np) { - if (prev) { - prev->gc.next = (EjsGCLink*) np->gc.next; - } else { - slab->allocList[0].next = (EjsGCLink*) np->gc.next; - } - break; - } - prev = np; - } - if (np == 0) { - mprAssert(0); - } - } -#endif - - /* - * Insert into the free list. Only use the next ptr - */ - block = (EjsGCLink*) ptr; - -#if BLD_DEBUG -#if !BREW || BREW_SIMULATOR - if ((uint) block == breakAddr) { - mprBreakpoint(MPR_LOC, "Watched Block"); - } -#endif - mprAssert(block->magic == EJS_MAGIC); - block->magic = EJS_MAGIC_FREE; -#endif - - block->next = slab->freeList.next; - slab->freeList.next = block; - -#if BLD_FEATURE_ALLOC_STATS - slab->allocCount--; - if (++slab->freeCount >= slab->peakFree) { - slab->peakFree = slab->freeCount; - } - slab->totalReclaimed++; - if (slabIndex != 2) { - slabIndex = slabIndex; - } -#endif -} - -/******************************************************************************/ -/* - * Mark an object as being in-use. Traverse all properties for referenced - * objects and base classes. - */ - -static void markObjByVar(Ejs *ep, EjsVar *obj) -{ - EjsProperty *pp; - EjsVar *vp, *baseClass; - - mprAssert(ep); - mprAssert(obj); - - obj->objectState->gcMarked = 1; - -#if BLD_DEBUG - if (ep->gc.debugLevel >= 3) { - int indent = min(ep->gc.gcIndent * 2, 32); - mprLog(ep, 0, "%.*s %-24s %.*s 0x%08X", - indent, " ", - obj->propertyName, - 32 - indent, "................................ ", - (uint) obj->objectState); - ep->gc.gcIndent++; - } - ep->gc.objectsInUse++; -#endif - - /* - * Traverse all referenced objects - * OPT -- optimize by directly accessing the object links and not using - * ejsGetFirst/NextProperty. Then just examine objects - * OPT -- first property in global is global. Should optimize this. - */ - pp = ejsGetFirstProperty(obj, EJS_ENUM_ALL); - while (pp) { - vp = ejsGetVarPtr(pp); - if (vp->type == EJS_TYPE_OBJECT) { - if (!vp->objectState->gcMarked) { -#if FUTURE - /* - * OPT -- we can use the dirty bit on objects to avoid - * visiting permanent objects that are clean. If so, don't - * forget the else case below. - */ - obj = vp->objectState; - if ((!obj->alive && !obj->permanent) || obj->dirty) -#endif - markObjByVar(ep, vp); - } - - } else { -#if BLD_DEBUG - if (ep->gc.debugLevel >= 3) { - int indent = min(ep->gc.gcIndent * 2, 32); - mprLog(ep, 0, "%.*s %-24s %.*s %s", - indent, " ", - vp->propertyName, - 32 - indent, "................................ ", - ejsGetVarTypeAsString(vp)); - } - ep->gc.propertiesInUse++; -#endif - } - pp = ejsGetNextProperty(pp, EJS_ENUM_ALL); - } - - /* - * Traverse the base class - */ - baseClass = obj->objectState->baseClass; - if (baseClass) { - mprAssert(baseClass->type == EJS_TYPE_OBJECT); - mprAssert(baseClass->objectState); - if (baseClass->objectState) { - if (! baseClass->objectState->gcMarked) { - markObjByVar(ep, baseClass); - } - } - } -#if BLD_DEBUG - if (ep->gc.debugLevel >= 3) { - ep->gc.gcIndent--; - } -#endif -} - - -/******************************************************************************/ -/* - * Mark phase. Examine all variable frames and the return result. - */ - -static void mark(Ejs *ep) -{ - EjsVar *vp; - int i; - -#if BLD_DEBUG - if (ep->gc.debugLevel >= 3) { - mprLog(ep, 0, " "); - mprLog(ep, 0, "GC: Marked Blocks:"); - } -#endif - - if (ep->frames) { - for (i = 0; i < mprGetItemCount(ep->frames); i++) { - - vp = (EjsVar*) mprGetItem(ep->frames, i); - mprAssert(vp->type == EJS_TYPE_OBJECT); - - if (! vp->objectState->gcMarked) { - markObjByVar(ep, vp); - } - } - } - - vp = ep->result; - if (vp && vp->type == EJS_TYPE_OBJECT && ! vp->objectState->gcMarked) { - markObjByVar(ep, vp); - } - - vp = ep->currentObj; - if (vp && vp->type == EJS_TYPE_OBJECT && ! vp->objectState->gcMarked) { - markObjByVar(ep, vp); - } - - vp = ejsGetVarPtr(ep->currentProperty); - if (vp && vp->type == EJS_TYPE_OBJECT && ! vp->objectState->gcMarked) { - markObjByVar(ep, vp); - } - - /* - * OPT -- we could mark master as "mark permanent" somehow and - * then we would not need to walk the master objects. - */ - if (ep->slabAllocContext == ep->service->master) { - if (ep->service->master->global) { - markObjByVar(ep, ep->service->master->global); - } - } - -#if BLD_DEBUG - if (ep->gc.debugLevel >= 3) { - mprLog(ep, 0, " "); - } -#endif -} - - -/******************************************************************************/ -#if UNUSED - -static void resetMark(EjsVar *obj) -{ - EjsProperty *pp; - EjsVar *vp, *baseClass; - - obj->objectState->gcMarked = 0; - obj->objectState->visited = 1; - - pp = ejsGetFirstProperty(obj, EJS_ENUM_ALL); - while (pp) { - vp = ejsGetVarPtr(pp); - if (vp->type == EJS_TYPE_OBJECT && !vp->objectState->visited) { - resetMark(vp); - } - pp = ejsGetNextProperty(pp, EJS_ENUM_ALL); - } - - baseClass = obj->objectState->baseClass; - if (baseClass) { - mprAssert(baseClass->type == EJS_TYPE_OBJECT); - mprAssert(baseClass->objectState); - if (baseClass->objectState) { - if (! baseClass->objectState->visited) { - resetMark(baseClass); - } - } - } - obj->objectState->visited = 0; -} - -/******************************************************************************/ -/* - * Mark phase. Examine all variable frames and the return result. - */ - -static void resetAllMarks(Ejs *ep) -{ - EjsVar *vp; - int i; - - for (i = 0; i < mprGetItemCount(ep->frames); i++) { - vp = (EjsVar*) mprGetItem(ep->frames, i); - resetMark(vp); - } - - if (ep->result && ep->result->type == EJS_TYPE_OBJECT && - ! ep->result->objectState->gcMarked) { - resetMark(ep->result); - } -} - -#endif -/******************************************************************************/ -/* - * Sweep up the garbage - */ - -static void resetMarks(Ejs *ep, EjsSlab *slab) -{ - EjsVar *vp; - EjsObj *obj; - int gen, i; - - for (gen = EJS_GEN_NEW; gen < EJS_GEN_MAX; gen++) { - obj = (EjsObj*) slab->allocList[gen].next; - for (; obj; obj = (EjsObj*) obj->gc.next) { - obj->gcMarked = 0; - obj->visited = 0; - } - } - - if (ep->frames) { - for (i = 0; i < mprGetItemCount(ep->frames); i++) { - - vp = (EjsVar*) mprGetItem(ep->frames, i); - mprAssert(vp->type == EJS_TYPE_OBJECT); - - vp->objectState->gcMarked = 0; - vp->objectState->visited = 0; - } - } - - if (ep->result && ep->result->type == EJS_TYPE_OBJECT) { - ep->result->objectState->gcMarked = 0; - } -} - -/******************************************************************************/ -/* - * Mark all permanent and non-alive objects - */ - -static void markPerm(Ejs *ep, uint gen) -{ - EjsSlab *slab; - EjsObj *obj; - - slab = &ep->slabs[EJS_SLAB_OBJ]; - - for (obj = (EjsObj*) slab->allocList[gen].next; obj; ) { - - if (! obj->gcMarked) { - if (!obj->alive || obj->permanent) { - markObj(obj); - } - } - obj = (EjsObj*) obj->gc.next; - - } -} - -/******************************************************************************/ - -static void markObj(EjsObj *obj) -{ - EjsProperty *pp; - EjsPropLink *lp, *head; - EjsObj *op; - - mprAssert(obj); - - obj->gcMarked = 1; - - head = &obj->link; - for (lp = head->next; lp != head; lp = lp->next) { - - pp = ejsGetPropertyFromLink(lp); - - if (pp->var.type == EJS_TYPE_OBJECT) { - op = pp->var.objectState; - if (op != 0 && !op->gcMarked) { - markObj(op); - } - } - } -} - -/******************************************************************************/ -/* - * Sweep up the garbage. Return the number of objects freed. - */ - -static int sweep(Ejs *ep, uint gen) -{ - EjsSlab *slab; - EjsObj *obj, *next, *prev; - int count; - - slab = &ep->slabs[EJS_SLAB_OBJ]; - - /* - * Examine allocated objects in the specified generation (only). - * NOTE: we only sweep object allocated to this interpreter and so - * we do not sweep any permanent objects in the default interpreter. - */ - prev = 0; - count = 0; - for (obj = (EjsObj*) slab->allocList[gen].next; obj; obj = next) { - - next = (EjsObj*) obj->gc.next; - -#if BLD_DEBUG && (!BREW || BREW_SIMULATOR) - if ((uint) obj == breakAddr) { - mprBreakpoint(MPR_LOC, "Watched Block"); - } -#endif - - /* - * If object has not been marked inuse and is not a permanent - * object, then free it. - */ - if (! obj->gcMarked && obj->alive && !obj->permanent) { - -#if BLD_DEBUG - if (ep->gc.debugLevel >= 2) { - if (obj->objName) { - mprLog(ep, 0, "GC: destroy %-18s %10d, %8X", - obj->objName, (uint) obj, (uint) obj); - } else { - mprLog(ep, 0, "GC: destroy UNKNOWN %x", (uint) obj); - } - } -#endif - if (ejsDestroyObj(ep, obj) < 0) { - prev = obj; - obj->gcMarked = 0; - continue; - } - - if (prev) { - prev->gc.next = (EjsGCLink*) next; - } else { - slab->allocList[gen].next = (EjsGCLink*) next; - } - count++; - - } else { - prev = obj; - /* Reset for next time */ - obj->gcMarked = 0; - } - } - - if (gen == (EJS_GEN_OLD - 1)) { - slab->lastRecentBlock = prev; - } -#if BLD_FEATURE_ALLOC_STATS - slab->totalSweeps++; -#endif -#if BLD_DEBUG - if (ep->gc.debugLevel > 0) { - mprLog(ep, 0, "GC: Sweep freed %d objects", count); - } -#endif - return count; -} - -/******************************************************************************/ -/* - * Sweep all variables - */ - -void ejsSweepAll(Ejs *ep) -{ - EjsSlab *slab; - EjsObj *obj, *next, *prev; - int gen; - - slab = &ep->slabs[EJS_SLAB_OBJ]; - - for (gen = EJS_GEN_NEW; gen < EJS_GEN_MAX; gen++) { - prev = 0; - for (obj = (EjsObj*) slab->allocList[gen].next; obj; obj = next) { - next = (EjsObj*) obj->gc.next; - ejsDestroyObj(ep, obj); - } - break; - } -} - -/******************************************************************************/ - -bool ejsObjIsCollectable(EjsVar *vp) -{ - if (vp == 0 || !ejsVarIsObject(vp)) { - return 0; - } - return (vp->objectState->alive && !vp->objectState->permanent); -} - -/******************************************************************************/ -#if FUTURE - -static void ageGenerations(Ejs *ep) -{ - EjsSlab *slab; - EjsGCLink *oldList; - int gen; - - slab = &ep->slabs[EJS_SLAB_OBJ]; - - /* - * Age all blocks. First append all (old - 1) blocks onto the old - * alloc list - */ - oldList = &slab->allocList[EJS_GEN_OLD]; - - if (slab->lastRecentBlock) { - slab->lastRecentBlock->gc.next = oldList->next; - oldList->next = (EjsGCLink*) slab->lastRecentBlock; - } - - /* - * Now simply copy all allocation lists up one generation - */ - for (gen = EJS_GEN_OLD - 1; gen > 0; gen--) { - slab->allocList[gen] = slab->allocList[gen - 1]; - } - slab->allocList[0].next = 0; -} - -#endif -/******************************************************************************/ -/* - * Collect the garbage. This is a mark and sweep over all possible objects. - * If an object is not referenced, it and all contained properties will be - * freed. If a slabIndex is provided, the collection halts when a block is - * available for allocation on that slab. - * - * Return 0 if memory is now available after collecting garbage. Otherwise, - * return MPR_ERR_MEMORY. - */ - -int ejsCollectGarbage(Ejs *ep, int slabIndex) -{ - EjsGeneration gen; - - if (ep->flags & EJS_FLAGS_DONT_GC) { - return -1; - } - - /* - * Prevent destructors invoking the garbage collector - */ - if (ep->gc.collecting) { - return 0; - } - ep->gc.collecting = 1; - - resetMarks(ep, &ep->slabs[EJS_SLAB_OBJ]); - - /* - * Examine each generation of objects starting with the most recent - * generation. Stop scanning when we have a free block to use. - */ - for (gen = EJS_GEN_NEW; gen < EJS_GEN_MAX; gen++) { - - if (slabIndex >= 0 && ep->slabs[slabIndex].freeList.next) { - break; - } - - /* - * FUTURE OPT. Should mark objects in new generation and those - * with a dirty bit set in older generations. Don't need to mark - * entire heap. But how to keep list of dirty objects. - */ - mark(ep); - markPerm(ep, gen); - sweep(ep, gen); - - /* FUTURE - not using generations yet */ - break; - } - - /* - * FUTURE -- not using generations yet. - * - * ageGenerations(ep); - */ - - ep->gc.workDone = 0; - ep->gc.collecting = 0; - - return (gen < EJS_GEN_MAX) ? 0 : MPR_ERR_MEMORY; -} - - -/******************************************************************************/ -/* - * Should be called when the app has been idle for a little while and when it - * is likely to be idle a bit longer. Call ejsIsTimeForGC to see if this is - * true. Return the count of objects collected . - */ - -int ejsIncrementalCollectGarbage(Ejs *ep) -{ - int count; - - if (ep->gc.collecting) { - return 0; - } - - ep->gc.collecting = 1; - - resetMarks(ep, &ep->slabs[EJS_SLAB_OBJ]); - mark(ep); - - /* Not generational yet */ - count = sweep(ep, EJS_GEN_NEW); - - ep->gc.collecting = 0; - ep->gc.workDone = 0; - - return count; -} - -/******************************************************************************/ -#if BLD_DEBUG - -void ejsDumpObjects(Ejs *ep) -{ - int oldDebugLevel; - - mprLog(ep, 0, "Dump of objects in use\n"); - - oldDebugLevel = ep->gc.debugLevel; - - ep->gc.debugLevel = 3; - ep->gc.objectsInUse = 0; - ep->gc.propertiesInUse = 0; - ep->gc.collecting = 1; - - resetMarks(ep, &ep->slabs[EJS_SLAB_OBJ]); - mark(ep); - - ep->gc.collecting = 0; - ep->gc.debugLevel = oldDebugLevel; - - mprLog(ep, 0, "%d objects and %d properties in use", - ep->gc.objectsInUse, ep->gc.propertiesInUse); - mprLog(ep, 0, "%d object bytes, %d property bytes and %d total", - (int) (ep->gc.objectsInUse * sizeof(EjsObj)), - (int) (ep->gc.propertiesInUse * sizeof(EjsProperty)), - (int) ((ep->gc.objectsInUse * sizeof(EjsObj) + - ep->gc.propertiesInUse * sizeof(EjsProperty)))); -} - -#endif -/******************************************************************************/ -/* - * Return true if there is time to do a garbage collection and if we will - * benefit from it. - */ - -int ejsIsTimeForGC(Ejs *ep, int timeTillNextEvent) -{ - EjsGC *gc; - - if (timeTillNextEvent < EJS_MIN_TIME_FOR_GC) { - /* - * Not enough time to complete a collection - */ - return 0; - } - - gc = &ep->gc; - - /* - * Return if we haven't done enough work to warrant a collection - * Trigger a little short of the work quota to try to run GC before - * a demand allocation requires it. - */ - if (!gc->enable || !gc->enableIdleCollect || - (gc->workDone < (gc->workQuota - EJS_GC_MIN_WORK_QUOTA))) { - return 0; - } - -#if UNUSED - mprLog(ep, 0, "Time for GC. Work done %d, time till next event %d", - gc->workDone, timeTillNextEvent); -#endif - return 1; -} - -/******************************************************************************/ -/* - * Return the amount of memory in use by EJS - */ - -uint ejsGetUsedMemory(Ejs *ep) -{ -#if BLD_FEATURE_ALLOC_STATS - EjsSlab *slab; - int i, totalMemory, slabMemory; - - totalMemory = 0; - for (i = 0; i < EJS_SLAB_MAX; i++) { - slab = &ep->slabs[i]; - slabMemory = slab->allocCount * slab->size; - totalMemory += slabMemory; - } - return totalMemory; -#else - return 0; -#endif -} - -/******************************************************************************/ -/* - * Return the amount of memory allocated by EJS - */ - -uint ejsGetAllocatedMemory(Ejs *ep) -{ -#if BLD_FEATURE_ALLOC_STATS - EjsSlab *slab; - int i, totalMemory, slabMemory; - - totalMemory = 0; - for (i = 0; i < EJS_SLAB_MAX; i++) { - slab = &ep->slabs[i]; - slabMemory = (slab->allocCount + slab->freeCount) * slab->size; - totalMemory += slabMemory; - } - return totalMemory; -#else - return 0; -#endif -} - -/******************************************************************************/ -/* - * On a memory allocation failure, go into graceful degrade mode. Set all - * slab allocation chunk increments to 1 so we can create an exception block - * to throw. - */ - -static void ejsGracefulDegrade(Ejs *ep) -{ - EjsSlab *slab; - int i; - - mprLog(ep, 1, "WARNING: Memory almost depleted. In graceful degrade mode"); - for (i = 0; i < EJS_SLAB_MAX; i++) { - slab = &ep->slabs[i]; - slab->allocIncrement = 8; - } - ep->gc.degraded = 1; -} - -/******************************************************************************/ - -int ejsSetGCDebugLevel(Ejs *ep, int debugLevel) -{ - int old; - - old = ep->gc.debugLevel; - ep->gc.debugLevel = debugLevel; - return old; -} - -/******************************************************************************/ - -int ejsSetGCMaxMemory(Ejs *ep, uint maxMemory) -{ - int old; - - old = ep->gc.maxMemory; - ep->gc.maxMemory = maxMemory; - - return old; -} - -/******************************************************************************/ - -bool ejsBlockInUseInt(EjsVar *vp) -{ - if (vp) { -#if BLD_DEBUG - if (vp->gc.magic != EJS_MAGIC) { - return 0; - } - if (vp->type == EJS_TYPE_OBJECT && vp->objectState && - vp->objectState->gc.magic != EJS_MAGIC) { - return 0; - } -#endif - return 1; - } - return 1; -} - -/******************************************************************************/ -#else -void ejsGarbageDummy() {} - -#endif /* BLD_FEATURE_EJS */ - -/******************************************************************************/ -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/ejsLex.c b/source4/lib/appweb/ejs-2.0/ejs/ejsLex.c deleted file mode 100644 index fbfee6e4d5..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/ejsLex.c +++ /dev/null @@ -1,1033 +0,0 @@ -/* - * @file ejsLex.c - * @brief EJS Lexical Analyser - * @overview EJS lexical analyser. This implementes a lexical analyser - * for a subset of the JavaScript language. - */ -/********************************* Copyright **********************************/ -/* - * @copy default.g - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Portions Copyright (c) GoAhead Software, 1995-2000. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if BLD_FEATURE_EJS - -/****************************** Forward Declarations **************************/ - -static int getLexicalToken(Ejs *ep, int state); -static int tokenAddChar(Ejs *ep, int c); -static int inputGetc(Ejs *ep); -static void inputPutback(Ejs *ep, int c); -static int charConvert(Ejs *ep, int base, int maxDig); -static void parseNumber(Ejs *ep, EjsType type); - -/************************************* Code ***********************************/ -/* - * Open a new input script - */ - -int ejsLexOpenScript(Ejs *ep, const char *script) -{ - EjsInput *ip; - - mprAssert(ep); - mprAssert(script); - - if ((ip = mprAllocTypeZeroed(ep, EjsInput)) == NULL) { - return MPR_ERR_MEMORY; - } - ip->next = ep->input; - ep->input = ip; - ip->procName = ep->proc ? ep->proc->procName : NULL; - ip->fileName = ep->fileName ? ep->fileName : NULL; - -/* - * Create the parse token buffer and script buffer - */ - ip->tokServp = ip->tokbuf; - ip->tokEndp = ip->tokbuf; - - ip->script = script; - ip->scriptSize = strlen(script); - ip->scriptServp = (char*) ip->script; - - ip->lineNumber = 1; - ip->lineColumn = 0; - - ip->putBackIndex = -1; - - return 0; -} - -/******************************************************************************/ -/* - * Close the input script - */ - -void ejsLexCloseScript(Ejs *ep) -{ - EjsInput *ip; - - mprAssert(ep); - - ip = ep->input; - mprAssert(ip); - ep->input = ip->next; - - mprFree(ip); -} - -/******************************************************************************/ -/* - * Initialize an input state structure - */ - -int ejsInitInputState(EjsInput *ip) -{ - mprAssert(ip); - - memset(ip, 0, sizeof(*ip)); - ip->putBackIndex = -1; - - return 0; -} -/******************************************************************************/ -/* - * Save the input state - */ - -void ejsLexSaveInputState(Ejs *ep, EjsInput *state) -{ - EjsInput *ip; - int i; - - mprAssert(ep); - - ip = ep->input; - mprAssert(ip); - - *state = *ip; - - for (i = 0; i <= ip->putBackIndex; i++) { - mprStrcpy(state->putBack[i].tokbuf, EJS_MAX_TOKEN, - ip->putBack[i].tokbuf); - state->putBack[i].tid = ip->putBack[i].tid; - } - - mprStrcpy(state->line, sizeof(state->line), ip->line); - - state->lineColumn = ip->lineColumn; - state->lineNumber = ip->lineNumber; -} - -/******************************************************************************/ -/* - * Restore the input state - */ - -void ejsLexRestoreInputState(Ejs *ep, EjsInput *state) -{ - EjsInput *ip; - EjsToken *tp; - int i; - - mprAssert(ep); - mprAssert(state); - - ip = ep->input; - mprAssert(ip); - - mprStrcpy(ip->tokbuf, sizeof(ip->tokbuf), state->tokbuf); - ip->tokServp = state->tokServp; - ip->tokEndp = state->tokEndp; - - ip->script = state->script; - ip->scriptServp = state->scriptServp; - ip->scriptSize = state->scriptSize; - - ip->putBackIndex = state->putBackIndex; - for (i = 0; i <= ip->putBackIndex; i++) { - tp = &ip->putBack[i]; - tp->tid = state->putBack[i].tid; - mprStrcpy(tp->tokbuf, sizeof(tp->tokbuf), state->putBack[i].tokbuf); - } - - mprStrcpy(ip->line, sizeof(ip->line), state->line); - - ip->lineColumn = state->lineColumn; - ip->lineNumber = state->lineNumber; -} - -/******************************************************************************/ -/* - * Free a saved input state - */ - -void ejsLexFreeInputState(Ejs *ep, EjsInput *state) -{ - mprAssert(ep); - mprAssert(state); - - state->putBackIndex = -1; - state->lineColumn = 0; -} - -/******************************************************************************/ -/* - * Get the next EJS token - */ - -int ejsLexGetToken(Ejs *ep, int state) -{ - mprAssert(ep); - - ep->tid = getLexicalToken(ep, state); - return ep->tid; -} - -/******************************************************************************/ - -/* - * Check for reserved words "if", "else", "var", "for", "delete", "function", - * "class", "extends", "public", "private", "protected", "try", "catch", - * "finally", "throw", "return", "get", "set", "this", "module", "each" - * - * The "new" and "in" reserved words are handled below. The "true", "false", - * "null" "typeof" and "undefined" reserved words are handled as global - * objects. - * - * Other reserved words not supported: - * "break", "case", "continue", "default", "do", - * "instanceof", "switch", "while", "with" - * - * ECMA extensions reserved words (not supported): - * "abstract", "boolean", "byte", "char", "const", - * "debugger", "double", "enum", "export", - * "final", "float", "goto", "implements", "import", "int", - * "interface", "long", "native", "package", - * "short", "static", "super", "synchronized", "transient", "volatile" - * - * FUTURE -- use a hash lookup - */ - -static int checkReservedWord(Ejs *ep, int state, int c, int tid) -{ - /* FUTURE -- probably should return for all tokens != EJS_TOK_ID */ - /* FUTURE -- Should have a hash for this. MUCH faster. */ - - if (!isalpha(ep->token[0]) || tid == EJS_TOK_LITERAL) { - return tid; - } - if (state == EJS_STATE_STMT) { - /* FUTURE OPT -- convert to hash lookup */ - if (strcmp(ep->token, "if") == 0) { - inputPutback(ep, c); - return EJS_TOK_IF; - } else if (strcmp(ep->token, "else") == 0) { - inputPutback(ep, c); - return EJS_TOK_ELSE; - } else if (strcmp(ep->token, "var") == 0) { - inputPutback(ep, c); - return EJS_TOK_VAR; - } else if (strcmp(ep->token, "new") == 0) { - inputPutback(ep, c); - return EJS_TOK_NEW; - } else if (strcmp(ep->token, "for") == 0) { - inputPutback(ep, c); - return EJS_TOK_FOR; - } else if (strcmp(ep->token, "delete") == 0) { - inputPutback(ep, c); - return EJS_TOK_DELETE; - } else if (strcmp(ep->token, "function") == 0) { - inputPutback(ep, c); - return EJS_TOK_FUNCTION; - } else if (strcmp(ep->token, "class") == 0) { - inputPutback(ep, c); - return EJS_TOK_CLASS; - } else if (strcmp(ep->token, "module") == 0) { - inputPutback(ep, c); - return EJS_TOK_MODULE; - } else if (strcmp(ep->token, "extends") == 0) { - inputPutback(ep, c); - return EJS_TOK_EXTENDS; - } else if (strcmp(ep->token, "try") == 0) { - inputPutback(ep, c); - return EJS_TOK_TRY; - } else if (strcmp(ep->token, "catch") == 0) { - inputPutback(ep, c); - return EJS_TOK_CATCH; - } else if (strcmp(ep->token, "finally") == 0) { - inputPutback(ep, c); - return EJS_TOK_FINALLY; - } else if (strcmp(ep->token, "throw") == 0) { - inputPutback(ep, c); - return EJS_TOK_THROW; - } else if (strcmp(ep->token, "public") == 0) { - inputPutback(ep, c); - return EJS_TOK_PUBLIC; - } else if (strcmp(ep->token, "protected") == 0) { - inputPutback(ep, c); - return EJS_TOK_PROTECTED; - } else if (strcmp(ep->token, "private") == 0) { - inputPutback(ep, c); - return EJS_TOK_PRIVATE; - } else if (strcmp(ep->token, "get") == 0) { - inputPutback(ep, c); - return EJS_TOK_GET; - } else if (strcmp(ep->token, "set") == 0) { - inputPutback(ep, c); - return EJS_TOK_SET; - } else if (strcmp(ep->token, "extends") == 0) { - inputPutback(ep, c); - return EJS_TOK_EXTENDS; - } else if (strcmp(ep->token, "try") == 0) { - inputPutback(ep, c); - return EJS_TOK_TRY; - } else if (strcmp(ep->token, "catch") == 0) { - inputPutback(ep, c); - return EJS_TOK_CATCH; - } else if (strcmp(ep->token, "finally") == 0) { - inputPutback(ep, c); - return EJS_TOK_FINALLY; - } else if (strcmp(ep->token, "throw") == 0) { - inputPutback(ep, c); - return EJS_TOK_THROW; - } else if (strcmp(ep->token, "public") == 0) { - inputPutback(ep, c); - return EJS_TOK_PUBLIC; - } else if (strcmp(ep->token, "protected") == 0) { - inputPutback(ep, c); - return EJS_TOK_PROTECTED; - } else if (strcmp(ep->token, "private") == 0) { - inputPutback(ep, c); - return EJS_TOK_PRIVATE; - } else if (strcmp(ep->token, "get") == 0) { - inputPutback(ep, c); - return EJS_TOK_GET; - } else if (strcmp(ep->token, "set") == 0) { - inputPutback(ep, c); - return EJS_TOK_SET; - } else if (strcmp(ep->token, "each") == 0) { - inputPutback(ep, c); - return EJS_TOK_EACH; - } else if (strcmp(ep->token, "return") == 0) { - if ((c == ';') || (c == '(')) { - inputPutback(ep, c); - } - return EJS_TOK_RETURN; - } - - } else if (state == EJS_STATE_EXPR) { - if (strcmp(ep->token, "new") == 0) { - inputPutback(ep, c); - return EJS_TOK_NEW; - } else if (strcmp(ep->token, "in") == 0) { - inputPutback(ep, c); - return EJS_TOK_IN; - } else if (strcmp(ep->token, "function") == 0) { - inputPutback(ep, c); - return EJS_TOK_FUNCTION; - } - - } else if (state == EJS_STATE_DEC) { - if (strcmp(ep->token, "extends") == 0) { - inputPutback(ep, c); - return EJS_TOK_EXTENDS; - } - } - return tid; -} - -/******************************************************************************/ -/* - * Get the next EJS token - */ - -static int getLexicalToken(Ejs *ep, int state) -{ - EjsType type; - EjsInput *ip; - int done, tid, c, quote, style, idx, isHex; - - mprAssert(ep); - ip = ep->input; - mprAssert(ip); - - ep->tid = -1; - tid = -1; - type = BLD_FEATURE_NUM_TYPE_ID; - isHex = 0; - - /* - * Use a putback tokens first. Don't free strings as caller needs access. - */ - if (ip->putBackIndex >= 0) { - idx = ip->putBackIndex; - tid = ip->putBack[idx].tid; - ep->token = (char*) ip->putBack[idx].tokbuf; - tid = checkReservedWord(ep, state, 0, tid); - ip->putBackIndex--; - return tid; - } - ep->token = ip->tokServp = ip->tokEndp = ip->tokbuf; - *ip->tokServp = '\0'; - - if ((c = inputGetc(ep)) < 0) { - return EJS_TOK_EOF; - } - - /* - * Main lexical analyser - */ - for (done = 0; !done; ) { - switch (c) { - case -1: - return EJS_TOK_EOF; - - case ' ': - case '\t': - case '\r': - do { - if ((c = inputGetc(ep)) < 0) - break; - } while (c == ' ' || c == '\t' || c == '\r'); - break; - - case '\n': - return EJS_TOK_NEWLINE; - - case '(': - tokenAddChar(ep, c); - return EJS_TOK_LPAREN; - - case ')': - tokenAddChar(ep, c); - return EJS_TOK_RPAREN; - - case '[': - tokenAddChar(ep, c); - return EJS_TOK_LBRACKET; - - case ']': - tokenAddChar(ep, c); - return EJS_TOK_RBRACKET; - - case '.': - tokenAddChar(ep, c); - return EJS_TOK_PERIOD; - - case '{': - tokenAddChar(ep, c); - return EJS_TOK_LBRACE; - - case '}': - tokenAddChar(ep, c); - return EJS_TOK_RBRACE; - - case '+': - if ((c = inputGetc(ep)) < 0) { - ejsSyntaxError(ep, 0); - return EJS_TOK_ERR; - } - if (c != '+' ) { - inputPutback(ep, c); - tokenAddChar(ep, EJS_EXPR_PLUS); - return EJS_TOK_EXPR; - } - tokenAddChar(ep, EJS_EXPR_INC); - return EJS_TOK_INC_DEC; - - case '-': - if ((c = inputGetc(ep)) < 0) { - ejsSyntaxError(ep, 0); - return EJS_TOK_ERR; - } - if (c != '-' ) { - inputPutback(ep, c); - tokenAddChar(ep, EJS_EXPR_MINUS); - return EJS_TOK_EXPR; - } - tokenAddChar(ep, EJS_EXPR_DEC); - return EJS_TOK_INC_DEC; - - case '*': - tokenAddChar(ep, EJS_EXPR_MUL); - return EJS_TOK_EXPR; - - case '%': - tokenAddChar(ep, EJS_EXPR_MOD); - return EJS_TOK_EXPR; - - case '/': - /* - * Handle the division operator and comments - */ - if ((c = inputGetc(ep)) < 0) { - ejsSyntaxError(ep, 0); - return EJS_TOK_ERR; - } - if (c != '*' && c != '/') { - inputPutback(ep, c); - tokenAddChar(ep, EJS_EXPR_DIV); - return EJS_TOK_EXPR; - } - style = c; - /* - * Eat comments. Both C and C++ comment styles are supported. - */ - while (1) { - if ((c = inputGetc(ep)) < 0) { - if (style == '/') { - return EJS_TOK_EOF; - } - ejsSyntaxError(ep, 0); - return EJS_TOK_ERR; - } - if (c == '\n' && style == '/') { - break; - } else if (c == '*') { - c = inputGetc(ep); - if (style == '/') { - if (c == '\n') { - break; - } - } else { - if (c == '/') { - break; - } - } - } - } - /* - * Continue looking for a token, so get the next character - */ - if ((c = inputGetc(ep)) < 0) { - return EJS_TOK_EOF; - } - break; - - case '<': /* < and <= */ - if ((c = inputGetc(ep)) < 0) { - ejsSyntaxError(ep, 0); - return EJS_TOK_ERR; - } - if (c == '<') { - tokenAddChar(ep, EJS_EXPR_LSHIFT); - return EJS_TOK_EXPR; - } else if (c == '=') { - tokenAddChar(ep, EJS_EXPR_LESSEQ); - return EJS_TOK_EXPR; - } - tokenAddChar(ep, EJS_EXPR_LESS); - inputPutback(ep, c); - return EJS_TOK_EXPR; - - case '>': /* > and >= */ - if ((c = inputGetc(ep)) < 0) { - ejsSyntaxError(ep, 0); - return EJS_TOK_ERR; - } - if (c == '>') { - tokenAddChar(ep, EJS_EXPR_RSHIFT); - return EJS_TOK_EXPR; - } else if (c == '=') { - tokenAddChar(ep, EJS_EXPR_GREATEREQ); - return EJS_TOK_EXPR; - } - tokenAddChar(ep, EJS_EXPR_GREATER); - inputPutback(ep, c); - return EJS_TOK_EXPR; - - case '=': /* "==" */ - if ((c = inputGetc(ep)) < 0) { - ejsSyntaxError(ep, 0); - return EJS_TOK_ERR; - } - if (c == '=') { - tokenAddChar(ep, EJS_EXPR_EQ); - return EJS_TOK_EXPR; - } - inputPutback(ep, c); - return EJS_TOK_ASSIGNMENT; - - case '!': /* "!=" or "!"*/ - if ((c = inputGetc(ep)) < 0) { - ejsSyntaxError(ep, 0); - return EJS_TOK_ERR; - } - if (c == '=') { - tokenAddChar(ep, EJS_EXPR_NOTEQ); - return EJS_TOK_EXPR; - } - inputPutback(ep, c); - tokenAddChar(ep, EJS_EXPR_BOOL_COMP); - return EJS_TOK_EXPR; - - case ';': - tokenAddChar(ep, c); - return EJS_TOK_SEMI; - - case ',': - tokenAddChar(ep, c); - return EJS_TOK_COMMA; - - case ':': - tokenAddChar(ep, c); - return EJS_TOK_COLON; - - case '|': /* "||" */ - if ((c = inputGetc(ep)) < 0 || c != '|') { - ejsSyntaxError(ep, 0); - return EJS_TOK_ERR; - } - tokenAddChar(ep, EJS_COND_OR); - return EJS_TOK_LOGICAL; - - case '&': /* "&&" */ - if ((c = inputGetc(ep)) < 0 || c != '&') { - ejsSyntaxError(ep, 0); - return EJS_TOK_ERR; - } - tokenAddChar(ep, EJS_COND_AND); - return EJS_TOK_LOGICAL; - - case '\"': /* String quote */ - case '\'': - quote = c; - if ((c = inputGetc(ep)) < 0) { - ejsSyntaxError(ep, 0); - return EJS_TOK_ERR; - } - - while (c != quote) { - /* - * Check for escape sequence characters - */ - if (c == '\\') { - c = inputGetc(ep); - - if (isdigit(c)) { - /* - * Octal support, \101 maps to 65 = 'A'. Put first - * char back so converter will work properly. - */ - inputPutback(ep, c); - c = charConvert(ep, 8, 3); - - } else { - switch (c) { - case 'n': - c = '\n'; break; - case 'b': - c = '\b'; break; - case 'f': - c = '\f'; break; - case 'r': - c = '\r'; break; - case 't': - c = '\t'; break; - case 'x': - /* - * Hex support, \x41 maps to 65 = 'A' - */ - c = charConvert(ep, 16, 2); - break; - case 'u': - /* - * Unicode support, \x0401 maps to 65 = 'A' - */ - c = charConvert(ep, 16, 2); - c = c*16 + charConvert(ep, 16, 2); - - break; - case '\'': - case '\"': - case '\\': - break; - default: - if (tokenAddChar(ep, '\\') < 0) { - return EJS_TOK_ERR; - } - } - } - if (tokenAddChar(ep, c) < 0) { - return EJS_TOK_ERR; - } - } else { - if (tokenAddChar(ep, c) < 0) { - return EJS_TOK_ERR; - } - } - if ((c = inputGetc(ep)) < 0) { - ejsSyntaxError(ep, "Unmatched Quote"); - return EJS_TOK_ERR; - } - } - return EJS_TOK_LITERAL; - - case '0': - if (tokenAddChar(ep, c) < 0) { - return EJS_TOK_ERR; - } - if ((c = inputGetc(ep)) < 0) { - break; - } - if (tolower(c) == 'x') { - if (tokenAddChar(ep, c) < 0) { - return EJS_TOK_ERR; - } - if ((c = inputGetc(ep)) < 0) { - break; - } - isHex = 1; - if (! isxdigit(c)) { - parseNumber(ep, type); - inputPutback(ep, c); - return EJS_TOK_NUMBER; - } - } else if (! isdigit(c)) { -#if BLD_FEATURE_FLOATING_POINT - if (c == '.' || tolower(c) == 'e' || c == '+' || c == '-') { - /* Fall through */ - type = EJS_TYPE_FLOAT; - } else -#endif - { - parseNumber(ep, type); - inputPutback(ep, c); - return EJS_TOK_NUMBER; - } - } - /* Fall through to get more digits */ - - case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - if (isHex) { - do { - if (tokenAddChar(ep, c) < 0) { - return EJS_TOK_ERR; - } - if ((c = inputGetc(ep)) < 0) { - break; - } - } while (isxdigit(c)); - - } else { -#if BLD_FEATURE_FLOATING_POINT - do { - if (tokenAddChar(ep, c) < 0) { - return EJS_TOK_ERR; - } - if ((c = inputGetc(ep)) < 0) { - break; - } - c = tolower(c); - if (c == '.' || c == 'e' || c == 'f') { - type = EJS_TYPE_FLOAT; - } - } while (isdigit(c) || c == '.' || c == 'e' || - c == 'f' || - ((type == EJS_TYPE_FLOAT) && (c == '+' || c == '-'))); -#else - do { - if (tokenAddChar(ep, c) < 0) { - return EJS_TOK_ERR; - } - if ((c = inputGetc(ep)) < 0) { - break; - } - } while (isdigit(c)); -#endif - } - - parseNumber(ep, type); - inputPutback(ep, c); - return EJS_TOK_NUMBER; - - default: - /* - * Identifiers or a function names - */ - while (1) { - if (c == '\\') { - if ((c = inputGetc(ep)) < 0) { - break; - } - if (c == '\n' || c == '\r') { - break; - } - } else if (tokenAddChar(ep, c) < 0) { - break; - } - if ((c = inputGetc(ep)) < 0) { - break; - } - if (!isalnum(c) && c != '$' && c != '_' && - c != '\\' && c != '@') { - break; - } - } - if (*ep->token == '\0') { - c = inputGetc(ep); - break; - } - - if (! isalpha((int) *ep->token) && *ep->token != '$' && - *ep->token != '_' && *ep->token != '@') { - ejsError(ep, EJS_SYNTAX_ERROR, "Invalid identifier %s", - ep->token); - return EJS_TOK_ERR; - } - - tid = checkReservedWord(ep, state, c, EJS_TOK_ID); - if (tid != EJS_TOK_ID) { - return tid; - } - - /* - * Skip white space after token to find out whether this is - * a function or not. - */ - while (c == ' ' || c == '\t' || c == '\r' || c == '\n') { - if ((c = inputGetc(ep)) < 0) - break; - } - - tid = EJS_TOK_ID; - if ((strlen(ep->token) + 1) >= EJS_MAX_ID) { - ejsError(ep, EJS_SYNTAX_ERROR, - "Identifier too big. Max is %d letters.", EJS_MAX_ID); - return EJS_TOK_ERR; - } - done++; - } - } - - /* - * Putback the last extra character for next time - */ - inputPutback(ep, c); - return tid; -} - -/******************************************************************************/ - -static void parseNumber(Ejs *ep, EjsType type) -{ - switch (type) { - case EJS_TYPE_INT: - ep->tokenNumber.integer = ejsParseInteger(ep->token); - ep->tokenNumber.type = type; - break; - -#if BLD_FEATURE_FLOATING_POINT - case EJS_TYPE_FLOAT: - ep->tokenNumber.floating = atof(ep->token); - ep->tokenNumber.type = type; - break; -#endif - -#if BLD_FEATURE_INT64 - case EJS_TYPE_INT64: - ep->tokenNumber.integer64 = ejsParseInteger64(ep->token); - ep->tokenNumber.type = type; - break; -#endif - } -} - -/******************************************************************************/ -/* - * Convert a hex or octal character back to binary, return original char if - * not a hex digit - */ - -static int charConvert(Ejs *ep, int base, int maxDig) -{ - int i, c, lval, convChar; - - lval = 0; - for (i = 0; i < maxDig; i++) { - if ((c = inputGetc(ep)) < 0) { - break; - } - /* - * Initialize to out of range value - */ - convChar = base; - if (isdigit(c)) { - convChar = c - '0'; - } else if (c >= 'a' && c <= 'f') { - convChar = c - 'a' + 10; - } else if (c >= 'A' && c <= 'F') { - convChar = c - 'A' + 10; - } - /* - * If unexpected character then return it to buffer. - */ - if (convChar >= base) { - inputPutback(ep, c); - break; - } - lval = (lval * base) + convChar; - } - return lval; -} - -/******************************************************************************/ -/* - * Putback the last token read. Accept at most one push back token. - */ - -void ejsLexPutbackToken(Ejs *ep, int tid, char *string) -{ - EjsInput *ip; - EjsToken *tp; - int idx; - - mprAssert(ep); - ip = ep->input; - mprAssert(ip); - - ip->putBackIndex += 1; - - mprAssert(ip->putBackIndex < EJS_TOKEN_STACK); - idx = ip->putBackIndex; - - tp = &ip->putBack[idx]; - tp->tid = tid; - - mprStrcpy(tp->tokbuf, sizeof(tp->tokbuf), string); -} - -/******************************************************************************/ -/* - * Add a character to the token buffer - */ - -static int tokenAddChar(Ejs *ep, int c) -{ - EjsInput *ip; - - mprAssert(ep); - ip = ep->input; - mprAssert(ip); - - if (ip->tokEndp >= &ip->tokbuf[sizeof(ip->tokbuf) - 1]) { - ejsSyntaxError(ep, "Token too big"); - return -1; - } - *ip->tokEndp++ = c; - *ip->tokEndp = '\0'; - - return 0; -} - -/******************************************************************************/ -/* - * Get another input character - */ - -static int inputGetc(Ejs *ep) -{ - EjsInput *ip; - int c; - - mprAssert(ep); - ip = ep->input; - - if (ip->scriptSize <= 0) { - return -1; - } - - c = (uchar) (*ip->scriptServp++); - ip->scriptSize--; - - /* - * For debugging, accumulate the line number and the currenly parsed line - */ - if (c == '\n') { -#if 0 && BLD_DEBUG - if (ip->lineColumn > 0) { - printf("PARSED: %s\n", ip->line); - } -#endif - ip->lineNumber++; - ip->lineColumn = 0; - } else if ((ip->lineColumn + 2) < sizeof(ip->line)) { - ip->line[ip->lineColumn++] = c; - ip->line[ip->lineColumn] = '\0'; - } - return c; -} - -/******************************************************************************/ -/* - * Putback a character onto the input queue - */ - -static void inputPutback(Ejs *ep, int c) -{ - EjsInput *ip; - - mprAssert(ep); - - if (c > 0) { - ip = ep->input; - *--ip->scriptServp = c; - ip->scriptSize++; - if (--(ip->lineColumn) < 0) { - ip->lineColumn = 0; - } - mprAssert(ip->line); - mprAssert(ip->lineColumn >= 0); - mprAssert(ip->lineColumn < sizeof(ip->line)); - ip->line[ip->lineColumn] = '\0'; - } -} - -/******************************************************************************/ - -#else -void ejsLexDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/ejsParser.c b/source4/lib/appweb/ejs-2.0/ejs/ejsParser.c deleted file mode 100644 index 9fce6d27ee..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/ejsParser.c +++ /dev/null @@ -1,4514 +0,0 @@ -/* - * @file ejsParser.c - * @brief EJS Parser and Execution - */ -/********************************* Copyright **********************************/ -/* - * @copy default.g - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Portions Copyright (c) GoAhead Software, 1995-2000. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if BLD_FEATURE_EJS - -/****************************** Forward Declarations **************************/ - -static int createClass(Ejs *ep, EjsVar *parentClass, - const char *className, EjsVar *baseClass); -static int createProperty(Ejs *ep, EjsVar **obj, const char *id, - int state); -static int evalCond(Ejs *ep, EjsVar *lhs, int rel, EjsVar *rhs); -static int evalExpr(Ejs *ep, EjsVar *lhs, int rel, EjsVar *rhs); -#if BLD_FEATURE_FLOATING_POINT -static int evalFloatExpr(Ejs *ep, double l, int rel, double r); -#endif -static int evalBoolExpr(Ejs *ep, int l, int rel, int r); -static int evalNumericExpr(Ejs *ep, EjsNum l, int rel, EjsNum r); -static int evalObjExpr(Ejs *ep, EjsVar *lhs, int rel, EjsVar *rhs) ; -static int evalStringExpr(Ejs *ep, EjsVar *lhs, int rel, EjsVar *rhs); -static int evalMethod(Ejs *ep, EjsVar *obj, EjsProc *proc, int flags); -static EjsProperty *findProperty(Ejs *ep, EjsVar *op, const char *property, - int flags); -static EjsVar *pickSpace(Ejs *ep, int state, const char *property, int flags); -static void freeProc(Ejs *ep, EjsProc *proc); -static int parseArgs(Ejs *ep, int state, int flags); -static int parseArrayLiteral(Ejs *ep, int state, int flags, char *id); -static int parseAssignment(Ejs *ep, int state, int flags, char *id); -static int parseClass(Ejs *ep, int state, int flags); -static int parseForInner(Ejs *ep, int state, int flags, - EjsInput *condScript, EjsInput *incrScript, - EjsInput *bodyScript, EjsInput *endScript); -static int parseCond(Ejs *ep, int state, int flags); -static int parseDeclaration(Ejs *ep, int state, int flags); -static int parseExpr(Ejs *ep, int state, int flags); -static int parseFor(Ejs *ep, int state, int flags); -static int parseRegFor(Ejs *ep, int state, int flags); -static int parseForIn(Ejs *ep, int state, int flags, int each); -static int parseId(Ejs *ep, int state, int flags, char **id, int *done); -static int parseInc(Ejs *ep, int state, int flags); -static int parseIf(Ejs *ep, int state, int flags, int *done); -static int parseFunction(Ejs *ep, int state, int flags); -static int parseMethod(Ejs *ep, int state, int flags, char *id); -static int parseObjectLiteral(Ejs *ep, int state, int flags, char *id); -static int parseStmt(Ejs *ep, int state, int flags); -static int parseThrow(Ejs *ep, int state, int flags); -static int parseTry(Ejs *ep, int state, int flags); -static void removeNewlines(Ejs *ep, int state); -static EjsProperty *searchSpacesForProperty(Ejs *ep, int state, EjsVar *obj, - char *property, int flags); -static int assignPropertyValue(Ejs *ep, char *id, int state, EjsVar *value, - int flags); -static int updateProperty(Ejs *ep, EjsVar *obj, const char *id, int state, - EjsVar *value); -static void updateResult(Ejs *ep, int state, int flags, EjsVar *vp); -static int getNextNonSpaceToken(Ejs *ep, int state); - -static int callConstructor(Ejs *ep, EjsVar *thisObj, EjsVar *baseClass, - MprArray *args); -static int callCMethod(Ejs *ep, EjsVar *obj, EjsProc *proc, - EjsVar *prototype); -static int callStringCMethod(Ejs *ep, EjsVar *obj, EjsProc *proc, - EjsVar *prototype); -static int callMethod(Ejs *ep, EjsVar *obj, EjsProc *proc, - EjsVar *prototype); -static int runMethod(Ejs *ep, EjsVar *thisObj, EjsVar *method, - const char *methodName, MprArray *args); - -static EjsInput *getInputStruct(Ejs *ep); -static void freeInputStruct(Ejs *ep, EjsInput *input); - -static void *pushFrame(Ejs *ep, int size); -static void *popFrame(Ejs *ep, int size); - -/************************************* Code ***********************************/ -/* - * Recursive descent parser for EJS - */ - -int ejsParse(Ejs *ep, int state, int flags) -{ - mprAssert(ep); - -#if MOB - if (mprStackCheck(ep)) { - char *stack; - stack = ejsFormatStack(ep); - mprLog(ep, 0, "\nStack grew : MAX %d\n", mprStackSize(ep)); - mprLog(ep, 0, "Stack\n %s\n", stack); - mprFree(stack); - } -#endif - - if (ep->flags & EJS_FLAGS_EXIT) { - return EJS_STATE_RET; - } - - ep->inputMarker = ep->input->scriptServp; - - switch (state) { - /* - * Any statement, method arguments or conditional expressions - */ - case EJS_STATE_STMT: - state = parseStmt(ep, state, flags); - if (state != EJS_STATE_STMT_BLOCK_DONE && state != EJS_STATE_STMT_DONE){ - goto err; - } - break; - - case EJS_STATE_DEC: - state = parseStmt(ep, state, flags); - if (state != EJS_STATE_DEC_DONE) { - goto err; - } - break; - - case EJS_STATE_EXPR: - state = parseStmt(ep, state, flags); - if (state != EJS_STATE_EXPR_DONE) { - goto err; - } - break; - - /* - * Variable declaration list - */ - case EJS_STATE_DEC_LIST: - state = parseDeclaration(ep, state, flags); - if (state != EJS_STATE_DEC_LIST_DONE) { - goto err; - } - break; - - /* - * Method argument string - */ - case EJS_STATE_ARG_LIST: - state = parseArgs(ep, state, flags); - if (state != EJS_STATE_ARG_LIST_DONE) { - goto err; - } - break; - - /* - * Logical condition list (relational operations separated by &&, ||) - */ - case EJS_STATE_COND: - state = parseCond(ep, state, flags); - if (state != EJS_STATE_COND_DONE) { - goto err; - } - break; - - /* - * Expression list - */ - case EJS_STATE_RELEXP: - state = parseExpr(ep, state, flags); - if (state != EJS_STATE_RELEXP_DONE) { - goto err; - } - break; - } - - /* - * Recursion protection - */ - if (ep->input->scriptServp == ep->inputMarker) { - if (ep->recurseCount++ > 20) { - ejsSyntaxError(ep, "Input syntax error"); - state = EJS_STATE_ERR; - } - } else { - ep->recurseCount = 0; - } - - if (state == EJS_STATE_RET || state == EJS_STATE_EOF) { - return state; - } - -done: - return state; - -err: - if (state == EJS_STATE_RET || state == EJS_STATE_EOF) { - goto done; - } - if (state != EJS_STATE_ERR) { - ejsSyntaxError(ep, 0); - } - state = EJS_STATE_ERR; - goto done; -} - -/******************************************************************************/ -/* - * Local vars - */ - -typedef struct ParseStmt { - EjsProc *saveProc; - EjsProperty *pp; - EjsVar *saveObj, *exception; - char *str, *id; - int done, tid, rs, saveObjPerm, expectEndOfStmt; -} ParseStmt; - -/* - * Parse expression (leftHandSide operator rightHandSide) - */ - - -static int parseStmt(Ejs *ep, int state, int flags) -{ - ParseStmt *sp; - - mprAssert(ep); - - if ((sp = pushFrame(ep, sizeof(ParseStmt))) == 0) { - return EJS_STATE_ERR; - } - - sp->id = 0; - sp->expectEndOfStmt = 0; - sp->saveProc = NULL; - - ep->currentObj = 0; - ep->currentProperty = 0; - - for (sp->done = 0; !sp->done && state != EJS_STATE_ERR; ) { - sp->tid = ejsLexGetToken(ep, state); - -#if (WIN || BREW_SIMULATOR) && BLD_DEBUG && DISABLED - /* MOB -- make cross platform */ - _CrtCheckMemory(); -#endif - - switch (sp->tid) { - default: - ejsLexPutbackToken(ep, sp->tid, ep->token); - goto done; - - case EJS_TOK_EXPR: - if (state == EJS_STATE_EXPR) { - ejsLexPutbackToken(ep, EJS_TOK_EXPR, ep->token); - } - goto done; - - case EJS_TOK_LOGICAL: - ejsLexPutbackToken(ep, sp->tid, ep->token); - goto done; - - case EJS_TOK_ERR: - if (state != EJS_STATE_ERR && !ep->gotException) { - ejsSyntaxError(ep, 0); - } - state = EJS_STATE_ERR; - goto done; - - case EJS_TOK_EOF: - state = EJS_STATE_EOF; - goto done; - - case EJS_TOK_NEWLINE: - break; - - case EJS_TOK_SEMI: - /* - * This case is when we discover no statement and just a lone ';' - */ - if (state != EJS_STATE_STMT) { - ejsLexPutbackToken(ep, sp->tid, ep->token); - } - goto done; - - case EJS_TOK_LBRACKET: - if (flags & EJS_FLAGS_EXE) { - ep->currentObj = &ep->currentProperty->var; - if (ep->currentObj != 0 && ep->currentObj->type != - EJS_TYPE_OBJECT) { - ejsError(ep, EJS_REFERENCE_ERROR, - "Property reference to a non-object type \"%s\"\n", - sp->id); - goto err; - } - } - - sp->saveObj = ep->currentObj; - sp->saveObjPerm = ejsMakeObjPermanent(sp->saveObj, 1); - - sp->rs = ejsParse(ep, EJS_STATE_RELEXP, flags); - - ejsMakeObjPermanent(sp->saveObj, sp->saveObjPerm); - ep->currentObj = sp->saveObj; - - if (sp->rs < 0) { - state = sp->rs; - goto done; - } - - mprFree(sp->id); - /* MOB rc */ - sp->str = ejsVarToString(ep, ep->result); - sp->id = mprStrdup(ep, sp->str); - - if (sp->id[0] == '\0') { - if (flags & EJS_FLAGS_EXE) { - ejsError(ep, EJS_RANGE_ERROR, - "[] expression evaluates to the empty string\n"); - goto err; - } - } else { - sp->pp = searchSpacesForProperty(ep, state, ep->currentObj, - sp->id, flags); - ep->currentProperty = sp->pp; - updateResult(ep, state, flags, ejsGetVarPtr(sp->pp)); - } - - if ((sp->tid = ejsLexGetToken(ep, state)) != EJS_TOK_RBRACKET) { - ejsSyntaxError(ep, "Missing ']'"); - goto err; - } - break; - - case EJS_TOK_PERIOD: - if (flags & EJS_FLAGS_EXE) { - if (ep->currentProperty == 0) { - ejsError(ep, EJS_REFERENCE_ERROR, - "Undefined object \"%s\"", sp->id); - goto err; - } - } - ep->currentObj = &ep->currentProperty->var; - if (flags & EJS_FLAGS_EXE) { - if (ep->currentObj != 0 && ep->currentObj->type != - EJS_TYPE_OBJECT) { - ejsError(ep, EJS_REFERENCE_ERROR, - "Property reference to a non-object type \"%s\"\n", - sp->id); - goto err; - } - } - if ((sp->tid = ejsLexGetToken(ep, state)) != EJS_TOK_ID) { - ejsError(ep, EJS_REFERENCE_ERROR, "Bad property after '.': %s", - ep->token); - goto err; - } - /* Fall through */ - - case EJS_TOK_ID: - state = parseId(ep, state, flags, &sp->id, &sp->done); - if (sp->done && state == EJS_STATE_STMT) { - sp->expectEndOfStmt = 1; - } - break; - - case EJS_TOK_ASSIGNMENT: - sp->tid = ejsLexGetToken(ep, state); - if (sp->tid == EJS_TOK_LBRACE) { - /* - * var = { name: value, name: value, ... } - */ - if (parseObjectLiteral(ep, state, flags, sp->id) < 0) { - ejsSyntaxError(ep, "Bad object literal"); - goto err; - } - - } else if (sp->tid == EJS_TOK_LBRACKET) { - /* - * var = [ array elements ] - */ - if (parseArrayLiteral(ep, state, flags, sp->id) < 0) { - ejsSyntaxError(ep, "Bad array literal"); - goto err; - } - - } else if (sp->tid == EJS_TOK_EXPR && - (int) *ep->token == EJS_EXPR_LESS) { - /* - * var = .../ - */ - ejsSyntaxError(ep, "XML literals are not yet supported"); - goto err; - - } else { - /* - * var = expression - */ - ejsLexPutbackToken(ep, sp->tid, ep->token); - state = parseAssignment(ep, state, flags, sp->id); - if (state == EJS_STATE_ERR) { - if (ep->flags & EJS_FLAGS_EXIT) { - state = EJS_STATE_RET; - goto done; - } - if (!ep->gotException) { - ejsSyntaxError(ep, 0); - } - goto err; - } - } - - if (flags & EJS_FLAGS_EXE) { - if (assignPropertyValue(ep, sp->id, state, ep->result, - flags) < 0) { - if (ep->gotException == 0) { - ejsError(ep, EJS_EVAL_ERROR, "Can't set property %s", - sp->id); - } - goto err; - } - } - - if (state == EJS_STATE_STMT) { - sp->expectEndOfStmt = 1; - goto done; - } - break; - - case EJS_TOK_INC_DEC: - state = parseInc(ep, state, flags); - if (state == EJS_STATE_STMT) { - sp->expectEndOfStmt = 1; - } - break; - - case EJS_TOK_NEW: - /* MOB -- could we remove rs and just use state */ - sp->rs = ejsParse(ep, EJS_STATE_EXPR, flags | EJS_FLAGS_NEW); - if (sp->rs < 0) { - state = sp->rs; - goto done; - } - break; - - case EJS_TOK_DELETE: - sp->rs = ejsParse(ep, EJS_STATE_EXPR, flags | EJS_FLAGS_DELETE); - if (sp->rs < 0) { - state = sp->rs; - goto done; - } - if (flags & EJS_FLAGS_EXE) { - /* Single place where properties are deleted */ - if (ep->currentObj == 0 || ep->currentProperty == 0) { - ejsError(ep, EJS_EVAL_ERROR, - "Can't find property to delete"); - goto err; - } - if (ep->currentObj->isArray) { - ejsSetArrayLength(ep, ep->currentObj, 0, - ep->currentProperty->name, 0); - } - ejsDeleteProperty(ep, ep->currentObj, - ep->currentProperty->name); - ep->currentProperty = 0; - } - goto done; - - case EJS_TOK_FUNCTION: - /* - * Parse a function declaration - */ - state = parseFunction(ep, state, flags); - goto done; - - case EJS_TOK_THROW: - state = parseThrow(ep, state, flags); - goto done; - - case EJS_TOK_TRY: - state = parseTry(ep, state, flags); - goto done; - - case EJS_TOK_CLASS: - case EJS_TOK_MODULE: - state = parseClass(ep, state, flags); - goto done; - - case EJS_TOK_LITERAL: - /* - * Set the result to the string literal - */ - if (flags & EJS_FLAGS_EXE) { - ejsWriteVarAsString(ep, ep->result, ep->token); - ejsSetVarName(ep, ep->result, ""); - } - if (state == EJS_STATE_STMT) { - sp->expectEndOfStmt = 1; - } - goto done; - - case EJS_TOK_NUMBER: - /* - * Set the result to the parsed number - */ - if (flags & EJS_FLAGS_EXE) { - ejsWriteVar(ep, ep->result, &ep->tokenNumber, 0); - } - if (state == EJS_STATE_STMT) { - sp->expectEndOfStmt = 1; - } - goto done; - - case EJS_TOK_METHOD_NAME: - /* - * parse a method() invocation - */ - mprAssert(ep->currentObj); - state = parseMethod(ep, state, flags, sp->id); - if (state == EJS_STATE_STMT) { - sp->expectEndOfStmt = 1; - } - if (ep->flags & EJS_FLAGS_EXIT) { - state = EJS_STATE_RET; - } - goto done; - - case EJS_TOK_IF: - state = parseIf(ep, state, flags, &sp->done); - if (state < 0) { - goto done; - } - break; - - case EJS_TOK_FOR: - state = parseFor(ep, state, flags); - goto done; - - case EJS_TOK_VAR: - if ((sp->rs = ejsParse(ep, EJS_STATE_DEC_LIST, flags)) < 0) { - state = sp->rs; - goto done; - } - goto done; - - case EJS_TOK_COMMA: - ejsLexPutbackToken(ep, sp->tid, ep->token); - goto done; - - case EJS_TOK_LPAREN: - if (state == EJS_STATE_EXPR) { - if ((sp->rs = ejsParse(ep, EJS_STATE_RELEXP, flags)) < 0) { - state = sp->rs; - goto done; - } - if (ejsLexGetToken(ep, state) != EJS_TOK_RPAREN) { - ejsSyntaxError(ep, 0); - goto err; - } - goto done; - - } else if (state == EJS_STATE_STMT) { - ejsLexPutbackToken(ep, EJS_TOK_METHOD_NAME, ep->token); - } - break; - - case EJS_TOK_RPAREN: - ejsLexPutbackToken(ep, sp->tid, ep->token); - goto done; - - case EJS_TOK_EXTENDS: - if (! (flags & EJS_FLAGS_CLASS_DEC)) { - ejsSyntaxError(ep, 0); - goto err; - } - sp->saveObj = ep->currentObj; - sp->saveObjPerm = ejsMakeObjPermanent(sp->saveObj, 1); - - sp->rs = ejsParse(ep, EJS_STATE_STMT, flags); - ejsMakeObjPermanent(sp->saveObj, sp->saveObjPerm); - - if (sp->rs < 0) { - state = sp->rs; - goto done; - } - - if (flags & EJS_FLAGS_EXE) { - if (createClass(ep, sp->saveObj, sp->id, - ejsGetVarPtr(ep->currentProperty)) < 0) { - goto err; - } - } - if (ejsLexGetToken(ep, state) != EJS_TOK_LBRACE) { - ejsSyntaxError(ep, 0); - goto err; - } - ejsLexPutbackToken(ep, ep->tid, ep->token); - goto done; - - case EJS_TOK_LBRACE: - if (flags & EJS_FLAGS_CLASS_DEC) { - if (state == EJS_STATE_DEC) { - if (flags & EJS_FLAGS_EXE) { - if (createClass(ep, ep->currentObj, sp->id, 0) < 0) { - goto err; - } - } - ejsLexPutbackToken(ep, sp->tid, ep->token); - - } else if (state == EJS_STATE_STMT) { - ejsLexPutbackToken(ep, sp->tid, ep->token); - } - goto done; - } - - /* - * This handles any code in braces except "if () {} else {}" - */ - if (state != EJS_STATE_STMT) { - ejsSyntaxError(ep, 0); - goto err; - } - - /* - * Parse will return EJS_STATE_STMT_BLOCK_DONE when the RBRACE - * is seen. - */ - sp->exception = 0; - do { - state = ejsParse(ep, EJS_STATE_STMT, flags); - if (state == EJS_STATE_ERR) { - /* - * We need to keep parsing to get to the end of the block - */ - if (sp->exception == 0) { - sp->exception = ejsDupVar(ep, ep->result, - EJS_SHALLOW_COPY); - if (sp->exception == 0) { - ejsMemoryError(ep); - goto err; - } - if (sp->exception->type == EJS_TYPE_OBJECT) { - ejsMakeObjLive(sp->exception, 0); - mprAssert(sp->exception->objectState->alive == 0); - } - - /* - * If we're in a try block, we need to keep parsing - * so we can find the end of the block and the start - * of the catch block. Otherwise, we are done. - */ - if (!(flags & EJS_FLAGS_TRY)) { - break; - } - } - flags &= ~EJS_FLAGS_EXE; - if (ep->recurseCount > 20) { - break; - } - state = EJS_STATE_STMT_DONE; - ep->gotException = 0; - } - - } while (state == EJS_STATE_STMT_DONE); - - if (sp->exception) { - ep->gotException = 1; - ejsWriteVar(ep, ep->result, sp->exception, EJS_SHALLOW_COPY); - - /* Eat the closing brace */ - ejsLexGetToken(ep, state); - ejsFreeVar(ep, sp->exception); - - goto err; - } - ejsFreeVar(ep, sp->exception); - - if (state < 0) { - goto done; - } - - if (ejsLexGetToken(ep, state) != EJS_TOK_RBRACE) { - ejsSyntaxError(ep, 0); - goto err; - } - state = EJS_STATE_STMT_DONE; - goto done; - - case EJS_TOK_RBRACE: - if (state == EJS_STATE_STMT) { - ejsLexPutbackToken(ep, sp->tid, ep->token); - state = EJS_STATE_STMT_BLOCK_DONE; - - } else if (state == EJS_STATE_EXPR) { - ejsLexPutbackToken(ep, sp->tid, ep->token); - state = EJS_STATE_EXPR; - - } else { - ejsSyntaxError(ep, 0); - state = EJS_STATE_ERR; - } - goto done; - - case EJS_TOK_RETURN: - if ((sp->rs = ejsParse(ep, EJS_STATE_RELEXP, flags)) < 0) { - state = sp->rs; - goto done; - } - if (flags & EJS_FLAGS_EXE) { - state = EJS_STATE_RET; - goto done; - } - break; - } - } -done: - mprFree(sp->id); - - if (sp->expectEndOfStmt && state >= 0) { - sp->tid = ejsLexGetToken(ep, state); - if (sp->tid == EJS_TOK_RBRACE) { - ejsLexPutbackToken(ep, EJS_TOK_RBRACE, ep->token); - - } else if (sp->tid != EJS_TOK_SEMI && sp->tid != EJS_TOK_NEWLINE && - sp->tid != EJS_TOK_EOF) { - ejsSyntaxError(ep, 0); - state = EJS_STATE_ERR; - - } else { - /* - * Skip newlines after semi-colon - */ - removeNewlines(ep, state); - } - } - - /* - * Advance the state - */ - switch (state) { - case EJS_STATE_STMT: - case EJS_STATE_STMT_DONE: - state = EJS_STATE_STMT_DONE; - break; - - case EJS_STATE_DEC: - case EJS_STATE_DEC_DONE: - state = EJS_STATE_DEC_DONE; - break; - - case EJS_STATE_EXPR: - case EJS_STATE_EXPR_DONE: - state = EJS_STATE_EXPR_DONE; - break; - - case EJS_STATE_STMT_BLOCK_DONE: - case EJS_STATE_EOF: - case EJS_STATE_RET: - break; - - default: - if (state != EJS_STATE_ERR) { - ejsSyntaxError(ep, 0); - } - state = EJS_STATE_ERR; - } - popFrame(ep, sizeof(ParseStmt)); - return state; - -err: - state = EJS_STATE_ERR; - goto done; -} - -/******************************************************************************/ -/* - * Local vars - */ - -typedef struct ParseFor { - char *initToken; - int tid, foundVar, initId, each; -} ParseFor; - -/* - * Parse method arguments - */ - -static int parseFor(Ejs *ep, int state, int flags) -{ - ParseFor *sp; - - if ((sp = pushFrame(ep, sizeof(ParseFor))) == 0) { - return EJS_STATE_ERR; - } - - mprAssert(ep); - - if (state != EJS_STATE_STMT) { - ejsSyntaxError(ep, 0); - goto err; - } - - if ((sp->tid = ejsLexGetToken(ep, state)) == EJS_TOK_EACH) { - sp->each = 1; - sp->tid = ejsLexGetToken(ep, state); - - } else { - sp->each = 0; - } - - if (sp->tid != EJS_TOK_LPAREN) { - ejsSyntaxError(ep, 0); - goto err; - } - - /* - * Need to peek 2-3 tokens ahead and see if this is a - * for [each] ([var] x in set) - * or - * for (init ; whileCond; incr) - */ - sp->initId = ejsLexGetToken(ep, EJS_STATE_EXPR); - sp->foundVar = 0; - if (sp->initId == EJS_TOK_ID && strcmp(ep->token, "var") == 0) { - sp->foundVar = 1; - sp->initId = ejsLexGetToken(ep, EJS_STATE_EXPR); - } - sp->initToken = mprStrdup(ep, ep->token); - - sp->tid = ejsLexGetToken(ep, EJS_STATE_EXPR); - - ejsLexPutbackToken(ep, sp->tid, ep->token); - ejsLexPutbackToken(ep, sp->initId, sp->initToken); - mprFree(sp->initToken); - - if (sp->foundVar) { - ejsLexPutbackToken(ep, EJS_TOK_ID, "var"); - } - - if (sp->tid == EJS_TOK_IN) { - state = parseForIn(ep, state, flags, sp->each); - - } else { - state = parseRegFor(ep, state, flags); - } - -done: - popFrame(ep, sizeof(ParseFor)); - return state; - -err: - state = EJS_STATE_ERR; - goto done; -} - -/******************************************************************************/ -/* - * Parse method arguments - */ - -static int parseArgs(Ejs *ep, int state, int flags) -{ - EjsVar *vp; - int tid; - - mprAssert(ep); - - do { - /* - * Peek and see if there are no args - */ - tid = ejsLexGetToken(ep, state); - ejsLexPutbackToken(ep, tid, ep->token); - if (tid == EJS_TOK_RPAREN) { - break; - } - - /* - * If this is part of a constructor, must run methods in args normally - */ - flags &= ~EJS_FLAGS_NEW; - - state = ejsParse(ep, EJS_STATE_RELEXP, flags); - if (state < 0) { - return state; - } - if (flags & EJS_FLAGS_EXE) { - mprAssert(ep->proc->args); - vp = ejsDupVar(ep, ep->result, EJS_SHALLOW_COPY); - if (vp == 0) { - ejsMemoryError(ep); - return EJS_STATE_ERR; - } - /* MOB */ - if (vp->type == EJS_TYPE_OBJECT) { - ejsMakeObjLive(vp, 0); - mprAssert(vp->objectState->alive == 0); - } - - /* - * Propagate the name - */ - ejsSetVarName(ep, vp, ep->result->propertyName); - - mprAddItem(ep->proc->args, vp); - - } - /* - * Peek at the next token, continue if more args (ie. comma seen) - */ - tid = ejsLexGetToken(ep, state); - if (tid != EJS_TOK_COMMA) { - ejsLexPutbackToken(ep, tid, ep->token); - } - } while (tid == EJS_TOK_COMMA); - - if (tid != EJS_TOK_RPAREN && state != EJS_STATE_RELEXP_DONE) { - ejsSyntaxError(ep, 0); - return EJS_STATE_ERR; - } - return EJS_STATE_ARG_LIST_DONE; -} - -/******************************************************************************/ -/* - * Local vars - */ - -typedef struct ParseAssign { - EjsProperty *saveProperty; - EjsVar *saveObj; - int saveObjPerm, savePropPerm, rc; -} ParseAssign; - -/* - * Parse an assignment statement - */ - -static int parseAssignment(Ejs *ep, int state, int flags, char *id) -{ - ParseAssign *sp; - - - if (id == 0) { - if (!ep->gotException) { - ejsSyntaxError(ep, 0); - } - return EJS_STATE_ERR; - } - - if ((sp = pushFrame(ep, sizeof(ParseAssign))) == 0) { - return EJS_STATE_ERR; - } - - mprAssert(ep->currentObj); - - /* - * Parse the right hand side of the "=" - */ - sp->saveObj = ep->currentObj; - sp->saveProperty = ep->currentProperty; - - sp->saveObjPerm = ejsMakeObjPermanent(sp->saveObj, 1); - sp->savePropPerm = ejsMakeObjPermanent(ejsGetVarPtr(sp->saveProperty), 1); - - sp->rc = ejsParse(ep, EJS_STATE_RELEXP, flags | EJS_FLAGS_ASSIGNMENT); - - ejsMakeObjPermanent(sp->saveObj, sp->saveObjPerm); - ejsMakeObjPermanent(ejsGetVarPtr(sp->saveProperty), sp->savePropPerm); - - if (sp->rc < 0) { - state = EJS_STATE_ERR; - } - - ep->currentObj = sp->saveObj; - ep->currentProperty = sp->saveProperty; - - popFrame(ep, sizeof(ParseAssign)); - - if (! (flags & EJS_FLAGS_EXE)) { - return state; - } - - return state; -} - -/******************************************************************************/ - -static int assignPropertyValue(Ejs *ep, char *id, int state, EjsVar *value, - int flags) -{ - EjsProperty *saveProperty; - EjsVar *saveObj, *obj, *vp; - char *procName; - int saveObjPerm, savePropPerm, rc; - - mprAssert(flags & EJS_FLAGS_EXE); - - if (ep->currentProperty && - !ep->currentProperty->var.flags & EJS_GET_ACCESSOR) { - obj = ep->currentObj; - - } else { - /* - * Handle any set accessors. - * FUTURE OPT -- could be faster - * FUTURE OPT -- coming here even when doing just a set "x = value"; - */ - procName = 0; - if (mprAllocStrcat(MPR_LOC_ARGS(ep), &procName, EJS_MAX_ID + 5, 0, - "-set-", id, 0) > 0) { - - MprArray *args; - - ep->currentProperty = searchSpacesForProperty(ep, state, - ep->currentObj, procName, flags); - - if (ep->currentProperty) { - args = mprCreateItemArray(ep, EJS_INC_ARGS, EJS_MAX_ARGS); - - vp = ejsDupVar(ep, value, EJS_SHALLOW_COPY); - mprAddItem(args, vp); - mprAssert(! ejsObjIsCollectable(vp)); - - saveObj = ep->currentObj; - saveProperty = ep->currentProperty; - - saveObjPerm = ejsMakeObjPermanent(saveObj, 1); - savePropPerm = ejsMakeObjPermanent(ejsGetVarPtr(saveProperty), - 1); - - /* - * Invoke the set accessor - */ - rc = ejsRunMethod(ep, ep->currentObj, procName, args); - mprFree(procName); - ejsFreeMethodArgs(ep, args); - - ejsMakeObjPermanent(saveObj, saveObjPerm); - ejsMakeObjPermanent(ejsGetVarPtr(saveProperty), savePropPerm); - - ep->currentObj = saveObj; - ep->currentProperty = saveProperty; - - if (rc < 0) { - return EJS_STATE_ERR; - } - return state; - } - mprFree(procName); - } - - if (ep->currentProperty == 0) { - /* - * MOB -- can we omit this as updateProperty below will create - */ - if (createProperty(ep, &obj, id, state) < 0) { - return EJS_STATE_ERR; - } - } - } - - if (updateProperty(ep, obj, id, state, value) < 0) { - return EJS_STATE_ERR; - } - - vp = ejsGetVarPtr(ep->currentProperty); - if (vp->type == EJS_TYPE_OBJECT) { - ejsMakeObjLive(vp, 1); - } - - return state; -} - -/******************************************************************************/ - -static int parseObjectLiteral(Ejs *ep, int state, int flags, char *id) -{ - EjsProperty *saveProperty; - EjsVar *saveObj; - EjsVar *obj; - char *name; - int saveObjPerm, savePropPerm, tid; - - name = 0; - - saveObj = ep->currentObj; - saveProperty = ep->currentProperty; - - saveObjPerm = ejsMakeObjPermanent(saveObj, 1); - savePropPerm = ejsMakeObjPermanent(ejsGetVarPtr(saveProperty), 1); - - if (flags & EJS_FLAGS_EXE) { - obj = ejsCreateSimpleObj(ep, "Object"); - if (obj == 0) { - ejsMemoryError(ep); - goto err; - } - mprAssert(! ejsObjIsCollectable(obj)); - - } else { - obj = 0; - } - - do { - tid = getNextNonSpaceToken(ep, state); - if (tid != EJS_TOK_ID) { - ejsSyntaxError(ep, 0); - goto err; - } - name = mprStrdup(ep, ep->token); - - tid = getNextNonSpaceToken(ep, state); - if (tid != EJS_TOK_COLON) { - ejsSyntaxError(ep, 0); - goto err; - } - - if (flags & EJS_FLAGS_EXE) { - /* FUTURE OPT -- can we optimize this. We are double accessing id - with the Put below. Should we be using this or ejsSetProperty - */ - if (ejsCreatePropertyMethod(ep, obj, name) == 0) { - ejsMemoryError(ep); - goto err; - } - } - - if (ejsParse(ep, EJS_STATE_RELEXP, flags) < 0) { - goto err; - } - if (flags & EJS_FLAGS_EXE) { - if (ejsSetPropertyMethod(ep, obj, name, ep->result) == 0) { - ejsMemoryError(ep); - goto err; - } - } - mprFree(name); - name = 0; - - tid = getNextNonSpaceToken(ep, state); - - } while (tid == EJS_TOK_COMMA); - - if (tid != EJS_TOK_RBRACE) { - ejsSyntaxError(ep, 0); - goto err; - } - - if (flags & EJS_FLAGS_EXE) { - ejsMakeObjLive(obj, 1); - ejsWriteVar(ep, ep->result, obj, EJS_SHALLOW_COPY); - } - -done: - ejsMakeObjPermanent(saveObj, saveObjPerm); - ejsMakeObjPermanent(ejsGetVarPtr(saveProperty), savePropPerm); - - ep->currentObj = saveObj; - ep->currentProperty = saveProperty; - - if (obj) { - ejsFreeVar(ep, obj); - } - return state; - -err: - mprFree(name); - state = EJS_STATE_ERR; - goto done; -} - -/******************************************************************************/ - -static int parseArrayLiteral(Ejs *ep, int state, int flags, char *id) -{ - EjsProperty *saveProperty; - EjsVar *saveObj; - EjsVar *obj; - int saveObjPerm, savePropPerm, tid; - - saveObj = ep->currentObj; - saveProperty = ep->currentProperty; - - saveObjPerm = ejsMakeObjPermanent(saveObj, 1); - savePropPerm = ejsMakeObjPermanent(ejsGetVarPtr(saveProperty), 1); - - if (flags & EJS_FLAGS_EXE) { - obj = ejsCreateArray(ep, 0); - if (obj == 0) { - ejsMemoryError(ep); - goto err; - } - mprAssert(! ejsObjIsCollectable(obj)); - - } else { - obj = 0; - } - - do { - if (ejsParse(ep, EJS_STATE_RELEXP, flags) < 0) { - goto err; - } - if (flags & EJS_FLAGS_EXE) { - /* MOB _- should this be put[array.length] */ - if (ejsAddArrayElt(ep, obj, ep->result, EJS_SHALLOW_COPY) == 0) { - goto err; - } - } - - tid = getNextNonSpaceToken(ep, state); - - } while (tid == EJS_TOK_COMMA); - - if (tid != EJS_TOK_RBRACKET) { - ejsSyntaxError(ep, "Missing right bracket"); - goto err; - } - - if (flags & EJS_FLAGS_EXE) { - ejsMakeObjLive(obj, 1); - ejsWriteVar(ep, ep->result, obj, EJS_SHALLOW_COPY); - } - -done: - ejsMakeObjPermanent(saveObj, saveObjPerm); - ejsMakeObjPermanent(ejsGetVarPtr(saveProperty), savePropPerm); - - ep->currentObj = saveObj; - ep->currentProperty = saveProperty; - - ejsFreeVar(ep, obj); - return state; - -err: - state = EJS_STATE_ERR; - goto done; -} - -/******************************************************************************/ -/* - * Create a property. - */ - -/* -MOB -- simplify this. Enforce ep->currentObj to be always set. -Then we can delete this and just call - - ejsCreatePropertyMethod(ep->currentObj, id); -*/ -//XX -static int createProperty(Ejs *ep, EjsVar **objp, const char *id, int state) -{ - EjsVar *obj, *vp; - - mprAssert(id && *id); - mprAssert(objp); - - /* - * Determine the variable scope to use for the property. - * Standard says: "var x" means declare locally. - * "x = 2" means declare globally if x is undefined. - */ - if (ep->currentObj) { - if (ep->currentObj->type != EJS_TYPE_OBJECT) { - ejsSyntaxError(ep, "Reference is not an object"); - return EJS_STATE_ERR; - } - obj = ep->currentObj; - - } else { - /* MOB -- we should never be doing this here. ep->currentObj should - always be set already */ - obj = (state == EJS_STATE_DEC) ? ep->local : ep->global; - } - mprAssert(obj); - - vp = ejsCreatePropertyMethod(ep, obj, id); - if (vp == 0) { - if (!ep->gotException) { - ejsMemoryError(ep); - } - return EJS_STATE_ERR; - } - - *objp = obj; - return state; -} - -/******************************************************************************/ -/* - * Update a property. - * - * Return with ep->currentProperty updated to point to the property. - */ - -static int updateProperty(Ejs *ep, EjsVar *obj, const char *id, int state, - EjsVar *value) -{ - EjsVar *vp; - - /* - * MOB -- do ready-only check here - */ - vp = ejsSetPropertyMethod(ep, obj, id, value); - if (vp == 0) { - ejsMemoryError(ep); - return EJS_STATE_ERR; - } - ep->currentProperty = ejsGetPropertyPtr(vp); - - obj->objectState->dirty = 1; - - return state; -} - -/******************************************************************************/ -/* - * Local vars - */ - -typedef struct ParseCond { - EjsVar lhs, rhs; - int tid, operator; -} ParseCond; - -/* - * Parse conditional expression (relational ops separated by ||, &&) - */ - -static int parseCond(Ejs *ep, int state, int flags) -{ - ParseCond *sp; - - if ((sp = pushFrame(ep, sizeof(ParseCond))) == 0) { - return EJS_STATE_ERR; - } - - mprAssert(ep); - - if (flags & EJS_FLAGS_EXE) { - ejsClearVar(ep, ep->result); - } - - sp->lhs.type = sp->rhs.type = EJS_TYPE_UNDEFINED; - sp->lhs.objectState = sp->rhs.objectState = 0; - sp->lhs.allocatedData = sp->rhs.allocatedData = 0; - - ejsSetVarName(ep, &sp->lhs, "lhs"); - ejsSetVarName(ep, &sp->rhs, "rhs"); - - sp->operator = 0; - - do { - /* - * Recurse to handle one side of a conditional. Accumulate the - * left hand side and the final result in ep->result. - */ - state = ejsParse(ep, EJS_STATE_RELEXP, flags); - if (state < 0) { - break; - } - - if (flags & EJS_FLAGS_EXE) { - if (sp->operator > 0) { - /* - * FUTURE -- does not do precedence - */ - ejsWriteVar(ep, &sp->rhs, ep->result, EJS_SHALLOW_COPY); - if (evalCond(ep, &sp->lhs, sp->operator, &sp->rhs) < 0) { - state = EJS_STATE_ERR; - break; - } - /* Result left in ep->result */ - /* MOB */ - if (sp->lhs.type == EJS_TYPE_OBJECT) { - mprAssert(sp->lhs.objectState->alive == 0); - } - if (sp->rhs.type == EJS_TYPE_OBJECT) { - mprAssert(sp->rhs.objectState->alive == 0); - } - } - } - - sp->tid = ejsLexGetToken(ep, state); - if (sp->tid == EJS_TOK_LOGICAL) { - sp->operator = (int) *ep->token; - - } else if (sp->tid == EJS_TOK_RPAREN || sp->tid == EJS_TOK_SEMI) { - ejsLexPutbackToken(ep, sp->tid, ep->token); - state = EJS_STATE_COND_DONE; - break; - - } else { - ejsLexPutbackToken(ep, sp->tid, ep->token); - } - - if (flags & EJS_FLAGS_EXE) { - ejsWriteVar(ep, &sp->lhs, ep->result, EJS_SHALLOW_COPY); - } - - } while (state == EJS_STATE_RELEXP_DONE); - - ejsClearVar(ep, &sp->lhs); - ejsClearVar(ep, &sp->rhs); - - popFrame(ep, sizeof(ParseCond)); - - return state; -} - -/******************************************************************************/ -/* - * Parse variable declaration list. Declarations can be of the following forms: - * var x; - * var x, y, z; - * var x = 1 + 2 / 3, y = 2 + 4; - * var x = { property: value, property: value ... }; - * var x = [ property: value, property: value ... ]; - * - * We set the variable to NULL if there is no associated assignment. - */ - -static int parseDeclaration(Ejs *ep, int state, int flags) -{ - int tid; - - mprAssert(ep); - - do { - if ((tid = ejsLexGetToken(ep, state)) != EJS_TOK_ID) { - ejsSyntaxError(ep, 0); - return EJS_STATE_ERR; - } - ejsLexPutbackToken(ep, tid, ep->token); - - /* - * Parse the entire assignment or simple identifier declaration - */ - if (ejsParse(ep, EJS_STATE_DEC, flags) != EJS_STATE_DEC_DONE) { - return EJS_STATE_ERR; - } - - /* - * Peek at the next token, continue if comma seen - * Stop on ";" or "in" which is used in a "for (var x in ..." - */ - tid = ejsLexGetToken(ep, state); - - if (tid == EJS_TOK_SEMI) { - return EJS_STATE_DEC_LIST_DONE; - - } else if (tid == EJS_TOK_IN) { - ejsLexPutbackToken(ep, tid, ep->token); - return EJS_STATE_DEC_LIST_DONE; - - } else if (flags & EJS_FLAGS_CLASS_DEC && - (tid == EJS_TOK_LBRACE || tid == EJS_TOK_EXTENDS)) { - ejsLexPutbackToken(ep, tid, ep->token); - return EJS_STATE_DEC_LIST_DONE; - - } else if (tid == EJS_TOK_RPAREN && flags & EJS_FLAGS_CATCH) { - ejsLexPutbackToken(ep, tid, ep->token); - return EJS_STATE_DEC_LIST_DONE; - - } else if (tid != EJS_TOK_COMMA) { - ejsSyntaxError(ep, 0); - return EJS_STATE_ERR; - } - - } while (tid == EJS_TOK_COMMA); - - if (tid != EJS_TOK_SEMI) { - ejsSyntaxError(ep, 0); - return EJS_STATE_ERR; - } - return EJS_STATE_DEC_LIST_DONE; -} - -/******************************************************************************/ -/* - * Local vars - */ - -typedef struct ParseExpr { - EjsVar lhs, rhs; - int rel, tid, unaryMinus; -} ParseExpr; - -/* - * Parse expression (leftHandSide operator rightHandSide) - */ - -static int parseExpr(Ejs *ep, int state, int flags) -{ - ParseExpr *sp; - - mprAssert(ep); - - if ((sp = pushFrame(ep, sizeof(ParseExpr))) == 0) { - return EJS_STATE_ERR; - } - - if (flags & EJS_FLAGS_EXE) { - ejsClearVar(ep, ep->result); - } - - sp->lhs.type = sp->rhs.type = EJS_TYPE_UNDEFINED; - sp->lhs.objectState = sp->rhs.objectState = 0; - sp->lhs.allocatedData = sp->rhs.allocatedData = 0; - - ejsSetVarName(ep, &sp->lhs, "lhs"); - ejsSetVarName(ep, &sp->rhs, "rhs"); - - sp->rel = 0; - sp->tid = 0; - sp->unaryMinus = 0; - - do { - /* - * This loop will handle an entire expression list. We call parse - * to evalutate each term which returns the result in ep->result. - */ - if (sp->tid == EJS_TOK_LOGICAL) { - state = ejsParse(ep, EJS_STATE_RELEXP, flags); - if (state < 0) { - break; - } - } else { - sp->tid = ejsLexGetToken(ep, state); - if (sp->tid == EJS_TOK_EXPR && (int) *ep->token == EJS_EXPR_MINUS) { - sp->unaryMinus = 1; - - } else { - ejsLexPutbackToken(ep, sp->tid, ep->token); - } - - state = ejsParse(ep, EJS_STATE_EXPR, flags); - if (state < 0) { - break; - } - } - - if (flags & EJS_FLAGS_EXE) { - if (sp->unaryMinus) { - switch (ep->result->type) { - default: - case EJS_TYPE_UNDEFINED: - case EJS_TYPE_NULL: - case EJS_TYPE_STRING_CMETHOD: - case EJS_TYPE_CMETHOD: - case EJS_TYPE_METHOD: - case EJS_TYPE_PTR: - case EJS_TYPE_OBJECT: - case EJS_TYPE_STRING: - case EJS_TYPE_BOOL: - ejsError(ep, EJS_SYNTAX_ERROR, "Invalid unary minus"); - state = EJS_STATE_ERR; - break; - -#if BLD_FEATURE_FLOATING_POINT - case EJS_TYPE_FLOAT: - ep->result->floating = - ep->result->floating; - break; -#endif - - case EJS_TYPE_INT: - ep->result->integer = - ep->result->integer; - break; - -#if BLD_FEATURE_INT64 - case EJS_TYPE_INT64: - ep->result->integer64 = - ep->result->integer64; - break; -#endif - } - } - sp->unaryMinus = 0; - - if (sp->rel > 0) { - ejsWriteVar(ep, &sp->rhs, ep->result, EJS_SHALLOW_COPY); - if (sp->tid == EJS_TOK_LOGICAL) { - if (evalCond(ep, &sp->lhs, sp->rel, &sp->rhs) < 0) { - state = EJS_STATE_ERR; - break; - } - } else { - if (evalExpr(ep, &sp->lhs, sp->rel, &sp->rhs) < 0) { - state = EJS_STATE_ERR; - break; - } - } - } - /* MOB */ - if (sp->lhs.type == EJS_TYPE_OBJECT) { - ejsMakeObjLive(&sp->lhs, 0); - mprAssert(sp->lhs.objectState->alive == 0); - } - if (sp->rhs.type == EJS_TYPE_OBJECT) { - ejsMakeObjLive(&sp->rhs, 0); - mprAssert(sp->rhs.objectState->alive == 0); - } - } - - if ((sp->tid = ejsLexGetToken(ep, state)) == EJS_TOK_EXPR || - sp->tid == EJS_TOK_INC_DEC || sp->tid == EJS_TOK_LOGICAL) { - sp->rel = (int) *ep->token; - ejsWriteVar(ep, &sp->lhs, ep->result, EJS_SHALLOW_COPY); - - } else { - ejsLexPutbackToken(ep, sp->tid, ep->token); - state = EJS_STATE_RELEXP_DONE; - } - - } while (state == EJS_STATE_EXPR_DONE); - - ejsClearVar(ep, &sp->lhs); - ejsClearVar(ep, &sp->rhs); - - popFrame(ep, sizeof(ParseExpr)); - - return state; -} - -/******************************************************************************/ -/* - * Local vars - */ - -typedef struct ParseForIn { - EjsInput *endScript, *bodyScript; - EjsProperty *pp, *nextp; - EjsVar *iteratorVar, *setVar, *vp; - int forFlags, tid; -} ParseForIn; - -/* - * Parse the "for ... in" statement. Format for the statement is: - * - * for [each] (var varName in expression) { - * body; - * } - */ - -static int parseForIn(Ejs *ep, int state, int flags, int each) -{ - ParseForIn *sp; - - mprAssert(ep); - - if ((sp = pushFrame(ep, sizeof(ParseForIn))) == 0) { - return EJS_STATE_ERR; - } - - sp->setVar = 0; - sp->iteratorVar = 0; - sp->bodyScript = 0; - sp->endScript = 0; - - sp->tid = ejsLexGetToken(ep, state); - if (sp->tid != EJS_TOK_ID && sp->tid != EJS_TOK_VAR) { - ejsSyntaxError(ep, 0); - goto err; - } - ejsLexPutbackToken(ep, sp->tid, ep->token); - - state = ejsParse(ep, EJS_STATE_EXPR, EJS_FLAGS_FORIN | flags); - if (state < 0) { - goto done; - } - if (flags & EJS_FLAGS_EXE) { - if (ep->currentProperty == 0) { - ejsSyntaxError(ep, 0); - goto err; - } - sp->iteratorVar = &ep->currentProperty->var; - } else { - sp->iteratorVar = 0; - } - - if (ejsLexGetToken(ep, state) != EJS_TOK_IN) { - ejsSyntaxError(ep, 0); - goto err; - } - - /* - * Get the set - */ - sp->tid = ejsLexGetToken(ep, state); - if (sp->tid != EJS_TOK_ID) { - ejsSyntaxError(ep, 0); - goto err; - } - ejsLexPutbackToken(ep, sp->tid, ep->token); - - state = ejsParse(ep, EJS_STATE_EXPR, flags); - if (state < 0) { - goto done; - } - - if ((flags & EJS_FLAGS_EXE) && - (ep->result == 0 || ep->result->type == EJS_TYPE_UNDEFINED)) { - ejsError(ep, EJS_REFERENCE_ERROR, "Can't access array or object"); - goto err; - } - - if (ejsLexGetToken(ep, state) != EJS_TOK_RPAREN) { - ejsSyntaxError(ep, 0); - goto err; - } - - sp->setVar = ejsDupVar(ep, ep->result, EJS_SHALLOW_COPY); - - sp->bodyScript = getInputStruct(ep); - - /* - * Parse the body and remember the end of the body script - */ - sp->forFlags = flags & ~EJS_FLAGS_EXE; - ejsLexSaveInputState(ep, sp->bodyScript); - - state = ejsParse(ep, EJS_STATE_STMT, sp->forFlags); - if (state < 0) { - goto done; - } - - sp->endScript = getInputStruct(ep); - ejsInitInputState(sp->endScript); - ejsLexSaveInputState(ep, sp->endScript); - - /* - * Enumerate the properties - */ - if (flags & EJS_FLAGS_EXE) { - if (sp->setVar->type == EJS_TYPE_OBJECT) { - - sp->setVar->objectState->preventDeleteProp = 1; - - sp->pp = ejsGetFirstProperty(sp->setVar, 0); - while (sp->pp) { - sp->nextp = ejsGetNextProperty(sp->pp, 0); - if (! sp->pp->dontEnumerate && !sp->pp->delayedDelete) { - if (each) { - sp->vp = ejsWriteVar(ep, sp->iteratorVar, - ejsGetVarPtr(sp->pp), EJS_SHALLOW_COPY); - } else { - sp->vp = ejsWriteVarAsString(ep, sp->iteratorVar, - sp->pp->name); - } - if (sp->vp == 0) { - ejsError(ep, EJS_MEMORY_ERROR, - "Can't write to variable"); - goto err; - } - - ejsLexRestoreInputState(ep, sp->bodyScript); - - state = ejsParse(ep, EJS_STATE_STMT, flags); - - if (state < 0) { - if (sp->setVar->objectState) { - sp->setVar->objectState->preventDeleteProp = 0; - } - goto done; - } - } - sp->pp = sp->nextp; - } - - /* - * Process delayed deletes - */ - if (sp->setVar->objectState) { - sp->setVar->objectState->preventDeleteProp = 0; - if (sp->setVar->objectState->delayedDeleteProp) { - sp->pp = ejsGetFirstProperty(sp->setVar, 0); - while (sp->pp) { - sp->nextp = ejsGetNextProperty(sp->pp, 0); - if (sp->pp->delayedDelete) { - ejsDeleteProperty(ep, sp->setVar, sp->pp->name); - } - sp->pp = sp->nextp; - } - sp->setVar->objectState->delayedDeleteProp = 0; - } - } - - } else { - ejsError(ep, EJS_REFERENCE_ERROR, - "Variable to iterate over is not an array or object"); - goto err; - } - } - - ejsLexRestoreInputState(ep, sp->endScript); - -done: - if (sp->endScript) { - ejsLexFreeInputState(ep, sp->endScript); - ejsLexFreeInputState(ep, sp->bodyScript); - } - - if (sp->bodyScript) { - freeInputStruct(ep, sp->bodyScript); - } - if (sp->endScript) { - freeInputStruct(ep, sp->endScript); - } - - if (sp->setVar) { - ejsFreeVar(ep, sp->setVar); - } - - popFrame(ep, sizeof(ParseForIn)); - - return state; - -err: - state = EJS_STATE_ERR; - goto done; -} - -/******************************************************************************/ -/* - * Parse the for statement. Format for the expression is: - * - * for (initial; condition; incr) { - * body; - * } - */ - -static int parseRegFor(Ejs *ep, int state, int flags) -{ - EjsInput *condScript, *endScript, *bodyScript, *incrScript; - - endScript = getInputStruct(ep); - bodyScript = getInputStruct(ep); - incrScript = getInputStruct(ep); - condScript = getInputStruct(ep); - - ejsInitInputState(endScript); - ejsInitInputState(bodyScript); - ejsInitInputState(incrScript); - ejsInitInputState(condScript); - - state = parseForInner(ep, state, flags, - condScript, incrScript, bodyScript, endScript); - - ejsLexFreeInputState(ep, condScript); - ejsLexFreeInputState(ep, incrScript); - ejsLexFreeInputState(ep, endScript); - ejsLexFreeInputState(ep, bodyScript); - - freeInputStruct(ep, condScript); - freeInputStruct(ep, incrScript); - freeInputStruct(ep, endScript); - freeInputStruct(ep, bodyScript); - - return state; -} - -/******************************************************************************/ - -static int parseForInner(Ejs *ep, int state, int flags, EjsInput *condScript, - EjsInput *incrScript, EjsInput *bodyScript, EjsInput *endScript) -{ - int forFlags, cond, rs; - - mprAssert(ep); - - /* - * Evaluate the for loop initialization statement - */ - if ((state = ejsParse(ep, EJS_STATE_STMT, flags)) < 0) { - return state; - } - - /* - * The first time through, we save the current input context just prior - * to each step: prior to the conditional, the loop increment and - * the loop body. - */ - ejsLexSaveInputState(ep, condScript); - if ((rs = ejsParse(ep, EJS_STATE_COND, flags)) < 0) { - return rs; - } - - cond = (ep->result->boolean != 0); - - if (ejsLexGetToken(ep, state) != EJS_TOK_SEMI) { - ejsSyntaxError(ep, 0); - return EJS_STATE_ERR; - } - - /* - * Don't execute the loop increment statement or the body - * first time. - */ - forFlags = flags & ~EJS_FLAGS_EXE; - ejsLexSaveInputState(ep, incrScript); - if ((rs = ejsParse(ep, EJS_STATE_EXPR, forFlags)) < 0) { - return rs; - } - - if (ejsLexGetToken(ep, state) != EJS_TOK_RPAREN) { - ejsSyntaxError(ep, 0); - return EJS_STATE_ERR; - } - - /* - * Parse the body and remember the end of the body script - */ - ejsLexSaveInputState(ep, bodyScript); - if ((rs = ejsParse(ep, EJS_STATE_STMT, forFlags)) < 0) { - return rs; - } - ejsLexSaveInputState(ep, endScript); - - /* - * Now actually do the for loop. Note loop has been rotated - */ - while (cond && (flags & EJS_FLAGS_EXE)) { - /* - * Evaluate the body - */ - ejsLexRestoreInputState(ep, bodyScript); - - if ((rs = ejsParse(ep, EJS_STATE_STMT, flags)) < 0) { - return rs; - } - - /* - * Evaluate the increment script - */ - ejsLexRestoreInputState(ep, incrScript); - if ((rs = ejsParse(ep, EJS_STATE_EXPR, flags)) < 0) { - return rs; - } - /* - * Evaluate the condition - */ - ejsLexRestoreInputState(ep, condScript); - if ((rs = ejsParse(ep, EJS_STATE_COND, flags)) < 0) { - return 0; - } - mprAssert(ep->result->type == EJS_TYPE_BOOL); - cond = (ep->result->boolean != 0); - } - - ejsLexRestoreInputState(ep, endScript); - - return state; -} - -/******************************************************************************/ -/* - * Create the bare class object - */ - -static int createClass(Ejs *ep, EjsVar *obj, const char *className, - EjsVar *baseClass) -{ - EjsVar *classObj, *existingClass; - - existingClass = ejsGetClass(ep, obj, className); - if (existingClass) { - /* - * We allow partial clases and method redefinition - * FUTURE -- should prevent this if the class is sealed. - * DISABLED Error message and return OK. - */ - /* ejsError(ep, EJS_EVAL_ERROR, "Can't create class %s", className); */ - return 0; - } - - if (baseClass == 0) { - baseClass = ejsGetClass(ep, ep->service->globalClass, "Object"); - mprAssert(baseClass); - } - - classObj = ejsCreateSimpleClass(ep, baseClass, className); - if (classObj == 0) { - ejsMemoryError(ep); - return -1; - } - mprAssert(! ejsObjIsCollectable(classObj)); - - ep->currentProperty = ejsSetPropertyAndFree(ep, obj, className, classObj); - mprAssert(ep->currentProperty); - - if (ep->currentProperty == 0) { - return -1; - } - - return 0; -} - -/******************************************************************************/ -/* - * Local vars for parseTry - */ - -typedef struct ParseTry { - EjsVar *exception; - int tid, caught, rs, catchFlags; -} ParseTry; - -/* - * Parse try block - * - * try {} - */ - -static int parseTry(Ejs *ep, int state, int flags) -{ - ParseTry *sp; - - if ((sp = pushFrame(ep, sizeof(ParseTry))) == 0) { - return EJS_STATE_ERR; - } - - mprAssert(ep); - - sp->caught = 0; - sp->exception = 0; - sp->catchFlags = flags; - - /* - * Execute the code in the try block - */ - sp->rs = ejsParse(ep, EJS_STATE_STMT, flags | EJS_FLAGS_TRY); - if (sp->rs < 0) { - if (sp->rs == EJS_STATE_ERR) { - sp->exception = ejsDupVar(ep, ep->result, EJS_SHALLOW_COPY); - if (sp->exception == 0) { - ejsMemoryError(ep); - goto err; - } - } else { - state = sp->rs; - goto done; - } - - } else { - sp->catchFlags = flags & ~EJS_FLAGS_EXE; - } - - /* - * On success path or when an exception is caught, we must parse all - * catch and finally blocks. - */ - sp->tid = getNextNonSpaceToken(ep, state); - - if (sp->tid == EJS_TOK_CATCH) { - - ep->gotException = 0; - - sp->tid = getNextNonSpaceToken(ep, state); - - if (sp->tid == EJS_TOK_LBRACE) { - /* - * Unqualified "catch " - */ - ejsLexPutbackToken(ep, sp->tid, ep->token); - if (ejsParse(ep, EJS_STATE_STMT, sp->catchFlags) >= 0) { - sp->caught++; - } - - } else if (sp->tid == EJS_TOK_LPAREN) { - - /* - * Qualified "catch (variable) " - */ - if ((sp->rs = ejsParse(ep, EJS_STATE_DEC_LIST, - sp->catchFlags | EJS_FLAGS_CATCH)) < 0) { - ejsSyntaxError(ep, "Bad catch statement"); - state = sp->rs; - goto done; - } - - sp->tid = getNextNonSpaceToken(ep, state); - if (sp->tid != EJS_TOK_RPAREN) { - ejsSyntaxError(ep, 0); - goto err; - } - - if (sp->catchFlags & EJS_FLAGS_EXE) { - if (ep->currentProperty == 0) { - ejsError(ep, EJS_EVAL_ERROR, "Can't define catch variable"); - goto err; - } - - /* - * Set the catch variable - */ - if (ejsWriteVar(ep, - ejsGetVarPtr(ep->currentProperty), sp->exception, - EJS_SHALLOW_COPY) == 0) { - ejsError(ep, EJS_EVAL_ERROR, "Can't update catch variable"); - goto err; - } - } - - /* - * Parse the catch block - */ - if ((sp->rs = ejsParse(ep, EJS_STATE_STMT, sp->catchFlags)) < 0) { - state = sp->rs; - goto done; - } - sp->caught++; - ep->gotException = 0; - } - sp->tid = getNextNonSpaceToken(ep, state); - } - - /* - * Parse the finally block - */ - if (sp->tid == EJS_TOK_FINALLY) { - if (ejsParse(ep, EJS_STATE_STMT, flags) < 0) { - goto err; - } - } else { - ejsLexPutbackToken(ep, sp->tid, ep->token); - } - - /* - * Set the exception value - */ - if (sp->exception && !sp->caught) { - ejsWriteVar(ep, ep->result, sp->exception, EJS_SHALLOW_COPY); - goto err; - } - - state = EJS_STATE_STMT_DONE; - -done: - if (sp->exception) { - ejsFreeVar(ep, sp->exception); - } - - popFrame(ep, sizeof(ParseTry)); - return state; - - -err: - state = EJS_STATE_ERR; - goto done; -} - -/******************************************************************************/ -/* - * Parse throw statement - * - * throw expression - */ - -static int parseThrow(Ejs *ep, int state, int flags) -{ - int rc; - - mprAssert(ep); - - if ((rc = ejsParse(ep, EJS_STATE_EXPR, flags)) < 0) { - return rc; - } - - - if (flags & EJS_FLAGS_EXE) { - /* - * We have thrown the exception so set the state to ERR - */ - ep->gotException = 1; - return EJS_STATE_ERR; - } - return state; -} - -/******************************************************************************/ -/* - * Parse a class and module declaration - * - * class [extends baseClass] { - * [public | private | ... ] var declarations ... - * [constructor] function declarations ... - * } - * - * Modules are identical except declared with a "module" instead of - * "class". Modules cannot be instantiated and are used for mixins. - * - */ - -static int parseClass(Ejs *ep, int state, int flags) -{ - int originalToken, tid, fid; - - mprAssert(ep); - - originalToken = ep->tid; - - /* - * Parse "class Name [extends BaseClass]" - */ - if (ejsParse(ep, EJS_STATE_DEC_LIST, flags | EJS_FLAGS_CLASS_DEC) < 0) { - return EJS_STATE_ERR; - } - - tid = getNextNonSpaceToken(ep, state); - - if (tid != EJS_TOK_LBRACE) { - return EJS_STATE_ERR; - } - - /* - * After parsing the class body, ep->local will contain the actual - * class/module object. So, we save ep->local by creating a new block. - */ - if (flags & EJS_FLAGS_EXE) { - fid = ejsSetBlock(ep, ejsGetVarPtr(ep->currentProperty)); - ejsSetVarName(ep, ep->local, ep->currentProperty->name); - - } else { - fid = -1; - } - - /* FUTURE -- should prevent modules from being instantiated */ - - /* - * Parse class body - */ - do { - state = ejsParse(ep, EJS_STATE_STMT, flags); - if (state < 0) { - if (fid >= 0) { - ejsCloseBlock(ep, fid); - } - return state; - } - tid = getNextNonSpaceToken(ep, state); - if (tid == EJS_TOK_RBRACE) { - break; - } - ejsLexPutbackToken(ep, tid, ep->token); - - } while (state >= 0); - - if (fid >= 0) { - ejsCloseBlock(ep, fid); - } - - if (tid != EJS_TOK_RBRACE) { - ejsSyntaxError(ep, 0); - state = EJS_STATE_ERR; - } - - return state; -} - -/******************************************************************************/ -/* - * Parse a function declaration - */ - -static int parseFunction(Ejs *ep, int state, int flags) -{ - EjsInput *endScript, *bodyScript; - EjsProperty *pp; - EjsVar *func, *funcProp, *currentObj, *vp, *baseClass; - char *procName; - int varFlags, len, tid, bodyFlags, innerState; - - mprAssert(ep); - - func = 0; - varFlags = 0; - - /* - * method (arg, arg, arg) { body }; - * method name(arg, arg, arg) { body }; - */ - - tid = ejsLexGetToken(ep, state); - - if (tid == EJS_TOK_GET) { - varFlags |= EJS_GET_ACCESSOR; - tid = ejsLexGetToken(ep, state); - - } else if (tid == EJS_TOK_SET) { - varFlags |= EJS_SET_ACCESSOR; - tid = ejsLexGetToken(ep, state); - } - - if (tid == EJS_TOK_ID) { - if (varFlags & EJS_SET_ACCESSOR) { - - if (mprAllocStrcat(MPR_LOC_ARGS(ep), &procName, EJS_MAX_ID + 5, - 0, "-set-", ep->token, 0) < 0) { - ejsError(ep, EJS_SYNTAX_ERROR, - "Name %s is too long", ep->token); - return EJS_STATE_ERR; - } - - } else { - procName = mprStrdup(ep, ep->token); - } - - tid = ejsLexGetToken(ep, state); - - } else { - procName = 0; - } - - if (tid != EJS_TOK_LPAREN) { - mprFree(procName); - ejsSyntaxError(ep, 0); - return EJS_STATE_ERR; - } - - /* - * Hand craft the method value structure. - */ - if (flags & EJS_FLAGS_EXE) { - func = ejsCreateMethodVar(ep, 0, 0, 0); - if (func == 0) { - mprFree(procName); - ejsMemoryError(ep); - return EJS_STATE_ERR; - } - func->flags = varFlags; - } - - tid = ejsLexGetToken(ep, state); - while (tid == EJS_TOK_ID) { - if (flags & EJS_FLAGS_EXE) { - mprAddItem(func->method.args, - mprStrdup(func->method.args, ep->token)); - } - tid = ejsLexGetToken(ep, state); - if (tid == EJS_TOK_RPAREN || tid != EJS_TOK_COMMA) { - break; - } - tid = ejsLexGetToken(ep, state); - } - if (tid != EJS_TOK_RPAREN) { - mprFree(procName); - ejsFreeVar(ep, func); - ejsSyntaxError(ep, 0); - return EJS_STATE_ERR; - } - - /* Allow new lines before opening brace */ - do { - tid = ejsLexGetToken(ep, state); - } while (tid == EJS_TOK_NEWLINE); - - if (tid != EJS_TOK_LBRACE) { - mprFree(procName); - ejsFreeVar(ep, func); - ejsSyntaxError(ep, 0); - return EJS_STATE_ERR; - } - - /* - * Register the method name early to allow for recursive - * method calls (see note in ECMA standard, page 71) - */ - funcProp = 0; - if (flags & EJS_FLAGS_EXE && procName) { - currentObj = pickSpace(ep, 0, procName, flags | EJS_FLAGS_LOCAL); - pp = ejsSetProperty(ep, currentObj, procName, func); - if (pp == 0) { - ejsFreeVar(ep, func); - ejsMemoryError(ep); - return EJS_STATE_ERR; - } - funcProp = ejsGetVarPtr(pp); - } - - - bodyScript = getInputStruct(ep); - - /* - * Parse the method body. Turn execute off. - */ - bodyFlags = flags & ~EJS_FLAGS_EXE; - ejsLexSaveInputState(ep, bodyScript); - - do { - innerState = ejsParse(ep, EJS_STATE_STMT, bodyFlags); - } while (innerState == EJS_STATE_STMT_DONE); - - tid = ejsLexGetToken(ep, state); - - if (innerState != EJS_STATE_STMT_BLOCK_DONE || tid != EJS_TOK_RBRACE) { - mprFree(procName); - ejsFreeVar(ep, func); - ejsLexFreeInputState(ep, bodyScript); - if (innerState != EJS_STATE_ERR) { - ejsSyntaxError(ep, 0); - } - freeInputStruct(ep, bodyScript); - return EJS_STATE_ERR; - } - - if (flags & EJS_FLAGS_EXE) { - endScript = getInputStruct(ep); - ejsLexSaveInputState(ep, endScript); - - /* - * Save the method body between the starting and ending parse - * positions. Overwrite the trailing '}' with a null. - */ - len = endScript->scriptServp - bodyScript->scriptServp; - func->method.body = mprAlloc(ep, len + 1); - memcpy(func->method.body, bodyScript->scriptServp, len); - - if (len <= 0) { - func->method.body[0] = '\0'; - } else { - func->method.body[len - 1] = '\0'; - } - ejsLexFreeInputState(ep, bodyScript); - ejsLexFreeInputState(ep, endScript); - freeInputStruct(ep, endScript); - - /* - * If we are in an assignment, don't register the method name, rather - * return the method structure in the parser result. - */ - if (procName) { - currentObj = pickSpace(ep, 0, procName, flags | EJS_FLAGS_LOCAL); - pp = ejsSetProperty(ep, currentObj, procName, func); - if (pp == 0) { - ejsFreeVar(ep, func); - ejsMemoryError(ep); - return EJS_STATE_ERR; - } - - if (currentObj->objectState->className && - strcmp(currentObj->objectState->className, procName) == 0) { - baseClass = currentObj->objectState->baseClass; - if (baseClass) { - if (strstr(func->method.body, "super(") != 0) { - funcProp->callsSuper = 1; - /* - * Define super() to point to the baseClass constructor - */ - vp = ejsGetPropertyAsVar(ep, baseClass, - baseClass->objectState->className); - if (vp) { - mprAssert(vp); - if (ejsSetProperty(ep, currentObj, "super", - vp) == 0) { - ejsFreeVar(ep, func); - ejsMemoryError(ep); - return EJS_STATE_ERR; - } - } - } - } - } - } - /* - * Always return the function. Try for all stmts to be expressions. - */ - /* MOB - rc */ - ejsWriteVar(ep, ep->result, func, EJS_SHALLOW_COPY); - } - freeInputStruct(ep, bodyScript); - - mprFree(procName); - ejsFreeVar(ep, func); - - return state; -} - -/******************************************************************************/ -/* - * Local vars - */ - -typedef struct ParseMethod { - EjsProc proc, *saveProc; - EjsVar *saveObj, *newObj; - int saveObjPerm, rc; - -} ParseMethod; - -/* - * Parse a method name and invoke the method. See parseFunction for - * function declarations. - */ - -static int parseMethod(Ejs *ep, int state, int flags, char *id) -{ - ParseMethod *sp; - - if ((sp = pushFrame(ep, sizeof(ParseMethod))) == 0) { - return EJS_STATE_ERR; - } - - /* - * Must save any current ep->proc value for the current stack frame - * to allow for recursive method calls. - */ - sp->saveProc = (ep->proc) ? ep->proc: 0; - - memset(&sp->proc, 0, sizeof(EjsProc)); - sp->proc.procName = mprStrdup(ep, id); - sp->proc.fn = &ep->currentProperty->var; - sp->proc.args = mprCreateItemArray(ep, EJS_INC_ARGS, EJS_MAX_ARGS); - ep->proc = &sp->proc; - -#if BLD_DEBUG - if (strcmp(sp->proc.procName, "printv") == 0) { - flags |= EJS_FLAGS_TRACE_ARGS; - } -#endif - - if (flags & EJS_FLAGS_EXE) { - ejsClearVar(ep, ep->result); - } - - if (! (flags & EJS_FLAGS_NO_ARGS)) { - sp->saveObj = ep->currentObj; - sp->saveObjPerm = ejsMakeObjPermanent(sp->saveObj, 1); - sp->rc = ejsParse(ep, EJS_STATE_ARG_LIST, flags); - ejsMakeObjPermanent(sp->saveObj, sp->saveObjPerm); - if (sp->rc < 0) { - goto err; - } - ep->currentObj = sp->saveObj; - } - -#if BLD_DEBUG - flags &= ~EJS_FLAGS_TRACE_ARGS; -#endif - - /* - * Evaluate the method if required - */ - if (flags & EJS_FLAGS_EXE) { - if (flags & EJS_FLAGS_NEW) { - sp->newObj = ejsCreateObjUsingArgv(ep, ep->currentObj, - sp->proc.procName, sp->proc.args); - - if (sp->newObj == 0) { - state = EJS_STATE_ERR; - - } else { - mprAssert(! ejsObjIsCollectable(sp->newObj)); - - /* - * Return the newly created object as the result of the - * command. NOTE: newObj may not be an object! - */ - /* MOB - rc */ - ejsWriteVar(ep, ep->result, sp->newObj, EJS_SHALLOW_COPY); - if (ejsVarIsObject(sp->newObj)) { - ejsMakeObjLive(sp->newObj, 1); - mprAssert(ejsObjIsCollectable(sp->newObj)); - mprAssert(ejsBlockInUse(sp->newObj)); - } - ejsFreeVar(ep, sp->newObj); - } - - } else { - - if (evalMethod(ep, ep->currentObj, &sp->proc, flags) < 0) { - /* Methods must call ejsError to set exceptions */ - state = EJS_STATE_ERR; - } - } - } - - if (! (flags & EJS_FLAGS_NO_ARGS)) { - if (ejsLexGetToken(ep, state) != EJS_TOK_RPAREN) { - if (state != EJS_STATE_ERR) { - ejsSyntaxError(ep, 0); - } - state = EJS_STATE_ERR; - } - } - -done: - freeProc(ep, &sp->proc); - ep->proc = sp->saveProc; - - popFrame(ep, sizeof(ParseMethod)); - return state; - -err: - state = EJS_STATE_ERR; - goto done; -} - -/******************************************************************************/ -/* - * Parse an identifier. This is a segment of a fully qualified variable. - * May come here for an initial identifier or for property names - * after a "." or "[...]". - */ - -static int parseId(Ejs *ep, int state, int flags, char **id, int *done) -{ - EjsVar *null; - int tid; - - mprFree(*id); - *id = mprStrdup(ep, ep->token); - - if (ep->currentObj == 0) { - /* First identifier segement */ - ep->currentObj = pickSpace(ep, state, *id, flags); - } - - tid = ejsLexGetToken(ep, state); - if (tid == EJS_TOK_ASSIGNMENT) { - flags |= EJS_FLAGS_LHS; - } - - /* - * Find the referenced variable and store it in currentProperty. - */ - if (flags & EJS_FLAGS_EXE) { - ep->currentProperty = searchSpacesForProperty(ep, state, - ep->currentObj, *id, flags); - - /* - * Handle properties that have been deleted inside an enumeration - */ - if (ep->currentProperty && ep->currentProperty->delayedDelete) { - ep->currentProperty = 0; - } - - if (ep->currentProperty && - ejsVarIsMethod(&ep->currentProperty->var) && - tid != EJS_TOK_LPAREN) { - if (ep->currentProperty->var.flags & EJS_GET_ACCESSOR) { - ejsLexPutbackToken(ep, tid, ep->token); - state = parseMethod(ep, state, flags | EJS_FLAGS_NO_ARGS, *id); - if (ep->flags & EJS_FLAGS_EXIT) { - state = EJS_STATE_RET; - } - if (state >= 0) { - ejsSetVarName(ep, ep->result, ep->currentProperty->name); - } - return state; - } - } - /* - * OPT. We should not have to do this always - */ - updateResult(ep, state, flags, ejsGetVarPtr(ep->currentProperty)); - } - - flags &= ~EJS_FLAGS_LHS; - - if (tid == EJS_TOK_LPAREN) { - if (ep->currentProperty == 0 && (flags & EJS_FLAGS_EXE)) { - ejsError(ep, EJS_REFERENCE_ERROR, - "Method name not defined \"%s\"", *id); - return EJS_STATE_ERR; - } - ejsLexPutbackToken(ep, EJS_TOK_METHOD_NAME, ep->token); - return state; - } - - if (tid == EJS_TOK_PERIOD || tid == EJS_TOK_LBRACKET || - tid == EJS_TOK_ASSIGNMENT || tid == EJS_TOK_INC_DEC) { - ejsLexPutbackToken(ep, tid, ep->token); - return state; - } - - if (flags & EJS_FLAGS_CLASS_DEC) { - if (tid == EJS_TOK_LBRACE || tid == EJS_TOK_EXTENDS) { - ejsLexPutbackToken(ep, tid, ep->token); - return state; - } - } - - if (flags & EJS_FLAGS_DELETE) { - if (tid == EJS_TOK_RBRACE) { - ejsLexPutbackToken(ep, tid, ep->token); - } - } - - /* - * Only come here for variable access and declarations. - * Assignment handled elsewhere. - */ - if (flags & EJS_FLAGS_EXE) { - if (state == EJS_STATE_DEC) { - /* - * Declare a variable. Standard allows: var x ; var x ; - */ -#if DISABLED - if (ep->currentProperty != 0) { - ejsError(ep, EJS_REFERENCE_ERROR, - "Variable already defined \"%s\"", *id); - return EJS_STATE_ERR; - } -#endif - /* - * Create or overwrite if it already exists - * Set newly declared variables to the null value. - */ - null = ejsCreateNullVar(ep); - ep->currentProperty = ejsSetPropertyAndFree(ep, ep->currentObj, - *id, null); - ejsClearVar(ep, ep->result); - - } else if (flags & EJS_FLAGS_FORIN) { - /* - * This allows "for (x" when x has not yet been defined - */ - if (ep->currentProperty == 0) { - /* MOB -- return code */ - ep->currentProperty = ejsCreateProperty(ep, - ep->currentObj, *id); - } - - } else if (ep->currentProperty == 0) { - - if (ep->currentObj && ((ep->currentObj == ep->global || - (ep->currentObj == ep->local)))) { - /* - * Test against currentObj and not currentObj->objectState - * as we must allow "i = global.x" and not allow - * "i = x" where x does not exist. - */ - ejsError(ep, EJS_REFERENCE_ERROR, - "Undefined variable \"%s\"", *id); - return EJS_STATE_ERR; - } - - if (flags & EJS_FLAGS_DELETE) { - ejsError(ep, EJS_REFERENCE_ERROR, - "Undefined variable \"%s\"", *id); - return EJS_STATE_ERR; - } - } - } - ejsLexPutbackToken(ep, tid, ep->token); - if (tid == EJS_TOK_RBRACKET || tid == EJS_TOK_COMMA || - tid == EJS_TOK_IN) { - *done = 1; - } - return state; -} - -/******************************************************************************/ -/* - * Local vars - */ - -typedef struct ParseIf { - int ifResult, thenFlags, elseFlags, tid, rs; -} ParseIf; - -/* - * Parse an "if" statement - */ - -static int parseIf(Ejs *ep, int state, int flags, int *done) -{ - ParseIf *sp; - - if ((sp = pushFrame(ep, sizeof(ParseIf))) == 0) { - return EJS_STATE_ERR; - } - - if (state != EJS_STATE_STMT) { - goto err; - } - if (ejsLexGetToken(ep, state) != EJS_TOK_LPAREN) { - goto err; - } - - /* - * Evaluate the entire condition list "(condition)" - */ - if (ejsParse(ep, EJS_STATE_COND, flags) < 0) { - goto err; - } - if (ejsLexGetToken(ep, state) != EJS_TOK_RPAREN) { - goto err; - } - - /* - * This is the "then" case. We need to always parse both cases and - * execute only the relevant case. - */ - sp->ifResult = ejsVarToBoolean(ep->result); - if (sp->ifResult) { - sp->thenFlags = flags; - sp->elseFlags = flags & ~EJS_FLAGS_EXE; - } else { - sp->thenFlags = flags & ~EJS_FLAGS_EXE; - sp->elseFlags = flags; - } - - /* - * Process the "then" case. - */ - if ((sp->rs = ejsParse(ep, EJS_STATE_STMT, sp->thenFlags)) < 0) { - if (! ep->gotException) { - state = sp->rs; - goto done; - } - } - - /* - * Check to see if there is an "else" case - */ - removeNewlines(ep, state); - sp->tid = ejsLexGetToken(ep, state); - if (sp->tid != EJS_TOK_ELSE) { - ejsLexPutbackToken(ep, sp->tid, ep->token); - *done = 1; - if (ep->gotException) { - goto err; - } - goto done; - } - - /* - * Process the "else" case. - */ - state = ejsParse(ep, EJS_STATE_STMT, sp->elseFlags); - -done: - *done = 1; - if (ep->gotException) { - state = EJS_STATE_ERR; - } - popFrame(ep, sizeof(ParseIf)); - return state; - - -err: - state = EJS_STATE_ERR; - goto done; -} - -/******************************************************************************/ -/* - * Parse a postix "++" or "--" statement - */ - -static int parseInc(Ejs *ep, int state, int flags) -{ - EjsVar *one; - - if (! (flags & EJS_FLAGS_EXE)) { - return state; - } - - if (ep->currentProperty == 0) { - ejsError(ep, EJS_REFERENCE_ERROR, - "Undefined variable \"%s\"", ep->token); - return EJS_STATE_ERR; - } - one = ejsCreateIntegerVar(ep, 1); - if (evalExpr(ep, &ep->currentProperty->var, (int) *ep->token, one) < 0) { - ejsFreeVar(ep, one); - return EJS_STATE_ERR; - } - if (ejsWriteVar(ep, &ep->currentProperty->var, ep->result, - EJS_SHALLOW_COPY) < 0) { - ejsError(ep, EJS_IO_ERROR, "Can't write to variable"); - ejsFreeVar(ep, one); - return EJS_STATE_ERR; - } - ejsFreeVar(ep, one); - return state; -} - -/******************************************************************************/ -/* - * Evaluate a condition. Implements &&, ||, !. Returns with a boolean result - * in ep->result. Returns EJS_STATE_ERR on errors, zero if successful. - */ - -static int evalCond(Ejs *ep, EjsVar *lhs, int rel, EjsVar *rhs) -{ - int l, r, lval; - - mprAssert(rel > 0); - - l = ejsVarToBoolean(lhs); - r = ejsVarToBoolean(rhs); - - switch (rel) { - case EJS_COND_AND: - lval = l && r; - break; - case EJS_COND_OR: - lval = l || r; - break; - default: - ejsError(ep, EJS_SYNTAX_ERROR, "Bad operator %d", rel); - return -1; - } - - /* MOB - rc */ - ejsWriteVarAsBoolean(ep, ep->result, lval); - return 0; -} - - -/******************************************************************************/ -/* - * return true if this string is a valid number - */ - -static int stringIsNumber(const char *s) -{ - char *endptr = NULL; - - if (s == NULL || *s == 0) { - return 0; - } - /* MOB -- not ideal */ -#if BREW - /* MOB this should check all digits and not just the first. */ - /* Does not support floating point - easy */ - - if (isdigit(*s) || (*s == '-' && isdigit(s[1]))) { - return 1; - } -#else - strtod(s, &endptr); -#endif - if (endptr != NULL && *endptr == 0) { - return 1; - } - return 0; -} - -/******************************************************************************/ -/* - * Evaluate an operation. Returns with the result in ep->result. Returns -1 - * on errors, otherwise zero is returned. - */ - -static int evalExpr(Ejs *ep, EjsVar *lhs, int rel, EjsVar *rhs) -{ - EjsNum lval; - char *str; - int rc; - - mprAssert(rel > 0); - str = 0; - lval = 0; - - /* - * Type conversion. This is tricky and must be according to the standard. - * Only numbers (including floats) and strings can be compared. All other - * types are first converted to numbers by preference and if that fails, - * to strings. - * - * MOB -- should we do "valueOf" here also. - */ - if (lhs->type == EJS_TYPE_OBJECT && - (rhs->type != EJS_TYPE_OBJECT && - (rhs->type != EJS_TYPE_UNDEFINED && rhs->type != EJS_TYPE_NULL))) { - if (ejsVarIsNumber(rhs)) { - if (ejsRunMethod(ep, lhs, "toValue", 0) == 0) { - /* MOB - rc */ - ejsWriteVar(ep, lhs, ep->result, EJS_SHALLOW_COPY); - } else { - if (ejsRunMethod(ep, lhs, "toString", 0) == 0) { - /* MOB - rc */ - ejsWriteVar(ep, lhs, ep->result, EJS_SHALLOW_COPY); - } - } - - } else { - if (ejsRunMethod(ep, lhs, "toString", 0) == 0) { - /* MOB - rc */ - ejsWriteVar(ep, lhs, ep->result, EJS_SHALLOW_COPY); - } else { - if (ejsRunMethod(ep, lhs, "toValue", 0) == 0) { - /* MOB - rc */ - ejsWriteVar(ep, lhs, ep->result, EJS_SHALLOW_COPY); - } - } - } - /* Nothing more can be done */ - } - - if (rhs->type == EJS_TYPE_OBJECT && - (lhs->type != EJS_TYPE_OBJECT && - (lhs->type != EJS_TYPE_UNDEFINED && lhs->type != EJS_TYPE_NULL))) { - if (ejsVarIsNumber(lhs)) { - /* If LHS is number, then convert to a value first */ - if (ejsRunMethod(ep, rhs, "toValue", 0) == 0) { - /* MOB - rc */ - ejsWriteVar(ep, rhs, ep->result, EJS_SHALLOW_COPY); - } else { - if (ejsRunMethod(ep, rhs, "toString", 0) == 0) { - /* MOB - rc */ - ejsWriteVar(ep, rhs, ep->result, EJS_SHALLOW_COPY); - } - } - - } else { - /* If LHS is not a number, then convert to a string first */ - if (ejsRunMethod(ep, rhs, "toString", 0) == 0) { - /* MOB - rc */ - ejsWriteVar(ep, rhs, ep->result, EJS_SHALLOW_COPY); - - } else { - if (ejsRunMethod(ep, rhs, "toValue", 0) == 0) { - /* MOB - rc */ - ejsWriteVar(ep, rhs, ep->result, EJS_SHALLOW_COPY); - } - } - } - /* Nothing more can be done */ - } - - /* - * undefined and null are special, in that they don't get promoted when - * comparing. - */ - if (rel == EJS_EXPR_EQ || rel == EJS_EXPR_NOTEQ) { - if (lhs->type == EJS_TYPE_UNDEFINED || - rhs->type == EJS_TYPE_UNDEFINED) { - return evalBoolExpr(ep, - lhs->type == EJS_TYPE_UNDEFINED, - rel, - rhs->type == EJS_TYPE_UNDEFINED); - } - - if (lhs->type == EJS_TYPE_NULL || rhs->type == EJS_TYPE_NULL) { - return evalBoolExpr(ep, - lhs->type == EJS_TYPE_NULL, - rel, - rhs->type == EJS_TYPE_NULL); - } - } - - /* - * From here on, lhs and rhs may contain allocated data (strings), so - * we must always destroy before overwriting. - */ - - /* - * Only allow a few bool operations. Otherwise convert to number. - */ - if (lhs->type == EJS_TYPE_BOOL && rhs->type == EJS_TYPE_BOOL && - (rel != EJS_EXPR_EQ && rel != EJS_EXPR_NOTEQ && - rel != EJS_EXPR_BOOL_COMP)) { - ejsWriteVarAsNumber(ep, lhs, ejsVarToNumber(lhs)); - } - - /* - * Types do not match, so try to coerce the right operand to match the left - * But first, try to convert a left operand that is a numeric stored as a - * string, into a numeric. - */ - if (lhs->type != rhs->type) { - if (lhs->type == EJS_TYPE_STRING) { - if (stringIsNumber(lhs->string)) { - ejsWriteVarAsNumber(ep, lhs, ejsVarToNumber(lhs)); - - /* Examine further below */ - - } else { - /* - * Convert the RHS to a string - * MOB rc - */ - str = ejsVarToString(ep, rhs); - ejsWriteVarAsString(ep, rhs, str); - } - -#if BLD_FEATURE_FLOATING_POINT - } else if (lhs->type == EJS_TYPE_FLOAT) { - /* - * Convert rhs to floating - */ - ejsWriteVarAsFloat(ep, rhs, ejsVarToFloat(rhs)); - -#endif -#if BLD_FEATURE_INT64 - } else if (lhs->type == EJS_TYPE_INT64) { - /* - * Convert the rhs to 64 bit - */ - ejsWriteVarAsInteger64(ep, rhs, ejsVarToInteger64(rhs)); -#endif - } else if (lhs->type == EJS_TYPE_BOOL || lhs->type == EJS_TYPE_INT) { - - if (rhs->type == EJS_TYPE_STRING) { - if (stringIsNumber(rhs->string)) { - ejsWriteVarAsNumber(ep, rhs, ejsVarToNumber(rhs)); - } else { - /* - * Convert to lhs to a string - */ - str = ejsVarToString(ep, lhs); - /* MOB -- rc */ - if (str) { - ejsWriteVarAsString(ep, lhs, str); - } - } - -#if BLD_FEATURE_FLOATING_POINT - } else if (rhs->type == EJS_TYPE_FLOAT) { - /* - * Convert lhs to floating - */ - ejsWriteVarAsFloat(ep, lhs, ejsVarToFloat(lhs)); -#endif - - } else { - /* - * Forcibly convert both operands to numbers - */ - ejsWriteVarAsNumber(ep, lhs, ejsVarToNumber(lhs)); - ejsWriteVarAsNumber(ep, rhs, ejsVarToNumber(rhs)); - } - } - } - - /* - * We have failed to coerce the types to be the same. Special case here - * for undefined and null. We need to allow comparisions against these - * special values. - */ - if (lhs->type == EJS_TYPE_UNDEFINED || lhs->type == EJS_TYPE_NULL) { - switch (rel) { - case EJS_EXPR_EQ: - lval = lhs->type == rhs->type; - break; - case EJS_EXPR_NOTEQ: - lval = lhs->type != rhs->type; - break; - case EJS_EXPR_BOOL_COMP: - lval = ! ejsVarToBoolean(rhs); - break; - default: - ejsWriteVar(ep, ep->result, rhs, EJS_SHALLOW_COPY); - return 0; - } - ejsWriteVarAsBoolean(ep, ep->result, lval); - return 0; - } - - /* - * Types are the same here - */ - switch (lhs->type) { - default: - case EJS_TYPE_UNDEFINED: - case EJS_TYPE_NULL: - /* Should be handled above */ - mprAssert(0); - return 0; - - case EJS_TYPE_STRING_CMETHOD: - case EJS_TYPE_CMETHOD: - case EJS_TYPE_METHOD: - case EJS_TYPE_PTR: - ejsWriteVarAsBoolean(ep, ep->result, 0); - return 0; - - case EJS_TYPE_OBJECT: - rc = evalObjExpr(ep, lhs, rel, rhs); - break; - - case EJS_TYPE_BOOL: - rc = evalBoolExpr(ep, lhs->boolean, rel, rhs->boolean); - break; - -#if BLD_FEATURE_FLOATING_POINT - case EJS_TYPE_FLOAT: - rc = evalFloatExpr(ep, lhs->floating, rel, rhs->floating); - break; -#endif - - case EJS_TYPE_INT: - rc = evalNumericExpr(ep, (EjsNum) lhs->integer, rel, - (EjsNum) rhs->integer); - break; - -#if BLD_FEATURE_INT64 - case EJS_TYPE_INT64: - rc = evalNumericExpr(ep, (EjsNum) lhs->integer64, rel, - (EjsNum) rhs->integer64); - break; -#endif - - case EJS_TYPE_STRING: - rc = evalStringExpr(ep, lhs, rel, rhs); - } - - /* MOB */ - if (lhs->type == EJS_TYPE_OBJECT) { - ejsMakeObjLive(lhs, 0); - mprAssert(lhs->objectState->alive == 0); - } - if (rhs->type == EJS_TYPE_OBJECT) { - ejsMakeObjLive(rhs, 0); - mprAssert(rhs->objectState->alive == 0); - } - - return rc; -} - -/******************************************************************************/ -#if BLD_FEATURE_FLOATING_POINT -/* - * Expressions with floating operands - */ - -static int evalFloatExpr(Ejs *ep, double l, int rel, double r) -{ - double lval; - int logical; - - lval = 0; - logical = 0; - - switch (rel) { - case EJS_EXPR_PLUS: - lval = l + r; - break; - case EJS_EXPR_INC: - lval = l + 1; - break; - case EJS_EXPR_MINUS: - lval = l - r; - break; - case EJS_EXPR_DEC: - lval = l - 1; - break; - case EJS_EXPR_MUL: - lval = l * r; - break; - case EJS_EXPR_DIV: - lval = l / r; - break; - default: - logical++; - break; - } - - /* - * Logical operators - */ - if (logical) { - - switch (rel) { - case EJS_EXPR_EQ: - lval = l == r; - break; - case EJS_EXPR_NOTEQ: - lval = l != r; - break; - case EJS_EXPR_LESS: - lval = (l < r) ? 1 : 0; - break; - case EJS_EXPR_LESSEQ: - lval = (l <= r) ? 1 : 0; - break; - case EJS_EXPR_GREATER: - lval = (l > r) ? 1 : 0; - break; - case EJS_EXPR_GREATEREQ: - lval = (l >= r) ? 1 : 0; - break; - case EJS_EXPR_BOOL_COMP: - lval = (r == 0) ? 1 : 0; - break; - default: - ejsError(ep, EJS_SYNTAX_ERROR, "Bad operator %d", rel); - return -1; - } - ejsWriteVarAsBoolean(ep, ep->result, lval != 0); - - } else { - ejsWriteVarAsFloat(ep, ep->result, lval); - } - return 0; -} - -#endif /* BLD_FEATURE_FLOATING_POINT */ -/******************************************************************************/ -/* - * Expressions with object operands - */ - -static int evalObjExpr(Ejs *ep, EjsVar *lhs, int rel, EjsVar *rhs) -{ - int lval; - - switch (rel) { - case EJS_EXPR_EQ: - lval = lhs->objectState == rhs->objectState; - break; - case EJS_EXPR_NOTEQ: - lval = lhs->objectState != rhs->objectState; - break; - default: - ejsError(ep, EJS_SYNTAX_ERROR, "Bad operator %d", rel); - return -1; - } - ejsWriteVarAsBoolean(ep, ep->result, lval); - return 0; -} - -/******************************************************************************/ -/* - * Expressions with boolean operands - */ - -static int evalBoolExpr(Ejs *ep, int l, int rel, int r) -{ - int lval; - - switch (rel) { - case EJS_EXPR_EQ: - lval = l == r; - break; - case EJS_EXPR_NOTEQ: - lval = l != r; - break; - case EJS_EXPR_BOOL_COMP: - lval = (r == 0) ? 1 : 0; - break; - default: - ejsError(ep, EJS_SYNTAX_ERROR, "Bad operator %d", rel); - return -1; - } - ejsWriteVarAsBoolean(ep, ep->result, lval); - return 0; -} - -/******************************************************************************/ -/* - * Expressions with numeric operands - */ - -static int evalNumericExpr(Ejs *ep, EjsNum l, int rel, EjsNum r) -{ - EjsNum lval; - int logical; - - lval = 0; - logical = 0; - - switch (rel) { - case EJS_EXPR_PLUS: - lval = l + r; - break; - case EJS_EXPR_INC: - lval = l + 1; - break; - case EJS_EXPR_MINUS: - lval = l - r; - break; - case EJS_EXPR_DEC: - lval = l - 1; - break; - case EJS_EXPR_MUL: - lval = l * r; - break; - case EJS_EXPR_DIV: - if (r != 0) { - lval = l / r; - } else { - ejsError(ep, EJS_RANGE_ERROR, "Divide by zero"); - return -1; - } - break; - case EJS_EXPR_MOD: - if (r != 0) { - lval = l % r; - } else { - ejsError(ep, EJS_RANGE_ERROR, "Modulo zero"); - return -1; - } - break; - case EJS_EXPR_LSHIFT: - lval = l << r; - break; - case EJS_EXPR_RSHIFT: - lval = l >> r; - break; - - default: - logical++; - break; - } - - /* - * Logical operators - */ - if (logical) { - - switch (rel) { - case EJS_EXPR_EQ: - lval = l == r; - break; - case EJS_EXPR_NOTEQ: - lval = l != r; - break; - case EJS_EXPR_LESS: - lval = (l < r) ? 1 : 0; - break; - case EJS_EXPR_LESSEQ: - lval = (l <= r) ? 1 : 0; - break; - case EJS_EXPR_GREATER: - lval = (l > r) ? 1 : 0; - break; - case EJS_EXPR_GREATEREQ: - lval = (l >= r) ? 1 : 0; - break; - case EJS_EXPR_BOOL_COMP: - lval = (r == 0) ? 1 : 0; - break; - default: - ejsError(ep, EJS_SYNTAX_ERROR, "Bad operator %d", rel); - return -1; - } - ejsWriteVarAsBoolean(ep, ep->result, lval != 0); - - } else { - ejsWriteVarAsNumber(ep, ep->result, lval); - } - return 0; -} - -/******************************************************************************/ -/* - * Expressions with string operands - */ - -static int evalStringExpr(Ejs *ep, EjsVar *lhs, int rel, EjsVar *rhs) -{ - int lval; - - mprAssert(ep); - mprAssert(lhs); - mprAssert(rhs); - - switch (rel) { - case EJS_EXPR_LESS: - lval = strcmp(lhs->string, rhs->string) < 0; - break; - case EJS_EXPR_LESSEQ: - lval = strcmp(lhs->string, rhs->string) <= 0; - break; - case EJS_EXPR_GREATER: - lval = strcmp(lhs->string, rhs->string) > 0; - break; - case EJS_EXPR_GREATEREQ: - lval = strcmp(lhs->string, rhs->string) >= 0; - break; - case EJS_EXPR_EQ: - lval = strcmp(lhs->string, rhs->string) == 0; - break; - case EJS_EXPR_NOTEQ: - lval = strcmp(lhs->string, rhs->string) != 0; - break; - case EJS_EXPR_PLUS: - /* - * This differs from all the above operations. We append rhs to lhs. - */ - ejsClearVar(ep, ep->result); - ejsStrcat(ep, ep->result, lhs); - ejsStrcat(ep, ep->result, rhs); - return 0; - - case EJS_EXPR_INC: - case EJS_EXPR_DEC: - case EJS_EXPR_MINUS: - case EJS_EXPR_DIV: - case EJS_EXPR_MOD: - case EJS_EXPR_LSHIFT: - case EJS_EXPR_RSHIFT: - default: - ejsSyntaxError(ep, "Bad operator"); - return -1; - } - - ejsWriteVarAsBoolean(ep, ep->result, lval); - return 0; -} - -/******************************************************************************/ -/* - * Evaluate a method. obj is set to the current object if a method is being - * run. - */ - -static int evalMethod(Ejs *ep, EjsVar *obj, EjsProc *proc, int flags) -{ - EjsProperty *pp; - EjsVar *saveThis, *prototype; - int saveThisPerm, rc, fid; - - mprAssert(ep); - - rc = 0; - fid = -1; - saveThis = 0; - saveThisPerm = 0; - prototype = proc->fn; - - if (prototype == 0) { - ejsError(ep, EJS_EVAL_ERROR, "Undefined method"); - return EJS_STATE_ERR; - } - - if (prototype->type == EJS_TYPE_OBJECT) { - prototype = ejsGetPropertyAsVar(ep, prototype, proc->procName); - } - - if (prototype) { - /* - * Create a new variable stack frame. ie. new local variables. - * Some C methods (eg. include) don't create a new local context. - */ - if (! (prototype->flags & EJS_NO_LOCAL)) { - fid = ejsOpenBlock(ep); - if (fid < 0) { - return EJS_STATE_ERR; - } - mprAssert(ejsBlockInUse(ep->local)); - - pp = ejsSetProperty(ep, ep->local, "this", obj); - ejsMakePropertyEnumerable(pp, 0); - - /* - * Optimization. Save "this" during this block. - */ - saveThis = ep->thisObject; - ep->thisObject = ejsGetVarPtr(pp); - saveThisPerm = ejsMakeObjPermanent(saveThis, 1); - } - - switch (prototype->type) { - default: - mprAssert(0); - break; - - case EJS_TYPE_STRING_CMETHOD: - rc = callStringCMethod(ep, obj, proc, prototype); - break; - - case EJS_TYPE_CMETHOD: - rc = callCMethod(ep, obj, proc, prototype); - break; - - case EJS_TYPE_METHOD: - rc = callMethod(ep, obj, proc, prototype); - break; - } - - if (fid >= 0) { - ejsMakeObjPermanent(saveThis, saveThisPerm); - ep->thisObject = saveThis; - mprAssert(ejsBlockInUse(ep->local)); - mprAssert(ejsBlockInUse(ep->thisObject)); - ejsCloseBlock(ep, fid); - } - } - - return rc; -} - -/******************************************************************************/ -/* - * Create a new object and call all required constructors. - * obj may be null in which case we look globally for className. - */ - -EjsVar *ejsCreateObjUsingArgvInternal(EJS_LOC_DEC(ep, loc), EjsVar *obj, - const char *className, MprArray *args) -{ - EjsVar *baseClass, *objectClass, *thisObj; - int rc; - - mprAssert(className && *className); - - /* - * Create a new object of the required class and pass it into the - * constructor as the "this" local variable. - */ - baseClass = ejsGetClass(ep, obj, className); - if (baseClass == 0) { - - if (obj && obj->objectState->className && - strcmp(obj->objectState->className, className) == 0) { - /* - * Handle case where we are calling the constructor inside - * the class. In this case, obj == baseClass. - */ - thisObj = ejsCreateSimpleObjUsingClassInt(EJS_LOC_PASS(ep, loc), - obj); - - } else { - - /* - * If the baseClass does not exist, try to create an Object - * We do this for compatibility with JS 1.5 style new Function. - * MOB -- but this masks an error if we really need className. - */ - objectClass = ejsGetClass(ep, 0, "Object"); - thisObj = ejsCreateSimpleObjUsingClassInt(EJS_LOC_PASS(ep, loc), - objectClass); - } - - } else { - thisObj = ejsCreateSimpleObjUsingClassInt(EJS_LOC_PASS(ep, loc), - baseClass); - } - - if (thisObj == 0) { - ejsMemoryError(ep); - return 0; - } - - /* - * Make the object permanent. While currently not alive, the constructor - * below may make the object alive. - */ - ejsMakeObjPermanent(thisObj, 1); - mprAssert(! ejsObjIsCollectable(thisObj)); - - rc = 0; - if (baseClass) { - if (! baseClass->objectState->noConstructor) { - rc = callConstructor(ep, thisObj, baseClass, args); - } - } else { - /* - * className is the function name when calling new on functions - */ - rc = ejsRunMethod(ep, thisObj, className, args); - } - - /* - * Constructor may change the type to a non-object. - * Function() does this. Ensure object is not collectable yet. - */ - if (ejsVarIsObject(thisObj)) { - ejsMakeObjPermanent(thisObj, 0); - ejsMakeObjLive(thisObj, 0); - } - - if (rc < 0) { - if (rc == MPR_ERR_NOT_FOUND) { - /* No constructor (default) */ - return thisObj; - } - if (! (ep->flags & EJS_FLAGS_EXIT)) { - if (! ep->gotException) { - ejsMemoryError(ep); - } - } - ejsFreeVar(ep, thisObj); - return 0; - } - - mprAssert(ejsBlockInUse(thisObj)); - - return thisObj; -} - -/******************************************************************************/ -/* - * Local vars - */ - -typedef struct CallCons { - EjsVar *subClassConstructor, *subClass, *method; -} CallCons; - -/* - * Create a new object and call all required constructors. - */ - -static int callConstructor(Ejs *ep, EjsVar *thisObj, EjsVar *baseClass, - MprArray *args) -{ - CallCons *sp; - int state; - - if ((sp = pushFrame(ep, sizeof(CallCons))) == 0) { - return EJS_STATE_ERR; - } - - mprAssert(baseClass); - mprAssert(baseClass->objectState); - - state = 0; - - /* - * method will be null if there is no constructor for this class - */ - sp->method = ejsGetPropertyAsVar(ep, baseClass, - baseClass->objectState->className); - - if (sp->method == 0 || !ejsVarIsMethod(sp->method) || - !sp->method->callsSuper) { - /* - * Invoke base class constructors in reverse order (RECURSIVE) - */ - sp->subClass = baseClass->objectState->baseClass; - if (sp->subClass) { - - /* - * Note that the Object class does not have a constructor for - * speed. Construction for the base Object is done via - * ejsCreateObj above. The code below will invoke constructors - * in the right order (bottom up) via recursion. MOB -- need to - * scan for super() MOB -- Bug. Fails poorly if no constructor. - * Should allows this and invoke a default constructor. - */ - sp->subClassConstructor = ejsGetPropertyAsVar(ep, sp->subClass, - sp->subClass->objectState->className); - - if (sp->subClassConstructor) { - - if (callConstructor(ep, thisObj, sp->subClass, 0) < 0) { - if (! ep->gotException) { - ejsMemoryError(ep); - } - goto err; - } - } - } - } - - if (sp->method) { - /* - * Finally, invoke the constructor for this class itself. - */ - state = runMethod(ep, thisObj, sp->method, - baseClass->objectState->className, args); - } - -done: - popFrame(ep, sizeof(CallCons)); - return state; - -err: - state = EJS_STATE_ERR; - goto done; -} - -/******************************************************************************/ -/* - * Create a new object and call all required constructors using string args. - * MOB -- would be good to parse constructorArgs for "," and break into - * separate args. - * Returned object is not yet collectable. Will have alive bit cleared. - */ - -EjsVar *ejsCreateObj(Ejs *ep, EjsVar *obj, const char *className, - const char *constructorArgs) -{ - MprArray *args; - EjsVar *newp, *vp; - - args = mprCreateItemArray(ep, 0, 0); - if (args == 0) { - return 0; - } - - if (constructorArgs && *constructorArgs) { - vp = ejsCreateStringVarInternal(EJS_LOC_ARGS(ep), constructorArgs); - - if (mprAddItem(args, vp) < 0) { - mprFree(args); - return 0; - } - } - - newp = ejsCreateObjUsingArgv(ep, obj, className, args); - - ejsFreeMethodArgs(ep, args); - - mprAssert(! ejsObjIsCollectable(newp)); - mprAssert(ejsBlockInUse(newp)); - - return newp; -} - -/******************************************************************************/ - -static int callStringCMethod(Ejs *ep, EjsVar *obj, EjsProc *proc, - EjsVar *prototype) -{ - EjsVar **argValues; - MprArray *actualArgs; - char **argBuf, *str; - int i, rc; - - actualArgs = proc->args; - argValues = (EjsVar**) actualArgs->items; - - if (actualArgs->length > 0) { - argBuf = mprAlloc(ep, actualArgs->length * sizeof(char*)); - for (i = 0; i < actualArgs->length; i++) { - str = ejsVarToString(ep, argValues[i]); - /* MOB rc */ - argBuf[i] = mprStrdup(ep, str); - } - } else { - argBuf = 0; - } - - /* - * Call the method depending on the various handle flags - */ - ep->userData = prototype->cMethodWithStrings.userData; - if (prototype->flags & EJS_ALT_HANDLE) { - /* - * Used by the AppWeb GaCompat module. The alt handle is set to the - * web server request struct - */ - rc = ((EjsAltStringCMethod) - prototype->cMethodWithStrings.fn) - (ep, ep->altHandle, obj, actualArgs->length, argBuf); - - } else if (prototype->flags & EJS_PRIMARY_HANDLE) { - /* - * Used by ESP. The primary handle is set to the esp struct - */ - rc = (prototype->cMethodWithStrings.fn)(ep->primaryHandle, - obj, actualArgs->length, argBuf); - - } else { - /* - * Used EJS for the standard procs - */ - rc = (prototype->cMethodWithStrings.fn)(ep, obj, actualArgs->length, - argBuf); - } - - if (actualArgs->length > 0) { - for (i = 0; i < actualArgs->length; i++) { - mprFree(argBuf[i]); - } - mprFree(argBuf); - } - ep->userData = 0; - - return rc; -} - -/******************************************************************************/ - -static int callCMethod(Ejs *ep, EjsVar *obj, EjsProc *proc, EjsVar *prototype) -{ - EjsVar **argValues; - MprArray *actualArgs; - int rc; - - actualArgs = proc->args; - argValues = (EjsVar**) actualArgs->items; - - ep->userData = prototype->cMethod.userData; - - /* - * Call the method depending on the various handle flags - * Sometimes cMethod.fn is NULL if there is no constructor for - * an object. - */ - if (prototype->flags & EJS_ALT_HANDLE) { - /* - * Use by the GaCompat module. The alt handle is set to the - * web server request struct - */ - rc = ((EjsAltCMethod) prototype->cMethod.fn) - (ep, ep->altHandle, obj, actualArgs->length, argValues); - - } else if (prototype->flags & EJS_PRIMARY_HANDLE) { - /* - * Used by ESP. The primary handle is set to the esp struct - */ - rc = (prototype->cMethod.fn) - (ep->primaryHandle, obj, actualArgs->length, argValues); - - } else { - /* - * Used EJS for the standard procs - */ - rc = (prototype->cMethod.fn)(ep, obj, actualArgs->length, argValues); - } - - ep->userData = 0; - - return rc; -} - -/******************************************************************************/ -/* - * Local vars - */ - -typedef struct CallMethod { - MprArray *formalArgs, *actualArgs; - EjsVar *arguments, *callee, **argValues; - char **argNames, buf[16]; - int i, argumentsObj; -} CallMethod; - - -static int callMethod(Ejs *ep, EjsVar *obj, EjsProc *proc, EjsVar *prototype) -{ - CallMethod *sp; - int i; - - if ((sp = pushFrame(ep, sizeof(CallMethod))) == 0) { - return EJS_STATE_ERR; - } - - sp->arguments = 0; - sp->callee = 0; - - sp->actualArgs = proc->args; - sp->argValues = (EjsVar**) sp->actualArgs->items; - sp->formalArgs = prototype->method.args; - sp->argNames = (char**) sp->formalArgs->items; - - /* - * Only create arguments and callee if the function actually uses them - */ - sp->argumentsObj = 0; - if (strstr(prototype->method.body, "arguments") != 0) { - sp->argumentsObj++; - - /* - * Create the arguments and callee variables - * MOB -- should we make real arrays here ? YES - */ - sp->arguments = ejsCreateSimpleObj(ep, "Object"); - ejsSetVarName(ep, sp->arguments, "arguments"); - mprAssert(! ejsObjIsCollectable(sp->arguments)); - - sp->callee = ejsCreateSimpleObj(ep, "Object"); - ejsSetVarName(ep, sp->callee, "callee"); - mprAssert(! ejsObjIsCollectable(sp->callee)); - - /* - * Overwrite the length property - */ - ejsSetPropertyToInteger(ep, sp->arguments, "length", - sp->actualArgs->length); - ejsSetPropertyToInteger(ep, sp->callee, "length", - sp->formalArgs->length); - } - - /* - * Define all the agruments to be set to the actual parameters - */ - for (i = 0; i < sp->formalArgs->length; i++) { - if (i >= sp->actualArgs->length) { - /* MOB -- return code */ - ejsCreateProperty(ep, ep->local, sp->argNames[i]); - - } else { - /* MOB -- return code */ - ejsSetProperty(ep, ep->local, sp->argNames[i], sp->argValues[i]); - } - } - - if (sp->argumentsObj) { - for (i = 0; i < sp->actualArgs->length; i++) { - mprItoa(sp->buf, sizeof(sp->buf), i); - ejsSetProperty(ep, sp->arguments, sp->buf, sp->argValues[i]); - } - - ejsSetPropertyAndFree(ep, sp->arguments, "callee", sp->callee); - ejsSetPropertyAndFree(ep, ep->local, "arguments", sp->arguments); - } - - /* - * Actually run the method - */ - - i = ejsEvalScript(ep, prototype->method.body, 0); - - popFrame(ep, sizeof(CallMethod)); - return i; -} - -/******************************************************************************/ -/* - * Run a method. Obj is set to "this" object. MethodName must exist in it - * or in a sub class. - */ - -int ejsRunMethod(Ejs *ep, EjsVar *obj, const char *methodName, MprArray *args) -{ - EjsProperty *pp; - EjsProc proc, *saveProc; - int rc; - - mprAssert(obj); - mprAssert(methodName && *methodName); - - pp = ejsGetProperty(ep, obj, methodName); - if (pp == 0) { - /* MOB -- this should be all in some common accessor routine */ - pp = ejsGetProperty(ep, ep->local, methodName); - if (pp == 0) { - pp = ejsGetProperty(ep, ep->global, methodName); - if (pp == 0) { - ejsError(ep, EJS_REFERENCE_ERROR, - "Undefined method \"%s\"", methodName); - return MPR_ERR_NOT_FOUND; - } - } - } - - saveProc = ep->proc; - ep->proc = &proc; - - memset(&proc, 0, sizeof(EjsProc)); - - ejsClearVar(ep, ep->result); - - /* MOB -- if closures are going to work, we need to have proc be an - Object and let the GC look after it */ - - proc.fn = &pp->var; - if (proc.fn == 0 || proc.fn->type == EJS_TYPE_UNDEFINED) { - ep->proc = saveProc; - return MPR_ERR_NOT_FOUND; - } - - proc.procName = mprStrdup(ep, methodName); - if (args == 0) { - proc.args = mprCreateItemArray(ep, EJS_INC_ARGS, EJS_MAX_ARGS); - } else { - proc.args = args; - } - - rc = evalMethod(ep, obj, &proc, 0); - - if (args) { - proc.args = 0; - } - freeProc(ep, &proc); - - ep->proc = saveProc; - - return rc; -} - -/******************************************************************************/ -/* - * Run a method. Obj is set to "this" object. MethodName must exist in it - * or in a sub class. - */ - -int ejsRunMethodCmd(Ejs *ep, EjsVar *obj, const char *methodName, - const char *cmdFmt, ...) -{ - MprArray *args; - va_list cmdArgs; - char *buf, *arg, *cp; - int rc; - - mprAssert(methodName && *methodName); - mprAssert(cmdFmt && *cmdFmt); - - va_start(cmdArgs, cmdFmt); - mprAllocVsprintf(MPR_LOC_ARGS(ep), &buf, 0, cmdFmt, cmdArgs); - va_end(cmdArgs); - - args = mprCreateItemArray(ep, EJS_INC_ARGS, EJS_MAX_ARGS); - - for (arg = cp = buf; cp && *cp; cp++) { - if (*cp == ',') { - *cp = 0; - mprAddItem(args, ejsParseVar(ep, arg, 0)); - arg = cp + 1; - } - } - if (cp > arg) { - mprAddItem(args, ejsParseVar(ep, arg, 0)); - } - - rc = ejsRunMethod(ep, obj, methodName, args); - - ejsFreeMethodArgs(ep, args); - mprFree(buf); - - return rc; -} - -/******************************************************************************/ -/* - * Run a method. Obj is set to "this" object. - */ - -static int runMethod(Ejs *ep, EjsVar *thisObj, EjsVar *method, - const char *methodName, MprArray *args) -{ - EjsProc proc, *saveProc; - int rc; - - mprAssert(thisObj); - mprAssert(method); - - saveProc = ep->proc; - ep->proc = &proc; - - memset(&proc, 0, sizeof(EjsProc)); - - ejsClearVar(ep, ep->result); - - /* MOB -- if closures are going to work, we need to have proc be an - Object and let the GC look after it */ - - proc.fn = method; - if (proc.fn == 0 || proc.fn->type == EJS_TYPE_UNDEFINED) { - ep->proc = saveProc; - return MPR_ERR_NOT_FOUND; - } - - proc.procName = mprStrdup(ep, methodName); - if (args == 0) { - proc.args = mprCreateItemArray(ep, EJS_INC_ARGS, EJS_MAX_ARGS); - } else { - proc.args = args; - } - - rc = evalMethod(ep, thisObj, &proc, 0); - - if (args) { - proc.args = 0; - } - freeProc(ep, &proc); - - ep->proc = saveProc; - - return rc; -} - -/******************************************************************************/ -/* - * Find which object contains the property given the current context. - * We call this when there is no explicit object and the object must be - * determined by the context. - */ - -static EjsVar *pickSpace(Ejs *ep, int state, const char *property, int flags) -{ - EjsVar *obj; - - mprAssert(ep); - mprAssert(property && *property); - - /* MOB - this is ugly and the logic is confused */ - - if (flags & EJS_FLAGS_GLOBAL) { - obj = ep->global; - - } else if (state == EJS_STATE_DEC || flags & EJS_FLAGS_LOCAL) { - obj = ep->local; - - } else { - /* First look local, then this and finally global */ - - if (ejsGetSimpleProperty(ep, ep->local, property)) { - obj = ep->local; - - } else if (ep->thisObject && - findProperty(ep, ep->thisObject, property, flags)) { - obj = ep->thisObject; - - } else { -#if EJS_ECMA_STND - obj = ep->global; -#else - if (flags & EJS_FLAGS_EXE && - !findProperty(ep, ep->global, property, flags)) { - obj = ep->local; - } else { - obj = ep->global; - } -#endif - } - } - return obj; -} - -/******************************************************************************/ -/* - * Find an object property given a object and a property name. We - * intelligently look in the local and global namespaces depending on - * our state. If not found in local or global, try base classes for method - * names only. Returns the property or NULL. - * MOB -- need to rework this API. - */ - -static EjsProperty *searchSpacesForProperty(Ejs *ep, int state, EjsVar *obj, - char *property, int flags) -{ - EjsProperty *pp; - - if (obj) { - return findProperty(ep, obj, property, flags); - } - - /* MOB -- really should have a search stack */ - - pp = findProperty(ep, ep->local, property, flags); - if (pp == 0 && state != EJS_STATE_DEC) { - - if (ep->thisObject) { - pp = findProperty(ep, ep->thisObject, property, flags); - } - if (pp == 0) { - pp = findProperty(ep, ep->global, property, flags); - } - } - return pp; -} - -/******************************************************************************/ -/* - * Search an object and its base classes to find an object given an object - * an a property name. If not an assignment (LHS), then follow base classes. - * Otherwise, just look in the specified object. - */ - -static EjsProperty *findProperty(Ejs *ep, EjsVar *op, const char *property, - int flags) -{ - /* MOB -- NEW. Remove when EXE fixes are in. */ - if (! (flags & EJS_FLAGS_EXE) && op->type == EJS_TYPE_UNDEFINED) { - return 0; - } - - if (flags & EJS_FLAGS_LHS) { - return ejsGetPropertyPtr(ejsGetSimpleProperty(ep, op, property)); - - } else { - /* - * Follow base classes - */ - return ejsGetPropertyPtr(ejsGetProperty(ep, op, property)); - } -} - -/******************************************************************************/ -/* - * Update result - */ - -static void updateResult(Ejs *ep, int state, int flags, EjsVar *vp) -{ - if (flags & EJS_FLAGS_EXE && state != EJS_STATE_DEC) { - ejsClearVar(ep, ep->result); - if (vp) { - ejsWriteVar(ep, ep->result, vp, EJS_SHALLOW_COPY); - ejsSetVarName(ep, ep->result, vp->propertyName); - } - } -} - -/******************************************************************************/ -/* - * Append to the pointer value - */ - -int ejsStrcat(Ejs *ep, EjsVar *dest, EjsVar *src) -{ - char *oldBuf, *buf, *str; - int oldLen, newLen, len; - - mprAssert(dest); - mprAssert(ejsVarIsString(src)); - - if (ejsVarIsValid(dest)) { - - if (! ejsVarIsString(dest)) { - /* Bad type for dest */ - return -1; - } - - if (! ejsVarIsString(src)) { - str = ejsVarToString(ep, src); - if (str == 0) { - return -1; - } - len = strlen(str); - - } else { - str = src->string; - len = src->length; - } - - oldBuf = dest->string; - oldLen = dest->length; - newLen = oldLen + len + 1; - - if (newLen < MPR_SLAB_STR_MAX) { - buf = oldBuf; - } else { - buf = mprRealloc(ep, oldBuf, newLen); - if (buf == 0) { - return -1; - } - dest->string = buf; - } - memcpy(&buf[oldLen], str, len); - dest->length += len; - - } else { - ejsWriteVarAsString(ep, dest, src->string); - } - return 0; -} - -/******************************************************************************/ -/* - * Exit the script - */ - -void ejsExit(Ejs *ep, int status) -{ - ep->scriptStatus = status; - ep->flags |= EJS_FLAGS_EXIT; -} - -/******************************************************************************/ -/* - * Free an argument list - */ - -static void freeProc(Ejs *ep, EjsProc *proc) -{ - if (proc->args) { - ejsFreeMethodArgs(ep, proc->args); - } - - if (proc->procName) { - mprFree(proc->procName); - proc->procName = NULL; - } -} - -/******************************************************************************/ - -void ejsFreeMethodArgs(Ejs *ep, MprArray *args) -{ - int i; - - for (i = args->length - 1; i >= 0; i--) { - ejsFreeVar(ep, args->items[i]); - mprRemoveItemByIndex(args, i); - } - mprFree(args); -} - -/******************************************************************************/ -/* - * This method removes any new lines. Used for else cases, etc. - */ - -static void removeNewlines(Ejs *ep, int state) -{ - int tid; - - do { - tid = ejsLexGetToken(ep, state); - } while (tid == EJS_TOK_NEWLINE); - - ejsLexPutbackToken(ep, tid, ep->token); -} - -/******************************************************************************/ - -static int getNextNonSpaceToken(Ejs *ep, int state) -{ - int tid; - - do { - tid = ejsLexGetToken(ep, state); - } while (tid == EJS_TOK_NEWLINE); - return tid; -} - -/******************************************************************************/ - -int ejsGetFlags(Ejs *ep) -{ - return ep->flags; -} - -/******************************************************************************/ - -bool ejsIsExiting(Ejs *ep) -{ - return (ep->flags & EJS_FLAGS_EXIT) ? 1: 0; -} - -/******************************************************************************/ - -void ejsClearExiting(Ejs *ep) -{ - ep->flags &= ~EJS_FLAGS_EXIT; -} - -/******************************************************************************/ - -static EjsInput *getInputStruct(Ejs *ep) -{ - EjsInput *input; - - if (ep->inputList) { - input = ep->inputList; - ep->inputList = input->nextInput; - - } else { - input = mprAlloc(ep, sizeof(EjsInput)); - } - return input; -} - -/******************************************************************************/ - -static void freeInputStruct(Ejs *ep, EjsInput *input) -{ - input->nextInput = ep->inputList; - ep->inputList = input; -} - -/******************************************************************************/ - -static void *pushFrame(Ejs *ep, int size) -{ - /* - * Grow down stack - */ - ep->stkPtr -= size; - if (ep->stkPtr < ep->stack) { - mprError(ep, MPR_LOC, "Exceeded parse stack"); - return 0; - } - return ep->stkPtr; -} - -/******************************************************************************/ - -static void *popFrame(Ejs *ep, int size) -{ - ep->stkPtr += size; - if (ep->stkPtr > &ep->stack[EJS_MAX_STACK]) { - mprError(ep, MPR_LOC, "Over poped parse stack"); - return 0; - } - return ep->stkPtr; -} - -/******************************************************************************/ -#else -void ejsParserDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/ejsVar.c b/source4/lib/appweb/ejs-2.0/ejs/ejsVar.c deleted file mode 100644 index 1f8e9266a3..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/ejsVar.c +++ /dev/null @@ -1,4033 +0,0 @@ -/** - * @file ejsVar.c - * @brief Mbedthis Portable Runtime Universal Variable Type - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/******************************* Documentation ********************************/ - -/* - * This module is NOT multithreaded. - * - * Properties are variables that are stored in an object type variable. - * Properties can be primitive data types, other objects or methods. - * Properties are indexed by a character name. - */ - -/********************************** Includes **********************************/ - -#include "ejs.h" - -/***************************** Forward Declarations ***************************/ - -static EjsProperty *allocProperty(Ejs *ep, EjsVar *op, const char *property, - int propertyIndex, EjsProperty *last); -static EjsVar *copyVar(EJS_LOC_DEC(ep, loc), EjsVar *dest, - const EjsVar *src, EjsCopyDepth copyDepth); -static EjsObj *createObj(EJS_LOC_DEC(ep, loc)); -static char *getNextVarToken(char **next, char *tokBuf, int tokBufLen); -static int hash(const char *property); -static void unlinkProperty(EjsObj *obj, EjsPropLink *propLink); -static void linkPropertyBefore(EjsObj *obj, EjsPropLink *at, - EjsPropLink *propLink); -static int sortAllProperties(Ejs *ep, EjsProperty *p1, - EjsProperty *p2, const char *propertyName, int order); -static int sortByProperty(Ejs *ep, EjsProperty *p1, EjsProperty *p2, - const char *propertyName, int order); -static int dupString(MPR_LOC_DEC(ctx, loc), uchar **dest, - const void *src, int nbytes); -#if UNUSED && KEEP -static void linkPropertyAfter(EjsObj *obj, EjsPropLink *at, - EjsPropLink *propLink); -#endif - -static EjsProperty *hashLookup(EjsObj *obj, const char *property, - int *propertyIndex, EjsProperty **hashTail); - -/******************************************************************************/ -/********************************** Var Routines ******************************/ -/******************************************************************************/ - -EjsType ejsGetVarType(EjsVar *vp) -{ - mprAssert(vp); - - return vp->type; -} - -/******************************************************************************/ - -void ejsFreeVar(Ejs *ep, EjsVar *vp) -{ - if (vp) { - ejsClearVar(ep, vp); - ejsFree(ep, vp, EJS_SLAB_VAR); - } -} - -/******************************************************************************/ -#if UNUSED -/* - * Clear the value by freeing any allocated data. This will release objects - * so that later garbage collection can reclaim storage if there are no other - * object references. - */ - -void ejsZeroVar(Ejs *ep, EjsVar *vp) -{ - vp->type = EJS_TYPE_UNDEFINED; - vp->objectState = 0; - vp->method.body = 0; - vp->method.args = 0; - vp->callsSuper = 0; - vp->ptr.destructor = 0; - vp->allocatedData = 0; -} - -#endif -/******************************************************************************/ -/* - * Clear the value by freeing any allocated data. This will release objects - * so that later garbage collection can reclaim storage if there are no other - * object references. - */ - -void ejsClearVar(Ejs *ep, EjsVar *vp) -{ - MprArray *argList; - int i; - - mprAssert(vp); - mprAssert(ep); - - if (! vp->allocatedData) { - vp->type = EJS_TYPE_UNDEFINED; - return; - } - if (vp->type == EJS_TYPE_UNDEFINED) { - return; - } - - switch (vp->type) { - default: - break; - - case EJS_TYPE_STRING: - mprFree(vp->string); - vp->string = 0; - break; - - case EJS_TYPE_OBJECT: - /* - * Set the "alive" bit so that the GC will cleanup if no - * other references. - */ - if (vp->objectState) { - vp->objectState->alive = 1; - } - vp->objectState = 0; - break; - - case EJS_TYPE_METHOD: - argList = vp->method.args; - /* - * MOB OPT -- should be able to do just one mprFree(vp->method.args) - */ - mprFree(vp->method.body); - if (argList) { - for (i = 0; i < argList->length; i++) { - mprFree(argList->items[i]); - } - mprFree(vp->method.args); - } - vp->method.args = 0; - vp->method.body = 0; - vp->callsSuper = 0; - break; - - case EJS_TYPE_PTR: - if (vp->ptr.destructor) { - (vp->ptr.destructor)(ep, vp); - } - break; - } - - vp->type = EJS_TYPE_UNDEFINED; - vp->allocatedData = 0; -} - -/******************************************************************************/ -/* - * Initialize an undefined value. - */ - -EjsVar *ejsCreateUndefinedVar(Ejs *ep) -{ - EjsVar *vp; - - mprAssert(ep); - - vp = ejsAllocVar(EJS_LOC_ARGS(ep)); - if (vp) { - vp->type = EJS_TYPE_UNDEFINED; - } - return vp; -} - -/******************************************************************************/ -/* - * Initialize an null value. - */ - -EjsVar *ejsCreateNullVar(Ejs *ep) -{ - EjsVar *vp; - - mprAssert(ep); - - vp = ejsAllocVar(EJS_LOC_ARGS(ep)); - if (vp) { - vp->type = EJS_TYPE_NULL; - } - return vp; -} - -/******************************************************************************/ - -EjsVar *ejsCreateBoolVar(Ejs *ep, int value) -{ - EjsVar *vp; - - mprAssert(ep); - - vp = ejsAllocVar(EJS_LOC_ARGS(ep)); - if (vp) { - vp->type = EJS_TYPE_BOOL; - vp->boolean = value; - } - return vp; -} - -/******************************************************************************/ -/* - * Initialize a C method. - */ - -EjsVar *ejsCreateCMethodVar(Ejs *ep, EjsCMethod fn, void *userData, int flags) -{ - EjsVar *vp; - - mprAssert(ep); - - vp = ejsAllocVar(EJS_LOC_ARGS(ep)); - if (vp) { - vp->type = EJS_TYPE_CMETHOD; - vp->cMethod.fn = fn; - vp->cMethod.userData = userData; - vp->flags = flags; - } - return vp; -} - -/******************************************************************************/ -/* - * Initialize a C method. - */ - -EjsVar *ejsCreateStringCMethodVar(Ejs *ep, EjsStringCMethod fn, - void *userData, int flags) -{ - EjsVar *vp; - - mprAssert(ep); - mprAssert(fn); - - vp = ejsAllocVar(EJS_LOC_ARGS(ep)); - if (vp) { - vp->type = EJS_TYPE_STRING_CMETHOD; - vp->cMethodWithStrings.fn = fn; - vp->cMethodWithStrings.userData = userData; - vp->flags = flags; - } - return vp; -} - -/******************************************************************************/ -/* - * Initialize an opaque pointer. - */ - -EjsVar *ejsCreatePtrVar(Ejs *ep, void *ptr, EjsDestructor destructor) -{ - EjsVar *vp; - - mprAssert(ep); - mprAssert(ptr); - - vp = ejsAllocVar(EJS_LOC_ARGS(ep)); - if (vp) { - vp->type = EJS_TYPE_PTR; - vp->ptr.userPtr = ptr; - vp->ptr.destructor = destructor; - vp->allocatedData = 1; - } - return vp; -} - -/******************************************************************************/ -#if BLD_FEATURE_FLOATING_POINT -/* - * Initialize a floating value. - */ - -EjsVar *ejsCreateFloatVar(Ejs *ep, double value) -{ - EjsVar *vp; - - mprAssert(ep); - - vp = ejsAllocVar(EJS_LOC_ARGS(ep)); - if (vp) { - vp->type = EJS_TYPE_FLOAT; - vp->floating = value; - } - return vp; -} - -#endif -/******************************************************************************/ -/* - * Initialize an integer value. - */ - -EjsVar *ejsCreateIntegerVar(Ejs *ep, int value) -{ - EjsVar *vp; - - mprAssert(ep); - - vp = ejsAllocVar(EJS_LOC_ARGS(ep)); - if (vp) { - vp->type = EJS_TYPE_INT; - vp->integer = value; - } - return vp; -} - -/******************************************************************************/ -#if BLD_FEATURE_INT64 -/* - * Initialize a 64-bit integer value. - */ - -EjsVar *ejsCreateInteger64Var(Ejs *ep, int64 value) -{ - EjsVar *vp; - - mprAssert(ep); - - vp = ejsAllocVar(EJS_LOC_ARGS(ep)); - if (vp) { - vp->type = EJS_TYPE_INT64; - vp->integer64 = value; - } - return vp; -} - -#endif /* BLD_FEATURE_INT64 */ -/******************************************************************************/ -/* - * Initialize an number variable. Type is defined by configure. - */ - -EjsVar *ejsCreateNumberVar(Ejs *ep, EjsNum value) -{ - EjsVar *vp; - - mprAssert(ep); - - vp = ejsAllocVar(EJS_LOC_ARGS(ep)); - mprAssert(vp); - - if (vp) { - vp->type = BLD_FEATURE_NUM_TYPE_ID; -#if BLD_FEATURE_NUM_TYPE_ID == EJS_TYPE_INT64 - vp->integer64 = value; -#elif BLD_FEATURE_NUM_TYPE_ID == EJS_TYPE_FLOAT - vp->float = value; -#else - vp->integer = value; -#endif - } - return vp; -} - -/******************************************************************************/ -/* - * Initialize a (bare) JavaScript method. args and body can be null. - */ - -EjsVar *ejsCreateMethodVar(Ejs *ep, const char *body, MprArray *args, int flags) -{ - EjsVar *vp; - int i; - - mprAssert(ep); - - vp = ejsAllocVar(EJS_LOC_ARGS(ep)); - mprAssert(vp); - - if (vp == 0) { - return 0; - } - - vp->type = EJS_TYPE_METHOD; - - vp->allocatedData = 1; - - vp->method.args = mprCreateItemArray(ep, EJS_INC_ARGS, EJS_MAX_ARGS); - if (vp->method.args == 0) { - mprAssert(vp->method.args); - ejsFreeVar(ep, vp); - return 0; - } - - if (args) { - for (i = 0; i < args->length; i++) { - mprAddItem(vp->method.args, - mprStrdup(vp->method.args, mprGetItem(args, i))); - } - } - vp->method.body = mprStrdup(vp->method.args, body); - - if (vp->method.body == 0) { - ejsFreeVar(ep, vp); - return 0; - } - vp->flags = flags; - - return vp; -} - -/******************************************************************************/ -/* - * Initialize an object variable. - */ - -EjsVar *ejsCreateObjVarInternal(EJS_LOC_DEC(ep, loc)) -{ - EjsVar *vp; - - mprAssert(ep); - - vp = ejsAllocVar(EJS_LOC_PASS(ep, loc)); - mprAssert(vp); - - if (vp) { - vp->type = EJS_TYPE_OBJECT; - vp->objectState = createObj(EJS_LOC_PASS(ep, loc)); - if (vp->objectState == 0) { - ejsFreeVar(ep, vp); - return 0; - } - vp->allocatedData = 1; - } - return vp; -} - -/******************************************************************************/ -/* - * Initialize a string value. - */ - -EjsVar *ejsCreateStringVarInternal(EJS_LOC_DEC(ep, loc), const char *value) -{ - EjsVar *vp; - - mprAssert(ep); - - vp = ejsAllocVar(EJS_LOC_PASS(ep, loc)); - mprAssert(vp); - - if (vp) { - vp->type = EJS_TYPE_STRING; - vp->string = mprStrdupInternal(EJS_LOC_PASS(ep, loc), value); - if (vp->string == 0) { - ejsFreeVar(ep, vp); - return 0; - } - vp->length = strlen(vp->string); - vp->allocatedData = 1; - } - return vp; -} - -/******************************************************************************/ -/* - * Initialize a binary string value. - */ - -EjsVar *ejsCreateBinaryStringVar(Ejs *ep, const uchar *value, int len) -{ - EjsVar *vp; - - mprAssert(ep); - - vp = ejsAllocVar(EJS_LOC_ARGS(ep)); - if (vp) { - vp->type = EJS_TYPE_STRING; - vp->length = dupString(MPR_LOC_ARGS(ep), &vp->ustring, value, len); - if (vp->length < 0) { - ejsFreeVar(ep, vp); - return 0; - } - vp->allocatedData = 1; - } - return vp; -} - -/******************************************************************************/ - -void ejsSetClassName(Ejs *ep, EjsVar *vp, const char *name) -{ - EjsObj *obj; - - if (vp == 0 || !ejsVarIsObject(vp) || vp->objectState == 0) { - mprAssert(0); - return; - } - obj = vp->objectState; - - if (obj->className) { - mprFree(obj->className); - } - obj->className = mprStrdup(ep, name); -} - -/******************************************************************************/ - -EjsVar *ejsDupVarInternal(EJS_LOC_DEC(ep, loc), EjsVar *src, - EjsCopyDepth copyDepth) -{ - EjsVar *vp; - - vp = ejsAllocVar(EJS_LOC_PASS(ep, loc)); - if (vp == 0) { - return 0; - } - - vp->type = EJS_TYPE_UNDEFINED; - - return copyVar(EJS_LOC_PASS(ep, loc), vp, src, copyDepth); -} - -/******************************************************************************/ -/* - * Set a var to a new value - */ - -EjsVar *ejsWriteVarInternal(EJS_LOC_DEC(ep, loc), EjsVar *dest, - const EjsVar *src, EjsCopyDepth copyDepth) -{ - mprAssert(dest); - mprAssert(src); - - return copyVar(EJS_LOC_PASS(ep, loc), dest, src, copyDepth); -} - -/******************************************************************************/ -/* - * Set a var using a new bool value - */ - -EjsVar *ejsWriteVarAsBoolean(Ejs *ep, EjsVar *dest, int value) -{ - mprAssert(dest); - - if (dest->type != EJS_TYPE_UNDEFINED) { - ejsClearVar(ep, dest); - } - - dest->type = EJS_TYPE_BOOL; - dest->boolean = value; - dest->allocatedData = 0; - dest->flags = 0; - - return dest; -} - -/******************************************************************************/ -/* - * Set a var using a new C Method - */ - -EjsVar *ejsWriteVarAsCMethod(Ejs *ep, EjsVar *dest, EjsCMethod fn, - void *userData, int flags) -{ - mprAssert(dest); - - if (dest->type != EJS_TYPE_UNDEFINED) { - ejsClearVar(ep, dest); - } - - dest->type = EJS_TYPE_CMETHOD; - dest->cMethod.fn = fn; - dest->cMethod.userData = userData; - dest->flags = flags; - dest->allocatedData = 0; - - return dest; -} - -/******************************************************************************/ -#if BLD_FEATURE_FLOATING_POINT -/* - * Set a var using a new float value - */ - -EjsVar *ejsWriteVarAsFloat(Ejs *ep, EjsVar *dest, double value) -{ - mprAssert(dest); - - if (dest->type != EJS_TYPE_UNDEFINED) { - ejsClearVar(ep, dest); - } - - dest->type = EJS_TYPE_FLOAT; - dest->floating = value; - dest->allocatedData = 0; - dest->flags = 0; - - return dest; -} - -#endif -/******************************************************************************/ -/* - * Set a var using a new integer value - */ - -EjsVar *ejsWriteVarAsInteger(Ejs *ep, EjsVar *dest, int value) -{ - mprAssert(dest); - - if (dest->type != EJS_TYPE_UNDEFINED) { - ejsClearVar(ep, dest); - } - - dest->type = EJS_TYPE_INT; - dest->integer = value; - dest->allocatedData = 0; - dest->flags = 0; - - return dest; -} - -/******************************************************************************/ -#if BLD_FEATURE_INT64 -/* - * Set a var using a new integer value - */ - -EjsVar *ejsWriteVarAsInteger64(Ejs *ep, EjsVar *dest, int64 value) -{ - mprAssert(dest); - - if (dest->type != EJS_TYPE_UNDEFINED) { - ejsClearVar(ep, dest); - } - - dest->type = EJS_TYPE_INT64; - dest->integer64 = value; - dest->allocatedData = 0; - dest->flags = 0; - - return dest; -} - -#endif -/******************************************************************************/ -/* - * Set a var using a new Method - */ - -EjsVar *ejsWriteVarAsMethod(Ejs *ep, EjsVar *dest, const char *body, - MprArray *args) -{ - EjsVar **srcArgs, *arg; - int i; - - mprAssert(ep); - mprAssert(dest); - mprAssert(body); - - if (dest->type != EJS_TYPE_UNDEFINED) { - ejsClearVar(ep, dest); - } - - dest->method.args = mprCreateItemArray(ep, EJS_INC_ARGS, EJS_MAX_ARGS); - if (dest->method.args == 0) { - return 0; - } - - dest->type = EJS_TYPE_METHOD; - - if (args) { - srcArgs = (EjsVar**) args->items; - for (i = 0; i < args->length; i++) { - arg = ejsDupVar(ep, srcArgs[i], EJS_SHALLOW_COPY); - if (arg == 0) { - return 0; - } - if (mprAddItem(dest->method.args, arg) < 0) { - return 0; - } - } - } - - dest->method.body = mprStrdup(dest->method.args, body); - if (dest->method.body == 0) { - return 0; - } - - dest->allocatedData = 1; - dest->flags = 0; - - return dest; -} - -/******************************************************************************/ -/* - * Set a var to null - */ - -EjsVar *ejsWriteVarAsNull(Ejs *ep, EjsVar *dest) -{ - mprAssert(dest); - - if (dest->type != EJS_TYPE_UNDEFINED) { - ejsClearVar(ep, dest); - } - - dest->type = EJS_TYPE_NULL; - dest->allocatedData = 0; - dest->flags = 0; - - return dest; -} - -/******************************************************************************/ -/* - * Set a var using a new number value - */ - -EjsVar *ejsWriteVarAsNumber(Ejs *ep, EjsVar *dest, EjsNum value) -{ - mprAssert(dest); - - if (dest->type != EJS_TYPE_UNDEFINED) { - ejsClearVar(ep, dest); - } - - dest->type = EJS_NUM_VAR; - dest->ejsNumber = value; - dest->allocatedData = 0; - dest->flags = 0; - - return dest; -} - -/******************************************************************************/ -/* - * Set a var using a new C Method - */ - -EjsVar *ejsWriteVarAsStringCMethod(Ejs *ep, EjsVar *dest, EjsStringCMethod fn, - void *userData, int flags) -{ - mprAssert(dest); - - if (dest->type != EJS_TYPE_UNDEFINED) { - ejsClearVar(ep, dest); - } - - dest->type = EJS_TYPE_CMETHOD; - dest->cMethodWithStrings.fn = fn; - dest->cMethodWithStrings.userData = userData; - dest->flags = flags; - dest->allocatedData = 0; - - return dest; -} - -/******************************************************************************/ -/* - * Set a var using a new string value - */ - -EjsVar *ejsWriteVarAsStringInternal(EJS_LOC_DEC(ep, loc), EjsVar *dest, - const char *value) -{ - mprAssert(dest); - mprAssert(value); - - if (dest->type != EJS_TYPE_UNDEFINED) { - ejsClearVar(ep, dest); - } - - dest->string = mprStrdupInternal(EJS_LOC_PASS(ep, loc), value); - if (dest->string == 0) { - return 0; - } - - dest->length = strlen(dest->string); - - dest->type = EJS_TYPE_STRING; - dest->allocatedData = 1; - dest->flags = 0; - - return dest; -} - -/******************************************************************************/ -/* - * Set a var using a new string value - */ - -EjsVar *ejsWriteVarAsBinaryString(Ejs *ep, EjsVar *dest, const uchar *value, - int len) -{ - mprAssert(dest); - mprAssert(value); - - ejsClearVar(ep, dest); - - if (dest->type != EJS_TYPE_UNDEFINED) { - ejsClearVar(ep, dest); - } - - dest->length = dupString(MPR_LOC_ARGS(ep), &dest->ustring, value, len); - if (dest->length < 0) { - return 0; - } - - dest->type = EJS_TYPE_STRING; - dest->allocatedData = 1; - dest->flags = 0; - - return dest; -} - -/******************************************************************************/ -/* - * Set a var to undefined - */ - -EjsVar *ejsWriteVarAsUndefined(Ejs *ep, EjsVar *dest) -{ - mprAssert(dest); - - if (dest->type != EJS_TYPE_UNDEFINED) { - ejsClearVar(ep, dest); - } - - dest->type = EJS_TYPE_UNDEFINED; - dest->allocatedData = 0; - dest->flags = 0; - - return dest; -} - -/******************************************************************************/ -/* - * Convert a value to a text based representation of its value - * If you provide a format, you MUST ensure you know the type. - * Caller must free the result. - */ - -char *ejsFormatVar(Ejs *ep, const char *fmt, EjsVar *vp) -{ - char *buf, *src, *value, *allocValue; - uchar *ubuf; - int len; - - buf = 0; - allocValue = 0; - value = 0; - - switch (vp->type) { - case EJS_TYPE_UNDEFINED: - value = "undefined"; - break; - - case EJS_TYPE_NULL: - value = "null"; - break; - - case EJS_TYPE_PTR: - if (fmt == NULL || *fmt == '\0') { - len = mprAllocSprintf(MPR_LOC_ARGS(ep), &buf, 0, - "[Opaque Pointer %p]", vp->ptr.userPtr); - } else { - len = mprAllocSprintf(MPR_LOC_ARGS(ep), &buf, 0, fmt, vp->ptr); - } - goto done; - - case EJS_TYPE_BOOL: - value = (vp->boolean) ? "true" : "false"; - break; - -#if BLD_FEATURE_FLOATING_POINT - case EJS_TYPE_FLOAT: - if (fmt == NULL || *fmt == '\0') { - fmt = "%f"; - } - len = mprAllocSprintf(MPR_LOC_ARGS(ep), &buf, 0, fmt, vp->floating); - goto done; -#endif - - case EJS_TYPE_INT: - if (fmt == NULL || *fmt == '\0') { - fmt = "%d"; - } - mprAllocSprintf(MPR_LOC_ARGS(ep), &buf, 0, fmt, vp->integer); - goto done; - -#if BLD_FEATURE_INT64 - case EJS_TYPE_INT64: - if (fmt == NULL || *fmt == '\0') { - fmt = "%Ld"; - } - mprAllocSprintf(MPR_LOC_ARGS(ep), &buf, 0, fmt, vp->integer64); - goto done; -#endif - - case EJS_TYPE_CMETHOD: - value = "[C Method]"; - break; - - case EJS_TYPE_STRING_CMETHOD: - value = "[C StringMethod]"; - break; - - case EJS_TYPE_METHOD: - value = ejsVarToString(ep, vp); - break; - - case EJS_TYPE_OBJECT: - value = ejsVarToString(ep, vp); - break; - - case EJS_TYPE_STRING: - src = vp->string; - mprAssert(src); - - if (fmt && *fmt && src) { - mprAllocSprintf(MPR_LOC_ARGS(ep), &buf, 0, fmt, src); - - } else if (src == NULL) { - buf = mprStrdup(ep, "null"); - - } else { - ubuf = (uchar*) buf; - if (dupString(MPR_LOC_ARGS(ep), &ubuf, src, vp->length) < 0) { - return mprStrdup(ep, ""); - } - buf = (char*) ubuf; - } - break; - - default: - mprAssert(0); - } - - if (fmt == NULL || *fmt == '\0') { - len = mprAllocSprintf(MPR_LOC_ARGS(ep), &buf, 0, "%s", value); - } else { - len = mprAllocSprintf(MPR_LOC_ARGS(ep), &buf, 0, fmt, value); - } - -done: - if (allocValue) { - mprFree(allocValue); - } - return buf; -} - -/******************************************************************************/ -/* - * Convert the variable to a boolean. Only for primitive types. - */ - -int ejsVarToBoolean(EjsVar *vp) -{ - mprAssert(vp); - - switch (vp->type) { - case EJS_TYPE_UNDEFINED: - case EJS_TYPE_NULL: - case EJS_TYPE_STRING_CMETHOD: - case EJS_TYPE_CMETHOD: - case EJS_TYPE_METHOD: - return 0; - - case EJS_TYPE_OBJECT: - return (vp->objectState != NULL); - - case EJS_TYPE_PTR: - return (vp->ptr.userPtr != NULL); - - case EJS_TYPE_BOOL: - return vp->boolean; - -#if BLD_FEATURE_FLOATING_POINT - case EJS_TYPE_FLOAT: - return (vp->floating != 0 && !ejsIsNan(vp->floating)); -#endif - - case EJS_TYPE_INT: - return (vp->integer != 0); - -#if BLD_FEATURE_INT64 - case EJS_TYPE_INT64: - return (vp->integer64 != 0); -#endif - - case EJS_TYPE_STRING: - return (vp->length > 0); -#if UNUSED - if (strcmp(vp->string, "true") == 0 || - strcmp(vp->string, "TRUE") == 0) { - return 1; - - } else if (strcmp(vp->string, "false") == 0 || - strcmp(vp->string, "FALSE") == 0) { - return 0; - - } else { - return atoi(vp->string); - } -#endif - } - - /* Not reached */ - return 0; -} - -/******************************************************************************/ -#if BLD_FEATURE_FLOATING_POINT -/* - * Convert the variable to a floating point number. Only for primitive types. - */ - -double ejsVarToFloat(EjsVar *vp) -{ - mprAssert(vp); - - switch (vp->type) { - case EJS_TYPE_UNDEFINED: - case EJS_TYPE_NULL: - case EJS_TYPE_STRING_CMETHOD: - case EJS_TYPE_CMETHOD: - case EJS_TYPE_METHOD: - case EJS_TYPE_OBJECT: - case EJS_TYPE_PTR: - return 0; - - case EJS_TYPE_BOOL: - return (vp->boolean) ? 1.0 : 0.0; - - case EJS_TYPE_FLOAT: - return vp->floating; - - case EJS_TYPE_INT: - return (double) vp->integer; - -#if BLD_FEATURE_INT64 - case EJS_TYPE_INT64: - return (double) vp->integer64; -#endif - - case EJS_TYPE_STRING: - if (vp->length == 0) { - return 0.0; - } else { - return atof(vp->string); - } - } - - /* Not reached */ - return 0; -} - -#endif -/******************************************************************************/ -/* - * Convert the variable to an Integer type. Only works for primitive types. - */ - -int ejsVarToInteger(EjsVar *vp) -{ - mprAssert(vp); - - switch (vp->type) { - case EJS_TYPE_UNDEFINED: - case EJS_TYPE_NULL: - case EJS_TYPE_STRING_CMETHOD: - case EJS_TYPE_CMETHOD: - case EJS_TYPE_METHOD: - case EJS_TYPE_OBJECT: - return 0; - - case EJS_TYPE_BOOL: - return (vp->boolean) ? 1 : 0; - -#if BLD_FEATURE_FLOATING_POINT - case EJS_TYPE_FLOAT: - if (ejsIsNan(vp->floating)) { - return 0; - } - return (int) vp->floating; -#endif - - case EJS_TYPE_INT: - return vp->integer; - -#if BLD_FEATURE_INT64 - case EJS_TYPE_INT64: - return (int) vp->integer64; -#endif - - case EJS_TYPE_STRING: - if (vp->length == 0) { - return 0; - } else { - return ejsParseInteger(vp->string); - } - } - - /* Not reached */ - return 0; -} - -/******************************************************************************/ -#if BLD_FEATURE_INT64 -/* - * Convert the variable to an Integer64 type. Only works for primitive types. - */ - -int64 ejsVarToInteger64(EjsVar *vp) -{ - mprAssert(vp); - - switch (vp->type) { - case EJS_TYPE_UNDEFINED: - case EJS_TYPE_NULL: - case EJS_TYPE_STRING_CMETHOD: - case EJS_TYPE_CMETHOD: - case EJS_TYPE_METHOD: - case EJS_TYPE_OBJECT: - case EJS_TYPE_PTR: - return 0; - - case EJS_TYPE_BOOL: - return (vp->boolean) ? 1 : 0; - -#if BLD_FEATURE_FLOATING_POINT - case EJS_TYPE_FLOAT: - if (ejsIsNan(vp->floating)) { - return 0; - } - return (int64) vp->floating; -#endif - - case EJS_TYPE_INT: - return vp->integer; - - case EJS_TYPE_INT64: - return vp->integer64; - - case EJS_TYPE_STRING: - if (vp->length == 0) { - return 0; - } else { - return ejsParseInteger64(vp->string); - } - } - - /* Not reached */ - return 0; -} - -#endif /* BLD_FEATURE_INT64 */ -/******************************************************************************/ -/* - * Convert the variable to a number type. Only works for primitive types. - */ - -EjsNum ejsVarToNumber(EjsVar *vp) -{ -#if BLD_FEATURE_NUM_TYPE_ID == EJS_TYPE_INT64 - return ejsVarToInteger64(vp); -#elif BLD_FEATURE_NUM_TYPE_ID == EJS_TYPE_FLOAT - return ejsVarToFloat(vp); -#else - return ejsVarToInteger(vp); -#endif -} - -/******************************************************************************/ -/* - * Convert a var to a string. Store the result in ep->castTemp. If allocated - * set ep->castAlloc to TRUE. Caller must NOT free the result. - */ - -char *ejsVarToString(Ejs *ep, EjsVar *vp) -{ - MprBuf *bp; - char numBuf[16]; - int len, i; - - if (ep->castAlloc) { - mprFree(ep->castTemp); - } - ep->castTemp = 0; - ep->castAlloc = 0; - - switch (vp->type) { - case EJS_TYPE_UNDEFINED: - ep->castTemp = "undefined"; - break; - - case EJS_TYPE_NULL: - ep->castTemp = "null"; - break; - - case EJS_TYPE_PTR: - len = mprAllocSprintf(MPR_LOC_ARGS(ep), &ep->castTemp, 0, - "[Opaque Pointer %p]", vp->ptr.userPtr); - ep->castAlloc = 1; - break; - - case EJS_TYPE_BOOL: - if (vp->boolean) { - ep->castTemp = "true"; - } else { - ep->castTemp = "false"; - } - break; - -#if BLD_FEATURE_FLOATING_POINT - case EJS_TYPE_FLOAT: - len = mprAllocSprintf(MPR_LOC_ARGS(ep), &ep->castTemp, 0, - "%f", vp->floating); - ep->castAlloc = 1; - break; -#endif - - case EJS_TYPE_INT: - mprItoa(numBuf, sizeof(numBuf), vp->integer); - ep->castTemp = mprStrdup(ep, numBuf); - ep->castAlloc = 1; - break; - -#if BLD_FEATURE_INT64 - case EJS_TYPE_INT64: - mprAllocSprintf(MPR_LOC_ARGS(ep), &ep->castTemp, 0, - "%Ld", vp->integer64); - ep->castAlloc = 1; - break; -#endif - - case EJS_TYPE_CMETHOD: - ep->castTemp = "[C Method]"; - break; - - case EJS_TYPE_STRING_CMETHOD: - ep->castTemp = "[C StringMethod]"; - break; - - case EJS_TYPE_METHOD: - bp = mprCreateBuf(ep, 0, 0); - mprPutStringToBuf(bp, "function ("); - for (i = 0; i < vp->method.args->length; i++) { - mprPutStringToBuf(bp, vp->method.args->items[i]); - if ((i + 1) < vp->method.args->length) { - mprPutStringToBuf(bp, ", "); - } - } - mprPutStringToBuf(bp, ") {"); - mprPutStringToBuf(bp, vp->method.body); - mprPutStringToBuf(bp, "}"); - mprAddNullToBuf(bp); - ep->castTemp = mprStealBuf(ep, bp); - ep->castAlloc = 1; - mprFree(bp); - break; - - case EJS_TYPE_OBJECT: - if (ejsRunMethod(ep, vp, "toString", 0) < 0) { - return mprStrdup(ep, "[object Object]"); - } - ep->castTemp = mprStrdup(ep, ep->result->string); - ep->castAlloc = 1; - break; - - case EJS_TYPE_STRING: - if (vp->string == 0) { - ep->castTemp = "null"; - } else { - ep->castTemp = vp->string; - } - break; - - default: - mprAssert(0); - } - - mprAssert(ep->castTemp); - return ep->castTemp; -} - -/******************************************************************************/ - -char *ejsVarToStringEx(Ejs *ep, EjsVar *vp, bool *alloc) -{ - char *str; - - mprAssert(alloc); - - str = ejsVarToString(ep, vp); - *alloc = ep->castAlloc; - ep->castAlloc = 0; - ep->castTemp = 0; - return str; -} - -/******************************************************************************/ -/* - * Parse a string based on formatting instructions and intelligently - * create a variable. - * - * Float format: [+|-]DIGITS][DIGITS][(e|E)[+|-]DIGITS] - */ - -EjsVar *ejsParseVar(Ejs *ep, const char *buf, EjsType preferredType) -{ - EjsType type; - const char *cp; - int isHex; - - mprAssert(buf); - - type = preferredType; - - if (preferredType == EJS_TYPE_UNDEFINED) { - isHex = 0; - if (*buf == '-' || *buf == '+') { - type = EJS_NUM_VAR; - - } else if (!isdigit((int) *buf)) { - if (strcmp(buf, "true") == 0 || strcmp(buf, "false") == 0) { - type = EJS_TYPE_BOOL; - } else { - type = EJS_TYPE_STRING; - } - - } else if (isdigit((int) *buf)) { - type = EJS_NUM_VAR; - cp = buf; - if (*cp && tolower(cp[1]) == 'x') { - cp = &cp[2]; - isHex = 1; - for (cp = buf; *cp; cp++) { - if (! isxdigit((int) *cp)) { - break; - } - } - } else { -#if BLD_FEATURE_FLOATING_POINT - /* Could be integer or float */ - for (cp = buf; *cp; cp++) { - if (! isdigit((int) *cp)) { - int c = tolower(*cp); - if (c == '.' || c == 'e' || c == 'f') { - type = EJS_TYPE_FLOAT; - break; - } - } - } -#endif - } - } - } - - switch (type) { - case EJS_TYPE_OBJECT: - case EJS_TYPE_UNDEFINED: - case EJS_TYPE_NULL: - case EJS_TYPE_PTR: - default: - break; - - case EJS_TYPE_BOOL: - return ejsCreateBoolVar(ep, ejsParseBoolean(buf)); - - case EJS_TYPE_INT: - return ejsCreateIntegerVar(ep, ejsParseInteger(buf)); - -#if BLD_FEATURE_INT64 - case EJS_TYPE_INT64: - return ejsCreateInteger64Var(ep, ejsParseInteger64(buf)); -#endif - - case EJS_TYPE_STRING: - if (strcmp(buf, "null") == 0) { - return ejsCreateNullVar(ep); - - } else if (strcmp(buf, "undefined") == 0) { - return ejsCreateUndefinedVar(ep); - } - - return ejsCreateStringVar(ep, buf); - -#if BLD_FEATURE_FLOATING_POINT - case EJS_TYPE_FLOAT: - return ejsCreateFloatVar(ep, atof(buf)); -#endif - - } - return ejsCreateUndefinedVar(ep); -} - -/******************************************************************************/ -/* - * Convert the variable to a number type. Only works for primitive types. - */ - -bool ejsParseBoolean(const char *s) -{ - if (s == 0 || *s == '\0') { - return 0; - } - if (strcmp(s, "false") == 0 || strcmp(s, "FALSE") == 0) { - return 0; - } - return 1; -} - -/******************************************************************************/ -/* - * Convert the variable to a number type. Only works for primitive types. - */ - -EjsNum ejsParseNumber(const char *s) -{ -#if BLD_FEATURE_NUM_TYPE_ID == EJS_TYPE_INT64 - return ejsParseInteger64(s); -#elif BLD_FEATURE_NUM_TYPE_ID == EJS_TYPE_FLOAT - return ejsParseFloat(s); -#else - return ejsParseInteger(s); -#endif -} - -/******************************************************************************/ -#if BLD_FEATURE_INT64 -/* - * Convert the string buffer to an Integer64. - */ - -int64 ejsParseInteger64(const char *str) -{ - const char *cp; - int64 num64; - int radix, c, negative; - - mprAssert(str); - - cp = str; - num64 = 0; - negative = 0; - - if (*cp == '-') { - cp++; - negative = 1; - } else if (*cp == '+') { - cp++; - } - - /* - * Parse a number. Observe hex and octal prefixes (0x, 0) - */ - if (*cp != '0') { - /* - * Normal numbers (Radix 10) - */ - while (isdigit((int) *cp)) { - num64 = (*cp - '0') + (num64 * 10); - cp++; - } - } else { - cp++; - if (tolower(*cp) == 'x') { - cp++; - radix = 16; - while (*cp) { - c = tolower(*cp); - if (isdigit(c)) { - num64 = (c - '0') + (num64 * radix); - } else if (c >= 'a' && c <= 'f') { - num64 = (c - 'a' + 10) + (num64 * radix); - } else { - break; - } - cp++; - } - - } else{ - radix = 8; - while (*cp) { - c = tolower(*cp); - if (isdigit(c) && c < '8') { - num64 = (c - '0') + (num64 * radix); - } else { - break; - } - cp++; - } - } - } - - if (negative) { - return 0 - num64; - } - return num64; -} - -#endif /* BLD_FEATURE_INT64 */ -/******************************************************************************/ -/* - * Convert the string buffer to an Integer. - */ - -int ejsParseInteger(const char *str) -{ - const char *cp; - int num; - int radix, c, negative; - - mprAssert(str); - - cp = str; - num = 0; - negative = 0; - - if (*cp == '-') { - cp++; - negative = 1; - } else if (*cp == '+') { - cp++; - } - - /* - * Parse a number. Observe hex and octal prefixes (0x, 0) - */ - if (*cp != '0') { - /* - * Normal numbers (Radix 10) - */ - while (isdigit((int) *cp)) { - num = (*cp - '0') + (num * 10); - cp++; - } - } else { - cp++; - if (tolower(*cp) == 'x') { - cp++; - radix = 16; - while (*cp) { - c = tolower(*cp); - if (isdigit(c)) { - num = (c - '0') + (num * radix); - } else if (c >= 'a' && c <= 'f') { - num = (c - 'a' + 10) + (num * radix); - } else { - break; - } - cp++; - } - - } else{ - radix = 8; - while (*cp) { - c = tolower(*cp); - if (isdigit(c) && c < '8') { - num = (c - '0') + (num * radix); - } else { - break; - } - cp++; - } - } - } - - if (negative) { - return 0 - num; - } - return num; -} - -/******************************************************************************/ -#if BLD_FEATURE_FLOATING_POINT -/* - * Convert the string buffer to an Floating. - */ - -double ejsParseFloat(const char *str) -{ - return atof(str); -} - -/******************************************************************************/ - -int ejsIsNan(double f) -{ -#if WIN - return _isnan(f); -#elif VXWORKS - /* FUTURE */ - return (0); -#else - return (f == FP_NAN); -#endif -} -/******************************************************************************/ - -int ejsIsInfinite(double f) -{ -#if WIN - return !_finite(f); -#elif VXWORKS - /* FUTURE */ - return (0); -#else - return (f == FP_INFINITE); -#endif -} - -#endif /* BLD_FEATURE_FLOATING_POINT */ - -/******************************************************************************/ -/* - * Single point of control for all assignment to properties. - * - * Copy an objects core value (only). This preserves the destination object's - * name. This implements copy by reference for objects and copy by value for - * strings and other types. Caller must free dest prior to calling. - */ - -static EjsVar *copyVar(EJS_LOC_DEC(ep, loc), EjsVar *dest, const EjsVar *src, - EjsCopyDepth copyDepth) -{ - Ejs *ejsContext; - EjsObj *srcObj; - EjsProperty *destp; - const char **srcArgs; - char *str; - int i; - - mprAssert(dest); - mprAssert(src); - - if (dest == src) { - return dest; - } - - if (dest->type != EJS_TYPE_UNDEFINED) { - ejsClearVar(ep, dest); - } - - dest->allocatedData = 0; - - switch (src->type) { - default: - case EJS_TYPE_UNDEFINED: - case EJS_TYPE_NULL: - break; - - case EJS_TYPE_BOOL: - dest->boolean = src->boolean; - break; - - case EJS_TYPE_PTR: - dest->ptr = src->ptr; - if (dest->ptr.destructor) { - dest->allocatedData = 1; - } - break; - - case EJS_TYPE_STRING_CMETHOD: - dest->cMethodWithStrings = src->cMethodWithStrings; - break; - - case EJS_TYPE_CMETHOD: - dest->cMethod = src->cMethod; - break; - -#if BLD_FEATURE_FLOATING_POINT - case EJS_TYPE_FLOAT: - dest->floating = src->floating; - break; -#endif - - case EJS_TYPE_INT: - dest->integer = src->integer; - break; - -#if BLD_FEATURE_INT64 - case EJS_TYPE_INT64: - dest->integer64 = src->integer64; - break; -#endif - - case EJS_TYPE_OBJECT: - if (copyDepth == EJS_SHALLOW_COPY) { - - /* - * If doing a shallow copy and the src object is from the same - * interpreter, or we are copying from the master interpreter, or - * we are using a shared slab, then we can do a shallow copy. - * Otherwise, we must do a deep copy. - */ - srcObj = src->objectState; - if (srcObj->ejs == ep || srcObj->ejs == ep->service->master || - (ep->flags & EJS_FLAGS_SHARED_SLAB)) { - dest->objectState = src->objectState; - dest->allocatedData = 1; - break; - } - } - - /* - * Doing a deep or recursive deep. Can get here if doing a shallow - * copy and the object is from another non-master interpeter and not - * using a shared slab. - * - * We must make sure the data is allocated using the right memory - * context. It must be the same as the destination parent object. - * Otherwise, when we free the property memory, the parent may - * have a dangling pointer. - */ - if (dest->isProperty) { - destp = ejsGetPropertyPtr(dest); - if (destp->parentObj == 0) { - ejsContext = ep; - - } else { - mprAssert(destp->parentObj); - ejsContext = destp->parentObj->ejs; - mprAssert(ejsContext); - } - - } else { - ejsContext = ep; - } - - dest->objectState = createObj(EJS_LOC_PASS(ejsContext, loc)); - if (dest->objectState == 0) { - /* Memory Error */ - return 0; - } - - dest->objectState->baseClass = src->objectState->baseClass; - dest->objectState->methods = src->objectState->methods; - dest->objectState->noConstructor = src->objectState->noConstructor; - dest->objectState->objName = - mprStrdup(ejsContext, src->objectState->objName); - - if (dest->objectState->objName == 0) { - return 0; - } - - if (ejsCopyProperties(ep, dest, src, copyDepth) == 0) { - return 0; - } - dest->allocatedData = 1; - break; - - case EJS_TYPE_METHOD: - dest->method.args = mprCreateItemArray(ep, EJS_INC_ARGS, - EJS_MAX_ARGS); - if (dest->method.args == 0) { - return 0; - } - dest->allocatedData = 1; - if (src->method.args) { - srcArgs = (const char**) src->method.args->items; - for (i = 0; i < src->method.args->length; i++) { - str = mprStrdupInternal(EJS_LOC_PASS(dest->method.args, - loc), srcArgs[i]); - if (str == 0) { - mprFree(dest->method.args); - dest->method.args = 0; - return 0; - } - if (mprAddItem(dest->method.args, str) < 0) { - mprFree(dest->method.args); - dest->method.args = 0; - return 0; - } - } - } - dest->method.body = mprStrdup(dest->method.args, src->method.body); - if (dest->method.body == 0) { - mprFree(dest->method.args); - dest->method.args = 0; - return 0; - } - dest->callsSuper = src->callsSuper; - break; - - case EJS_TYPE_STRING: - dest->length = src->length; - if (src->string) { - /* Shallow, deep or recursive deep */ - dest->length = dupString(MPR_LOC_PASS(ep, loc), &dest->ustring, - src->ustring, src->length); - if (dest->length < 0) { - return 0; - } - dest->allocatedData = 1; - - } else { - dest->string = src->string; - dest->allocatedData = 0; - } - break; - } - - dest->type = src->type; - dest->flags = src->flags; - dest->isArray = src->isArray; - - return dest; -} - -/******************************************************************************/ -/* - * Copy all properies in an object. Must preserve property order - */ - -EjsVar *ejsCopyProperties(Ejs *ep, EjsVar *dest, const EjsVar *src, - EjsCopyDepth copyDepth) -{ - EjsProperty *srcProp, *destProp, *last, *next; - int propertyIndex; - - srcProp = ejsGetFirstProperty(src, EJS_ENUM_ALL); - while (srcProp) { - next = ejsGetNextProperty(srcProp, EJS_ENUM_ALL); - if (srcProp->visited) { - srcProp = next; - continue; - } - - /* - * This finds the last variable in the hash chain - * FUTURE OPT. This is slow. If used double link, we could locate the - * tail more easily. - */ - destProp = hashLookup(dest->objectState, srcProp->name, - &propertyIndex, &last); - mprAssert(destProp == 0); - - destProp = allocProperty(ep, dest, srcProp->name, propertyIndex, last); - if (destProp == 0) { - mprAssert(destProp); - return 0; - } - - /* - * Recursively copy the object. If DEEP_COPY, then we - * will do a shallow copy of the object contents. If - * RECURSIVE_DEEP, then we do a deep copy at all levels. - */ - srcProp->visited = 1; - - if (copyVar(EJS_LOC_ARGS(ep), ejsGetVarPtr(destProp), - ejsGetVarPtr(srcProp), - (copyDepth == EJS_DEEP_COPY) ? EJS_SHALLOW_COPY : copyDepth) - == 0) { - return 0; - } - srcProp->visited = 0; - - srcProp = next; - } - return dest; -} - -/******************************************************************************/ -/********************************** Properties ********************************/ -/******************************************************************************/ -/* - * Create a property in an object and return a pointer to it. If the property - * already exists then just return a pointer to it (no error). - * To test for existance of a property, use GetProperty - */ - -static EjsProperty *hashLookup(EjsObj *obj, const char *property, - int *propertyIndex, EjsProperty **hashTail) -{ - EjsProperty *prop, *last; - int index; - - mprAssert(obj); - mprAssert(property); - - if (obj == 0 || property == 0 || *property == '\0') { - mprAssert(0); - return 0; - } - - /* - * Find the property in the hash chain if it exists - */ - index = hash(property); - prop = obj->propertyHash[index]; - for (last = 0; prop != 0; last = prop, prop = prop->hashNext) { - if (prop->name[0] == property[0] && - strcmp(prop->name, property) == 0) { - break; - } - } - if (propertyIndex) { - *propertyIndex = index; - } - if (hashTail) { - *hashTail = last; - } - - return prop; -} - -/******************************************************************************/ -/* - * Create a property in an object and return a pointer to it. If the property - * already exists then just return a pointer to it (no error). If the property - * does not exist, create an undefined variable. To test for existance of a - * property, use GetProperty. - */ - -EjsProperty *ejsCreateSimpleProperty(Ejs *ep, EjsVar *op, const char *property) -{ - EjsProperty *prop, *last; - int propertyIndex; - - if (op == 0 || op->type != EJS_TYPE_OBJECT || property == 0 || - *property == '\0') { - mprAssert(0); - return 0; - } - - /* - * Find the property in the hash chain if it exists - */ - prop = hashLookup(op->objectState, property, &propertyIndex, &last); - - if (prop == 0) { - /* - * Create a new property - */ - prop = allocProperty(ep, op, property, propertyIndex, last); - if (prop == 0) { - mprAssert(prop == 0); - return 0; - } - } - return prop; -} - -/******************************************************************************/ -/* - * Create a property in an object and return a pointer to it. If the property - * already exists then just return a pointer to it (no error). - * To test for existance of a property, use GetProperty - */ - -EjsProperty *ejsCreateSimpleNonUniqueProperty(Ejs *ep, EjsVar *op, - const char *property) -{ - EjsProperty *prop, *last; - int propertyIndex; - - if (op == 0 || op->type != EJS_TYPE_OBJECT || property == 0 || - *property == '\0') { - mprAssert(0); - return 0; - } - - /* - * Find end of chain - */ - propertyIndex = hash(property); - prop = op->objectState->propertyHash[propertyIndex]; - for (last = 0; prop != 0; last = prop, prop = prop->hashNext) { - ; - } - - return allocProperty(ep, op, property, propertyIndex, last); -} - -/******************************************************************************/ -/* - * Find a property in an object and return a pointer to it. - * This does NOT traverse base classes. - */ - -EjsProperty *ejsGetSimpleProperty(Ejs *ep, EjsVar *op, const char *property) -{ - mprAssert(op); - mprAssert(op->type == EJS_TYPE_OBJECT); - mprAssert(property && *property); - - /* - * This is an internal API. It has very little checking. - */ - return hashLookup(op->objectState, property, 0, 0); -} - -/******************************************************************************/ - -/* - * NOTE: There is no ejsSetSimpleProperty as all the ejsSetProperty routines - * operate only on the instance and don't follow base classes. ie. there is - * no simple version required. However, there is a ejsSetBaseProperty routine - * that will follow base classes and is used to set static properties in base - * classes - */ - -/******************************************************************************/ -/******************************* Property Access ******************************/ -/******************************************************************************/ -/* - * The property get routines follow base classes and utilize the propery - * method access routines. The property set routines do not follow base - * classes. The property ejsSetBase... routines do follow base classes. - */ - -/* - * Find a property in an object and return a pointer to it. - * This follows base classes. - */ - -EjsProperty *ejsGetProperty(Ejs *ep, EjsVar *op, const char *property) -{ - EjsVar *vp, *newOp; - int maxBaseClasses = 50; - - do { - if (op->type != EJS_TYPE_OBJECT) { - mprAssert(op->type == EJS_TYPE_OBJECT); - return 0; - } - mprAssert(op->objectState); - - vp = ejsGetPropertyMethod(ep, op, property); - if (vp != 0) { - /* - * Found - */ - break; - } - - newOp = op->objectState->baseClass; - if (newOp == 0) { - if (op->objectState != ep->objectClass->objectState) { - newOp = ep->objectClass; - } - } - op = newOp; - - /* - * A little bit of sanity checking - */ - if (--maxBaseClasses <= 0) { - mprAssert(maxBaseClasses > 0); - break; - } - - } while (op); - - return ejsGetPropertyPtr(vp); -} - -/******************************************************************************/ -/* - * Get the property's variable. Optionally create if it does not exist. - */ - -EjsVar *ejsGetPropertyAsVar(Ejs *ep, EjsVar *vp, const char *property) -{ - return ejsGetVarPtr(ejsGetProperty(ep, vp, property)); -} - -/******************************************************************************/ -/* - * Get the property's value as a binary string. - */ - -const uchar *ejsGetPropertyAsBinaryString(Ejs *ep, EjsVar *obj, - const char *property, int *length) -{ - EjsVar *vp; - - vp = ejsGetVarPtr(ejsGetProperty(ep, obj, property)); - if (vp == 0 || ejsVarIsUndefined(vp)) { - return 0; - } - - if (vp->type == EJS_TYPE_STRING) { - if (length) { - *length = vp->length; - } - return vp->ustring; - } - return 0; -} - -/******************************************************************************/ -/* - * Get the property's value as a string. - */ - -const char *ejsGetPropertyAsString(Ejs *ep, EjsVar *obj, const char *property) -{ - EjsVar *vp; - - vp = ejsGetVarPtr(ejsGetProperty(ep, obj, property)); - if (vp == 0 || ejsVarIsUndefined(vp)) { - return 0; - } - - if (vp->type == EJS_TYPE_STRING) { - return vp->string; - } - return 0; -} - -/******************************************************************************/ -/* - * Get the property's value as a number. - */ - -BLD_FEATURE_NUM_TYPE ejsGetPropertyAsNumber(Ejs *ep, EjsVar *obj, - const char *property) -{ - EjsVar *vp; - - vp = ejsGetVarPtr(ejsGetProperty(ep, obj, property)); - if (vp == 0 || ejsVarIsUndefined(vp)) { - return 0; - } - - return ejsVarToNumber(vp); -} - -/******************************************************************************/ -/* - * Get the property's value as a integer. - */ - -int ejsGetPropertyAsInteger(Ejs *ep, EjsVar *obj, const char *property) -{ - EjsVar *vp; - - vp = ejsGetVarPtr(ejsGetProperty(ep, obj, property)); - if (vp == 0 || ejsVarIsUndefined(vp)) { - return 0; - } - - return ejsVarToInteger(vp); -} - -/******************************************************************************/ -/* - * Get the property's value as a boolean. - */ - -bool ejsGetPropertyAsBoolean(Ejs *ep, EjsVar *obj, const char *property) -{ - EjsVar *vp; - - vp = ejsGetVarPtr(ejsGetProperty(ep, obj, property)); - if (vp == 0 || ejsVarIsUndefined(vp)) { - return 0; - } - - return ejsVarToBoolean(vp); -} - -/******************************************************************************/ -/* - * Get the property's value as a pointer. - */ - -void *ejsGetPropertyAsPtr(Ejs *ep, EjsVar *obj, const char *property) -{ - EjsVar *vp; - - vp = ejsGetVarPtr(ejsGetProperty(ep, obj, property)); - if (vp == 0 || ejsVarIsUndefined(vp)) { - return 0; - } - if (vp->type == EJS_TYPE_PTR) { - return vp->ptr.userPtr; - } - return 0; -} - -/******************************************************************************/ -/* - * Create a property in the object. This will override any base class - * properties. - * - * MOB -- need to spell out the difference between ejsSetProperty and - * ejsCreateProperty. - */ - -EjsProperty *ejsCreateProperty(Ejs *ep, EjsVar *obj, const char *property) -{ - EjsVar *vp; - - vp = ejsCreatePropertyMethod(ep, obj, property); - return ejsGetPropertyPtr(vp); -} - -/******************************************************************************/ -/* - * Set a property's variable value. Create the property if it does not exist. - * This routine DOES follow base classes. - */ - -EjsProperty *ejsSetBaseProperty(Ejs *ep, EjsVar *op, const char *property, - const EjsVar *value) -{ - EjsVar *vp, *newOp; - int maxBaseClasses = 50; - - do { - if (op->type != EJS_TYPE_OBJECT) { - mprAssert(op->type == EJS_TYPE_OBJECT); - return 0; - } - mprAssert(op->objectState); - - vp = ejsGetPropertyMethod(ep, op, property); - if (vp != 0) { - /* - * Found - */ - vp = ejsSetPropertyMethod(ep, op, property, value); - break; - } - - newOp = op->objectState->baseClass; - if (newOp == 0) { - if (op->objectState != ep->objectClass->objectState) { - newOp = ep->objectClass; - } - } - op = newOp; - - /* - * A little bit of sanity checking - */ - if (--maxBaseClasses <= 0) { - mprAssert(maxBaseClasses > 0); - break; - } - - } while (op); - - return ejsGetPropertyPtr(vp); -} - -/******************************************************************************/ -/* - * Set a property's variable value. Create the property if it does not exist. - * This does NOT follow base classes. Okay when updating instance properties, - * but not for class (static) properties. This does a shallow copy which - * will copy references. - */ - -EjsProperty *ejsSetProperty(Ejs *ep, EjsVar *obj, const char *property, - const EjsVar *value) -{ - EjsVar *vp; - - vp = ejsSetPropertyMethod(ep, obj, property, value); - - return ejsGetPropertyPtr(vp); -} - -/******************************************************************************/ -/* - * Set a property's variable value by assigning the given value. The caller - * must NOT free value as it is assigned directly into the property's value. - */ - -EjsProperty *ejsSetPropertyAndFree(Ejs *ep, EjsVar *obj, - const char *property, EjsVar *value) -{ - EjsVar *vp; - - vp = ejsSetPropertyMethod(ep, obj, property, value); - - ejsFree(ep, value, EJS_SLAB_VAR); - - return ejsGetPropertyPtr(vp); -} - -/******************************************************************************/ - -EjsProperty *ejsSetPropertyToCMethod(Ejs *ep, EjsVar *vp, const char *prop, - EjsCMethod fn, void *userData, int flags) -{ - EjsVar v; - - ejsInitVar(&v, EJS_TYPE_CMETHOD); - v.cMethod.fn = fn; - v.cMethod.userData = userData; - v.flags = flags; - - return ejsSetProperty(ep, vp, prop, &v); -} - -/******************************************************************************/ - -EjsProperty *ejsSetPropertyToBoolean(Ejs *ep, EjsVar *vp, const char *prop, - int value) -{ - EjsVar v; - - ejsInitVar(&v, EJS_TYPE_BOOL); - v.boolean = value; - - return ejsSetProperty(ep, vp, prop, &v); -} - -/******************************************************************************/ -#if BLD_FEATURE_FLOATING_POINT - -EjsProperty *ejsSetPropertyToFloat(Ejs *ep, EjsVar *vp, const char *prop, - double value) -{ - EjsVar v; - - ejsInitVar(&v, EJS_TYPE_FLOAT); - v.floating = value; - - return ejsSetProperty(ep, vp, prop, &v); -} - -#endif -/******************************************************************************/ - -EjsProperty *ejsSetPropertyToInteger(Ejs *ep, EjsVar *vp, const char *prop, - int value) -{ - EjsVar v; - - ejsInitVar(&v, EJS_TYPE_INT); - v.integer = value; - - return ejsSetProperty(ep, vp, prop, &v); -} - -/******************************************************************************/ -#if BLD_FEATURE_INT64 - -EjsProperty *ejsSetPropertyToInteger64(Ejs *ep, EjsVar *vp, const char *prop, - int64 value) -{ - EjsVar v; - - ejsInitVar(&v, EJS_TYPE_INT64); - v.integer64 = value; - - return ejsSetProperty(ep, vp, prop, &v); -} - -#endif -/******************************************************************************/ - -EjsProperty *ejsSetPropertyToNull(Ejs *ep, EjsVar *vp, const char *prop) -{ - EjsVar v; - - ejsInitVar(&v, EJS_TYPE_NULL); - - return ejsSetProperty(ep, vp, prop, &v); -} - -/******************************************************************************/ - -EjsProperty *ejsSetPropertyToMethod(Ejs *ep, EjsVar *vp, const char *prop, - const char *body, MprArray *args, int flags) -{ - return ejsSetPropertyAndFree(ep, vp, prop, - ejsCreateMethodVar(ep, body, args, flags)); -} - -/******************************************************************************/ - -EjsProperty *ejsSetPropertyToNumber(Ejs *ep, EjsVar *vp, const char *prop, - EjsNum value) -{ - return ejsSetPropertyAndFree(ep, vp, prop, ejsCreateNumberVar(ep, value)); -} - -/******************************************************************************/ - -EjsProperty *ejsSetPropertyToStringCMethod(Ejs *ep, EjsVar *vp, - const char *prop, EjsStringCMethod fn, void *userData, int flags) -{ - EjsVar v; - - ejsInitVar(&v, EJS_TYPE_STRING_CMETHOD); - v.cMethodWithStrings.fn = fn; - v.cMethodWithStrings.userData = userData; - v.flags = flags; - - return ejsSetProperty(ep, vp, prop, &v); -} - -/******************************************************************************/ - -EjsProperty *ejsSetPropertyToString(Ejs *ep, EjsVar *vp, const char *prop, - const char *value) -{ - EjsProperty *pp; - EjsVar v; - - ejsInitVar(&v, EJS_TYPE_STRING); - - /* FUTURE OPT */ - v.string = mprStrdupInternal(EJS_LOC_ARGS(ep), value); - if (v.string == 0) { - return 0; - } - v.length = strlen(v.string); - v.allocatedData = 1; - - pp = ejsSetProperty(ep, vp, prop, &v); - - mprFree(v.string); - - return pp; -} - -/******************************************************************************/ - -EjsProperty *ejsSetPropertyToBinaryString(Ejs *ep, EjsVar *vp, - const char *prop, const uchar *value, int len) -{ - EjsProperty *pp; - EjsVar v; - - ejsInitVar(&v, EJS_TYPE_STRING); - - /* FUTURE OPT */ - v.length = dupString(MPR_LOC_ARGS(ep), &v.ustring, value, len); - if (v.length < 0) { - return 0; - } - v.allocatedData = 1; - - pp = ejsSetProperty(ep, vp, prop, &v); - - mprFree(v.ustring); - - return pp; -} - -/******************************************************************************/ - -EjsProperty *ejsSetPropertyToUndefined(Ejs *ep, EjsVar *vp, const char *prop) -{ - EjsVar v; - - ejsInitVar(&v, EJS_TYPE_UNDEFINED); - - return ejsSetProperty(ep, vp, prop, &v); -} - -/******************************************************************************/ - -EjsProperty *ejsSetPropertyToPtr(Ejs *ep, EjsVar *vp, const char *prop, - void *ptr, EjsDestructor destructor) -{ - EjsVar v; - - ejsInitVar(&v, EJS_TYPE_PTR); - v.ptr.userPtr = ptr; - v.ptr.destructor = destructor; - v.allocatedData = 1; - - return ejsSetProperty(ep, vp, prop, &v); -} - -/******************************************************************************/ - -EjsProperty *ejsSetPropertyToNewObj(Ejs *ep, EjsVar *vp, const char *prop, - const char *className, MprArray *args) -{ - return ejsSetPropertyAndFree(ep, vp, prop, - ejsCreateObjUsingArgv(ep, 0, className, args)); -} - -/******************************************************************************/ - -EjsProperty *ejsSetPropertyToObj(Ejs *ep, EjsVar *op, const char *prop) -{ - return ejsSetPropertyAndFree(ep, op, prop, ejsCreateObjVar(ep)); -} - -/******************************************************************************/ -/* - * Convenience routines - */ - -EjsVar *ejsSetPropertyToObjAsVar(Ejs *ep, EjsVar *op, const char *prop) -{ - return ejsGetVarPtr(ejsSetPropertyToObj(ep, op, prop)); -} - -/******************************************************************************/ -/******************************************************************************/ -/******************************************************************************/ -/******************************************************************************/ -/* - * Create a script method - */ - -EjsProperty *ejsDefineMethod(Ejs *ep, EjsVar *vp, const char *prop, - const char *body, MprArray *args) -{ - if (vp == 0) { - vp = ejsGetGlobalObj(ep); - } - return ejsSetPropertyToMethod(ep, vp, prop, body, args, 0); -} - -/******************************************************************************/ -/* - * Create a C language method - */ - -EjsProperty *ejsDefineCMethod(Ejs *ep, EjsVar *vp, const char *prop, - EjsCMethod fn, int flags) -{ - if (vp == 0) { - vp = ejsGetGlobalObj(ep); - } - return ejsSetPropertyToCMethod(ep, vp, prop, fn, 0, flags); -} - -/******************************************************************************/ -/* - * Define accessors - */ - -EjsProperty *ejsDefineAccessors(Ejs *ep, EjsVar *vp, const char *prop, - const char *getBody, const char *setBody) -{ - EjsProperty *pp; - MprArray *args; - char *propName; - - if (vp == 0) { - vp = ejsGetGlobalObj(ep); - } - - if (ejsSetPropertyToMethod(ep, vp, prop, getBody, 0, EJS_GET_ACCESSOR) < 0){ - ejsMemoryError(ep); - return 0; - } - - /* MOB -- OPT to use SLAB */ - /* MOB -- need to encapsulate this logic */ - - if (mprAllocStrcat(MPR_LOC_ARGS(ep), &propName, EJS_MAX_ID+5, 0, - "-set-", prop, NULL) < 0) { - ejsMemoryError(ep); - return 0; - } - - args = mprCreateItemArray(ep, EJS_INC_ARGS, EJS_MAX_ARGS); - mprAddItem(args, mprStrdup(args, "value")); - - pp = ejsSetPropertyToMethod(ep, vp, propName, setBody, args, - EJS_SET_ACCESSOR); - mprFree(propName); - - if (pp == 0) { - ejsMemoryError(ep); - return 0; - } - - return pp; -} - -/******************************************************************************/ -/* - * Define C accessors - */ - -EjsProperty *ejsDefineCAccessors(Ejs *ep, EjsVar *vp, const char *prop, - EjsCMethod getFn, EjsCMethod setFn, int flags) -{ - EjsProperty *pp; - char *propName; - - if (vp == 0) { - vp = ejsGetGlobalObj(ep); - } - pp = ejsSetPropertyToCMethod(ep, vp, prop, getFn, 0, - flags | EJS_GET_ACCESSOR); - if (pp == 0) { - ejsMemoryError(ep); - return 0; - } - - /* MOB -- OPT to use SLAB */ - if (mprAllocStrcat(MPR_LOC_ARGS(ep), &propName, EJS_MAX_ID + 5, 0, - "-set-", prop, NULL) < 0) { - ejsMemoryError(ep); - return 0; - } - pp = ejsSetPropertyToCMethod(ep, vp, propName, setFn, 0, - flags | EJS_SET_ACCESSOR); - mprFree(propName); - - if (pp == 0) { - ejsMemoryError(ep); - return 0; - } - return pp; -} - -/******************************************************************************/ -/* - * Create a C language method with string arguments - */ - -EjsProperty *ejsDefineStringCMethod(Ejs *ep, EjsVar *vp, const char *prop, - EjsStringCMethod fn, int flags) -{ - if (vp == 0) { - vp = ejsGetGlobalObj(ep); - } - return ejsSetPropertyToStringCMethod(ep, vp, prop, fn, 0, flags); -} - -/******************************************************************************/ - -void ejsSetCMethodUserData(EjsVar *obj, void *userData) -{ - /* - * This is a little dirty. We rely on the userData being in the same - * place in the var structure. - */ - obj->cMethod.userData = userData; -} - -/******************************************************************************/ - -void ejsSetVarFlags(EjsVar *obj, int flags) -{ - obj->flags = flags; -} - -/******************************************************************************/ - -void *ejsGetCMethodUserData(EjsVar *obj) -{ - return obj->cMethod.userData; -} - -/******************************************************************************/ - -int ejsGetVarFlags(EjsVar *obj) -{ - return obj->flags; -} - -/******************************************************************************/ - -void ejsSetObjDestructor(Ejs *ep, EjsVar *obj, EjsDestructor destructor) -{ - obj->objectState->destructor = destructor; -} - -/******************************************************************************/ - -void ejsClearObjDestructor(Ejs *ep, EjsVar *obj) -{ - obj->objectState->destructor = 0; -} - -/******************************************************************************/ -/* - * Create a new property - */ - -static EjsProperty *allocProperty(Ejs *ep, EjsVar *op, const char *property, - int propertyIndex, EjsProperty *last) -{ - EjsProperty *prop; - EjsObj *obj; - - obj = op->objectState; - - /* - * Allocate the property using the memory context of the owning object - */ - prop = ejsAllocProperty(EJS_LOC_ARGS(obj->ejs)); - if (prop == 0) { - return 0; - } - if (mprStrcpy(prop->name, sizeof(prop->name), property) < 0) { - ejsError(ep, EJS_REFERENCE_ERROR, - "Property name %s is too long. Max is %d letters.", - prop->name, EJS_MAX_ID); - return 0; - } - - ejsSetVarName(ep, ejsGetVarPtr(prop), &prop->name[0]); - - /* - * Do hash linkage - */ - if (last) { - last->hashNext = prop; - } else { - obj->propertyHash[propertyIndex] = prop; - } - -#if BLD_DEBUG - prop->link.propertyName = prop->name; - prop->link.property = prop; - prop->link.head = &obj->link; -#endif - - /* - * Inserting before the dummy head will append to the end - */ - linkPropertyBefore(obj, &obj->link, &prop->link); - - obj->numProperties++; - prop->parentObj = obj; - mprAssert(obj->ejs); - - return prop; -} - -/******************************************************************************/ -/* - * Delete a property from this object - */ - -int ejsDeleteProperty(Ejs *ep, EjsVar *vp, const char *property) -{ - EjsProperty *prop, *last; - EjsObj *obj; - int propertyIndex; - - mprAssert(vp); - mprAssert(property && *property); - mprAssert(vp->type == EJS_TYPE_OBJECT); - - if (vp->type != EJS_TYPE_OBJECT) { - mprAssert(vp->type == EJS_TYPE_OBJECT); - return MPR_ERR_BAD_ARGS; - } - - prop = hashLookup(vp->objectState, property, &propertyIndex, &last); - if (prop == (EjsProperty*) 0) { - return MPR_ERR_NOT_FOUND; - } - obj = vp->objectState; - -#if FUTURE - if (prop->readonly) { - mprAssert(! prop->readonly); - return MPR_ERR_READ_ONLY; - } -#endif - - /* - * If doing enumerations, then the object will mark preventDelete to - * prevent any properties being deleted and thus disturbing the - * traversal. - */ - if (obj->preventDeleteProp) { - obj->delayedDeleteProp = 1; - prop->delayedDelete = 1; - return 0; - } - - /* - * Remove from hash - */ - if (last) { - last->hashNext = prop->hashNext; - } else { - obj->propertyHash[propertyIndex] = prop->hashNext; - } - - unlinkProperty(obj, &prop->link); - obj->numProperties--; - - /* - * Free any property data and return to the slab - */ - if (prop->var.type != EJS_TYPE_OBJECT) { - ejsClearVar(ep, ejsGetVarPtr(prop)); - } - ejsFree(ep, prop, EJS_SLAB_PROPERTY); - - return 0; -} - -/******************************************************************************/ -/* - * Remove a property's value from this object. The property is set to - * undefined. - */ - -EjsVar *ejsClearProperty(Ejs *ep, EjsVar *vp, const char *property) -{ - EjsProperty *prop; - - mprAssert(vp); - mprAssert(property && *property); - mprAssert(vp->type == EJS_TYPE_OBJECT); - - if (vp->type != EJS_TYPE_OBJECT) { - mprAssert(vp->type == EJS_TYPE_OBJECT); - return 0; - } - - prop = hashLookup(vp->objectState, property, 0, 0); - if (prop == (EjsProperty*) 0) { - return 0; - } -#if FUTURE - if (prop->readonly) { - mprAssert(! prop->readonly); - return 0; - } -#endif - - ejsClearVar(ep, &prop->var); - return &prop->var; -} - -/******************************************************************************/ -/* - * Unlink a property from the ordered list of properties - */ - -static void unlinkProperty(EjsObj *obj, EjsPropLink *propLink) -{ - propLink->prev->next = propLink->next; - propLink->next->prev = propLink->prev; -} - -/******************************************************************************/ -#if UNUSED && KEEP -/* - * Insert a link after a specified link. - */ - -static void linkPropertyAfter(EjsObj *obj, EjsPropLink *at, - EjsPropLink *propLink) -{ - propLink->next = at->next; - propLink->prev = at; - - at->next->prev = propLink; - at->next = propLink; -} - -#endif -/******************************************************************************/ -/* - * Insert a link before a specified link. - */ - -static void linkPropertyBefore(EjsObj *obj, EjsPropLink *at, - EjsPropLink *propLink) -{ - propLink->prev = at->prev; - propLink->next = at; - - at->prev->next = propLink; - at->prev = propLink; -} - -/******************************************************************************/ -/* - * This routine will sort properties in an object. If propertyName is not - * null, then the properties in op must be objects with a property of the - * name propertyName. If propertyName is null, then the properties of op - * are directly sorted. If order is 1, they are sorted in ascending order. - * If -1, they are sorted in descending order. - * - * NOTE: arrays keep their original index values. - */ - -void ejsSortProperties(Ejs *ep, EjsVar *op, EjsSortFn fn, - const char *propertyName, int order) -{ - EjsProperty *p1, *p2, *tmp; - EjsPropLink *l1, *l2, *oldL1Spot; - EjsObj *obj; - - obj = op->objectState; - - p1 = ejsGetFirstProperty(op, 0); - while (p1) { - if (p1->dontEnumerate) { - p1 = ejsGetNextProperty(p1, 0); - continue; - } - - p2 = ejsGetFirstProperty(op, 0); - while (p2 && p2 != p1) { - - if (p2->dontEnumerate) { - p2 = ejsGetNextProperty(p2, 0); - continue; - } - - if (fn == 0) { - if (propertyName) { - fn = sortByProperty; - } else { - fn = sortAllProperties; - } - } - - if (fn(ep, p1, p2, propertyName, order) < 0) { - - l1 = &p1->link; - l2 = &p2->link; - - /* - * Swap the properties without disturbing the hash chains. - * l1 is always after l2 in the list. Unlink l1 and remember - * the one after l1. - */ - oldL1Spot = l1->next; - unlinkProperty(obj, l1); - - /* - * Manually reinsert l1 by replacing l2 with l1. l2 is out of - * the chain. - */ - l2->prev->next = l1; - l2->next->prev = l1; - l1->prev = l2->prev; - l1->next = l2->next; - - /* - * Reinsert l2 before the spot where l1 was. - */ - linkPropertyBefore(obj, oldL1Spot, l2); - - /* - * Swap the pointers so we continue to traverse correctly - */ - tmp = p1; - p1 = p2; - p2 = tmp; - } - p2 = ejsGetNextProperty(p2, 0); - } - p1 = ejsGetNextProperty(p1, 0); - } -} - -/******************************************************************************/ -/* - * Sort properties. Strings are sorted in ascending ASCII collating sequence - * Numbers are sorted in increasing numerical order. - */ -static int sortAllProperties(Ejs *ep, EjsProperty *p1, EjsProperty *p2, - const char *propertyName, int order) -{ - EjsVar *v1, *v2; - char *buf1, *buf2; - int rc, buf1Alloc; - - v1 = ejsGetVarPtr(p1); - v2 = ejsGetVarPtr(p2); - - if (v1->type == v2->type) { - /* MOB -- should support Numbers */ - if (v1->type == EJS_TYPE_INT) { - if (v1->integer < v2->integer) { - return - order; - - } else if (v1->integer == v2->integer) { - return 0; - } - return order; - -#if BLD_FEATURE_FLOATING_POINT - } else if (v1->type == EJS_TYPE_FLOAT) { - if (v1->floating < v2->floating) { - return - order; - - } else if (v1->floating == v2->floating) { - return 0; - } - return order; - -#endif - } else if (v1->type == EJS_TYPE_STRING) { - /* MOB -- need binary support ? */ - return strcmp(v1->string, v2->string) * order; - - } else { - - buf1 = ejsVarToStringEx(ep, v1, &buf1Alloc); - buf2 = ejsVarToString(ep, v2); - - rc = strcmp(buf1, buf2); - - if (buf1Alloc) { - mprFree(buf1); - } - - return rc * order; - } - - } else { - /* Type mismatch in array */ - return 0; - } - return 0; -} - -/******************************************************************************/ -/* - * Sort an object by a given property. - */ -static int sortByProperty(Ejs *ep, EjsProperty *p1, EjsProperty *p2, - const char *propertyName, int order) -{ - EjsVar *o1, *o2, *v1, *v2; - char *buf1, *buf2; - int rc, buf1Alloc; - - o1 = ejsGetVarPtr(p1); - o2 = ejsGetVarPtr(p2); - - if (!ejsVarIsObject(o1) || !ejsVarIsObject(o2)) { - mprAssert(ejsVarIsObject(o1)); - mprAssert(ejsVarIsObject(o2)); - return 0; - } - - v1 = ejsGetPropertyAsVar(ep, o1, propertyName); - v2 = ejsGetPropertyAsVar(ep, o2, propertyName); - - if (v1 == 0 || v2 == 0) { - /* Property name not found */ - return 0; - } - - if (v1->type != v2->type) { - mprAssert(v1->type == v2->type); - return 0; - } - - if (v1->type == v2->type) { - /* MOB -- should support Numbers */ - if (v1->type == EJS_TYPE_INT) { - if (v1->integer < v2->integer) { - return -order; - - } else if (v1->integer == v2->integer) { - return 0; - } - return order; - -#if BLD_FEATURE_FLOATING_POINT - } else if (v1->type == EJS_TYPE_FLOAT) { - if (v1->floating < v2->floating) { - return -order; - - } else if (v1->floating == v2->floating) { - return 0; - } - return order; - -#endif - } else if (v1->type == EJS_TYPE_STRING) { - /* MOB -- need binary support ? */ - return strcmp(v1->string, v2->string) * order; - - } else { - buf1 = ejsVarToStringEx(ep, v1, &buf1Alloc); - - buf2 = ejsVarToString(ep, v2); - - rc = strcmp(buf1, buf2); - - if (buf1Alloc) { - mprFree(buf1); - } - - return rc * order; - } - - } else { - /* Type mismatch in array */ - return 0; - } - return 0; -} - -/******************************************************************************/ -/* - * Set a property's name - */ - -void ejsSetPropertyName(EjsProperty *pp, const char *property) -{ - mprStrcpy(pp->name, sizeof(pp->name), property); -} - -/******************************************************************************/ - -int ejsMakePropertyEnumerable(EjsProperty *prop, int enumerate) -{ - int oldValue; - - oldValue = prop->dontEnumerate; - prop->dontEnumerate = !enumerate; - return oldValue; -} - -/******************************************************************************/ - -void ejsMakePropertyPrivate(EjsProperty *prop, int isPrivate) -{ - prop->isPrivate = isPrivate; -} - -/******************************************************************************/ -/* - * Make a variable read only. Can still be deleted. - */ - -void ejsMakePropertyReadOnly(EjsProperty *prop, int readonly) -{ - prop->readonly = readonly; -} - -/******************************************************************************/ - -int ejsMakeObjPermanent(EjsVar *vp, int permanent) -{ - int oldValue; - - if (vp && vp->type == EJS_TYPE_OBJECT) { - oldValue = vp->objectState->permanent; - vp->objectState->permanent = permanent; - } else { - oldValue = 0; - } - return oldValue; -} - -/******************************************************************************/ - -int ejsMakeObjLive(EjsVar *vp, bool alive) -{ - int oldValue; - - oldValue = 0; - if (vp && vp->type == EJS_TYPE_OBJECT) { - oldValue = vp->objectState->alive; - vp->objectState->alive = alive; - } else { - oldValue = 0; - } - return oldValue; -} - -/******************************************************************************/ - -void ejsMakeClassNoConstructor(EjsVar *vp) -{ - mprAssert(vp->type == EJS_TYPE_OBJECT); - - if (vp->type == EJS_TYPE_OBJECT) { - vp->objectState->noConstructor = 1; - } -} - -/******************************************************************************/ -/* - * Get the count of properties. - */ - -int ejsGetPropertyCount(EjsVar *vp) -{ - EjsProperty *pp; - EjsPropLink *lp, *head; - int count; - - mprAssert(vp); - - if (vp->type != EJS_TYPE_OBJECT) { - return 0; - } - - count = 0; - - head = &vp->objectState->link; - for (lp = head->next; lp != head; lp = lp->next) { - pp = ejsGetPropertyFromLink(lp); - if (! pp->dontEnumerate) { - count++; - } - } - return count; -} - -/******************************************************************************/ -/* - * Get the first property in an object. Used for walking all properties in an - * object. This will only enumerate properties in this class and not in base - * classes. - */ - -EjsProperty *ejsGetFirstProperty(const EjsVar *op, int flags) -{ - EjsProperty *pp; - EjsObj *obj; - EjsPropLink *head, *lp; - - mprAssert(op); - mprAssert(op->type == EJS_TYPE_OBJECT); - - if (op->type != EJS_TYPE_OBJECT) { - mprAssert(op->type == EJS_TYPE_OBJECT); - return 0; - } - pp = 0; - - do { - obj = op->objectState; - - head = &obj->link; - lp = head->next; - - while (lp != head) { - pp = ejsGetPropertyFromLink(lp); - if (! pp->dontEnumerate || (flags & EJS_ENUM_HIDDEN)) { - break; - } - lp = lp->next; - } - if (lp != head || op->type != EJS_TYPE_OBJECT || - !(flags & EJS_ENUM_CLASSES)) { - break; - } - - op = obj->baseClass; - - } while (lp == 0 && op); - - return pp; -} - -/******************************************************************************/ -/* - * Get the next property in sequence. This will only enumerate properties in - * this class and not in base classes. - */ - -EjsProperty *ejsGetNextProperty(EjsProperty *last, int flags) -{ - EjsProperty *pp; - EjsObj *obj; - EjsPropLink *lp, *head; - - obj = last->parentObj; - - lp = last->link.next; - head = &obj->link; - pp = 0; - - while (obj) { - while (lp != head) { - pp = ejsGetPropertyFromLink(lp); - if (! pp->dontEnumerate || (flags & EJS_ENUM_HIDDEN)) { - break; - } - lp = lp->next; - } - if (lp != head || !(flags & EJS_ENUM_CLASSES)) { - break; - } - - /* - * Now iterate over properties in base classes (down the chain) - */ - if (obj->baseClass == 0) { - break; - } - - obj = obj->baseClass->objectState; - if (obj == 0) { - break; - } - } - return pp; -} - -/******************************************************************************/ -/* - * Find a variable given a variable name and return the parent object and - * the variable itself. This routine supports literal variable and property - * names that may be objects or arrays but may NOT have expressions. - * Returns -1 on errors or if the variable is not found. - * FUTURE -- Needs OPT - */ - -EjsVar *ejsFindProperty(Ejs *ep, EjsVar **obj, char **property, EjsVar *global, - EjsVar *local, const char *fullName, int create) -{ - EjsProperty *currentProp; - EjsVar *currentObj; - /* MOB -- WARNING BIG */ - char tokBuf[EJS_MAX_ID], propertyName[EJS_MAX_ID]; - char *token, *next, *cp, *endp; - - mprAssert(fullName && *fullName); - - currentProp = 0; - currentObj = 0; - - if (global == 0) { - global = ep->global; - } - - if (obj) { - *obj = 0; - } - if (property) { - *property = 0; - } - - if (fullName == 0) { - return 0; - } - - next = (char*) fullName; - token = getNextVarToken(&next, tokBuf, sizeof(tokBuf)); - mprStrcpy(propertyName, sizeof(propertyName), token); - - if (local) { - currentProp = ejsGetProperty(ep, local, token); - currentObj = local; - } - if (currentProp == 0) { - currentProp = ejsGetProperty(ep, global, token); - currentObj = global; - } - - token = getNextVarToken(&next, tokBuf, sizeof(tokBuf)); - - while (currentObj != 0 && token != 0 && *token) { - - if (currentProp == 0) { - return 0; - } - currentObj = ¤tProp->var; - currentProp = 0; - - if (*token == '[') { - token = getNextVarToken(&next, tokBuf, sizeof(tokBuf)); - - mprStrcpy(propertyName, sizeof(propertyName), token); - cp = propertyName; - if (*cp == '\"') { - cp++; - if ((endp = strchr(cp, '\"')) != 0) { - *endp = '\0'; - } - } else if (*cp == '\'') { - cp++; - if ((endp = strchr(cp, '\'')) != 0) { - *endp = '\0'; - } - } - - currentProp = ejsGetProperty(ep, currentObj, propertyName); - - token = getNextVarToken(&next, tokBuf, sizeof(tokBuf)); - if (*token != ']') { - return 0; - } - - } else if (*token == '.') { - token = getNextVarToken(&next, tokBuf, sizeof(tokBuf)); - if (!isalpha((int) token[0]) && - token[0] != '_' && token[0] != '$') { - return 0; - } - - mprStrcpy(propertyName, sizeof(propertyName), token); - currentProp = ejsGetProperty(ep, currentObj, token); - - } else { - currentProp = ejsGetProperty(ep, currentObj, token); - } - - if (next == 0 || *next == '\0') { - break; - } - token = getNextVarToken(&next, tokBuf, sizeof(tokBuf)); - } - - if (obj) { - *obj = currentObj; - } - - - if (currentProp == 0 && currentObj >= 0 && create) { - currentProp = ejsCreateSimpleProperty(ep, currentObj, propertyName); - } - - if (property) { - *property = currentProp->name; - } - return ejsGetVarPtr(currentProp); -} - -/******************************************************************************/ -/* - * Get the next token as part of a variable specification. This will return - * a pointer to the next token and will return a pointer to the next token - * (after this one) in "next". The tokBuf holds the parsed token. - */ - -static char *getNextVarToken(char **next, char *tokBuf, int tokBufLen) -{ - char *start, *cp; - int len; - - start = *next; - while (isspace((int) *start) || *start == '\n' || *start == '\r') { - start++; - } - cp = start; - - if (*cp == '.' || *cp == '[' || *cp == ']') { - cp++; - } else { - while (*cp && *cp != '.' && *cp != '[' && *cp != ']' && - !isspace((int) *cp) && *cp != '\n' && *cp != '\r') { - cp++; - } - } - len = mprMemcpy(tokBuf, tokBufLen - 1, start, cp - start); - tokBuf[len] = '\0'; - - *next = cp; - return tokBuf; -} - -/******************************************************************************/ - -EjsVar *ejsGetGlobalClass(Ejs *ep) -{ - return ep->global; -} - -/******************************************************************************/ -/*************************** Property Access Methods **************************/ -/******************************************************************************/ -/* - * Create an undefined property. This routine calls the object method hooks. - */ - -/* MOB -- better suffix than "Method" */ -EjsVar *ejsCreatePropertyMethod(Ejs *ep, EjsVar *op, const char *property) -{ - EjsVar *vp; - - mprAssert(ep); - mprAssert(op); - mprAssert(property && *property); - - if (op == 0) { - return 0; - } - - mprAssert(op->type == EJS_TYPE_OBJECT); - mprAssert(op->objectState); - - if (op->objectState == 0) { - return 0; - } - - if (op->objectState->methods == 0) { - vp = ejsGetVarPtr(ejsCreateSimpleProperty(ep, op, property)); - } else { - vp = (op->objectState->methods->createProperty)(ep, op, property); - } - - if (vp == 0) { - mprAssert(vp); - op->objectState->hasErrors = 1; - return 0; - } - - /* - * FUTURE - find a better way. - */ - if (op->isArray) { - ejsSetArrayLength(ep, op, property, 0, 0); - } - return vp; -} - -/******************************************************************************/ - -int ejsDeletePropertyMethod(Ejs *ep, EjsVar *op, const char *property) -{ - int rc; - - mprAssert(ep); - mprAssert(op); - mprAssert(property && *property); - - if (op == 0) { - return -1; - } - - mprAssert(op->type == EJS_TYPE_OBJECT); - mprAssert(op->objectState); - - if (op->objectState == 0) { - return -1; - } - - if (op->objectState->methods == 0) { - rc = ejsDeleteProperty(ep, op, property); - } else { - rc = (op->objectState->methods->deleteProperty)(ep, op, property); - } - - if (rc < 0) { - op->objectState->hasErrors = 1; - } - - op->objectState->dirty = 1; - - return rc; -} - -/******************************************************************************/ -/* - * Set the value of a property. Create if it does not exist - * If the object has property accessor methods defined, use those. - */ - -EjsVar *ejsSetPropertyMethod(Ejs *ep, EjsVar *op, const char *property, - const EjsVar *value) -{ - EjsVar *vp; - - mprAssert(ep); - mprAssert(op); - mprAssert(property && *property); - mprAssert(value); - - if (op == 0) { - return 0; - } - - mprAssert(op->type == EJS_TYPE_OBJECT); - mprAssert(op->objectState); - - if (op->objectState == 0) { - return 0; - } - - if (op->objectState->methods == 0) { - vp = ejsGetVarPtr(ejsCreateSimpleProperty(ep, op, property)); - if (vp && ejsWriteVar(ep, vp, (EjsVar*) value, EJS_SHALLOW_COPY) < 0) { - mprAssert(0); - op->objectState->hasErrors = 1; - return 0; - } - - } else { - vp = (op->objectState->methods->setProperty)(ep, op, property, value); - } - - if (vp == 0) { - mprAssert(vp); - op->objectState->hasErrors = 1; - return 0; - } - - if (vp->type == EJS_TYPE_OBJECT) { - /* - * We make an object alive (and subject to garbage collection) when - * it is referenced in some other object. If this is undesirable, the - * caller should make the object permanent while calling this routine - * and then afterward clear the alive bit by calling ejsMakeObjLive(). - */ - if (op->objectState != vp->objectState) { - vp->objectState->alive = 1; - } -#if BLD_DEBUG - { - EjsProperty *pp = ejsGetPropertyPtr(vp); - ejsSetVarName(ep, vp, &pp->name[0]); - if (value->propertyName == 0) { - ejsSetVarName(ep, (EjsVar*) value, &pp->name[0]); - } - } -#endif - } - - /* - * Trap assignments to array.length. MOB - find a better way. - */ - if (vp->isArrayLength) { - ejsSetArrayLength(ep, op, 0, 0, value); - } - - op->objectState->dirty = 1; - - return vp; -} - -/******************************************************************************/ - -EjsVar *ejsGetPropertyMethod(Ejs *ep, EjsVar *op, const char *property) -{ - mprAssert(ep); - mprAssert(op); - mprAssert(property && *property); - - if (op == 0) { - return 0; - } - - mprAssert(op->type == EJS_TYPE_OBJECT); - mprAssert(op->objectState); - - if (op->objectState == 0) { - return 0; - } - - if (op->objectState->methods == 0) { - return ejsGetVarPtr(ejsGetSimpleProperty(ep, op, property)); - } else { - return (op->objectState->methods->getProperty)(ep, op, property); - } -} - -/******************************************************************************/ -/*************************** Advisory Locking Support *************************/ -/******************************************************************************/ -#if BLD_FEATURE_MULTITHREAD - -void ejsLockObj(EjsVar *vp) -{ - mprAssert(vp); - mprAssert(vp->type == EJS_TYPE_OBJECT); - mprAssert(vp->objectState); - - if (vp->objectState->mutex == 0) { - vp->objectState->mutex = mprCreateLock(vp->objectState->ejs); - } - mprLock(vp->objectState->mutex); -} - -/******************************************************************************/ - -void ejsUnlockObj(EjsVar *vp) -{ - mprAssert(vp); - mprAssert(vp->type == EJS_TYPE_OBJECT); - mprAssert(vp->objectState); - - if (vp->objectState->mutex) { - mprUnlock(vp->objectState->mutex); - } -} - -#endif -/******************************************************************************/ -/************************** Internal Support Routines *************************/ -/******************************************************************************/ -/* - * Create an object. - */ - -static EjsObj *createObj(EJS_LOC_DEC(ep, loc)) -{ - EjsObj *op; - EjsPropLink *lp; - - op = (EjsObj*) ejsAllocObj(EJS_LOC_PASS(ep, loc)); - if (op == NULL) { - return 0; - } - - /* - * The objectState holds the dummy head for the ordered list of properties - */ - lp = &op->link; - lp->next = lp->prev = lp; - -#if BLD_DEBUG - /* - * This makes it much easier to debug the list - */ - lp->head = lp; - lp->propertyName = "dummyHead"; -#endif - - return op; -} - -/******************************************************************************/ -/* - * Destroy an object. Called by the garbage collector if there are no more - * references to an object. - */ - -int ejsDestroyObj(Ejs *ep, EjsObj *obj) -{ - EjsProperty *pp; - EjsPropLink *lp, *head, *nextLink; - - mprAssert(obj); - - if (obj->destructor) { - EjsVar v; - memset(&v, 0, sizeof(v)); - v.type = EJS_TYPE_OBJECT; - v.objectState = obj; - ejsSetVarName(ep, &v, "destructor"); - -#if BLD_FEATURE_ALLOC_LEAK_TRACK - v.gc.allocatedBy = "static"; -#endif - - if ((obj->destructor)(ep, &v) < 0) { - return -1; - } - } - mprFree(obj->objName); - obj->objName = 0; - - /* - * Just for safety. An object may be marked by a GC on the default - * interpreter. After destroying, it won't be on the free list and so - * won't be reset. - */ - obj->gcMarked = 0; - obj->visited = 0; - - head = &obj->link; - for (lp = head->next; lp != head; lp = nextLink) { - - pp = ejsGetPropertyFromLink(lp); - nextLink = lp->next; - - /* - * We don't unlink as we are destroying all properties. - * If an object, we don't need to clear either. - */ - if (pp->var.type != EJS_TYPE_OBJECT) { - ejsClearVar(ep, ejsGetVarPtr(pp)); - } - ejsFree(ep, pp, EJS_SLAB_PROPERTY); - } - -#if BLD_FEATURE_MULTITHREAD - if (obj->mutex) { - mprDestroyLock(obj->mutex); - } -#endif - - ejsFree(ep, obj, EJS_SLAB_OBJ); - return 0; -} - -/******************************************************************************/ -/* - * Fast hash. The history of this algorithm is part of lost computer science - * folk lore. - */ - -static int hash(const char *property) -{ - uint sum; - - mprAssert(property); - - sum = 0; - while (*property) { - sum += (sum * 33) + *property++; - } - - return sum % EJS_OBJ_HASH_SIZE; -} - -/******************************************************************************/ -/* - * Set a new length for an array. If create is non-null, then it is the name - * of a new array index. If delete is set, it is the name of an index being - * deleted. If setLength is set to a variable, it counts the new length for the - * array. Note that create and delete are ignored if they are non-integer - * array indexes (eg. normal properties). - */ - -void ejsSetArrayLength(Ejs *ep, EjsVar *obj, const char *create, - const char *delete, const EjsVar *setLength) -{ - EjsVar *vp; - char idx[16]; - int oldSize, newSize, i; - - vp = ejsGetPropertyAsVar(ep, obj, "length"); - oldSize = vp->integer; - newSize = oldSize; - - if (create) { - if (isdigit(*create)) { - i = atoi(create); - newSize = max(i + 1, oldSize); - } - } else if (delete) { - if (isdigit(*delete)) { - i = atoi(delete); - newSize = (i == (oldSize - 1) ? oldSize - 1 : oldSize); - } - } else { - newSize = setLength->integer; - } - - for (i = newSize; i < oldSize; i++) { - mprItoa(idx, sizeof(idx), i); - ejsDeleteProperty(ep, obj, idx); - } - - if (ejsWriteVarAsInteger(ep, vp, newSize) == 0) { - mprAssert(0); - } -} - -/******************************************************************************/ - -void ejsClearObjErrors(EjsVar *vp) -{ - if (vp == 0 || vp->type != EJS_TYPE_OBJECT || vp->objectState == 0) { - mprAssert(0); - return; - } - vp->objectState->hasErrors = 0; -} - -/******************************************************************************/ - -int ejsObjHasErrors(EjsVar *vp) -{ - if (vp == 0 || vp->type != EJS_TYPE_OBJECT || vp->objectState == 0) { - mprAssert(0); - return -1; - } - return vp->objectState->hasErrors; -} - -/******************************************************************************/ - -bool ejsIsObjDirty(EjsVar *vp) -{ - mprAssert(vp->type == EJS_TYPE_OBJECT && vp->objectState); - - if (vp->type == EJS_TYPE_OBJECT && vp->objectState) { - return vp->objectState->dirty; - } - return 0; -} - -/******************************************************************************/ - -void ejsResetObjDirtyBit(EjsVar *vp) -{ - mprAssert(vp->type == EJS_TYPE_OBJECT && vp->objectState); - - if (vp->type == EJS_TYPE_OBJECT && vp->objectState) { - vp->objectState->dirty = 0; - } -} - -/******************************************************************************/ -/* - * Copy a string. Always null terminate. - */ - -static int dupString(MPR_LOC_DEC(ctx, loc), uchar **dest, const void *src, - int nbytes) -{ - mprAssert(dest); - mprAssert(src); - - if (nbytes > 0) { - *dest = mprMemdupInternal(MPR_LOC_PASS(ctx, loc), src, nbytes + 1); - if (*dest == 0) { - return MPR_ERR_MEMORY; - } - - } else { - *dest = (uchar*) mprAlloc(ctx, 1); - nbytes = 0; - } - - (*dest)[nbytes] = '\0'; - - return nbytes; -} - -/******************************************************************************/ - -const char *ejsGetVarTypeAsString(EjsVar *vp) -{ - switch (vp->type) { - default: - case EJS_TYPE_UNDEFINED: - return "undefined"; - case EJS_TYPE_NULL: - return "null"; - case EJS_TYPE_BOOL: - return "bool"; - case EJS_TYPE_CMETHOD: - return "cmethod"; - case EJS_TYPE_FLOAT: - return "float"; - case EJS_TYPE_INT: - return "int"; - case EJS_TYPE_INT64: - return "int64"; - case EJS_TYPE_OBJECT: - return "object"; - case EJS_TYPE_METHOD: - return "method"; - case EJS_TYPE_STRING: - return "string"; - case EJS_TYPE_STRING_CMETHOD: - return "string method"; - case EJS_TYPE_PTR: - return "ptr"; - } -} - -/******************************************************************************/ - -void *ejsGetVarUserPtr(EjsVar *vp) -{ - mprAssert(vp); - mprAssert(vp->type == EJS_TYPE_PTR); - - if (!ejsVarIsPtr(vp)) { - return 0; - } - return vp->ptr.userPtr; -} - -/******************************************************************************/ - -void ejsSetVarUserPtr(EjsVar *vp, void *data) -{ - mprAssert(vp); - mprAssert(vp->type == EJS_TYPE_PTR); - - vp->ptr.userPtr = data; -} - -/******************************************************************************/ -/* - * Return TRUE if target is a subclass (or the same class) as baseClass. - */ - -bool ejsIsSubClass(EjsVar *target, EjsVar *baseClass) -{ - do { - if (target->objectState == baseClass->objectState) { - return 1; - } - target = target->objectState->baseClass; - } while (target); - - return 0; -} - -/******************************************************************************/ -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/ejsVar.h b/source4/lib/appweb/ejs-2.0/ejs/ejsVar.h deleted file mode 100644 index 071665e00b..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/ejsVar.h +++ /dev/null @@ -1,1091 +0,0 @@ -/* - * ejsVar.h -- EJS Universal Variable Type - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/* - * Variables can efficiently store primitive types and can hold references to - * objects. Objects can store properties which are themselves variables. - * Properties can be primitive data types, other objects or methods. - * Properties are indexed by a character name. A variable may store one of - * the following types: - * - * string, integer, integer-64bit, C method, C method with string args, - * Javascript method, Floating point number, boolean value, Undefined - * value and the Null value. - * - * Variables have names while objects may be referenced by multiple variables. - * Objects use reference counting for garbage collection. - * - * This module is not thread safe for performance and compactness. It relies - * on upper modules to provide thread synchronization as required. The API - * provides primitives to get variable/object references or to get copies of - * variables which will help minimize required lock times. - */ - -#ifndef _h_EJS_VAR -#define _h_EJS_VAR 1 - -/********************************* Includes ***********************************/ - -#include "mpr.h" - -/********************************** Defines ***********************************/ -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Defined in ejs.h - */ -typedef struct Ejs Ejs; - -/* - * Constants - */ -#if BLD_FEATURE_SQUEEZE - /** - * Maximum property or variable name size - */ - #define EJS_MAX_ID 64 - - /* - * EJS_VAR_HASH_SIZE must be less than the size of the bit field - * propertyIndex in EjsProperty. - */ - #define EJS_OBJ_HASH_SIZE 13 - - /** - * Maximum number of arguments per function call - */ - #define EJS_MAX_ARGS 32 - #define EJS_INC_ARGS 8 /* Frame stack increment */ - -#else - #define EJS_MAX_ID 256 - #define EJS_OBJ_HASH_SIZE 29 - #define EJS_MAX_ARGS 64 - #define EJS_INC_ARGS 8 -#endif - -#define EJS_VAR_MAX_RECURSE 5 /* Max object loops */ - -#if !DOXYGEN -/* - * Forward declare types - */ -struct Ejs; -struct EjsObj; -struct EjsProperty; -struct EjsVar; -#endif - -/** - * @overview EJ primitive variable type - * @description EJ primitive variable values are stored in EjsVar structures. - * The type of the primitive data is described by an EjsType field. - * EjsVar variable types. - * @stability Prototype. - * @library libejs. - * @see EJS_TYPE_UNDEFINED, EJS_TYPE_NULL, EJS_TYPE_BOOL, EJS_TYPE_CMETHOD, - * EJS_TYPE_FLOAT, EJS_TYPE_INT, EJS_TYPE_INT64, EJS_TYPE_OBJECT, - * EJS_TYPE_METHOD, EJS_TYPE_STRING, EJS_TYPE_STRING_CMETHOD, EJS_TYPE_PTR, - */ -typedef uint EjsType; -#define EJS_TYPE_UNDEFINED 0 /**< Undefined. No value has been set */ -#define EJS_TYPE_NULL 1 /**< Value defined to be null. */ -#define EJS_TYPE_BOOL 2 /**< Boolean type. */ -#define EJS_TYPE_CMETHOD 3 /**< C method */ -#define EJS_TYPE_FLOAT 4 /**< Floating point number */ -#define EJS_TYPE_INT 5 /**< Integer number */ -#define EJS_TYPE_INT64 6 /**< 64-bit Integer number */ -#define EJS_TYPE_OBJECT 7 /**< Object reference */ -#define EJS_TYPE_METHOD 8 /**< JavaScript method */ -#define EJS_TYPE_STRING 9 /**< String (immutable) */ -#define EJS_TYPE_STRING_CMETHOD 10 /**< C method with string args */ -#define EJS_TYPE_PTR 11 /**< Opaque pointer */ - -/* - * Create a type for the default number type - * Config.h will define the default number type. For example: - * - * BLD_FEATURE_NUM_TYPE=int - * BLD_FEATURE_NUM_TYPE_ID=EJS_TYPE_INT - */ - -/** - * Set to the type used for EJS numeric variables. Will equate to int, int64 - * or double. - */ -typedef BLD_FEATURE_NUM_TYPE EjsNum; - -/** - * Set to the EJS_TYPE used for EJS numeric variables. Will equate to - * EJS_TYPE_INT, EJS_TYPE_INT64 or EJS_TYPE_FLOAT. - */ -#define EJS_NUM_VAR BLD_FEATURE_NUM_TYPE_ID -#define EJS_TYPE_NUM BLD_FEATURE_NUM_TYPE_ID - -/* - * Return TRUE if a variable is a method type - */ -#define ejsVarIsMethod(vp) \ - ((vp)->type == EJS_TYPE_METHOD || (vp)->type == EJS_TYPE_STRING_CMETHOD || \ - (vp)->type == EJS_TYPE_CMETHOD) - -/* - * Return TRUE if a variable is a numeric type - */ -#define ejsVarIsNumber(vp) \ - ((vp)->type == EJS_TYPE_INT || (vp)->type == EJS_TYPE_INT64 || \ - (vp)->type == EJS_TYPE_FLOAT) - -/* - * Return TRUE if a variable is a boolean - */ -#define ejsVarIsBoolean(vp) \ - ((vp)->type == EJS_TYPE_BOOL) - -/* - * Return TRUE if a variable is an integer type - */ -#define ejsVarIsInteger(vp) ((vp)->type == EJS_TYPE_INT) - -/* - * Return TRUE if a variable is a string - */ -#define ejsVarIsString(vp) \ - ((vp)->type == EJS_TYPE_STRING) - -/* - * Return TRUE if a variable is an object - */ -#define ejsVarIsObject(vp) \ - ((vp)->type == EJS_TYPE_OBJECT) - -/* - * Return TRUE if a variable is a floating number - */ -#define ejsVarIsFloating(vp) \ - ((vp)->type == EJS_TYPE_FLOAT) - -/* - * Return TRUE if a variable is undefined - */ -#define ejsVarIsUndefined(var) \ - ((var)->type == EJS_TYPE_UNDEFINED) - -/* - * Return TRUE if a variable is null - */ -#define ejsVarIsNull(var) \ - ((var)->type == EJS_TYPE_NULL) - -/* - * Return TRUE if a variable is a valid type (not null or undefined) - */ -#define ejsVarIsValid(var) \ - (((var)->type != EJS_TYPE_NULL) && ((var)->type != EJS_TYPE_UNDEFINED)) - -/* - * Return TRUE if a variable is a ptr type - */ -#define ejsVarIsPtr(vp) \ - ((vp)->type == EJS_TYPE_PTR) - -/* MOB -- convert all ep to ejs */ -/** - * @overview C Method signature - * @description This is the calling signature for C Methods. - * @param ejs Ejs reference returned from ejsCreateInterp - * @param thisObj Reference to the "this" object. (The object containing the - * method). - * @param argc Number of arguments. - * @param argv Array of arguments. Each argument is held in an EjsVar type. - * @stability Prototype. - * @library libejs. - * @see ejsCreateCMethodVar - */ -typedef int (*EjsCMethod)(struct Ejs *ejs, struct EjsVar *thisObj, - int argc, struct EjsVar **argv); - -/** - * C Method with string arguments signature - * @overview C Method with string arguments signature - * @description This is the calling signature for C Methods. - * @param ejs Ejs reference returned from ejsCreateInterp - * @param thisObj Reference to the "this" object (object containing the - * method. - * @param argc Number of arguments. - * @param argv Array of arguments. Each argument is held in an C string - * pointer. - * @stability Prototype. - * @library libejs. - * @see ejsCreateStringCMethodVar - */ -typedef int (*EjsStringCMethod)(struct Ejs *ep, struct EjsVar *thisObj, - int argc, char **argv); - -/** - * Flags for types: EJS_TYPE_CMETHOD, EJS_TYPE_STRING_CMETHOD - * NOTE: flags == 0 means to use the EJS handle on method callbacks - */ -/* Use the primary handle on method callbacks */ -#define EJS_PRIMARY_HANDLE 0x1 - -/* Use the alternate handle on method callbacks */ -#define EJS_ALT_HANDLE 0x2 - -/** Method should not create a new local variable block */ -#define EJS_NO_LOCAL 0x4 - -/* Method is a get accessor */ -#define EJS_GET_ACCESSOR 0x8 - -/* Method is a set accessor */ -#define EJS_SET_ACCESSOR 0x10 - -/* - * Flags for E4X (Xml type) - */ -/* Node is a text node */ -#define EJS_XML_FLAGS_TEXT 0x1 - -/* Node is a processing instruction */ -#define EJS_XML_FLAGS_PI 0x2 - -/* Node is a comment */ -#define EJS_XML_FLAGS_COMMENT 0x4 - -/* Node is an attribute */ -#define EJS_XML_FLAGS_ATTRIBUTE 0x8 - -/* Node is an element */ -#define EJS_XML_FLAGS_ELEMENT 0x10 - -/** - * Copy depth - * @overview Specifies how an object should be copied - * @description The EjsCopyDepth type specifies how an object's properties - * should be copied. Several routines take EjsCopyDepth parameters to - * control how the properties of an object should be copied. It provides - * three copy options: - * @see ejsWriteVar - */ -typedef enum EjsCopyDepth { - /** - * During an object copy, object property references will be copied so - * that the original object and the copy will share the same reference to - * a property object. Properties containing primitive types including - * strings will have their values copied and will not share references. - */ - EJS_SHALLOW_COPY, /** Copy strings. Copy object references. */ - /* - * During an object copy, object properties will be replicated so that - * the original object and the copy will not share references to the same - * object properties. If the original object's properties are themselves - * objects, their properties will not be copied. Only their references - * will be copied. i.e. the deep copy is one level deep. - */ - EJS_DEEP_COPY, /** Copy strings and copy object contents. */ - /* - * During an object copy, all object properties will be replicated so that - * the original object and the copy will not share references to the same - * object properties. If the original object's properties are themselves - * objects, their properties will be copied. i.e. the copy is of infinite - * depth. - */ - EJS_RECURSIVE_DEEP_COPY /** Copy strings and copy object contents - recursively (complete copy). */ -} EjsCopyDepth; - - -/* - * Enumeration flags - */ -/** Enumerate data properties */ -#define EJS_ENUM_DATA 0x0 - -/** Enumerate sub classes */ -#define EJS_ENUM_CLASSES 0x1 - -/** Enumerate non-enumerable properties */ -#define EJS_ENUM_HIDDEN 0x2 - -/** Enumerate all properties */ -#define EJS_ENUM_ALL (0x3) - -/** Magic number when allocated */ -#define EJS_MAGIC 0xe801e2ec -#define EJS_MAGIC_FREE 0xe701e3ea - - -/* - * Garbage Collection Linkage. Free list only uses the next pointers. - */ -typedef struct EjsGCLink { -#if BLD_DEBUG - uint magic; /* Magic number */ -#endif -#if BLD_FEATURE_ALLOC_LEAK_TRACK - const char *allocatedBy; /* Who allocated this */ -#endif - struct EjsGCLink *next; /* Next property */ -} EjsGCLink; - - -/** - * @overview EJS Variable Type - * @description The EJ language supports an extensive set of primitive types. - * These variable types can efficiently store primitive data types such as - * integers, strings, binary string, booleans, floating point numbers, - * pointer references, and objects. EjsVars are the universal type used by - * EJ to hold objects, classes and properties. - * \n\n - * An EjsVar may store one of the following types: - * @li Boolean - * @li Floating point (if supported in this build) - * @li Integer - * @li 64 bit integer (if supported in this build) - * @li String - * @li Binary string - * @li C function or C++ method - * @li C function with string args - * @li Javascript method - * @li Object - * @li Null value. - * @li Undefined value - * \n\n - * Objects can hold object properties which are themselves EJS variables. - * Properties are hash indexed by the property name and are stored in - * an ordered sequence. i.e. Order of properties is maintained. Objects may - * be referenced by multiple variables and they use garbage collection to - * reclaim memory no longer in use by objects and properties. - * - * @warning This module is @e not thread safe for performance and - * compactness. It relies on upper modules to provide thread - * synchronization as required. The API provides primitives to get - * variable/object references or to get copies of variables which should - * help minimize required lock times. - * @stability Prototype. - * @library libejs - * @see Ejs, EjsProperty, ejsCreateStringVar, ejsFreeVar - */ - -typedef struct EjsVar { /* Size 12 bytes */ - /* - * GC must be first - */ -#if BLD_DEBUG || BLD_FEATURE_ALLOC_LEAK_TRACK - EjsGCLink gc; /* Garbage collection links */ -#endif - -#if BLD_DEBUG - const char *propertyName; /* Ptr to property name */ -#endif - - /* - * Union of primitive types. When debugging on Linux, don't use unions - * as the gdb debugger can't display them. - */ -#if (!BLD_DEBUG && !VXWORKS) || WIN || BREW_SIMULATOR - union { -#endif - /* - * For debugging, we order the common types first - */ - struct EjsObj *objectState; /* Object state information */ - int integer; - bool boolean; - -#if BLD_FEATURE_FLOATING_POINT - double floating; -#endif -#if BLD_FEATURE_INT64 - int64 integer64; -#endif - - struct { - int length; /* String length (sans null) */ - /* - * All strings always have a trailing null allocated - */ - union { - char *string; /* String */ - uchar *ustring; /* Binary string */ - }; - }; - - struct { /* Javascript methods */ - MprArray *args; /* Null terminated */ - char *body; - } method; - - struct { /* Method with EjsVar args */ - EjsCMethod fn; /* Method pointer */ - void *userData; /* User data for method */ - } cMethod; - - struct { /* Method with string args */ - EjsStringCMethod fn; /* Method pointer */ - void *userData; /* User data for method */ - } cMethodWithStrings; - - struct { - void *userPtr; /* Opaque pointer */ - int (*destructor)(Ejs *ejs, struct EjsVar *vp); - } ptr; - -#if (!BLD_DEBUG && !VXWORKS) || WIN || BREW_SIMULATOR - }; -#endif - - /* - * Packed bit field (32 bits) - */ - uint flags : 8; /* Type specific flags */ - EjsType type : 4; /* Selector into union */ - uint stringLen : 4; /* Length of string if inline */ - uint allocatedData : 1; /* Node needs freeing */ - uint isArray : 1; /* Var is an array */ - uint isArrayLength : 1; /* Var is array.length */ - uint callsSuper : 1; /* Method calls super() */ - uint isProperty : 1; /* Part of a property */ - uint reserved : 11; /* Unused */ - -} EjsVar; - - -/* - * Linkage for the ordered list of properties - */ -typedef struct EjsPropLink { - struct EjsPropLink *next; /* Next property */ - struct EjsPropLink *prev; /* Previous property */ - - /* - * To make debugging easier - */ -#if BLD_DEBUG - const char *propertyName; /* Pointer to name */ - struct EjsProperty *property; /* Pointer to property */ - struct EjsPropLink *head; /* Dummy head of list */ -#endif -} EjsPropLink; - - -/** - * @overview Object Property Type - * @description The EjsProperty type is used to store all object properties. - * It contains the property name, property linkage, propery attributes - * such as public/private, enumerable and readonly settings. It also - * contains an EjsVar to store the property data value. - * @stability Prototype. - * @library libejs - * @see Ejs, EjsVar - */ -typedef struct EjsProperty { /* Size 96 bytes in squeeze */ - /* - * EjsVar must be first. We often take the address of "var" and take - * advantage of if an EjsProperty is null, then &prop->var will be null - * also. Be WARNED. External users should use ejsGetVarPtr and - * ejsGetPropertyPtr to convert between the two. - */ - EjsVar var; /* Property value */ - - /* OPT change this to a pointer to the base class property */ - char name[EJS_MAX_ID]; /* Name */ - - uint visited : 1; /* Has been traversed */ - uint isPrivate : 1; /* Property is private */ - uint isProtected : 1; /* Property is protected */ - uint dontEnumerate : 1; /* Not enumerable */ - uint dontDelete : 1; /* Prevent delete */ - uint readonly : 1; /* Unmodifiable */ - uint allowNonUnique : 1; /* Multiple of same name ok */ - uint delayedDelete : 1; - uint reserved : 24; - - EjsPropLink link; /* Ordered linked list */ - struct EjsProperty *hashNext; /* Hash table linkage */ - - /* MOB -- is this really required */ - struct EjsObj *parentObj; /* Pointer to parent object */ - -} EjsProperty; - - -#define EJS_OP_DOT 0x1 -#define EJS_OP_INDEX 0x2 -#define EJS_OP_PLUS 0x3 -#define EJS_OP_MINUS 0x4 -#define EJS_OP_MULTIPLY 0x5 -#define EJS_OP_DIVIDE 0x6 -#define EJS_OP_CALL 0x7 - -typedef struct EjsOp { - int opType; - -} EjsOp; - -/* - * Propety Access Methods. Used per class. - * MOB -- rename EjsHelpers - */ -typedef struct EjsMethods { -#if FUTURE - int (*create)(Ejs *ep, EjsVar *thisObj); - int (*deleteProperty)(Ejs *ep, EjsVar *thisObj, const char *prop); - EjsVar *(*getProperty)(Ejs *ep, EjsVar *thisObj, const char *prop); - EjsVar *(*setProperty)(Ejs *ep, EjsVar *thisObj, const char *prop); - int (*hasProperty)(Ejs *ep, EjsVar *thisObj, const char *prop); - int (*hasInstance)(Ejs *ep, EjsVar *thisObj, const char *prop); - int (*operate)(Ejs *ep, EjsVar *thisObj, EjsOp op, EjsVar *result, - EjsVar *lhs, EjsVar *rhs, int *code); -#else - - EjsVar *(*createProperty)(Ejs *ep, EjsVar *obj, const char *property); - int (*deleteProperty)(Ejs *ep, EjsVar *obj, const char *property); - EjsVar *(*getProperty)(Ejs *ep, EjsVar *obj, const char *property); - EjsVar *(*setProperty)(Ejs *ep, EjsVar *obj, const char *property, - const EjsVar *value); - /* - * Other implemented internal properties in ECMA-262 are: - * - * [[Construct]] implemented via EjsVar methods - * [[Prototype]] implemented via EjsObj->baseClass - * [[Class]] implemented via EjsObj->baseClass->name - * [[Value]] Implemented via EjsProperty + EjsVar + EjsObj - */ - - /* - * FUTURE -- not implemented - */ - int (*canPut)(Ejs *ep, EjsVar *obj, const char *property); - int (*defaultValue)(Ejs *ep, EjsVar *obj, const char *property, - const char *hint); - int (*hasProperty)(Ejs *ep, EjsVar *obj, const char *property); - EjsVar *(*call)(Ejs *ep, EjsVar *obj, const char *property, - EjsVar *args); - int (*hasInstance)(Ejs *ep, EjsVar *obj, const char *property); - int (*scope)(Ejs *ep, EjsVar *obj, const char *property); - int (*match)(Ejs *ep, EjsVar *obj, const char *property, - const char *string, int index); -#endif -} EjsMethods; - - -/* - * Ejs Object Type - */ -typedef struct EjsObj { - /* - * GC must be first - */ - EjsGCLink gc; /* Garbage collection links */ - - union { - char *objName; /* Object name */ - char *className; /* Class name */ - }; - - struct EjsVar *baseClass; /* Pointer to base class object */ - - EjsPropLink link; /* Ordered list of properties */ - - /* OPT -- dynamically allocate this only if required */ - EjsProperty *propertyHash[EJS_OBJ_HASH_SIZE]; /* Hash chains */ - - /* OPT -- could save this and store off baseClass only */ - EjsMethods *methods; /* Property access methods */ - void *nativeData; /* Native object data */ - - int (*destructor)(Ejs *ejs, struct EjsVar *vp); - - uint numProperties : 16; /* Total count of items */ - uint visited : 1; /* Has been traversed */ - uint gcMarked : 1; /* Node marked in-use by GC */ - uint permanent : 1; /* Permanent object, dont GC */ - uint alive : 1; /* Only GC if alive */ - uint noConstructor : 1; /* Object has no constructor */ - uint dirty : 1; /* Object has been modified */ - uint hasErrors : 1; /* Update error */ - uint preventDeleteProp : 1; /* Don't allow prop deletion */ - uint delayedDeleteProp : 1; /* Delayed delete of props */ - uint reserved : 7; /* Unused */ - - Ejs *ejs; /* Owning interp */ - -#if BLD_FEATURE_MULTITHREAD - MprLock *mutex; /* Advisory mutex lock */ -#endif -} EjsObj; - - -/* - * Define a field macro so code an use numbers in a "generic" fashion. - */ -#if EJS_NUM_VAR == EJS_TYPE_INT || DOXYGEN -/* - * Default numeric type - */ -#define ejsNumber integer -#endif -#if EJS_NUM_VAR == EJS_TYPE_INT64 -/* Default numeric type */ -#define ejsNumber integer64 -#endif -#if EJS_NUM_VAR == EJS_TYPE_FLOAT -/* Default numeric type */ -#define ejsNumber floating -#endif - -typedef BLD_FEATURE_NUM_TYPE EjsNumber; - -/* - * Memory allocation slabs - */ -#define EJS_SLAB_OBJ 0 -#define EJS_SLAB_PROPERTY 1 -#define EJS_SLAB_VAR 2 -#define EJS_SLAB_MAX 3 - -/** - * Object and pointer property destructory type - */ -typedef int (*EjsDestructor)(Ejs *ejs, EjsVar *vp); - -#if BLD_FEATURE_ALLOC_LEAK_TRACK || DOXYGEN -/* - * Line number information args and declarations for ejsAlloc. - * Use EJS_LOC_ARGS in normal user code. - * Use EJS_LOC_DEC in declarations. - * Use EJS_LOC_PASS in layered APIs to pass original line info down. - */ -#define EJS_LOC_ARGS(ejs) ejs, MPR_LOC -#define EJS_LOC_DEC(ejs, loc) Ejs *ejs, const char *loc -#define EJS_LOC_PASS(ejs, loc) ejs, loc -#else -#define EJS_LOC_ARGS(ejs) ejs -#define EJS_LOC_DEC(ejs, loc) Ejs *ejs -#define EJS_LOC_PASS(ejs, loc) ejs -#endif - -/******************************* Internal Prototypes **************************/ - -#define ejsInitVar(vp, varType) \ - if (1) { \ - (vp)->type = varType; \ - (vp)->isArray = 0; \ - (vp)->flags = 0; \ - } else -extern void ejsClearVar(Ejs *ep, EjsVar *vp); - -extern int ejsDestroyObj(Ejs *ep, EjsObj *obj); -extern EjsVar *ejsCreatePropertyMethod(Ejs *ep, EjsVar *obj, - const char *name); -extern EjsVar *ejsSetPropertyMethod(Ejs *ep, EjsVar *obj, const char *name, - const EjsVar *value); -extern EjsVar *ejsGetPropertyMethod(Ejs *ep, EjsVar *obj, const char *name); -extern int ejsDeletePropertyMethod(Ejs *ep, EjsVar *obj, - const char *name); -extern void ejsSetArrayLength(Ejs *ep, EjsVar *obj, const char *creating, - const char *deleting, const EjsVar *setLength); - -/* - * At the moment, these are the same routine - */ -extern void ejsSetClassName(Ejs *ep, EjsVar *obj, const char *name); -#define ejsSetObjName ejsSetObjName - -extern bool ejsIsObjDirty(EjsVar *vp); -extern void ejsResetObjDirtyBit(EjsVar *vp); - -extern int ejsObjHasErrors(EjsVar *vp); -extern void ejsClearObjErrors(EjsVar *vp); - -extern EjsVar *ejsClearProperty(Ejs *ep, EjsVar *obj, const char *prop); - -typedef int (*EjsSortFn)(Ejs *ep, EjsProperty *p1, EjsProperty *p2, - const char *propertyName, int order); -extern void ejsSortProperties(Ejs *ep, EjsVar *obj, EjsSortFn fn, - const char *propertyName, int order); - -#if BLD_DEBUG -#define ejsSetVarName(ep, vp, varName) \ - if (1) { \ - (vp)->propertyName = varName; \ - if ((vp)->type == EJS_TYPE_OBJECT && \ - (vp)->objectState && \ - ((vp)->objectState->objName == 0)) { \ - (vp)->objectState->objName = \ - mprStrdup(ep, varName); \ - } \ - } else -#else -#define ejsSetVarName(ep, vp, varName) -#endif - -EjsVar *ejsFindProperty(Ejs *ep, EjsVar **obj, char **property, - EjsVar *global, EjsVar *local, const char *fullName, - int create); - -extern EjsVar *ejsCopyProperties(Ejs *ep, EjsVar *dest, - const EjsVar *src, EjsCopyDepth copyDepth); - -#define EJS_LINK_OFFSET ((uint) (&((EjsProperty*) 0)->link)) -#define ejsGetPropertyFromLink(lp) \ - ((EjsProperty*) ((char*) lp - EJS_LINK_OFFSET)) - -#define ejsGetObjPtr(vp) ((EjsObj*) vp->objectState) - -extern void ejsMakePropertyPrivate(EjsProperty *pp, int isPrivate); -extern void ejsMakePropertyReadOnly(EjsProperty *pp, int readonly); -extern void ejsMakePropertyUndeleteable(EjsProperty *pp, int deletable); -extern int ejsMakeObjLive(EjsVar *vp, bool alive); -extern void ejsMakeClassNoConstructor(EjsVar *vp); - -extern bool ejsBlockInUseInt(EjsVar *vp); -#if BLD_DEBUG - #define ejsBlockInUse(vp) ejsBlockInUseInt(vp) -#else - #define ejsBlockInUse(vp) -#endif - -/********************************* Prototypes *********************************/ - -/* - * Variable constructors and destructors - */ -extern EjsVar *ejsCreateBinaryStringVar(Ejs *ep, const uchar *value, - int len); -extern EjsVar *ejsCreateBoolVar(Ejs *ep, int value); -extern EjsVar *ejsCreateCMethodVar(Ejs *ep, EjsCMethod fn, - void *userData, int flags); -#if BLD_FEATURE_FLOATING_POINT -extern EjsVar *ejsCreateFloatVar(Ejs *ep, double value); -#endif -extern EjsVar *ejsCreateIntegerVar(Ejs *ep, int value); -#if BLD_FEATURE_INT64 -extern EjsVar *ejsCreateInteger64Var(Ejs *ep, int64 value); -#endif - -extern EjsVar *ejsCreateMethodVar(Ejs *ep, const char *body, - MprArray *args, int flags); -extern EjsVar *ejsCreateNullVar(Ejs *ep); -extern EjsVar *ejsCreateNumberVar(Ejs *ep, EjsNumber value); - -#define ejsCreateObjVar(ep) \ - ejsCreateObjVarInternal(EJS_LOC_ARGS(ep)) -extern EjsVar *ejsCreateObjVarInternal(EJS_LOC_DEC(ep, loc)); - -extern EjsVar *ejsCreatePtrVar(Ejs *ep, void *ptr, EjsDestructor dest); - -extern EjsVar *ejsCreateStringCMethodVar(Ejs *ep, EjsStringCMethod fn, - void *userData, int flags); - -#define ejsCreateStringVar(ep, value) \ - ejsCreateStringVarInternal(EJS_LOC_ARGS(ep), value) -extern EjsVar *ejsCreateStringVarInternal(EJS_LOC_DEC(ep, loc), - const char *value); - -extern EjsVar *ejsCreateUndefinedVar(Ejs *ep); - -/* MOB -- naming. Should be Create/Destroy */ -extern void ejsFreeVar(Ejs *ep, EjsVar *vp); - -/* - * Var support routines - */ -extern int ejsGetVarFlags(EjsVar *vp); -extern void ejsSetVarFlags(EjsVar *obj, int flags); - -extern EjsType ejsGetVarType(EjsVar *vp); -extern const char *ejsGetVarTypeAsString(EjsVar *vp); - -extern void *ejsGetCMethodUserData(EjsVar *obj); -extern void ejsSetCMethodUserData(EjsVar *obj, void *userData); - -extern void *ejsGetVarUserPtr(EjsVar *vp); -extern void ejsSetVarUserPtr(EjsVar *vp, void *data); - - -/* - * Variable access and manipulation. These work on standalone objects. - */ -#define ejsDupVar(ep, src, copyDepth) \ - ejsDupVarInternal(EJS_LOC_ARGS(ep), src, copyDepth) -extern EjsVar *ejsDupVarInternal(EJS_LOC_DEC(ep, loc), EjsVar *src, - EjsCopyDepth copyDepth); -#define ejsWriteVar(ep, dest, src, copyDepth) \ - ejsWriteVarInternal(EJS_LOC_ARGS(ep), dest, src, copyDepth) -extern EjsVar *ejsWriteVarInternal(EJS_LOC_DEC(ep, loc), EjsVar *dest, - const EjsVar *src, EjsCopyDepth copyDepth); -extern EjsVar *ejsWriteVarAsBinaryString(Ejs *ep, EjsVar *dest, - const uchar *value, int len); -extern EjsVar *ejsWriteVarAsBoolean(Ejs *ep, EjsVar *dest, bool value); -extern EjsVar *ejsWriteVarAsCMethod(Ejs *ep, EjsVar *dest, EjsCMethod fn, - void *userData, int flags); -#if BLD_FEATURE_FLOATING_POINT -extern EjsVar *ejsWriteVarAsFloat(Ejs *ep, EjsVar *dest, double value); -#endif -extern EjsVar *ejsWriteVarAsInteger(Ejs *ep, EjsVar *dest, int value); -#if BLD_FEATURE_INT64 -extern EjsVar *ejsWriteVarAsInteger64(Ejs *ep, EjsVar *dest, int64 value); -#endif -extern EjsVar *ejsWriteVarAsMethod(Ejs *ep, EjsVar *dest, - const char *body, MprArray *args); -extern EjsVar *ejsWriteVarAsNull(Ejs *ep, EjsVar *dest); -extern EjsVar *ejsWriteVarAsNumber(Ejs *ep, EjsVar *dest, EjsNum value); -#define ejsWriteVarAsString(ep, dest, value) \ - ejsWriteVarAsStringInternal(EJS_LOC_ARGS(ep), dest, value) -extern EjsVar *ejsWriteVarAsStringInternal(EJS_LOC_DEC(ep, loc), - EjsVar *dest, const char *value); -extern EjsVar *ejsWriteVarAsStringCMethod(Ejs *ep, EjsVar *dest, - EjsStringCMethod fn, void *userData, int flags); -extern EjsVar *ejsWriteVarAsUndefined(Ejs *ep, EjsVar *dest); - -/* - * These routines do not convert types - */ -/* MOB -- make this a fn and pass back the length as an arg */ -#define ejsReadVarAsBinaryString(vp) ((const uchar*) (vp->ustring)); -#define ejsReadVarAsBoolean(vp) (vp->boolean); -#define ejsReadVarAsCMethod(vp) (vp->cMethod); -#if BLD_FEATURE_FLOATING_POINT -#define ejsReadVarAsFloat(vp) (vp->floating); -#endif -#define ejsReadVarAsInteger(vp) (vp->integer); -#if BLD_FEATURE_INT64 -#define ejsReadVarAsInteger64(vp) (vp->int64); -#endif -#define ejsReadVarAsString(vp) ((const char*) (vp->string)); -#define ejsReadVarAsStringCMethod(vp) (vp->cMethodWithStrings); -/* MOB -- remove this fn */ -#define ejsReadVarStringLength(vp) (vp->length); - -/* - * Object property creation routines - */ -extern EjsProperty *ejsCreateProperty(Ejs *ep, EjsVar *obj, const char *prop); -extern EjsProperty *ejsCreateSimpleProperty(Ejs *ep, EjsVar *obj, - const char *prop); -extern EjsProperty *ejsCreateSimpleNonUniqueProperty(Ejs *ep, EjsVar *obj, - const char *prop); -/* MOB -- should be destroy */ -extern int ejsDeleteProperty(Ejs *ep, EjsVar *obj, const char *prop); - - -/* - * Get property routines - */ -extern EjsProperty *ejsGetProperty(Ejs *ep, EjsVar *obj, const char *prop); -extern EjsProperty *ejsGetSimpleProperty(Ejs *ep, EjsVar *obj, - const char *prop); - -extern EjsVar *ejsGetPropertyAsVar(Ejs *ep, EjsVar *obj, - const char *prop); -extern int ejsGetPropertyCount(EjsVar *obj); - -extern const uchar *ejsGetPropertyAsBinaryString(Ejs *ep, EjsVar *obj, - const char *prop, int *length); -extern bool ejsGetPropertyAsBoolean(Ejs *ep, EjsVar *obj, - const char *prop); -extern int ejsGetPropertyAsInteger(Ejs *ep, EjsVar *obj, - const char *prop); -extern int64 ejsGetPropertyAsInteger64(Ejs *ep, EjsVar *obj, - const char *prop); -extern EjsNum ejsGetPropertyAsNumber(Ejs *ep, EjsVar *obj, - const char *prop); -extern void *ejsGetPropertyAsPtr(Ejs *ep, EjsVar *obj, - const char *prop); -extern const char *ejsGetPropertyAsString(Ejs *ep, EjsVar *obj, - const char *prop); - -/* - * Object property update routines - */ -extern EjsProperty *ejsSetBaseProperty(Ejs *ep, EjsVar *obj, const char *prop, - const EjsVar *value); -extern EjsProperty *ejsSetProperty(Ejs *ep, EjsVar *obj, const char *prop, - const EjsVar *value); -extern EjsProperty *ejsSetPropertyAndFree(Ejs *ep, EjsVar *obj, - const char *prop, EjsVar *value); -extern EjsProperty *ejsSetPropertyToBinaryString(Ejs *ep, EjsVar *obj, - const char *prop, const uchar *value, int len); -extern EjsProperty *ejsSetPropertyToBoolean(Ejs *ep, EjsVar *obj, - const char *prop, bool value); -extern EjsProperty *ejsSetPropertyToCMethod(Ejs *ep, EjsVar *obj, - const char *prop, EjsCMethod fn, void *userData, - int flags); -#if BLD_FEATURE_FLOATING_POINT -extern EjsProperty *ejsSetPropertyToFloat(Ejs *ep, EjsVar *obj, - const char *prop, double value); -#endif -extern EjsProperty *ejsSetPropertyToInteger(Ejs *ep, EjsVar *obj, - const char *prop, int value); -#if BLD_FEATURE_INT64 -extern EjsProperty *ejsSetPropertyToInteger64(Ejs *ep, EjsVar *obj, - const char *prop, int64 value); -#endif -extern EjsProperty *ejsSetPropertyToMethod(Ejs *ep, EjsVar *obj, - const char *prop, const char *body, MprArray *args, - int flags); -extern EjsProperty *ejsSetPropertyToNewObj(Ejs *ep, EjsVar *obj, - const char *prop, const char *className, - MprArray *args); -extern EjsProperty *ejsSetPropertyToNull(Ejs *ep, EjsVar *obj, - const char *prop); -extern EjsProperty *ejsSetPropertyToNumber(Ejs *ep, EjsVar *obj, - const char *prop, EjsNum value); -extern EjsProperty *ejsSetPropertyToObj(Ejs *ep, EjsVar *obj, - const char *prop); -extern EjsProperty *ejsSetPropertyToPtr(Ejs *ep, EjsVar *obj, - const char *prop, void *ptr, EjsDestructor destructor); - -extern EjsProperty *ejsSetPropertyToStringCMethod(Ejs *ep, EjsVar *obj, - const char *prop, EjsStringCMethod fn, - void *userData, int flags); -extern EjsProperty *ejsSetPropertyToString(Ejs *ep, EjsVar *obj, - const char *prop, const char *value); -extern EjsProperty *ejsSetPropertyToUndefined(Ejs *ep, EjsVar *obj, - const char *prop); - - -/* Convenience function */ -extern EjsVar *ejsSetPropertyToObjAsVar(Ejs *ep, EjsVar *obj, - const char *prop); -extern void ejsSetObjDestructor(Ejs *ep, EjsVar *obj, - EjsDestructor destructor); -extern void ejsClearObjDestructor(Ejs *ep, EjsVar *obj); - -/* - * Enumeration of properties - * MOB -- should these take an ejs parameter to be consistent - */ -extern EjsProperty *ejsGetFirstProperty(const EjsVar *obj, int flags); -extern EjsProperty *ejsGetNextProperty(EjsProperty *last, int flags); - -/* - * Method definition and control. - */ -extern EjsProperty *ejsDefineMethod(Ejs *ep, EjsVar *obj, const char *prop, - const char *body, MprArray *args); -extern EjsProperty *ejsDefineCMethod(Ejs *ep, EjsVar *obj, const char *prop, - EjsCMethod fn, int flags); - -extern EjsProperty *ejsDefineStringCMethod(Ejs *ep, EjsVar *obj, - const char *prop, EjsStringCMethod fn, int flags); - -extern EjsProperty *ejsDefineAccessors(Ejs *ep, EjsVar *obj, - const char *prop, const char *getBody, - const char *setBody); -extern EjsProperty *ejsDefineCAccessors(Ejs *ep, EjsVar *obj, - const char *prop, EjsCMethod getFn, EjsCMethod setFn, - int flags); - -/* - * Macro to get the variable value portion of a property - */ -#define ejsGetVarPtr(pp) (&((pp)->var)) -#define ejsGetPropertyPtr(vp) ((EjsProperty*) vp) - -/* MOB -- take ejs to be consistent */ -extern int ejsMakePropertyEnumerable(EjsProperty *pp, bool enumerable); -extern int ejsMakeObjPermanent(EjsVar *vp, bool permanent); - - -/* - * Var conversion routines - * MOB -- should these take an Ejs as first arg for consistency - */ -extern bool ejsVarToBoolean(EjsVar *vp); -#if BLD_FEATURE_FLOATING_POINT -extern double ejsVarToFloat(EjsVar *vp); -#endif -extern int ejsVarToInteger(EjsVar *vp); -#if BLD_FEATURE_INT64 -extern int64 ejsVarToInteger64(EjsVar *vp); -#endif -extern EjsNum ejsVarToNumber(EjsVar *vp); -extern char *ejsVarToString(Ejs *ep, EjsVar *vp); -extern char *ejsVarToStringEx(Ejs *ep, EjsVar *vp, bool *alloc); -extern char *ejsFormatVar(Ejs *ep, const char *fmt, EjsVar *vp); - -#if BLD_FEATURE_FLOATING_POINT -extern double ejsParseFloat(const char *str); -#endif -/* - * Parsing and type range checking routines - */ -extern bool ejsParseBoolean(const char *str); -extern int ejsParseInteger(const char *str); -#if BLD_FEATURE_INT64 -extern int64 ejsParseInteger64(const char *str); -#endif -extern EjsNum ejsParseNumber(const char *str); -extern EjsVar *ejsParseVar(Ejs *ep, const char *str, EjsType prefType); - -#if BLD_FEATURE_FLOATING_POINT -extern bool ejsIsInfinite(double f); -extern bool ejsIsNan(double f); -#endif - -/* - * Advisory locking support - */ -#if BLD_FEATURE_MULTITHREAD -extern void ejsLockObj(EjsVar *vp); -extern void ejsUnlockObj(EjsVar *vp); -#endif - -/* - * Just for debugging - */ -extern bool ejsObjIsCollectable(EjsVar *vp); - -#ifdef __cplusplus -} -#endif - -/*****************************************************************************/ -#endif /* _h_EJS_VAR */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/lib/event.js b/source4/lib/appweb/ejs-2.0/ejs/lib/event.js deleted file mode 100644 index 283a3ec72f..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/lib/event.js +++ /dev/null @@ -1,141 +0,0 @@ -/* - * @file event.js - * @brief Event class - * @copy Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved. - * - * Usage: - * listener = new System.Listener(); - * listener.onClick = function() { - * // Any code here - * } - * eventTarget.addListener(eventName, listener); - * or - * listener = new System.Listener(obj, method); - * eventTarget.addListener(eventName, listener); - * - * To fire events: - * eventTarget.fire(eventName, new System.Event("My Event")); - */ - -/******************************************************************************/ -/* - * Base event class - */ -class System.Event -{ - var type; // keyboard - var timeStamp; - var arg; - - /* MOB -- constructor should take a type */ - function Event(arg) - { - timeStamp = time(); - type = "default"; - this.arg = arg; - } -} - -/* MOB -- should not be needed */ -Event = System.Event; - -class System.Listener -{ - var obj; - var method; - - function Listener(obj, method) - { - if (arguments.length >= 1) { - this.obj = obj; - } else { - this.obj = this; - } - if (arguments.length == 2) { - this.method = method; - } else { - this.method = "onEvent"; - } - } -} -/* MOB -- should not be needed */ -Listener = System.Listener; - - -/* - * The Event target class - */ -class System.EventTarget -{ - // Private - var events; /* Hash of a event names */ - - function EventTarget() - { - events = new Object(); - } - - // Public - function addListener(eventName, listener) - { - var listeners = events[eventName]; - if (listeners == undefined) { - listeners = events[eventName] = new Array(); - } - if (arguments.length == 2) { - var method = eventName; - } - /* MOB OPT */ - for (var i = 0; i < listeners.length; i++) { - var l = listeners[i]; - if (l == listener) { - return; - } - } - listeners[listeners.length] = listener; - } - - function removeListener(eventName, listener) - { - var listeners = events[eventName]; - - if (listeners == undefined) { - return; - } - - for (var i = 0; i < listeners.length; i++) { - var l = listeners[i]; - if (l == listener) { - // MOB -- want listeners.splice here - // listeners.splice(i, 1); - for (var j = i; j < (listeners.length - 1); j++) { - listeners[j] = listeners[j + 1]; - } - delete listeners[listeners.length - 1]; - i = listeners.length; - } - } - } - - function fire(eventName, event) - { - var listeners = events[eventName]; - - if (listeners == undefined) { - // println("Event.fire(): unknown eventName " + eventName); - return; - } - - for (var i = listeners.length - 1; i >= 0; i--) { - var listener = listeners[i]; - var method = listener.obj[listener.method]; - if (method == undefined) { - throw new EvalError("Undefined method: " + listener.method); - } - listener.obj[listener.method](listener, event); - } - } -} - -/* MOB -- should not be needed */ -EventTarget = System.EventTarget; diff --git a/source4/lib/appweb/ejs-2.0/ejs/lib/global.js b/source4/lib/appweb/ejs-2.0/ejs/lib/global.js deleted file mode 100644 index f2daaa57c0..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/lib/global.js +++ /dev/null @@ -1,34 +0,0 @@ -/* - * @file global.js - * @brief Misc global functions - * @copy Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved. - */ - -/******************************************************************************/ - -function min(a, b) -{ - if (a < b) { - return a; - } else { - return b; - } -} - - -function max(a, b) -{ - if (a > b) { - return a; - } else { - return b; - } -} - -function abs(a) -{ - if (a < 0) { - return -a; - } - return a; -} diff --git a/source4/lib/appweb/ejs-2.0/ejs/lib/startup.js b/source4/lib/appweb/ejs-2.0/ejs/lib/startup.js deleted file mode 100644 index e627a96e04..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/lib/startup.js +++ /dev/null @@ -1,15 +0,0 @@ -/* - * @file startup.js - * @brief Embedded JavaScript Startup Code - * @copy Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved. - * - * Invoked automatically on startup. - */ - -/******************************************************************************/ - -// println("Loading startup.js ..."); - -include("lib/event.js"); -include("lib/global.js"); -include("lib/timer.js"); diff --git a/source4/lib/appweb/ejs-2.0/ejs/lib/timer.js b/source4/lib/appweb/ejs-2.0/ejs/lib/timer.js deleted file mode 100644 index f4cb8b12ce..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/lib/timer.js +++ /dev/null @@ -1,158 +0,0 @@ -/* - * @file timer.js - * @brief Timer class - * @copy Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved. - * - * Usage: - * timer = new System.Timer("name", period); - * timer.onTick = function(arg) { - * // Anything here - * } - * timer.start(); - * or - * - * timer = new System.Timer("name", period, obj, method); - * timer.start(); - */ - -/******************************************************************************/ - -class System.Timer -{ - var id; - - /* MOB -- really need accessor on period. If user updates period, - then due must be updated. */ - var period; - var due; - var runOnce; // Run timer just once - var method; // Callback method - var obj; // Callback object - - function Timer(id, period, obj, method) - { - this.id = id; - this.period = period; - due = time() + period; - - if (arguments.length >= 3) { - this.obj = obj; - } else { - this.obj = this; - } - if (arguments.length >= 4) { - this.method = method; - } else { - this.method = "onTick"; - } - } - - /* MOB this should be deprecated */ - function reschedule(period) - { - /* MOB -- should update the timer service somehow */ - this.period = period; - } - - function run(now) - { - if (obj[method] == undefined) { - trace("Timer cant find timer method " + method); - due = now + this.period; - return; - } - - /* - * Run the timer - */ - try { - obj[method](this); - } - catch (error) { - trace("Timer exception: " + error); - } - - if (runOnce) { - timerService.removeTimer(this); - - } else { - due = now + this.period; - } - } - - function start() - { - if (obj[method] == undefined) { - throw new Error("Callback method is undefined"); - } else { - timerService.addTimer(this); - } - } - - function stop() - { - timerService.removeTimer(this); - } - -} - -/* MOB -- should not need this */ -Timer = System.Timer; - - -/* - * Timer service - */ -class System.TimerService -{ - var timers; - var nextDue; - - function TimerService() - { - timers = new Object(); - nextDue = 0; - global.timerService = this; - } - - function addTimer(timer) - { - timers[timer.id] = timer; - } - - function removeTimer(timer) - { - try { - delete timers[timer.id]; - } - catch {} - } - - function getIdleTime() - { - return nextDue - time(); - } - - function runTimers() - { - var now = time(); - - nextDue = 2147483647; /* MOB -- MATH.MAX_INT; */ - - for each (var timer in timers) - { - if (timer.due < now) { - timer.run(now); - } - } - for each (var timer in timers) - { - if (timer.due < nextDue) { - nextDue = timer.due; - } - } - // println("runTimers leaving with " + (nextDue - now)); - return nextDue - time(); - } -} -TimerService = System.TimerService; diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/.ignore b/source4/lib/appweb/ejs-2.0/ejs/system/.ignore deleted file mode 100755 index fb5a29031e..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/.ignore +++ /dev/null @@ -1 +0,0 @@ -.updated diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/Makefile b/source4/lib/appweb/ejs-2.0/ejs/system/Makefile deleted file mode 100755 index 2d83662655..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/Makefile +++ /dev/null @@ -1,27 +0,0 @@ -# -# Makefile to build the EJS Object Model -# -# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. -# - -COMPILE := *.c -EXPORT_OBJECTS := yes -MAKE_IFLAGS := -I.. -I../../mpr -I../../exml - -include make.dep - -ifeq ($(BLD_HOST_UNIX),1) -PRE_DIRS = UNIX -else -PRE_DIRS = $(BLD_HOST_OS) -endif - -compileExtra: .updated - -.updated: $(FILES) - @touch .updated - -## Local variables: -## tab-width: 4 -## End: -## vim: tw=78 sw=4 ts=4 diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/README.TXT b/source4/lib/appweb/ejs-2.0/ejs/system/README.TXT deleted file mode 100644 index a24e0e299c..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/README.TXT +++ /dev/null @@ -1,63 +0,0 @@ -Embedded JavaScript System Model - - -- Need args, arg types and exceptions thrown -- Error classes - -class Global - class System - class environment - var - class GC - void function run() - function tune() - function getUsedMemory() // Should be properties - function getAllocatedMemory() // Should be properties - - var javascript - var null - var undefined - var true - var false - var Nan - var Infinity - - function random // Not implemented - function sleep // Not implemented - function exit - function yield // Not implemented - - Debug - isDebugMode - - Limits - isLimitsMode // Not implemented - stack // Not implemented - heap // Not implemented - flash // Not implemented - - Memory - getUsedMemory() // Should be properties - getAvailableMemory() // Should be properties - used - flash // Not implemented - - assert() - breakpoint() - dirname() - basename() - eval() - exit() - print() - println() - printVars() - sleep() - sort() - time() - typeof() - include() - trace() - printf() // Not implemented - sprintf() - - diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/.ignore b/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/.ignore deleted file mode 100644 index fb5a29031e..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/.ignore +++ /dev/null @@ -1 +0,0 @@ -.updated diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/Makefile b/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/Makefile deleted file mode 100755 index 424747052a..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -# -# Makefile to build the EJS Object Model for WIN -# -# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. -# - -COMPILE := *.c -EXPORT_OBJECTS := yes -MAKE_IFLAGS := -I../.. -I../../../mpr - -include make.dep - -compileExtra: .updated - -.updated: $(FILES) - @touch .updated - -## Local variables: -## tab-width: 4 -## End: -## vim: tw=78 sw=4 ts=4 diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/ejsFile.c b/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/ejsFile.c deleted file mode 100644 index 772303152e..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/ejsFile.c +++ /dev/null @@ -1,98 +0,0 @@ -/* - * @file ejsFile.c - * @brief File class for the EJ System Object Model - */ -/********************************** Copyright *********************************/ -/* - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -/******************************************************************************/ -/* - * Default Constructor - */ - -/******************************************************************************/ -/************************************ Methods *********************************/ -/******************************************************************************/ -/* - * function open(); - */ - -static int openProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsTrace(ep, "File.open()\n"); - return 0; -} - -/******************************************************************************/ -/* - * function close(); - */ - -static int closeProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsTrace(ep, "File.close()\n"); - return 0; -} - -/******************************************************************************/ -/* - * function read(); - */ - -static int readProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsTrace(ep, "File.read()\n"); - return 0; -} - -/******************************************************************************/ -/* - * function write(); - */ - -static int writeProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsTrace(ep, "File.write()\n"); - return 0; -} - -/******************************************************************************/ -/******************************** Initialization ******************************/ -/******************************************************************************/ - -int ejsDefineFileClass(Ejs *ep) -{ - EjsVar *fileClass; - - fileClass = ejsDefineClass(ep, "File", "Object", 0); - if (fileClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - /* - * Define the methods - */ - ejsDefineCMethod(ep, fileClass, "open", openProc, 0); - ejsDefineCMethod(ep, fileClass, "close", closeProc, 0); - ejsDefineCMethod(ep, fileClass, "read", readProc, 0); - ejsDefineCMethod(ep, fileClass, "write", writeProc, 0); - - return ejsObjHasErrors(fileClass) ? MPR_ERR_CANT_INITIALIZE: 0; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/ejsFileSystem.c b/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/ejsFileSystem.c deleted file mode 100755 index 7b39c16e4d..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/ejsFileSystem.c +++ /dev/null @@ -1,454 +0,0 @@ -/* - * @file ejsFileSystem.c - * @brief FileSystem class for the EJ System Object Model - * MOB -- this is almost the same as for Windows. Should common up. - */ -/********************************** Copyright *********************************/ -/* - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - */ -/********************************** Includes **********************************/ - -#include "ejs.h" -#include - -/******************************************************************************/ -/************************************ Methods *********************************/ -/******************************************************************************/ -/* - * function void access(string path); - * MOB - API insufficient. Access for read or write? - */ - -static int accessProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int rc; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: access(path)"); - return -1; - } - - rc = access(argv[0]->string, 04); - - ejsSetReturnValueToBoolean(ejs, (rc == 0) ? 1 : 0); - return 0; -} - -/******************************************************************************/ -/* - * function void mkdir(string path); - */ - -static int mkdirProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: mkdir(path)"); - return -1; - } - - if (mprMakeDirPath(ejs, argv[0]->string) < 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant create directory"); - return -1; - } - return 0; -} - -/******************************************************************************/ -/* - * function void rmdir(string path); - */ - -static int rmdirProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int rc; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: mkdir(path)"); - return -1; - } - - rc = mprDeleteDir(ejs, argv[0]->string); - - if (rc < 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant remove directory"); - return -1; - } - return 0; -} - -/******************************************************************************/ -/* - * function void dirList(string path, [bool enumDirs]); - * MOB -- need pattern to match (what about "." and ".." and ".*" - */ - -static int dirListProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - DIR *dir; - struct dirent *dirent; - char path[MPR_MAX_FNAME]; - EjsVar *array, *vp; - uchar enumDirs; - - if (argc < 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: dirList(path)"); - return -1; - } - if (argc == 2) { - enumDirs = ejsVarToBoolean(argv[1]); - } else { - enumDirs = 0; - } - array = ejsCreateArray(ejs, 0); - ejsMakeObjPermanent(array, 1); - - /* - * First collect the files - */ - mprSprintf(path, sizeof(path), "%s/*.*", argv[0]->string); - - dir = opendir(path); - if (dir == 0) { - ejsError(ejs, EJS_ARG_ERROR, "Can't enumerate dirList(path)"); - return -1; - } - - while ((dirent = readdir(dir)) != 0) { - if (dirent->d_name[0] == '.') { - continue; - } - if (!enumDirs || (dirent->d_type & DT_DIR)) { - mprSprintf(path, sizeof(path), "%s/%s", argv[0]->string, - dirent->d_name); - vp = ejsCreateStringVar(ejs, path); - ejsAddArrayElt(ejs, array, vp, EJS_SHALLOW_COPY); - ejsFreeVar(ejs, vp); - } - } - - closedir(dir); - - ejsSetReturnValue(ejs, array); - ejsMakeObjPermanent(array, 0); - - /* - * Can free now as the return value holds the reference - */ - ejsFreeVar(ejs, array); - - return 0; -} - -/******************************************************************************/ -/* - * function void getFreeSpace(); - */ - -static int getFreeSpaceProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ -#if UNUSED - MprApp *app; - uint space; - - app = mprGetApp(ejs); - space = IFILEMGR_GetFreeSpace(app->fileMgr, 0); - ejsSetReturnValueToInteger(ejs, space); -#endif - - return 0; -} - -/******************************************************************************/ -/* - * function void writeFile(string path, var data); - */ - -static int writeFileProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - MprFile *file; - char *data, *buf; - int bytes, length, rc; - - if (argc != 2 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: writeFile(path, var)"); - return -1; - } - - if (ejsVarIsString(argv[1])) { - data = argv[1]->string; - length = argv[1]->length; - buf = 0; - } else { - buf = data = ejsVarToString(ejs, argv[1]); - length = strlen(data); - } - - /* - * Create fails if already present - */ - rc = mprDelete(ejs, argv[0]->string); - file = mprOpen(ejs, argv[0]->string, O_CREAT | O_WRONLY | O_BINARY, 0664); - if (file == 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant create %s", argv[0]->string); - mprFree(buf); - return -1; - } - - rc = 0; - bytes = mprWrite(file, data, length); - if (bytes != length) { - ejsError(ejs, EJS_IO_ERROR, "Write error to %s", argv[1]->string); - rc = -1; - } - - mprClose(file); - - mprFree(buf); - return rc; -} - -/******************************************************************************/ -/* - * function string readFile(string path); - */ - -static int readFileProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - MprApp *app; - MprFile *file; - MprBuf *buf; - char *data; - int bytes, rc; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: readFile(path)"); - return -1; - } - buf = mprCreateBuf(ejs, MPR_BUF_INCR, MPR_MAX_BUF); - if (buf == 0) { - ejsMemoryError(ejs); - return -1; - } - - data = mprAlloc(ejs, MPR_BUFSIZE); - if (buf == 0) { - mprFree(buf); - ejsMemoryError(ejs); - return -1; - } - - app = mprGetApp(ejs); - file = mprOpen(ejs, argv[0]->string, O_RDONLY, 0664); - if (file == 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant open %s", argv[0]->string); - mprFree(buf); - return -1; - } - - rc = 0; - while ((bytes = mprRead(file, data, MPR_BUFSIZE)) > 0) { - if (mprPutBlockToBuf(buf, data, bytes) != bytes) { - ejsError(ejs, EJS_IO_ERROR, "Write error to %s", argv[1]->string); - rc = -1; - break; - } - } - - ejsSetReturnValueToBinaryString(ejs, (uchar*) mprGetBufStart(buf), - mprGetBufLength(buf)); - - mprClose(file); - mprFree(data); - mprFree(buf); - - return rc; -} - -/******************************************************************************/ -/* - * function void remove(string path); - */ - -static int removeProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int rc; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: remove(path)"); - return -1; - } - - rc = unlink(argv[0]->string); - if (rc < 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant remove file"); - return -1; - } - return 0; -} - -/******************************************************************************/ -/* - * function void rename(string from, string to); - */ - -static int renameProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int rc; - - if (argc != 2 || !ejsVarIsString(argv[0]) || !ejsVarIsString(argv[1])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: rename(old, new)"); - return -1; - } - - unlink(argv[1]->string); - rc = rename(argv[0]->string, argv[1]->string); - if (rc < 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant rename file"); - return -1; - } - return 0; -} - -/******************************************************************************/ -/* - * function void copy(string old, string new); - */ - -static int copyProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - MprFile *from, *to; - char *buf; - uint bytes; - int rc; - - if (argc != 2 || !ejsVarIsString(argv[0]) || !ejsVarIsString(argv[1])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: copy(old, new)"); - return -1; - } - - buf = mprAlloc(ejs, MPR_BUFSIZE); - if (buf == 0) { - ejsMemoryError(ejs); - return -1; - } - - from = mprOpen(ejs, argv[0]->string, O_RDONLY | O_BINARY, 0664); - if (from == 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant open %s", argv[0]->string); - mprFree(buf); - return -1; - } - - to = mprOpen(ejs, argv[1]->string, O_CREAT | O_BINARY, 0664); - if (to == 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant create %s", argv[1]->string); - mprClose(from); - mprFree(buf); - return -1; - } - - rc = 0; - while ((bytes = mprRead(from, buf, MPR_BUFSIZE)) > 0) { - if (mprWrite(to, buf, bytes) != bytes) { - ejsError(ejs, EJS_IO_ERROR, "Write error to %s", argv[1]->string); - rc = -1; - break; - } - } - - mprClose(from); - mprClose(to); - mprFree(buf); - - return rc; -} - -/******************************************************************************/ -/* - * function FileInfo getFileInfo(string path); - * - * MOB -- should create a real class FileInfo - */ - -static int getFileInfoProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - MprFileInfo info; - EjsVar *fileInfo; - int rc; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: getFileInfo(path)"); - return -1; - } - - fileInfo = ejsCreateObjVar(ejs); - if (fileInfo == 0) { - ejsMemoryError(ejs); - return -1; - } - ejsMakeObjPermanent(fileInfo, 1); - - rc = mprGetFileInfo(ejs, argv[0]->string, &info); - if (rc < 0) { - ejsMakeObjPermanent(fileInfo, 0); - ejsFreeVar(ejs, fileInfo); - ejsError(ejs, EJS_IO_ERROR, "Cant get file info for %s", - argv[0]->string); - return -1; - } - - ejsSetPropertyToInteger(ejs, fileInfo, "created", info.ctime); - ejsSetPropertyToInteger(ejs, fileInfo, "length", info.size); - ejsSetPropertyToBoolean(ejs, fileInfo, "isDir", info.isDir); - - ejsSetReturnValue(ejs, fileInfo); - ejsMakeObjPermanent(fileInfo, 0); - - return 0; -} - -/******************************************************************************/ -/******************************** Initialization ******************************/ -/******************************************************************************/ - -int ejsDefineFileSystemClass(Ejs *ejs) -{ - EjsVar *fileSystemClass; - - fileSystemClass = ejsDefineClass(ejs, "FileSystem", "Object", 0); - if (fileSystemClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - /* - * Define the methods - */ - ejsDefineCMethod(ejs, fileSystemClass, "access", accessProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "mkdir", mkdirProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "rmdir", rmdirProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "dirList", dirListProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "writeFile", writeFileProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "readFile", readFileProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "remove", removeProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "rename", renameProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "copy", copyProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "getFileInfo", getFileInfoProc, 0); - - // MOB -- should be a property with accessor - ejsDefineCMethod(ejs, fileSystemClass, "getFreeSpace", getFreeSpaceProc, 0); - - return ejsObjHasErrors(fileSystemClass) ? MPR_ERR_CANT_INITIALIZE: 0; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/ejsHTTP.c b/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/ejsHTTP.c deleted file mode 100755 index 25821f6960..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/UNIX/ejsHTTP.c +++ /dev/null @@ -1,488 +0,0 @@ -/* - * @file ejsHTTP.c - * @brief HTTP class for the EJ System Object Model - */ -/********************************** Copyright *********************************/ -/* - * Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved. - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if UNUSED -/*********************************** Defines **********************************/ - -#define EJS_WEB_PROPERTY "-web" -#define EJS_HTTP_PROPERTY "-http" - -#define EJS_HTTP_DISPOSED 550 - -/* - * Control structure for one HTTP request structure - */ -typedef struct HTTPControl { - Ejs *ejs; - IWebResp *webResp; - AEECallback *callback; - MprBuf *buf; - EjsVar *thisObj; - char *url; - MprTime requestStarted; - uint timeout; -} HTTPControl; - -/****************************** Forward Declarations **************************/ - -static void cleanup(HTTPControl *hp); -static int createWeb(Ejs *ejs, EjsVar *thisObj); -static void brewCallback(HTTPControl *hp); -static int httpDestructor(Ejs *ejs, EjsVar *vp); -static void httpCallback(HTTPControl *hp, int responseCode); -static int setCallback(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv); - -/******************************************************************************/ -/* - * Constructor - */ - -int ejsHTTPConstructor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 0 && argc != 2) { - ejsError(ejs, EJS_ARG_ERROR, - "Bad usage: HTTP([obj = this, method = onComplete]);"); - return -1; - } - - if (createWeb(ejs, thisObj) < 0) { - return -1; - } - - setCallback(ejs, thisObj, argc, argv); - return 0; -} - -/******************************************************************************/ - -static int createWeb(Ejs *ejs, EjsVar *thisObj) -{ - MprApp *app; - void *web; - - app = mprGetApp(ejs); - - /* - * Create one instance of IWeb for the entire application. Do it here - * so only widgets that require HTTP incurr the overhead. - */ - web = mprGetKeyValue(ejs, "bpWeb"); - if (web == 0) { - if (ISHELL_CreateInstance(app->shell, AEECLSID_WEB, &web) != SUCCESS) { - ejsError(ejs, EJS_IO_ERROR, "Can't create IWEB"); - return -1; - } - } - mprSetKeyValue(ejs, "bpWeb", web); - return 0; -} - -/******************************************************************************/ -/************************************ Methods *********************************/ -/******************************************************************************/ -/* - * function setCallback(obj, methodString); - */ - -static int setCallback(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc >= 1) { - ejsSetProperty(ejs, thisObj, "obj", argv[0]); - } else { - ejsSetProperty(ejs, thisObj, "obj", thisObj); - } - - if (argc >= 2) { - ejsSetProperty(ejs, thisObj, "method", argv[1]); - } else { - ejsSetPropertyToString(ejs, thisObj, "method", "onComplete"); - } - - return 0; -} - -/******************************************************************************/ -/* - * function fetch(); - */ - -static int fetchProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - HTTPControl *hp; - EjsProperty *pp; - MprApp *app; - IWeb *web; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: fetch(url)"); - return -1; - } - - app = mprGetApp(ejs); - web = (IWeb*) mprGetKeyValue(ejs, "bpWeb"); - - /* - * Web options - * - * WEBOPT_USERAGENT (char*) sets user agent - * WEBOPT_HANDLERDATA (void*) - * WEBOPT_CONNECTTIMEOUT (uint) msec - * WEBOPT_CONTENTLENGTH (long) - * WEBOPT_IDLECONNTIMEOUT (int) - * WEBOPT_ACTIVEXACTIONST (uint) Number of active requests - * - * WEBREQUEST_REDIRECT redirect transparently - * - */ - - hp = mprAllocType(ejs, HTTPControl); - if (hp == 0) { - ejsMemoryError(ejs); - return -1; - } - - hp->ejs = ejs; - hp->buf = mprCreateBuf(hp, MPR_BUF_INCR, MPR_MAX_BUF); - if (hp->buf == 0) { - mprFree(hp); - ejsMemoryError(ejs); - return -1; - } - - /* - * We copy thisObj because we need to preserve both the var and the object. - * We pass the var to brewCallback and so it must persist. The call to - * ejsMakeObjPermanent will stop the GC from collecting the object. - */ - hp->thisObj = ejsDupVar(ejs, thisObj, EJS_SHALLOW_COPY); - ejsSetVarName(ejs, hp->thisObj, "internalHttp"); - - /* - * Must keep a reference to the http object - */ - ejsMakeObjPermanent(hp->thisObj, 1); - - /* - * Make a property so we can access the HTTPControl structure from other - * methods. - */ - pp = ejsSetPropertyToPtr(ejs, thisObj, EJS_HTTP_PROPERTY, hp, 0); - ejsMakePropertyEnumerable(pp, 0); - ejsSetObjDestructor(ejs, hp->thisObj, httpDestructor); - - hp->url = mprStrdup(hp, argv[0]->string); - - hp->timeout = ejsGetPropertyAsInteger(ejs, thisObj, "timeout"); - mprGetTime(hp, &hp->requestStarted); - - hp->callback = mprAllocTypeZeroed(hp, AEECallback); - CALLBACK_Init(hp->callback, brewCallback, hp); - - hp->webResp = 0; - IWEB_GetResponse(web, - (web, &hp->webResp, hp->callback, hp->url, - WEBOPT_HANDLERDATA, hp, - WEBOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)", - WEBOPT_CONNECTTIMEOUT, hp->timeout, - WEBOPT_COPYOPTS, TRUE, - WEBOPT_CONTENTLENGTH, 0, - WEBOPT_END)); - - ejsSetPropertyToString(ejs, thisObj, "status", "active"); - - return 0; -} - -/******************************************************************************/ -/* - * Called whenver the http object is deleted. - */ - -static int httpDestructor(Ejs *ejs, EjsVar *thisObj) -{ - HTTPControl *hp; - - /* - * If the httpCallback has run, then this property will not exist - */ - hp = ejsGetPropertyAsPtr(ejs, thisObj, EJS_HTTP_PROPERTY); - - if (hp) { - cleanup(hp); - } - - return 0; -} - -/******************************************************************************/ -/* - * Stop the request immediately without calling the callback - */ - -static int stopProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - HTTPControl *hp; - - hp = ejsGetPropertyAsPtr(ejs, thisObj, EJS_HTTP_PROPERTY); - - if (hp) { - cleanup(hp); - } - - return 0; -} - -/******************************************************************************/ -/* - * Brew HTTP callback. Invoked for any return data. - */ - -static void brewCallback(HTTPControl *hp) -{ - Ejs *ejs; - EjsVar *thisObj; - ISource *source; - WebRespInfo *info; - char data[MPR_BUF_INCR]; - int bytes; - - mprAssert(hp); - mprAssert(hp->webResp); - - info = IWEBRESP_GetInfo(hp->webResp); - - if (info == 0) { - mprAssert(info); - /* should not happen */ - return; - } - - ejs = hp->ejs; - thisObj = hp->thisObj; - - if (! WEB_ERROR_SUCCEEDED(info->nCode)) { - ejsSetPropertyToString(ejs, thisObj, "status", "error"); - httpCallback(hp, info->nCode); - return; - } - - if (hp->timeout) { - if (mprGetTimeRemaining(hp, hp->requestStarted, hp->timeout) <= 0) { - ejsSetPropertyToString(ejs, thisObj, "status", "timeout"); - httpCallback(hp, 504); - return; - } - } - - /* - * Normal success - */ - source = info->pisMessage; - mprAssert(source); - - bytes = ISOURCE_Read(source, data, sizeof(data)); - - switch (bytes) { - case ISOURCE_WAIT: // No data yet - ISOURCE_Readable(source, hp->callback); - break; - - case ISOURCE_ERROR: - ejsSetPropertyToString(ejs, thisObj, "status", "error"); - httpCallback(hp, info->nCode); - break; - - case ISOURCE_END: - mprAddNullToBuf(hp->buf); - ejsSetPropertyToString(ejs, thisObj, "status", "complete"); - httpCallback(hp, info->nCode); - break; - - default: - if (bytes > 0) { - if (mprPutBlockToBuf(hp->buf, data, bytes) != bytes) { - ejsSetPropertyToString(ejs, thisObj, "status", "partialData"); - httpCallback(hp, 500); - } - } - ISOURCE_Readable(source, hp->callback); - break; - } -} - -/******************************************************************************/ -/* - * Invoke the HTTP completion method - */ - -static void httpCallback(HTTPControl *hp, int responseCode) -{ - Ejs *ejs; - EjsVar *thisObj, *callbackObj; - MprArray *args; - char *msg; - const char *callbackMethod; - - mprAssert(hp); - mprAssert(hp->webResp); - - thisObj = hp->thisObj; - ejs = hp->ejs; - - ejsSetPropertyToInteger(ejs, thisObj, "responseCode", responseCode); - if (mprGetBufLength(hp->buf) > 0) { - ejsSetPropertyToBinaryString(ejs, thisObj, "responseData", - mprGetBufStart(hp->buf), mprGetBufLength(hp->buf)); - } - - callbackObj = ejsGetPropertyAsVar(ejs, thisObj, "obj"); - callbackMethod = ejsGetPropertyAsString(ejs, thisObj, "method"); - - if (callbackObj != 0 && callbackMethod != 0) { - - args = mprCreateItemArray(ejs, EJS_INC_ARGS, EJS_MAX_ARGS); - mprAddItem(args, ejsDupVar(ejs, hp->thisObj, EJS_SHALLOW_COPY)); - - if (ejsRunMethod(ejs, callbackObj, callbackMethod, args) < 0) { - msg = ejsGetErrorMsg(ejs); - mprError(ejs, MPR_LOC, "HTTP callback failed. Details: %s", msg); - } - ejsFreeMethodArgs(ejs, args); - - } else if (ejsRunMethod(ejs, thisObj, "onComplete", 0) < 0) { - msg = ejsGetErrorMsg(ejs); - mprError(ejs, MPR_LOC, "HTTP onComplete failed. Details: %s", msg); - } - - cleanup(hp); -} - -/******************************************************************************/ -/* - * Cleanup - */ - -static void cleanup(HTTPControl *hp) -{ - Ejs *ejs; - MprApp *app; - int rc; - - mprAssert(hp); - mprAssert(hp->webResp); - - ejs = hp->ejs; - - if (hp->webResp) { - rc = IWEBRESP_Release(hp->webResp); - // mprAssert(rc == 0); - hp->webResp = 0; - } - - if (hp->callback) { - CALLBACK_Cancel(hp->callback); - mprFree(hp->callback); - hp->callback = 0; - } - - /* - * Once the property is deleted, then if the destructor runs, it will - * notice that the EJS_HTTP_PROPERTY is undefined. - */ - ejsDeleteProperty(ejs, hp->thisObj, EJS_HTTP_PROPERTY); - - /* - * Allow garbage collection to work on thisObj - */ - ejsMakeObjPermanent(hp->thisObj, 0); - ejsFreeVar(ejs, hp->thisObj); - - mprFree(hp->buf); - mprFree(hp->url); - - mprFree(hp); - - app = mprGetApp(ejs); - - - ISHELL_SendEvent(app->shell, (AEECLSID) app->classId, EVT_USER, 0, 0); -} - -/******************************************************************************/ -/******************************** Initialization ******************************/ -/******************************************************************************/ - -int ejsDefineHTTPClass(Ejs *ejs) -{ - EjsVar *httpClass; - - httpClass = - ejsDefineClass(ejs, "HTTP", "Object", ejsHTTPConstructor); - if (httpClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - /* - * Define the methods - */ - ejsDefineCMethod(ejs, httpClass, "fetch", fetchProc, 0); - ejsDefineCMethod(ejs, httpClass, "stop", stopProc, 0); - ejsDefineCMethod(ejs, httpClass, "setCallback", setCallback, 0); - -#if FUTURE - ejsDefineCMethod(ejs, httpClass, "put", put, 0); - ejsDefineCMethod(ejs, httpClass, "upload", upload, 0); - ejsDefineCMethod(ejs, httpClass, "addUploadFile", addUploadFile, 0); - ejsDefineCMethod(ejs, httpClass, "addPostData", addPostData, 0); - ejsDefineCMethod(ejs, httpClass, "setUserPassword", setUserPassword, 0); - ejsDefineCMethod(ejs, httpClass, "addCookie", addCookie, 0); -#endif - - /* - * Define properties - */ - ejsSetPropertyToString(ejs, httpClass, "status", "inactive"); - - /* This default should come from player.xml */ - - ejsSetPropertyToInteger(ejs, httpClass, "timeout", 30 * 1000); - ejsSetPropertyToInteger(ejs, httpClass, "responseCode", 0); - - return ejsObjHasErrors(httpClass) ? MPR_ERR_CANT_INITIALIZE: 0; -} - -/******************************************************************************/ - -void ejsTermHTTPClass(Ejs *ejs) -{ - IWeb *web; - int rc; - - web = (IWeb*) mprGetKeyValue(ejs, "bpWeb"); - if (web) { - rc = IWEB_Release(web); - mprAssert(rc == 0); - } -} - -#endif -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/WIN/.ignore b/source4/lib/appweb/ejs-2.0/ejs/system/WIN/.ignore deleted file mode 100644 index fb5a29031e..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/WIN/.ignore +++ /dev/null @@ -1 +0,0 @@ -.updated diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/WIN/Makefile b/source4/lib/appweb/ejs-2.0/ejs/system/WIN/Makefile deleted file mode 100755 index 424747052a..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/WIN/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -# -# Makefile to build the EJS Object Model for WIN -# -# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. -# - -COMPILE := *.c -EXPORT_OBJECTS := yes -MAKE_IFLAGS := -I../.. -I../../../mpr - -include make.dep - -compileExtra: .updated - -.updated: $(FILES) - @touch .updated - -## Local variables: -## tab-width: 4 -## End: -## vim: tw=78 sw=4 ts=4 diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/WIN/ejsFile.c b/source4/lib/appweb/ejs-2.0/ejs/system/WIN/ejsFile.c deleted file mode 100644 index 24c521891e..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/WIN/ejsFile.c +++ /dev/null @@ -1,98 +0,0 @@ -/* - * @file ejsFile.c - * @brief File class for the EJScript System Object Model - */ -/********************************** Copyright *********************************/ -/* - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -/******************************************************************************/ -/* - * Default Constructor - */ - -/******************************************************************************/ -/************************************ Methods *********************************/ -/******************************************************************************/ -/* - * function open(); - */ - -static int openProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsTrace(ep, "File.open()\n"); - return 0; -} - -/******************************************************************************/ -/* - * function close(); - */ - -static int closeProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsTrace(ep, "File.close()\n"); - return 0; -} - -/******************************************************************************/ -/* - * function read(); - */ - -static int readProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsTrace(ep, "File.read()\n"); - return 0; -} - -/******************************************************************************/ -/* - * function write(); - */ - -static int writeProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsTrace(ep, "File.write()\n"); - return 0; -} - -/******************************************************************************/ -/******************************** Initialization ******************************/ -/******************************************************************************/ - -int ejsDefineFileClass(Ejs *ep) -{ - EjsVar *fileClass; - - fileClass = ejsDefineClass(ep, "File", "Object", 0); - if (fileClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - /* - * Define the methods - */ - ejsDefineCMethod(ep, fileClass, "open", openProc, 0); - ejsDefineCMethod(ep, fileClass, "close", closeProc, 0); - ejsDefineCMethod(ep, fileClass, "read", readProc, 0); - ejsDefineCMethod(ep, fileClass, "write", writeProc, 0); - - return ejsObjHasErrors(fileClass) ? MPR_ERR_CANT_INITIALIZE: 0; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/WIN/ejsFileSystem.c b/source4/lib/appweb/ejs-2.0/ejs/system/WIN/ejsFileSystem.c deleted file mode 100755 index 66c3b84870..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/WIN/ejsFileSystem.c +++ /dev/null @@ -1,456 +0,0 @@ -/* - * @file ejsFileSystem.c - * @brief FileSystem class for the EJ System Object Model - */ -/********************************** Copyright *********************************/ -/* - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -/******************************************************************************/ -/* - * Default Constructor - */ - -/******************************************************************************/ -/************************************ Methods *********************************/ -/******************************************************************************/ -/* - * function void access(string path); - * MOB - API insufficient. Access for read or write? - */ - -static int accessProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int rc; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: access(path)"); - return -1; - } - - rc = access(argv[0]->string, 04); - - ejsSetReturnValueToBoolean(ejs, (rc == 0) ? 1 : 0); - return 0; -} - -/******************************************************************************/ -/* - * function void mkdir(string path); - */ - -static int mkdirProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: mkdir(path)"); - return -1; - } - - if (mprMakeDirPath(ejs, argv[0]->string) < 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant create directory"); - return -1; - } - return 0; -} - -/******************************************************************************/ -/* - * function void rmdir(string path); - */ - -static int rmdirProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int rc; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: mkdir(path)"); - return -1; - } - - rc = mprDeleteDir(ejs, argv[0]->string); - - if (rc < 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant remove directory"); - return -1; - } - return 0; -} - -/******************************************************************************/ -/* - * function void dirList(string path, [bool enumDirs]); - * MOB -- need pattern to match (what about "." and ".." and ".*" - */ - -static int dirListProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - WIN32_FIND_DATA findData; - HANDLE h; - char path[MPR_MAX_FNAME]; - EjsVar *array, *vp; - uchar enumDirs; - - if (argc < 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: dirList(path)"); - return -1; - } - if (argc == 2) { - enumDirs = ejsVarToBoolean(argv[1]); - } else { - enumDirs = 0; - } - array = ejsCreateArray(ejs, 0); - ejsMakeObjPermanent(array, 1); - - /* - * First collect the files - */ - mprSprintf(path, sizeof(path), "%s/*.*", argv[0]->string); - h = FindFirstFile(path, &findData); - if (h == INVALID_HANDLE_VALUE) { - ejsError(ejs, EJS_ARG_ERROR, "Can't enumerate dirList(path)"); - return -1; - } - - do { - if (findData.cFileName[0] == '.') { - continue; - } - if (!enumDirs || - (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { - mprSprintf(path, sizeof(path), "%s/%s", argv[0]->string, - findData.cFileName); - vp = ejsCreateStringVar(ejs, path); - ejsAddArrayElt(ejs, array, vp, EJS_SHALLOW_COPY); - ejsFreeVar(ejs, vp); - } - } while (FindNextFile(h, &findData) != 0); - - FindClose(h); - - ejsSetReturnValue(ejs, array); - ejsMakeObjPermanent(array, 0); - - /* - * Can free now as the return value holds the reference - */ - ejsFreeVar(ejs, array); - - return 0; -} - -/******************************************************************************/ -/* - * function void getFreeSpace(); - */ - -static int getFreeSpaceProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ -#if UNUSED - MprApp *app; - uint space; - - app = mprGetApp(ejs); - space = IFILEMGR_GetFreeSpace(app->fileMgr, 0); - ejsSetReturnValueToInteger(ejs, space); -#endif - - return 0; -} - -/******************************************************************************/ -/* - * function void writeFile(string path, var data); - */ - -static int writeFileProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - MprFile *file; - char *data, *buf; - int bytes, length, rc; - - if (argc != 2 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: writeFile(path, var)"); - return -1; - } - - if (ejsVarIsString(argv[1])) { - data = argv[1]->string; - length = argv[1]->length; - buf = 0; - } else { - buf = data = ejsVarToString(ejs, argv[1]); - length = strlen(data); - } - - /* - * Create fails if already present - */ - rc = mprDelete(ejs, argv[0]->string); - file = mprOpen(ejs, argv[0]->string, O_CREAT | O_WRONLY | O_BINARY, 0664); - if (file == 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant create %s", argv[0]->string); - mprFree(buf); - return -1; - } - - rc = 0; - bytes = mprWrite(file, data, length); - if (bytes != length) { - ejsError(ejs, EJS_IO_ERROR, "Write error to %s", argv[1]->string); - rc = -1; - } - - mprClose(file); - - mprFree(buf); - return rc; -} - -/******************************************************************************/ -/* - * function string readFile(string path); - */ - -static int readFileProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - MprApp *app; - MprFile *file; - MprBuf *buf; - char *data; - int bytes, rc; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: readFile(path)"); - return -1; - } - buf = mprCreateBuf(ejs, MPR_BUF_INCR, MPR_MAX_BUF); - if (buf == 0) { - ejsMemoryError(ejs); - return -1; - } - - data = mprAlloc(ejs, MPR_BUFSIZE); - if (buf == 0) { - mprFree(buf); - ejsMemoryError(ejs); - return -1; - } - - app = mprGetApp(ejs); - file = mprOpen(ejs, argv[0]->string, O_RDONLY, 0664); - if (file == 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant open %s", argv[0]->string); - mprFree(buf); - return -1; - } - - rc = 0; - while ((bytes = mprRead(file, data, MPR_BUFSIZE)) > 0) { - if (mprPutBlockToBuf(buf, data, bytes) != bytes) { - ejsError(ejs, EJS_IO_ERROR, "Write error to %s", argv[1]->string); - rc = -1; - break; - } - } - - ejsSetReturnValueToBinaryString(ejs, mprGetBufStart(buf), - mprGetBufLength(buf)); - - mprClose(file); - mprFree(data); - mprFree(buf); - - return rc; -} - -/******************************************************************************/ -/* - * function void remove(string path); - */ - -static int removeProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int rc; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: remove(path)"); - return -1; - } - - rc = unlink(argv[0]->string); - if (rc < 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant remove file"); - return -1; - } - return 0; -} - -/******************************************************************************/ -/* - * function void rename(string from, string to); - */ - -static int renameProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int rc; - - if (argc != 2 || !ejsVarIsString(argv[0]) || !ejsVarIsString(argv[1])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: rename(old, new)"); - return -1; - } - - unlink(argv[1]->string); - rc = rename(argv[0]->string, argv[1]->string); - if (rc < 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant rename file"); - return -1; - } - return 0; -} - -/******************************************************************************/ -/* - * function void copy(string old, string new); - */ - -static int copyProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - MprFile *from, *to; - char *buf; - int bytes, rc; - - if (argc != 2 || !ejsVarIsString(argv[0]) || !ejsVarIsString(argv[1])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: copy(old, new)"); - return -1; - } - - buf = mprAlloc(ejs, MPR_BUFSIZE); - if (buf == 0) { - ejsMemoryError(ejs); - return -1; - } - - from = mprOpen(ejs, argv[0]->string, O_RDONLY | O_BINARY, 0664); - if (from == 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant open %s", argv[0]->string); - mprFree(buf); - return -1; - } - - to = mprOpen(ejs, argv[1]->string, O_CREAT | O_BINARY, 0664); - if (to == 0) { - ejsError(ejs, EJS_IO_ERROR, "Cant create %s", argv[1]->string); - mprClose(from); - mprFree(buf); - return -1; - } - - rc = 0; - while ((bytes = mprRead(from, buf, MPR_BUFSIZE)) > 0) { - if (mprWrite(to, buf, bytes) != bytes) { - ejsError(ejs, EJS_IO_ERROR, "Write error to %s", argv[1]->string); - rc = -1; - break; - } - } - - mprClose(from); - mprClose(to); - mprFree(buf); - - return rc; -} - -/******************************************************************************/ -/* - * function FileInfo getFileInfo(string path); - * - * MOB -- should create a real class FileInfo - */ - -static int getFileInfoProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - MprFileInfo info; - EjsVar *fileInfo; - int rc; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: getFileInfo(path)"); - return -1; - } - - fileInfo = ejsCreateObjVar(ejs); - if (fileInfo == 0) { - ejsMemoryError(ejs); - return -1; - } - ejsMakeObjPermanent(fileInfo, 1); - - rc = mprGetFileInfo(ejs, argv[0]->string, &info); - if (rc < 0) { - ejsMakeObjPermanent(fileInfo, 0); - ejsFreeVar(ejs, fileInfo); - ejsError(ejs, EJS_IO_ERROR, "Cant get file info for %s", - argv[0]->string); - return -1; - } - - ejsSetPropertyToInteger(ejs, fileInfo, "created", info.ctime); - ejsSetPropertyToInteger(ejs, fileInfo, "length", info.size); - ejsSetPropertyToBoolean(ejs, fileInfo, "isDir", info.isDir); - - ejsSetReturnValue(ejs, fileInfo); - ejsMakeObjPermanent(fileInfo, 0); - - return 0; -} - -/******************************************************************************/ -/******************************** Initialization ******************************/ -/******************************************************************************/ - -int ejsDefineFileSystemClass(Ejs *ejs) -{ - EjsVar *fileSystemClass; - - fileSystemClass = ejsDefineClass(ejs, "FileSystem", "Object", 0); - if (fileSystemClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - /* - * Define the methods - */ - ejsDefineCMethod(ejs, fileSystemClass, "access", accessProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "mkdir", mkdirProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "rmdir", rmdirProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "dirList", dirListProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "writeFile", writeFileProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "readFile", readFileProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "remove", removeProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "rename", renameProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "copy", copyProc, 0); - ejsDefineCMethod(ejs, fileSystemClass, "getFileInfo", getFileInfoProc, 0); - - // MOB -- should be a property with accessor - ejsDefineCMethod(ejs, fileSystemClass, "getFreeSpace", getFreeSpaceProc, 0); - - return ejsObjHasErrors(fileSystemClass) ? MPR_ERR_CANT_INITIALIZE: 0; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/WIN/ejsHTTP.c b/source4/lib/appweb/ejs-2.0/ejs/system/WIN/ejsHTTP.c deleted file mode 100755 index 25821f6960..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/WIN/ejsHTTP.c +++ /dev/null @@ -1,488 +0,0 @@ -/* - * @file ejsHTTP.c - * @brief HTTP class for the EJ System Object Model - */ -/********************************** Copyright *********************************/ -/* - * Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved. - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if UNUSED -/*********************************** Defines **********************************/ - -#define EJS_WEB_PROPERTY "-web" -#define EJS_HTTP_PROPERTY "-http" - -#define EJS_HTTP_DISPOSED 550 - -/* - * Control structure for one HTTP request structure - */ -typedef struct HTTPControl { - Ejs *ejs; - IWebResp *webResp; - AEECallback *callback; - MprBuf *buf; - EjsVar *thisObj; - char *url; - MprTime requestStarted; - uint timeout; -} HTTPControl; - -/****************************** Forward Declarations **************************/ - -static void cleanup(HTTPControl *hp); -static int createWeb(Ejs *ejs, EjsVar *thisObj); -static void brewCallback(HTTPControl *hp); -static int httpDestructor(Ejs *ejs, EjsVar *vp); -static void httpCallback(HTTPControl *hp, int responseCode); -static int setCallback(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv); - -/******************************************************************************/ -/* - * Constructor - */ - -int ejsHTTPConstructor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 0 && argc != 2) { - ejsError(ejs, EJS_ARG_ERROR, - "Bad usage: HTTP([obj = this, method = onComplete]);"); - return -1; - } - - if (createWeb(ejs, thisObj) < 0) { - return -1; - } - - setCallback(ejs, thisObj, argc, argv); - return 0; -} - -/******************************************************************************/ - -static int createWeb(Ejs *ejs, EjsVar *thisObj) -{ - MprApp *app; - void *web; - - app = mprGetApp(ejs); - - /* - * Create one instance of IWeb for the entire application. Do it here - * so only widgets that require HTTP incurr the overhead. - */ - web = mprGetKeyValue(ejs, "bpWeb"); - if (web == 0) { - if (ISHELL_CreateInstance(app->shell, AEECLSID_WEB, &web) != SUCCESS) { - ejsError(ejs, EJS_IO_ERROR, "Can't create IWEB"); - return -1; - } - } - mprSetKeyValue(ejs, "bpWeb", web); - return 0; -} - -/******************************************************************************/ -/************************************ Methods *********************************/ -/******************************************************************************/ -/* - * function setCallback(obj, methodString); - */ - -static int setCallback(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc >= 1) { - ejsSetProperty(ejs, thisObj, "obj", argv[0]); - } else { - ejsSetProperty(ejs, thisObj, "obj", thisObj); - } - - if (argc >= 2) { - ejsSetProperty(ejs, thisObj, "method", argv[1]); - } else { - ejsSetPropertyToString(ejs, thisObj, "method", "onComplete"); - } - - return 0; -} - -/******************************************************************************/ -/* - * function fetch(); - */ - -static int fetchProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - HTTPControl *hp; - EjsProperty *pp; - MprApp *app; - IWeb *web; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsError(ejs, EJS_ARG_ERROR, "Bad usage: fetch(url)"); - return -1; - } - - app = mprGetApp(ejs); - web = (IWeb*) mprGetKeyValue(ejs, "bpWeb"); - - /* - * Web options - * - * WEBOPT_USERAGENT (char*) sets user agent - * WEBOPT_HANDLERDATA (void*) - * WEBOPT_CONNECTTIMEOUT (uint) msec - * WEBOPT_CONTENTLENGTH (long) - * WEBOPT_IDLECONNTIMEOUT (int) - * WEBOPT_ACTIVEXACTIONST (uint) Number of active requests - * - * WEBREQUEST_REDIRECT redirect transparently - * - */ - - hp = mprAllocType(ejs, HTTPControl); - if (hp == 0) { - ejsMemoryError(ejs); - return -1; - } - - hp->ejs = ejs; - hp->buf = mprCreateBuf(hp, MPR_BUF_INCR, MPR_MAX_BUF); - if (hp->buf == 0) { - mprFree(hp); - ejsMemoryError(ejs); - return -1; - } - - /* - * We copy thisObj because we need to preserve both the var and the object. - * We pass the var to brewCallback and so it must persist. The call to - * ejsMakeObjPermanent will stop the GC from collecting the object. - */ - hp->thisObj = ejsDupVar(ejs, thisObj, EJS_SHALLOW_COPY); - ejsSetVarName(ejs, hp->thisObj, "internalHttp"); - - /* - * Must keep a reference to the http object - */ - ejsMakeObjPermanent(hp->thisObj, 1); - - /* - * Make a property so we can access the HTTPControl structure from other - * methods. - */ - pp = ejsSetPropertyToPtr(ejs, thisObj, EJS_HTTP_PROPERTY, hp, 0); - ejsMakePropertyEnumerable(pp, 0); - ejsSetObjDestructor(ejs, hp->thisObj, httpDestructor); - - hp->url = mprStrdup(hp, argv[0]->string); - - hp->timeout = ejsGetPropertyAsInteger(ejs, thisObj, "timeout"); - mprGetTime(hp, &hp->requestStarted); - - hp->callback = mprAllocTypeZeroed(hp, AEECallback); - CALLBACK_Init(hp->callback, brewCallback, hp); - - hp->webResp = 0; - IWEB_GetResponse(web, - (web, &hp->webResp, hp->callback, hp->url, - WEBOPT_HANDLERDATA, hp, - WEBOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)", - WEBOPT_CONNECTTIMEOUT, hp->timeout, - WEBOPT_COPYOPTS, TRUE, - WEBOPT_CONTENTLENGTH, 0, - WEBOPT_END)); - - ejsSetPropertyToString(ejs, thisObj, "status", "active"); - - return 0; -} - -/******************************************************************************/ -/* - * Called whenver the http object is deleted. - */ - -static int httpDestructor(Ejs *ejs, EjsVar *thisObj) -{ - HTTPControl *hp; - - /* - * If the httpCallback has run, then this property will not exist - */ - hp = ejsGetPropertyAsPtr(ejs, thisObj, EJS_HTTP_PROPERTY); - - if (hp) { - cleanup(hp); - } - - return 0; -} - -/******************************************************************************/ -/* - * Stop the request immediately without calling the callback - */ - -static int stopProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - HTTPControl *hp; - - hp = ejsGetPropertyAsPtr(ejs, thisObj, EJS_HTTP_PROPERTY); - - if (hp) { - cleanup(hp); - } - - return 0; -} - -/******************************************************************************/ -/* - * Brew HTTP callback. Invoked for any return data. - */ - -static void brewCallback(HTTPControl *hp) -{ - Ejs *ejs; - EjsVar *thisObj; - ISource *source; - WebRespInfo *info; - char data[MPR_BUF_INCR]; - int bytes; - - mprAssert(hp); - mprAssert(hp->webResp); - - info = IWEBRESP_GetInfo(hp->webResp); - - if (info == 0) { - mprAssert(info); - /* should not happen */ - return; - } - - ejs = hp->ejs; - thisObj = hp->thisObj; - - if (! WEB_ERROR_SUCCEEDED(info->nCode)) { - ejsSetPropertyToString(ejs, thisObj, "status", "error"); - httpCallback(hp, info->nCode); - return; - } - - if (hp->timeout) { - if (mprGetTimeRemaining(hp, hp->requestStarted, hp->timeout) <= 0) { - ejsSetPropertyToString(ejs, thisObj, "status", "timeout"); - httpCallback(hp, 504); - return; - } - } - - /* - * Normal success - */ - source = info->pisMessage; - mprAssert(source); - - bytes = ISOURCE_Read(source, data, sizeof(data)); - - switch (bytes) { - case ISOURCE_WAIT: // No data yet - ISOURCE_Readable(source, hp->callback); - break; - - case ISOURCE_ERROR: - ejsSetPropertyToString(ejs, thisObj, "status", "error"); - httpCallback(hp, info->nCode); - break; - - case ISOURCE_END: - mprAddNullToBuf(hp->buf); - ejsSetPropertyToString(ejs, thisObj, "status", "complete"); - httpCallback(hp, info->nCode); - break; - - default: - if (bytes > 0) { - if (mprPutBlockToBuf(hp->buf, data, bytes) != bytes) { - ejsSetPropertyToString(ejs, thisObj, "status", "partialData"); - httpCallback(hp, 500); - } - } - ISOURCE_Readable(source, hp->callback); - break; - } -} - -/******************************************************************************/ -/* - * Invoke the HTTP completion method - */ - -static void httpCallback(HTTPControl *hp, int responseCode) -{ - Ejs *ejs; - EjsVar *thisObj, *callbackObj; - MprArray *args; - char *msg; - const char *callbackMethod; - - mprAssert(hp); - mprAssert(hp->webResp); - - thisObj = hp->thisObj; - ejs = hp->ejs; - - ejsSetPropertyToInteger(ejs, thisObj, "responseCode", responseCode); - if (mprGetBufLength(hp->buf) > 0) { - ejsSetPropertyToBinaryString(ejs, thisObj, "responseData", - mprGetBufStart(hp->buf), mprGetBufLength(hp->buf)); - } - - callbackObj = ejsGetPropertyAsVar(ejs, thisObj, "obj"); - callbackMethod = ejsGetPropertyAsString(ejs, thisObj, "method"); - - if (callbackObj != 0 && callbackMethod != 0) { - - args = mprCreateItemArray(ejs, EJS_INC_ARGS, EJS_MAX_ARGS); - mprAddItem(args, ejsDupVar(ejs, hp->thisObj, EJS_SHALLOW_COPY)); - - if (ejsRunMethod(ejs, callbackObj, callbackMethod, args) < 0) { - msg = ejsGetErrorMsg(ejs); - mprError(ejs, MPR_LOC, "HTTP callback failed. Details: %s", msg); - } - ejsFreeMethodArgs(ejs, args); - - } else if (ejsRunMethod(ejs, thisObj, "onComplete", 0) < 0) { - msg = ejsGetErrorMsg(ejs); - mprError(ejs, MPR_LOC, "HTTP onComplete failed. Details: %s", msg); - } - - cleanup(hp); -} - -/******************************************************************************/ -/* - * Cleanup - */ - -static void cleanup(HTTPControl *hp) -{ - Ejs *ejs; - MprApp *app; - int rc; - - mprAssert(hp); - mprAssert(hp->webResp); - - ejs = hp->ejs; - - if (hp->webResp) { - rc = IWEBRESP_Release(hp->webResp); - // mprAssert(rc == 0); - hp->webResp = 0; - } - - if (hp->callback) { - CALLBACK_Cancel(hp->callback); - mprFree(hp->callback); - hp->callback = 0; - } - - /* - * Once the property is deleted, then if the destructor runs, it will - * notice that the EJS_HTTP_PROPERTY is undefined. - */ - ejsDeleteProperty(ejs, hp->thisObj, EJS_HTTP_PROPERTY); - - /* - * Allow garbage collection to work on thisObj - */ - ejsMakeObjPermanent(hp->thisObj, 0); - ejsFreeVar(ejs, hp->thisObj); - - mprFree(hp->buf); - mprFree(hp->url); - - mprFree(hp); - - app = mprGetApp(ejs); - - - ISHELL_SendEvent(app->shell, (AEECLSID) app->classId, EVT_USER, 0, 0); -} - -/******************************************************************************/ -/******************************** Initialization ******************************/ -/******************************************************************************/ - -int ejsDefineHTTPClass(Ejs *ejs) -{ - EjsVar *httpClass; - - httpClass = - ejsDefineClass(ejs, "HTTP", "Object", ejsHTTPConstructor); - if (httpClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - /* - * Define the methods - */ - ejsDefineCMethod(ejs, httpClass, "fetch", fetchProc, 0); - ejsDefineCMethod(ejs, httpClass, "stop", stopProc, 0); - ejsDefineCMethod(ejs, httpClass, "setCallback", setCallback, 0); - -#if FUTURE - ejsDefineCMethod(ejs, httpClass, "put", put, 0); - ejsDefineCMethod(ejs, httpClass, "upload", upload, 0); - ejsDefineCMethod(ejs, httpClass, "addUploadFile", addUploadFile, 0); - ejsDefineCMethod(ejs, httpClass, "addPostData", addPostData, 0); - ejsDefineCMethod(ejs, httpClass, "setUserPassword", setUserPassword, 0); - ejsDefineCMethod(ejs, httpClass, "addCookie", addCookie, 0); -#endif - - /* - * Define properties - */ - ejsSetPropertyToString(ejs, httpClass, "status", "inactive"); - - /* This default should come from player.xml */ - - ejsSetPropertyToInteger(ejs, httpClass, "timeout", 30 * 1000); - ejsSetPropertyToInteger(ejs, httpClass, "responseCode", 0); - - return ejsObjHasErrors(httpClass) ? MPR_ERR_CANT_INITIALIZE: 0; -} - -/******************************************************************************/ - -void ejsTermHTTPClass(Ejs *ejs) -{ - IWeb *web; - int rc; - - web = (IWeb*) mprGetKeyValue(ejs, "bpWeb"); - if (web) { - rc = IWEB_Release(web); - mprAssert(rc == 0); - } -} - -#endif -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/ejsGC.c b/source4/lib/appweb/ejs-2.0/ejs/system/ejsGC.c deleted file mode 100644 index 411975f80e..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/ejsGC.c +++ /dev/null @@ -1,326 +0,0 @@ -/* - * @file ejsGC.c - * @brief Garbage collector class for the EJS Object Model - */ -/********************************** Copyright *********************************/ -/* - * Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved. - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -/******************************************************************************/ -/************************************ Methods *********************************/ -/******************************************************************************/ -#if (WIN || BREW_SIMULATOR) && BLD_DEBUG - -static int checkProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - _CrtCheckMemory(); - return 0; -} - -#endif -/******************************************************************************/ - -static int debugProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 1) { - ejsError(ep, EJS_ARG_ERROR, "Bad args: debug(debugLevel)"); - return -1; - } - - ejsSetGCDebugLevel(ep, ejsVarToInteger(argv[0])); - return 0; -} - -/******************************************************************************/ -/* - * Print stats and dump objects - */ - -static int printStatsProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - bool leakStats; - - if (argc > 1) { - leakStats = ejsVarToInteger(argv[0]); - } else { - leakStats = 0; - } - -#if BLD_FEATURE_ALLOC_STATS - ejsPrintAllocReport(ep, 0); - - mprPrintAllocReport(mprGetApp(ep), leakStats, 0); -#endif - -#if BLD_DEBUG - ejsDumpObjects(ep); -#endif - - return 0; -} - -/******************************************************************************/ - -static int runProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc > 1) { - ejsError(ep, EJS_ARG_ERROR, "Bad args: run([quick])"); - return -1; - } - - if (argc == 1) { - ejsIncrementalCollectGarbage(ep); - } else { - ejsCollectGarbage(ep, -1); - } - return 0; -} - -/******************************************************************************/ - -static int usedMemoryProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsSetReturnValueToInteger(ep, ejsGetUsedMemory(ep)); - return 0; -} - -/******************************************************************************/ - -static int allocatedMemoryProc(Ejs *ep, EjsVar *thisObj, int argc, - EjsVar **argv) -{ -#if BLD_FEATURE_ALLOC_STATS - ejsSetReturnValueToInteger(ep, ejsGetAllocatedMemory(ep)); -#endif - return 0; -} - -/******************************************************************************/ - -static int mprMemoryProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ -#if BLD_FEATURE_ALLOC_STATS - ejsSetReturnValueToInteger(ep, mprGetAllocatedMemory(ep)); -#endif - return 0; -} - -/******************************************************************************/ - -static int peakMprMemoryProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ -#if BLD_FEATURE_ALLOC_STATS - ejsSetReturnValueToInteger(ep, mprGetPeakAllocatedMemory(ep)); -#endif - return 0; -} - -/******************************************************************************/ - -static int getDebugLevel(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsSetReturnValueToInteger(ep, ep->gc.debugLevel); - return 0; -} - -/******************************************************************************/ - -static int setDebugLevel(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 1) { - ejsArgError(ep, "Bad arguments"); - return -1; - } - ep->gc.debugLevel= ejsVarToInteger(argv[0]); - return 0; -} - -/******************************************************************************/ - -static int getEnable(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsSetReturnValueToBoolean(ep, ep->gc.enable); - return 0; -} - -/******************************************************************************/ - -static int setEnable(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 1) { - ejsArgError(ep, "Bad arguments"); - return -1; - } - ep->gc.enable= ejsVarToBoolean(argv[0]); - return 0; -} - -/******************************************************************************/ - -static int getDemandCollect(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsSetReturnValueToBoolean(ep, ep->gc.enableDemandCollect); - return 0; -} - -/******************************************************************************/ - -static int setDemandCollect(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 1) { - ejsArgError(ep, "Bad arguments"); - return -1; - } - ep->gc.enableDemandCollect = ejsVarToBoolean(argv[0]); - return 0; -} - -/******************************************************************************/ - -static int getIdleCollect(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsSetReturnValueToBoolean(ep, ep->gc.enableIdleCollect); - return 0; -} - -/******************************************************************************/ - -static int setIdleCollect(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 1) { - ejsArgError(ep, "Bad arguments"); - return -1; - } - ep->gc.enableIdleCollect = ejsVarToBoolean(argv[0]); - return 0; -} - -/******************************************************************************/ - -static int getWorkQuota(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsSetReturnValueToInteger(ep, ep->gc.workQuota); - return 0; -} - -/******************************************************************************/ - -static int setWorkQuota(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int quota; - - if (argc != 1) { - ejsArgError(ep, "Bad arguments"); - return -1; - } - quota = ejsVarToInteger(argv[0]); - if (quota < EJS_GC_MIN_WORK_QUOTA && quota != 0) { - ejsArgError(ep, "Bad work quota"); - return -1; - } - - ep->gc.workQuota = quota; - return 0; -} - -/******************************************************************************/ - -static int getMaxMemory(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsSetReturnValueToInteger(ep, ep->gc.maxMemory); - return 0; -} - -/******************************************************************************/ - -static int setMaxMemory(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int maxMemory; - - if (argc != 1) { - ejsArgError(ep, "Bad arguments"); - return -1; - } - maxMemory = ejsVarToInteger(argv[0]); - if (maxMemory < 0) { - ejsArgError(ep, "Bad maxMemory"); - return -1; - } - - ep->gc.maxMemory = maxMemory; - return 0; -} - -/******************************************************************************/ -/******************************** Initialization ******************************/ -/******************************************************************************/ - -int ejsDefineGCClass(Ejs *ep) -{ - EjsVar *gcClass; - int flags; - - flags = EJS_NO_LOCAL; - - /* - * NOTE: We create the GC class and define static methods on it. There - * is no object instance - */ - gcClass = ejsDefineClass(ep, "System.GC", "Object", 0); - if (gcClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - /* - * MOB -- convert these to properties with accessors when available - */ - ejsDefineCMethod(ep, gcClass, "printStats", printStatsProc, flags); - ejsDefineCMethod(ep, gcClass, "run", runProc, flags); - - ejsDefineCMethod(ep, gcClass, "getUsedMemory", usedMemoryProc, flags); - ejsDefineCMethod(ep, gcClass, "getAllocatedMemory", allocatedMemoryProc, - flags); - ejsDefineCMethod(ep, gcClass, "getMprMemory", mprMemoryProc, flags); - ejsDefineCMethod(ep, gcClass, "getPeakMprMemory", peakMprMemoryProc, flags); - ejsDefineCMethod(ep, gcClass, "debug", debugProc, flags); - -#if (WIN || BREW_SIMULATOR) && BLD_DEBUG - ejsDefineCMethod(ep, gcClass, "check", checkProc, flags); -#endif - - ejsDefineCAccessors(ep, gcClass, "debugLevel", - getDebugLevel, setDebugLevel, flags); - - ejsDefineCAccessors(ep, gcClass, "enable", - getEnable, setEnable, flags); - - ejsDefineCAccessors(ep, gcClass, "demandCollect", - getDemandCollect, setDemandCollect, flags); - - ejsDefineCAccessors(ep, gcClass, "idleCollect", - getIdleCollect, setIdleCollect, flags); - - ejsDefineCAccessors(ep, gcClass, "workQuota", - getWorkQuota, setWorkQuota, flags); - - ejsDefineCAccessors(ep, gcClass, "maxMemory", - getMaxMemory, setMaxMemory, flags); - - return ejsObjHasErrors(gcClass) ? MPR_ERR_CANT_INITIALIZE : 0; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/ejsGlobal.c b/source4/lib/appweb/ejs-2.0/ejs/system/ejsGlobal.c deleted file mode 100755 index 6ab8f867e1..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/ejsGlobal.c +++ /dev/null @@ -1,785 +0,0 @@ -/* - * @file ejsGlobal.c - * @brief EJS support methods - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -#if BLD_FEATURE_EJS - -/******************************************************************************/ -/************************************* Code ***********************************/ -/******************************************************************************/ -/* - * assert(condition) - */ - -static int assertProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int b; - - if (argc < 1) { - ejsError(ep, EJS_ARG_ERROR, "usage: assert(condition)"); - return -1; - } - b = ejsVarToBoolean(argv[0]); - if (b == 0) { - ejsError(ep, EJS_ASSERT_ERROR, "Assertion failure at line %d", - ejsGetLineNumber(ep)); - return -1; - } - ejsWriteVarAsBoolean(ep, ep->result, b); - return 0; -} - -/******************************************************************************/ -/* - * breakpoint(msg) - */ - -static int breakpointProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - char *buf; - - if (argc < 1) { - return 0; - } - buf = ejsVarToString(ep, argv[0]); - if (buf) { - mprBreakpoint(0, buf); - } - return 0; -} - -/******************************************************************************/ -/* - * basename(path) - */ - -static int basenameProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - char *path; - - if (argc != 1) { - ejsError(ep, EJS_ARG_ERROR, "usage: basename(path)"); - return -1; - } - - path = ejsVarToString(ep, argv[0]); - if (path == 0) { - return MPR_ERR_MEMORY; - } - ejsSetReturnValueToString(ep, mprGetBaseName(path)); - - return 0; -} - -/******************************************************************************/ -/* - * stripext(path) - */ - -static int stripextProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - char *cp, *path, *stripPath; - - if (argc != 1) { - ejsError(ep, EJS_ARG_ERROR, "usage: stripext(path)"); - return -1; - } - - path = ejsVarToString(ep, argv[0]); - if (path == 0) { - return MPR_ERR_MEMORY; - } - stripPath = mprStrdup(ep, path); - - if ((cp = strrchr(stripPath, '.')) != 0) { - *cp = '\0'; - } - - ejsSetReturnValueToString(ep, stripPath); - - mprFree(stripPath); - - return 0; -} - -/******************************************************************************/ -/* - * dirname(path) - */ - -static int dirnameProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - char *path; - char dirname[MPR_MAX_FNAME]; - - if (argc != 1) { - ejsError(ep, EJS_ARG_ERROR, "usage: dirname(path)"); - return -1; - } - - path = ejsVarToString(ep, argv[0]); - if (path == 0) { - return MPR_ERR_MEMORY; - } - - ejsSetReturnValueToString(ep, - mprGetDirName(dirname, sizeof(dirname), path)); - - return 0; -} - -/******************************************************************************/ -/* - * trim(string) -- trim white space - */ - -static int trimProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - char *str, *buf, *cp; - - if (argc != 1) { - ejsError(ep, EJS_ARG_ERROR, "usage: trim(string)"); - return -1; - } - - str = ejsVarToString(ep, argv[0]); - if (str == 0) { - return MPR_ERR_MEMORY; - } - str = buf = mprStrdup(ep, str); - - while (isspace(*str)) { - str++; - } - cp = &str[strlen(str) - 1]; - while (cp >= str) { - if (isspace(*cp)) { - *cp = '\0'; - } else { - break; - } - cp--; - } - - ejsSetReturnValueToString(ep, str); - - mprFree(buf); - - return 0; -} - -/******************************************************************************/ -/* - * Terminate the script - */ - -static int exitScript(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int status; - - if (argc != 1) { - ejsError(ep, EJS_ARG_ERROR, "usage: exit(status)"); - return -1; - } - status = (int) ejsVarToInteger(argv[0]); - ejsExit(ep, status); - - ejsWriteVarAsString(ep, ep->result, ""); - return 0; -} - -/******************************************************************************/ -/* - * include javascript libraries. - */ - -static int includeProc(Ejs *ep, EjsVar *thisObj, int argc, char **argv) -{ - int i; - - mprAssert(argv); - - for (i = 0; i < argc; i++) { - if (ejsEvalFile(ep, argv[i], 0) < 0) { - return -1; - } - } - return 0; -} - -/******************************************************************************/ -/* - * include javascript libraries at the global level - */ - -static int includeGlobalProc(Ejs *ep, EjsVar *thisObj, int argc, char **argv) -{ - int fid, i; - - mprAssert(argv); - - /* - * Create a new block and set the context to be the global scope - */ - fid = ejsSetBlock(ep, ep->global); - - for (i = 0; i < argc; i++) { - if (ejsEvalFile(ep, argv[i], 0) < 0) { - ejsCloseBlock(ep, fid); - return -1; - } - } - ejsCloseBlock(ep, fid); - return 0; -} - -/******************************************************************************/ -#if BLD_DEBUG -/* - * Print variables to stdout - */ - -static int printvProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - EjsVar *vp; - char *buf; - int i; - - for (i = 0; i < argc; ) { - vp = argv[i++]; - - /* mprPrintf(ep, "arg[%d] = ", i); */ - - buf = ejsVarToString(ep, vp); - - if (vp->propertyName == 0 || *vp->propertyName == '\0') { - mprPrintf(ep, "%s: ", buf); - - } else if (i < argc) { - mprPrintf(ep, "%s = %s, ", vp->propertyName, buf); - } else { - mprPrintf(ep, "%s = %s\n", vp->propertyName, buf); - } - } - return 0; -} - -#endif -/******************************************************************************/ -/* - * Print the args to stdout - */ - -static int printProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - char *buf; - int i; - - for (i = 0; i < argc; i++) { - buf = ejsVarToString(ep, argv[i]); - mprPrintf(ep, "%s", buf); - } - return 0; -} - -/******************************************************************************/ -/* - * println - */ - -static int printlnProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - printProc(ep, thisObj, argc, argv); - mprPrintf(ep, "\n"); - return 0; -} - -/******************************************************************************/ -#if FUTURE -/* - * sprintf - */ - -static int sprintfProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - va_list ap; - char *buf; - void **args; - int result; - - if (argc <= 1) { - ejsError(ep, EJS_ARG_ERROR, "Usage: sprintf(fmt, [args ...])"); - return -1; - } - - args = mprAlloc(ep, sizeof(void*) * (argc - 1)); - if (args == 0) { - mprAssert(args); - return -1; - } - - for (i = 1; i < argc; i++) { - args[i - 1] = argv[i]); - } - - va_start(ap, fmt); - *buf = 0; - result = inner(0, &buf, MPR_MAX_STRING, fmt, args); - va_end(ap); - - ejsSetReturnValueToString(ep, buf); - - mprFree(buf); - return 0; -} - -/******************************************************************************/ - -inner(const char *fmt, void **args) -{ - va_list ap; - - va_start(ap, fmt); - *buf = 0; - mprSprintfCore(ctx, &buf, maxSize, fmt, ap, MPR_PRINTF_ARGV); - va_end(ap); -} - -#endif -/******************************************************************************/ -/* - * sleep - */ - -static int sleepProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 1) { - ejsError(ep, EJS_ARG_ERROR, "Usage: sleep(milliseconds)"); - return -1; - } - mprSleep(ep, ejsVarToInteger(argv[0])); - return 0; -} - -/******************************************************************************/ -/* - * sort properties - * FUTURE -- should have option to sort object based on a given property value - * ascending or descending - * Usage: sort(object, order = ascending, property = 0); - */ - -static int sortProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - const char *property; - int error, order; - - error = 0; - property = 0; - - /* - * Default order is increasing - */ - order = 1; - - if (argc < 1 || argc > 3 || !ejsVarIsObject(argv[0])) { - error++; - } - - if (argc >= 2) { - order = ejsVarToInteger(argv[1]); - } - - /* - * If property is not defined, it sorts the properties in the object - */ - if (argc == 3) { - if (! ejsVarIsString(argv[2])) { - error++; - } else { - property = argv[2]->string; - } - } - - if (error) { - ejsError(ep, EJS_ARG_ERROR, "Usage: sort(object, [order], [property])"); - return -1; - } - ejsSortProperties(ep, argv[0], 0, property, order); - return 0; -} - -/******************************************************************************/ -/* - * Get a time mark - * MOB -- WARNING: this can overflow. OK on BREW, but other O/Ss it may have - * overflowed on the first call. It should be renamed. - * MOB -- replace with proper Date. - */ - -static int timeProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - MprTime now; - - mprGetTime(ep, &now); -#if WIN || LINUX || SOLARIS -{ - /* MOB -- poor hack */ - static MprTime initial; - if (initial.sec == 0) { - initial = now; - } - now.sec -= initial.sec; - - if (initial.msec > now.msec) { - now.msec = now.msec + 1000 - initial.msec; - now.sec--; - } else { - now.msec -= initial.msec; - } -} -#endif - /* MOB -- this can overflow */ - ejsSetReturnValueToInteger(ep, now.sec * 1000 + now.msec); - return 0; -} - -/******************************************************************************/ -/* - * MOB -- Temporary Get the date (time since Jan 6, 1980 GMT - */ - -static int dateProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ -#if BREW - uint now; - - now = GETTIMESECONDS(); - ejsSetReturnValueToInteger(ep, now); -#endif - return 0; -} - -/******************************************************************************/ -/* - * strlen(string) - */ - -static int strlenProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - char *buf; - int len; - - if (argc != 1) { - ejsError(ep, EJS_ARG_ERROR, "Usage: strlen(var)"); - return -1; - } - - len = 0; - if (! ejsVarIsString(argv[0])) { - buf = ejsVarToString(ep, argv[0]); - if (buf) { - len = strlen(buf); - } - - } else { - len = argv[0]->length; - } - - ejsSetReturnValueToInteger(ep, len); - return 0; -} - -/******************************************************************************/ -/* - * toint(num) - */ - -static int tointProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int i; - - if (argc != 1) { - ejsError(ep, EJS_ARG_ERROR, "Usage: toint(number)"); - return -1; - } - - i = ejsVarToInteger(argv[0]); - - ejsSetReturnValueToInteger(ep, i); - return 0; -} - -/******************************************************************************/ -/* - * string strstr(string, pat) - */ - -static int strstrProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - char *str, *pat; - char *s; - int strAlloc; - - if (argc != 2) { - ejsError(ep, EJS_ARG_ERROR, "Usage: strstr(string, pat)"); - return -1; - } - - str = ejsVarToString(ep, argv[0]); - - strAlloc = ep->castAlloc; - ep->castTemp = 0; - - pat = ejsVarToString(ep, argv[1]); - - s = strstr(str, pat); - - if (s == 0) { - ejsSetReturnValueToUndefined(ep); - } else { - ejsSetReturnValueToString(ep, s); - } - - if (strAlloc) { - mprFree(str); - } - - return 0; -} - -/******************************************************************************/ -/* - * Trace - */ - -static int traceProc(Ejs *ep, EjsVar *thisObj, int argc, char **argv) -{ - if (argc == 1) { - mprLog(ep, 0, "%s", argv[0]); - - } else if (argc == 2) { - mprLog(ep, atoi(argv[0]), "%s", argv[1]); - - } else { - ejsError(ep, EJS_ARG_ERROR, "Usage: trace([level], message)"); - return -1; - } - ejsWriteVarAsString(ep, ep->result, ""); - return 0; -} - -/******************************************************************************/ -/* - * Evaluate a sub-script. It is evaluated in the same variable scope as - * the calling script / method. - */ - -static int evalScriptProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - EjsVar *arg; - int i; - - ejsWriteVarAsUndefined(ep, ep->result); - - for (i = 0; i < argc; i++) { - arg = argv[i]; - if (arg->type != EJS_TYPE_STRING) { - continue; - } - if (ejsEvalScript(ep, arg->string, 0) < 0) { - return -1; - } - } - /* - * Return with the value of the last expression - */ - return 0; -} - -/******************************************************************************/ - -/* MOB -- need a real datatype returning int, int64, etc */ - -static int typeofProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - const struct { - EjsType type; - const char *name; - } types[] = { - { EJS_TYPE_UNDEFINED, "undefined" }, -#if EJS_ECMA_STND - { EJS_TYPE_NULL, "object" }, -#else - { EJS_TYPE_NULL, "null" }, -#endif - { EJS_TYPE_BOOL, "boolean" }, - { EJS_TYPE_CMETHOD, "function" }, - { EJS_TYPE_FLOAT, "number" }, - { EJS_TYPE_INT, "number" }, - { EJS_TYPE_INT64, "number" }, - { EJS_TYPE_OBJECT, "object" }, - { EJS_TYPE_METHOD, "function" }, - { EJS_TYPE_STRING, "string" }, - { EJS_TYPE_STRING_CMETHOD, "function" }, - { EJS_TYPE_PTR, "pointer" } - }; - const char *type; - int i; - - type = NULL; - if (argc != 1) { - ejsError(ep, EJS_ARG_ERROR, "Bad args: typeof(var)"); - return -1; - } - - for (i = 0; i < MPR_ARRAY_SIZE(types); i++) { - if (argv[0]->type == types[i].type) { - type = types[i].name; - break; - } - } - if (type == NULL) { - mprAssert(type); - return -1; - } - - ejsSetReturnValueToString(ep, type); - return 0; -} - -/******************************************************************************/ -/* - * Define the standard properties and methods inherited by all interpreters - * Obj is set to the global class in the default interpreter. When an - * interpreter attempts to write to any property, a copy will be written - * into the interpeters own global space. This is like a "copy-on-write". - */ - -int ejsDefineGlobalProperties(Ejs *ep) -{ - EjsVar *obj; - - obj = ep->service->globalClass; - mprAssert(obj); - - ejsSetPropertyToNull(ep, obj, "null"); - ejsSetPropertyToUndefined(ep, obj, "undefined"); - ejsSetPropertyToBoolean(ep, obj, "true", 1); - ejsSetPropertyToBoolean(ep, obj, "false", 0); - -#if BLD_FEATURE_FLOATING_POINT - { - /* MOB. Fix. This generates warnings on some systems. - This is intended. */ - double d = 0.0; - double e = 0.0; - ejsSetPropertyToFloat(ep, obj, "NaN", e / d); - - d = MAX_FLOAT; - ejsSetPropertyToFloat(ep, obj, "Infinity", d * d); - } -#endif - -#if BLD_FEATURE_LEGACY_API - /* - * DEPRECATED: 2.0. - * So that ESP/ASP can ignore "language=javascript" statements - */ - ejsSetPropertyToInteger(ep, obj, "javascript", 0); -#endif - - /* - * Extension methods. We go directly to the mpr property APIs for speed. - * Flags will cause the callbacks to be supplied the Ejs handle. - */ - ejsDefineCMethod(ep, obj, "assert", assertProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "breakpoint", breakpointProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "basename", basenameProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "dirname", dirnameProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "stripext", stripextProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "trim", trimProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "eval", evalScriptProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "exit", exitScript, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "print", printProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "println", printlnProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "sleep", sleepProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "sort", sortProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "time", timeProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "date", dateProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "strlen", strlenProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "strstr", strstrProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "typeof", typeofProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "toint", tointProc, EJS_NO_LOCAL); - - ejsDefineStringCMethod(ep, obj, "include", includeProc, EJS_NO_LOCAL); - ejsDefineStringCMethod(ep, obj, "includeGlobal", includeGlobalProc, - EJS_NO_LOCAL); - ejsDefineStringCMethod(ep, obj, "trace", traceProc, EJS_NO_LOCAL); - -#if BLD_DEBUG - ejsDefineCMethod(ep, obj, "printv", printvProc, EJS_NO_LOCAL); -#endif - -#if FUTURE - ejsDefineCMethod(ep, obj, "printf", printfProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, obj, "sprintf", sprintfProc, EJS_NO_LOCAL); -#endif - - if (ejsObjHasErrors(obj)) { - return MPR_ERR_CANT_INITIALIZE; - } - return 0; -} - -/******************************************************************************/ - -#else -void ejsProcsDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystem.c b/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystem.c deleted file mode 100644 index e035e1c740..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystem.c +++ /dev/null @@ -1,112 +0,0 @@ -/* - * @file ejsSystem.c - * @brief System class for the EJS Object Model - */ -/********************************** Copyright *********************************/ -/* - * Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved. - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -/******************************************************************************/ -/************************************ Methods *********************************/ -/******************************************************************************/ -#if UNUSED -/* - * function int random() - */ - -static int randomProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsTrace(ep, "random()\n"); - return 0; -} - -/******************************************************************************/ -/* - * function void yield() - */ - -static int yieldProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsTrace(ep, "yield()\n"); - return 0; -} - -/******************************************************************************/ -/* - * function void sleep(int milliSeconds) - */ - -static int sleepProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsTrace(ep, "sleep()\n"); - return 0; -} - -#endif -/******************************************************************************/ -/* - * function void exit(int status) - * - * Exit the widget with the given status. All JavaScript processing ceases. - */ - -static int exitProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv) -{ - int status; - - status = 0; - if ((argc == 1) && ejsVarIsInteger(argv[0])) { - status = argv[0]->integer; - } - ejsExit(ep, status); - return 0; -} - -/******************************************************************************/ -/******************************** Initialization ******************************/ -/******************************************************************************/ - -int ejsDefineSystemClass(Ejs *ep) -{ - EjsVar *systemClass; - - /* - * We create the system class and define static methods on it. - * NOTE: There is no object instance - */ - systemClass = ejsDefineClass(ep, "System", "Object", 0); - if (systemClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - ejsDefineCMethod(ep, systemClass, "exit", exitProc, EJS_NO_LOCAL); - -#if UNUSED - ejsDefineCMethod(ep, systemClass, "random", randomProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, systemClass, "yield", yieldProc, EJS_NO_LOCAL); - ejsDefineCMethod(ep, systemClass, "sleep", sleepProc, EJS_NO_LOCAL); - - /* - * Define properties - */ - ejsSetPropertyToString(systemClass, "name", ""); -#endif - - return ejsObjHasErrors(systemClass) ? MPR_ERR_CANT_INITIALIZE : 0; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemApp.c b/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemApp.c deleted file mode 100644 index e2f1ceb363..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemApp.c +++ /dev/null @@ -1,49 +0,0 @@ -/* - * @file ejsSystemApp.c - * @brief App class - */ -/********************************** Copyright *********************************/ -/* - * Copyright (c) Mbedthis Software Inc, 2005-2006. All Rights Reserved. - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -/************************************ Code ************************************/ - -int ejsDefineAppClass(Ejs *ep) -{ - EjsVar *appClass; - - appClass = ejsDefineClass(ep, "System.App", "Object", 0); - if (appClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - /* - * Define properties - */ - ejsSetPropertyToString(ep, appClass, "name", BLD_PRODUCT); - ejsSetPropertyToString(ep, appClass, "title", BLD_NAME); - ejsSetPropertyToString(ep, appClass, "version", BLD_VERSION); - - /* - * Command line arguments - */ - ejsSetPropertyToNull(ep, appClass, "args"); - - return ejsObjHasErrors(appClass) ? MPR_ERR_CANT_INITIALIZE : 0; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemDebug.c b/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemDebug.c deleted file mode 100644 index 5a011e2a2d..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemDebug.c +++ /dev/null @@ -1,60 +0,0 @@ -/* - * @file ejsSystemDebug.c - * @brief System.Debug class - */ -/********************************** Copyright *********************************/ -/* - * Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved. - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -/******************************************************************************/ -/************************************ Methods *********************************/ -/******************************************************************************/ -/* - * function bool isDebugMode() - * MOB -- convert to accessor - */ - -static int isDebugMode(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsTrace(ejs, "isDebugMode()\n"); - ejsSetReturnValueToInteger(ejs, mprGetDebugMode(ejs)); - return 0; -} - -/******************************************************************************/ -/******************************** Initialization ******************************/ -/******************************************************************************/ - -int ejsDefineDebugClass(Ejs *ejs) -{ - EjsVar *systemDebugClass; - - systemDebugClass = ejsDefineClass(ejs, "System.Debug", "Object", 0); - if (systemDebugClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - /* - * Define the class methods - */ - ejsDefineCMethod(ejs, systemDebugClass, "isDebugMode", isDebugMode, - EJS_NO_LOCAL); - - return ejsObjHasErrors(systemDebugClass) ? MPR_ERR_CANT_INITIALIZE : 0; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemLog.c b/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemLog.c deleted file mode 100644 index 66467f8fcf..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemLog.c +++ /dev/null @@ -1,163 +0,0 @@ -/* - * @file ejsSystemLog.c - * @brief System.Log class for the EJS Object Model - */ -/********************************** Copyright *********************************/ -/* - * Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved. - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -/*********************************** Usage ************************************/ -/* - * System.Log.setLog(path); - * System.Log.enable; - */ -/******************************************************************************/ - -static void logHandler(MPR_LOC_DEC(ctx, loc), int flags, int level, - const char *msg) -{ - MprApp *app; - char *buf; - int len; - - app = mprGetApp(ctx); - if (app->logFile == 0) { - return; - } - - if (flags & MPR_LOG_SRC) { - len = mprAllocSprintf(MPR_LOC_PASS(ctx, loc), &buf, 0, - "Log %d: %s\n", level, msg); - - } else if (flags & MPR_ERROR_SRC) { - len = mprAllocSprintf(MPR_LOC_PASS(ctx, loc), &buf, 0, - "Error: %s\n", msg); - - } else if (flags & MPR_FATAL_SRC) { - len = mprAllocSprintf(MPR_LOC_PASS(ctx, loc), &buf, 0, - "Fatal: %s\n", msg); - - } else if (flags & MPR_ASSERT_SRC) { -#if BLD_FEATURE_ALLOC_LEAK_TRACK - len = mprAllocSprintf(MPR_LOC_PASS(ctx, loc), &buf, 0, - "Assertion %s, failed at %s\n", - msg, loc); -#else - len = mprAllocSprintf(MPR_LOC_PASS(ctx, loc), &buf, 0, - "Assertion %s, failed\n", msg); -#endif - - } else if (flags & MPR_RAW) { - /* OPT */ - len = mprAllocSprintf(MPR_LOC_PASS(ctx, loc), &buf, 0, - "%s", msg); - - } else { - return; - } - - mprPuts(app->logFile, buf, len); - - mprFree(buf); -} - -/******************************************************************************/ -/************************************ Methods *********************************/ -/******************************************************************************/ -/* - * function int setLog(string path) - */ - -static int setLog(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - const char *path; - MprFile *file; - MprApp *app; - - if (argc != 1 || !ejsVarIsString(argv[0])) { - ejsArgError(ejs, "Usage: setLog(path)"); - return -1; - } - - app = mprGetApp(ejs); - - /* - * Ignore errors if we can't create the log file. - * Use the app context so this will live longer than the interpreter - * MOB -- this leaks files. - */ - path = argv[0]->string; - file = mprOpen(app, path, O_CREAT | O_TRUNC | O_WRONLY, 0664); - if (file) { - app->logFile = file; - mprSetLogHandler(ejs, logHandler); - } - mprLog(ejs, 0, "Test log"); - - return 0; -} - -/******************************************************************************/ -#if UNUSED - -static int enableSetAccessor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - if (argc != 1) { - ejsArgError(ejs, "Usage: set(value)"); - return -1; - } - ejsSetProperty(ejs, thisObj, "_enabled", argv[0]); - return 0; -} - -/******************************************************************************/ - -static int enableGetAccessor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsSetReturnValue(ejs, ejsGetPropertyAsVar(ejs, thisObj, "_enabled")); - return 0; -} - -#endif -/******************************************************************************/ -/******************************** Initialization ******************************/ -/******************************************************************************/ - -int ejsDefineLogClass(Ejs *ejs) -{ - EjsVar *logClass; - - logClass = ejsDefineClass(ejs, "System.Log", "Object", 0); - if (logClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - ejsDefineCMethod(ejs, logClass, "setLog", setLog, EJS_NO_LOCAL); - -#if UNUSED - EjsProperty *pp; - ejsDefineCAccessors(ejs, logClass, "enable", enableSetAccessor, - enableGetAccessor, EJS_NO_LOCAL); - - pp = ejsSetPropertyToBoolean(ejs, logClass, "_enabled", 0); - ejsMakePropertyEnumerable(pp, 0); -#endif - - return ejsObjHasErrors(logClass) ? MPR_ERR_CANT_INITIALIZE : 0; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemMemory.c b/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemMemory.c deleted file mode 100755 index d10787b1b4..0000000000 --- a/source4/lib/appweb/ejs-2.0/ejs/system/ejsSystemMemory.c +++ /dev/null @@ -1,174 +0,0 @@ -/* - * @file ejsSystemMemory.c - * @brief System.Memory class - */ -/********************************** Copyright *********************************/ -/* - * Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved. - */ -/********************************** Includes **********************************/ - -#include "ejs.h" - -/****************************** Forward Declarations***************************/ - -static uint getUsedMemory(Ejs *ejs); - -/******************************************************************************/ -/*********************************** Methods *********************************/ -/******************************************************************************/ - -static int getUsedMemoryProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsSetReturnValueToInteger(ejs, getUsedMemory(ejs)); - return 0; -} - -/******************************************************************************/ - -static int getUsedStackProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv) -{ - ejsSetReturnValueToInteger(ejs, mprStackSize(ejs)); - return 0; -} - -/******************************************************************************/ -/* - * Public function - */ - -uint ejsGetAvailableMemory(Ejs *ejs) -{ - EjsVar *memoryClass; - uint ram; - - memoryClass = ejsGetClass(ejs, 0, "System.Memory"); - - ram = ejsGetPropertyAsInteger(ejs, memoryClass, "ram"); - return ram - getUsedMemory(ejs); -} - -/******************************************************************************/ - -static int getAvailableMemoryProc(Ejs *ejs, EjsVar *thisObj, int argc, - EjsVar **argv) -{ - EjsVar *memoryClass; - uint ram; - - memoryClass = ejsGetClass(ejs, 0, "System.Memory"); - - ram = ejsGetPropertyAsInteger(ejs, memoryClass, "ram"); -#if BREW - ejsSetReturnValueToInteger(ejs, ram - getUsedMemory(ejs)); -#else - ejsSetReturnValueToInteger(ejs, 0); -#endif - return 0; -} - -/******************************************************************************/ - -static uint getUsedMemory(Ejs *ejs) -{ -#if BREW - MprApp *app; - IHeap *heap; - uint memInUse; - void *ptr; - - app = mprGetApp(ejs); - ptr = (void*) &heap; - if (ISHELL_CreateInstance(app->shell, AEECLSID_HEAP, (void**) ptr) - == SUCCESS) { - memInUse = IHEAP_GetMemStats(heap); - IHEAP_Release(heap); - } else { - memInUse = 0; - } - - return memInUse; -#else - return 0; -#endif -} - -/******************************************************************************/ -/******************************** Initialization ******************************/ -/******************************************************************************/ - -int ejsDefineMemoryClass(Ejs *ejs) -{ - EjsVar *memoryClass; - uint used; - -#if BREW - MprApp *app; - AEEDeviceInfo *info; - - /* - * Get needed information for class properties. - */ - info = mprAllocType(ejs, AEEDeviceInfo); - if (info == 0) { - return MPR_ERR_CANT_ALLOCATE; - } - info->wStructSize = sizeof(AEEDeviceInfo); - app = mprGetApp(ejs); - ISHELL_GetDeviceInfo(app->shell, info); - used = getUsedMemory(ejs); -#else - used = 0; -#endif - - /* - * Create the class - */ - memoryClass = ejsDefineClass(ejs, "System.Memory", "Object", 0); - if (memoryClass == 0) { - return MPR_ERR_CANT_INITIALIZE; - } - - /* - * Define the class methods - * MOB -- change to accessors - */ - ejsDefineCMethod(ejs, memoryClass, "getUsedStack", getUsedStackProc, - EJS_NO_LOCAL); - ejsDefineCMethod(ejs, memoryClass, "getUsedMemory", getUsedMemoryProc, - EJS_NO_LOCAL); - ejsDefineCMethod(ejs, memoryClass, "getAvailableMemory", - getAvailableMemoryProc, EJS_NO_LOCAL); - - /* - * Define properties - */ -#if BREW - ejsSetPropertyToInteger(ejs, memoryClass, "ram", info->dwRAM); - -#if UNUSED - /* MOB -- delete this */ - ejsSetPropertyToInteger(ejs, memoryClass, "available", - info->dwRAM - used); -#endif -#endif - -#if UNUSED - ejsSetPropertyToInteger(ejs, memoryClass, "used", used); - ejsSetPropertyToInteger(ejs, memoryClass, "flash", 0); -#endif - - return ejsObjHasErrors(memoryClass) ? MPR_ERR_CANT_INITIALIZE : 0; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/exml/Makefile b/source4/lib/appweb/ejs-2.0/exml/Makefile deleted file mode 100644 index 663e65ed53..0000000000 --- a/source4/lib/appweb/ejs-2.0/exml/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -# -# Makefile for Embedded XML (EXML) -# -# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. -# - -# -# EXML may be linked into shared handlers so we must build the objects both -# shared and static. -# -COMPILE := *.c -EXPORT_OBJECTS := yes -MAKE_IFLAGS := -I../mpr - -include make.dep - -ifeq ($(BLD_FEATURE_TEST),1) -POST_DIRS := test -endif - -TARGETS += $(BLD_BIN_DIR)/libexml$(BLD_LIB) - -ifeq ($(BLD_FEATURE_XML),1) -compileExtra: $(TARGETS) -endif - -# MOB -- remove when FEATURE_XML is defined -compileExtra: $(TARGETS) - -$(BLD_BIN_DIR)/libexml$(BLD_LIB): $(FILES) - @bld --library $(BLD_BIN_DIR)/libexml \ - --objectsDir $(BLD_OBJ_DIR) --objectList files --libs mpr - -cleanExtra: - @echo "rm -f $(TARGETS)" | $(BLDOUT) - @rm -f $(TARGETS) - @rm -f $(BLD_BIN_DIR)/libexml.* - -## Local variables: -## tab-width: 4 -## End: -## vim: tw=78 sw=4 ts=4 diff --git a/source4/lib/appweb/ejs-2.0/exml/exml.h b/source4/lib/appweb/ejs-2.0/exml/exml.h deleted file mode 100644 index 44c50a56b9..0000000000 --- a/source4/lib/appweb/ejs-2.0/exml/exml.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * exml.h -- Embedded Xml Parser header - * - * Copyright (c) Mbedthis Software, LLC, 2003-2003. All Rights Reserved. -- MOB - */ - -#ifndef _h_EXML -#define _h_EXML 1 - -/******************************** Description *********************************/ - -#include "mpr.h" - -/********************************** Defines ***********************************/ - -#if BLD_FEATURE_SQUEEZE - #define EXML_BUFSIZE 512 /* Read buffer size */ -#else - #define EXML_BUFSIZE 1024 /* Read buffer size */ -#endif - -/* - * XML parser states. The states that are passed to the user handler have - * "U" appended to the comment. The error states (ERR and EOF) must be - * negative. - */ -#define EXML_ERR -1 /* Error */ -#define EXML_EOF -2 /* End of input */ -#define EXML_BEGIN 1 /* Before next tag */ -#define EXML_AFTER_LS 2 /* Seen "<" */ -#define EXML_COMMENT 3 /* Seen ""); - if (rc < 0) { - return TOKEN_TOO_BIG; - } else if (rc == 0) { - return TOKEN_ERR; - } - return TOKEN_COMMENT; - } - } - } - trimToken(xp); - return TOKEN_TEXT; - } - if ((c = getNextChar(xp)) < 0) { - return TOKEN_EOF; - } - } - - /* Should never get here */ - mprAssert(0); - return TOKEN_ERR; -} - -/******************************************************************************/ -/* - * Scan for a pattern. Eat and discard input up to the pattern. Return 1 if - * the pattern was found, return 0 if not found. Return < 0 on errors. - */ - -static int scanFor(Exml *xp, char *str) -{ - MprBuf *tokBuf; - char *cp; - int c; - - mprAssert(str); - - tokBuf = xp->tokBuf; - - while (1) { - for (cp = str; *cp; cp++) { - if ((c = getNextChar(xp)) < 0) { - return 0; - } - if (tokBuf) { - if (mprPutCharToBuf(tokBuf, c) < 0) { - return -1; - } - } - if (c != *cp) { - break; - } - } - if (*cp == '\0') { - /* - * Remove the pattern from the tokBuf - */ - if (tokBuf) { - mprAdjustBufEnd(tokBuf, -(int) strlen(str)); - trimToken(xp); - } - return 1; - } - } -} - -/******************************************************************************/ -/* - * Get another character. We read and buffer blocks of data if we need more - * data to parse. - */ - -static int getNextChar(Exml *xp) -{ - MprBuf *inBuf; - char c; - int l; - - inBuf = xp->inBuf; - if (mprGetBufLength(inBuf) <= 0) { - /* - * Flush to reset the servp/endp pointers to the start of the buffer - * so we can do a maximal read - */ - mprFlushBuf(inBuf); - l = (xp->readFn)(xp, xp->inputArg, mprGetBufStart(inBuf), - mprGetBufLinearSpace(inBuf)); - if (l <= 0) { - return -1; - } - mprAdjustBufEnd(inBuf, l); - } - c = mprGetCharFromBuf(inBuf); - - if (c == '\n') { - xp->lineNumber++; - } - return c; -} - -/******************************************************************************/ -/* - * Put back a character in the input buffer - */ - -static int putLastChar(Exml *xp, int c) -{ - if (mprInsertCharToBuf(xp->inBuf, (char) c) < 0) { - mprAssert(0); - return -1; - } - if (c == '\n') { - xp->lineNumber--; - } - return 0; -} - -/******************************************************************************/ -/* - * Output a parse message - */ - -static void error(Exml *xp, char *fmt, ...) -{ - va_list args; - char *buf; - - mprAssert(fmt); - - va_start(args, fmt); - mprAllocVsprintf(MPR_LOC_ARGS(xp), &buf, MPR_MAX_STRING, fmt, args); - va_end(args); - - /* - * MOB need to add the failing line text and a pointer to which column - */ - mprFree(xp->errMsg); - mprAllocSprintf(MPR_LOC_ARGS(xp), &xp->errMsg, MPR_MAX_STRING, - "XML error: %s\nAt line %d\n", buf, xp->lineNumber); - - mprFree(buf); -} - -/******************************************************************************/ -/* - * Remove trailing whitespace in a token and ensure it is terminated with - * a NULL for easy parsing - */ - -static void trimToken(Exml *xp) -{ - while (isspace(mprLookAtLastCharInBuf(xp->tokBuf))) { - mprAdjustBufEnd(xp->tokBuf, -1); - } - mprAddNullToBuf(xp->tokBuf); -} - -/******************************************************************************/ - -const char *exmlGetErrorMsg(Exml *xp) -{ - if (xp->errMsg == 0) { - return ""; - } - return xp->errMsg; -} - -/******************************************************************************/ - -int exmlGetLineNumber(Exml *xp) -{ - return xp->lineNumber; -} - -/******************************************************************************/ -#else - -void exmlParserDummy() {} -#endif /* BLD_FEATURE_EXML */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/exml/files b/source4/lib/appweb/ejs-2.0/exml/files deleted file mode 100644 index 0f10ea44dd..0000000000 --- a/source4/lib/appweb/ejs-2.0/exml/files +++ /dev/null @@ -1 +0,0 @@ -${BLD_OBJ_DIR}/exmlParser${BLD_OBJ} diff --git a/source4/lib/appweb/ejs-2.0/mpr/Makefile b/source4/lib/appweb/ejs-2.0/mpr/Makefile deleted file mode 100644 index 6dd0e45d9e..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/Makefile +++ /dev/null @@ -1,41 +0,0 @@ -# -# Makefile for the Mbedthis Portable Runtime (MPR) library -# -# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. -# - -COMPILE := *.c -EXPORT_OBJECTS := yes - -include make.dep - -ifeq ($(BLD_HOST_UNIX),1) -PRE_DIRS = UNIX -else -PRE_DIRS = $(BLD_HOST_OS) -endif - -POST_DIRS = package - -TARGETS += $(BLD_BIN_DIR)/libmpr$(BLD_LIB) - -compileExtra: $(TARGETS) - -# -# Build the mpr libraries -# -$(BLD_BIN_DIR)/libmpr$(BLD_LIB): files \ - $(shell BLD_OBJ=$(BLD_OBJ) \; BLD_OBJ_DIR=$(BLD_OBJ_DIR) \; \ - eval echo `cat files`) - @bld --library $(BLD_BIN_DIR)/libmpr \ - --objectsDir $(BLD_OBJ_DIR) --objectList files - -cleanExtra: - @echo "rm -f $(TARGETS)" | $(BLDOUT) - @rm -f $(TARGETS) - @rm -f $(BLD_BIN_DIR)/libmpr.* - -## Local variables: -## tab-width: 4 -## End: -## vim: tw=78 sw=4 ts=4 diff --git a/source4/lib/appweb/ejs-2.0/mpr/UNIX/Makefile b/source4/lib/appweb/ejs-2.0/mpr/UNIX/Makefile deleted file mode 100644 index 5259b1e3a0..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/UNIX/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -# -# Makefile for the Mbedthis Portable Runtime (MPR) library for UNIX -# -# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. -# - -COMPILE := *.c -EXPORT_OBJECTS := yes -MAKE_IFLAGS := -I.. - -include make.dep - -## Local variables: -## tab-width: 4 -## End: -## vim: tw=78 sw=4 ts=4 diff --git a/source4/lib/appweb/ejs-2.0/mpr/UNIX/mprFile.c b/source4/lib/appweb/ejs-2.0/mpr/UNIX/mprFile.c deleted file mode 100644 index f647f1ed56..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/UNIX/mprFile.c +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @file mprFile.c - * @brief File services for Unix - * @overview - * @remarks - * See mprGenFile.c for other file services. - */ - -/******************************************************************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************** Includes **********************************/ - -#include "mpr.h" - -/************************************ Code ************************************/ - -int mprGetFileInfo(MprCtx ctx, const char *path, MprFileInfo *info) -{ - struct stat s; - - mprAssert(path); - mprAssert(info); - - if (stat(path, &s) < 0) { - return -1; - } - - info->size = s.st_size; - info->ctime = s.st_ctime; - info->mtime = s.st_mtime; - info->inode = s.st_ino; - info->isDir = (s.st_mode & S_IFDIR) != 0; - info->isReg = (s.st_mode & S_IFREG) != 0; - - if (strcmp(path, "/dev/null") == 0) { - info->isReg = 0; - } - - return 0; -} - -/******************************************************************************/ - -int mprMakeDir(MprCtx ctx, const char *path, int perms) -{ - return mkdir(path, perms); -} - -/******************************************************************************/ -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/UNIX/mprPlatform.c b/source4/lib/appweb/ejs-2.0/mpr/UNIX/mprPlatform.c deleted file mode 100644 index 2c7fbf8a00..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/UNIX/mprPlatform.c +++ /dev/null @@ -1,218 +0,0 @@ -/** - * @file mprPlatform.c - * @brief Cross platform routines - * @overview This module provides low level cross platform routines. - * @remarks Most routines in this file are not thread-safe. It is the callers - * responsibility to perform all thread synchronization. - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************** Includes **********************************/ -/* - * We need to use the underlying str(cpy) routines to implement our safe - * alternatives - */ -#if !DOXYGEN -#define UNSAFE_FUNCTIONS_OK 1 -#endif - -#include "mpr.h" - -/************************************ Code ************************************/ - -char *mprInetToStr(char *buffer, int bufsize, const struct in_addr in) -{ -#if HAVE_NTOA_R - inet_ntoa_r(in, buffer, bufsize); -#else - uchar *cp; - /* FUTURE -- this is not portable */ - cp = (uchar*) ∈ - mprSprintf(buffer, bufsize, "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]); -#endif - return buffer; -} - -/******************************************************************************/ - -void mprSetShell(MprCtx ctx, void *shell) -{ -} - -/******************************************************************************/ - -void *mprGetShell(MprCtx ctx) -{ - return 0; -} - -/******************************************************************************/ -/* - * Sleep. Period given in milliseconds. - */ - -void mprSleep(MprCtx ctx, int milliseconds) -{ - struct timespec timeout; - int rc; - - mprAssert(milliseconds >= 0); - timeout.tv_sec = milliseconds / 1000; - timeout.tv_nsec = (milliseconds % 1000) * 1000000; - do { - rc = nanosleep(&timeout, 0); - } while (rc < 0 && errno == EINTR); -} - -/******************************************************************************/ -/* - * Make intervening directories - */ - -int mprMakeDirPath(MprCtx ctx, const char *path) -{ - char dir[MPR_MAX_PATH], buf[MPR_MAX_PATH]; - char *dirSep; - char *next, *tok; - - dir[0] = '\0'; - dirSep = "/\\"; - - if (path == 0 || *path == '\0') { - return MPR_ERR_BAD_ARGS; - } - - mprStrcpy(buf, sizeof(buf), path); - next = mprStrTok(buf, dirSep, &tok); - if (*buf == '/') { - dir[0] = '/'; - } - while (next != NULL) { - if (strcmp(next, ".") == 0 ) { - next = mprStrTok(NULL, dirSep, &tok); - continue; - } - strcat(dir, next); - if (access(dir, R_OK) != 0) { - if (mkdir(dir, 0666) < 0) { - return MPR_ERR_CANT_CREATE; - } - } - strcat(dir, "/"); - next = mprStrTok(NULL, dirSep, &tok); - } - return 0; -} - -/******************************************************************************/ -/* - * Get a fully qualified file name for the given path. Return with forward - * slashes always - */ - -char *mprGetFullPathName(char *buf, int buflen, const char *path) -{ - if (mprStrcpy(buf, buflen, path) < 0) { - mprAssert(0); - return 0; - } - return buf; -} - -/******************************************************************************/ -/* - * Replacement for gethostbyname that is multi-thread safe - */ - -struct hostent *mprGetHostByName(MprCtx ctx, const char *name) -{ - MprApp *app; - struct hostent *hp; - struct hostent *ip; - int count, i; - - hp = (struct hostent*) mprAlloc(ctx, sizeof(struct hostent)); - memset(hp, 0, sizeof(struct hostent)); - - app = mprGetApp(ctx); - - #undef gethostbyname - - mprGlobalLock(app); - ip = gethostbyname(name); - mprGlobalUnlock(app); - - if (ip == 0) { - return 0; - } - hp->h_addrtype = ip->h_addrtype; - hp->h_length = ip->h_length; - hp->h_name = mprStrdup(hp, ip->h_name); - hp->h_addr_list = 0; - hp->h_aliases = 0; - - for (count = 0; ip->h_addr_list[count] != 0; ) { - count++; - } - if (count > 0) { - count++; - hp->h_addr_list = mprAlloc(hp, count * sizeof(char*)); - for (i = 0; ip->h_addr_list[i] != 0; i++) { - memcpy(&hp->h_addr_list[i], &ip->h_addr_list[i], ip->h_length); - } - hp->h_addr_list[i] = 0; - } - - for (count = 0; ip->h_aliases[count] != 0; ) { - count++; - } - if (count > 0) { - count++; - hp->h_aliases = mprAlloc(hp, count * sizeof(char*)); - for (i = 0; ip->h_aliases[i] != 0; i++) { - hp->h_aliases[i] = mprStrdup(hp, ip->h_aliases[i]); - } - hp->h_aliases[i] = 0; - } - return hp; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/UNIX/mprTime.c b/source4/lib/appweb/ejs-2.0/mpr/UNIX/mprTime.c deleted file mode 100644 index 0153c0622d..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/UNIX/mprTime.c +++ /dev/null @@ -1,163 +0,0 @@ -/** - * @file mprTime.c - * @brief Time handling for Unix - * @overview - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************* Includes ***********************************/ - -#include "mpr.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#undef localtime -#undef localtime_r -#undef gmtime -#undef gmtime_r -#undef ctime -#undef ctime_r -#undef asctime -#undef asctime_r - -/******************************************************************************/ -/* - * Returns time in seconds and milliseconds. This is NOT time-of-day. - */ - -MprTime *mprGetTime(MprCtx ctx, MprTime *tp) -{ - struct timeval tv; - - if (gettimeofday(&tv, 0) < 0) { - mprAssert(0); - tp->sec = 0; - tp->msec = 0; - return tp; - } - tp->sec = tv.tv_sec; - tp->msec = tv.tv_usec / 1000; - return tp; -} - -/******************************************************************************/ -/* - * Thread-safe wrapping of localtime - */ - -struct tm *mprLocaltime(MprCtx ctx, struct tm *timep, time_t *now) -{ - localtime_r(now, timep); - - return timep; -} - -/******************************************************************************/ -/* - * Thread-safe wrapping of gmtime - */ - -struct tm *mprGmtime(MprCtx ctx, time_t *now, struct tm *timep) -{ - gmtime_r(now, timep); - - return timep; -} - -/******************************************************************************/ -/* - * Thread-safe wrapping of ctime - */ - -int mprCtime(MprCtx ctx, char *buf, int bufsize, const time_t *timer) -{ - char localBuf[80]; - char *cp; - int len; - - mprAssert(buf); - - mprGlobalLock(ctx); - - cp = ctime_r(timer, localBuf); - if ((int) strlen(cp) >= bufsize) { - mprStrcpy(buf, bufsize, "WONT FIT"); - mprAssert(0); - return MPR_ERR_WONT_FIT; - } - len = mprStrcpy(buf, bufsize, cp); - - if (buf[len - 1] == '\n') { - buf[len - 1] = '\0'; - } - - mprGlobalUnlock(ctx); - - return 0; -} - -/******************************************************************************/ -/* - * Thread-safe wrapping of asctime - */ - -int mprAsctime(MprCtx ctx, char *buf, int bufsize, const struct tm *timeptr) -{ - char *cp; - char localBuf[80]; - - cp = asctime_r(timeptr, localBuf); - if ((int) strlen(cp) >= bufsize) { - mprAssert(0); - return MPR_ERR_WONT_FIT; - } - mprStrcpy(buf, bufsize, cp); - - return strlen(buf); -} - -/******************************************************************************/ - -#ifdef __cplusplus -} -#endif - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/VXWORKS/Makefile b/source4/lib/appweb/ejs-2.0/mpr/VXWORKS/Makefile deleted file mode 100644 index f3a2394b6e..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/VXWORKS/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -# -# Makefile for the Mbedthis Portable Runtime (MPR) library for VXWORKS -# -# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. -# - -COMPILE := *.c -EXPORT_OBJECTS := yes -MAKE_IFLAGS := -I.. - -include make.dep - -## Local variables: -## tab-width: 4 -## End: -## vim: tw=78 sw=4 ts=4 diff --git a/source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprFile.c b/source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprFile.c deleted file mode 100644 index ae0b523faa..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprFile.c +++ /dev/null @@ -1,85 +0,0 @@ -/** - * @file mprUnixFile.c - * @brief File services for Unix - * @overview - * @remarks - */ - -/******************************************************************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************** Includes **********************************/ - -#include "mpr.h" - -/************************************ Code ************************************/ - -int mprGetFileInfo(MprCtx ctx, const char *path, MprFileInfo *info) -{ - struct stat s; - - mprAssert(path); - mprAssert(info); - - if (stat(path, &s) < 0) { - return -1; - } - - info->size = s.st_size; - info->ctime = s.st_ctime; - info->mtime = s.st_mtime; - info->inode = s.st_ino; - info->isDir = (s.st_mode & S_IFDIR) != 0; - info->isReg = (s.st_mode & S_IFREG) != 0; - - if (strcmp(path, "/dev/null") == 0) { - info->isReg = 0; - } - - return 0; -} - -/******************************************************************************/ - -int mprMakeDir(MprCtx ctx, const char *path, int perms) -{ - return mkdir(path, perms); -} - -/******************************************************************************/ -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprPlatform.c b/source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprPlatform.c deleted file mode 100644 index 29258dfe1c..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprPlatform.c +++ /dev/null @@ -1,191 +0,0 @@ -/** - * @file mprPlatform.c - * @brief Cross platform routines - * @overview This module provides low level cross platform routines. - * @remarks Most routines in this file are not thread-safe. It is the callers - * responsibility to perform all thread synchronization. - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************** Includes **********************************/ -/* - * We need to use the underlying str(cpy) routines to implement our safe - * alternatives - */ -#if !DOXYGEN -#define UNSAFE_FUNCTIONS_OK 1 -#endif - -#include "mpr.h" - -/************************************ Code ************************************/ - -char *mprInetToStr(char *buffer, int bufsize, const struct in_addr in) -{ -#if HAVE_NTOA_R - inet_ntoa_r(in, buffer, bufsize); -#else - uchar *cp; - /* FUTURE -- this is not portable */ - cp = (uchar*) ∈ - mprSprintf(buffer, bufsize, "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]); -#endif - return buffer; -} - -/******************************************************************************/ - -void mprSetShell(MprCtx ctx, void *shell) -{ -} - -/******************************************************************************/ - -void *mprGetShell(MprCtx ctx) -{ - return 0; -} - -/******************************************************************************/ -/* - * Sleep. Period given in milliseconds. - */ - -void mprSleep(MprCtx ctx, int milliseconds) -{ - struct timeval timeout; - int rc; - - timeout.tv_sec = milliseconds / 1000; - timeout.tv_usec = (milliseconds % 1000) * 1000; - do { - rc = select(1, 0, 0, 0, &timeout); - } while (rc < 0 && errno == EINTR); -} - -/******************************************************************************/ -/* - * Make intervening directories - */ - -int mprMakeDirPath(MprCtx ctx, const char *path) -{ - char dir[MPR_MAX_PATH], buf[MPR_MAX_PATH]; - char *dirSep; - char *next, *tok; - - dir[0] = '\0'; - dirSep = "/\\"; - - if (path == 0 || *path == '\0') { - return MPR_ERR_BAD_ARGS; - } - - mprStrcpy(buf, sizeof(buf), path); - next = mprStrTok(buf, dirSep, &tok); - if (*buf == '/') { - dir[0] = '/'; - } - while (next != NULL) { - if (strcmp(next, ".") == 0 ) { - next = mprStrTok(NULL, dirSep, &tok); - continue; - } - strcat(dir, next); - if (access(dir, R_OK) != 0) { - if (mkdir(dir) < 0) { - return MPR_ERR_CANT_CREATE; - } - } - strcat(dir, "/"); - next = mprStrTok(NULL, dirSep, &tok); - } - return 0; -} - -/******************************************************************************/ -/* - * Get a fully qualified file name for the given path. Return with forward - * slashes always - */ - -char *mprGetFullPathName(char *buf, int buflen, const char *path) -{ - if (mprStrcpy(buf, buflen, path) < 0) { - mprAssert(0); - return 0; - } - return buf; -} - -/******************************************************************************/ -/* - * Replacement for gethostbyname that is multi-thread safe - */ - -struct hostent *mprGetHostByName(MprCtx ctx, const char *name) -{ - struct hostent *hp; - - hp = (struct hostent*) mprAlloc(ctx, sizeof(struct hostent)); - memset(hp, 0, sizeof(struct hostent)); - - struct in_addr inaddr; - inaddr.s_addr = (ulong) hostGetByName(name); - if (inaddr.s_addr < 0) { - mprAssert(0); - return 0; - } - hp->h_addrtype = AF_INET; - hp->h_length = sizeof(int); - hp->h_name = mprStrdup(name); - hp->h_addr_list = 0; - hp->h_aliases = 0; - - hp->h_addr_list = new char*[2]; - hp->h_addr_list[0] = (char *) mprAlloc(hp, sizeof(struct in_addr)); - memcpy(&hp->h_addr_list[0], &inaddr, hp->h_length); - hp->h_addr_list[1] = 0; - - return hp; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprTime.c b/source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprTime.c deleted file mode 100755 index c9b7560f46..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/VXWORKS/mprTime.c +++ /dev/null @@ -1,163 +0,0 @@ -/** - * @file mprTime.c - * @brief Time handling for VxWorks - * @overview - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************* Includes ***********************************/ - -#include "mpr.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#undef localtime -#undef localtime_r -#undef gmtime -#undef gmtime_r -#undef ctime -#undef ctime_r -#undef asctime -#undef asctime_r - -/******************************************************************************/ -/* - * Returns time in seconds and milliseconds. This is NOT time-of-day. - */ - -MprTime *mprGetTime(MprCtx ctx, MprTime *tp) -{ - struct timeval tv; - - if (gettimeofday(&tv, 0) < 0) { - mprAssert(0); - tp->sec = 0; - tp->msec = 0; - return tp; - } - tp->sec = tv.tv_sec; - tp->msec = tv.tv_usec / 1000; - return tp; -} - -/******************************************************************************/ -/* - * Thread-safe wrapping of localtime - */ - -struct tm *mprLocaltime(MprCtx ctx, struct tm *timep, time_t *now) -{ - localtime_r(now, timep); - - return timep; -} - -/******************************************************************************/ -/* - * Thread-safe wrapping of gmtime - */ - -struct tm *mprGmtime(MprCtx ctx, time_t *now, struct tm *timep) -{ - gmtime_r(now, timep); - - return timep; -} - -/******************************************************************************/ -/* - * Thread-safe wrapping of ctime - */ - -int mprCtime(MprCtx ctx, char *buf, int bufsize, const time_t *timer) -{ - char localBuf[80]; - char *cp; - int len; - - mprAssert(buf); - - mprGlobalLock(ctx); - - cp = ctime_r(timer, localBuf); - if ((int) strlen(cp) >= bufsize) { - mprStrcpy(buf, bufsize, "WONT FIT"); - mprAssert(0); - return MPR_ERR_WONT_FIT; - } - len = mprStrcpy(buf, bufsize, cp); - - if (buf[len - 1] == '\n') { - buf[len - 1] = '\0'; - } - - mprGlobalUnlock(ctx); - - return 0; -} - -/******************************************************************************/ -/* - * Thread-safe wrapping of asctime - */ - -int mprAsctime(MprCtx ctx, char *buf, int bufsize, const struct tm *timeptr) -{ - char *cp; - char localBuf[80]; - - cp = asctime_r(timeptr, localBuf); - if ((int) strlen(cp) >= bufsize) { - mprAssert(0); - return MPR_ERR_WONT_FIT; - } - mprStrcpy(buf, bufsize, cp); - - return strlen(buf); -} - -/******************************************************************************/ - -#ifdef __cplusplus -} -#endif - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/WIN/Makefile b/source4/lib/appweb/ejs-2.0/mpr/WIN/Makefile deleted file mode 100644 index 84e30ff8f1..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/WIN/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -# -# Makefile for the Mbedthis Portable Runtime (MPR) library for Windows -# -# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. -# - -COMPILE := *.c -EXPORT_OBJECTS := yes -MAKE_IFLAGS := -I.. - -include make.dep - -## Local variables: -## tab-width: 4 -## End: -## vim: tw=78 sw=4 ts=4 diff --git a/source4/lib/appweb/ejs-2.0/mpr/WIN/mprFile.c b/source4/lib/appweb/ejs-2.0/mpr/WIN/mprFile.c deleted file mode 100644 index 9ac1669f3d..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/WIN/mprFile.c +++ /dev/null @@ -1,123 +0,0 @@ -/** - * @file mprWinFile.c - * @brief File services for Windows - * @overview - * @remarks - */ - -/******************************************************************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************** Includes **********************************/ - -#include "mpr.h" - -/************************************ Code ************************************/ - -int mprGetFileInfo(MprCtx ctx, const char *path, MprFileInfo *info) -{ - struct stat s; - - mprAssert(path); - mprAssert(info); - - if (stat(path, &s) < 0) { - return -1; - } - - info->size = s.st_size; - /* - * MOB -- these are time64_t. Loss of precision - */ - info->ctime = (uint) s.st_ctime; - info->mtime = (uint) s.st_mtime; - info->inode = s.st_ino; - info->isDir = (s.st_mode & S_IFDIR) != 0; - info->isReg = (s.st_mode & S_IFREG) != 0; - - /* - * Work hard on windows to determine if the file is a regular file. - * FUTURE -- OPT. Eliminate this CreateFile. - */ - if (info->isReg) { - long fileType, att; - - if ((att = GetFileAttributes(path)) == -1) { - return -1; - } - if (att & (FILE_ATTRIBUTE_REPARSE_POINT | - FILE_ATTRIBUTE_DIRECTORY | - FILE_ATTRIBUTE_ENCRYPTED | - FILE_ATTRIBUTE_SYSTEM | - FILE_ATTRIBUTE_OFFLINE)) { - /* - * Catch accesses to devices like CON, AUX, NUL, LPT etc - * att will be set to ENCRYPTED on Win9X and NT. - */ - info->isReg = 0; - } - if (info->isReg) { - HANDLE handle; - handle = CreateFile(path, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, - 0, OPEN_EXISTING, 0, 0); - if (handle == INVALID_HANDLE_VALUE) { - info->isReg = 0; - } else { - fileType = GetFileType(handle); - if (fileType == FILE_TYPE_CHAR || fileType == FILE_TYPE_PIPE) { - info->isReg = 0; - } - CloseHandle(handle); - } - } - } - if (strcmp(path, "nul") == 0) { - info->isReg = 0; - } - return 0; -} - -/******************************************************************************/ - -int mprMakeDir(MprCtx ctx, const char *path, int perms) -{ - return mkdir(path, perms); -} - -/******************************************************************************/ -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/WIN/mprPlatform.c b/source4/lib/appweb/ejs-2.0/mpr/WIN/mprPlatform.c deleted file mode 100644 index 65718694b1..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/WIN/mprPlatform.c +++ /dev/null @@ -1,378 +0,0 @@ -/** - * @file mprPlatform.c - * @brief Cross platform routines - * @overview This module provides low level cross platform routines. - * @remarks Most routines in this file are not thread-safe. It is the callers - * responsibility to perform all thread synchronization. - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************** Includes **********************************/ -/* - * We need to use the underlying str(cpy) routines to implement our safe - * alternatives - */ -#if !DOXYGEN -#define UNSAFE_FUNCTIONS_OK 1 -#endif - -#include "mpr.h" - -/**************************** Forward Declarations ****************************/ - -static const char *getHive(const char *keyPath, HKEY *hive); - -/************************************ Code ************************************/ - -char *mprInetToStr(char *buffer, int bufsize, const struct in_addr in) -{ -#if HAVE_NTOA_R - inet_ntoa_r(in, buffer, bufsize); -#else - uchar *cp; - cp = (uchar*) ∈ - mprSprintf(buffer, bufsize, "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]); -#endif - return buffer; -} - -/******************************************************************************/ - -void mprSetShell(MprCtx ctx, void *shell) -{ -} - -/******************************************************************************/ - -void *mprGetShell(MprCtx ctx) -{ - return 0; -} - -/******************************************************************************/ -/* - * Sleep. Period given in milliseconds. - */ - -void mprSleep(MprCtx ctx, int milliseconds) -{ - Sleep(milliseconds); -} - -/******************************************************************************/ -/* - * Make intervening directories - */ - -int mprMakeDirPath(MprCtx ctx, const char *path) -{ - char dir[MPR_MAX_PATH], buf[MPR_MAX_PATH]; - char *dirSep; - char *next, *tok; - - dir[0] = '\0'; - dirSep = "/\\"; - - if (path == 0 || *path == '\0') { - return MPR_ERR_BAD_ARGS; - } - - mprStrcpy(buf, sizeof(buf), path); - next = mprStrTok(buf, dirSep, &tok); - if (*buf == '/') { - dir[0] = '/'; - } - while (next != NULL) { - if (strcmp(next, ".") == 0 ) { - next = mprStrTok(NULL, dirSep, &tok); - continue; - } - strcat(dir, next); - if (access(dir, R_OK) != 0) { - if (_mkdir(dir) < 0) { - return MPR_ERR_CANT_CREATE; - } - } - strcat(dir, "/"); - next = mprStrTok(NULL, dirSep, &tok); - } - return 0; -} - -/******************************************************************************/ -/* - * Get a fully qualified file name for the given path. Return with forward - * slashes always - */ - -char *mprGetFullPathName(char *buf, int buflen, const char *path) -{ -#if (WIN || NW || OS2) && !BLD_FEATURE_ROMFS - char *junk, *cp; - int rc; - - --buflen; - rc = GetFullPathName(path, buflen, buf, &junk); - for (cp = buf; *cp; cp++) { - if (*cp == '\\') { - *cp = '/'; - } - } - buf[buflen] = '\0'; -#else - if (mprStrcpy(buf, buflen, path) < 0) { - mprAssert(0); - return 0; - } -#endif - return buf; -} - -/******************************************************************************/ -/* - * Replacement for gethostbyname that is multi-thread safe - */ - -struct hostent *mprGetHostByName(MprCtx ctx, const char *name) -{ - MprApp *app; - struct hostent *hp; - struct hostent *ip; - int count, i; - - hp = (struct hostent*) mprAlloc(ctx, sizeof(struct hostent)); - memset(hp, 0, sizeof(struct hostent)); - - app = mprGetApp(ctx); - - #undef gethostbyname - - mprGlobalLock(app); - ip = gethostbyname(name); - mprGlobalUnlock(app); - - if (ip == 0) { - return 0; - } - hp->h_addrtype = ip->h_addrtype; - hp->h_length = ip->h_length; - hp->h_name = mprStrdup(hp, ip->h_name); - hp->h_addr_list = 0; - hp->h_aliases = 0; - - for (count = 0; ip->h_addr_list[count] != 0; ) { - count++; - } - if (count > 0) { - count++; - hp->h_addr_list = mprAlloc(hp, count * sizeof(char*)); - for (i = 0; ip->h_addr_list[i] != 0; i++) { - memcpy(&hp->h_addr_list[i], &ip->h_addr_list[i], ip->h_length); - } - hp->h_addr_list[i] = 0; - } - - for (count = 0; ip->h_aliases[count] != 0; ) { - count++; - } - if (count > 0) { - count++; - hp->h_aliases = mprAlloc(hp, count * sizeof(char*)); - for (i = 0; ip->h_aliases[i] != 0; i++) { - hp->h_aliases[i] = mprStrdup(hp, ip->h_aliases[i]); - } - hp->h_aliases[i] = 0; - } - return hp; -} - -/******************************************************************************/ -/* - * Read a registry value. Returns allocated memory in buf. - */ - -int mprReadRegistry(MprCtx ctx, char **buf, int max, const char *key, - const char *name) -{ - HKEY top, h; - char *value; - ulong type, size; - - mprAssert(key && *key); - mprAssert(buf); - - /* - * Get the registry hive - */ - if ((key = getHive(key, &top)) == 0) { - return MPR_ERR_CANT_ACCESS; - } - - if (RegOpenKeyEx(top, key, 0, KEY_READ, &h) != ERROR_SUCCESS) { - return MPR_ERR_CANT_ACCESS; - } - - /* - * Get the type - */ - if (RegQueryValueEx(h, name, 0, &type, 0, &size) != ERROR_SUCCESS) { - RegCloseKey(h); - return MPR_ERR_CANT_READ; - } - if (type != REG_SZ && type != REG_EXPAND_SZ) { - RegCloseKey(h); - return MPR_ERR_BAD_TYPE; - } - - value = (char*) mprAlloc(ctx, size); - if ((int) size > max) { - RegCloseKey(h); - return MPR_ERR_WONT_FIT; - } - if (RegQueryValueEx(h, name, 0, &type, (uchar*) value, &size) != - ERROR_SUCCESS) { - mprFree(value); - RegCloseKey(h); - return MPR_ERR_CANT_READ; - } - - RegCloseKey(h); - *buf = value; - return 0; -} - -/******************************************************************************/ -/* - * Write a string registry value. Returns allocated memory in buf. - */ - -int mprWriteRegistry(MprCtx ctx, const char *key, const char *name, - const char *value) -{ - HKEY top, h, subHandle; - ulong disposition; - - mprAssert(key && *key); - mprAssert(name && *name); - mprAssert(value && *value); - - /* - * Get the registry hive - */ - if ((key = getHive(key, &top)) == 0) { - return MPR_ERR_CANT_ACCESS; - } - - if (name) { - /* - * Write a registry string value - */ - if (RegOpenKeyEx(top, key, 0, KEY_ALL_ACCESS, &h) != ERROR_SUCCESS) { - return MPR_ERR_CANT_ACCESS; - } - if (RegSetValueEx(h, name, 0, REG_SZ, value, strlen(value) + 1) - != ERROR_SUCCESS) { - RegCloseKey(h); - return MPR_ERR_CANT_READ; - } - - } else { - /* - * Create a new sub key - */ - if (RegOpenKeyEx(top, key, 0, KEY_CREATE_SUB_KEY, &h) != ERROR_SUCCESS){ - return MPR_ERR_CANT_ACCESS; - } - if (RegCreateKeyEx(h, name, 0, NULL, REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, NULL, &subHandle, &disposition) != ERROR_SUCCESS) { - return MPR_ERR_CANT_ACCESS; - } - RegCloseKey(subHandle); - } - RegCloseKey(h); - return 0; -} - -/******************************************************************************/ -/* - * Determine the registry hive by the first portion of the path. Return - * a pointer to the rest of key path after the hive portion. - */ - -static const char *getHive(const char *keyPath, HKEY *hive) -{ - char key[MPR_MAX_STRING], *cp; - int len; - - mprAssert(keyPath && *keyPath); - - *hive = 0; - - mprStrcpy(key, sizeof(key), keyPath); - key[sizeof(key) - 1] = '\0'; - - if (cp = strchr(key, '\\')) { - *cp++ = '\0'; - } - if (cp == 0 || *cp == '\0') { - return 0; - } - - if (!mprStrcmpAnyCase(key, "HKEY_LOCAL_MACHINE")) { - *hive = HKEY_LOCAL_MACHINE; - } else if (!mprStrcmpAnyCase(key, "HKEY_CURRENT_USER")) { - *hive = HKEY_CURRENT_USER; - } else if (!mprStrcmpAnyCase(key, "HKEY_USERS")) { - *hive = HKEY_USERS; - } else if (!mprStrcmpAnyCase(key, "HKEY_CLASSES_ROOT")) { - *hive = HKEY_CLASSES_ROOT; - } else { - return 0; - } - - if (*hive == 0) { - return 0; - } - len = strlen(key) + 1; - return keyPath + len; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/WIN/mprTime.c b/source4/lib/appweb/ejs-2.0/mpr/WIN/mprTime.c deleted file mode 100644 index 74e59c9c73..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/WIN/mprTime.c +++ /dev/null @@ -1,192 +0,0 @@ -/** - * @file mprTime.c - * @brief Time handling for Windows - * @overview - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************* Includes ***********************************/ - -#include "mpr.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/************************************ Code ************************************/ -/* - * Returns time in seconds and milliseconds. This is NOT time-of-day. - */ - -MprTime *mprGetTime(MprCtx ctx, MprTime *tp) -{ - FILETIME fileTime; - int64 now, base; - - GetSystemTimeAsFileTime(&fileTime); - - now = ((((int64) fileTime.dwHighDateTime) << BITS(uint)) + - ((int64) fileTime.dwLowDateTime)); - - /* - * Convert from 100-nanosec units to milliseconds - */ - now = (now / 10000); - - /* - * Adjust to be seconds since Jan 1 1970. Do this to be consistent with - * UNIX but not really required by the API definition. - */ - base = ((UINT64(365) * 86400 * (1970 - 1601)) * 1000); - now -= base; - tp->sec = (uint) (now / 1000); - tp->msec = (uint) (now % 1000); - -#if UNUSED -{ - static int64 start; - - if (start == 0) { - start = now; - } - if (now < start) { - mprLog(ctx, 0, "TIME WENT BACKWARDS"); - mprLog(ctx, 0, "start %Ld", start); - mprLog(ctx, 0, "now %Ld", now); - } - mprLog(ctx, 0, "getTime %Ld", now); - start = now; -} -#endif - - return tp; -} - -/******************************************************************************/ -/* - * Thread-safe wrapping of localtime - */ - -struct tm *mprLocaltime(MprCtx ctx, struct tm *timep, time_t *now) -{ - struct tm *tbuf; - mprGlobalLock(ctx); - tbuf = localtime(now); - *timep = *tbuf; - mprGlobalUnlock(ctx); - - return timep; -} - -/******************************************************************************/ -/* - * Thread-safe wrapping of gmtime - */ - -struct tm *mprGmtime(MprCtx ctx, time_t *now, struct tm *timep) -{ - struct tm *tbuf; - tbuf = gmtime(now); - *timep = *tbuf; - - return timep; -} - -/******************************************************************************/ -/* - * Thread-safe wrapping of ctime - */ - -int mprCtime(MprCtx ctx, char *buf, int bufsize, const time_t *timer) -{ - char *cp; - int len; - - mprAssert(buf); - - mprGlobalLock(ctx); - - cp = ctime(timer); - if ((int) strlen(cp) >= bufsize) { - mprStrcpy(buf, bufsize, "WONT FIT"); - mprAssert(0); - mprGlobalUnlock(ctx); - return MPR_ERR_WONT_FIT; - } - - len = mprStrcpy(buf, bufsize, cp); - if (buf[len - 1] == '\n') { - buf[len - 1] = '\0'; - } - - mprGlobalUnlock(ctx); - - return 0; -} - -/******************************************************************************/ -/* - * Thread-safe wrapping of asctime - */ - -int mprAsctime(MprCtx ctx, char *buf, int bufsize, const struct tm *timeptr) -{ - char *cp; - - mprAssert(buf); - mprGlobalLock(ctx); - cp = asctime(timeptr); - if ((int) strlen(cp) >= bufsize) { - mprAssert(0); - mprGlobalUnlock(ctx); - return MPR_ERR_WONT_FIT; - } - mprStrcpy(buf, bufsize, cp); - mprGlobalUnlock(ctx); - - return strlen(buf); -} - -/******************************************************************************/ - -#ifdef __cplusplus -} -#endif - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/files b/source4/lib/appweb/ejs-2.0/mpr/files deleted file mode 100644 index 290c9ce790..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/files +++ /dev/null @@ -1,14 +0,0 @@ -${BLD_OBJ_DIR}/mpr${BLD_OBJ} -${BLD_OBJ_DIR}/mprAlloc${BLD_OBJ} -${BLD_OBJ_DIR}/mprArray${BLD_OBJ} -${BLD_OBJ_DIR}/mprBuf${BLD_OBJ} -${BLD_OBJ_DIR}/mprFile${BLD_OBJ} -${BLD_OBJ_DIR}/mprGenFile${BLD_OBJ} -${BLD_OBJ_DIR}/mprGenTime${BLD_OBJ} -${BLD_OBJ_DIR}/mprLock${BLD_OBJ} -${BLD_OBJ_DIR}/mprLog${BLD_OBJ} -${BLD_OBJ_DIR}/mprPlatform${BLD_OBJ} -${BLD_OBJ_DIR}/mprPrintf${BLD_OBJ} -${BLD_OBJ_DIR}/mprString${BLD_OBJ} -${BLD_OBJ_DIR}/mprSymbol${BLD_OBJ} -${BLD_OBJ_DIR}/mprTime${BLD_OBJ} diff --git a/source4/lib/appweb/ejs-2.0/mpr/mpr.c b/source4/lib/appweb/ejs-2.0/mpr/mpr.c deleted file mode 100644 index 163b51eccf..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mpr.c +++ /dev/null @@ -1,340 +0,0 @@ -/** - * @file mpr.c - * @brief Mpr initialization - * @overview - * @remarks Most routines in this file are not thread-safe. It is the callers - * responsibility to perform all thread synchronization. - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************** Includes **********************************/ -/* - * We need to use the underlying str(cpy) routines to implement our safe - * alternatives - */ -#if !DOXYGEN -#define UNSAFE_FUNCTIONS_OK 1 -#endif - -#include "mpr.h" - -/******************************************************************************/ -/* - * Initialize the MPR. Create the top level memory context. This routine is - * the first call an MPR application must do. If using MprServices, the - * creation of an Mpr object will call this routine. - */ - -MprApp *mprInit(MprAllocCback cback) -{ - return mprInitEx(cback, 0); -} - -/******************************************************************************/ -/* - * Add a shell parameter then do the regular init - */ - -MprApp *mprInitEx(MprAllocCback cback, void *shell) -{ - MprApp *app; - - app = (MprApp*) mprAllocInit(cback); - - mprAssert(app); - if (app == 0) { - return 0; - } - - app->name = mprStrdup(app, BLD_PRODUCT); - app->title = mprStrdup(app, BLD_NAME); - app->version = mprStrdup(app, BLD_VERSION); - - mprSetShell(app, shell); - - app->table = mprCreateSymbolTable(app, 0); - - if (mprStartFileServices(app) < 0) { - mprAllocTerm(app); - return 0; - } - -#if BLD_FEATURE_MULTITHREAD - mprInitThreads(app); -#endif - - /* - * See if any of the preceeding allocations failed - */ - if (mprGetAllocErrors(app) > 0) { - mprAllocTerm(app); - return 0; - } - - /* - * Mark all blocks allocated so far as required. They will then be - * omitted from leak reports. - */ - mprSetRequiredAlloc(app, 1); - - return app; -} - -/******************************************************************************/ -/* - * Terminate the MPR. If doStats is true, then output a memory allocation - * report. - */ - -void mprTerm(MprApp *app, bool doStats) -{ -#if BLD_FEATURE_ALLOC_STATS - if (doStats) { - mprPrintAllocReport(app, 1, "MPR Memory Allocation Report"); - } -#endif - -#if BLD_FEATURE_MULTITHREAD - mprTermThreads(app); -#endif - - mprStopFileServices(app); - -#if BLD_DEBUG - mprValidateAllocTree(app); -#endif - mprAllocTerm(app); -} - -/******************************************************************************/ - -bool mprIsExiting(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - if (app == 0) { - return 1; - } - return app->flags & MPR_APP_EXITING; -} - -/******************************************************************************/ - -int mprHasAllocError(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - if (app == 0) { - return 1; - } - - return app->flags & MPR_APP_ALLOC_ERROR; -} - -/******************************************************************************/ - -void mprSignalExit(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - app->flags |= MPR_APP_EXITING; -} - -/******************************************************************************/ - -void mprSignalAllocError(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - app->flags |= MPR_APP_ALLOC_ERROR; -} - -/******************************************************************************/ - -int mprSetAppName(MprCtx ctx, const char *name, const char *title, - const char *version) -{ - MprApp *app; - - app = mprGetApp(ctx); - - if (name) { - mprFree(app->name); - if ((app->name = mprStrdup(ctx, name)) == 0) { - return MPR_ERR_CANT_ALLOCATE; - } - } - - if (title) { - mprFree(app->title); - if ((app->title = mprStrdup(ctx, title)) == 0) { - return MPR_ERR_CANT_ALLOCATE; - } - } - - if (version) { - mprFree(app->version); - if ((app->version = mprStrdup(ctx, version)) == 0) { - return MPR_ERR_CANT_ALLOCATE; - } - } - return 0; -} - -/******************************************************************************/ - -const char *mprGetAppName(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - return app->name; -} - -/******************************************************************************/ - -const char *mprGetAppTitle(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - return app->title; -} - -/******************************************************************************/ - -const char *mprGetAppVersion(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - return app->version; -} - -/******************************************************************************/ - -int mprSetKeyValue(MprCtx ctx, const char *key, void *ptr) -{ - MprApp *app; - - app = mprGetApp(ctx); - if (mprInsertSymbol(app->table, key, ptr) == 0) { - return MPR_ERR_CANT_WRITE; - } - return 0; -} - -/******************************************************************************/ - -int mprRemoveKeyValue(MprCtx ctx, const char *key) -{ - MprApp *app; - - app = mprGetApp(ctx); - return mprRemoveSymbol(app->table, key); -} - -/******************************************************************************/ - -void *mprGetKeyValue(MprCtx ctx, const char *key) -{ - MprApp *app; - - app = mprGetApp(ctx); - return mprLookupSymbol(app->table, key); -} - -/******************************************************************************/ - -bool mprGetDebugMode(MprCtx ctx) -{ - return mprGetApp(ctx)->debugMode; -} - -/******************************************************************************/ - -void mprSetDebugMode(MprCtx ctx, bool on) -{ - mprGetApp(ctx)->debugMode = on; -} - -/******************************************************************************/ - -void mprSetLogHandler(MprCtx ctx, MprLogHandler handler) -{ - mprGetApp(ctx)->logHandler = handler; -} - -/******************************************************************************/ - -MprLogHandler mprGetLogHandler(MprCtx ctx) -{ - return mprGetApp(ctx)->logHandler; -} - -#if UNUSED -/******************************************************************************/ - -void mprSetMprInstance(MprCtx ctx, void *mprInstance) -{ - mprGetApp(ctx)->mprInstance = mprInstance; -} - -/******************************************************************************/ - -void *mprGetMprInstance(MprCtx ctx) -{ - return mprGetApp(ctx)->mprInstance; -} - -#endif -/******************************************************************************/ - -const char *mprCopyright() -{ - return "Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved."; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/mpr.h b/source4/lib/appweb/ejs-2.0/mpr/mpr.h deleted file mode 100644 index 67505a6e01..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mpr.h +++ /dev/null @@ -1,1027 +0,0 @@ -/* - * @file mpr.h - * @brief Header for the Mbedthis Portable Runtime (MPR) Base. - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/******************************* Documentation ********************************/ -/* - * See mpr.dox for additional documentation. - */ - -/******************************************************************************/ - -#ifndef _h_MPR -#define _h_MPR 1 - -/***********************************Includes **********************************/ - -#include "mprOs.h" - -/******************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - -/********************************** Constants *********************************/ - -#if BLD_FEATURE_SQUEEZE -#if BREW || DOXYGEN -/* - * Maximum length of a file path name. Reduced from the system maximum to - * save memory space. - */ -#define MPR_MAX_FNAME 64 /**< Reasonable filename size */ -#define MPR_MAX_PATH 64 /**< Reasonable path name size */ -#define MPR_DEFAULT_STACK (16 * 1024) /**< Default stack size */ -#else -#define MPR_MAX_FNAME 128 /**< Reasonable filename size */ -#define MPR_MAX_PATH 256 /**< Reasonable path name size */ -#define MPR_DEFAULT_STACK (32 * 1024) /**< Default stack size */ -#endif -/* - * Reasonable length of a file name used by the product. Use where you know - * the expected file name and it is certain to be less than this limit. - */ -#define MPR_DEFAULT_ALLOC 64 /**< Default small alloc size */ -#define MPR_DEFAULT_HASH_SIZE 23 /**< Default size of hash table */ -#define MPR_MAX_ARGC 32 /**< Reasonable max of args */ -#define MPR_MAX_STRING 512 /**< Maximum (stack) string size */ -#define MPR_MAX_LOG_STRING 512 /**< Maximum log message */ -#define MPR_MAX_URL 256 /**< Reasonable size of a URL */ -#define MPR_BUFSIZE 512 /**< Reasonable size for buffers */ -#define MPR_SLAB_STR_MAX 32 /**< Size of string slab blocks */ -#define MPR_SLAB_STR_INC 32 /**< Pre-allocate increment */ -#define MPR_SLAB_DEFAULT_INC 8 /**< Default pre-allocate inc */ -#define MPR_ARRAY_INCR 8 /**< Default array growth inc */ -#define MPR_BUF_INCR 1024 /**< Default array growth inc */ -#define MPR_MAX_BUF (1024*4096) /**< Default array growth inc */ - -#define MPR_BLK_HDR_SIZE ((sizeof(struct MprBlk) + 3) & ~3) - -#else -#define MPR_MAX_FNAME 256 -#define MPR_MAX_PATH 1024 -#define MPR_DEFAULT_ALLOC 256 -#define MPR_DEFAULT_HASH_SIZE 43 -#define MPR_DEFAULT_STACK (64 * 1024) -#define MPR_MAX_ARGC 128 -#define MPR_MAX_STRING 4096 -#define MPR_MAX_LOG_STRING 8192 -#define MPR_MAX_URL 1024 -#define MPR_BUFSIZE 1024 -#define MPR_SLAB_STR_MAX 32 -#define MPR_SLAB_STR_INC 64 -#define MPR_SLAB_DEFAULT_INC 16 -#define MPR_ARRAY_INCR 16 -#define MPR_BUF_INCR 1024 -#define MPR_MAX_BUF (1024*4096) - -#define MPR_BLK_HDR_SIZE ((sizeof(struct MprBlk) + 15) & ~15) -#endif - -/** - * Maximum size of a host name string - */ -#define MPR_MAX_IP_NAME 64 - -/** - * Maximum size of an IP address - */ -#define MPR_MAX_IP_ADDR 16 - -/** - * Maximum size of an IP address including port number - */ -#define MPR_MAX_IP_ADDR_PORT 32 - -#define MPR_MAX_SLAB 16 /* Slabs from 32-512 bytes */ - -#define MPR_MAX_TIME_SYNC (10 * 1000) /* Time sync adjustments */ - -/** - * @overview Memory context type - * @description Blocks of memory are allocated using a memory context - * as the parent with the \ref MprApp structure being the root of the - * tree. Any allocated memory block may serve as the memory context for - * subsequent memory allocations. Freeing a block via \ref mprFree will - * release the allocated block and all child blocks. - * @stability Prototype. - * @library libmpr. - * @see mprInit, mprAlloc, mprFree - */ -typedef const void *MprCtx; - -/* - * Allocated memory destructor type - */ -typedef int (*MprDestructor)(void *); - -/******************************** Error Codes *********************************/ - -/* - * Standard MPR return and error codes - */ - -#define MPR_ERR_OK (0) -/**< Success */ - -#define MPR_ERR_BASE (-200) -/**< Base error code */ - -#define MPR_ERR_GENERAL (MPR_ERR_BASE - 1) -/**< General error */ -#define MPR_ERR_ABORTED (MPR_ERR_BASE - 2) -/**< Action aborted */ -#define MPR_ERR_ALREADY_EXISTS (MPR_ERR_BASE - 3) -/**< Item already exists */ -#define MPR_ERR_BAD_ARGS (MPR_ERR_BASE - 4) -/**< Bad arguments or paramaeters */ -#define MPR_ERR_BAD_FORMAT (MPR_ERR_BASE - 5) -/**< Bad input format */ -#define MPR_ERR_BAD_HANDLE (MPR_ERR_BASE - 6) -#define MPR_ERR_BAD_STATE (MPR_ERR_BASE - 7) -/**< Module is in a bad state */ -#define MPR_ERR_BAD_SYNTAX (MPR_ERR_BASE - 8) -/**< Input has bad syntax */ -#define MPR_ERR_BAD_TYPE (MPR_ERR_BASE - 9) -#define MPR_ERR_BAD_VALUE (MPR_ERR_BASE - 10) -#define MPR_ERR_BUSY (MPR_ERR_BASE - 11) -#define MPR_ERR_CANT_ACCESS (MPR_ERR_BASE - 12) -/**< Can't access the file or resource */ -#define MPR_ERR_CANT_COMPLETE (MPR_ERR_BASE - 13) -#define MPR_ERR_CANT_CREATE (MPR_ERR_BASE - 14) -/**< Can't create the file or resource */ -#define MPR_ERR_CANT_INITIALIZE (MPR_ERR_BASE - 15) -#define MPR_ERR_CANT_OPEN (MPR_ERR_BASE - 16) -/**< Can't open the file or resource */ -#define MPR_ERR_CANT_READ (MPR_ERR_BASE - 17) -/**< Can't read from the file or resource */ -#define MPR_ERR_CANT_WRITE (MPR_ERR_BASE - 18) -/**< Can't write to the file or resource */ -#define MPR_ERR_DELETED (MPR_ERR_BASE - 19) -#define MPR_ERR_NETWORK (MPR_ERR_BASE - 20) -#define MPR_ERR_NOT_FOUND (MPR_ERR_BASE - 21) -#define MPR_ERR_NOT_INITIALIZED (MPR_ERR_BASE - 22) -/**< Module or resource is not initialized */ -#define MPR_ERR_NOT_READY (MPR_ERR_BASE - 23) -#define MPR_ERR_READ_ONLY (MPR_ERR_BASE - 24) -/**< The operation timed out */ -#define MPR_ERR_TIMEOUT (MPR_ERR_BASE - 25) -#define MPR_ERR_TOO_MANY (MPR_ERR_BASE - 26) -#define MPR_ERR_WONT_FIT (MPR_ERR_BASE - 27) -#define MPR_ERR_WOULD_BLOCK (MPR_ERR_BASE - 28) -#define MPR_ERR_CANT_ALLOCATE (MPR_ERR_BASE - 29) -// MOB -- rename NO_MEMORY -#define MPR_ERR_MEMORY (MPR_ERR_BASE - 30) -#define MPR_ERR_CANT_DELETE (MPR_ERR_BASE - 31) -#define MPR_ERR_MAX (MPR_ERR_BASE - 32) - -/* - * Standard logging trace levels are 0 to 9 with 0 being the most verbose. - * the These are ored with the error source and type flags. The MPR_LOG_MASK - * is used to extract the trace level from a flags word. We expect most apps - * to run with level 2 trace enabled. - */ -#define MPR_ERROR 1 /**< Hard error trace level */ -#define MPR_WARN 2 /**< Soft warning trace level */ -#define MPR_CONFIG 2 /**< Configuration settings trace level. */ -#define MPR_INFO 3 /**< Informational trace only */ -#define MPR_DEBUG 4 /**< Debug information trace level */ -#define MPR_VERBOSE 9 /**< Highest level of trace */ -#define MPR_LEVEL_MASK 0xf /**< Level mask */ - -/* - * Error source flags - */ -#define MPR_ERROR_SRC 0x10 /**< Originated from mprError */ -#define MPR_LOG_SRC 0x20 /**< Originated from mprLog */ -#define MPR_ASSERT_SRC 0x40 /**< Originated from mprAssert */ -#define MPR_FATAL_SRC 0x80 /**< Fatal error. Log and exit */ - -/* - * Log message type flags. Specify what kind of log / error message it is. - * Listener handlers examine this flag to determine if they should process - * the message.Assert messages are trapped when in DEV mode. Otherwise ignored. - */ -#define MPR_LOG_MSG 0x100 /**< Log trace message - not an error */ -#define MPR_ERROR_MSG 0x200 /**< General error */ -#define MPR_ASSERT_MSG 0x400 /**< Assert flags -- trap in debugger */ -#define MPR_USER_MSG 0x800 /**< User message */ - -/* - * Log output modifiers - */ -#define MPR_RAW 0x1000 /**< Raw trace output */ - -/* - * Error line number information. - */ -#define MPR_LINE(s) #s -#define MPR_LINE2(s) MPR_LINE(s) -#define MPR_LINE3 MPR_LINE2(__LINE__) -#define MPR_LOC __FILE__ ":" MPR_LINE3 - -/* - * Macros to pass file and line number information - * Use MPR_LOC_ARGS in normal user code. - * Use MPR_LOC_DEC in declarations. - * Use MPR_LOC_PASS in layered APIs to pass original line info down. - */ -#if BLD_FEATURE_ALLOC_LEAK_TRACK -#define MPR_LOC_ARGS(ctx) ctx, MPR_LOC -#define MPR_LOC_DEC(ctx, loc) MprCtx ctx, const char *loc -#define MPR_LOC_PASS(ctx, loc) ctx, loc -#else -#define MPR_LOC_ARGS(ctx) ctx -#define MPR_LOC_DEC(ctx, loc) MprCtx ctx -#define MPR_LOC_PASS(ctx, loc) ctx -#endif - -/******************************* Debug and Assert *****************************/ - -extern void mprBreakpoint(const char *loc, const char *msg); - -#if BLD_FEATURE_ASSERT - #define mprAssert(C) if (C) ; else mprStaticAssert(MPR_LOC, #C) -#else - #define mprAssert(C) if (1) ; else -#endif - -/********************************* Safe Strings *******************************/ -/* - * Unsafe functions that should not be used. Define UNSAFE_STRINGS_OK before - * including mpr.h if you really want to use these functions. A better approach - * is to undefine them just prior to using them in your C/C++ source file. - */ -#if BLD_FEATURE_SAFE_STRINGS - -#if BLD_FEATURE_PHP4_MODULE || BLD_FEATURE_PHP5_MODULE - #ifndef UNSAFE_FUNCTIONS_OK - #define UNSAFE_FUNCTIONS_OK 1 - #endif -#endif - -#ifndef UNSAFE_FUNCTIONS_OK - #define sprintf UseMprSprintfInstead - #define fprintf UseMprFprintfInstead - #define vsprintf UseMprVsprintfInstead - #define strtok UseMprStrTokInstead - #define gethostbyname UseMprGetHostByNameInstead - #define ctime UseMprCtimeInstead - #define asctime UseMprAsctimeInstead - #define localtime UseMprLocaltimeInstead - #define gmtime UseMprGmtimeInstead - #define malloc UseMprMallocInstead - #define free UseMprFreeInstead - #define realloc UseMprReallocInstead - #define strncpy UseMprStrcpyInstead - #define inet_ntoa UseMprInetToStrInstead - -#if !BREW - #define printf UseMprPrintfInstead -#endif - - #if FUTURE - #define strlen UseMprStrlenInstead - #define strcpy UseMprStrcpyInstead - #endif - -#endif /* UNSAFE_FUNCTIONS_OK */ -#endif /* BLD_FEATURE_SAFE_STRINGS */ - -/******************************************************************************/ - -struct MprBuf; -typedef int (*MprBufProc)(struct MprBuf* bp, void *arg); - -/** - * @overview Dynamic buffer structure - * @description MprBuf is a flexible, dynamic growable buffer structure. It - * utilizes a ring buffer mechanism and is suitable for high performance - * buffering in a variety of situations. - * @stability Prototype. - * @library libmpr. - * @see mprCreateBuf, mprFree, MprArray - */ -typedef struct MprBuf { - uchar *buf; /* Actual buffer for data */ - uchar *endbuf; /* Pointer one past the end of buffer */ - uchar *start; /* Pointer to next data char */ - uchar *end; /* Pointer one past the last data chr */ - int buflen; /* Current size of buffer */ - int maxsize; /* Max size the buffer can ever grow */ - int growBy; /* Next growth increment to use */ - MprBufProc refillProc; /* Auto-refill procedure */ - void *refillArg; /* Refill arg */ -} MprBuf; - -/** - * @overview File structure - * @description MprFile is the cross platform File I/O abstraction control - * structure. - * @stability Prototype. - * @library libmpr. - * @see mprOpen, mprClose, mprRead, mprWrite - */ -typedef struct MprFile -{ - MprBuf *buf; /* Buffer for I/O */ -#if BREW - IFile *fd; /* File handle */ -#else - int fd; -#endif -} MprFile; - -/** - * File information structure - * @overview File information structure - * @description MprFileInfo is the cross platform File information structure. - * @stability Prototype. - * @see mprGetFileInfo, mprOpen, mprClose, mprRead, mprWrite - */ -typedef struct MprFileInfo -{ - uint size; /* File length */ - uint ctime; /* Create time */ - uint mtime; /* Modified time */ - uint inode; /* Inode number */ - int isDir; /* Set if directory */ - int isReg; /* Set if a regular file */ -} MprFileInfo; - -/** - * @overview Mpr time structure. - * @description MprTime is the cross platform time abstraction structure. - * @stability Prototype. - * @library libmpr. - * @see mprGetTime - */ -typedef struct MprTime -{ - uint sec; /* Seconds */ - uint msec; /* Milliseconds */ -} MprTime; - - -/** - * @overview Generic array type - * @description The MprArray is a dynamic growable array suitable for storing - * pointers to arbitrary objects. - * @stability Prototype. - * @library libmpr. - * @see mprCreateItemArray, mprFree, MprBuf - */ -typedef struct MprArray -{ - int capacity; /* Current capacity of the array */ - int length; /* Count of used items */ - int incr; /* Growth increment */ - int maxSize; /* Maximum capacity */ - void **items; -} MprArray; - - -#if BLD_FEATURE_MULTITHREAD -/** - * @overview Multithreading lock control structure - * @description MprLock is used for multithread locking in multithreaded - * applications. - * @library libmpr. - * @see mprCreateLock, mprDestroyLock, mprLock, mprUnlock - */ -typedef struct -{ - #if WIN - CRITICAL_SECTION cs; /* O/S critical section */ - #endif - #if LINUX || MACOSX || SOLARIS - pthread_mutex_t cs; /* O/S critical section */ - #endif - #if VXWORKS - SEM_ID cs; /* Semaphore */ - #endif -} MprLock; -#endif - -/* - * Error and Logging callback - */ -typedef void (*MprLogHandler)(MPR_LOC_DEC(ctx, loc), int flags, - int level, const char *msg); - -/* - * Symbol table - * MOB -- rename hash - */ -typedef struct MprSymbol -{ - struct MprSymbol *next; /* Next symbol in hash chain */ - char *key; /* Symbol key */ - void *data; /* Pointer to symbol data */ - int bucket; /* Hash bucket index */ -} MprSymbol; - -typedef struct MprSymbolTable -{ - MprSymbol **buckets; - int hashSize; /* Size of the buckets array */ - int count; /* Number of symbols in the table */ -} MprSymbolTable; - - -/* - * Memory allocation error callback - */ -struct MprApp; -typedef int (*MprAllocCback)(struct MprApp *app, uint size, uint total, - bool granted); - - -/* - * Slab block pointer links - */ -typedef struct MprSlabBlock { - struct MprSlabBlock *next; -} MprSlabBlock; - - -#if BLD_FEATURE_ALLOC_STATS -/* - * Memory Slab Statistics - */ -typedef struct MprSlabStats { - uint allocCount; /* Number of allocated blocks */ - uint freeCount; /* Number of blocks on the slab freelist */ - uint peakAllocCount; /* Peak allocated */ - uint totalAllocCount; /* Total count of allocation calls */ - uint peakFreeCount; /* Peak on the free list */ - MprSlabBlock *next; -} MprSlabStats; -#endif - - -/* - * Slab control structure - */ -typedef struct MprSlab { - MprSlabBlock *next; - uint preAllocateIncr; /* Pre-allocation increment */ -#if BLD_FEATURE_ALLOC_STATS - MprSlabStats stats; -#endif -} MprSlab; - -/* - * Allocation stats (kept even in production code so we can detect memory - * allocation failures) - */ -typedef struct MprAllocStats -{ - uint bytesAllocated; /* Bytes currently allocated */ - uint peakAllocated; /* Peak bytes allocated */ - uint allocCount; /* Number of allocated blocks */ - uint redLine; /* Warn above this level */ - uint maxMemory; /* Max memory to allocate */ - uint errors; /* Allocation errors */ -} MprAllocStats; - -/* - * Memory allocation control - */ - -typedef struct MprAlloc { - MprSlab *slabs; /* Array[MPR_MAX_SLAB] of MprSlab */ - MprAllocCback cback; /* Memory allocation callback */ - MprAllocStats stats; /* Keep stats even in release */ - int inAllocException; /* Recursive protect */ -} MprAlloc; - - -/* - * MprApp State Flags - */ -#define MPR_APP_EXITING 0x1 /* App is exiting */ -#define MPR_APP_ALLOC_ERROR 0x2 /* App has allocation error */ - -/* MOB -- temporary */ -#define MPR_APP_NEED_GC 0x4 /* App needs GC */ - -/** - * @overview Primary MPR application control structure - * @description The MprApp structure stores critical application state - * information and is the root memory allocation context block. It is - * used as the MprCtx context for other memory allocations and is thus - * the ultimate parent of all allocated memory. - * \n\n - * The MprApp structure is allocated by the mprInit API. - */ -typedef struct MprApp -{ - uint magic; /* Corruption protection */ - MprFile *console; /* Stdout file */ - bool debugMode; /* Run in debug mode (no timers) */ - MprFile *error; /* Stderr file */ - int logLevel; /* Log trace level */ - MprFile *logFile; /* Log file */ - MprLogHandler logHandler; /* Current log handler callback */ - MprSymbolTable *table; - char *name; /* Product name */ - char *title; /* Product title */ - char *version; /* Product version */ - -#if BREW - uint classId; /* Brew class ID */ - IShell *shell; /* Brew shell object */ - IDisplay *display; /* Brew display object */ - IFileMgr *fileMgr; /* File manager */ - ITAPI *tapi; /* TAPI object */ - int displayHeight; /* Display height */ - int displayWidth; /* Display width */ - char *args; /* Command line args */ -#endif - - void *stackStart; /* Start of app stack */ - uint maxStack; /* Max stack size recorded */ - - MprAlloc alloc; /* Memory allocation data */ - int flags; /* App state flags */ - -#if BLD_FEATURE_MULTITHREAD - MprLock *globalLock; - MprLock *allocLock; -#endif -} MprApp; - - -/* - * String type. Minimum size is 8 words (32 bytes). - */ -#define MPR_MAX_INLINE_STR 24 - - -/* - * The block header structure for all allocated memory blocks (32 bytes) - * WARNING: Don't increase the size of this structure. It just fits into - * 32 bytes currently. Alignment requirements will double this size if you - * add one byte! - */ -typedef struct MprBlk -{ - MprApp *app; /* app is the top level alloc context */ - struct MprBlk *parent; /* Parent block */ - struct MprBlk *children; /* First child block */ - struct MprBlk *next; /* Next sibling */ - struct MprBlk *prev; /* Previous sibling */ - MprDestructor destructor; /* Destructor function (optional) */ - uint size; /* Size of block sans HDR_SIZE */ - uint flags; /* Allocation flags and magic number */ -#if BLD_FEATURE_ALLOC_LEAK_TRACK - const char *location; /* Allocating code (file + line) */ -#endif -} MprBlk; - -/******************************************************************************/ -/****************************** Internal Prototypes ***************************/ -/******************************************************************************/ - -extern void mprSignalAllocError(MprCtx ctx); - -/******************************************************************************/ -/********************************** Prototypes ********************************/ -/******************************************************************************/ - -extern MprApp *mprInit(MprAllocCback cback); -extern MprApp *mprInitEx(MprAllocCback cback, void *shell); -extern void mprTerm(MprApp *app, bool doStats); -extern void mprSignalExit(MprCtx ctx); -extern bool mprIsExiting(MprCtx ctx); -extern bool mprHasAllocError(MprCtx ctx); - -#if BLD_DEBUG && UNUSED -extern MprApp *mprGetApp(MprCtx ctx); -#else -#define mprGetApp(ctx) \ - (((MprBlk*) ((char*) ctx - MPR_BLK_HDR_SIZE))->app) -#endif - -/******************************************************************************/ - -extern int mprSetKeyValue(MprCtx ctx, const char *key, void *ptr); -/* MOB -- should this be delete or remove or unset */ -extern int mprRemoveKeyValue(MprCtx ctx, const char *key); -extern void *mprGetKeyValue(MprCtx ctx, const char *key); -/* MOB -- should be setAppName, getAppName */ -extern int mprSetAppName(MprCtx ctx, const char *name, const char *title, - const char *version); -extern const char *mprGetAppName(MprCtx ctx); -extern const char *mprGetAppTitle(MprCtx ctx); -extern const char *mprGetAppVersion(MprCtx ctx); - -/* - * File services - */ -extern void mprStopFileServices(MprCtx ctx); -extern int mprStartFileServices(MprCtx ctx); - -/* - * Item Array - */ -#define mprCreateItemArray(ctx, initialSize, maxSize) \ - mprCreateItemArrayInternal(MPR_LOC_ARGS(ctx), initialSize, \ - maxSize) - -extern MprArray *mprCreateItemArrayInternal(MPR_LOC_DEC(ctx, loc), - int initialSize, int maxSize); -/* MOB -- should be insert not add/delete or insert / remove */ -extern int mprAddItem(MprArray *array, void *item); -extern void mprClearItems(MprArray *array); -extern void mprClearAndFreeItems(MprArray *array); -extern int mprFindItem(MprArray *array, void *item); -extern void *mprGetFirstItem(MprArray *array, int *lastIndex); -extern void *mprGetItem(MprArray *array, int index); -extern int mprGetItemCapacity(MprArray *array); -extern int mprGetItemCount(MprArray *array); -extern void *mprGetNextItem(MprArray *array, int *lastIndex); -extern void *mprGetPrevItem(MprArray *array, int *lastIndex); -extern int mprRemoveItem(MprArray *array, void *item); -extern int mprRemoveItemByIndex(MprArray *array, int index); -extern int mprRemoveRangeOfItems(MprArray *array, int start, int end); - - -/* - * Printf replacements - */ -extern int mprSprintf(char *buf, int maxSize, const char *fmt, ...) - PRINTF_ATTRIBUTE(3,4); -extern int mprVsprintf(char *buf, int maxSize, const char *fmt, - va_list arg) PRINTF_ATTRIBUTE(3,0); -extern char *mprItoa(char *buf, int size, int value); -extern int mprAtoi(const char *str, int radix); - -extern int mprPrintf(MprCtx ctx, const char *fmt, ...) - PRINTF_ATTRIBUTE(2,3); -/* MOB -- NEED DOC */ -extern int mprErrorPrintf(MprCtx ctx, const char *fmt, ...) - PRINTF_ATTRIBUTE(2,3); -extern int mprStaticPrintf(MprCtx ctx, const char *fmt, ...) - PRINTF_ATTRIBUTE(2,3); -extern int mprPrintfError(MprCtx ctx, const char *fmt, ...) - PRINTF_ATTRIBUTE(2,3); -extern int mprFprintf(MprFile *file, const char *fmt, ...) - PRINTF_ATTRIBUTE(2,3); - -/* - * Safe string routines - */ -extern char *mprGetWordTok(char *buf, int bufsize, const char *str, - const char *delim, const char **tok); -extern int mprMemcpy(char *dest, int destMax, const char *src, - int nbytes); -extern int mprStrcat(char *dest, int max, const char *delim, - const char *src, ...); -extern int mprStrcpy(char *dest, int destMax, const char *src); - -extern int mprStrcmpAnyCase(const char *str1, const char *str2); -extern int mprStrcmpAnyCaseCount(const char *str1, const char *str2, - int len); -extern int mprStrlen(const char *src, int max); - -extern char *mprStrLower(char *str); -extern char *mprStrUpper(char *str); -extern char *mprStrTrim(char *str, const char *set); -extern char *mprStrTok(char *str, const char *delim, char **last); - -/* - * Symbol table - */ -extern MprSymbolTable *mprCreateSymbolTable(MprCtx ctx, int hashSize); -extern MprSymbol *mprGetFirstSymbol(MprSymbolTable *table); -extern MprSymbol *mprGetNextSymbol(MprSymbolTable *table, MprSymbol *last); -extern int mprGetSymbolCount(MprSymbolTable *table); -extern MprSymbol *mprInsertSymbol(MprSymbolTable *table, const char *key, - void *ptr); -extern void *mprLookupSymbol(MprSymbolTable *table, const char *key); -extern int mprRemoveSymbol(MprSymbolTable *table, const char *key); - -/* - * File I/O support - */ -extern void mprClose(MprFile *file); -extern int mprDelete(MprCtx ctx, const char *path); -extern int mprDeleteDir(MprCtx ctx, const char *path); -extern int mprGetFileInfo(MprCtx ctx, const char *path, MprFileInfo *info); -extern char *mprGets(MprFile *file, char *buf, uint size); -extern int mprMakeDir(MprCtx ctx, const char *path, int perms); -extern MprFile *mprOpen(MprCtx ctx, const char *path, int omode, int perms); -extern int mprPuts(MprFile *file, const char *buf, uint size); -extern int mprRead(MprFile *file, void *buf, uint size); -extern int mprSeek(MprFile *file, int seekType, long distance); -extern int mprWrite(MprFile *file, const void *buf, uint count); - -extern int mprMakeTempFileName(MprCtx ctx, char *buf, int bufsize, - const char *tmpDir); - - -/* - * Error handling and logging - */ -extern void mprSetLogHandler(MprCtx ctx, MprLogHandler handler); -extern MprLogHandler mprGetLogHandler(MprCtx ctx); - -extern void mprAssertError(MPR_LOC_DEC(ctx, loc), const char *msg); -extern void mprError(MPR_LOC_DEC(ctx, loc), - const char *fmt, ...) PRINTF_ATTRIBUTE(3,4); -extern void mprFatalError(MPR_LOC_DEC(ctx, loc), - const char *fmt, ...) PRINTF_ATTRIBUTE(3,4); -extern void mprLog(MprCtx ctx, int level, - const char *fmt, ...) PRINTF_ATTRIBUTE(3,4); -extern void mprRawLog(MprCtx ctx, const char *fmt, ...); -extern void mprStaticAssert(const char *loc, const char *msg); -extern void mprStaticError(MPR_LOC_DEC(ctx, loc), - const char *fmt, ...) PRINTF_ATTRIBUTE(3,4); -extern void mprUserError(MPR_LOC_DEC(ctx, loc), - const char *fmt, ...) PRINTF_ATTRIBUTE(3,4); - -/* - * Dynamic Buffering routines - */ -extern MprBuf *mprCreateBuf(MprCtx ctx, int initialSize, int maxSize); -extern char *mprStealBuf(MprCtx ctx, MprBuf *bp); -extern void mprAddNullToBuf(MprBuf *bp); -extern void mprAdjustBufStart(MprBuf *bp, int size); -extern void mprAdjustBufEnd(MprBuf *bp, int size); -extern void mprCopyBufDown(MprBuf *bp); -extern void mprFlushBuf(MprBuf *bp); -extern int mprGetCharFromBuf(MprBuf *bp); -extern int mprGetBlockFromBuf(MprBuf *bp, uchar *buf, int len); -extern int mprGetBufLength(MprBuf *bp); -extern int mprGetBufLinearSpace(MprBuf *bp); -extern int mprGetBufLinearData(MprBuf *bp); -extern char *mprGetBufOrigin(MprBuf *bp); -extern int mprGetBufSize(MprBuf *bp); -extern int mprGetBufSpace(MprBuf *bp); -extern char *mprGetBufStart(MprBuf *bp); -extern char *mprGetBufEnd(MprBuf *bp); -extern int mprInsertCharToBuf(MprBuf *bp, int c); -extern int mprLookAtNextCharInBuf(MprBuf *bp); -extern int mprLookAtLastCharInBuf(MprBuf *bp); -extern int mprPutCharToBuf(MprBuf *bp, int c); -extern int mprPutBlockToBuf(MprBuf *bp, const char *str, int size); -extern int mprPutIntToBuf(MprBuf *bp, int i); -extern int mprPutStringToBuf(MprBuf *bp, const char *str); -extern int mprPutFmtStringToBuf(MprBuf *bp, const char *fmt, ...); -extern int mprRefillBuf(MprBuf *bp); -extern void mprResetBufIfEmpty(MprBuf *bp); -extern void mprSetBufSize(MprBuf *bp, int initialSize, int maxSize); -extern MprBufProc mprGetBufRefillProc(MprBuf *bp); -extern void mprSetBufRefillProc(MprBuf *bp, MprBufProc fn, void *arg); - -/* - * General other xPlatform routines - */ -extern const char *mprGetBaseName(const char *name); -extern bool mprGetDebugMode(MprCtx ctx); -extern char *mprGetDirName(char *buf, int bufsize, const char *path); -extern char *mprGetFullPathName(char *buf, int buflen, const char *path); -extern int mprGetLogLevel(MprCtx ctx); -extern int mprGetOsError(); - - -extern int mprMakeArgv(MprCtx ctx, const char *prog, const char *cmd, - char ***argv, int *argc); -extern int mprMakeDirPath(MprCtx ctx, const char *path); -extern void mprSetDebugMode(MprCtx ctx, bool on); -extern void mprSetLogLevel(MprCtx ctx, int level); -extern void mprSleep(MprCtx ctx, int msec); -extern void mprSetShell(MprCtx ctx, void *shell); -extern void *mprGetShell(MprCtx ctx); -extern void mprSetClassId(MprCtx ctx, uint classId); -extern uint mprGetClassId(MprCtx ctx); - -#if BREW -extern void mprSetDisplay(MprCtx ctx, void *display); -extern void *mprGetDisplay(MprCtx ctx); -extern void mprSetFileMgr(MprCtx ctx, void *fileMgr); -extern void *mprGetFileMgr(MprCtx ctx); -#else -extern char *mprInetToStr(char *buf, int size, const struct in_addr in); -#endif - -/* - * Memory allocation - */ -extern MprApp *mprAllocInit(MprAllocCback cback); -extern void mprAllocTerm(MprApp *app); -extern void mprAllocAbort(); - -extern void *mprAllocBlock(MPR_LOC_DEC(ctx, loc), uint size); -extern void *mprAllocZeroedBlock(MPR_LOC_DEC(ctx, loc), uint size); -extern void *mprReallocBlock(MPR_LOC_DEC(ctx, loc), void *ptr, uint size); -extern int mprFree(void *ptr); -extern int mprStealAllocBlock(MPR_LOC_DEC(ctx, loc), const void *ptr); -extern void *mprMemdupInternal(MPR_LOC_DEC(ctx, loc), const void *ptr, - uint size); -extern char *mprStrndupInternal(MPR_LOC_DEC(ctx, loc), const char *str, - uint size); -extern char *mprStrdupInternal(MPR_LOC_DEC(ctx, loc), const char *str); - -extern void *mprSlabAllocBlock(MPR_LOC_DEC(ctx, loc), uint size, uint inc); -extern void *mprSlabAllocZeroedBlock(MPR_LOC_DEC(ctx, loc), uint size, - uint inc); - -extern uint mprGetAllocBlockSize(MprCtx ctx); -extern uint mprGetAllocBlockCount(MprCtx ctx); -extern uint mprGetAllocBlockMemory(MprCtx ctx); -extern void *mprGetAllocParent(MprCtx ctx); -extern uint mprGetAllocatedMemory(MprCtx ctx); -extern uint mprGetPeakAllocatedMemory(MprCtx ctx); -extern uint mprGetAllocatedSlabMemory(MprCtx ctx); -extern int mprIsAllocBlockValid(MprCtx ctx); -extern int mprStackCheck(MprCtx ctx); -extern int mprStackSize(MprCtx ctx); -extern int mprGetAllocErrors(MprCtx ctx); -extern void mprClearAllocErrors(MprCtx ctx); - -extern MprDestructor mprSetDestructor(MprCtx ctx, MprDestructor destructor); -extern MprAllocCback mprSetAllocCallback(MprApp *app, MprAllocCback cback); -extern void mprSetAllocLimits(MprApp *app, uint redLine, uint maxMemory); - -#if BLD_FEATURE_ALLOC_STATS -extern MprSlabStats *mprGetSlabAllocStats(MprApp *app, int slabIndex); -extern MprAllocStats *mprGetAllocStats(MprApp *app); -extern void mprPrintAllocReport(MprApp *app, bool doBlocks, - const char *msg); -#endif - -#if BLD_DEBUG -extern int mprPrintAllocBlocks(MprCtx ctx, int indent); -extern const char *mprGetAllocLocation(MprCtx ptr); -#endif - -extern int mprValidateBlock(MprCtx ctx); -extern int mprValidateAllocTree(MprCtx ptr); -extern void mprSetRequiredAlloc(MprCtx ptr, bool recurse); - -/* - * Sprintf style allocators - */ -extern int mprAllocSprintf(MPR_LOC_DEC(ctx, loc), char **buf, int maxSize, - const char *fmt, ...) PRINTF_ATTRIBUTE(5,6); -extern int mprAllocVsprintf(MPR_LOC_DEC(ctx, loc), char **buf, int maxSize, - const char *fmt, va_list arg) PRINTF_ATTRIBUTE(5,0); -extern int mprAllocMemcpy(MPR_LOC_DEC(ctx, loc), char **dest, int destMax, - const void *src, int nbytes); -extern int mprAllocStrcat(MPR_LOC_DEC(ctx, loc), char **dest, int max, - const char *delim, const char *src, ...); -extern int mprAllocStrcpy(MPR_LOC_DEC(ctx, loc), char **dest, int max, - const char *src); -extern int mprReallocStrcat(MPR_LOC_DEC(ctx, loc), char **dest, int max, - int existingLen, const char *delim, const char *src, ...); - -/* - * MACROS: These are the convenience macros to automatically supply file - * names and line numbers when debugging. - */ -#define mprNew(ctx) new(MPR_LOC_ARGS(ctx)) - -#define mprAlloc(ctx, size) mprAllocBlock(MPR_LOC_ARGS(ctx), size) - -#define mprAllocZeroed(ctx, size) mprAllocZeroedBlock(MPR_LOC_ARGS(ctx), size) - -#define mprSlabAlloc(ctx, size, inc) \ - ((type*) mprSlabAllocBlock(MPR_LOC_ARGS(ctx), size, inc)) - -#define mprSlabAllocZeroed(ctx, size, inc) \ - ((type*) mprSlabAllocBlock(MPR_LOC_ARGS(ctx), size, inc)) - -#define mprRealloc(ctx, ptr, size) mprReallocBlock(MPR_LOC_ARGS(ctx), ptr, size) - -#define mprMemdup(ctx, ptr, size) \ - mprMemdupInternal(MPR_LOC_ARGS(ctx), ptr, size) - -#define mprStrdup(ctx, str) mprStrdupInternal(MPR_LOC_ARGS(ctx), str) - -#define mprStrndup(ctx, str, size) mprStrndupDebug(MPR_LOC_ARGS(ctx), str, size) - -/* - * Allocate type macros - */ -#define mprAllocType(ctx, type) \ - ((type*) mprAllocBlock(MPR_LOC_ARGS(ctx), sizeof(type))) - -#define mprAllocTypeZeroed(ctx, type) \ - ((type*) mprAllocZeroedBlock(MPR_LOC_ARGS(ctx), sizeof(type))) - -#define mprSlabAllocType(ctx, type, inc) \ - ((type*) mprSlabAllocBlock(MPR_LOC_ARGS(ctx), sizeof(type), inc)) - -#define mprSlabAllocTypeZeroed(ctx, type, inc) \ - ((type*) mprSlabAllocZeroedBlock(MPR_LOC_ARGS(ctx), sizeof(type), \ - inc)) - -/* - * Multithread locking - */ -#if BLD_FEATURE_MULTITHREAD -extern void mprInitThreads(MprApp *app); -extern void mprTermThreads(MprApp *app); -extern MprLock *mprCreateLock(MprCtx ctx); -extern void mprDestroyLock(MprLock *lock); -extern void mprLock(MprLock *lock); -extern int mprTryLock(MprLock *lock); -extern void mprUnlock(MprLock *lock); -extern void mprGlobalLock(MprCtx ctx); -extern void mprGlobalUnlock(MprCtx ctx); -extern int mprGetCurrentThreadID(); -#else -/* - * Disable multithreading - */ -#define mprInitThreads(ctx, app) -#define mprTermThreads(app) -#define mprCreateLock(ctx) -#define mprDestroyLock(lock) -#define mprLock(lock) -#define mprTryLock(lock) -#define mprUnlock(lock) -#define mprGlobalLock(app) -#define mprGlobalUnlock(app) -#define mprGetCurrentThreadID() -#endif - -/* - * Time - */ -extern MprTime *mprGetTime(MprCtx ctx, MprTime *tp); -extern int mprGetTimeRemaining(MprCtx ctx, MprTime mark, uint timeout); -extern int mprGetElapsedTime(MprCtx ctx, MprTime mark); -extern int mprCompareTime(MprTime *t1, MprTime *t2); -extern uint mprSubtractTime(MprTime *t1, MprTime *t2); -extern void mprAddElapsedToTime(MprTime *time, uint elapsed); - -#if !BREW -extern int mprAsctime(MprCtx ctx, char *buf, int bufsize, - const struct tm *timeptr); -extern int mprCtime(MprCtx ctx, char *buf, int bufsize, - const time_t *timer); -extern struct tm *mprLocaltime(MprCtx ctx, struct tm *timep, time_t *now); -extern struct tm *mprGmtime(MprCtx ctx, time_t* now, struct tm *timep); -extern int mprRfcTime(MprCtx ctx, char *buf, int bufsize, - const struct tm *timep); -#endif /* !BREW */ - -/* - * Host name - */ -extern struct hostent* mprGetHostByName(MprCtx ctx, const char *name); - -#if WIN -extern int mprReadRegistry(MprCtx ctx, char **buf, int max, - const char *key, const char *val); -extern int mprWriteRegistry(MprCtx ctx, const char *key, const char *name, - const char *value); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* _h_MPR */ - - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/mprAlloc.c b/source4/lib/appweb/ejs-2.0/mpr/mprAlloc.c deleted file mode 100644 index 6fcaa63a6c..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mprAlloc.c +++ /dev/null @@ -1,1775 +0,0 @@ -/** - * @file mprAlloc.c - * @brief Memory Allocation - * @overview - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************* Includes ***********************************/ - -#define UNSAFE_FUNCTIONS_OK 1 - -#include "mpr.h" - -/******************************* Local Defines ********************************/ -/* - * Set to 1 to disable slab based allocations - */ -#define NO_SLAB 0 - -/* - * Validation mode is quite slow - */ -#define VALIDATE_ALLOC 0 -#if VALIDATE_ALLOC -#define VALIDATE_BLOCK(ptr) mprValidateBlock(ptr) -#else -#define VALIDATE_BLOCK(ptr) -#endif - -/* - * Align on 4 bytes if squeeze, Otherwize on 16 bytes. - */ -#define HDR_SIZE MPR_BLK_HDR_SIZE - -#define APP_MAGIC 0xa571cb80 -#define ALLOC_MAGIC 0xe814ecc0 - -/* - * This must be at least one word to ensure that the smallest allocation is - * 4 bytes. Slab allocations need at least one word to store their next ptr. - */ -#define ALLOC_ALIGN(x) (((x)+3)&~3) -#define GET_HDR(ptr) ((MprBlk*) (((char*) (ptr)) - HDR_SIZE)) -#define GET_PTR(bp) ((void*) (((char*) (bp)) + HDR_SIZE)) -#define VALID_HDR(bp) (((bp)->flags & ~0x3F) == ALLOC_MAGIC) -#define VALID_BLK(ptr) (VALID_HDR(GET_HDR(ptr))) - -/* - * In production releases, mprAssert will compile out (not be included) - * but CHECK_HDR will remain even in production builds. - */ -#define CHECK_HDR(bp) \ - if (1) { if (! VALID_HDR(bp)) { mprAllocAbort(); } } else - -/* - * Chunk the slabs into 32 byte increments. - * This allows for allocations up to 512 bytes via slabs and maximizes - * sharing of slab allocations. - * - * Index map: - * 0 == 32 bytes - * 1 == 64 bytes - * 2 == 96 bytes - * 3 == 128 bytes - * 4 == 160 bytes - * 5 == 192 bytes - * 6 == 224 bytes - * 7 == 256 bytes - * 8 == 288 bytes - * 9 == 320 bytes - * 10 == 352 bytes - * 11 == 384 bytes - * 12 == 416 bytes - * 13 == 448 bytes - * 14 == 480 bytes - * 15 == 512 bytes - */ -#define SLAB_ALIGN(size) ((size + 31) & ~31) -#define GET_SLAB(size) (size >> 6) - -/* - * Block flags - */ -#define ALLOC_FLAGS_FREE 0x1 /* Block is free */ -#define ALLOC_FLAGS_FREEING 0x2 /* Block is being freed */ -#define ALLOC_FLAGS_SLAB_BLOCK 0x4 /* Block was allocated from slab */ -#define ALLOC_FLAGS_REQUIRED 0x8 /* Block is required by alloc */ -#define ALLOC_FLAGS_KEEP 0x10 /* Keep block - don't mprFree */ -#define ALLOC_FLAGS_DONT_OS_FREE 0x20 /* Don't return mem to O/S */ -#define ALLOC_FLAGS_IS_SLAB 0x40 /* Block is a slab */ - -#if BLD_DEBUG && !BREW -/* - * Set this address to break when this address is allocated or freed. This is - * a block address (not a user ptr). - */ -static MprBlk *stopAlloc; -#endif - -#if !BREW -static MprCtx rootCtx; /* Root context if none supplied */ -#endif - -/***************************** Forward Declarations ***************************/ - -static int mprAllocException(MPR_LOC_DEC(ptr, loc), uint size, bool granted); -static void slabFree(MprBlk *bp); -static int growSlab(MPR_LOC_DEC(ctx, loc), MprSlab *slab, uint size, uint inc); - -/******************************************************************************/ -/* - * Put first in file so it is easy to locate in a debugger - */ - -void mprBreakpoint(const char *loc, const char *msg) -{ -} - -/******************************************************************************/ -#if (WIN || BREW_SIMULATOR) && BLD_DEBUG - -int crtReportHook(int type, char *msg, int *retval) -{ - printf("%s\n", msg); - *retval = 0; - return TRUE; -} - -#endif -/******************************************************************************/ -/* - * Initialize the memory subsystem - */ - -MprApp *mprAllocInit(MprAllocCback cback) -{ - MprAllocStats *stats; - MprApp *app; - MprSlab *slab; - MprBlk *bp, *sp; - int i; - - bp = malloc(sizeof(MprApp) + HDR_SIZE); - mprAssert(bp); - if (bp == 0) { - if (cback) { - (*cback)(0, sizeof(MprApp), 0, 0); - } - return 0; - } - memset(bp, 0, sizeof(MprApp) + HDR_SIZE); - - bp->parent = bp; - bp->size = sizeof(MprApp); - bp->flags = ALLOC_MAGIC; - bp->next = bp->prev = bp; - -#if BLD_FEATURE_ALLOC_LEAK_TRACK - bp->location = MPR_LOC; -#endif - - app = (MprApp*) GET_PTR(bp); - app->magic = APP_MAGIC; - - app->alloc.cback = cback; - app->stackStart = (void*) &app; - - bp->app = app; - - app->alloc.slabs = mprAllocZeroedBlock(MPR_LOC_PASS(app, MPR_LOC), - sizeof(MprSlab) * MPR_MAX_SLAB); - if (app->alloc.slabs == 0) { - mprFree(app); - return 0; - } - - /* - * The slab control structures must not be freed. Set keep to safeguard - * against accidents. - */ - sp = GET_HDR(app->alloc.slabs); - sp->flags |= ALLOC_FLAGS_KEEP; - - for (i = 0; i < MPR_MAX_SLAB; i++) { - /* - * This is overriden by requestors calling slabAlloc - */ - slab = &app->alloc.slabs[i]; - slab->preAllocateIncr = MPR_SLAB_DEFAULT_INC; - } - - /* - * Keep aggregated stats even in production code - */ - stats = &app->alloc.stats; - stats->bytesAllocated += sizeof(MprApp); - if (stats->bytesAllocated > stats->peakAllocated) { - stats->peakAllocated = stats->bytesAllocated; - } - stats->allocCount++; - -#if !BREW - rootCtx = app; -#endif -#if (WIN || BREW_SIMULATOR) && BLD_DEBUG - _CrtSetReportHook(crtReportHook); -#endif - return app; -} - -/******************************************************************************/ -/* - * Terminate the alloc module - */ - -void mprAllocTerm(MprApp *app) -{ - MprSlab *slabs; - MprBlk *appBlk, *slabBlk; - - /* - * Must do a carefully ordered cleanup. Need to free all children blocks - * before freeing the slab memory. Save a local pointer to the slabs. - */ - slabs = app->alloc.slabs; - - /* - * Free the app and all children. Set DONT_OS_FREE to prevent free() being - * called on app itself. We need that so we can free the slabs below. - */ - appBlk = GET_HDR(app); - appBlk->flags |= ALLOC_FLAGS_DONT_OS_FREE; - mprFree(app); - - /* - * Slabs are initially marked don't free. We must preserve them while all - * other blocks are freed. Then we clear the don't free flag and free. - * Now we don't have an app structure which is used by mprFree. We must - * fake it. - */ - slabBlk = GET_HDR(slabs); - slabBlk->flags &= ~ALLOC_FLAGS_KEEP; - mprFree(slabs); - - /* - * Now we can finally free the memory for the app structure - */ - free(appBlk); -} - -/******************************************************************************/ -/* - * Allocate a block - */ - -void *mprAllocBlock(MPR_LOC_DEC(ctx, loc), uint size) -{ - MprAllocStats *stats; - MprBlk *bp, *parent; - MprApp *app; - int diff; - - mprAssert(size > 0); - - if (ctx == 0) { -#if BREW - mprAssert(ctx); - return 0; -#else - ctx = rootCtx; -#endif - } - if (size == 0) { - size = 1; - } - - mprAssert(VALID_BLK(ctx)); - parent = GET_HDR(ctx); - mprAssert(VALID_HDR(parent)); - - CHECK_HDR(parent); - - size = ALLOC_ALIGN(size); - - app = parent->app; - - stats = &app->alloc.stats; - - mprLock(app->allocLock); - - stats->bytesAllocated += size + HDR_SIZE; - if (stats->bytesAllocated > stats->peakAllocated) { - stats->peakAllocated = stats->bytesAllocated; - } - - /* - * Prevent allocation if over the maximum - */ - if (stats->maxMemory && stats->bytesAllocated > stats->maxMemory) { - stats->bytesAllocated -= (size + HDR_SIZE); - mprUnlock(app->allocLock); - if (mprAllocException(MPR_LOC_PASS(ctx, loc), size, 0) < 0) { - return 0; - } - mprLock(app->allocLock); - } - - if ((bp = malloc(size + HDR_SIZE)) == 0) { - mprAssert(bp); - stats->errors++; - mprUnlock(app->allocLock); - mprAllocException(MPR_LOC_PASS(ctx, loc), size, 0); - return 0; - } - -#if BLD_DEBUG - memset(bp, 0xf7, size + HDR_SIZE); -#endif - -#if BLD_DEBUG && !BREW - if (bp == stopAlloc) { - mprBreakpoint(MPR_LOC, "breakOnAddr"); - } -#endif - - /* - * Warn if allocation puts us over the red line - */ - if (stats->redLine && stats->bytesAllocated > stats->redLine) { - mprUnlock(app->allocLock); - if (mprAllocException(MPR_LOC_PASS(ctx, loc), size, 1) < 0) { - return 0; - } - mprLock(app->allocLock); - } - - bp->size = size; - bp->flags = ALLOC_MAGIC; - bp->destructor = 0; - - bp->parent = parent; - - if (parent->children == 0) { - parent->children = bp; - bp->next = bp->prev = bp; - - } else { - /* - * Append to the end of the list. Preserve alloc order - */ - bp->next = parent->children; - bp->prev = parent->children->prev; - parent->children->prev->next = bp; - parent->children->prev = bp; - } - - bp->children = 0; - -#if BLD_FEATURE_ALLOC_LEAK_TRACK - bp->location = loc; -#endif - - bp->app = parent->app; - - VALIDATE_BLOCK(GET_PTR(bp)); - - stats->allocCount++; - - /* - * Monitor stack usage - */ - diff = (int) bp->app->stackStart - (int) &stats; - if (diff < 0) { - app->maxStack -= diff; - app->stackStart = (void*) &stats; - diff = 0; - } - - if ((uint) diff > app->maxStack) { - app->maxStack = diff; - } - mprUnlock(app->allocLock); - - return GET_PTR(bp); -} - -/******************************************************************************/ -/* - * Allocate and zero a block - */ - -void *mprAllocZeroedBlock(MPR_LOC_DEC(ctx, loc), uint size) -{ - void *newBlock; - - MprBlk *bp; - - bp = GET_HDR(ctx); - mprAssert(VALID_BLK(ctx)); - - newBlock = mprAllocBlock(MPR_LOC_PASS(ctx, loc), size); - if (newBlock) { - memset(newBlock, 0, size); - } - return newBlock; -} - -/******************************************************************************/ -/* - * Free a block of memory. Free all children recursively. - */ - -int mprFree(void *ptr) -{ - MprAllocStats *stats; - MprBlk *bp, *parent, *cp, *firstChild, *prev; - MprApp *app; - - if (ptr == 0) { - return 0; - } - - mprAssert(VALID_BLK(ptr)); - VALIDATE_BLOCK(ptr); - - bp = GET_HDR(ptr); - -#if BLD_DEBUG && !BREW - if (bp == stopAlloc) { - mprBreakpoint(MPR_LOC, "breakOnAddr"); - } -#endif - - mprAssert(bp); - mprAssert(VALID_HDR(bp)); - - CHECK_HDR(bp); - - /* - * Test if already freed - */ - mprAssert(! (bp->flags & ALLOC_FLAGS_FREE)); - if (bp->flags & ALLOC_FLAGS_FREE) { - return 0; - } - - /* - * Return if recursive freeing or this is a permanent block - */ - app = bp->app; - mprLock(app->allocLock); - if (bp->flags & (ALLOC_FLAGS_FREEING | ALLOC_FLAGS_KEEP)) { - mprUnlock(app->allocLock); - return 0; - } - bp->flags |= ALLOC_FLAGS_FREEING; - - - /* - * Call any destructors - */ - if (bp->destructor) { - mprUnlock(app->allocLock); - if ((bp->destructor)(ptr) < 0) { - return -1; - } - mprLock(app->allocLock); - bp->destructor = 0; - } - - /* - * Free the children. Free in reverse order so firstChild is preserved - * during the list scan as an end of list marker. - */ - if ((firstChild = bp->children) != 0) { - cp = firstChild->prev; - while (cp != firstChild) { - - mprAssert(VALID_HDR(cp)); - VALIDATE_BLOCK(GET_PTR(cp)); - - prev = cp->prev; - - /* - * FUTURE - OPT. Make this inline - */ - mprFree(GET_PTR(cp)); - - cp = prev; - } - - mprFree(GET_PTR(firstChild)); - - /* - * Just for clarity - */ - bp->children = 0; - } - - parent = bp->parent; - - mprAssert(VALID_HDR(parent)); - - /* - * Unlink from the parent - */ - if (parent->children == bp) { - if (bp->next == bp) { - parent->children = 0; - } else { - parent->children = bp->next; - } - } - - /* - * Remove from the sibling chain - */ - bp->prev->next = bp->next; - bp->next->prev = bp->prev; - - bp->flags |= ALLOC_FLAGS_FREE; - - /* - * Release the memory. If from a slab, return to the slab. Otherwise, - * return to the O/S. - */ - if (bp->flags & ALLOC_FLAGS_SLAB_BLOCK) { - slabFree(bp); - - } else { - mprAssert(bp); - - /* - * Update the stats - */ - stats = &bp->app->alloc.stats; - stats->bytesAllocated -= (bp->size + HDR_SIZE); - mprAssert(stats->bytesAllocated >= 0); - - stats->allocCount--; - mprAssert(stats->allocCount >= 0); - -#if BLD_DEBUG && !BREW - if (bp == stopAlloc) { - mprBreakpoint(MPR_LOC, "breakOnAddr"); - } -#endif - - /* - * Return to the O/S - */ - if (! (bp->flags & ALLOC_FLAGS_DONT_OS_FREE)) { - free(bp); - } - } - /* OPT */ - if (app != ptr) { - mprUnlock(app->allocLock); - } - - return 0; -} - -/******************************************************************************/ -/* - * Rallocate a block - */ - -void *mprReallocBlock(MPR_LOC_DEC(ctx, loc), void *ptr, uint size) -{ - MprBlk *bp, *newbp, *firstChild, *cp; - MprApp *app; - void *newPtr; - - mprAssert(VALID_BLK(ctx)); - mprAssert(size > 0); - - if (ptr == 0) { - return mprAllocBlock(MPR_LOC_PASS(ctx, loc), size); - } - - mprAssert(VALID_BLK(ptr)); - bp = GET_HDR(ptr); - mprAssert(bp); - mprAssert(VALID_HDR(bp)); - - CHECK_HDR(bp); - - if (size < bp->size) { - return ptr; - } - - newPtr = mprAllocBlock(MPR_LOC_PASS(ctx, loc), size); - if (newPtr == 0) { - bp->flags &= ~ALLOC_FLAGS_FREE; - free(bp); - return 0; - } - - newbp = GET_HDR(newPtr); - mprAssert(newbp->size >= size); - memcpy((char*) newbp + HDR_SIZE, (char*) bp + HDR_SIZE, bp->size); - mprAssert(newbp->size >= size); - - /* - * Fix the next / prev pointers - */ - app = bp->app; - mprLock(app->allocLock); - newbp->next->prev = newbp; - newbp->prev->next = newbp; - - /* - * Need to fix the parent pointer of all children - */ - if ((firstChild = newbp->children) != 0) { - cp = firstChild; - do { - cp->parent = newbp; - cp = cp->next; - } while (cp != firstChild); - } - - /* - * May need to set the children pointer of our parent - */ - if (newbp->parent->children == bp) { - newbp->parent->children = newbp; - } - - /* - * Free the original block - */ - mprFree(ptr); - - mprUnlock(app->allocLock); - - return GET_PTR(newbp); -} - -/******************************************************************************/ -/* - * Allocate a block from a slab - */ - -void *mprSlabAllocBlock(MPR_LOC_DEC(ctx, loc), uint size, uint inc) -{ - -#if NO_SLAB - return mprAllocBlock(MPR_LOC_PASS(ctx, loc), size); -#else - - MprBlk *parent, *bp; - MprSlabBlock *sb; - MprApp *app; - MprSlab *slab; - int slabIndex; - - if (ctx == 0) { - mprAssert(ctx); - return 0; - } - - mprAssert(size > 0); - mprAssert(VALID_BLK(ctx)); - - parent = GET_HDR(ctx); - mprAssert(VALID_HDR(parent)); - - CHECK_HDR(parent); - - size = SLAB_ALIGN(size); - - app = parent->app; - mprAssert(app); - - slabIndex = GET_SLAB(size); - - if (slabIndex < 0 || slabIndex >= MPR_MAX_SLAB) { - return mprAllocBlock(MPR_LOC_PASS(ctx, loc), size); - } - - /* - * Dequeue a block from the slab. "sb" will point to the user data - * portion of the block (i.e. after the MprBlk header). Slabs must be - * allocated off the "slabs" context to ensure they don't get freed - * until after all other blocks are freed. - */ - mprLock(app->allocLock); - slab = &app->alloc.slabs[slabIndex]; - if ((sb = slab->next) == 0) { - if (growSlab(MPR_LOC_ARGS(parent->app->alloc.slabs), - slab, size, inc) < 0) { - mprUnlock(app->allocLock); - return 0; - } - sb = slab->next; - } - mprAssert(sb); - - /* - * Dequeue the block - */ - slab->next = sb->next; - -#if BLD_FEATURE_ALLOC_STATS -{ - MprSlabStats *slabStats; - /* - * Update the slab stats - */ - slabStats = &slab->stats; - slabStats->totalAllocCount++; - slabStats->freeCount--; - slabStats->allocCount++; - if (slabStats->allocCount > slabStats->peakAllocCount) { - slabStats->peakAllocCount = slabStats->allocCount; - } -} -#endif /* BLD_FEATURE_ALLOC_STATS */ - - bp = GET_HDR(sb); - -#if BLD_DEBUG && !BREW - if (bp == stopAlloc) { - mprBreakpoint(MPR_LOC, "breakOnAddr"); - } -#endif - - bp->size = size; - bp->flags = ALLOC_MAGIC | ALLOC_FLAGS_SLAB_BLOCK; - bp->destructor = 0; - - bp->parent = parent; - - if (parent->children == 0) { - parent->children = bp; - bp->next = bp->prev = bp; - - } else { - /* - * Append to the end of the list. Preserve alloc order - */ - bp->next = parent->children; - bp->prev = parent->children->prev; - parent->children->prev->next = bp; - parent->children->prev = bp; - } - - bp->children = 0; - - bp->app = app; - -#if BLD_FEATURE_ALLOC_LEAK_TRACK - bp->location = loc; -#endif - mprUnlock(app->allocLock); - - return GET_PTR(bp); -#endif -} - -/******************************************************************************/ -/* - * Return a block back to its slab - */ - -static void slabFree(MprBlk *bp) -{ - MprSlab *slab; - MprApp *app; - void *ptr; - int slabIndex; - - mprAssert(VALID_HDR(bp)); - - slabIndex = GET_SLAB(bp->size); - mprAssert(0 <= slabIndex && slabIndex < MPR_MAX_SLAB); - - if (0 <= slabIndex && slabIndex < MPR_MAX_SLAB) { - mprLock(bp->app->allocLock); - slab = &bp->app->alloc.slabs[slabIndex]; - app = bp->app; - -#if BLD_DEBUG - memset(bp, 0xfc, bp->size + HDR_SIZE); -#endif - - ptr = GET_PTR(bp); - ((MprSlabBlock*) ptr)->next = slab->next; - slab->next = ((MprSlabBlock*) ptr); - -#if BLD_FEATURE_ALLOC_STATS -{ - MprSlabStats *slabStats; - slabStats = &slab->stats; - - slabStats->freeCount++; - slabStats->allocCount--; - - if (slabStats->freeCount >= slabStats->peakFreeCount) { - slabStats->peakFreeCount = slabStats->freeCount; - } -} -#endif - mprUnlock(app->allocLock); - } -} - -/******************************************************************************/ -/* - * Grow the slab and return the next free block - * Must be called locked. - */ - -static int growSlab(MPR_LOC_DEC(ctx, loc), MprSlab *slab, uint size, uint inc) -{ - MprBlk *bp; - MprSlabBlock *sb; - int i, chunkSize, len; - - mprAssert(VALID_BLK(ctx)); - mprAssert(slab); - mprAssert(size > 0); - - /* - * Take the maximum requested by anyone - */ - slab->preAllocateIncr = max(slab->preAllocateIncr, inc); - - /* - * We allocate an array of blocks each of user "size" bytes. - */ - chunkSize = HDR_SIZE + size; - len = chunkSize * slab->preAllocateIncr; - bp = mprAllocBlock(MPR_LOC_PASS(ctx, loc), len); - -#if BLD_DEBUG - memset(bp, 0xf1, len); -#endif - - if (bp == 0) { - mprAssert(0); - return MPR_ERR_MEMORY; - } - bp->flags |= ALLOC_FLAGS_IS_SLAB; - - /* - * We store the slab information in the user data portion - */ - sb = (MprSlabBlock*) GET_PTR(bp); - - - sb = (MprSlabBlock*) ((char*) sb + len - chunkSize); - for (i = slab->preAllocateIncr - 1; i >= 0; i--) { - sb->next = slab->next; - slab->next = sb; - sb = (MprSlabBlock*) ((char*) sb - chunkSize); - } - -#if BLD_FEATURE_ALLOC_STATS -{ - MprSlabStats *stats; - stats = &slab->stats; - stats->freeCount += slab->preAllocateIncr; - if (stats->freeCount > stats->peakFreeCount) { - stats->peakFreeCount = stats->freeCount; - } -} -#endif - - return 0; -} - -/******************************************************************************/ -/* - * Set the pre-allocate amount - */ - -int mprSetSlabPreAllocate(MprCtx ctx, int slabIndex, int preAllocateIncr) -{ - MprApp *app; - MprSlab *slab; - - mprAssert(VALID_BLK(ctx)); - mprAssert(0 <= slabIndex && slabIndex < MPR_MAX_SLAB); - mprAssert(preAllocateIncr > 0); - - if (0 <= slabIndex && slabIndex < MPR_MAX_SLAB) { - app = mprGetApp(ctx); - slab = &app->alloc.slabs[slabIndex]; - slab->preAllocateIncr = preAllocateIncr; - } else { - return MPR_ERR_BAD_ARGS; - } - return 0; -} - -/******************************************************************************/ - -void *mprSlabAllocZeroedBlock(MPR_LOC_DEC(ctx, loc), uint size, uint inc) -{ - void *newBlock; - - mprAssert(VALID_BLK(ctx)); - mprAssert(size > 0); - - newBlock = mprSlabAllocBlock(MPR_LOC_PASS(ctx, loc), size, inc); - if (newBlock) { - memset(newBlock, 0, size); - } - return newBlock; -} - -/******************************************************************************/ -/* - * Internal strdup function. Will use the slab allocator for small strings - */ - -char *mprStrdupInternal(MPR_LOC_DEC(ctx, loc), const char *str) -{ - char *newp; - int len; - - mprAssert(VALID_BLK(ctx)); - - if (str == 0) { - str = ""; - } - - len = strlen(str) + 1; - - if (len < MPR_SLAB_STR_MAX) { - newp = mprSlabAllocBlock(MPR_LOC_PASS(ctx, loc), MPR_SLAB_STR_MAX, - MPR_SLAB_STR_INC); - } else { - newp = mprAllocBlock(MPR_LOC_PASS(ctx, loc), len); - } - - if (newp) { - memcpy(newp, str, len); - } - - return newp; -} - -/******************************************************************************/ -/* - * Internal strndup function. Will use the slab allocator for small strings - */ - -char *mprStrndupInternal(MPR_LOC_DEC(ctx, loc), const char *str, uint size) -{ - char *newp; - uint len; - - mprAssert(VALID_BLK(ctx)); - - if (str == 0) { - str = ""; - } - len = strlen(str) + 1; - len = min(len, size); - - if (len < MPR_SLAB_STR_MAX) { - newp = mprSlabAllocBlock(MPR_LOC_PASS(ctx, loc), MPR_SLAB_STR_MAX, - MPR_SLAB_STR_INC); - } else { - newp = mprAllocBlock(MPR_LOC_PASS(ctx, loc), len); - } - - if (newp) { - memcpy(newp, str, len); - } - - return newp; -} - -/******************************************************************************/ -/* - * Internal memcpy function. Will use the slab allocator for small strings - */ - -void *mprMemdupInternal(MPR_LOC_DEC(ctx, loc), const void *ptr, uint size) -{ - char *newp; - - mprAssert(VALID_BLK(ctx)); - - if (size < MPR_SLAB_STR_MAX) { - newp = mprSlabAllocBlock(MPR_LOC_PASS(ctx, loc), MPR_SLAB_STR_MAX, - MPR_SLAB_STR_INC); - } else { - newp = mprAllocBlock(MPR_LOC_PASS(ctx, loc), size); - } - - if (newp) { - memcpy(newp, ptr, size); - } - - return newp; -} - -/******************************************************************************/ -/* - * Steal a block from one context and insert in another - */ - -int mprStealAllocBlock(MPR_LOC_DEC(ctx, loc), const void *ptr) -{ - MprBlk *bp, *parent; - - if (ptr == 0) { - return 0; - } - - mprAssert(VALID_BLK(ctx)); - mprAssert(VALID_BLK(ptr)); - - bp = GET_HDR(ptr); - -#if BLD_DEBUG && !BREW - if (bp == stopAlloc) { - mprBreakpoint(MPR_LOC, "breakOnAddr"); - } -#endif - - mprAssert(bp); - mprAssert(VALID_HDR(bp)); - mprAssert(ptr != mprGetAllocParent(ptr)); - - CHECK_HDR(bp); - - mprAssert(bp->prev); - mprAssert(bp->prev->next); - mprAssert(bp->next); - mprAssert(bp->next->prev); - - parent = bp->parent; - mprAssert(VALID_HDR(parent)); - - mprLock(bp->app->allocLock); - if (parent->children == bp) { - if (bp->next == bp) { - parent->children = 0; - } else { - parent->children = bp->next; - } - } - - bp->prev->next = bp->next; - bp->next->prev = bp->prev; - - parent = GET_HDR(ctx); - mprAssert(VALID_HDR(parent)); - bp->parent = parent; - - if (parent->children == 0) { - parent->children = bp; - bp->next = bp->prev = bp; - - } else { - bp->next = parent->children; - bp->prev = parent->children->prev; - parent->children->prev->next = bp; - parent->children->prev = bp; - } - -#if BLD_FEATURE_ALLOC_LEAK_TRACK - bp->location = loc; -#endif - - VALIDATE_BLOCK(GET_PTR(bp)); - - mprUnlock(bp->app->allocLock); - - return 0; -} - -/******************************************************************************/ - -void mprSetRequiredAlloc(MprCtx ptr, bool recurse) -{ - MprBlk *bp, *firstChild, *cp; - - bp = GET_HDR(ptr); - - bp->flags |= ALLOC_FLAGS_REQUIRED; - - if (recurse && (firstChild = bp->children) != 0) { - cp = firstChild; - do { - mprSetRequiredAlloc(GET_PTR(cp), recurse); - cp = cp->next; - } while (cp != firstChild); - } -} - -/******************************************************************************/ -/* - * Monitor stack usage. Return true if the stack has grown - */ - -int mprStackCheck(MprCtx ptr) -{ - MprApp *app; - int size; - - mprAssert(VALID_BLK(ptr)); - - app = mprGetApp(ptr); - - size = (int) app->stackStart - (int) &app; - if (size < 0) { - app->maxStack -= size; - app->stackStart = (void*) &app; - size = 0; - } - if ((uint) size > app->maxStack) { - app->maxStack = size; - return 1; - } - return 0; -} - -/******************************************************************************/ -/* - * Return the stack size - */ - -int mprStackSize(MprCtx ptr) -{ - MprApp *app; - - mprAssert(VALID_BLK(ptr)); - - app = mprGetApp(ptr); - return app->maxStack; -} - -/******************************************************************************/ - -static int mprAllocException(MPR_LOC_DEC(ctx, loc), uint size, bool granted) -{ - MprApp *app; - MprAlloc *alloc; - int rc; - - mprAssert(VALID_BLK(ctx)); - - app = mprGetApp(ctx); - alloc = &app->alloc; - - if (alloc->cback == 0) { - return 0; - } - - mprLock(app->allocLock); - if (alloc->inAllocException == 0) { - alloc->inAllocException = 1; - mprUnlock(app->allocLock); - - rc = (alloc->cback)(app, size, alloc->stats.bytesAllocated, granted); - - mprLock(app->allocLock); - app->alloc.inAllocException = 0; - mprUnlock(app->allocLock); - - return rc; - } - return 0; -} - -/******************************************************************************/ - -void mprSetAllocLimits(MprApp *app, uint redLine, uint maxMemory) -{ - app->alloc.stats.redLine = redLine; - app->alloc.stats.maxMemory = maxMemory; -} - -/******************************************************************************/ - -MprAllocCback mprSetAllocCallback(MprApp *app, MprAllocCback cback) -{ - MprAllocCback old; - - mprAssert(app); - mprAssert(VALID_BLK(app)); - - old = app->alloc.cback; - app->alloc.cback = cback; - return old; -} - -/******************************************************************************/ - -uint mprGetAllocBlockSize(MprCtx ptr) -{ - MprBlk *bp; - - mprAssert(VALID_BLK(ptr)); - - if (ptr == 0) { - return 0; - } - - bp = GET_HDR(ptr); - mprAssert(VALID_HDR(bp)); - - CHECK_HDR(bp); - - return bp->size; -} - -/******************************************************************************/ -/* - * Return the total block count used by a block including all children - */ - -uint mprGetAllocBlockCount(MprCtx ptr) -{ - MprBlk *bp, *firstChild, *cp; - uint count; - - mprAssert(VALID_BLK(ptr)); - - if (ptr == 0) { - return 0; - } - - bp = GET_HDR(ptr); - mprAssert(VALID_HDR(bp)); - - /* - * Add one for itself - */ - count = 1; - if ((firstChild = bp->children) != 0) { - cp = firstChild; - do { - count += mprGetAllocBlockCount(GET_PTR(cp)); - cp = cp->next; - } while (cp != firstChild); - } - return count; -} - -/******************************************************************************/ -/* - * Return the total of all memory allocated including slabs - */ - -uint mprGetAllocBlockMemory(MprCtx ptr) -{ - MprBlk *bp, *firstChild, *cp; - uint count; - - mprAssert(VALID_BLK(ptr)); - - if (ptr == 0) { - return 0; - } - - bp = GET_HDR(ptr); - mprAssert(VALID_HDR(bp)); - - count = bp->size + HDR_SIZE; - if ((firstChild = bp->children) != 0) { - cp = firstChild; - do { - count += mprGetAllocBlockMemory(GET_PTR(cp)); - cp = cp->next; - } while (cp != firstChild); - } - return count; -} - -/******************************************************************************/ -#if BLD_FEATURE_ALLOC_LEAK_TRACK - -const char *mprGetAllocLocation(MprCtx ptr) -{ - MprBlk *bp; - - if (ptr == 0) { - return 0; - } - mprAssert(VALID_BLK(ptr)); - - bp = GET_HDR(ptr); - mprAssert(VALID_HDR(bp)); - return bp->location; -} - -#endif -/******************************************************************************/ - -void *mprGetAllocParent(MprCtx ptr) -{ - MprBlk *bp; - - mprAssert(VALID_BLK(ptr)); - - if (ptr == 0) { - return 0; - } - - bp = GET_HDR(ptr); - mprAssert(VALID_HDR(bp)); - - CHECK_HDR(bp); - - return GET_PTR(bp->parent); -} - -/******************************************************************************/ - -MprAllocStats *mprGetAllocStats(MprApp *app) -{ - mprAssert(VALID_BLK(app)); - - return &app->alloc.stats; -} - -/******************************************************************************/ -#if BLD_FEATURE_ALLOC_STATS - -MprSlabStats *mprGetSlabAllocStats(MprApp *app, int slabIndex) -{ - MprSlab *slab; - - mprAssert(VALID_BLK(app)); - - if (0 <= slabIndex && slabIndex < MPR_MAX_SLAB) { - slab = &app->alloc.slabs[slabIndex]; - return &slab->stats; - } - - mprAssert(0 <= slabIndex && slabIndex < MPR_MAX_SLAB); - return 0; -} - -#endif /* BLD_FEATURE_ALLOC_STATS */ -/******************************************************************************/ -#if BLD_DEBUG - -int mprPrintAllocBlocks(MprCtx ptr, int indent) -{ - MprBlk *bp, *firstChild, *cp; - const char *location; - int subTotal, size, indentSpaces, code; - - subTotal = 0; - - bp = GET_HDR(ptr); - - if (! (bp->flags & ALLOC_FLAGS_REQUIRED)) { - size = bp->size + HDR_SIZE; - - /* - * Take one level off because we don't trace app - */ - indentSpaces = indent; - - if (bp->flags & ALLOC_FLAGS_REQUIRED) { - code = 'R'; - } else if (bp->flags & ALLOC_FLAGS_IS_SLAB) { - code = 'S'; - } else { - code = ' '; - } - -#if BLD_FEATURE_ALLOC_LEAK_TRACK - location = bp->location; -#else - location = ""; -#endif - mprLog(bp->app, 0, - "%c %.*s %-16s %.*s size %5d has %3d deps, total %6d", code, - indentSpaces, " ", - mprGetBaseName(location), - 8 - indent, " ", - size, - mprGetAllocBlockCount(GET_PTR(bp)), - mprGetAllocBlockMemory(GET_PTR(bp)) - /* (uint) bp */ - ); - - subTotal += size; - } - - if ((firstChild = bp->children) != 0) { - cp = firstChild; - do { - subTotal += mprPrintAllocBlocks(GET_PTR(cp), indent + 2); - cp = cp->next; - } while (cp != firstChild); - } - - return subTotal; -} - -#endif -/******************************************************************************/ -#if BLD_FEATURE_ALLOC_STATS -/* - * Print a memory allocation report that includes a list of allocated blocks - * and a statistics summary - */ - -void mprPrintAllocReport(MprApp *app, bool printBlocks, const char *msg) -{ - MprSlabStats *stats; - uint total; - int i, size; - - mprAssert(VALID_BLK(app)); - - if (msg) { - mprLog(app, 0, " "); - mprLog(app, 0, "%s", msg); - } - -#if BLD_DEBUG - /* - * Do block stats - */ - if (printBlocks) { - int sum; - mprLog(app, 0, " "); - sum = mprPrintAllocBlocks(app, 0); - if (sum) { - mprLog(app, 0, " Sum of blocks %d", sum); - } else { - mprLog(app, 0, " None"); - } - } -#endif - - /* - * Do Slab stats - */ - mprLog(app, 0, " "); - mprLog(app, 0, "MPR Slab Memory Stats"); - mprLog(app, 0, " "); - - mprLog(app, 0, - " Index Size Total Allocated Free PeakAlloc PeakFree TotalAlloc"); - - total = 0; - for (i = 0; i < MPR_MAX_SLAB; i++) { - stats = &app->alloc.slabs[i].stats; - size = 1 << (i + 5); - if (stats->totalAllocCount > 0) { - mprLog(app, 0, " %2d %6d %8d %9d %6d %9d %8d %10d", - i, size, size * (stats->allocCount + stats->freeCount), - stats->allocCount, stats->freeCount, - stats->peakAllocCount, stats->peakFreeCount, - stats->totalAllocCount); - total += size * (stats->allocCount + stats->freeCount); - } - } - mprLog(app, 0, " "); - mprLog(app, 0, "MPR Total Allocated Slab RAM: %10d", total); - mprLog(app, 0, "MPR Total Allocated RAM: %10d", - mprGetAllocatedMemory(app)); - mprLog(app, 0, "MPR Peak Allocated RAM: %10d", - mprGetPeakAllocatedMemory(app)); - mprLog(app, 0, " "); -} - -/******************************************************************************/ -/* - * Return the total memory allocated. - */ - -uint mprGetAllocatedMemory(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - - return app->alloc.stats.bytesAllocated; -} - -/******************************************************************************/ -/* - * Return the peak memory allocated. - */ - -uint mprGetPeakAllocatedMemory(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - - return app->alloc.stats.peakAllocated; -} - -/******************************************************************************/ -/* - * Return memory in the MPR slab. This excludes the EJS slabs - */ - -uint mprGetAllocatedSlabMemory(MprCtx ctx) -{ - MprApp *app; - MprSlabStats *stats; - uint total; - int i, size; - - app = mprGetApp(ctx); - - total = 0; - for (i = 0; i < MPR_MAX_SLAB; i++) { - stats = &app->alloc.slabs[i].stats; - size = 1 << (i + 5); - if (stats->totalAllocCount > 0) { - total += size * (stats->allocCount + stats->freeCount); - } - } - return total; -} - -#endif /* BLD_FEATURE_ALLOC_STATS */ -/******************************************************************************/ - -MprDestructor mprSetDestructor(MprCtx ptr, MprDestructor destructor) -{ - MprDestructor old; - MprBlk *bp; - - mprAssert(VALID_BLK(ptr)); - - if (ptr == 0) { - return 0; - } - - bp = GET_HDR(ptr); - - mprAssert(bp); - mprAssert(VALID_HDR(bp)); - mprAssert(ptr != mprGetAllocParent(ptr)); - - CHECK_HDR(bp); - - old = bp->destructor; - bp->destructor = destructor; - - return old; -} - -/******************************************************************************/ - -int mprIsAllocBlockValid(MprCtx ptr) -{ - MprBlk *bp; - - bp = GET_HDR(ptr); - return (bp && VALID_HDR(bp)); -} - -/******************************************************************************/ -#if VALIDATE_ALLOC -/* - * Exhaustive validation of the block and its children. Does not go recursive - * as it would be too slow. - */ - -int mprValidateBlock(MprCtx ptr) -{ - MprBlk *bp, *parent, *cp, *firstChild; - int count; - - mprAssert(ptr); - mprAssert(VALID_BLK(ptr)); - - bp = GET_HDR(ptr); - - mprAssert(bp); - mprAssert(VALID_HDR(bp)); - mprAssert(VALID_HDR(bp->parent)); - - if (ptr != bp->app) { - mprAssert(bp != bp->parent); - } - mprAssert(! (bp->flags & ALLOC_FLAGS_FREE)); - mprAssert(! (bp->flags & ALLOC_FLAGS_FREEING)); - - /* - * - */ - count = 0; - parent = bp->parent; - - if ((firstChild = bp->children) != 0) { - cp = firstChild; - mprAssert((int) cp != 0xfeefee); - do { - mprAssert(bp->next->prev == bp); - mprAssert(bp->prev->next == bp); - mprAssert(bp->prev->parent == parent); - mprAssert(bp->next->parent == parent); - - count++; - cp = cp->next; - - if (bp->next == bp) { - mprAssert(bp->prev == bp); - if (ptr != bp->app) { - mprAssert(parent->children == bp); - } - } - if (bp->prev == bp) { - mprAssert(bp->next == bp); - if (ptr != bp->app) { - mprAssert(parent->children == bp); - } - } - } while (cp != firstChild); - } - - return 0; -} - -#endif -/******************************************************************************/ -/* - * Validate a block and all children - */ - -int mprValidateAllocTree(MprCtx ptr) -{ -#if VALIDATE_ALLOC - MprBlk *bp, *cp, *firstChild; - - mprAssert(ptr); - mprAssert(VALID_BLK(ptr)); - - bp = GET_HDR(ptr); - - mprValidateBlock(GET_PTR(bp)); - - if ((firstChild = bp->children) != 0) { - cp = firstChild; - do { - mprValidateAllocTree(GET_PTR(cp)); - cp = cp->next; - } while (cp != firstChild); - } - -#endif - return 0; -} - -/******************************************************************************/ -#if UNUSED && FUTURE -/* - * Exhaustive validation of the block and its children. Does not go recursive - * as it would be too slow. - */ - -int mprValidateSlabs(MprApp *app) -{ - MprSlab *slab; - MprSlabStats *slabStats; - MprSlabBlock *sp; - int count, i; - - for (i = 0; i < MPR_MAX_SLAB; i++) { - slab = &app->alloc.slabs[i]; - slabStats = &slab->stats; - - count = 0; - for (sp = slab->next; sp; sp = sp->next) { - count++; - } - mprAssert(count == (int) slabStats->freeCount); - } - return 0; -} - -#endif -/******************************************************************************/ - -void mprAllocAbort() -{ -#if BREW - printf("Bad block header"); -#else - exit(255); -#endif -} - -/******************************************************************************/ -#undef mprGetApp -/* - * Get the root parent from any block (which is the MprApp structure) - */ - -MprApp *mprGetApp(MprCtx ptr) -{ - MprBlk *bp; - - mprAssert(ptr); - - bp = GET_HDR(ptr); - mprAssert(VALID_HDR(bp)); - - CHECK_HDR(bp); - - mprAssert(bp->app->magic == APP_MAGIC); - - return bp->app; -} - -/******************************************************************************/ - -int mprGetAllocErrors(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - return app->alloc.stats.errors; -} - -/******************************************************************************/ - -void mprClearAllocErrors(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - app->alloc.stats.errors = 0; -} - -/******************************************************************************/ -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/mprArray.c b/source4/lib/appweb/ejs-2.0/mpr/mprArray.c deleted file mode 100644 index 95b0a14450..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mprArray.c +++ /dev/null @@ -1,385 +0,0 @@ -/** - * @file mprArray.c - * @brief Growable array structure - * @overview Simple growable array structure. - * @remarks Most routines in this file are not thread-safe. It is the callers - * responsibility to perform all thread synchronization. - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************** Includes **********************************/ - -#include "mpr.h" - -/******************************************************************************/ -/* - * Create a general growable array structure. Use mprFree to destroy. - */ - -MprArray *mprCreateItemArrayInternal(MPR_LOC_DEC(ctx, loc), int initialSize, - int maxSize) -{ - MprArray *array; - int size; - - mprAssert(initialSize <= maxSize); - - array = (MprArray*) mprSlabAllocZeroedBlock(MPR_LOC_PASS(ctx, loc), - sizeof(MprArray), 0); - if (array == 0) { - return 0; - } - - if (initialSize == 0) { - initialSize = MPR_ARRAY_INCR; - } - if (maxSize == 0) { - maxSize = MAXINT; - } - size = initialSize * sizeof(void*); - - array->items = (void**) mprSlabAllocBlock(MPR_LOC_PASS(array, loc), - size, 0); - - if (array->items == 0) { - mprFree(array); - return 0; - } - - array->capacity = initialSize; - array->maxSize = maxSize; - array->incr = min(initialSize * 2, (array->maxSize - array->length)); - array->length = 0; - - return array; -} - -/******************************************************************************/ -/* - * Add an item to the array - */ - -int mprAddItem(MprArray *array, void *item) -{ - int memsize, index, len; - - mprAssert(array); - mprAssert(array->capacity >= 0); - mprAssert(array->length >= 0); - - if (array->length < array->capacity) { - /* - * Room to fit in the current capacity - */ - index = array->length++; - array->items[index] = item; - return index; - } - mprAssert(array->length == array->capacity); - - /* - * Need to grow the array - */ - if (array->capacity >= array->maxSize) { - mprAssert(array->capacity < array->maxSize); - return MPR_ERR_TOO_MANY; - } - - len = array->capacity + array->incr; - memsize = len * sizeof(void*); - - /* - * Grow the array of items - */ - - array->items = (void**) mprRealloc(array, array->items, memsize); - - /* - * Zero the new portion - */ - memset(&array->items[array->capacity], 0, sizeof(void*) * array->incr); - array->capacity = len; - - array->incr = min(array->incr * 2, (array->maxSize - array->length)); - - index = array->length++; - array->items[index] = item; - - return index; -} - -/******************************************************************************/ -/* - * Remove an item from the array - */ - -int mprRemoveItem(MprArray *array, void *item) -{ - int index; - - mprAssert(array); - mprAssert(array->capacity > 0); - mprAssert(array->length > 0); - - index = mprFindItem(array, item); - if (index < 0) { - return index; - } - - return mprRemoveItemByIndex(array, index); -} - -/******************************************************************************/ -/* - * Remove an index from the array - */ - -int mprRemoveItemByIndex(MprArray *array, int index) -{ - void **items; - int i; - - mprAssert(array); - mprAssert(array->capacity > 0); - mprAssert(index >= 0 && index < array->capacity); - mprAssert(array->items[index] != 0); - mprAssert(array->length > 0); - - if (index < 0 || index >= array->length) { - return MPR_ERR_NOT_FOUND; - } - - /* - * Copy down to compress - */ - items = array->items; - for (i = index; i < (array->length - 1); i++) { - items[i] = items[i + 1]; - } - array->length--; - -#if BLD_DEBUG - if (array->length < array->capacity) { - items[array->length] = 0; - } -#endif - return 0; -} - -/******************************************************************************/ - -int mprRemoveRangeOfItems(MprArray *array, int start, int end) -{ - void **items; - int i, count; - - mprAssert(array); - mprAssert(array->capacity > 0); - mprAssert(array->length > 0); - mprAssert(start > end); - - if (start < 0 || start >= array->length) { - return MPR_ERR_NOT_FOUND; - } - if (end < 0 || end >= array->length) { - return MPR_ERR_NOT_FOUND; - } - if (start > end) { - return MPR_ERR_BAD_ARGS; - } - - /* - * Copy down to compress - */ - items = array->items; - count = end - start; - for (i = start; i < (array->length - count); i++) { - items[i] = items[i + count]; - } - array->length -= count; - -#if BLD_DEBUG - if (array->length < array->capacity) { - for (i = array->length; i < array->capacity; i++) { - items[i] = 0; - } - } -#endif - return 0; -} - -/******************************************************************************/ - -void *mprGetItem(MprArray *array, int index) -{ - mprAssert(array); - - if (index < 0 || index >= array->length) { - return 0; - } - return array->items[index]; -} - -/******************************************************************************/ - -void *mprGetFirstItem(MprArray *array, int *last) -{ - mprAssert(array); - mprAssert(last); - - if (array == 0) { - return 0; - } - - *last = 0; - - if (array->length == 0) { - return 0; - } - return array->items[0]; -} - -/******************************************************************************/ - -void *mprGetNextItem(MprArray *array, int *last) -{ - int index; - - mprAssert(array); - mprAssert(last); - mprAssert(*last >= 0); - - index = *last; - - if (++index < array->length) { - *last = index; - return array->items[index]; - } - return 0; -} - -/******************************************************************************/ - -void *mprGetPrevItem(MprArray *array, int *last) -{ - int index; - - mprAssert(array); - mprAssert(last); - mprAssert(*last >= 0); - - if (array == 0) { - return 0; - } - - index = *last; - - if (--index < array->length && index >= 0) { - *last = index; - return array->items[index]; - } - return 0; -} - -/******************************************************************************/ - -int mprGetItemCount(MprArray *array) -{ - mprAssert(array); - - if (array == 0) { - return 0; - } - - return array->length; -} - -/******************************************************************************/ - -int mprGetItemCapacity(MprArray *array) -{ - mprAssert(array); - - if (array == 0) { - return 0; - } - - return array->capacity; -} - -/******************************************************************************/ - -void mprClearAndFreeItems(MprArray *array) -{ - int i; - - mprAssert(array); - - for (i = 0; i < array->length; i++) { - mprFree(array->items[i]); - } -} - -/******************************************************************************/ - -void mprClearItems(MprArray *array) -{ - mprAssert(array); - - array->length = 0; -} - -/******************************************************************************/ - -int mprFindItem(MprArray *array, void *item) -{ - int i; - - mprAssert(array); - - for (i = 0; i < array->length; i++) { - if (array->items[i] == item) { - return i; - } - } - return MPR_ERR_NOT_FOUND; -} - -/******************************************************************************/ -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/mprBuf.c b/source4/lib/appweb/ejs-2.0/mpr/mprBuf.c deleted file mode 100644 index ba9888a9fc..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mprBuf.c +++ /dev/null @@ -1,535 +0,0 @@ -/** - * @file mprBuf.c - * @brief Dynamic buffer module - * @overview - * @remarks - */ - -/******************************************************************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - - -/********************************** Includes **********************************/ - -#include "mpr.h" - -/**************************** Forward Declarations ****************************/ - -static int grow(MprBuf *bp); - -/*********************************** Code *************************************/ -/* - * Create a new buffer. "maxsize" is the limit to which the buffer can - * ever grow. -1 means no limit. The buffer can ever only fix maxsize-1 bytes. - * "initialSize" is used to define the amount to increase the size of the - * buffer each time if it becomes full. (Note: grow() will exponentially - * increase this number for performance.) - */ - -MprBuf *mprCreateBuf(MprCtx ctx, int initialSize, int maxSize) -{ - MprBuf *bp; - - if (initialSize <= 0) { - initialSize = MPR_DEFAULT_ALLOC; - } - bp = mprAllocTypeZeroed(ctx, MprBuf); - bp->growBy = MPR_BUFSIZE; - bp->maxsize = 0; - mprSetBufSize(bp, initialSize, maxSize); - return bp; -} - -/******************************************************************************/ -/* - * Set the initial buffer parameters and create the first buffer - */ - -void mprSetBufSize(MprBuf *bp, int initialSize, int max) -{ - mprAssert(initialSize > 0); - - if (max > 0 && initialSize > max) { - initialSize = max; - } - - if (bp->buf && bp->growBy > 0) { - mprFree(bp->buf); - } - - bp->buf = (uchar*) mprAlloc(bp, initialSize); - bp->growBy = initialSize; - bp->maxsize = max; - bp->buflen = initialSize; - bp->endbuf = &bp->buf[bp->buflen]; - bp->start = bp->buf; - bp->end = bp->buf; - *bp->start = '\0'; -} - -/******************************************************************************/ - -char *mprStealBuf(MprCtx ctx, MprBuf *bp) -{ - char *str; - - str = (char*) bp->start; - - mprStealAllocBlock(MPR_LOC_ARGS(ctx), bp->start); - - bp->start = bp->end = bp->buf = bp->endbuf = 0; - bp->buflen = 0; - - return str; -} - -/******************************************************************************/ - -void mprAddNullToBuf(MprBuf *bp) -{ - *((char*) bp->end) = (char) '\0'; -} - -/******************************************************************************/ - -void mprAdjustBufEnd(MprBuf *bp, int size) -{ - mprAssert(bp->buflen == (bp->endbuf - bp->buf)); - mprAssert(size < bp->buflen); - - bp->end += size; - if (bp->end >= bp->endbuf) { - bp->end -= bp->buflen; - } - if (bp->end < bp->buf) { - bp->end += bp->buflen; - } - - if (bp->end >= bp->endbuf) { - mprAssert(bp->end < bp->endbuf); - mprFlushBuf(bp); - } -} - -/******************************************************************************/ -/* - * Adjust the start pointer after a user copy - */ - -void mprAdjustBufStart(MprBuf *bp, int size) -{ - mprAssert(bp->buflen == (bp->endbuf - bp->buf)); - mprAssert(size < bp->buflen); - - bp->start += size; - while (bp->start >= bp->endbuf) { - bp->start -= bp->buflen; - } - while (bp->start < bp->buf) { - bp->start += bp->buflen; - } - - /* - * Flush the buffer if the start pointer is corrupted via a bad size - */ - if (bp->start >= bp->endbuf) { - mprAssert(bp->start < bp->endbuf); - mprFlushBuf(bp); - } -} - - -/******************************************************************************/ - -void mprFlushBuf(MprBuf *bp) -{ - bp->start = bp->buf; - bp->end = bp->buf; -} - -/******************************************************************************/ - -int mprGetCharFromBuf(MprBuf *bp) -{ - int c; - - if (bp->start == bp->end) { - return -1; - } - c = (uchar) *bp->start++; - if (bp->start >= bp->endbuf) { - bp->start = bp->buf; - } - return c; -} - -/******************************************************************************/ - -int mprGetBlockFromBuf(MprBuf *bp, uchar *buf, int size) -{ - int thisLen, bytesRead; - - mprAssert(buf); - mprAssert(size > 0); - mprAssert(bp->buflen == (bp->endbuf - bp->buf)); - - /* - * Get the max bytes in a straight copy - */ - bytesRead = 0; - while (size > 0) { - thisLen = mprGetBufLinearData(bp); - thisLen = min(thisLen, size); - if (thisLen <= 0) { - break; - } - - memcpy(buf, bp->start, thisLen); - buf += thisLen; - bp->start += thisLen; - size -= thisLen; - bytesRead += thisLen; - - if (bp->start >= bp->endbuf) { - bp->start = bp->buf; - } - } - return bytesRead; -} - -/******************************************************************************/ - -int mprGetBufLength(MprBuf *bp) -{ - if (bp->start > bp->end) { - return (bp->buflen + (bp->end - bp->start)); - } else { - return (bp->end - bp->start); - } -} - -/******************************************************************************/ - -int mprGetBufLinearData(MprBuf *bp) -{ - return min(mprGetBufLength(bp), (bp->endbuf - bp->start)); -} - -/******************************************************************************/ - -int mprGetBufLinearSpace(MprBuf *bp) -{ - int len = mprGetBufLength(bp); - int space = bp->buflen - len - 1; - return min((bp->endbuf - bp->end), space); -} - -/******************************************************************************/ - -int mprGetBufSize(MprBuf *bp) -{ - return bp->buflen; -} - -/******************************************************************************/ - -int mprGetBufSpace(MprBuf *bp) -{ - return bp->buflen - mprGetBufLength(bp) - 1; -} - -/******************************************************************************/ - -char *mprGetBufOrigin(MprBuf *bp) -{ - return (char*) bp->buf; -} - -/******************************************************************************/ - -char *mprGetBufStart(MprBuf *bp) -{ - return (char*) bp->start; -} - -/******************************************************************************/ - -char *mprGetBufEnd(MprBuf *bp) -{ - return (char*) bp->end; -} - -/******************************************************************************/ - -int mprInsertCharToBuf(MprBuf *bp, int c) -{ - char *cp; - int space; - - mprAssert(bp->buflen == (bp->endbuf - bp->buf)); - - space = bp->buflen - mprGetBufLength(bp) - 1; - if (space < (int) sizeof(char)) { - if (!grow(bp)) { - return -1; - } - } - if (bp->start <= bp->buf) { - bp->start = bp->endbuf; - } - cp = (char*) bp->start; - *--cp = (char) c; - bp->start = (uchar *) cp; - return 0; -} - -/******************************************************************************/ - -int mprLookAtNextCharInBuf(MprBuf *bp) -{ - if (bp->start == bp->end) { - return -1; - } - return *bp->start; -} - -/******************************************************************************/ - -int mprLookAtLastCharInBuf(MprBuf *bp) -{ - if (bp->start == bp->end) { - return -1; - } - return (bp->end == bp->buf) ? bp->endbuf[-1] : bp->end[-1]; -} - -/******************************************************************************/ - -int mprPutCharToBuf(MprBuf *bp, int c) -{ - char *cp; - int space; - - mprAssert(bp->buflen == (bp->endbuf - bp->buf)); - - space = bp->buflen - mprGetBufLength(bp) - 1; - if (space < (int) sizeof(char)) { - if (! grow(bp)) { - return -1; - } - } - - cp = (char*) bp->end; - *cp++ = (char) c; - bp->end = (uchar *) cp; - if (bp->end >= bp->endbuf) { - bp->end = bp->buf; - } - *((char*) bp->end) = (char) '\0'; - return 0; -} - -/******************************************************************************/ - -int mprPutBlockToBuf(MprBuf *bp, const char *str, int size) -{ - int thisLen, bytes, space; - - mprAssert(str); - mprAssert(size >= 0); - mprAssert(bp->buflen == (bp->endbuf - bp->buf)); - - /* - * Add the max we can in one copy - */ - bytes = 0; - while (size > 0) { - space = mprGetBufLinearSpace(bp); - thisLen = min(space, size); - if (thisLen <= 0) { - if (! grow(bp)) { - break; - } - space = mprGetBufLinearSpace(bp); - thisLen = min(space, size); - } - - memcpy(bp->end, str, thisLen); - str += thisLen; - bp->end += thisLen; - size -= thisLen; - bytes += thisLen; - - if (bp->end >= bp->endbuf) { - bp->end = bp->buf; - } - } - *((char*) bp->end) = (char) '\0'; - return bytes; -} - -/******************************************************************************/ - -int mprPutStringToBuf(MprBuf *bp, const char *str) -{ - return mprPutBlockToBuf(bp, str, strlen(str)); -} - -/******************************************************************************/ - -int mprPutFmtStringToBuf(MprBuf *bp, const char *fmt, ...) -{ - va_list ap; - char *buf; - int rc, len, space; - - va_start(ap, fmt); - space = mprGetBufLinearSpace(bp); - - /* - * Add max that the buffer can grow - */ - space += (bp->maxsize - bp->buflen - 1); - - len = mprAllocVsprintf(MPR_LOC_ARGS(bp), &buf, space, fmt, ap); - rc = mprPutBlockToBuf(bp, buf, len); - - mprFree(buf); - va_end(ap); - return rc; -} - -/******************************************************************************/ -/* - * Grow the buffer to fit new data. Return 1 if the buffer can grow. - * Grow using the growBy size specified when creating the buffer. - */ - -static int grow(MprBuf *bp) -{ - uchar *newbuf; - - if (bp->maxsize > 0 && bp->buflen >= bp->maxsize) { - return 0; - } - - newbuf = (uchar*) mprAlloc(bp, bp->buflen + bp->growBy); - if (bp->buf) { - memcpy(newbuf, bp->buf, bp->buflen); - mprFree(bp->buf); - } - - bp->buflen += bp->growBy; - bp->end = newbuf + (bp->end - bp->buf); - bp->start = newbuf + (bp->start - bp->buf); - bp->buf = newbuf; - bp->endbuf = &bp->buf[bp->buflen]; - - /* - * Increase growBy to reduce overhead - */ - bp->growBy *= 2; - if (bp->maxsize > 0 && (bp->buflen + bp->growBy) > bp->maxsize) { - bp->growBy = bp->maxsize - bp->buflen; - } - return 1; -} - -/******************************************************************************/ -/* - * Add a number to the buffer (always null terminated). - */ - -int mprPutIntToBuf(MprBuf *bp, int i) -{ - char numBuf[16]; - int rc; - - mprItoa(numBuf, sizeof(numBuf), i); - rc = mprPutStringToBuf(bp, numBuf); - *((char*) bp->end) = (char) '\0'; - - return rc; -} - -/******************************************************************************/ - -void mprCopyBufDown(MprBuf *bp) -{ - if (mprGetBufLength(bp) == 0) { - mprFlushBuf(bp); - return; - } - memmove(bp->buf, bp->start, (bp->end - bp->start)); - bp->end -= (bp->start - bp->buf); - bp->start = bp->buf; -} - -/******************************************************************************/ - -MprBufProc mprGetBufRefillProc(MprBuf *bp) -{ - return bp->refillProc; -} - -/******************************************************************************/ - -void mprSetBufRefillProc(MprBuf *bp, MprBufProc fn, void *arg) -{ - bp->refillProc = fn; - bp->refillArg = arg; -} - -/******************************************************************************/ - -int mprRefillBuf(MprBuf *bp) -{ - return (bp->refillProc) ? (bp->refillProc)(bp, bp->refillArg) : 0; -} - -/******************************************************************************/ - -void mprResetBufIfEmpty(MprBuf *bp) -{ - if (mprGetBufLength(bp) == 0) { - mprFlushBuf(bp); - } -} - -/******************************************************************************/ -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/mprGenFile.c b/source4/lib/appweb/ejs-2.0/mpr/mprGenFile.c deleted file mode 100644 index 517e43853f..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mprGenFile.c +++ /dev/null @@ -1,336 +0,0 @@ -/** - * @file mprGenFile.c - * @brief Generic File services - * @overview - * @remarks - * See OS/mprFile.c for the per O/S portions - */ - -/******************************************************************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************** Includes **********************************/ - -#include "mpr.h" - -/****************************** Forward Declarations **************************/ -#if !BREW - -static int closeDestructor(void *data); - -/************************************ Code ************************************/ - -int mprStartFileServices(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - app->console = mprAllocTypeZeroed(ctx, MprFile); - app->error = mprAllocTypeZeroed(ctx, MprFile); - - /* - * We assume that STDOUT is 1 and STDERR is 2 - */ - app->console->fd = 1; - app->error->fd = 2; - - return 0; -} - -/******************************************************************************/ - -void mprStopFileServices(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - - mprFree(app->console); - app->console = 0; - mprFree(app->error); - app->error = 0; -} - -/******************************************************************************/ - -MprFile *mprOpen(MprCtx ctx, const char *path, int omode, int perms) -{ - MprFile *file; - - mprAssert(path && *path); - - file = mprAllocTypeZeroed(ctx, MprFile); - - file->fd = open(path, omode, perms); - if (file->fd < 0) { - mprFree(file); - return 0; - } - - mprSetDestructor(file, closeDestructor); - return file; -} - -/******************************************************************************/ - -static int closeDestructor(void *data) -{ - MprFile *file = (MprFile*) data; - - mprAssert(file); - - mprClose(file); - return 0; -} - -/******************************************************************************/ - -void mprClose(MprFile *file) -{ - mprAssert(file); - - if (file < 0) { - return; - } - - mprAssert(file->fd >= 0); - close(file->fd); - - mprSetDestructor(file, 0); - mprFree(file); -} - -/******************************************************************************/ - -int mprRead(MprFile *file, void *buf, uint size) -{ - mprAssert(file); - - if (file == 0) { - return MPR_ERR_BAD_HANDLE; - } - - return read(file->fd, buf, size); -} - -/******************************************************************************/ - -int mprWrite(MprFile *file, const void *buf, uint count) -{ - mprAssert(file); - - if (file == 0) { - return MPR_ERR_BAD_HANDLE; - } - - return write(file->fd, buf, count); -} - -/******************************************************************************/ - -int mprSeek(MprFile *file, int seekType, long distance) -{ - mprAssert(file); - - if (file == 0) { - return MPR_ERR_BAD_HANDLE; - } - - return lseek(file->fd, seekType, distance); -} - -/******************************************************************************/ - -int mprDelete(MprCtx ctx, const char *path) -{ - return unlink(path); -} - -/******************************************************************************/ - -int mprDeleteDir(MprCtx ctx, const char *path) -{ - return rmdir(path); -} - -#endif /* !BREW */ -/******************************************************************************/ - -char *mprGets(MprFile *file, char *buf, uint size) -{ - MprBuf *bp; - int count, len, c; - - mprAssert(file); - - if (file == 0) { - return 0; - } - - if (file->buf == 0) { - file->buf = mprCreateBuf(file, MPR_DEFAULT_ALLOC, MPR_MAX_STRING); - } - bp = file->buf; - - /* - * Must leave room for null - */ - count = 0; - while (--size > 0) { - if (mprGetBufLength(bp) == 0) { - mprFlushBuf(bp); - len = mprRead(file, mprGetBufEnd(bp), - mprGetBufLinearSpace(bp)); - if (len <= 0) { - return 0; - } - mprAdjustBufEnd(bp, len); - mprAddNullToBuf(bp); - } - if ((c = mprGetCharFromBuf(bp)) == '\n') { - buf[count] = '\0'; - return buf; - } - buf[count++] = c; - } - buf[count] = '\0'; - return buf; -} - -/******************************************************************************/ - -int mprPuts(MprFile *file, const char *writeBuf, uint count) -{ - MprBuf *bp; - char *buf; - int total, bytes, len; - - mprAssert(file); - - /* - * Buffer output and flush when full. - */ - if (file->buf == 0) { - file->buf = mprCreateBuf(file, MPR_BUFSIZE, 0); - if (file->buf == 0) { - return MPR_ERR_CANT_ALLOCATE; - } - } - bp = file->buf; - - if (mprGetBufLength(bp) > 0 && mprGetBufSpace(bp) < (int) count) { - len = mprGetBufLength(bp); - if (mprWrite(file, mprGetBufStart(bp), len) != len) { - return MPR_ERR_CANT_WRITE; - } - mprFlushBuf(bp); - } - - total = 0; - buf = (char*) writeBuf; - - while (count > 0) { - bytes = mprPutBlockToBuf(bp, buf, count); - if (bytes <= 0) { - return MPR_ERR_CANT_ALLOCATE; - } - count -= bytes; - buf += bytes; - total += bytes; - mprAddNullToBuf(bp); - - if (count > 0) { - len = mprGetBufLength(bp); - if (mprWrite(file, mprGetBufStart(bp), len) != len) { - return MPR_ERR_CANT_WRITE; - } - mprFlushBuf(bp); - } - } - return total; -} - -/******************************************************************************/ - -int mprMakeTempFileName(MprCtx ctx, char *buf, int bufsize, const char *tempDir) -{ - MprFile *file; - MprTime now; - char *dir; - int seed, i; - - if (tempDir == 0) { -#if WIN - char *cp; - dir = mprStrdup(ctx, getenv("TEMP")); - for (cp = dir; *cp; cp++) { - if (*cp == '\\') { - *cp = '/'; - } - } -#else - dir = mprStrdup(ctx, "/tmp"); -#endif - } else { - dir = mprStrdup(ctx, tempDir); - } - - mprGetTime(ctx, &now); - seed = now.msec % 64000; - file = 0; - - for (i = 0; i < 128; i++) { - mprSprintf(buf, bufsize, "%s/MPR_%d_%d.tmp", dir, getpid(), seed++); - file = mprOpen(ctx, buf, O_CREAT | O_EXCL | O_BINARY, 0664); - if (file) { - break; - } - } - - if (file == 0) { - return MPR_ERR_CANT_CREATE; - } - - mprClose(file); - mprFree(dir); - - return 0; -} - -/******************************************************************************/ -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/mprGenTime.c b/source4/lib/appweb/ejs-2.0/mpr/mprGenTime.c deleted file mode 100644 index 6b0ed97bbc..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mprGenTime.c +++ /dev/null @@ -1,195 +0,0 @@ -/** - * @file mprGenTime.c - * @brief Generic Time handling - * @overview - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************* Includes ***********************************/ - -#include "mpr.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/******************************************************************************/ -/* - * Return the number of milliseconds until the given timeout has expired. - */ - -int mprGetTimeRemaining(MprCtx ctx, MprTime mark, uint timeout) -{ - MprTime now; - uint diff; - - mprGetTime(ctx, &now); - diff = ((now.sec - mark.sec) * 1000) + (now.msec - mark.msec); - - if (diff < 0) { - /* - * Detect time going backwards - */ - mprAssert(diff >= 0); - diff = 0; - } - return (int) (timeout - diff); -} - -/******************************************************************************/ -/* - * Return the number of milliseconds until the given timeout has expired. - */ - -int mprGetElapsedTime(MprCtx ctx, MprTime mark) -{ - MprTime now; - - mprGetTime(ctx, &now); - return ((now.sec - mark.sec) * 1000) + (now.msec - mark.msec); -} - -/******************************************************************************/ - -void mprAddElapsedToTime(MprTime *time, uint elapsed) -{ - time->sec += elapsed / 1000; - time->msec += elapsed % 1000; - if (time->msec > 1000) { - time->msec -= 1000; - time->sec++; - } -} - -/******************************************************************************/ - -int mprCompareTime(MprTime *t1, MprTime *t2) -{ - if (t1->sec < t2->sec) { - return -1; - } else if (t1->sec == t2->sec) { - if (t1->msec < t2->msec) { - return -1; - } else if (t1->msec == t2->msec) { - return 0; - } - } - return 1; -} - -/******************************************************************************/ - -uint mprSubtractTime(MprTime *t1, MprTime *t2) -{ - return ((t1->sec - t2->sec) * 1000) + (t1->msec - t2->msec); -} - -/******************************************************************************/ -#if !BREW -/* - * Thread-safe RFC822 dates (Eg: "Fri, 07 Jan 2003 12:12:21 GMT") - */ - -int mprRfcTime(MprCtx ctx, char *buf, int bufsize, const struct tm *timep) -{ - char months[12][4] = { - "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", - "Oct", "Nov", "Dec" - }; - - char days[7][4] = { - "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" - }; - - char *dayp, *monthp; - int year; - - if (bufsize < 30) { - return MPR_ERR_WONT_FIT; - } - dayp = &days[timep->tm_wday][0]; - *buf++ = *dayp++; - *buf++ = *dayp++; - *buf++ = *dayp++; - *buf++ = ','; - *buf++ = ' '; - - *buf++ = timep->tm_mday / 10 + '0'; - *buf++ = timep->tm_mday % 10 + '0'; - *buf++ = ' '; - - monthp = &months[timep->tm_mon][0]; - *buf++ = *monthp++; - *buf++ = *monthp++; - *buf++ = *monthp++; - *buf++ = ' '; - - year = 1900 + timep->tm_year; - /* This routine isn't y10k ready. */ - *buf++ = year / 1000 + '0'; - *buf++ = year % 1000 / 100 + '0'; - *buf++ = year % 100 / 10 + '0'; - *buf++ = year % 10 + '0'; - *buf++ = ' '; - - *buf++ = timep->tm_hour / 10 + '0'; - *buf++ = timep->tm_hour % 10 + '0'; - *buf++ = ':'; - *buf++ = timep->tm_min / 10 + '0'; - *buf++ = timep->tm_min % 10 + '0'; - *buf++ = ':'; - *buf++ = timep->tm_sec / 10 + '0'; - *buf++ = timep->tm_sec % 10 + '0'; - *buf++ = ' '; - - *buf++ = 'G'; - *buf++ = 'M'; - *buf++ = 'T'; - *buf++ = 0; - return 0; -} - -#endif -/******************************************************************************/ - -#ifdef __cplusplus -} -#endif - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/mprLock.c b/source4/lib/appweb/ejs-2.0/mpr/mprLock.c deleted file mode 100644 index df9ce276d4..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mprLock.c +++ /dev/null @@ -1,266 +0,0 @@ -/** - * @file mprThread.c - * @brief Mbedthis Portable Runtime Base Thread Locking Support - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -#include "mpr.h" - -#if BLD_FEATURE_MULTITHREAD -/************************************ Code ************************************/ - -void mprInitThreads(MprApp *app) -{ - mprAssert(app); - - if (app->globalLock == 0) { - app->globalLock = mprCreateLock(app); - app->allocLock = mprCreateLock(app); - } -} - -/******************************************************************************/ - -void mprTermThreads(MprApp *app) -{ - mprAssert(app); - - if (app->globalLock) { - mprDestroyLock(app->globalLock); - app->globalLock = 0; - } - if (app->allocLock) { - MprLock *lock = app->allocLock; - app->allocLock = 0; - mprDestroyLock(lock); - } -} - -/******************************************************************************/ - -MprLock *mprCreateLock(MprCtx ctx) -{ - MprLock *lock; - - mprAssert(ctx); - - lock = mprAllocType(ctx, MprLock); - -#if BLD_HOST_UNIX - pthread_mutexattr_t attr; - - pthread_mutexattr_init(&attr); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP); - pthread_mutex_init(&lock->cs, &attr); - pthread_mutexattr_destroy(&attr); -#elif WIN - InitializeCriticalSectionAndSpinCount(&lock->cs, 5000); -#elif VXWORKS - lock->cs = semMCreate(SEM_Q_PRIORITY | SEM_DELETE_SAFE | - SEM_INVERSION_SAFE); - if (lock->cs == 0) { - mprAssert(0); - mprFree(lock); - return 0; - } -#endif - return lock; -} - -/******************************************************************************/ -/* - * Destroy a lock. Must be locked on entrance. - */ - -void mprDestroyLock(MprLock *lock) -{ - mprAssert(lock); - if (lock == 0) { - return; - } - -#if BLD_HOST_UNIX - pthread_mutex_unlock(&lock->cs); - pthread_mutex_destroy(&lock->cs); -#elif WIN - DeleteCriticalSection(&lock->cs); -#elif VXWORKS - semDelete(lock->cs); -#endif - mprFree(lock); -} - -/******************************************************************************/ -/* - * Lock a mutex - */ - -void mprLock(MprLock *lock) -{ - /* - * OPT -- Do this just so we can allocate MprApp before we have created its - * lock. Should remove this test here and in mprUnlock. - */ - if (lock == 0) { - return; - } - -#if BLD_HOST_UNIX - pthread_mutex_lock(&lock->cs); -#elif WIN - EnterCriticalSection(&lock->cs); -#elif VXWORKS - semTake(lock->cs, WAIT_FOREVER); -#endif -} - -/******************************************************************************/ -/* - * Try to attain a lock. Do not block! - */ - -int mprTryLock(MprLock *lock) -{ - mprAssert(lock); - -#if BLD_HOST_UNIX - { - int err; - - if ((err = pthread_mutex_trylock(&lock->cs)) != 0) { - if (err == EBUSY) { - return MPR_ERR_BUSY; - } else { - return MPR_ERR_CANT_ACCESS; - } - } - return 0; - } -#elif WIN - if (TryEnterCriticalSection(&lock->cs) == 0) { - return MPR_ERR_BUSY; - } -#elif VXWORKS - { - int rc; - - rc = semTake(cs, NO_WAIT); - if (rc == -1) { - mprAssert(0); - } - if (rc == S_objLib_OBJ_UNAVAILABLE) { - return MPR_ERR_BUSY; - } else { - return MPR_ERR_CANT_ACCESS; - } - /* Success */ - return 0; - } -#endif - return 0; -} - -/******************************************************************************/ -/* - * Unlock. - */ - -void mprUnlock(MprLock *lock) -{ - if (lock == 0) { - return; - } - -#if BLD_HOST_UNIX - pthread_mutex_unlock(&lock->cs); -#elif WIN - LeaveCriticalSection(&lock->cs); -#elif VXWORKS - semGive(lock->cs); -#endif -} - -/******************************************************************************/ -/* - * Big global lock. Avoid using this. - */ - -void mprGlobalLock(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - mprAssert(app); - - if (app && app->globalLock) { - mprLock(app->globalLock); - } -} - -/******************************************************************************/ - -void mprGlobalUnlock(MprCtx ctx) -{ - MprApp *app; - - app = mprGetApp(ctx); - mprAssert(app); - - if (app && app->globalLock) { - mprUnlock(app->globalLock); - } -} - -/******************************************************************************/ - -int mprGetCurrentThreadID() -{ -#if BLD_HOST_UNIX - return (int) pthread_self(); -#elif WIN - return GetCurrentThreadId(); -#elif VXWORKS - return (int) pthread_self(); -#endif -} - -/******************************************************************************/ -#endif /* BLD_FEATURE_MULTITHREAD */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/mprLog.c b/source4/lib/appweb/ejs-2.0/mpr/mprLog.c deleted file mode 100644 index 1eb175ed95..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mprLog.c +++ /dev/null @@ -1,602 +0,0 @@ -/** - * @file mprLog.c - * @brief Mbedthis Portable Runtime (MPR) Logging and error reporting. - * @remarks We always provide these routines. - */ - -/*********************************** License **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -#include "mpr.h" - -/****************************** Forward Declarations **************************/ - -static void defaultLogHandler(MPR_LOC_DEC(ctx, loc), int flags, - int level, const char *msg); -static void logOutput(MPR_LOC_DEC(ctx, loc), int flags, int level, - const char *msg); - -/************************************ Code ************************************/ - -void mprLog(MprCtx ctx, int level, const char *fmt, ...) -{ - va_list args; - char *buf; - - if (level > mprGetLogLevel(ctx)) { - return; - } - - va_start(args, fmt); - mprAllocVsprintf(MPR_LOC_ARGS(ctx), &buf, 0, fmt, args); - va_end(args); - - logOutput(MPR_LOC_ARGS(ctx), MPR_LOG_SRC, level, buf); - - va_end(args); - mprFree(buf); -} - -/*****************************************************************************/ -/* - * Do raw output - */ - -void mprRawLog(MprCtx ctx, const char *fmt, ...) -{ - va_list args; - char *buf; - int len; - - va_start(args, fmt); - len = mprAllocVsprintf(MPR_LOC_ARGS(ctx), &buf, 0, fmt, args); - va_end(args); - - logOutput(MPR_LOC_ARGS(ctx), MPR_RAW, 0, buf); - mprFree(buf); -} - -/*****************************************************************************/ -/* - * Handle an error - */ - -void mprError(MPR_LOC_DEC(ctx, loc), const char *fmt, ...) -{ - va_list args; - char *buf; - int len; - - va_start(args, fmt); - len = mprAllocVsprintf(MPR_LOC_ARGS(ctx), &buf, 0, fmt, args); - va_end(args); - - logOutput(MPR_LOC_PASS(ctx, loc), MPR_ERROR_MSG | MPR_ERROR_SRC, 0, buf); - - mprFree(buf); -} - -/*****************************************************************************/ -/* - * Handle an error that should be displayed to the user - */ - -void mprUserError(MPR_LOC_DEC(ctx, loc), const char *fmt, ...) -{ - va_list args; - char *buf; - int len; - - va_start(args, fmt); - len = mprAllocVsprintf(MPR_LOC_ARGS(ctx), &buf, 0, fmt, args); - va_end(args); - - logOutput(MPR_LOC_PASS(ctx, loc), MPR_USER_MSG | MPR_ERROR_SRC, 0, buf); - - mprFree(buf); -} - -/*****************************************************************************/ -/* - * Handle a fatal error. Forcibly shutdown the application. - */ - -void mprFatalError(MPR_LOC_DEC(ctx, loc), const char *fmt, ...) -{ - va_list args; - char *buf; - int len; - - va_start(args, fmt); - len = mprAllocVsprintf(MPR_LOC_ARGS(ctx), &buf, 0, fmt, args); - va_end(args); - - logOutput(MPR_LOC_PASS(ctx, loc), MPR_USER_MSG | MPR_FATAL_SRC, 0, buf); - - mprFree(buf); - -#if BREW - mprSignalExit(ctx); -#else - exit(2); -#endif -} - -/*****************************************************************************/ -/* - * Handle a program assertion - */ - -void mprAssertError(MPR_LOC_DEC(ctx, loc), const char *msg) -{ - logOutput(MPR_LOC_PASS(ctx, loc), MPR_ASSERT_MSG | MPR_ASSERT_SRC, 0, msg); -} - -/*****************************************************************************/ -/* - * Handle an error - */ - -void mprStaticError(MPR_LOC_DEC(ctx, loc), const char *fmt, ...) -{ - va_list args; - int len; - char buf[MPR_MAX_STRING]; - - va_start(args, fmt); - len = mprVsprintf(buf, sizeof(buf), fmt, args); - va_end(args); - - logOutput(MPR_LOC_PASS(ctx, loc), MPR_ERROR_MSG | MPR_ERROR_SRC, 0, buf); -} - -/*****************************************************************************/ -/* - * Direct output to the standard output. Does not hook into the logging - * system and does not allocate memory. - */ - -void mprStaticAssert(const char *loc, const char *msg) -{ -#if BLD_DEBUG - char buf[MPR_MAX_STRING]; - int len; - - len = mprSprintf(buf, sizeof(buf), "Assertion %s, failed at %s\n", - msg, loc); - mprBreakpoint(loc, buf); - -#if BLD_HOST_UNIX - /* - * MOB -- but is stdout always okay to use - */ - write(1, buf, len); -#elif BREW || WIN - /* - * Only time we use printf. We can't get an alloc context so we have - * to use real print - */ -#if BREW && !BREW_SIMULATOR - printf(" MP: %s\n", buf); -#else - printf("%s\n", buf); -#endif - -#endif -#endif -} - -/*****************************************************************************/ - -int mprGetLogLevel(MprCtx ctx) -{ - return mprGetApp(ctx)->logLevel; -} - -/******************************************************************************/ - -void mprSetLogLevel(MprCtx ctx, int level) -{ - mprGetApp(ctx)->logLevel = level; -} - -/*****************************************************************************/ -/* - * Output a log message to the log handler - */ - -static void logOutput(MPR_LOC_DEC(ctx, loc), int flags, int level, - const char *msg) -{ - MprLogHandler handler; - - if (flags & (MPR_ERROR_SRC | MPR_FATAL_SRC | MPR_ASSERT_SRC)) { - mprBreakpoint(MPR_LOC, 0); - } - - mprAssert(ctx != 0); - handler = mprGetApp(ctx)->logHandler; - if (handler != 0) { - (handler)(MPR_LOC_PASS(ctx, loc), flags, level, msg); - return; - } - defaultLogHandler(MPR_LOC_PASS(ctx, loc), flags, level, msg); -} - -/*****************************************************************************/ -/* - * Default log output is just to the console - */ - -static void defaultLogHandler(MPR_LOC_DEC(ctx, loc), int flags, - int level, const char *msg) -{ - MprApp *app; - char *prefix; - - app = mprGetApp(ctx); - prefix = app->name; - - while (*msg == '\n') { - mprPrintf(ctx, "\n"); - msg++; - } - - if (flags & MPR_LOG_SRC) { -#if BREW && !BREW_SIMULATOR - mprPrintf(ctx, "%s\n", msg); -#else - mprPrintf(ctx, "%s: %d: %s\n", prefix, level, msg); -#endif - - } else if (flags & MPR_ERROR_SRC) { - /* - * Use static printing to avoid malloc when the messages are small. - * This is important for memory allocation errors. - */ - if (strlen(msg) < (MPR_MAX_STRING - 32)) { - mprStaticPrintf(ctx, "%s: Error: %s\n", prefix, msg); - } else { - mprPrintf(ctx, "%s: Error: %s\n", prefix, msg); - } - - } else if (flags & MPR_FATAL_SRC) { - mprPrintf(ctx, "%s: Fatal: %s\n", prefix, msg); - - } else if (flags & MPR_ASSERT_SRC) { -#if BLD_FEATURE_ALLOC_LEAK_TRACK - mprPrintf(ctx, "%s: Assertion %s, failed at %s\n", prefix, msg, loc); -#else - mprPrintf(ctx, "%s: Assertion %s, failed\n", prefix, msg); -#endif - - } else if (flags & MPR_RAW) { - mprPrintf(ctx, "%s", msg); - - } else { - return; - } -} - -/*****************************************************************************/ -/* - * Map the O/S error code to portable error codes. - */ - -int mprGetOsError() -{ -#if WIN - int rc; - rc = GetLastError(); - - /* - * Client has closed the pipe - */ - if (rc == ERROR_NO_DATA) { - return EPIPE; - } - return rc; -#endif -#if LINUX || VXWORKS || SOLARIS - return errno; -#endif -#if BREW - /* - * No such thing on Brew. Errors are per class - */ - return 0; -#endif -} - -/******************************************************************************/ -#if UNUSED - -const char *mprGetErrorMsg(int err) -{ - /* - * MPR error messages. Declare here so we don't have any globals. - */ - char *mprErrMessages[] = { - /* 0 MPR_ERR_OK */ "Success", - /* -201 MPR_ERR_GENERAL */ "General error", - /* -202 MPR_ERR_ABORTED */ "Aborted", - /* -203 MPR_ERR_ALREADY_EXISTS */ "Already exists", - /* -204 MPR_ERR_BAD_ARGS */ "Bad args", - /* -205 MPR_ERR_BAD_FORMAT */ "Bad format", - /* -206 MPR_ERR_BAD_HANDLE */ "Bad handle", - /* -207 MPR_ERR_BAD_STATE */ "Bad state", - /* -208 MPR_ERR_BAD_SYNTAX */ "Bad syntax", - /* -209 MPR_ERR_BAD_TYPE */ "Bad type", - /* -210 MPR_ERR_BAD_VALUE */ "Bad value", - /* -211 MPR_ERR_BUSY */ "Busy", - /* -212 MPR_ERR_CANT_ACCESS */ "Can't access", - /* -213 MPR_ERR_CANT_COMPLETE */ "Can't complete", - /* -214 MPR_ERR_CANT_CREATE */ "Can't create", - /* -215 MPR_ERR_CANT_INITIALIZE */ "Can't initialize", - /* -216 MPR_ERR_CANT_OPEN */ "Can't open", - /* -217 MPR_ERR_CANT_READ */ "Can't read", - /* -218 MPR_ERR_CANT_WRITE */ "Can't write", - /* -219 MPR_ERR_DELETED */ "Already deleted", - /* -220 MPR_ERR_NETWORK */ "Network error", - /* -221 MPR_ERR_NOT_FOUND */ "Not found", - /* -222 MPR_ERR_NOT_INITIALIZED */ "Not initialized", - /* -223 MPR_ERR_NOT_READY */ "Not ready", - /* -224 MPR_ERR_READ_ONLY */ "Read only", - /* -225 MPR_ERR_TIMEOUT */ "Timeout", - /* -226 MPR_ERR_TOO_MANY */ "Too many", - /* -227 MPR_ERR_WONT_FIT */ "Won't fit", - /* -228 MPR_ERR_WOULD_BLOCK */ "Would block", - /* -229 MPR_ERR_CANT_ALLOCATE */ "Can't allocate", - }; - int mprNumErr = sizeof(mprErrMessages) / sizeof(char*); - -/* - * Operating system error messages - */ -#if WIN -char *osErrMessages[] = -{ - /* 0 */ "No error", - /* 1 EPERM */ "Operation not permitted", - /* 2 ENOENT */ "No such file or directory", - /* 3 ESRCH */ "No such process", - /* 4 EINTR */ "Interrupted function call", - /* 5 EIO */ "I/O error", - /* 6 ENXIO */ "No such device or address", - /* 7 E2BIG */ "Arg list too long", - /* 8 ENOEXEC */ "Exec format error", - /* 9 EBADF */ "Bad file number", - /* 10 ECHILD */ "No child processes", - /* 11 EAGAIN */ "Try again", - /* 12 ENOMEM */ "Out of memory", - /* 13 EACCES */ "Permission denied", - /* 14 EFAULT */ "Bad address", - /* 15 ENOTBLK */ "Unknown error", - /* 16 EBUSY */ "Resource busy", - /* 17 EEXIST */ "File exists", - /* 18 EXDEV */ "Improper link", - /* 19 ENODEV */ "No such device", - /* 20 ENOTDIR */ "Not a directory", - /* 21 EISDIR */ "Is a directory", - /* 22 EINVAL */ "Invalid argument", - /* 23 ENFILE */ "Too many open files in system", - /* 24 EMFILE */ "Too many open files", - /* 25 ENOTTY */ "Inappropriate I/O control operation", - /* 26 ETXTBSY */ "Unknown error", - /* 27 EFBIG */ "File too large", - /* 28 ENOSPC */ "No space left on device", - /* 29 ESPIPE */ "Invalid seek", - /* 30 EROFS */ "Read-only file system", - /* 31 EMLINK */ "Too many links", - /* 32 EPIPE */ "Broken pipe", - /* 33 EDOM */ "Domain error", - /* 34 ERANGE */ "Result too large", - /* 35 EUCLEAN */ "Unknown error", - /* 36 EDEADLK */ "Resource deadlock would occur", - /* 37 UNKNOWN */ "Unknown error", - /* 38 ENAMETOOLONG */ "Filename too long", - /* 39 ENOLCK */ "No locks available", - /* 40 ENOSYS */ "Function not implemented", - /* 41 ENOTEMPTY */ "Directory not empty", - /* 42 EILSEQ */ "Illegal byte sequence", - /* 43 ENETDOWN */ "Network is down", - /* 44 ECONNRESET */ "Connection reset", - /* 45 ECONNREFUSED */ "Connection refused", - /* 46 EADDRINUSE */ "Address already in use" - -}; - -#else /* WIN */ - -char *osErrMessages[] = -{ - /* 0 */ "Success" - /* 1 EPERM */ "Operation not permitted" - /* 2 ENOENT */ "No such file or directory" - /* 3 ESRCH */ "No such process" - /* 4 EINTR */ "Interrupted system call" - /* 5 EIO */ "I/O error" - /* 6 ENXIO */ "No such device or address" - /* 7 E2BIG */ "Arg list too long" - /* 8 ENOEXEC */ "Exec format error" - /* 9 EBADF */ "Bad file number" - /* 10 ECHILD */ "No child processes" - /* 11 EAGAIN */ "Try again" - /* 12 ENOMEM */ "Out of memory" - /* 13 EACCES */ "Permission denied" - /* 14 EFAULT */ "Bad address" - /* 15 ENOTBLK */ "Block device required" - /* 16 EBUSY */ "Device or resource busy" - /* 17 EEXIST */ "File exists" - /* 18 EXDEV */ "Cross-device link" - /* 19 ENODEV */ "No such device" - /* 20 ENOTDIR */ "Not a directory" - /* 21 EISDIR */ "Is a directory" - /* 22 EINVAL */ "Invalid argument" - /* 23 ENFILE */ "File table overflow" - /* 24 EMFILE */ "Too many open files" - /* 25 ENOTTY */ "Not a typewriter" - /* 26 ETXTBSY */ "Text file busy" - /* 27 EFBIG */ "File too large" - /* 28 ENOSPC */ "No space left on device" - /* 29 ESPIPE */ "Illegal seek" - /* 30 EROFS */ "Read-only file system" - /* 31 EMLINK */ "Too many links" - /* 32 EPIPE */ "Broken pipe" - /* 33 EDOM */ "Math argument out of domain of func" - /* 34 ERANGE */ "Math result not representable" - /* 35 EDEADLK */ "Resource deadlock would occur" - /* 36 ENAMETOOLONG */ "File name too long" - /* 37 ENOLCK */ "No record locks available" - /* 38 ENOSYS */ "Function not implemented" - /* 39 ENOTEMPTY */ "Directory not empty" - /* 40 ELOOP */ "Too many symbolic links encountered" - /* 41 EWOULDBLOCK EAGAIN */"Operation would block" - /* 42 ENOMSG */ "No message of desired type" - /* 43 EIDRM */ "Identifier removed" - -#if !BLD_FEATURE_SQUEEZE - /* 44 ECHRNG */ "Channel number out of range" - /* 45 EL2NSYNC */ "Level 2 not synchronized" - /* 46 EL3HLT */ "Level 3 halted" - /* 47 EL3RST */ "Level 3 reset" - /* 48 ELNRNG */ "Link number out of range" - /* 49 EUNATCH */ "Protocol driver not attached" - /* 50 ENOCSI */ "No CSI structure available" - /* 51 EL2HLT */ "Level 2 halted" - /* 52 EBADE */ "Invalid exchange" - /* 53 EBADR */ "Invalid request descriptor" - /* 54 EXFULL */ "Exchange full" - /* 55 ENOANO */ "No anode" - /* 56 EBADRQC */ "Invalid request code" - /* 57 EBADSLT */ "Invalid slot" - /* 59 EBFONT */ "Bad font file format" - /* 60 ENOSTR */ "Device not a stream" - /* 61 ENODATA */ "No data available" - /* 62 ETIME */ "Timer expired" - /* 63 ENOSR */ "Out of streams resources" - /* 64 ENONET */ "Machine is not on the network" - /* 65 ENOPKG */ "Package not installed" - /* 66 EREMOTE */ "Object is remote" - /* 67 ENOLINK */ "Link has been severed" - /* 68 EADV */ "Advertise error" - /* 69 ESRMNT */ "Srmount error" - /* 70 ECOMM */ "Communication error on send" - /* 71 EPROTO */ "Protocol error" - /* 72 EMULTIHOP */ "Multihop attempted" - /* 73 EDOTDOT */ "RFS specific error" - /* 74 EBADMSG */ "Not a data message" - /* 75 EOVERFLOW */ "Value too large for defined data type" - /* 76 ENOTUNIQ */ "Name not unique on network" - /* 77 EBADFD */ "File descriptor in bad state" - /* 78 EREMCHG */ "Remote address changed" - /* 79 ELIBACC */ "Can not access a needed shared library" - /* 80 ELIBBAD */ "Accessing a corrupted shared library" - /* 81 ELIBSCN */ ".lib section in a.out corrupted" - /* 82 ELIBMAX */ "Linking in too many shared libraries" - /* 83 ELIBEXEC */ "Cannot exec a shared library directly" - /* 84 EILSEQ */ "Illegal byte sequence" - /* 85 ERESTART */ "Interrupted system call should be restarted" - /* 86 ESTRPIPE */ "Streams pipe error" - /* 87 EUSERS */ "Too many users" - /* 88 ENOTSOCK */ "Socket operation on non-socket" - /* 89 EDESTADDRREQ */ "Destination address required" - /* 90 EMSGSIZE */ "Message too long" - /* 91 EPROTOTYPE */ "Protocol wrong type for socket" - /* 92 ENOPROTOOPT */ "Protocol not available" - /* 93 EPROTONOSUPPORT */ "Protocol not supported" - /* 94 ESOCKTNOSUPPORT */ "Socket type not supported" - /* 95 EOPNOTSUPP */ "Operation not supported on transport endpoint" - /* 96 EPFNOSUPPORT */ "Protocol family not supported" - /* 97 EAFNOSUPPORT */ "Address family not supported by protocol" - /* 98 EADDRINUSE */ "Address already in use" - /* 99 EADDRNOTAVAIL */ "Cannot assign requested address" - /* 100 ENETDOWN */ "Network is down" - /* 101 ENETUNREACH */ "Network is unreachable" - /* 102 ENETRESET */ "Network dropped connection because of reset" - /* 103 ECONNABORTED */ "Software caused connection abort" - /* 104 ECONNRESET */ "Connection reset by peer" - /* 105 ENOBUFS */ "No buffer space available" - /* 106 EISCONN */ "Transport endpoint is already connected" - /* 107 ENOTCONN */ "Transport endpoint is not connected" - /* 108 ESHUTDOWN */ "Cannot send after transport endpoint shutdown" - /* 109 ETOOMANYREFS */ "Too many references: cannot splice" - /* 110 ETIMEDOUT */ "Connection timed out" - /* 111 ECONNREFUSED */ "Connection refused" - /* 112 EHOSTDOWN */ "Host is down" - /* 113 EHOSTUNREACH */ "No route to host" - /* 114 EALREADY */ "Operation already in progress" - /* 115 EINPROGRESS */ "Operation now in progress" - /* 116 ESTALE */ "Stale NFS file handle" - /* 117 EUCLEAN */ "Structure needs cleaning" - /* 118 ENOTNAM */ "Not a XENIX named type file" - /* 119 ENAVAIL */ "No XENIX semaphores available" - /* 120 EISNAM */ "Is a named type file" - /* 121 EREMOTEIO */ "Remote I/O error" - /* 122 EDQUOT */ "Quota exceeded" - /* 123 ENOMEDIUM */ "No medium found" - /* 124 EMEDIUMTYPE */ "Wrong medium type" -}; -#endif /* BLD_FEATURE_SQUEEZE */ -#endif /* WIN */ - - int osNumErr = sizeof(osErrMessages) / sizeof(char*); - - if (err < MPR_ERR_BASE) { - err = MPR_ERR_BASE - err; - if (err < 0 || err >= mprNumErr) { - return "Bad error code"; - } - return mprErrMessages[err]; - - } else { - /* - * Negative O/S error code. Map to a positive standard Posix error. - */ - err = -err; - if (err < 0 || err >= osNumErr) { - return "Bad O/S error code"; - } - return osErrMessages[err]; - } -} - -#endif -/*****************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/mprOs.h b/source4/lib/appweb/ejs-2.0/mpr/mprOs.h deleted file mode 100644 index bed4ca5979..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mprOs.h +++ /dev/null @@ -1,707 +0,0 @@ -/* - * @file mprOs.h - * @brief Include O/S headers and smooth out per-O/S differences - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/******************************* Documentation ********************************/ - -/* - * This header is part of the Mbedthis Portable Runtime and aims to include - * all necessary O/S headers and to unify the constants and declarations - * required by Mbedthis products. It can be included by C or C++ programs. - */ - -/******************************************************************************/ - -#ifndef _h_MPR_OS_HDRS -#define _h_MPR_OS_HDRS 1 - -#include "buildConfig.h" - -/********************************* CPU Families *******************************/ -/* - * Porters, add your CPU families here and update configure code. - */ -#define MPR_CPU_UNKNOWN 0 -#define MPR_CPU_IX86 1 -#define MPR_CPU_PPC 2 -#define MPR_CPU_SPARC 3 -#define MPR_CPU_XSCALE 4 -#define MPR_CPU_ARM 5 -#define MPR_CPU_MIPS 6 -#define MPR_CPU_68K 7 -#define MPR_CPU_SIMNT 8 /* VxWorks NT simulator */ -#define MPR_CPU_SIMSPARC 9 /* VxWorks sparc simulator */ - -/********************************* O/S Includes *******************************/ - -#if LINUX || SOLARIS - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - -#if LINUX - #include -#endif - -#if SOLARIS - #include -#endif - -#if BLD_FEATURE_FLOATING_POINT - #define __USE_ISOC99 1 - #include - #include -#endif - -#endif /* LINUX || SOLARIS */ - -#if VXWORKS - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - - #if BLD_FEATURE_FLOATING_POINT - #include - #define __USE_ISOC99 1 - #include - #endif - - #include - #include - #include - #include - #include - #include - #include - #include - -#endif /* VXWORKS */ - -#if MACOSX - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -#endif /* MACOSX */ - -#if WIN - /* - * We replace insecure functions with Mbedthis replacements - */ - #define _CRT_SECURE_NO_DEPRECATE 1 - - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #define WIN32_LEAN_AND_MEAN - #include - #include - #include - #if BLD_FEATURE_FLOATING_POINT - #include - #endif - #include - #include - #include - -#if BLD_DEBUG - #include -#endif - #include "mprUnix.h" -#endif /* WIN */ - -#if BREW - #if BLD_FEATURE_FLOATING_POINT - #warning "Floating point is not supported on Brew" - #endif - #if BLD_FEATURE_MULTITHREAD - #warning "Multithreading is not supported on Brew" - #endif - - #include "AEEModGen.h" - #include "AEEAppGen.h" - #include "BREWVersion.h" - - #if BREW_MAJ_VER == 2 - /* - * Fix for BREW 2.X - */ - #ifdef __GNUC__ - #define __inline extern __inline__ - #endif - #include "AEENet.h" - #undef __inline - #endif - - #include "AEE.h" - #include "AEEBitmap.h" - #include "AEEDisp.h" - #include "AEEFile.h" - #include "AEEHeap.h" - #include "AEEImageCtl.h" - #include "AEEMedia.h" - #include "AEEMediaUtil.h" - #include "AEEMimeTypes.h" - #include "AEEStdLib.h" - #include "AEEShell.h" - #include "AEESoundPlayer.h" - #include "AEEText.h" - #include "AEETransform.h" - #include "AEEWeb.h" - #if BREW_MAJ_VER >= 3 - #include "AEESMS.h" - #endif - #include "AEETAPI.h" - -#if 0 - #include "AEESound.h" - #include "AEEDb.h" - #include "AEEMenu.h" -#endif - -#endif /* BREW */ - -/******************************************************************************/ -/******************************* General Defines ******************************/ -/******************************************************************************/ - -#ifndef MAXINT -#if INT_MAX - #define MAXINT INT_MAX -#else - #define MAXINT 0x7fffffff -#endif -#endif - -#ifndef BITSPERBYTE -#define BITSPERBYTE (8 * sizeof(char)) -#endif - -#define BITS(type) (BITSPERBYTE * (int) sizeof(type)) - -#ifndef max -#define max(a,b) (((a) > (b)) ? (a) : (b)) -#endif - -#ifndef min -#define min(a,b) (((a) < (b)) ? (a) : (b)) -#endif - -#define MPR_ARRAY_SIZE(type) (sizeof(type) / sizeof(type[0])) - -#ifndef PRINTF_ATTRIBUTE -#if (__GNUC__ >= 3) && !DOXYGEN && BLD_FEATURE_ALLOC_LEAK_TRACK -/** Use gcc attribute to check printf fns. a1 is the 1-based index of - * the parameter containing the format, and a2 the index of the first - * argument. Note that some gcc 2.x versions don't handle this - * properly **/ -#define PRINTF_ATTRIBUTE(a1, a2) __attribute__ ((format (__printf__, a1, a2))) -#else -#define PRINTF_ATTRIBUTE(a1, a2) -#endif -#endif - -typedef char *MprStr; /* Used for dynamic strings */ - -#ifdef __cplusplus -extern "C" { -#else -typedef int bool; -#endif - -/******************************************************************************/ -/******************************** Linux Defines *******************************/ -/******************************************************************************/ - -#if LINUX - typedef unsigned char uchar; - -#if BLD_FEATURE_INT64 - __extension__ typedef long long int int64; - __extension__ typedef unsigned long long int uint64; - #define INT64(x) (x##LL) - #define UINT64(x) (x##ULL) -#endif - - #define closesocket(x) close(x) - #define MPR_BINARY "" - #define MPR_TEXT "" - #define O_BINARY 0 - #define O_TEXT 0 - #define SOCKET_ERROR -1 - #define MPR_DLL_EXT ".so" - -#if BLD_FEATURE_FLOATING_POINT - #define MAX_FLOAT MAXFLOAT -#endif - -/* - * For some reason it is removed from fedora pthreads.h and only - * comes in for UNIX96 - */ -extern int pthread_mutexattr_gettype (__const pthread_mutexattr_t *__restrict - __attr, int *__restrict __kind) __THROW; -/* Set the mutex kind attribute in *ATTR to KIND (either PTHREAD_MUTEX_NORMAL, - PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK, or - PTHREAD_MUTEX_DEFAULT). */ -extern int pthread_mutexattr_settype (pthread_mutexattr_t *__attr, int __kind) - __THROW; - -#endif /* LINUX */ - -/******************************************************************************/ -/******************************* VxWorks Defines ******************************/ -/******************************************************************************/ - -#if VXWORKS - - typedef unsigned char uchar; - typedef unsigned int uint; - typedef unsigned long ulong; - - #define HAVE_SOCKLEN_T - typedef int socklen_t; - -#if BLD_FEATURE_INT64 - typedef long long int int64; - typedef unsigned long long int uint64; - #define INT64(x) (x##LL) - #define UINT64(x) (x##ULL) -#endif - - #define closesocket(x) close(x) - #define getpid() taskIdSelf() - #define MPR_BINARY "" - #define MPR_TEXT "" - #define O_BINARY 0 - #define O_TEXT 0 - #define SOCKET_ERROR -1 - #define MPR_DLL_EXT ".so" - -#if BLD_FEATURE_FLOATING_POINT - #define MAX_FLOAT FLT_MAX -#endif - - #undef R_OK - #define R_OK 4 - #undef W_OK - #define W_OK 2 - #undef X_OK - #define X_OK 1 - #undef F_OK - #define F_OK 0 - - #define MSG_NOSIGNAL 0 - - extern int access(char *path, int mode); - extern int sysClkRateGet(); - -#endif /* VXWORKS */ - -/******************************************************************************/ -/******************************** MacOsx Defines ******************************/ -/******************************************************************************/ -#if MACOSX - typedef unsigned long ulong; - typedef unsigned char uchar; - -#if BLD_FEATURE_INT64 - __extension__ typedef long long int int64; - __extension__ typedef unsigned long long int uint64; - #define INT64(x) (x##LL) - #define UINT64(x) (x##ULL) -#endif - - #define closesocket(x) close(x) - #define MPR_BINARY "" - #define MPR_TEXT "" - #define O_BINARY 0 - #define O_TEXT 0 - #define SOCKET_ERROR -1 - #define MPR_DLL_EXT ".dylib" - #define MSG_NOSIGNAL 0 - #define __WALL 0x40000000 - #define PTHREAD_MUTEX_RECURSIVE_NP PTHREAD_MUTEX_RECURSIVE - -#if BLD_FEATURE_FLOATING_POINT - #define MAX_FLOAT MAXFLOAT -#endif - -#endif /* MACOSX */ - -/******************************************************************************/ -/******************************* Windows Defines ******************************/ -/******************************************************************************/ - -#if WIN - typedef unsigned char uchar; - typedef unsigned int uint; - typedef unsigned long ulong; - typedef unsigned short ushort; - -/* - * We always define INT64 types on windows - */ -#if BLD_FEATURE_INT64 || 1 - typedef __int64 int64; - typedef unsigned __int64 uint64; - #define INT64(x) (x##i64) - #define UINT64(x) (x##Ui64) -#endif - - typedef int uid_t; - typedef void *handle; - typedef char *caddr_t; - typedef long pid_t; - typedef int gid_t; - typedef ushort mode_t; - typedef void *siginfo_t; - - #define HAVE_SOCKLEN_T - typedef int socklen_t; - - #undef R_OK - #define R_OK 4 - #undef W_OK - #define W_OK 2 - - /* - * On windows map X_OK to R_OK - */ - #undef X_OK - #define X_OK 4 - #undef F_OK - #define F_OK 0 - - #ifndef EADDRINUSE - #define EADDRINUSE 46 - #endif - #ifndef EWOULDBLOCK - #define EWOULDBLOCK EAGAIN - #endif - #ifndef ENETDOWN - #define ENETDOWN 43 - #endif - #ifndef ECONNRESET - #define ECONNRESET 44 - #endif - #ifndef ECONNREFUSED - #define ECONNREFUSED 45 - #endif - - #define MSG_NOSIGNAL 0 - #define MPR_BINARY "b" - #define MPR_TEXT "t" - -#if BLD_FEATURE_FLOATING_POINT - #define MAX_FLOAT DBL_MAX -#endif - -#ifndef FILE_FLAG_FIRST_PIPE_INSTANCE -#define FILE_FLAG_FIRST_PIPE_INSTANCE 0x00080000 -#endif - - #define MPR_DLL_EXT ".dll" -#endif /* WIN */ - -/******************************************************************************/ -/****************************** Solaris Defines *******************************/ -/******************************************************************************/ - -#if SOLARIS - typedef unsigned char uchar; - -#if BLD_FEATURE_INT64 - typedef long long int int64; - typedef unsigned long long int uint64; - #define INT64(x) (x##LL) - #define UINT64(x) (x##ULL) -#endif - - #define closesocket(x) close(x) - #define MPR_BINARY "" - #define MPR_TEXT "" - #define O_BINARY 0 - #define O_TEXT 0 - #define SOCKET_ERROR -1 - #define MPR_DLL_EXT ".so" - #define MSG_NOSIGNAL 0 - #define INADDR_NONE ((in_addr_t) 0xffffffff) - #define __WALL 0 - #define PTHREAD_MUTEX_RECURSIVE_NP PTHREAD_MUTEX_RECURSIVE - -#if BLD_FEATURE_FLOATING_POINT - #define MAX_FLOAT MAXFLOAT -#endif - -#endif /* SOLARIS */ - -/******************************************************************************/ -/********************************* BREW Defines *******************************/ -/******************************************************************************/ - -#if BREW - typedef unsigned char uchar; - typedef unsigned int uint; - typedef unsigned long ulong; - typedef unsigned short ushort; - - typedef uint off_t; - typedef long pid_t; - -#if UNUSED - typedef int uid_t; - typedef void *handle; - typedef char *caddr_t; - typedef int gid_t; - typedef ushort mode_t; - typedef void *siginfo_t; - - #define HAVE_SOCKLEN_T - typedef int socklen_t; - - #ifndef EADDRINUSE - #define EADDRINUSE 46 - #endif - #ifndef EWOULDBLOCK - #define EWOULDBLOCK EAGAIN - #endif - #ifndef ENETDOWN - #define ENETDOWN 43 - #endif - #ifndef ECONNRESET - #define ECONNRESET 44 - #endif - #ifndef ECONNREFUSED - #define ECONNREFUSED 45 - #endif - - #define MSG_NOSIGNAL 0 - #define MPR_BINARY "b" - #define MPR_TEXT "t" - - #define MPR_DLL_EXT ".dll" -#endif - - #define O_RDONLY 0 - #define O_WRONLY 1 - #define O_RDWR 2 - #define O_CREAT 0x200 - #define O_TRUNC 0x400 - #define O_BINARY 0 - #define O_TEXT 0x20000 - #define O_EXCL 0x40000 - #define O_APPEND 0x80000 - - #define R_OK 4 - #define W_OK 2 - #define X_OK 1 - #define F_OK 0 - - #define SEEK_SET 0 - #define SEEK_CUR 1 - #define SEEK_END 2 - -#if UNUSED -struct stat { - uint st_size; -}; -#endif - -extern int getpid(); -extern int isalnum(int c); -extern int isalpha(int c); -extern int isdigit(int c); -extern int islower(int c); -extern int isupper(int c); -extern int isspace(int c); -extern int isxdigit(int c); - -extern uint strlen(const char *str); -extern char *strstr(const char *string, const char *strSet); -extern void *memset(const void *dest, int c, uint count); -extern void exit(int status); -extern char *strpbrk(const char *str, const char *set); -extern uint strspn(const char *str, const char *set); -extern int tolower(int c); -extern int toupper(int c); -extern void *memcpy(void *dest, const void *src, uint count); -extern void *memmove(void *dest, const void *src, uint count); - -extern int atoi(const char *str); -extern void free(void *ptr); -extern void *malloc(uint size); -extern void *realloc(void *ptr, uint size); -extern char *strcat(char *dest, const char *src); -extern char *strchr(const char *str, int c); -extern int strcmp(const char *s1, const char *s2); -extern int strncmp(const char *s1, const char *s2, uint count); -extern char *strcpy(char *dest, const char *src); -extern char *strncpy(char *dest, const char *src, uint count); -extern char *strrchr(const char *str, int c); - -#undef printf -#define printf DBGPRINTF - -#if BREW_SIMULATOR && BLD_DEBUG -extern _CRTIMP int __cdecl _CrtCheckMemory(void); -extern _CRTIMP int __cdecl _CrtSetReportHook(); -#endif - -#endif /* BREW */ - -/******************************************************************************/ -#ifdef __cplusplus -} -#endif - -#endif /* _h_MPR_OS_HDRS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/mprPrintf.c b/source4/lib/appweb/ejs-2.0/mpr/mprPrintf.c deleted file mode 100644 index 2d0951acfa..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mprPrintf.c +++ /dev/null @@ -1,924 +0,0 @@ -/** - * @file mprPrintf.c - * @brief Printf routines safe for embedded programming - * @overview This module provides safe replacements for the standard - * printf formatting routines. - * @remarks Most routines in this file are not thread-safe. It is the callers - * responsibility to perform all thread synchronization. - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************** Includes **********************************/ -/* - * We need to use the underlying str(cpy) routines to implement our safe - * alternatives - */ -#if !DOXYGEN -#define UNSAFE_FUNCTIONS_OK 1 -#endif - -#include "mpr.h" - -/*********************************** Defines **********************************/ -/* - * Class definitions - */ -#define CLASS_NORMAL 0 /* [All other] Normal characters */ -#define CLASS_PERCENT 1 /* [%] Begin format */ -#define CLASS_MODIFIER 2 /* [-+ #,] Modifiers */ -#define CLASS_ZERO 3 /* [0] Special modifier */ -#define CLASS_STAR 4 /* [*] Width supplied by arg */ -#define CLASS_DIGIT 5 /* [1-9] Field widths */ -#define CLASS_DOT 6 /* [.] Introduce precision */ -#define CLASS_BITS 7 /* [hlL] Length bits */ -#define CLASS_TYPE 8 /* [cdfinopsSuxX] Type specifiers */ - -#define STATE_NORMAL 0 /* Normal chars in format string */ -#define STATE_PERCENT 1 /* "%" */ -#define STATE_MODIFIER 2 /* Read flag */ -#define STATE_WIDTH 3 /* Width spec */ -#define STATE_DOT 4 /* "." */ -#define STATE_PRECISION 5 /* Precision spec */ -#define STATE_BITS 6 /* Size spec */ -#define STATE_TYPE 7 /* Data type */ -#define STATE_COUNT 8 - -/* - * Format: %[modifier][width][precision][bits][type] - * - * #define CLASS_MODIFIER 2 [-+ #,] Modifiers - * #define CLASS_BITS 7 [hlL] Length bits - */ - - -/* - * Flags - */ -#define SPRINTF_LEFT 0x1 /* Left align */ -#define SPRINTF_SIGN 0x2 /* Always sign the result */ -#define SPRINTF_LEAD_SPACE 0x4 /* put leading space for +ve numbers */ -#define SPRINTF_ALTERNATE 0x8 /* Alternate format */ -#define SPRINTF_LEAD_ZERO 0x10 /* Zero pad */ -#define SPRINTF_SHORT 0x20 /* 16-bit */ -#define SPRINTF_LONG 0x40 /* 32-bit */ -#if BLD_FEATURE_INT64 -#define SPRINTF_LONGLONG 0x80 /* 64-bit */ -#endif -#define SPRINTF_COMMA 0x100 /* Thousand comma separators */ -#define SPRINTF_UPPER_CASE 0x200 /* As the name says for numbers */ - -typedef struct Format { - uchar *buf; - uchar *endbuf; - uchar *start; - uchar *end; - int growBy; - int maxsize; - - int precision; - int radix; - int width; - int flags; - int len; -} Format; - -static int growBuf(MPR_LOC_DEC(ctx, loc), Format *fmt); - -#define BPUT(ctx, loc, fmt, c) \ - if (1) { \ - /* Less one to allow room for the null */ \ - if ((fmt)->end >= ((fmt)->endbuf - sizeof(char))) { \ - if (growBuf(MPR_LOC_PASS(ctx, loc), fmt)) { \ - *(fmt)->end++ = (c); \ - } \ - } else { \ - *(fmt)->end++ = (c); \ - } \ - } else - -#define BPUTNULL(ctx, loc, fmt) \ - if (1) { \ - if ((fmt)->end > (fmt)->endbuf) { \ - if (growBuf(MPR_LOC_PASS(ctx, loc), fmt)) { \ - *(fmt)->end = '\0'; \ - } \ - } else { \ - *(fmt)->end = '\0'; \ - } \ - } else - -/******************************************************************************/ - -#if BLD_FEATURE_INT64 -#define unum uint64 -#define num int64 -#else -#define unum uint -#define num int -#endif - -/***************************** Forward Declarations ***************************/ -#ifdef __cplusplus -extern "C" { -#endif - -static int getState(char c, int state); -static int mprSprintfCore(MPR_LOC_DEC(ctx, loc), char **s, - int maxsize, const char *fmt, va_list arg); -static void outNum(MPR_LOC_DEC(ctx, loc), Format *fmt, const char *prefix, - unum val); - -#if BLD_FEATURE_FLOATING_POINT -static void outFloat(MPR_LOC_DEC(ctx, loc), Format *fmt, char specChar, - double value); -#endif - -/******************************************************************************/ - -int mprPrintf(MprCtx ctx, const char *fmt, ...) -{ - va_list ap; - char *buf; - int len; - MprApp *app; - - /* No asserts here as this is used as part of assert reporting */ - - app = mprGetApp(ctx); - - va_start(ap, fmt); - len = mprAllocVsprintf(MPR_LOC_ARGS(ctx), &buf, 0, fmt, ap); - va_end(ap); - if (len >= 0 && app->console) { - len = mprWrite(app->console, buf, len); - } - mprFree(buf); - - return len; -} - -/******************************************************************************/ - -int mprErrorPrintf(MprCtx ctx, const char *fmt, ...) -{ - va_list ap; - char *buf; - int len; - MprApp *app; - - /* No asserts here as this is used as part of assert reporting */ - - app = mprGetApp(ctx); - - va_start(ap, fmt); - len = mprAllocVsprintf(MPR_LOC_ARGS(ctx), &buf, 0, fmt, ap); - va_end(ap); - if (len >= 0 && app->error) { - len = mprWrite(app->error, buf, len); - } - mprFree(buf); - - return len; -} - -/******************************************************************************/ - -int mprFprintf(MprFile *file, const char *fmt, ...) -{ - va_list ap; - char *buf; - int len; - - if (file == 0) { - return MPR_ERR_BAD_HANDLE; - } - - va_start(ap, fmt); - len = mprAllocVsprintf(MPR_LOC_ARGS(file), &buf, 0, fmt, ap); - va_end(ap); - - if (len >= 0) { - len = mprWrite(file, buf, len); - } - mprFree(buf); - return len; -} - -/******************************************************************************/ -/* - * Printf with a static buffer. Used internally only. WILL NOT MALLOC. - */ - -int mprStaticPrintf(MprCtx ctx, const char *fmt, ...) -{ - va_list ap; - char buf[MPR_MAX_STRING]; - char *bufp; - int len; - MprApp *app; - - app = mprGetApp(ctx); - - va_start(ap, fmt); - bufp = buf; - len = mprSprintfCore(MPR_LOC_ARGS(0), &bufp, MPR_MAX_STRING, fmt, ap); - va_end(ap); - if (len >= 0) { - len = mprWrite(app->console, buf, len); - } - return len; -} - -/******************************************************************************/ - -int mprSprintf(char *buf, int n, const char *fmt, ...) -{ - va_list ap; - int result; - - mprAssert(buf); - mprAssert(fmt); - mprAssert(n > 0); - - va_start(ap, fmt); - result = mprSprintfCore(MPR_LOC_ARGS(0), &buf, n, fmt, ap); - va_end(ap); - return result; -} - -/******************************************************************************/ - -int mprVsprintf(char *buf, int n, const char *fmt, va_list arg) -{ - mprAssert(buf); - mprAssert(fmt); - mprAssert(n > 0); - - return mprSprintfCore(MPR_LOC_ARGS(0), &buf, n, fmt, arg); -} - -/******************************************************************************/ - -int mprAllocSprintf(MPR_LOC_DEC(ctx, loc), char **buf, int maxSize, - const char *fmt, ...) -{ - va_list ap; - int result; - - mprAssert(buf); - mprAssert(fmt); - - *buf = 0; - va_start(ap, fmt); - result = mprSprintfCore(MPR_LOC_PASS(ctx, loc), buf, maxSize, fmt, ap); - va_end(ap); - return result; -} - -/******************************************************************************/ - -int mprAllocVsprintf(MPR_LOC_DEC(ctx, loc), char **buf, int maxSize, - const char *fmt, va_list arg) -{ - mprAssert(buf); - mprAssert(fmt); - - *buf = 0; - return mprSprintfCore(MPR_LOC_PASS(ctx, loc), buf, maxSize, fmt, arg); -} - -/******************************************************************************/ - -static int getState(char c, int state) -{ - /* - * Declared here to remove all static / globals - * FUTURE OPT -- need to measure this. Could be slow on BREW. - */ - - char stateMap[] = { - /* STATES: Normal Percent Modifier Width Dot Prec Bits Type */ - /* CLASS 0 1 2 3 4 5 6 7 */ - /* Normal 0 */ 0, 0, 0, 0, 0, 0, 0, 0, - /* Percent 1 */ 1, 0, 1, 1, 1, 1, 1, 1, - /* Modifier 2 */ 0, 2, 2, 0, 0, 0, 0, 0, - /* Zero 3 */ 0, 2, 2, 3, 0, 5, 0, 0, - /* Star 4 */ 0, 3, 3, 0, 5, 0, 0, 0, - /* Digit 5 */ 0, 3, 3, 3, 5, 5, 0, 0, - /* Dot 6 */ 0, 4, 4, 4, 0, 0, 0, 0, - /* Bits 7 */ 0, 6, 6, 6, 6, 6, 6, 0, - /* Types 8 */ 0, 7, 7, 7, 7, 7, 7, 0, - }; - - /* - * Format: %[modifier][width][precision][bits][type] - */ - char classMap[] = { - /* 0 ' ' ! " # $ % & ' */ - 2, 0, 0, 2, 0, 1, 0, 0, - /* 07 ( ) * + , - . / */ - 0, 0, 4, 2, 2, 2, 6, 0, - /* 10 0 1 2 3 4 5 6 7 */ - 3, 5, 5, 5, 5, 5, 5, 5, - /* 17 8 9 : ; < = > ? */ - 5, 5, 0, 0, 0, 0, 0, 0, - /* 20 @ A B C D E F G */ - 0, 0, 0, 0, 0, 0, 0, 0, - /* 27 H I J K L M N O */ - 0, 0, 0, 0, 7, 0, 0, 0, - /* 30 P Q R S T U V W */ - 0, 0, 0, 8, 0, 0, 0, 0, - /* 37 X Y Z [ \ ] ^ _ */ - 8, 0, 0, 0, 0, 0, 0, 0, - /* 40 ' a b c d e f g */ - 0, 0, 0, 8, 8, 0, 8, 0, - /* 47 h i j k l m n o */ - 7, 8, 0, 0, 7, 0, 8, 8, - /* 50 p q r s t u v w */ - 8, 0, 0, 8, 0, 8, 0, 0, - /* 57 x y z */ - 8, 0, 0, - }; - - int chrClass; - - if (c < ' ' || c > 'z') { - chrClass = CLASS_NORMAL; - } else { - mprAssert((c - ' ') < (int) sizeof(classMap)); - chrClass = classMap[(c - ' ')]; - } - mprAssert((chrClass * STATE_COUNT + state) < (int) sizeof(stateMap)); - state = stateMap[chrClass * STATE_COUNT + state]; - return state; -} - -/******************************************************************************/ - -static int mprSprintfCore(MPR_LOC_DEC(ctx, loc), char **bufPtr, - int maxsize, const char *spec, va_list arg) -{ - Format fmt; - char *cp; - char c; - char *sValue; - num iValue; - unum uValue; - int count, i, len, state; - - mprAssert(bufPtr); - mprAssert(spec); - - if (*bufPtr != 0) { - mprAssert(maxsize > 0); - fmt.buf = (uchar*) *bufPtr; - fmt.endbuf = &fmt.buf[maxsize]; - fmt.growBy = 0; - } else { - if (maxsize <= 0) { - maxsize = MAXINT; - } - - len = min(MPR_DEFAULT_ALLOC, maxsize); - fmt.buf = (uchar*) mprAllocBlock(MPR_LOC_PASS(ctx, loc), len); - fmt.endbuf = &fmt.buf[len]; - fmt.growBy = MPR_DEFAULT_ALLOC * 2; - } - - fmt.maxsize = maxsize; - fmt.start = fmt.buf; - fmt.end = fmt.buf; - fmt.len = 0; - *fmt.start = '\0'; - - state = STATE_NORMAL; - - while ((c = *spec++) != '\0') { - state = getState(c, state); - - switch (state) { - case STATE_NORMAL: - BPUT(ctx, loc, &fmt, c); - break; - - case STATE_PERCENT: - fmt.precision = -1; - fmt.width = 0; - fmt.flags = 0; - break; - - case STATE_MODIFIER: - switch (c) { - case '+': - fmt.flags |= SPRINTF_SIGN; - break; - case '-': - fmt.flags |= SPRINTF_LEFT; - break; - case '#': - fmt.flags |= SPRINTF_ALTERNATE; - break; - case '0': - fmt.flags |= SPRINTF_LEAD_ZERO; - break; - case ' ': - fmt.flags |= SPRINTF_LEAD_SPACE; - break; - case ',': - fmt.flags |= SPRINTF_COMMA; - break; - } - break; - - case STATE_WIDTH: - if (c == '*') { - fmt.width = va_arg(arg, int); - if (fmt.width < 0) { - fmt.width = -fmt.width; - fmt.flags |= SPRINTF_LEFT; - } - } else { - while (isdigit((int)c)) { - fmt.width = fmt.width * 10 + (c - '0'); - c = *spec++; - } - spec--; - } - break; - - case STATE_DOT: - fmt.precision = 0; - fmt.flags &= ~SPRINTF_LEAD_ZERO; - break; - - case STATE_PRECISION: - if (c == '*') { - fmt.precision = va_arg(arg, int); - } else { - while (isdigit((int) c)) { - fmt.precision = fmt.precision * 10 + (c - '0'); - c = *spec++; - } - spec--; - } - break; - - case STATE_BITS: - switch (c) { -#if BLD_FEATURE_INT64 - case 'L': - fmt.flags |= SPRINTF_LONGLONG; /* 64 bit */ - break; -#endif - - case 'l': - fmt.flags |= SPRINTF_LONG; - break; - - case 'h': - fmt.flags |= SPRINTF_SHORT; - break; - } - break; - - case STATE_TYPE: - switch (c) { -#if BLD_FEATURE_FLOATING_POINT - case 'e': - case 'g': - case 'f': - fmt.radix = 10; - outFloat(MPR_LOC_PASS(ctx, loc), &fmt, c, - (double) va_arg(arg, double)); - break; -#endif - case 'c': - BPUT(ctx, loc, &fmt, (char) va_arg(arg, int)); - break; - - case 's': - case 'S': - sValue = va_arg(arg, char*); - if (sValue == 0) { - sValue = "null"; - len = strlen(sValue); - } else if (fmt.flags & SPRINTF_ALTERNATE) { - sValue++; - len = (int) *sValue; - } else if (fmt.precision >= 0) { - /* - * Can't use strlen(), the string may not have a null - */ - cp = sValue; - for (len = 0; len < fmt.precision; len++) { - if (*cp++ == '\0') { - break; - } - } - } else { - len = strlen(sValue); - } - if (!(fmt.flags & SPRINTF_LEFT)) { - for (i = len; i < fmt.width; i++) { - BPUT(ctx, loc, &fmt, (char) ' '); - } - } - for (i = 0; i < len && *sValue; i++) { - BPUT(ctx, loc, &fmt, *sValue++); - } - if (fmt.flags & SPRINTF_LEFT) { - for (i = len; i < fmt.width; i++) { - BPUT(ctx, loc, &fmt, (char) ' '); - } - } - break; - - case 'i': - ; - case 'd': - fmt.radix = 10; - if (fmt.flags & SPRINTF_SHORT) { - iValue = (short) va_arg(arg, int); - } else if (fmt.flags & SPRINTF_LONG) { - iValue = va_arg(arg, long); -#if BLD_FEATURE_INT64 - } else if (fmt.flags & SPRINTF_LONGLONG) { - iValue = va_arg(arg, num); -#endif - } else { - iValue = va_arg(arg, int); - } - if (iValue >= 0) { - if (fmt.flags & SPRINTF_LEAD_SPACE) { - outNum(MPR_LOC_PASS(ctx, loc), &fmt, " ", iValue); - } else if (fmt.flags & SPRINTF_SIGN) { - outNum(MPR_LOC_PASS(ctx, loc), &fmt, "+", iValue); - } else { - outNum(MPR_LOC_PASS(ctx, loc), &fmt, 0, iValue); - } - } else { - outNum(MPR_LOC_PASS(ctx, loc), &fmt, "-", -iValue); - } - break; - - case 'X': - fmt.flags |= SPRINTF_UPPER_CASE; - /* Fall through */ - case 'o': - case 'x': - case 'u': - if (fmt.flags & SPRINTF_SHORT) { - uValue = (ushort) va_arg(arg, uint); - } else if (fmt.flags & SPRINTF_LONG) { - uValue = va_arg(arg, ulong); -#if BLD_FEATURE_INT64 - } else if (fmt.flags & SPRINTF_LONGLONG) { - uValue = va_arg(arg, unum); -#endif - } else { - uValue = va_arg(arg, uint); - } - if (c == 'u') { - fmt.radix = 10; - outNum(MPR_LOC_PASS(ctx, loc), &fmt, 0, uValue); - } else if (c == 'o') { - fmt.radix = 8; - if (fmt.flags & SPRINTF_ALTERNATE && uValue != 0) { - outNum(MPR_LOC_PASS(ctx, loc), &fmt, "0", uValue); - } else { - outNum(MPR_LOC_PASS(ctx, loc), &fmt, 0, uValue); - } - } else { - fmt.radix = 16; - if (fmt.flags & SPRINTF_ALTERNATE && uValue != 0) { - if (c == 'X') { - outNum(MPR_LOC_PASS(ctx, loc), &fmt, "0X", uValue); - } else { - outNum(MPR_LOC_PASS(ctx, loc), &fmt, "0x", uValue); - } - } else { - outNum(MPR_LOC_PASS(ctx, loc), &fmt, 0, uValue); - } - } - break; - - case 'n': /* Count of chars seen thus far */ - if (fmt.flags & SPRINTF_SHORT) { - short *count = va_arg(arg, short*); - *count = fmt.end - fmt.start; - } else if (fmt.flags & SPRINTF_LONG) { - long *count = va_arg(arg, long*); - *count = fmt.end - fmt.start; - } else { - int *count = va_arg(arg, int *); - *count = fmt.end - fmt.start; - } - break; - - case 'p': /* Pointer */ -#if __WORDSIZE == 64 && BLD_FEATURE_INT64 - uValue = (unum) va_arg(arg, void*); -#else - uValue = (uint) (int) va_arg(arg, void*); -#endif - fmt.radix = 16; - outNum(MPR_LOC_PASS(ctx, loc), &fmt, "0x", uValue); - break; - - default: - BPUT(ctx, loc, &fmt, c); - } - } - } - BPUTNULL(ctx, loc, &fmt); - - count = fmt.end - fmt.start; - if (*bufPtr == 0) { - *bufPtr = (char*) fmt.buf; - } - return count; -} - -/******************************************************************************/ -/* - * Output a number according to the given format. If BLD_FEATURE_INT64 is - * defined, then uses 64 bits universally. Slower but smaller code. - */ - -static void outNum(MPR_LOC_DEC(ctx, loc), Format *fmt, const char *prefix, - unum value) -{ - char numBuf[64]; - char *cp; - char *endp; - char c; - int letter, len, leadingZeros, i, fill; - - endp = &numBuf[sizeof(numBuf) - 1]; - *endp = '\0'; - cp = endp; - - /* - * Convert to ascii - */ - if (fmt->radix == 16) { - do { - letter = (int) (value % fmt->radix); - if (letter > 9) { - if (fmt->flags & SPRINTF_UPPER_CASE) { - letter = 'A' + letter - 10; - } else { - letter = 'a' + letter - 10; - } - } else { - letter += '0'; - } - *--cp = letter; - value /= fmt->radix; - } while (value > 0); - - } else if (fmt->flags & SPRINTF_COMMA) { - i = 1; - do { - *--cp = '0' + (int) (value % fmt->radix); - value /= fmt->radix; - if ((i++ % 3) == 0 && value > 0) { - *--cp = ','; - } - } while (value > 0); - } else { - do { - *--cp = '0' + (int) (value % fmt->radix); - value /= fmt->radix; - } while (value > 0); - } - - len = endp - cp; - fill = fmt->width - len; - - if (prefix != 0) { - fill -= strlen(prefix); - } - leadingZeros = (fmt->precision > len) ? fmt->precision - len : 0; - fill -= leadingZeros; - - if (!(fmt->flags & SPRINTF_LEFT)) { - c = (fmt->flags & SPRINTF_LEAD_ZERO) ? '0': ' '; - for (i = 0; i < fill; i++) { - BPUT(ctx, loc, fmt, c); - } - } - if (prefix != 0) { - while (*prefix) { - BPUT(ctx, loc, fmt, *prefix++); - } - } - for (i = 0; i < leadingZeros; i++) { - BPUT(ctx, loc, fmt, '0'); - } - while (*cp) { - BPUT(ctx, loc, fmt, *cp); - cp++; - } - if (fmt->flags & SPRINTF_LEFT) { - for (i = 0; i < fill; i++) { - BPUT(ctx, loc, fmt, ' '); - } - } -} - -/******************************************************************************/ -#if BLD_FEATURE_FLOATING_POINT -/* - * Output a floating point number - */ - -static void outFloat(MPR_LOC_DEC(ctx, loc), Format *fmt, char specChar, - double value) -{ - char *cp; -#if FUTURE - char numBuf[64]; - char *endp; - char c; - int letter, len, leadingZeros, i, fill, width, precision; - - endp = &numBuf[sizeof(numBuf) - 1]; - *endp = '\0'; - - precision = fmt->precision; - if (precision < 0) { - precision = 6; - } else if (precision > (sizeof(numBuf) - 1)) { - precision = (sizeof(numBuf) - 1); - } - width = min(fmt->width, sizeof(numBuf) - 1); - - if (__isnanl(value)) { - "nan" - } else if (__isinfl(value)) { - "infinity" - } else if (value < 0) { - prefix = "-"; - } else if (fmt.flags & SPRINTF_LEAD_SPACE) { - prefix = " "; - } else if (fmt.flags & SPRINTF_SIGN) { - prefix = "+"; - } - - - /* - * Do the exponent part - */ - cp = &numBuf[sizeof(numBuf) - precision]; - for (i = 0; i < precision; i++) { - *cp++ = '0' + (int) (value % fmt->radix); - value /= fmt->radix; - } - - /* - * Do the decimal part - */ - if (fmt->flags & SPRINTF_COMMA) { - i = 1; - do { - *--cp = '0' + (int) (value % fmt->radix); - value /= fmt->radix; - if ((i++ % 3) == 0 && value > 0) { - *--cp = ','; - } - } while (value >= 1.0); - - } else { - do { - *--cp = '0' + (int) (value % fmt->radix); - value /= fmt->radix; - } while (value > 1.0); - } - - len = endp - cp; - fill = fmt->width - len; - - if (prefix != 0) { - fill -= strlen(prefix); - } - - leadingZeros = (fmt->precision > len) ? fmt->precision - len : 0; - fill -= leadingZeros; - - if (!(fmt->flags & SPRINTF_LEFT)) { - c = (fmt->flags & SPRINTF_LEAD_ZERO) ? '0': ' '; - for (i = 0; i < fill; i++) { - BPUT(ctx, loc, fmt, c); - } - } - if (prefix != 0) { - BPUT(ctx, loc, fmt, prefix); - } - for (i = 0; i < leadingZeros; i++) { - BPUT(ctx, loc, fmt, '0'); - } - BPUT(ctx, loc, fmt, cp); - if (fmt->flags & SPRINTF_LEFT) { - for (i = 0; i < fill; i++) { - BPUT(ctx, loc, fmt, ' '); - } - } -#else - char numBuf[64]; - if (specChar == 'f') { - sprintf(numBuf, "%*.*f", fmt->width, fmt->precision, value); - } else if (specChar == 'g') { - sprintf(numBuf, "%*.*g", fmt->width, fmt->precision, value); - } else if (specChar == 'e') { - sprintf(numBuf, "%*.*e", fmt->width, fmt->precision, value); - } - for (cp = numBuf; *cp; cp++) { - BPUT(ctx, loc, fmt, *cp); - } -#endif -} - -#endif /* BLD_FEATURE_FLOATING_POINT */ -/******************************************************************************/ -/* - * Grow the buffer to fit new data. Return 1 if the buffer can grow. - * Grow using the growBy size specified when creating the buffer. - */ - -static int growBuf(MPR_LOC_DEC(ctx, loc), Format *fmt) -{ - uchar *newbuf; - int buflen; - - buflen = fmt->endbuf - fmt->buf; - if (fmt->maxsize >= 0 && buflen >= fmt->maxsize) { - return 0; - } - if (fmt->growBy < 0) { - /* - * User supplied buffer - */ - return 0; - } - - newbuf = (uchar*) mprAlloc(ctx, buflen + fmt->growBy); - if (fmt->buf) { - memcpy(newbuf, fmt->buf, buflen); - mprFree(fmt->buf); - } - - buflen += fmt->growBy; - fmt->end = newbuf + (fmt->end - fmt->buf); - fmt->start = newbuf + (fmt->start - fmt->buf); - fmt->buf = newbuf; - fmt->endbuf = &fmt->buf[buflen]; - - /* - * Increase growBy to reduce overhead - */ - if ((buflen + (fmt->growBy * 2)) < fmt->maxsize) { - fmt->growBy *= 2; - } - return 1; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/mprString.c b/source4/lib/appweb/ejs-2.0/mpr/mprString.c deleted file mode 100644 index d39fc8b746..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mprString.c +++ /dev/null @@ -1,733 +0,0 @@ -/** - * @file mprString.c - * @brief String routines safe for embedded programming - * @overview This module provides safe replacements for the standard - * string library. - * @remarks Most routines in this file are not thread-safe. It is the callers - * responsibility to perform all thread synchronization. - */ - -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -#include "mpr.h" - -/********************************** Includes **********************************/ -/* - * We need to use the underlying str(cpy) routines to implement our safe - * alternatives - */ -#if !DOXYGEN -#define UNSAFE_FUNCTIONS_OK 1 -#endif - -/******************************************************************************/ -/**************************** Safe String Handling ****************************/ -/******************************************************************************/ - -int mprStrcpy(char *dest, int destMax, const char *src) -{ - int len; - - mprAssert(dest); - mprAssert(destMax >= 0); - mprAssert(src); - - len = strlen(src); - if (destMax > 0 && len >= destMax && len > 0) { - return MPR_ERR_WONT_FIT; - } - if (len > 0) { - memcpy(dest, src, len); - dest[len] = '\0'; - } else { - *dest = '\0'; - len = 0; - } - return len; -} - -/******************************************************************************/ - -int mprAllocStrcpy(MPR_LOC_DEC(ctx, loc), char **dest, int destMax, - const char *src) -{ - int len; - - mprAssert(dest); - mprAssert(destMax >= 0); - mprAssert(src); - - len = strlen(src); - if (destMax > 0 && len >= destMax) { - mprAssert(0); - return MPR_ERR_WONT_FIT; - } - if (len > 0) { - *dest = (char*) mprAllocBlock(MPR_LOC_PASS(ctx, loc), len); - memcpy(*dest, src, len); - (*dest)[len] = '\0'; - } else { - *dest = (char*) mprAlloc(ctx, 1); - *dest = '\0'; - len = 0; - } - return len; -} - -/******************************************************************************/ - -int mprMemcpy(char *dest, int destMax, const char *src, int nbytes) -{ - mprAssert(dest); - mprAssert(destMax <= 0 || destMax >= nbytes); - mprAssert(src); - mprAssert(nbytes >= 0); - - if (destMax > 0 && nbytes > destMax) { - mprAssert(0); - return MPR_ERR_WONT_FIT; - } - if (nbytes > 0) { - memcpy(dest, src, nbytes); - return nbytes; - } else { - return 0; - } -} - -/******************************************************************************/ - -int mprAllocMemcpy(MPR_LOC_DEC(ctx, loc), char **dest, int destMax, - const void *src, int nbytes) -{ - mprAssert(dest); - mprAssert(src); - mprAssert(nbytes > 0); - mprAssert(destMax <= 0 || destMax >= nbytes); - - if (destMax > 0 && nbytes > destMax) { - mprAssert(0); - return MPR_ERR_WONT_FIT; - } - if (nbytes > 0) { - *dest = (char*) mprAllocBlock(MPR_LOC_PASS(ctx,loc), nbytes); - if (*dest == 0) { - return MPR_ERR_MEMORY; - } - memcpy(*dest, src, nbytes); - } else { - *dest = (char*) mprAlloc(ctx, 1); - } - return nbytes; -} - -/******************************************************************************/ - -static int mprCoreStrcat(MPR_LOC_DEC(ctx, loc), char **destp, int destMax, - int existingLen, const char *delim, const char *src, va_list args) -{ - va_list ap; - char *dest, *str, *dp; - int sepLen, addBytes, required; - - mprAssert(destp); - mprAssert(destMax >= 0); - mprAssert(src); - - dest = *destp; - sepLen = (delim) ? strlen(delim) : 0; - -#ifdef __va_copy - __va_copy(ap, args); -#else - ap = args; -#endif - addBytes = 0; - if (existingLen > 0) { - addBytes += sepLen; - } - str = (char*) src; - - while (str) { - addBytes += strlen(str); - str = va_arg(ap, char*); - if (str) { - addBytes += sepLen; - } - } - - required = existingLen + addBytes + 1; - if (destMax > 0 && required >= destMax) { - mprAssert(0); - return MPR_ERR_WONT_FIT; - } - - if (ctx != 0) { - if (dest == 0) { - dest = (char*) mprAllocBlock(MPR_LOC_PASS(ctx, loc), required); - } else { - dest = (char*) mprReallocBlock(MPR_LOC_PASS(ctx, loc), dest, - required); - } - } else { - dest = (char*) *destp; - } - - dp = &dest[existingLen]; - if (delim && existingLen > 0) { - strcpy(dp, delim); - dp += sepLen; - } - - if (addBytes > 0) { -#ifdef __va_copy - __va_copy(ap, args); -#else - ap = args; -#endif - str = (char*) src; - while (str) { - strcpy(dp, str); - dp += strlen(str); - str = va_arg(ap, char*); - if (delim && str) { - strcpy(dp, delim); - dp += sepLen; - } - } - } else if (dest == 0) { - dest = (char*) mprAlloc(ctx, 1); - } - *dp = '\0'; - - *destp = dest; - mprAssert(dp < &dest[required]); - return required - 1; -} - -/***************************************************************************** - Note that this VARARGS function must be NULL (not 0, this must be a - pointer) terminated -*/ -int mprStrcat(char *dest, int destMax, const char *delim, const char *src, ...) -{ - va_list ap; - int rc; - - mprAssert(dest); - mprAssert(src); - - va_start(ap, src); - rc = mprCoreStrcat(MPR_LOC_ARGS(0), &dest, destMax, strlen(dest), - delim, src, ap); - va_end(ap); - return rc; -} - -/***************************************************************************** - Note that this VARARGS function must be NULL (not 0, this must be a - pointer) terminated -*/ -int mprAllocStrcat(MPR_LOC_DEC(ctx, loc), char **destp, int destMax, - const char *delim, const char *src, ...) -{ - va_list ap; - int rc; - - mprAssert(destp); - mprAssert(src); - - *destp = 0; - va_start(ap, src); - rc = mprCoreStrcat(MPR_LOC_PASS(ctx, loc), destp, destMax, 0, delim, - src, ap); - va_end(ap); - return rc; -} - -/***************************************************************************** - Note that this VARARGS function must be NULL (not 0, this must be a - pointer) terminated -*/ -int mprReallocStrcat(MPR_LOC_DEC(ctx, loc), char **destp, int destMax, - int existingLen, const char *delim, const char *src,...) -{ - va_list ap; - int rc; - - va_start(ap, src); - rc = mprCoreStrcat(MPR_LOC_PASS(ctx, loc), destp, destMax, existingLen, - delim, src, ap); - va_end(ap); - return rc; -} - -/******************************************************************************/ - -int mprStrlen(const char *src, int max) -{ - int len; - - len = strlen(src); - if (len >= max) { - mprAssert(0); - return MPR_ERR_WONT_FIT; - } - return len; -} - -/******************************************************************************/ - -char *mprStrTrim(char *str, const char *set) -{ - int len, i; - - if (str == 0 || set == 0) { - return str; - } - - i = strspn(str, set); - str += i; - - len = strlen(str); - while (strspn(&str[len - 1], set) > 0) { - str[len - 1] = '\0'; - len--; - } - return str; -} - -/******************************************************************************/ -/* - * Map a string to lower case (overwrites original string) - */ - -char *mprStrLower(char *str) -{ - char *cp; - - mprAssert(str); - - if (str == 0) { - return 0; - } - - for (cp = str; *cp; cp++) { - if (isupper(*cp)) { - *cp = (char) tolower(*cp); - } - } - return str; -} - -/******************************************************************************/ -/* - * Map a string to upper case (overwrites buffer) - */ - -char *mprStrUpper(char *str) -{ - char *cp; - - mprAssert(str); - if (str == 0) { - return 0; - } - - for (cp = str; *cp; cp++) { - if (islower(*cp)) { - *cp = (char) toupper(*cp); - } - } - return str; -} - -/******************************************************************************/ -/* - * Case insensitive string comparison. Stop at the end of str1. - */ - -int mprStrcmpAnyCase(const char *str1, const char *str2) -{ - int rc; - - if (str1 == 0 || str2 == 0) { - return -1; - } - if (str1 == str2) { - return 0; - } - - for (rc = 0; *str1 && rc == 0; str1++, str2++) { - rc = tolower(*str1) - tolower(*str2); - } - if (*str2) { - return -1; - } - return rc; -} - -/******************************************************************************/ -/* - * Case insensitive string comparison. Limited by length - */ - -int mprStrcmpAnyCaseCount(const char *str1, const char *str2, int len) -{ - int rc; - - if (str1 == 0 || str2 == 0) { - return -1; - } - if (str1 == str2) { - return 0; - } - - for (rc = 0; len-- > 0 && *str1 && rc == 0; str1++, str2++) { - rc = tolower(*str1) - tolower(*str2); - } - return rc; -} - -/******************************************************************************/ -/* - * Return the last portion of a pathname - */ - -const char *mprGetBaseName(const char *name) -{ - char *cp; - - cp = strrchr(name, '/'); - - if (cp == 0) { - cp = strrchr(name, '\\'); - if (cp == 0) { - return name; - } - } - if (cp == name) { - if (cp[1] == '\0') { - return name; - } - } else { - if (cp[1] == '\0') { - return ""; - } - } - return &cp[1]; -} - -/******************************************************************************/ -/* - * Return the directory portion of a pathname into the users buffer. - */ - -char *mprGetDirName(char *buf, int bufsize, const char *path) -{ - char *cp; - int dlen; - - mprAssert(path); - mprAssert(buf); - mprAssert(bufsize > 0); - - cp = strrchr(path, '/'); - if (cp == 0) { -#if WIN - cp = strrchr(path, '\\'); - if (cp == 0) -#endif - { - buf[0] = '\0'; - return buf; - } - } - - if (cp == path && cp[1] == '\0') { - strcpy(buf, "."); - return buf; - } - - dlen = cp - path; - if (dlen < bufsize) { - if (dlen == 0) { - dlen++; - } - mprMemcpy(buf, bufsize, path, dlen); - buf[dlen] = '\0'; - return buf; - } - return 0; -} - -/******************************************************************************/ -/* - * Thread-safe wrapping of strtok. Note "str" is modifed as per strtok() - */ - -char *mprStrTok(char *str, const char *delim, char **last) -{ - char *start, *end; - int i; - - start = str ? str : *last; - - if (start == 0) { - return 0; - } - - i = strspn(start, delim); - start += i; - if (*start == '\0') { - *last = 0; - return 0; - } - end = strpbrk(start, delim); - if (end) { - *end++ = '\0'; - i = strspn(end, delim); - end += i; - } - *last = end; - return start; -} - -/******************************************************************************/ -/* - * Split the buffer into word tokens - */ - -char *mprGetWordTok(char *buf, int bufsize, const char *str, const char *delim, - const char **tok) -{ - const char *start, *end; - int i, len; - - start = str ? str : *tok; - - if (start == 0) { - return 0; - } - - i = strspn(start, delim); - start += i; - if (*start =='\0') { - *tok = 0; - return 0; - } - end = strpbrk(start, delim); - if (end) { - len = min(end - start, bufsize - 1); - mprMemcpy(buf, bufsize, start, len); - buf[len] = '\0'; - } else { - if (mprStrcpy(buf, bufsize, start) < 0) { - buf[bufsize - 1] = '\0'; - return 0; - } - buf[bufsize - 1] = '\0'; - } - *tok = end; - return buf; -} - -/******************************************************************************/ -/* - * Format a number as a string. - */ - -char *mprItoa(char *buf, int size, int value) -{ - char numBuf[16]; - char *cp, *dp, *endp; - int negative; - - cp = &numBuf[sizeof(numBuf)]; - *--cp = '\0'; - - if (value < 0) { - negative = 1; - value = -value; - size--; - } else { - negative = 0; - } - - do { - *--cp = '0' + (value % 10); - value /= 10; - } while (value > 0); - - if (negative) { - *--cp = '-'; - } - - dp = buf; - endp = &buf[size]; - while (dp < endp && *cp) { - *dp++ = *cp++; - } - *dp++ = '\0'; - return buf; -} - -/******************************************************************************/ -/* - * Parse an ascii number. Supports radix 10 or 16. - */ - -int mprAtoi(const char *str, int radix) -{ - int c, val, negative; - - mprAssert(radix == 10 || radix == 16); - - if (str == 0) { - return 0; - } - - val = 0; - if (radix == 10 && *str == '-') { - negative = 1; - str++; - } else { - negative = 0; - } - - if (radix == 10) { - while (*str && isdigit(*str)) { - val = (val * radix) + *str - '0'; - str++; - } - } else if (radix == 16) { - if (*str == '0' && tolower(str[1]) == 'x') { - str += 2; - } - while (*str) { - c = tolower(*str); - if (isdigit(c)) { - val = (val * radix) + c - '0'; - } else if (c >= 'a' && c <= 'f') { - val = (val * radix) + c - 'a' + 10; - } else { - break; - } - str++; - } - } - - return (negative) ? -val: val; -} - -/******************************************************************************/ -/* - * Make an argv array. Caller must free by calling mprFree(argv) to free - * everything. - */ - -int mprMakeArgv(MprCtx ctx, const char *program, const char *cmd, - char ***argvp, int *argcp) -{ - char *cp, **argv, *buf, *args; - int size, argc; - - /* - * Allocate one buffer for argv and the actual args themselves - */ - size = strlen(cmd) + 1; - - buf = (char*) mprAlloc(ctx, (MPR_MAX_ARGC * sizeof(char*)) + size); - if (buf == 0) { - return MPR_ERR_MEMORY; - } - - args = &buf[MPR_MAX_ARGC * sizeof(char*)]; - strcpy(args, cmd); - argv = (char**) buf; - - argc = 0; - if (program) { - argv[argc++] = (char*) mprStrdup(ctx, program); - } - - for (cp = args; cp && *cp != '\0'; argc++) { - if (argc >= MPR_MAX_ARGC) { - mprAssert(argc < MPR_MAX_ARGC); - mprFree(buf); - *argvp = 0; - if (argcp) { - *argcp = 0; - } - return MPR_ERR_TOO_MANY; - } - while (isspace(*cp)) { - cp++; - } - if (*cp == '\0') { - break; - } - if (*cp == '"') { - cp++; - argv[argc] = cp; - while ((*cp != '\0') && (*cp != '"')) { - cp++; - } - } else { - argv[argc] = cp; - while (*cp != '\0' && !isspace(*cp)) { - cp++; - } - } - if (*cp != '\0') { - *cp++ = '\0'; - } - } - argv[argc] = 0; - - if (argcp) { - *argcp = argc; - } - *argvp = argv; - - return argc; -} - -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/mprSymbol.c b/source4/lib/appweb/ejs-2.0/mpr/mprSymbol.c deleted file mode 100644 index 11ac278db4..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mprSymbol.c +++ /dev/null @@ -1,279 +0,0 @@ -/* - * @file mprSym.cpp - * @brief Fast hashing symbol table lookup module - * @overview This symbol table uses a fast key lookup mechanism. Keys are - * strings and the value entries are arbitrary pointers. The keys are - * hashed into a series of buckets which then have a chain of hash - * entries using the standard doubly linked list classes (List/Link). - * The chain in in collating sequence so search time through the chain - * is on average (N/hashSize)/2. - * @remarks This module is not thread-safe. It is the callers responsibility - * to perform all thread synchronization. - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http: *www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http: *www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "mpr.h" - -/**************************** Forward Declarations ****************************/ - -static int hashIndex(const char *key, int size); -static MprSymbol *lookupInner(int *bucketIndex, MprSymbol **prevSp, - MprSymbolTable *table, const char *key); - -/*********************************** Code *************************************/ -/* - * Create a new symbol table of a given size. Caller should provide a size - * that is a prime number for the greatest efficiency. Caller should use - * mprFree to free the symbol table. - */ - -MprSymbolTable *mprCreateSymbolTable(MprCtx ctx, int hashSize) -{ - MprSymbolTable *table; - - table = mprAllocTypeZeroed(ctx, MprSymbolTable); - if (table == 0) { - return 0; - } - - if (hashSize < MPR_DEFAULT_HASH_SIZE) { - hashSize = MPR_DEFAULT_HASH_SIZE; - } - table->hashSize = hashSize; - - table->count = 0; - table->hashSize = hashSize; - table->buckets = mprAllocZeroedBlock(MPR_LOC_ARGS(table), - sizeof(MprSymbol*) * hashSize); - - if (table->buckets == 0) { - mprFree(table); - return 0; - } - - return table; -} - -/******************************************************************************/ -/* - * Insert an entry into the symbol table. If the entry already exists, update - * its value. Order of insertion is not preserved. - */ - -MprSymbol *mprInsertSymbol(MprSymbolTable *table, const char *key, void *ptr) -{ - MprSymbol *sp, *prevSp; - int index; - - sp = lookupInner(&index, &prevSp, table, key); - - if (sp != 0) { - /* - * Already exists. Just update the data. - */ - sp->data = ptr; - return sp; - } - - /* - * New entry - */ - sp = mprAllocTypeZeroed(table, MprSymbol); - if (sp == 0) { - return 0; - } - - sp->data = ptr; - sp->key = mprStrdup(sp, key); - sp->bucket = index; - - sp->next = table->buckets[index]; - table->buckets[index] = sp; - - table->count++; - return sp; -} - -/******************************************************************************/ -/* - * Remove an entry from the table - */ - -int mprRemoveSymbol(MprSymbolTable *table, const char *key) -{ - MprSymbol *sp, *prevSp; - int index; - - if ((sp = lookupInner(&index, &prevSp, table, key)) == 0) { - return MPR_ERR_NOT_FOUND; - } - - if (prevSp) { - prevSp->next = sp->next; - } else { - table->buckets[index] = sp->next; - } - table->count--; - - mprFree(sp); - return 0; -} - -/******************************************************************************/ -/* - * Lookup a key and return the hash entry - */ - -void *mprLookupSymbol(MprSymbolTable *table, const char *key) -{ - MprSymbol *sp; - - mprAssert(key); - - sp = lookupInner(0, 0, table, key); - if (sp == 0) { - return 0; - } - return sp->data; -} - -/******************************************************************************/ - -static MprSymbol *lookupInner(int *bucketIndex, MprSymbol **prevSp, - MprSymbolTable *table, const char *key) -{ - MprSymbol *sp, *prev; - int index, rc; - - mprAssert(key); - - index = hashIndex(key, table->hashSize); - if (bucketIndex) { - *bucketIndex = index; - } - - sp = table->buckets[index]; - prev = 0; - - while (sp) { - rc = strcmp(sp->key, key); - if (rc == 0) { - if (prevSp) { - *prevSp = prev; - } - return sp; - } - prev = sp; - mprAssert(sp != sp->next); - sp = sp->next; - } - return 0; -} - -/******************************************************************************/ - -int mprGetSymbolCount(MprSymbolTable *table) -{ - return table->count; -} - -/******************************************************************************/ -/* - * Return the first entry in the table. - */ - -MprSymbol *mprGetFirstSymTab(MprSymbolTable *table) -{ - MprSymbol *sp; - int i; - - mprAssert(table); - - for (i = 0; i < table->hashSize; i++) { - if ((sp = (MprSymbol*) table->buckets[i]) != 0) { - return sp; - } - } - return 0; -} - -/******************************************************************************/ -/* - * Return the next entry in the table - */ - -MprSymbol *mprGetNextSymTab(MprSymbolTable *table, MprSymbol *last) -{ - MprSymbol *sp; - int i; - - mprAssert(table); - - if (last->next) { - return last->next; - } - - for (i = last->bucket + 1; i < table->hashSize; i++) { - if ((sp = (MprSymbol*) table->buckets[i]) != 0) { - return sp; - } - } - return 0; -} - -/******************************************************************************/ -/* - * Hash the key to produce a hash index. - */ - -static int hashIndex(const char *key, int size) -{ - uint sum; - - sum = 0; - while (*key) { - sum += (sum * 33) + *key++; - } - - return sum % size; -} - -/******************************************************************************/ -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs-2.0/mpr/mprUnix.h b/source4/lib/appweb/ejs-2.0/mpr/mprUnix.h deleted file mode 100644 index fbbe29ae9c..0000000000 --- a/source4/lib/appweb/ejs-2.0/mpr/mprUnix.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * @file mprUnix.h - * @brief Make windows a bit more unix like - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/******************************* Documentation ********************************/ - -/* - * This header is part of the Mbedthis Portable Runtime and aims to include - * all necessary O/S headers and to unify the constants and declarations - * required by Mbedthis products. It can be included by C or C++ programs. - */ - -/******************************************************************************/ - -#ifndef _h_MPR_UNIX -#define _h_MPR_UNIX 1 - -/******************************************************************************/ -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Define BLD_NO_POSIX_REMAP if these defines mess with your app - */ -#if WIN && !BLD_NO_POSIX_REMAP -/* - * MOB -- clashes with ATL - */ -#define access _access -#define close _close -#define fileno _fileno -#define fstat _fstat -#define getpid _getpid -#define open _open -#define putenv _putenv -#define read _read -#define stat _stat -#define umask _umask -#define unlink _unlink -#define write _write -#define strdup _strdup -#define lseek _lseek -#define getcwd _getcwd -#define chdir _chdir - -#define mkdir(a,b) _mkdir(a) -#define rmdir(a) _rmdir(a) - -#define R_OK 4 -#define W_OK 2 -#define MPR_TEXT "t" - -extern void srand48(long); -extern long lrand48(void); -extern long ulimit(int, ...); -extern long nap(long); -extern int getuid(void); -extern int geteuid(void); -#endif - - -/******************************************************************************/ -#ifdef __cplusplus -} -#endif - -#endif /* _h_MPR_UNIX */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs/config.h b/source4/lib/appweb/ejs/config.h deleted file mode 100644 index 8c06d28147..0000000000 --- a/source4/lib/appweb/ejs/config.h +++ /dev/null @@ -1,141 +0,0 @@ -#define BLD_PRODUCT "Samba4" -#define BLD_NAME "Samba4 WEB Applications" -#define BLD_VERSION "4" -#define BLD_NUMBER "1" -#define BLD_TYPE "DEBUG" -#define BLD_DEFAULTS "normal" -#define BLD_PACKAGES "" -#define BLD_APPWEB_CONFIG "normal.conf" -#define BLD_APPWEB 0 -#define BLD_COMPANY "Mbedthis" -#define BLD_DEBUG 0 -#define BLD_DIRS "bootstrap include obj bin mpr ejs esp http doc appWeb appWebSamples images" -#define BLD_HTTP_PORT 7777 -#define BLD_LIB_VERSION "1.0.0" -#define BLD_SSL_PORT 4443 -#define BLD_CLEAN_INSTALL "0" -#define BLD_LICENSE "gpl" -#define BLD_HOST_SYSTEM "i686-pc-linux-gnu" -#define BLD_BUILD_SYSTEM "i686-pc-linux-gnu" -#define BLD_HOST_OS "LINUX" -#define BLD_HOST_CPU_ARCH MPR_CPU_IX86 -#define BLD_HOST_CPU "i686" -#define BLD_HOST_UNIX 1 -#define BLD_BUILD_OS "LINUX" -#define BLD_BUILD_CPU_ARCH MPR_CPU_IX86 -#define BLD_BUILD_CPU i686 -#define BLD_BUILD_UNIX 1 -#define BLD_ROOT_PREFIX "/" -#define BLD_FEATURE_ACCESS_LOG 0 -#define BLD_FEATURE_ADMIN_MODULE 0 -#define BLD_FEATURE_ASPNET_MODULE 0 -#define BLD_FEATURE_ASSERT 1 -#define BLD_FEATURE_AUTH_MODULE 0 -#define BLD_FEATURE_C_API_MODULE 1 -#define BLD_FEATURE_C_API_CLIENT 0 -#define BLD_FEATURE_CGI_MODULE 0 -#define BLD_FEATURE_COMPAT_MODULE 0 -#define BLD_FEATURE_CONFIG_PARSE 0 -#define BLD_FEATURE_CONFIG_SAVE 0 -#define BLD_FEATURE_COOKIE 0 -#define BLD_FEATURE_COPY_MODULE 0 -#define BLD_FEATURE_DIGEST 0 -#define BLD_FEATURE_DLL 0 -#define BLD_FEATURE_EGI_MODULE 0 -#define BLD_FEATURE_EJS 1 -#define BLD_FEATURE_ESP_MODULE 1 -#define BLD_FEATURE_EVAL_PERIOD 30 -#define BLD_FEATURE_FLOATING_POINT 1 -#define BLD_FEATURE_IF_MODIFIED 0 -#define BLD_FEATURE_INT64 1 -#define BLD_FEATURE_KEEP_ALIVE 0 -#define BLD_FEATURE_LEGACY_API 0 -#define BLD_FEATURE_LIB_STDCPP 0 -#define BLD_FEATURE_LICENSE 0 -#define BLD_FEATURE_LOG 0 -#define BLD_FEATURE_MULTITHREAD 0 -#define BLD_FEATURE_MALLOC 0 -#define BLD_FEATURE_MALLOC_STATS 0 -#define BLD_FEATURE_MALLOC_LEAK 0 -#define BLD_FEATURE_MALLOC_HOOK 0 -#define BLD_FEATURE_NUM_TYPE int64_t -#define BLD_FEATURE_NUM_TYPE_ID MPR_TYPE_INT64 -#define BLD_FEATURE_ROMFS 0 -#define BLD_FEATURE_RUN_AS_SERVICE 0 -#define BLD_FEATURE_SAFE_STRINGS 0 -#define BLD_FEATURE_SAMPLES 0 -#define BLD_FEATURE_SESSION 1 -#define BLD_FEATURE_SHARED 0 -#define BLD_FEATURE_SQUEEZE 0 -#define BLD_FEATURE_SSL_MODULE 0 -#define BLD_FEATURE_STATIC 1 -#define BLD_FEATURE_STATIC_LINK_LIBC 0 -#define BLD_FEATURE_TEST 0 -#define BLD_FEATURE_UPLOAD_MODULE 0 -#define BLD_FEATURE_XDB_MODULE 0 -#define BLD_FEATURE_ADMIN_MODULE_BUILTIN 0 -#define BLD_FEATURE_ASPNET_MODULE_BUILTIN 0 -#define BLD_FEATURE_AUTH_MODULE_BUILTIN 0 -#define BLD_FEATURE_C_API_MODULE_BUILTIN 0 -#define BLD_FEATURE_CGI_MODULE_BUILTIN 0 -#define BLD_FEATURE_COMPAT_MODULE_BUILTIN 0 -#define BLD_FEATURE_COPY_MODULE_BUILTIN 0 -#define BLD_FEATURE_EGI_MODULE_BUILTIN 0 -#define BLD_FEATURE_ESP_MODULE_BUILTIN 0 -#define BLD_FEATURE_SSL_MODULE_BUILTIN 0 -#define BLD_FEATURE_UPLOAD_MODULE_BUILTIN 0 -#define BLD_FEATURE_XDB_MODULE_BUILTIN 0 -#define BLD_FEATURE_ADMIN_MODULE_LOADABLE 0 -#define BLD_FEATURE_ASPNET_MODULE_LOADABLE 0 -#define BLD_FEATURE_AUTH_MODULE_LOADABLE 0 -#define BLD_FEATURE_C_API_MODULE_LOADABLE 0 -#define BLD_FEATURE_CGI_MODULE_LOADABLE 0 -#define BLD_FEATURE_COMPAT_MODULE_LOADABLE 0 -#define BLD_FEATURE_COPY_MODULE_LOADABLE 0 -#define BLD_FEATURE_EGI_MODULE_LOADABLE 0 -#define BLD_FEATURE_ESP_MODULE_LOADABLE 0 -#define BLD_FEATURE_SSL_MODULE_LOADABLE 0 -#define BLD_FEATURE_UPLOAD_MODULE_LOADABLE 0 -#define BLD_FEATURE_XDB_MODULE_LOADABLE 0 -#define BLD_AR_FOR_BUILD "ar" -#define BLD_CC_FOR_BUILD "cc" -#define BLD_CSC_FOR_BUILD "" -#define BLD_JAVAC_FOR_BUILD "" -#define BLD_LD_FOR_BUILD "ld" -#define BLD_RANLIB_FOR_BUILD "" -#define BLD_NM_FOR_BUILD "nm" -#define BLD_CFLAGS_FOR_BUILD "" -#define BLD_IFLAGS_FOR_BUILD "" -#define BLD_LDFLAGS_FOR_BUILD "" -#define BLD_ARCHIVE_FOR_BUILD ".a" -#define BLD_EXE_FOR_BUILD "" -#define BLD_OBJ_FOR_BUILD ".o" -#define BLD_PIOBJ_FOR_BUILD ".lo" -#define BLD_CLASS_FOR_BUILD ".class" -#define BLD_SHLIB_FOR_BUILD "" -#define BLD_SHOBJ_FOR_BUILD ".so" -#define BLD_AR_FOR_HOST "ar" -#define BLD_CC_FOR_HOST "cc" -#define BLD_CSC_FOR_HOST "csc" -#define BLD_JAVAC_FOR_HOST "javac" -#define BLD_LD_FOR_HOST "ld" -#define BLD_RANLIB_FOR_HOST "true" -#define BLD_NM_FOR_HOST "nm" -#define BLD_CFLAGS_FOR_HOST "" -#define BLD_IFLAGS_FOR_HOST "" -#define BLD_LDFLAGS_FOR_HOST "" -#define BLD_ARCHIVE_FOR_HOST ".a" -#define BLD_EXE_FOR_HOST "" -#define BLD_OBJ_FOR_HOST ".o" -#define BLD_PIOBJ_FOR_HOST ".lo" -#define BLD_CLASS_FOR_HOST ".class" -#define BLD_SHLIB_FOR_HOST "" -#define BLD_SHOBJ_FOR_HOST ".so" -#define BLD_TOOLS_DIR "${BLD_TOP}/bin" -#define BLD_BIN_DIR "${BLD_TOP}/bin" -#define BLD_INC_DIR "/usr/include/${BLD_PRODUCT}" -#define BLD_EXP_OBJ_DIR "${BLD_TOP}/obj" - -#ifndef MAX_FLOAT -#define MAX_FLOAT 3.40282347e+38F -#endif diff --git a/source4/lib/appweb/ejs/ejs.h b/source4/lib/appweb/ejs/ejs.h deleted file mode 100644 index c7b0c54d8e..0000000000 --- a/source4/lib/appweb/ejs/ejs.h +++ /dev/null @@ -1,136 +0,0 @@ -/* - * @file ejs.h - * @brief Primary Embedded Javascript (ECMAScript) header. - * @overview This Embedded Javascript (EJS) header defines the - * public API. This API should only be used by those directly - * using EJS without using Embedded Server Pages (ESP). ESP - * wraps all relevant APIs to expose a single consistent API. - * \n\n - * This API requires the mpr/var.h facilities to create and - * manage objects and properties. - */ -/********************************* Copyright **********************************/ -/* - * @copy default.g - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * Portions Copyright (c) GoAhead Software, 1995-2000. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#ifndef _h_EJS -#define _h_EJS 1 - -#include "lib/appweb/mpr/miniMpr.h" -#include "lib/appweb/mpr/var.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/********************************* Prototypes *********************************/ - -typedef MprVarHandle EjsId; -typedef MprVarHandle EjsHandle; - -/* - * Multithreaded lock routines - */ -typedef void (*EjsLock)(void *lockData); -typedef void (*EjsUnlock)(void *lockData); - -/********************************* Prototypes *********************************/ -/* - * Module management - */ -extern int ejsOpen(EjsLock lock, EjsUnlock unlock, void *lockData); -extern void ejsClose(void); -extern EjsId ejsOpenEngine(EjsHandle primaryHandle, EjsHandle altHandle); -extern void ejsCloseEngine(EjsId eid); - -void *ejs_save_state(void); -void ejs_restore_state(void *ptr); - -/* - * Evaluation functions - */ -extern int ejsEvalFile(EjsId eid, char *path, MprVar *result, char **emsg); -extern int ejsEvalScript(EjsId eid, char *script, MprVar *result, - char **emsg); -extern int ejsRunFunction(int eid, MprVar *obj, const char *functionName, - MprArray *args); - -/* - * Composite variable get / set routines. Can also use the MPR property - * routines on an object variable. - */ -extern MprVar ejsCreateObj(const char *name, int hashSize); -extern MprVar ejsCreateArray(const char *name, int hashSize); -extern bool ejsDestroyVar(MprVar *obj); -extern int ejsCopyVar(EjsId eid, const char *var, MprVar *value, - bool copyRef); -extern int ejsReadVar(EjsId eid, const char *var, MprVar *value); -extern int ejsWriteVar(EjsId eid, const char *var, MprVar *value); -extern int ejsWriteVarValue(EjsId eid, const char *var, MprVar value); -extern int ejsDeleteVar(EjsId eid, const char *var); - -extern MprVar *ejsGetLocalObject(EjsId eid); -extern MprVar *ejsGetGlobalObject(EjsId eid); - -/* - * Function routines - */ -extern void ejsDefineFunction(EjsId eid, const char *functionName, - char *args, char *body); -extern void ejsDefineCFunction(EjsId eid, const char *functionName, - MprCFunction fn, void *thisPtr, int flags); -extern void ejsDefineStringCFunction(EjsId eid, const char *functionName, - MprStringCFunction fn, void *thisPtr, int flags); -extern void *ejsGetThisPtr(EjsId eid); -extern MprVar *ejsGetReturnValue(EjsId eid); -extern int ejsGetLineNumber(EjsId eid); -extern int ejsParseArgs(int argc, char **argv, char *fmt, ...); -extern void ejsSetErrorMsg(EjsId eid, const char* fmt, ...) - PRINTF_ATTRIBUTE(2,3); -extern void ejsSetReturnValue(EjsId eid, MprVar value); -extern void ejsSetReturnString(EjsId eid, const char *str); - -#ifdef __cplusplus -} -#endif -#endif /* _h_EJS */ - -/*****************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs/ejsInternal.h b/source4/lib/appweb/ejs/ejsInternal.h deleted file mode 100644 index 8b66dafdca..0000000000 --- a/source4/lib/appweb/ejs/ejsInternal.h +++ /dev/null @@ -1,295 +0,0 @@ -/* - * @file ejsInternal.h - * @brief Private header for Embedded Javascript (ECMAScript) - * @overview This Embedded Javascript header defines the private Embedded - * Javascript internal structures. - */ -/********************************* Copyright **********************************/ -/* - * @copy default.g - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * Portions Copyright (c) GoAhead Software, 1995-2000. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************* Includes ***********************************/ - -#ifndef _h_EJS_INTERNAL -#define _h_EJS_INTERNAL 1 - -#include "ejs.h" - -/********************************** Defines ***********************************/ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Constants - */ - -#if BLD_FEATURE_SQUEEZE - #define EJS_PARSE_INCR 256 /* Growth factor */ - #define EJS_MAX_RECURSE 25 /* Sanity for maximum recursion */ - #define EJS_MAX_ID 128 /* Maximum ID length */ - #define EJS_OBJ_HASH_SIZE 13 /* Object hash table size */ - #define EJS_SMALL_OBJ_HASH_SIZE 11 /* Small object hash size */ - #define EJS_LIST_INCR 8 /* Growth increment for lists */ -#else - #define EJS_PARSE_INCR 1024 /* Growth factor */ - #define EJS_MAX_RECURSE 100 /* Sanity for maximum recursion */ - #define EJS_MAX_ID 256 /* Maximum ID length */ - #define EJS_OBJ_HASH_SIZE 29 /* Object hash table size */ - #define EJS_SMALL_OBJ_HASH_SIZE 11 /* Small object hash size */ - #define EJS_LIST_INCR 16 /* Growth increment for lists */ -#endif -#define EJS_TOKEN_STACK 4 /* Put back token stack */ - -/* - * Lexical analyser tokens - */ -#define EJS_TOK_ERR -1 /* Any error */ -#define EJS_TOK_LPAREN 1 /* ( */ -#define EJS_TOK_RPAREN 2 /* ) */ -#define EJS_TOK_IF 3 /* if */ -#define EJS_TOK_ELSE 4 /* else */ -#define EJS_TOK_LBRACE 5 /* { */ -#define EJS_TOK_RBRACE 6 /* } */ -#define EJS_TOK_LOGICAL 7 /* ||, &&, ! */ -#define EJS_TOK_EXPR 8 /* +, -, /, % */ -#define EJS_TOK_SEMI 9 /* ; */ -#define EJS_TOK_LITERAL 10 /* literal string */ -#define EJS_TOK_FUNCTION_NAME 11 /* functionName */ -#define EJS_TOK_NEWLINE 12 /* newline white space */ -#define EJS_TOK_ID 13 /* Identifier */ -#define EJS_TOK_EOF 14 /* End of script */ -#define EJS_TOK_COMMA 15 /* Comma */ -#define EJS_TOK_VAR 16 /* var */ -#define EJS_TOK_ASSIGNMENT 17 /* = */ -#define EJS_TOK_FOR 18 /* for */ -#define EJS_TOK_INC_DEC 19 /* ++, -- */ -#define EJS_TOK_RETURN 20 /* return */ -#define EJS_TOK_PERIOD 21 /* . */ -#define EJS_TOK_LBRACKET 22 /* [ */ -#define EJS_TOK_RBRACKET 23 /* ] */ -#define EJS_TOK_NEW 24 /* new */ -#define EJS_TOK_DELETE 25 /* delete */ -#define EJS_TOK_IN 26 /* in */ -#define EJS_TOK_FUNCTION 27 /* function */ -#define EJS_TOK_NUMBER 28 /* Number */ - -/* - * Expression operators - */ -#define EJS_EXPR_LESS 1 /* < */ -#define EJS_EXPR_LESSEQ 2 /* <= */ -#define EJS_EXPR_GREATER 3 /* > */ -#define EJS_EXPR_GREATEREQ 4 /* >= */ -#define EJS_EXPR_EQ 5 /* == */ -#define EJS_EXPR_NOTEQ 6 /* != */ -#define EJS_EXPR_PLUS 7 /* + */ -#define EJS_EXPR_MINUS 8 /* - */ -#define EJS_EXPR_DIV 9 /* / */ -#define EJS_EXPR_MOD 10 /* % */ -#define EJS_EXPR_LSHIFT 11 /* << */ -#define EJS_EXPR_RSHIFT 12 /* >> */ -#define EJS_EXPR_MUL 13 /* * */ -#define EJS_EXPR_ASSIGNMENT 14 /* = */ -#define EJS_EXPR_INC 15 /* ++ */ -#define EJS_EXPR_DEC 16 /* -- */ -#define EJS_EXPR_BOOL_COMP 17 /* ! */ - -/* - * Conditional operators - */ -#define EJS_COND_AND 1 /* && */ -#define EJS_COND_OR 2 /* || */ -#define EJS_COND_NOT 3 /* ! */ - -/* - * States - */ -#define EJS_STATE_ERR -1 /* Error state */ -#define EJS_STATE_EOF 1 /* End of file */ -#define EJS_STATE_COND 2 /* Parsing a "(conditional)" stmt */ -#define EJS_STATE_COND_DONE 3 -#define EJS_STATE_RELEXP 4 /* Parsing a relational expr */ -#define EJS_STATE_RELEXP_DONE 5 -#define EJS_STATE_EXPR 6 /* Parsing an expression */ -#define EJS_STATE_EXPR_DONE 7 -#define EJS_STATE_STMT 8 /* Parsing General statement */ -#define EJS_STATE_STMT_DONE 9 -#define EJS_STATE_STMT_BLOCK_DONE 10 /* End of block "}" */ -#define EJS_STATE_ARG_LIST 11 /* Function arg list */ -#define EJS_STATE_ARG_LIST_DONE 12 -#define EJS_STATE_DEC_LIST 16 /* Declaration list */ -#define EJS_STATE_DEC_LIST_DONE 17 -#define EJS_STATE_DEC 18 /* Declaration statement */ -#define EJS_STATE_DEC_DONE 19 -#define EJS_STATE_RET 20 /* Return statement */ - -#define EJS_STATE_BEGIN EJS_STATE_STMT - -/* - * General parsing flags. - */ -#define EJS_FLAGS_EXE 0x1 /* Execute statements */ -#define EJS_FLAGS_LOCAL 0x2 /* Get local vars only */ -#define EJS_FLAGS_GLOBAL 0x4 /* Get global vars only */ -#define EJS_FLAGS_CREATE 0x8 /* Create var */ -#define EJS_FLAGS_ASSIGNMENT 0x10 /* In assignment stmt */ -#define EJS_FLAGS_DELETE 0x20 /* Deleting a variable */ -#define EJS_FLAGS_FOREACH 0x40 /* In foreach */ -#define EJS_FLAGS_NEW 0x80 /* In a new stmt() */ -#define EJS_FLAGS_EXIT 0x100 /* Must exit */ - -/* - * Putback token - */ - -typedef struct EjsToken { - char *token; /* Token string */ - int id; /* Token ID */ -} EjsToken; - -/* - * EJ evaluation block structure - */ -typedef struct ejEval { - EjsToken putBack[EJS_TOKEN_STACK]; /* Put back token stack */ - int putBackIndex; /* Top of stack index */ - MprStr line; /* Current line */ - int lineLength; /* Current line length */ - int lineNumber; /* Parse line number */ - int lineColumn; /* Column in line */ - MprStr script; /* Input script for parsing */ - char *scriptServp; /* Next token in the script */ - int scriptSize; /* Length of script */ - MprStr tokbuf; /* Current token */ - char *tokEndp; /* Pointer past end of token */ - char *tokServp; /* Pointer to next token char */ - int tokSize; /* Size of token buffer */ - struct ejEval *next; /* used for backtraces */ - const char *procName; /* gives name in backtrace */ -} EjsInput; - -/* - * Function call structure - */ -typedef struct { - MprArray *args; /* Args for function */ - MprVar *fn; /* Function definition */ - char *procName; /* Function name */ -} EjsProc; - -/* - * Per EJS structure - */ -typedef struct ej { - EjsHandle altHandle; /* alternate callback handle */ - MprVar *currentObj; /* Ptr to current object */ - MprVar *currentProperty; /* Ptr to current property */ - EjsId eid; /* Halloc handle */ - char *error; /* Error message */ - int exitStatus; /* Status to exit() */ - int flags; /* Flags */ - MprArray *frames; /* List of variable frames */ - MprVar *global; /* Global object */ - EjsInput *input; /* Input evaluation block */ - MprVar *local; /* Local object */ - EjsHandle primaryHandle; /* primary callback handle */ - EjsProc *proc; /* Current function */ - MprVar result; /* Variable result */ - void *thisPtr; /* C++ ptr for functions */ - int tid; /* Current token id */ - char *token; /* Pointer to token string */ - MprVar tokenNumber; /* Parsed number */ -} Ejs; - -typedef int EjsBlock; /* Scope block id */ - -/* - * Function callback when using Alternate handles. - */ -typedef int (*EjsAltStringCFunction)(EjsHandle userHandle, EjsHandle altHandle, - int argc, char **argv); -typedef int (*EjsAltCFunction)(EjsHandle userHandle, EjsHandle altHandle, - int argc, MprVar **argv); - -/******************************** Prototypes **********************************/ -/* - * Ejs Lex - */ -extern int ejsLexOpenScript(Ejs* ep, char *script); -extern void ejsLexCloseScript(Ejs* ep); -extern int ejsInitInputState(EjsInput *ip); -extern void ejsLexSaveInputState(Ejs* ep, EjsInput* state); -extern void ejsLexFreeInputState(Ejs* ep, EjsInput* state); -extern void ejsLexRestoreInputState(Ejs* ep, EjsInput* state); -extern int ejsLexGetToken(Ejs* ep, int state); -extern void ejsLexPutbackToken(Ejs* ep, int tid, char *string); - -/* - * Parsing - */ -extern MprVar *ejsFindObj(Ejs *ep, int state, const char *property, - int flags); -extern MprVar *ejsFindProperty(Ejs *ep, int state, MprVar *obj, - char *property, int flags); -extern int ejsGetVarCore(Ejs *ep, const char *var, MprVar **obj, - MprVar **varValue, int flags); -extern int ejsParse(Ejs *ep, int state, int flags); -extern Ejs *ejsPtr(EjsId eid); -extern void ejsSetExitStatus(int eid, int status); -extern void ejsSetFlags(int orFlags, int andFlags); - -/* - * Create variable scope blocks - */ -extern EjsBlock ejsOpenBlock(EjsId eid); -extern int ejsCloseBlock(EjsId eid, EjsBlock vid); -extern int ejsEvalBlock(EjsId eid, char *script, MprVar *v, char **err); -extern int ejsDefineStandardProperties(MprVar *objVar); - -/* - * Error handling - */ -extern void ejsError(Ejs *ep, const char *fmt, ...) PRINTF_ATTRIBUTE(2,3); - -#ifdef __cplusplus -} -#endif -#endif /* _h_EJS_INTERNAL */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs/ejsLex.c b/source4/lib/appweb/ejs/ejsLex.c deleted file mode 100644 index b9a363cfc9..0000000000 --- a/source4/lib/appweb/ejs/ejsLex.c +++ /dev/null @@ -1,923 +0,0 @@ -/* - * @file ejsLex.c - * @brief EJS Lexical Analyser - * @overview EJS lexical analyser. This implementes a lexical analyser - * for a subset of the JavaScript language. - */ -/********************************* Copyright **********************************/ -/* - * @copy default.g - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * Portions Copyright (c) GoAhead Software, 1995-2000. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejsInternal.h" - -#if BLD_FEATURE_EJS - -/****************************** Forward Declarations **************************/ - -static int getLexicalToken(Ejs *ep, int state); -static int tokenAddChar(Ejs *ep, int c); -static int inputGetc(Ejs *ep); -static void inputPutback(Ejs *ep, int c); -static int charConvert(Ejs *ep, int base, int maxDig); - -/************************************* Code ***********************************/ -/* - * Open a new input script - */ - -int ejsLexOpenScript(Ejs *ep, char *script) -{ - EjsInput *ip; - - mprAssert(ep); - mprAssert(script); - - if ((ip = mprMalloc(sizeof(EjsInput))) == NULL) { - return -1; - } - memset(ip, 0, sizeof(*ip)); - ip->next = ep->input; - ep->input = ip; - ip->procName = ep->proc?ep->proc->procName:NULL; - -/* - * Create the parse token buffer and script buffer - */ - ip->tokbuf = mprMalloc(EJS_PARSE_INCR); - ip->tokSize = EJS_PARSE_INCR; - ip->tokServp = ip->tokbuf; - ip->tokEndp = ip->tokbuf; - - ip->script = mprStrdup(script); - ip->scriptSize = strlen(script); - ip->scriptServp = ip->script; - - ip->lineNumber = 1; - ip->lineLength = 0; - ip->lineColumn = 0; - ip->line = NULL; - - ip->putBackIndex = -1; - - return 0; -} - -/******************************************************************************/ -/* - * Close the input script - */ - -void ejsLexCloseScript(Ejs *ep) -{ - EjsInput *ip; - int i; - - mprAssert(ep); - - ip = ep->input; - mprAssert(ip); - ep->input = ip->next; - - for (i = 0; i < EJS_TOKEN_STACK; i++) { - mprFree(ip->putBack[i].token); - ip->putBack[i].token = 0; - } - - mprFree(ip->line); - mprFree(ip->tokbuf); - mprFree(ip->script); - - mprFree(ip); -} - -/******************************************************************************/ -/* - * Initialize an input state structure - */ - -int ejsInitInputState(EjsInput *ip) -{ - mprAssert(ip); - - memset(ip, 0, sizeof(*ip)); - ip->putBackIndex = -1; - - return 0; -} -/******************************************************************************/ -/* - * Save the input state - */ - -void ejsLexSaveInputState(Ejs *ep, EjsInput *state) -{ - EjsInput *ip; - int i; - - mprAssert(ep); - - ip = ep->input; - mprAssert(ip); - - *state = *ip; - - for (i = 0; i < ip->putBackIndex; i++) { - state->putBack[i].token = mprStrdup(ip->putBack[i].token); - state->putBack[i].id = ip->putBack[i].id; - } - for (; i < EJS_TOKEN_STACK; i++) { - state->putBack[i].token = 0; - } - - state->line = mprMalloc(ip->lineLength); - mprStrcpy(state->line, ip->lineLength, ip->line); - - state->lineColumn = ip->lineColumn; - state->lineNumber = ip->lineNumber; - state->lineLength = ip->lineLength; -} - -/******************************************************************************/ -/* - * Restore the input state - */ - -void ejsLexRestoreInputState(Ejs *ep, EjsInput *state) -{ - EjsInput *ip; - int i; - - mprAssert(ep); - mprAssert(state); - - ip = ep->input; - mprAssert(ip); - - ip->tokbuf = state->tokbuf; - ip->tokServp = state->tokServp; - ip->tokEndp = state->tokEndp; - ip->tokSize = state->tokSize; - - ip->script = state->script; - ip->scriptServp = state->scriptServp; - ip->scriptSize = state->scriptSize; - - ip->putBackIndex = state->putBackIndex; - for (i = 0; i < ip->putBackIndex; i++) { - mprFree(ip->putBack[i].token); - ip->putBack[i].id = state->putBack[i].id; - ip->putBack[i].token = mprStrdup(state->putBack[i].token); - } - - mprFree(ip->line); - ip->line = mprMalloc(state->lineLength); - mprStrcpy(ip->line, state->lineLength, state->line); - - ip->lineColumn = state->lineColumn; - ip->lineNumber = state->lineNumber; - ip->lineLength = state->lineLength; -} - -/******************************************************************************/ -/* - * Free a saved input state - */ - -void ejsLexFreeInputState(Ejs *ep, EjsInput *state) -{ - int i; - - mprAssert(ep); - mprAssert(state); - - for (i = 0; i < EJS_TOKEN_STACK; i++) { - mprFree(state->putBack[i].token); - } - state->putBackIndex = -1; - mprFree(state->line); - state->lineLength = 0; - state->lineColumn = 0; -} - -/******************************************************************************/ -/* - * Get the next EJS token - */ - -int ejsLexGetToken(Ejs *ep, int state) -{ - mprAssert(ep); - - ep->tid = getLexicalToken(ep, state); - return ep->tid; -} - -/******************************************************************************/ - -/* - * Check for reserved words "if", "else", "var", "for", "foreach", - * "delete", "function", and "return". "new", "in" and "function" - * done below. "true", "false", "null", "undefined" are handled - * as global objects. - * - * Other reserved words not supported: - * "break", "case", "catch", "continue", "default", "do", - * "finally", "instanceof", "switch", "this", "throw", "try", - * "typeof", "while", "with" - * - * ECMA extensions reserved words (not supported): - * "abstract", "boolean", "byte", "char", "class", "const", - * "debugger", "double", "enum", "export", "extends", - * "final", "float", "goto", "implements", "import", "int", - * "interface", "long", "native", "package", "private", - * "protected", "public", "short", "static", "super", - * "synchronized", "throws", "transient", "volatile" - */ - -static int checkReservedWord(Ejs *ep, int state, int c, int tid) -{ - if (state == EJS_STATE_STMT) { - if (strcmp(ep->token, "if") == 0) { - inputPutback(ep, c); - return EJS_TOK_IF; - } else if (strcmp(ep->token, "else") == 0) { - inputPutback(ep, c); - return EJS_TOK_ELSE; - } else if (strcmp(ep->token, "var") == 0) { - inputPutback(ep, c); - return EJS_TOK_VAR; - } else if (strcmp(ep->token, "for") == 0) { - inputPutback(ep, c); - return EJS_TOK_FOR; - } else if (strcmp(ep->token, "delete") == 0) { - inputPutback(ep, c); - return EJS_TOK_DELETE; - } else if (strcmp(ep->token, "function") == 0) { - inputPutback(ep, c); - return EJS_TOK_FUNCTION; - } else if (strcmp(ep->token, "return") == 0) { - if ((c == ';') || (c == '(')) { - inputPutback(ep, c); - } - return EJS_TOK_RETURN; - } - } else if (state == EJS_STATE_EXPR) { - if (strcmp(ep->token, "new") == 0) { - inputPutback(ep, c); - return EJS_TOK_NEW; - } else if (strcmp(ep->token, "in") == 0) { - inputPutback(ep, c); - return EJS_TOK_IN; - } else if (strcmp(ep->token, "function") == 0) { - inputPutback(ep, c); - return EJS_TOK_FUNCTION; - } - } - return tid; -} - -/******************************************************************************/ -/* - * Get the next EJS token - */ - -static int getLexicalToken(Ejs *ep, int state) -{ - MprType type; - EjsInput *ip; - int done, tid, c, quote, style, idx; - - mprAssert(ep); - ip = ep->input; - mprAssert(ip); - - ep->tid = -1; - tid = -1; - type = BLD_FEATURE_NUM_TYPE_ID; - - /* - * Use a putback tokens first. Don't free strings as caller needs access. - */ - if (ip->putBackIndex >= 0) { - idx = ip->putBackIndex; - tid = ip->putBack[idx].id; - ep->token = (char*) ip->putBack[idx].token; - tid = checkReservedWord(ep, state, 0, tid); - ip->putBackIndex--; - return tid; - } - ep->token = ip->tokServp = ip->tokEndp = ip->tokbuf; - *ip->tokServp = '\0'; - - if ((c = inputGetc(ep)) < 0) { - return EJS_TOK_EOF; - } - - /* - * Main lexical analyser - */ - for (done = 0; !done; ) { - switch (c) { - case -1: - return EJS_TOK_EOF; - - case ' ': - case '\t': - case '\r': - do { - if ((c = inputGetc(ep)) < 0) - break; - } while (c == ' ' || c == '\t' || c == '\r'); - break; - - case '\n': - return EJS_TOK_NEWLINE; - - case '(': - tokenAddChar(ep, c); - return EJS_TOK_LPAREN; - - case ')': - tokenAddChar(ep, c); - return EJS_TOK_RPAREN; - - case '[': - tokenAddChar(ep, c); - return EJS_TOK_LBRACKET; - - case ']': - tokenAddChar(ep, c); - return EJS_TOK_RBRACKET; - - case '.': - tokenAddChar(ep, c); - return EJS_TOK_PERIOD; - - case '{': - tokenAddChar(ep, c); - return EJS_TOK_LBRACE; - - case '}': - tokenAddChar(ep, c); - return EJS_TOK_RBRACE; - - case '+': - if ((c = inputGetc(ep)) < 0) { - ejsError(ep, "Syntax Error"); - return EJS_TOK_ERR; - } - if (c != '+' ) { - inputPutback(ep, c); - tokenAddChar(ep, EJS_EXPR_PLUS); - return EJS_TOK_EXPR; - } - tokenAddChar(ep, EJS_EXPR_INC); - return EJS_TOK_INC_DEC; - - case '-': - if ((c = inputGetc(ep)) < 0) { - ejsError(ep, "Syntax Error"); - return EJS_TOK_ERR; - } - if (c != '-' ) { - inputPutback(ep, c); - tokenAddChar(ep, EJS_EXPR_MINUS); - return EJS_TOK_EXPR; - } - tokenAddChar(ep, EJS_EXPR_DEC); - return EJS_TOK_INC_DEC; - - case '*': - tokenAddChar(ep, EJS_EXPR_MUL); - return EJS_TOK_EXPR; - - case '%': - tokenAddChar(ep, EJS_EXPR_MOD); - return EJS_TOK_EXPR; - - case '/': - /* - * Handle the division operator and comments - */ - if ((c = inputGetc(ep)) < 0) { - ejsError(ep, "Syntax Error"); - return EJS_TOK_ERR; - } - if (c != '*' && c != '/') { - inputPutback(ep, c); - tokenAddChar(ep, EJS_EXPR_DIV); - return EJS_TOK_EXPR; - } - style = c; - /* - * Eat comments. Both C and C++ comment styles are supported. - */ - while (1) { - if ((c = inputGetc(ep)) < 0) { - if (style == '/') { - return EJS_TOK_EOF; - } - ejsError(ep, "Syntax Error"); - return EJS_TOK_ERR; - } - if (c == '\n' && style == '/') { - break; - } else if (c == '*') { - c = inputGetc(ep); - if (style == '/') { - if (c == '\n') { - break; - } - } else { - if (c == '/') { - break; - } - } - } - } - /* - * Continue looking for a token, so get the next character - */ - if ((c = inputGetc(ep)) < 0) { - return EJS_TOK_EOF; - } - break; - - case '<': /* < and <= */ - if ((c = inputGetc(ep)) < 0) { - ejsError(ep, "Syntax Error"); - return EJS_TOK_ERR; - } - if (c == '<') { - tokenAddChar(ep, EJS_EXPR_LSHIFT); - return EJS_TOK_EXPR; - } else if (c == '=') { - tokenAddChar(ep, EJS_EXPR_LESSEQ); - return EJS_TOK_EXPR; - } - tokenAddChar(ep, EJS_EXPR_LESS); - inputPutback(ep, c); - return EJS_TOK_EXPR; - - case '>': /* > and >= */ - if ((c = inputGetc(ep)) < 0) { - ejsError(ep, "Syntax Error"); - return EJS_TOK_ERR; - } - if (c == '>') { - tokenAddChar(ep, EJS_EXPR_RSHIFT); - return EJS_TOK_EXPR; - } else if (c == '=') { - tokenAddChar(ep, EJS_EXPR_GREATEREQ); - return EJS_TOK_EXPR; - } - tokenAddChar(ep, EJS_EXPR_GREATER); - inputPutback(ep, c); - return EJS_TOK_EXPR; - - case '=': /* "==" */ - if ((c = inputGetc(ep)) < 0) { - ejsError(ep, "Syntax Error"); - return EJS_TOK_ERR; - } - if (c == '=') { - tokenAddChar(ep, EJS_EXPR_EQ); - return EJS_TOK_EXPR; - } - inputPutback(ep, c); - return EJS_TOK_ASSIGNMENT; - - case '!': /* "!=" or "!"*/ - if ((c = inputGetc(ep)) < 0) { - ejsError(ep, "Syntax Error"); - return EJS_TOK_ERR; - } - if (c == '=') { - tokenAddChar(ep, EJS_EXPR_NOTEQ); - return EJS_TOK_EXPR; - } - inputPutback(ep, c); - tokenAddChar(ep, EJS_EXPR_BOOL_COMP); - return EJS_TOK_EXPR; - - case ';': - tokenAddChar(ep, c); - return EJS_TOK_SEMI; - - case ',': - tokenAddChar(ep, c); - return EJS_TOK_COMMA; - - case '|': /* "||" */ - if ((c = inputGetc(ep)) < 0 || c != '|') { - ejsError(ep, "Syntax Error"); - return EJS_TOK_ERR; - } - tokenAddChar(ep, EJS_COND_OR); - return EJS_TOK_LOGICAL; - - case '&': /* "&&" */ - if ((c = inputGetc(ep)) < 0 || c != '&') { - ejsError(ep, "Syntax Error"); - return EJS_TOK_ERR; - } - tokenAddChar(ep, EJS_COND_AND); - return EJS_TOK_LOGICAL; - - case '\"': /* String quote */ - case '\'': - quote = c; - if ((c = inputGetc(ep)) < 0) { - ejsError(ep, "Syntax Error"); - return EJS_TOK_ERR; - } - - while (c != quote) { - /* - * Check for escape sequence characters - */ - if (c == '\\') { - c = inputGetc(ep); - - if (isdigit(c)) { - /* - * Octal support, \101 maps to 65 = 'A'. Put first - * char back so converter will work properly. - */ - inputPutback(ep, c); - c = charConvert(ep, 8, 3); - - } else { - switch (c) { - case 'n': - c = '\n'; break; - case 'b': - c = '\b'; break; - case 'f': - c = '\f'; break; - case 'r': - c = '\r'; break; - case 't': - c = '\t'; break; - case 'x': - /* - * Hex support, \x41 maps to 65 = 'A' - */ - c = charConvert(ep, 16, 2); - break; - case 'u': - /* - * Unicode support, \x0401 maps to 65 = 'A' - */ - c = charConvert(ep, 16, 2); - c = c*16 + charConvert(ep, 16, 2); - - break; - case '\'': - case '\"': - case '\\': - break; - default: - ejsError(ep, "Invalid Escape Sequence"); - return EJS_TOK_ERR; - } - } - if (tokenAddChar(ep, c) < 0) { - return EJS_TOK_ERR; - } - } else { - if (tokenAddChar(ep, c) < 0) { - return EJS_TOK_ERR; - } - } - if ((c = inputGetc(ep)) < 0) { - ejsError(ep, "Unmatched Quote"); - return EJS_TOK_ERR; - } - } - return EJS_TOK_LITERAL; - - case '0': - if (tokenAddChar(ep, c) < 0) { - return EJS_TOK_ERR; - } - if ((c = inputGetc(ep)) < 0) { - break; - } - if (tolower(c) == 'x') { - do { - if (tokenAddChar(ep, c) < 0) { - return EJS_TOK_ERR; - } - if ((c = inputGetc(ep)) < 0) { - break; - } - } while (isdigit(c) || (tolower(c) >= 'a' && tolower(c) <= 'f')); - - mprDestroyVar(&ep->tokenNumber); - ep->tokenNumber = mprParseVar(ep->token, type); - inputPutback(ep, c); - return EJS_TOK_NUMBER; - } - if (! isdigit(c)) { -#if BLD_FEATURE_FLOATING_POINT - if (c == '.' || tolower(c) == 'e' || c == '+' || c == '-') { - /* Fall through */ - type = MPR_TYPE_FLOAT; - } else -#endif - { - mprDestroyVar(&ep->tokenNumber); - ep->tokenNumber = mprParseVar(ep->token, type); - inputPutback(ep, c); - return EJS_TOK_NUMBER; - } - } - /* Fall through to get more digits */ - - case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - do { - if (tokenAddChar(ep, c) < 0) { - return EJS_TOK_ERR; - } - if ((c = inputGetc(ep)) < 0) { - break; - } -#if BLD_FEATURE_FLOATING_POINT - if (c == '.' || tolower(c) == 'e' || tolower(c) == 'f') { - type = MPR_TYPE_FLOAT; - } - } while (isdigit(c) || c == '.' || tolower(c) == 'e' || tolower(c) == 'f' || - ((type == MPR_TYPE_FLOAT) && (c == '+' || c == '-'))); -#else - } while (isdigit(c)); -#endif - - mprDestroyVar(&ep->tokenNumber); - ep->tokenNumber = mprParseVar(ep->token, type); - inputPutback(ep, c); - return EJS_TOK_NUMBER; - - default: - /* - * Identifiers or a function names - */ - while (1) { - if (c == '\\') { - if ((c = inputGetc(ep)) < 0) { - break; - } - if (c == '\n' || c == '\r') { - break; - } - } else if (tokenAddChar(ep, c) < 0) { - break; - } - if ((c = inputGetc(ep)) < 0) { - break; - } - if (!isalnum(c) && c != '$' && c != '_' && c != '\\') { - break; - } - } - if (*ep->token == '\0') { - c = inputGetc(ep); - break; - } - if (! isalpha((int) *ep->token) && *ep->token != '$' && - *ep->token != '_') { - ejsError(ep, "Invalid identifier %s", ep->token); - return EJS_TOK_ERR; - } - - tid = checkReservedWord(ep, state, c, EJS_TOK_ID); - if (tid != EJS_TOK_ID) { - return tid; - } - - /* - * Skip white space after token to find out whether this is - * a function or not. - */ - while (c == ' ' || c == '\t' || c == '\r' || c == '\n') { - if ((c = inputGetc(ep)) < 0) - break; - } - - tid = EJS_TOK_ID; - done++; - } - } - - /* - * Putback the last extra character for next time - */ - inputPutback(ep, c); - return tid; -} - -/******************************************************************************/ -/* - * Convert a hex or octal character back to binary, return original char if - * not a hex digit - */ - -static int charConvert(Ejs *ep, int base, int maxDig) -{ - int i, c, lval, convChar; - - lval = 0; - for (i = 0; i < maxDig; i++) { - if ((c = inputGetc(ep)) < 0) { - break; - } - /* - * Initialize to out of range value - */ - convChar = base; - if (isdigit(c)) { - convChar = c - '0'; - } else if (c >= 'a' && c <= 'f') { - convChar = c - 'a' + 10; - } else if (c >= 'A' && c <= 'F') { - convChar = c - 'A' + 10; - } - /* - * If unexpected character then return it to buffer. - */ - if (convChar >= base) { - inputPutback(ep, c); - break; - } - lval = (lval * base) + convChar; - } - return lval; -} - -/******************************************************************************/ -/* - * Putback the last token read. Accept at most one push back token. - */ - -void ejsLexPutbackToken(Ejs *ep, int tid, char *string) -{ - EjsInput *ip; - int idx; - - mprAssert(ep); - ip = ep->input; - mprAssert(ip); - - ip->putBackIndex += 1; - idx = ip->putBackIndex; - ip->putBack[idx].id = tid; - - if (ip->putBack[idx].token) { - if (ip->putBack[idx].token == string) { - return; - } - mprFree(ip->putBack[idx].token); - } - ip->putBack[idx].token = mprStrdup(string); -} - -/******************************************************************************/ -/* - * Add a character to the token buffer - */ - -static int tokenAddChar(Ejs *ep, int c) -{ - EjsInput *ip; - uchar *oldbuf; - - mprAssert(ep); - ip = ep->input; - mprAssert(ip); - - if (ip->tokEndp >= &ip->tokbuf[ip->tokSize - 1]) { - ip->tokSize += EJS_PARSE_INCR; - oldbuf = ip->tokbuf; - ip->tokbuf = mprRealloc(ip->tokbuf, ip->tokSize); - if (ip->tokbuf == 0) { - ejsError(ep, "Token too big"); - return -1; - } - ip->tokEndp += (int) ((uchar*) ip->tokbuf - oldbuf); - ip->tokServp += (int) ((uchar*) ip->tokbuf - oldbuf); - ep->token += (int) ((uchar*) ip->tokbuf - oldbuf); - } - *ip->tokEndp++ = c; - *ip->tokEndp = '\0'; - - return 0; -} - -/******************************************************************************/ -/* - * Get another input character - */ - -static int inputGetc(Ejs *ep) -{ - EjsInput *ip; - int c; - - mprAssert(ep); - ip = ep->input; - - if (ip->scriptSize <= 0) { - return -1; - } - - c = (uchar) (*ip->scriptServp++); - ip->scriptSize--; - - /* - * For debugging, accumulate the line number and the currenly parsed line - */ - if (c == '\n') { -#if BLD_DEBUG && 0 - if (ip->lineColumn > 0) { - printf("PARSED: %s\n", ip->line); - } -#endif - ip->lineNumber++; - ip->lineColumn = 0; - } else { - if ((ip->lineColumn + 2) >= ip->lineLength) { - ip->lineLength += 80; - ip->line = mprRealloc(ip->line, ip->lineLength * sizeof(char)); - } - ip->line[ip->lineColumn++] = c; - ip->line[ip->lineColumn] = '\0'; - } - return c; -} - -/******************************************************************************/ -/* - * Putback a character onto the input queue - */ - -static void inputPutback(Ejs *ep, int c) -{ - EjsInput *ip; - - mprAssert(ep); - - if (c != 0) { - ip = ep->input; - *--ip->scriptServp = c; - ip->scriptSize++; - ip->lineColumn--; - ip->line[ip->lineColumn] = '\0'; - } -} - -/******************************************************************************/ - -#else -void ejsLexDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs/ejsLib.c b/source4/lib/appweb/ejs/ejsLib.c deleted file mode 100644 index 67d0a4e760..0000000000 --- a/source4/lib/appweb/ejs/ejsLib.c +++ /dev/null @@ -1,1090 +0,0 @@ -/* - * @file ejs.c - * @brief Embedded JavaScript (EJS) - * @overview Main module interface logic. - */ -/********************************* Copyright **********************************/ -/* - * @copy default.g - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * Portions Copyright (c) GoAhead Software, 1995-2000. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejsInternal.h" - -#if BLD_FEATURE_EJS - -/********************************** Local Data ********************************/ - -/* - * These fields must be locked before any access when multithreaded - */ -static MprVar master; /* Master object */ -static MprArray *ejsList; /* List of ej handles */ - -#if BLD_FEATURE_MULTITHREAD -static EjsLock lock; -static EjsUnlock unlock; -static void *lockData; -#define ejsLock() if (lock) { (lock)(lockData); } else -#define ejsUnlock() if (unlock) { (unlock)(lockData); } else -#else -#define ejsLock() -#define ejsUnlock() -#endif - - -/* - save/restore global ejs state - used to cope with simultaneous ejs requests - this is a workaround for the use of global variables in ejs -*/ -struct ejs_state_ctx { - MprVar master; - MprArray *ejsList; -}; - -void *ejs_save_state(void) -{ - struct ejs_state_ctx *ctx = talloc(talloc_autofree_context(), struct ejs_state_ctx); - ctx->master = master; - ctx->ejsList = ejsList; - return ctx; -} - -void ejs_restore_state(void *ptr) -{ - struct ejs_state_ctx *ctx = talloc_get_type(ptr, struct ejs_state_ctx); - master = ctx->master; - ejsList = ctx->ejsList; - talloc_free(ctx); -} - - -/****************************** Forward Declarations **************************/ - -static char *getNextVarToken(char **next, char *tokBuf, int tokBufLen); - -/************************************* Code ***********************************/ -/* - * Initialize the EJ subsystem - */ - -int ejsOpen(EjsLock lockFn, EjsUnlock unlockFn, void *data) -{ - MprVar *np; - -#if BLD_FEATURE_MULTITHREAD - if (lockFn) { - lock = lockFn; - unlock = unlockFn; - lockData = data; - } -#endif - ejsLock(); - - /* - * Master is the top level object (above global). It is used to clone its - * contents into the global scope for each. This is never visible to the - * user, so don't use ejsCreateObj(). - */ - master = mprCreateObjVar("master", EJS_SMALL_OBJ_HASH_SIZE); - if (master.type == MPR_TYPE_UNDEFINED) { - ejsUnlock(); - return MPR_ERR_CANT_ALLOCATE; - } - - ejsList = mprCreateArray(); - ejsDefineStandardProperties(&master); - - /* - * Make these objects immutable - */ - np = mprGetFirstProperty(&master, MPR_ENUM_FUNCTIONS | MPR_ENUM_DATA); - while (np) { - mprSetVarReadonly(np, 1); - np = mprGetNextProperty(&master, np, MPR_ENUM_FUNCTIONS | - MPR_ENUM_DATA); - } - ejsUnlock(); - return 0; -} - -/******************************************************************************/ - -void ejsClose() -{ - ejsLock(); - mprDestroyArray(ejsList); - mprDestroyVar(&master); - ejsUnlock(); -} - -/******************************************************************************/ -/* - * Create and initialize an EJS engine - */ - -EjsId ejsOpenEngine(EjsHandle primaryHandle, EjsHandle altHandle) -{ - MprVar *np; - Ejs *ep; - - ep = (Ejs *)mprMalloc(sizeof(Ejs)); - if (ep == 0) { - return (EjsId) -1; - } - memset(ep, 0, sizeof(Ejs)); - - ejsLock(); - ep->eid = (EjsId) mprAddToArray(ejsList, ep); - ejsUnlock(); - - /* - * Create array of local variable frames - */ - ep->frames = mprCreateArray(); - if (ep->frames == 0) { - ejsCloseEngine(ep->eid); - return (EjsId) -1; - } - ep->primaryHandle = primaryHandle; - ep->altHandle = altHandle; - - /* - * Create first frame: global variables - */ - ep->global = (MprVar*) mprMalloc(sizeof(MprVar)); - *ep->global = ejsCreateObj("global", EJS_OBJ_HASH_SIZE); - if (ep->global->type == MPR_TYPE_UNDEFINED) { - ejsCloseEngine(ep->eid); - return (EjsId) -1; - } - mprAddToArray(ep->frames, ep->global); - - /* - * Create first local variable frame - */ - ep->local = (MprVar*) mprMalloc(sizeof(MprVar)); - *ep->local = ejsCreateObj("local", EJS_OBJ_HASH_SIZE); - if (ep->local->type == MPR_TYPE_UNDEFINED) { - ejsCloseEngine(ep->eid); - return (EjsId) -1; - } - mprAddToArray(ep->frames, ep->local); - - /* - * Clone all master variables into the global frame. This does a - * reference copy. - * - * ejsDefineStandardProperties(ep->global); - */ - np = mprGetFirstProperty(&master, MPR_ENUM_FUNCTIONS | MPR_ENUM_DATA); - while (np) { - mprCreateProperty(ep->global, np->name, np); - np = mprGetNextProperty(&master, np, MPR_ENUM_FUNCTIONS | - MPR_ENUM_DATA); - } - - mprCreateProperty(ep->global, "global", ep->global); - mprCreateProperty(ep->global, "this", ep->global); - mprCreateProperty(ep->local, "local", ep->local); - - return ep->eid; -} - -/******************************************************************************/ -/* - * Close an EJS instance - */ - -void ejsCloseEngine(EjsId eid) -{ - Ejs *ep; - MprVar *vp; - void **handles; - int i; - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return; - } - - mprFree(ep->error); - mprDestroyVar(&ep->result); - mprDestroyVar(&ep->tokenNumber); - - if (ep->local) { - mprDeleteProperty(ep->local, "local"); - } - mprDeleteProperty(ep->global, "this"); - mprDeleteProperty(ep->global, "global"); - - handles = ep->frames->handles; - for (i = 0; i < ep->frames->max; i++) { - vp = handles[i]; - if (vp) { -#if BLD_DEBUG - if (vp->type == MPR_TYPE_OBJECT && vp->properties->refCount > 1) { - mprLog(7, "ejsCloseEngine: %s has ref count %d\n", - vp->name, vp->properties->refCount); - } -#endif - mprDestroyVar(vp); - mprFree(vp); - mprRemoveFromArray(ep->frames, i); - } - } - mprDestroyArray(ep->frames); - - ejsLock(); - mprRemoveFromArray(ejsList, (int) ep->eid); - ejsUnlock(); - - mprFree(ep); -} - -/******************************************************************************/ -/* - * Evaluate an EJS script file - */ - -int ejsEvalFile(EjsId eid, char *path, MprVar *result, char **emsg) -{ - struct stat sbuf; - Ejs *ep; - char *script; - int rc, fd; - - mprAssert(path && *path); - - if (emsg) { - *emsg = NULL; - } - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - goto error; - } - - if ((fd = open(path, O_RDONLY | O_BINARY, 0666)) < 0) { - ejsError(ep, "Can't open %s\n", path); - goto error; - } - - if (stat(path, &sbuf) < 0) { - close(fd); - ejsError(ep, "Cant stat %s", path); - goto error; - } - - if ((script = (char*) mprMalloc(sbuf.st_size + 1)) == NULL) { - close(fd); - ejsError(ep, "Cant malloc %d", (int) sbuf.st_size); - goto error; - } - - if (read(fd, script, sbuf.st_size) != (int) sbuf.st_size) { - close(fd); - mprFree(script); - ejsError(ep, "Error reading %s", path); - goto error; - } - - script[sbuf.st_size] = '\0'; - close(fd); - - rc = ejsEvalBlock(eid, script, result, emsg); - mprFree(script); - - return rc; - -/* - * Error return - */ -error: - if(emsg) - *emsg = mprStrdup(ep->error); - return -1; -} - -/******************************************************************************/ -/* - * Create a new variable scope block. This pushes the old local frame down - * the stack and creates a new local variables frame. - */ - -int ejsOpenBlock(EjsId eid) -{ - Ejs *ep; - - if((ep = ejsPtr(eid)) == NULL) { - return -1; - } - - ep->local = (MprVar*) mprMalloc(sizeof(MprVar)); - *ep->local = ejsCreateObj("localBlock", EJS_OBJ_HASH_SIZE); - - mprCreateProperty(ep->local, "local", ep->local); - - return mprAddToArray(ep->frames, ep->local); -} - -/******************************************************************************/ -/* - * Close a variable scope block opened via ejsOpenBlock. Pop back the old - * local variables frame. - */ - -int ejsCloseBlock(EjsId eid, int fid) -{ - Ejs *ep; - - if((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return -1; - } - - /* - * Must remove self-references before destroying "local" - */ - mprDeleteProperty(ep->local, "local"); - - mprDestroyVar(ep->local); - mprFree(ep->local); - - mprRemoveFromArray(ep->frames, fid); - ep->local = (MprVar*) ep->frames->handles[ep->frames->used - 1]; - - return 0; -} - -/******************************************************************************/ -/* - * Create a new variable scope block and evaluate a script. All frames - * created during this context will be automatically deleted when complete. - * vp and emsg are optional. i.e. created local variables will be discarded - * when this routine returns. - */ - -int ejsEvalBlock(EjsId eid, char *script, MprVar *vp, char **emsg) -{ - int rc, fid; - - mprAssert(script); - - fid = ejsOpenBlock(eid); - rc = ejsEvalScript(eid, script, vp, emsg); - ejsCloseBlock(eid, fid); - - return rc; -} - -/******************************************************************************/ -/* - * Parse and evaluate a EJS. Return the result in *vp. The result is "owned" - * by EJ and the caller must not free it. Returns -1 on errors and zero - * for success. On errors, emsg will be set to the reason. The caller must - * free emsg. - */ - -int ejsEvalScript(EjsId eid, char *script, MprVar *vp, char **emsg) -{ - Ejs *ep; - int state; - void *endlessLoopTest; - int loopCounter; - - if (emsg) { - *emsg = NULL; - } - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return -1; - } - - mprDestroyVar(&ep->result); - - if (script == 0) { - return 0; - } - - /* - * Allocate a new evaluation block, and save the old one - */ - ejsLexOpenScript(ep, script); - - /* - * Do the actual parsing and evaluation - */ - loopCounter = 0; - endlessLoopTest = NULL; - ep->exitStatus = 0; - - do { - state = ejsParse(ep, EJS_STATE_BEGIN, EJS_FLAGS_EXE); - - if (state == EJS_STATE_RET) { - state = EJS_STATE_EOF; - } - /* - * Stuck parser and endless recursion protection. - */ - if (endlessLoopTest == ep->input->scriptServp) { - if (loopCounter++ > 10) { - state = EJS_STATE_ERR; - ejsError(ep, "Syntax error"); - } - } else { - endlessLoopTest = ep->input->scriptServp; - loopCounter = 0; - } - } while (state != EJS_STATE_EOF && state != EJS_STATE_ERR); - - ejsLexCloseScript(ep); - - /* - * Return any error string to the user - */ - if (state == EJS_STATE_ERR && emsg) { - *emsg = mprStrdup(ep->error); - } - - if (state == EJS_STATE_ERR) { - return -1; - } - - if (vp) { - *vp = ep->result; - } - - return ep->exitStatus; -} - -/******************************************************************************/ -/* - * Core error handling - */ - -static void ejsErrorCore(Ejs* ep, const char *fmt, va_list args) - PRINTF_ATTRIBUTE(2, 0); - -static void ejsErrorCore(Ejs* ep, const char *fmt, va_list args) -{ - EjsInput *ip; - char *errbuf, *msgbuf; - int frame = 0; - - mprAssert(ep); - - msgbuf = NULL; - mprAllocVsprintf(&msgbuf, MPR_MAX_STRING, fmt, args); - - ip = ep->input; - mprAllocSprintf(&errbuf, MPR_MAX_STRING, "%s\nBacktrace:\n", msgbuf); - - /* form a backtrace */ - while (ip) { - char *msg2, *ebuf2; - mprAllocSprintf(&msg2, MPR_MAX_STRING, - "\t[%2d] %20s:%-4d -> %s\n", - frame++, ip->procName?ip->procName:"", ip->lineNumber, ip->line); - ebuf2 = mprRealloc(errbuf, strlen(errbuf) + strlen(msg2) + 1); - if (ebuf2 == NULL) break; - errbuf = ebuf2; - memcpy(errbuf+strlen(errbuf), msg2, strlen(msg2)+1); - mprFree(msg2); - ip = ip->next; - } - mprFree(ep->error); - ep->error = errbuf; - mprFree(msgbuf); -} - -/******************************************************************************/ -/* - * Internal use function to set the error message - */ - -void ejsError(Ejs* ep, const char* fmt, ...) -{ - va_list args; - - va_start(args, fmt); - ejsErrorCore(ep, fmt, args); - va_end(args); -} - -/******************************************************************************/ -/* - * Public routine to set the error message - */ - -void ejsSetErrorMsg(EjsId eid, const char* fmt, ...) -{ - va_list args; - Ejs *ep; - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return; - } - va_start(args, fmt); - ejsErrorCore(ep, fmt, args); - va_end(args); -} - -/******************************************************************************/ -/* - * Get the current line number - */ - -int ejsGetLineNumber(EjsId eid) -{ - Ejs *ep; - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return -1; - } - return ep->input->lineNumber; -} - -/******************************************************************************/ -/* - * Return the local object - */ - -MprVar *ejsGetLocalObject(EjsId eid) -{ - Ejs *ep; - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return 0; - } - return ep->local; -} - -/******************************************************************************/ -/* - * Return the global object - */ - -MprVar *ejsGetGlobalObject(EjsId eid) -{ - Ejs *ep; - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return 0; - } - return ep->global; -} - -/******************************************************************************/ -/* - * Copy the value of an object property. Return value is in "value". - * If deepCopy is true, copy all object/strings. Otherwise, object reference - * counts are incremented. Callers must always call mprDestroyVar on the - * return value to prevent leaks. - * - * Returns: -1 on errors or if the variable is not found. - */ - -int ejsCopyVar(EjsId eid, const char *var, MprVar *value, bool deepCopy) -{ - Ejs *ep; - MprVar *vp; - - mprAssert(var && *var); - mprAssert(value); - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return -1; - } - - if (ejsGetVarCore(ep, var, 0, &vp, 0) < 0) { - return -1; - } - - return mprCopyProperty(value, vp, deepCopy); -} - -/******************************************************************************/ -/* - * Return the value of an object property. Return value is in "value". - * Objects and strings are not copied and reference counts are not modified. - * Callers should NOT call mprDestroyVar. Returns: -1 on errors or if the - * variable is not found. - */ - -int ejsReadVar(EjsId eid, const char *var, MprVar *value) -{ - Ejs *ep; - MprVar *vp; - - mprAssert(var && *var); - mprAssert(value); - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return -1; - } - - if (ejsGetVarCore(ep, var, 0, &vp, 0) < 0) { - return -1; - } - - return mprReadProperty(vp, value); -} - -/******************************************************************************/ -/* - * Set a variable that may be an arbitrarily complex object or array reference. - * Will always define in the top most variable frame. - */ - -int ejsWriteVar(EjsId eid, const char *var, MprVar *value) -{ - Ejs *ep; - MprVar *vp; - - mprAssert(var && *var); - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return -1; - } - - if (ejsGetVarCore(ep, var, 0, &vp, EJS_FLAGS_CREATE) < 0) { - return -1; - } - mprAssert(vp); - - /* - * Only copy the value. Don't overwrite the object's name - */ - mprWriteProperty(vp, value); - - return 0; -} - -/******************************************************************************/ -/* - * Set a variable that may be an arbitrarily complex object or array reference. - * Will always define in the top most variable frame. - */ - -int ejsWriteVarValue(EjsId eid, const char *var, MprVar value) -{ - return ejsWriteVar(eid, var, &value); -} - -/******************************************************************************/ -/* - * Delete a variable - */ - -int ejsDeleteVar(EjsId eid, const char *var) -{ - Ejs *ep; - MprVar *vp; - MprVar *obj; - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return -1; - } - if (ejsGetVarCore(ep, var, &obj, &vp, 0) < 0) { - return -1; - } - mprDeleteProperty(obj, vp->name); - return 0; -} - -/******************************************************************************/ -/* - * Set the expression return value - */ - -void ejsSetReturnValue(EjsId eid, MprVar value) -{ - Ejs *ep; - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return; - } - mprCopyVar(&ep->result, &value, MPR_SHALLOW_COPY); -} - -/******************************************************************************/ -/* - * Set the expression return value to a string value - */ - -void ejsSetReturnString(EjsId eid, const char *str) -{ - Ejs *ep; - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return; - } - mprCopyVarValue(&ep->result, mprCreateStringVar(str, 0), MPR_SHALLOW_COPY); -} - -/******************************************************************************/ -/* - * Get the expression return value - */ - -MprVar *ejsGetReturnValue(EjsId eid) -{ - Ejs *ep; - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return 0; - } - return &ep->result; -} - -/******************************************************************************/ -/* - * Define a C function. If eid < 0, then update the master object with this - * function. NOTE: in this case, functionName must be simple without any "." or - * "[]" elements. If eid >= 0, add to the specified script engine. In this - * case, functionName can be an arbitrary object reference and can contain "." - * or "[]". - */ - -void ejsDefineCFunction(EjsId eid, const char *functionName, MprCFunction fn, - void *thisPtr, int flags) -{ - if (eid < 0) { - ejsLock(); - mprCreatePropertyValue(&master, functionName, - mprCreateCFunctionVar(fn, thisPtr, flags)); - ejsUnlock(); - } else { - ejsWriteVarValue(eid, functionName, - mprCreateCFunctionVar(fn, thisPtr, flags)); - } -} - -/******************************************************************************/ -/* - * Define a C function with String arguments - */ - -void ejsDefineStringCFunction(EjsId eid, const char *functionName, - MprStringCFunction fn, void *thisPtr, int flags) -{ - if (eid < 0) { - ejsLock(); - mprCreatePropertyValue(&master, functionName, - mprCreateStringCFunctionVar(fn, thisPtr, flags)); - ejsUnlock(); - } else { - ejsWriteVarValue(eid, functionName, - mprCreateStringCFunctionVar(fn, thisPtr, flags)); - } -} - -/******************************************************************************/ -/* - * Define a JavaScript function. Args should be comma separated. - * Body should not contain braces. - */ - -void ejsDefineFunction(EjsId eid, const char *functionName, char *args, - char *body) -{ - MprVar v; - - v = mprCreateFunctionVar(args, body, 0); - if (eid < 0) { - ejsLock(); - mprCreateProperty(&master, functionName, &v); - ejsUnlock(); - } else { - ejsWriteVar(eid, functionName, &v); - } - mprDestroyVar(&v); -} - -/******************************************************************************/ - -void *ejsGetThisPtr(EjsId eid) -{ - Ejs *ep; - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return 0; - } - return ep->thisPtr; -} - -/******************************************************************************/ -/* - * Find a variable given a variable name and return the parent object and - * the variable itself, the variable . This routine supports variable names - * that may be objects or arrays but may NOT have expressions in the array - * indicies. Returns -1 on errors or if the variable is not found. - */ - -int ejsGetVarCore(Ejs *ep, const char *vname, MprVar **obj, - MprVar **varValue, int flags) -{ - MprVar *currentObj; - MprVar *currentVar; - char tokBuf[EJS_MAX_ID]; - char *propertyName, *token, *next, *cp, *varName; - - if (obj) { - *obj = 0; - } - if (varValue) { - *varValue = 0; - } - currentObj = ejsFindObj(ep, 0, vname, flags); - currentVar = 0; - propertyName = 0; - - next = varName = mprStrdup(vname); - - token = getNextVarToken(&next, tokBuf, sizeof(tokBuf)); - - while (currentObj != 0 && token != 0 && *token) { - - if (*token == '[') { - token = getNextVarToken(&next, tokBuf, sizeof(tokBuf)); - - propertyName = token; - if (*propertyName == '\"') { - propertyName++; - if ((cp = strchr(propertyName, '\"')) != 0) { - *cp = '\0'; - } - } else if (*propertyName == '\'') { - propertyName++; - if ((cp = strchr(propertyName, '\'')) != 0) { - *cp = '\0'; - } - } - - currentObj = currentVar; - currentVar = ejsFindProperty(ep, 0, currentObj, propertyName, 0); - - token = getNextVarToken(&next, tokBuf, sizeof(tokBuf)); - if (*token != ']') { - mprFree(varName); - return -1; - } - - } else if (*token == '.') { - token = getNextVarToken(&next, tokBuf, sizeof(tokBuf)); - if (!isalpha((int) token[0]) && - token[0] != '_' && token[0] != '$') { - mprFree(varName); - return -1; - } - - propertyName = token; - currentObj = currentVar; - currentVar = ejsFindProperty(ep, 0, currentObj, token, 0); - - } else { - currentVar = ejsFindProperty(ep, 0, currentObj, token, 0); - } - token = getNextVarToken(&next, tokBuf, sizeof(tokBuf)); - } - mprFree(varName); - - if (currentVar == 0 && currentObj >= 0 && flags & EJS_FLAGS_CREATE) { - currentVar = mprCreatePropertyValue(currentObj, propertyName, - mprCreateUndefinedVar()); - } - if (obj) { - *obj = currentObj; - } - - /* - * Don't use mprCopyVar as it will copy the data - */ - if (varValue) { - *varValue = currentVar; - } - return currentVar ? 0 : -1; -} - -/******************************************************************************/ -/* - * Get the next token as part of a variable specification. This will return - * a pointer to the next token and will return a pointer to the next token - * (after this one) in "next". The tokBuf holds the parsed token. - */ -static char *getNextVarToken(char **next, char *tokBuf, int tokBufLen) -{ - char *start, *cp; - int len; - - start = *next; - while (isspace((int) *start) || *start == '\n' || *start == '\r') { - start++; - } - cp = start; - - if (*cp == '.' || *cp == '[' || *cp == ']') { - cp++; - } else { - while (*cp && *cp != '.' && *cp != '[' && *cp != ']' && - !isspace((int) *cp) && *cp != '\n' && *cp != '\r') { - cp++; - } - } - len = mprMemcpy(tokBuf, tokBufLen - 1, start, cp - start); - tokBuf[len] = '\0'; - - *next = cp; - return tokBuf; -} - -/******************************************************************************/ -/* - * Get the EJS structure pointer - */ - -Ejs *ejsPtr(EjsId eid) -{ - Ejs *handle; - int intId; - - intId = (int) eid; - - ejsLock(); - mprAssert(0 <= intId && intId < ejsList->max); - - if (intId < 0 || intId >= ejsList->max || ejsList->handles[intId] == NULL) { - mprAssert(0); - ejsUnlock(); - return NULL; - } - handle = ejsList->handles[intId]; - ejsUnlock(); - return handle; -} - -/******************************************************************************/ -/* - * Utility routine to crack JavaScript arguments. Return the number of args - * seen. This routine only supports %s and %d type args. - * - * Typical usage: - * - * if (ejsParseArgs(argc, argv, "%s %d", &name, &age) < 2) { - * mprError("Insufficient args\n"); - * return -1; - * } - */ - -int ejsParseArgs(int argc, char **argv, char *fmt, ...) -{ - va_list vargs; - bool *bp; - char *cp, **sp, *s; - int *ip, argn; - - va_start(vargs, fmt); - - if (argv == 0) { - return 0; - } - - for (argn = 0, cp = fmt; cp && *cp && argn < argc && argv[argn]; ) { - if (*cp++ != '%') { - continue; - } - - s = argv[argn]; - switch (*cp) { - case 'b': - bp = va_arg(vargs, bool*); - if (bp) { - if (strcmp(s, "true") == 0 || s[0] == '1') { - *bp = 1; - } else { - *bp = 0; - } - } else { - *bp = 0; - } - break; - - case 'd': - ip = va_arg(vargs, int*); - *ip = atoi(s); - break; - - case 's': - sp = va_arg(vargs, char**); - *sp = s; - break; - - default: - mprAssert(0); - } - argn++; - } - - va_end(vargs); - return argn; -} - -/******************************************************************************/ - -#else -void ejsDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/******************************************************************************/ -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs/ejsParser.c b/source4/lib/appweb/ejs/ejsParser.c deleted file mode 100644 index da922a5728..0000000000 --- a/source4/lib/appweb/ejs/ejsParser.c +++ /dev/null @@ -1,2436 +0,0 @@ -/* - * @file ejsParser.c - * @brief EJS Parser and Execution - */ -/********************************* Copyright **********************************/ -/* - * @copy default.g - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * Portions Copyright (c) GoAhead Software, 1995-2000. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/********************************** Includes **********************************/ - -#include "ejsInternal.h" - -#if BLD_FEATURE_EJS - -/****************************** Forward Declarations **************************/ - -static void appendValue(MprVar *v1, MprVar *v2); -static int evalCond(Ejs *ep, MprVar *lhs, int rel, MprVar *rhs); -static int evalExpr(Ejs *ep, MprVar *lhs, int rel, MprVar *rhs); -#if BLD_FEATURE_FLOATING_POINT -static int evalFloatExpr(Ejs *ep, double l, int rel, double r); -#endif -static int evalBoolExpr(Ejs *ep, bool l, int rel, bool r); -static int evalPtrExpr(Ejs *ep, void *l, int rel, void *r); -static int evalNumericExpr(Ejs *ep, MprNum l, int rel, MprNum r); -static int evalStringExpr(Ejs *ep, MprVar *lhs, int rel, MprVar *rhs); -static int evalFunction(Ejs *ep, MprVar *obj, int flags); -static void freeProc(EjsProc *proc); -static int parseArgs(Ejs *ep, int state, int flags); -static int parseAssignment(Ejs *ep, int state, int flags, char *id, - char *fullName); -static int parseCond(Ejs *ep, int state, int flags); -static int parseDeclaration(Ejs *ep, int state, int flags); -static int parseExpr(Ejs *ep, int state, int flags); -static int parseFor(Ejs *ep, int state, int flags); -static int parseForIn(Ejs *ep, int state, int flags); -static int parseFunctionDec(Ejs *ep, int state, int flags); -static int parseFunction(Ejs *ep, int state, int flags, char *id); -static int parseId(Ejs *ep, int state, int flags, char **id, - char **fullName, int *fullNameLen, int *done); -static int parseInc(Ejs *ep, int state, int flags); -static int parseIf(Ejs *ep, int state, int flags, int *done); -static int parseStmt(Ejs *ep, int state, int flags); -static void removeNewlines(Ejs *ep, int state); -static void updateResult(Ejs *ep, int state, int flags, MprVar *vp); - -/************************************* Code ***********************************/ -/* - * Recursive descent parser for EJS - */ - -int ejsParse(Ejs *ep, int state, int flags) -{ - mprAssert(ep); - - switch (state) { - /* - * Any statement, function arguments or conditional expressions - */ - case EJS_STATE_STMT: - if ((state = parseStmt(ep, state, flags)) != EJS_STATE_STMT_DONE && - state != EJS_STATE_EOF && state != EJS_STATE_STMT_BLOCK_DONE && - state != EJS_STATE_RET) { - state = EJS_STATE_ERR; - } - break; - - case EJS_STATE_DEC: - if ((state = parseStmt(ep, state, flags)) != EJS_STATE_DEC_DONE && - state != EJS_STATE_EOF) { - state = EJS_STATE_ERR; - } - break; - - case EJS_STATE_EXPR: - if ((state = parseStmt(ep, state, flags)) != EJS_STATE_EXPR_DONE && - state != EJS_STATE_EOF) { - state = EJS_STATE_ERR; - } - break; - - /* - * Variable declaration list - */ - case EJS_STATE_DEC_LIST: - state = parseDeclaration(ep, state, flags); - break; - - /* - * Function argument string - */ - case EJS_STATE_ARG_LIST: - state = parseArgs(ep, state, flags); - break; - - /* - * Logical condition list (relational operations separated by &&, ||) - */ - case EJS_STATE_COND: - state = parseCond(ep, state, flags); - break; - - /* - * Expression list - */ - case EJS_STATE_RELEXP: - state = parseExpr(ep, state, flags); - break; - } - - if (state == EJS_STATE_ERR && ep->error == NULL) { - ejsError(ep, "Syntax error"); - } - return state; -} - -/******************************************************************************/ -/* - * Parse any statement including functions and simple relational operations - */ - -static int parseStmt(Ejs *ep, int state, int flags) -{ - EjsProc *saveProc; - MprVar *vp, *saveObj; - char *id, *fullName, *initToken; - int done, expectSemi, tid, fullNameLen, rel; - int initId; - - mprAssert(ep); - - expectSemi = 0; - saveProc = NULL; - id = 0; - fullName = 0; - fullNameLen = 0; - - ep->currentObj = 0; - ep->currentProperty = 0; - - for (done = 0; !done && state != EJS_STATE_ERR; ) { - tid = ejsLexGetToken(ep, state); - - switch (tid) { - default: - ejsLexPutbackToken(ep, EJS_TOK_EXPR, ep->token); - done++; - break; - - case EJS_TOK_EXPR: - rel = (int) *ep->token; - if (state == EJS_STATE_EXPR) { - ejsLexPutbackToken(ep, EJS_TOK_EXPR, ep->token); - } - done++; - break; - - case EJS_TOK_LOGICAL: - ejsLexPutbackToken(ep, tid, ep->token); - done++; - break; - - case EJS_TOK_ERR: - state = EJS_STATE_ERR; - done++; - break; - - case EJS_TOK_EOF: - state = EJS_STATE_EOF; - done++; - break; - - case EJS_TOK_NEWLINE: - break; - - case EJS_TOK_SEMI: - /* - * This case is when we discover no statement and just a lone ';' - */ - if (state != EJS_STATE_STMT) { - ejsLexPutbackToken(ep, tid, ep->token); - } - done++; - break; - - case EJS_TOK_PERIOD: - if (flags & EJS_FLAGS_EXE) { - if (ep->currentProperty == 0) { - ejsError(ep, "Undefined object \"%s\"\n", id); - goto error; - } - } - ep->currentObj = ep->currentProperty; - - if ((tid = ejsLexGetToken(ep, state)) != EJS_TOK_ID) { - ejsError(ep, "Bad property after '.': %s\n", ep->token); - goto error; - } - mprFree(id); - id = mprStrdup(ep->token); - - vp = ejsFindProperty(ep, state, ep->currentObj, id, flags); - updateResult(ep, state, flags, vp); - -#if BLD_DEBUG - fullNameLen = mprReallocStrcat(&fullName, MPR_MAX_VAR, fullNameLen, - 0, ".", NULL); -#endif - - ep->currentProperty = vp; - ejsLexPutbackToken(ep, tid, ep->token); - break; - - case EJS_TOK_LBRACKET: - ep->currentObj = ep->currentProperty; - saveObj = ep->currentObj; - if (ejsParse(ep, EJS_STATE_RELEXP, flags) != EJS_STATE_RELEXP_DONE){ - goto error; - } - ep->currentObj = saveObj; - - mprFree(id); - mprVarToString(&id, MPR_MAX_STRING, 0, &ep->result); - - if (id[0] == '\0') { - if (flags & EJS_FLAGS_EXE) { - ejsError(ep, - "[] expression evaluates to the empty string\n"); - goto error; - } - } else { - vp = ejsFindProperty(ep, state, ep->currentObj, id, flags); - ep->currentProperty = vp; - updateResult(ep, state, flags, vp); - } - -#if BLD_DEBUG - if (id[0] && strlen(id) < (MPR_MAX_VAR / 2)) { - /* - * If not executing yet, id may not be known - */ - fullNameLen = mprReallocStrcat(&fullName, MPR_MAX_VAR, - fullNameLen, 0, "[", id, "]", NULL); - } -#endif - - if ((tid = ejsLexGetToken(ep, state)) != EJS_TOK_RBRACKET) { - ejsError(ep, "Missing ']'\n"); - goto error; - } - break; - - case EJS_TOK_ID: - state = parseId(ep, state, flags, &id, &fullName, &fullNameLen, - &done); - if (done && state == EJS_STATE_STMT) { - expectSemi++; - } - break; - - case EJS_TOK_ASSIGNMENT: - state = parseAssignment(ep, state, flags, id, fullName); - if (state == EJS_STATE_STMT) { - expectSemi++; - done++; - } - break; - - case EJS_TOK_INC_DEC: - state = parseInc(ep, state, flags); - if (state == EJS_STATE_STMT) { - expectSemi++; - } - break; - - case EJS_TOK_NEW: - if (ejsParse(ep, EJS_STATE_EXPR, flags | EJS_FLAGS_NEW) - != EJS_STATE_EXPR_DONE) { - goto error; - } - break; - - case EJS_TOK_DELETE: - if (ejsParse(ep, EJS_STATE_EXPR, - flags | EJS_FLAGS_DELETE) != EJS_STATE_EXPR_DONE) { - goto error; - } - if (flags & EJS_FLAGS_EXE) { - mprDeleteProperty(ep->currentObj, ep->currentProperty->name); - } - done++; - break; - - case EJS_TOK_FUNCTION: - state = parseFunctionDec(ep, state, flags); - done++; - break; - - case EJS_TOK_LITERAL: - /* - * Set the result to the string literal - */ - mprCopyVarValue(&ep->result, mprCreateStringVar(ep->token, 0), - MPR_SHALLOW_COPY); - if (state == EJS_STATE_STMT) { - expectSemi++; - } - done++; - break; - - case EJS_TOK_NUMBER: - /* - * Set the result to the parsed number - */ - mprCopyVar(&ep->result, &ep->tokenNumber, 0); - if (state == EJS_STATE_STMT) { - expectSemi++; - } - done++; - break; - - case EJS_TOK_FUNCTION_NAME: - state = parseFunction(ep, state, flags, id); - if (state == EJS_STATE_STMT) { - expectSemi++; - } - if (ep->flags & EJS_FLAGS_EXIT) { - state = EJS_STATE_RET; - } - done++; - break; - - case EJS_TOK_IF: - state = parseIf(ep, state, flags, &done); - if (state == EJS_STATE_RET) { - goto doneParse; - } - break; - - case EJS_TOK_FOR: - if (state != EJS_STATE_STMT) { - goto error; - } - if (ejsLexGetToken(ep, state) != EJS_TOK_LPAREN) { - goto error; - } - /* - * Need to peek 2-3 tokens ahead and see if this is a - * for ([var] x in set) - * or - * for (init ; whileCond; incr) - */ - initId = ejsLexGetToken(ep, EJS_STATE_EXPR); - if (initId == EJS_TOK_ID && strcmp(ep->token, "var") == 0) { - /* Simply eat var tokens */ - initId = ejsLexGetToken(ep, EJS_STATE_EXPR); - } - initToken = mprStrdup(ep->token); - - tid = ejsLexGetToken(ep, EJS_STATE_EXPR); - - ejsLexPutbackToken(ep, tid, ep->token); - ejsLexPutbackToken(ep, initId, initToken); - mprFree(initToken); - - if (tid == EJS_TOK_IN) { - if ((state = parseForIn(ep, state, flags)) < 0) { - goto error; - } - } else { - if ((state = parseFor(ep, state, flags)) < 0) { - goto error; - } - } - done++; - break; - - case EJS_TOK_VAR: - if (ejsParse(ep, EJS_STATE_DEC_LIST, flags) - != EJS_STATE_DEC_LIST_DONE) { - goto error; - } - done++; - break; - - case EJS_TOK_COMMA: - ejsLexPutbackToken(ep, tid, ep->token); - done++; - break; - - case EJS_TOK_LPAREN: - if (state == EJS_STATE_EXPR) { - if (ejsParse(ep, EJS_STATE_RELEXP, flags) - != EJS_STATE_RELEXP_DONE) { - goto error; - } - if (ejsLexGetToken(ep, state) != EJS_TOK_RPAREN) { - goto error; - } - } - done++; - break; - - case EJS_TOK_RPAREN: - ejsLexPutbackToken(ep, tid, ep->token); - done++; - break; - - case EJS_TOK_LBRACE: - /* - * This handles any code in braces except "if () {} else {}" - */ - if (state != EJS_STATE_STMT) { - goto error; - } - - /* - * Parse will return EJS_STATE_STMT_BLOCK_DONE when the RBRACE - * is seen. - */ - do { - state = ejsParse(ep, EJS_STATE_STMT, flags); - } while (state == EJS_STATE_STMT_DONE); - - if (state != EJS_STATE_RET) { - if (ejsLexGetToken(ep, state) != EJS_TOK_RBRACE) { - goto error; - } - state = EJS_STATE_STMT_DONE; - } - done++; - break; - - case EJS_TOK_RBRACE: - if (state == EJS_STATE_STMT) { - ejsLexPutbackToken(ep, tid, ep->token); - state = EJS_STATE_STMT_BLOCK_DONE; - done++; - break; - } - goto error; - - case EJS_TOK_RETURN: - if (ejsParse(ep, EJS_STATE_RELEXP, flags) - != EJS_STATE_RELEXP_DONE) { - goto error; - } - if (flags & EJS_FLAGS_EXE) { - while (ejsLexGetToken(ep, state) != EJS_TOK_EOF) { - ; - } - state = EJS_STATE_RET; - done++; - } - break; - } - } - - if (expectSemi) { - tid = ejsLexGetToken(ep, state); - if (tid != EJS_TOK_SEMI && tid != EJS_TOK_NEWLINE && - tid != EJS_TOK_EOF) { - goto error; - } - - /* - * Skip newline after semi-colon - */ - removeNewlines(ep, state); - } - -/* - * Free resources and return the correct status - */ -doneParse: - mprFree(id); - mprFree(fullName); - - /* - * Advance the state - */ - switch (state) { - case EJS_STATE_STMT: - return EJS_STATE_STMT_DONE; - - case EJS_STATE_DEC: - return EJS_STATE_DEC_DONE; - - case EJS_STATE_EXPR: - return EJS_STATE_EXPR_DONE; - - case EJS_STATE_STMT_DONE: - case EJS_STATE_STMT_BLOCK_DONE: - case EJS_STATE_EOF: - case EJS_STATE_RET: - return state; - - default: - return EJS_STATE_ERR; - } - -/* - * Common error exit - */ -error: - state = EJS_STATE_ERR; - goto doneParse; -} - -/******************************************************************************/ -/* - * Parse function arguments - */ - -static int parseArgs(Ejs *ep, int state, int flags) -{ - int tid; - - mprAssert(ep); - - do { - /* - * Peek and see if there are no args - */ - tid = ejsLexGetToken(ep, state); - ejsLexPutbackToken(ep, tid, ep->token); - if (tid == EJS_TOK_RPAREN) { - break; - } - - state = ejsParse(ep, EJS_STATE_RELEXP, flags); - if (state == EJS_STATE_EOF || state == EJS_STATE_ERR) { - return state; - } - if (state == EJS_STATE_RELEXP_DONE) { - if (flags & EJS_FLAGS_EXE) { - mprAssert(ep->proc->args); - mprAddToArray(ep->proc->args, - mprDupVar(&ep->result, MPR_SHALLOW_COPY)); - } - } - /* - * Peek at the next token, continue if more args (ie. comma seen) - */ - tid = ejsLexGetToken(ep, state); - if (tid != EJS_TOK_COMMA) { - ejsLexPutbackToken(ep, tid, ep->token); - } - } while (tid == EJS_TOK_COMMA); - - if (tid != EJS_TOK_RPAREN && state != EJS_STATE_RELEXP_DONE) { - return EJS_STATE_ERR; - } - return EJS_STATE_ARG_LIST_DONE; -} - -/******************************************************************************/ -/* - * Parse an assignment statement - */ - -static int parseAssignment(Ejs *ep, int state, int flags, char *id, - char *fullName) -{ - MprVar *vp, *saveProperty, *saveObj; - - if (id == 0) { - return -1; - } - - saveObj = ep->currentObj; - saveProperty = ep->currentProperty; - if (ejsParse(ep, EJS_STATE_RELEXP, flags | EJS_FLAGS_ASSIGNMENT) - != EJS_STATE_RELEXP_DONE) { - return -1; - } - ep->currentObj = saveObj; - ep->currentProperty = saveProperty; - - if (! (flags & EJS_FLAGS_EXE)) { - return state; - } - - if (ep->currentProperty) { - /* - * Update the variable. Update the property name if not - * yet defined. - */ - if (ep->currentProperty->name == 0 || - ep->currentProperty->name[0] == '\0') { - mprSetVarName(ep->currentProperty, id); - } - if (mprWriteProperty(ep->currentProperty, &ep->result) < 0){ - ejsError(ep, "Can't write to variable\n"); - return -1; - } - - } else { - /* - * Create the variable - */ - if (ep->currentObj) { - if (ep->currentObj->type != MPR_TYPE_OBJECT) { - if (strcmp(ep->currentObj->name, "session") == 0) { - ejsError(ep, "Variable \"%s\" is not an array or object." - "If using ESP, you need useSession(); in your page.", - ep->currentObj->name); - } else { - ejsError(ep, "Variable \"%s\" is not an array or object", - ep->currentObj->name); - } - return -1; - } - vp = mprCreateProperty(ep->currentObj, id, &ep->result); - - } else { - /* - * Standard says: "var x" means declare locally. - * "x = 2" means declare globally if x is undefined. - */ - if (state == EJS_STATE_DEC) { - vp = mprCreateProperty(ep->local, id, &ep->result); - } else { - vp = mprCreateProperty(ep->global, id, &ep->result); - } - } -#if BLD_DEBUG - mprSetVarFullName(vp, fullName); -#endif - } - return state; -} - -/******************************************************************************/ -/* - * Parse conditional expression (relational ops separated by ||, &&) - */ - -static int parseCond(Ejs *ep, int state, int flags) -{ - MprVar lhs, rhs; - int tid, operator; - - mprAssert(ep); - - mprDestroyVar(&ep->result); - rhs = lhs = mprCreateUndefinedVar(); - operator = 0; - - do { - /* - * Recurse to handle one side of a conditional. Accumulate the - * left hand side and the final result in ep->result. - */ - state = ejsParse(ep, EJS_STATE_RELEXP, flags); - if (state != EJS_STATE_RELEXP_DONE) { - state = EJS_STATE_ERR; - break; - } - - if (operator > 0) { - mprCopyVar(&rhs, &ep->result, MPR_SHALLOW_COPY); - if (evalCond(ep, &lhs, operator, &rhs) < 0) { - state = EJS_STATE_ERR; - break; - } - } - mprCopyVar(&lhs, &ep->result, MPR_SHALLOW_COPY); - - tid = ejsLexGetToken(ep, state); - if (tid == EJS_TOK_LOGICAL) { - operator = (int) *ep->token; - - } else if (tid == EJS_TOK_RPAREN || tid == EJS_TOK_SEMI) { - ejsLexPutbackToken(ep, tid, ep->token); - state = EJS_STATE_COND_DONE; - break; - - } else { - ejsLexPutbackToken(ep, tid, ep->token); - } - tid = (state == EJS_STATE_RELEXP_DONE); - - } while (state == EJS_STATE_RELEXP_DONE); - - mprDestroyVar(&lhs); - mprDestroyVar(&rhs); - return state; -} - -/******************************************************************************/ -/* - * Parse variable declaration list. Declarations can be of the following forms: - * var x; - * var x, y, z; - * var x = 1 + 2 / 3, y = 2 + 4; - * - * We set the variable to NULL if there is no associated assignment. - */ - -static int parseDeclaration(Ejs *ep, int state, int flags) -{ - int tid; - - mprAssert(ep); - - do { - if ((tid = ejsLexGetToken(ep, state)) != EJS_TOK_ID) { - return EJS_STATE_ERR; - } - ejsLexPutbackToken(ep, tid, ep->token); - - /* - * Parse the entire assignment or simple identifier declaration - */ - if (ejsParse(ep, EJS_STATE_DEC, flags) != EJS_STATE_DEC_DONE) { - return EJS_STATE_ERR; - } - - /* - * Peek at the next token, continue if comma seen - */ - tid = ejsLexGetToken(ep, state); - if (tid == EJS_TOK_SEMI) { - return EJS_STATE_DEC_LIST_DONE; - } else if (tid != EJS_TOK_COMMA) { - return EJS_STATE_ERR; - } - } while (tid == EJS_TOK_COMMA); - - if (tid != EJS_TOK_SEMI) { - return EJS_STATE_ERR; - } - return EJS_STATE_DEC_LIST_DONE; -} - -/******************************************************************************/ -/* - * Parse expression (leftHandSide operator rightHandSide) - */ - -static int parseExpr(Ejs *ep, int state, int flags) -{ - MprVar lhs, rhs; - int rel, tid; - - mprAssert(ep); - - mprDestroyVar(&ep->result); - rhs = lhs = mprCreateUndefinedVar(); - rel = 0; - tid = 0; - - do { - /* - * This loop will handle an entire expression list. We call parse - * to evalutate each term which returns the result in ep->result. - */ - if (tid == EJS_TOK_LOGICAL) { - state = ejsParse(ep, EJS_STATE_RELEXP, flags); - if (state != EJS_STATE_RELEXP_DONE) { - state = EJS_STATE_ERR; - break; - } - } else { - tid = ejsLexGetToken(ep, state); - if (tid == EJS_TOK_EXPR && (int) *ep->token == EJS_EXPR_MINUS) { - lhs = mprCreateIntegerVar(0); - rel = (int) *ep->token; - } else { - ejsLexPutbackToken(ep, tid, ep->token); - } - - state = ejsParse(ep, EJS_STATE_EXPR, flags); - if (state != EJS_STATE_EXPR_DONE) { - state = EJS_STATE_ERR; - break; - } - } - - if (rel > 0) { - mprCopyVar(&rhs, &ep->result, MPR_SHALLOW_COPY); - if (tid == EJS_TOK_LOGICAL) { - if (evalCond(ep, &lhs, rel, &rhs) < 0) { - state = EJS_STATE_ERR; - break; - } - } else { - if (evalExpr(ep, &lhs, rel, &rhs) < 0) { - state = EJS_STATE_ERR; - break; - } - } - } - mprCopyVar(&lhs, &ep->result, MPR_SHALLOW_COPY); - - if ((tid = ejsLexGetToken(ep, state)) == EJS_TOK_EXPR || - tid == EJS_TOK_INC_DEC || tid == EJS_TOK_LOGICAL) { - rel = (int) *ep->token; - - } else { - ejsLexPutbackToken(ep, tid, ep->token); - state = EJS_STATE_RELEXP_DONE; - } - - } while (state == EJS_STATE_EXPR_DONE); - - mprDestroyVar(&lhs); - mprDestroyVar(&rhs); - - return state; -} - -/******************************************************************************/ -/* - * Parse the "for ... in" statement. Format for the statement is: - * - * for (var in expr) { - * body; - * } - */ - -static int parseForIn(Ejs *ep, int state, int flags) -{ - EjsInput endScript, bodyScript; - MprVar *iteratorVar, *setVar, *vp, v; - int forFlags, tid; - - mprAssert(ep); - - tid = ejsLexGetToken(ep, state); - if (tid != EJS_TOK_ID) { - return -1; - } - ejsLexPutbackToken(ep, tid, ep->token); - - if (ejsParse(ep, EJS_STATE_EXPR, EJS_FLAGS_FOREACH | EJS_FLAGS_EXE) - != EJS_STATE_EXPR_DONE) { - return -1; - } - if (ep->currentProperty == 0) { - return -1; - } - iteratorVar = ep->currentProperty; - - if (ejsLexGetToken(ep, state) != EJS_TOK_IN) { - return -1; - } - - /* - * Get the set - */ - tid = ejsLexGetToken(ep, state); - if (tid != EJS_TOK_ID) { - return -1; - } - ejsLexPutbackToken(ep, tid, ep->token); - - if (ejsParse(ep, EJS_STATE_EXPR, flags) != EJS_STATE_EXPR_DONE) { - return -1; - } - if (ep->currentProperty == 0 && flags & EJS_FLAGS_EXE) { - return -1; - } - setVar = ep->currentProperty; - - if (ejsLexGetToken(ep, state) != EJS_TOK_RPAREN) { - return -1; - } - - /* - * Parse the body and remember the end of the body script - */ - forFlags = flags & ~EJS_FLAGS_EXE; - ejsLexSaveInputState(ep, &bodyScript); - if (ejsParse(ep, EJS_STATE_STMT, forFlags) != EJS_STATE_STMT_DONE) { - ejsLexFreeInputState(ep, &bodyScript); - return -1; - } - ejsInitInputState(&endScript); - ejsLexSaveInputState(ep, &endScript); - - /* - * Now actually do the for loop. - */ - if (flags & EJS_FLAGS_EXE) { - if (setVar->type == MPR_TYPE_OBJECT) { - vp = mprGetFirstProperty(setVar, MPR_ENUM_DATA); - while (vp) { - if (strcmp(vp->name, "length") != 0) { - v = mprCreateStringVar(vp->name, 0); - if (mprWriteProperty(iteratorVar, &v) < 0) { - ejsError(ep, "Can't write to variable\n"); - ejsLexFreeInputState(ep, &bodyScript); - ejsLexFreeInputState(ep, &endScript); - return -1; - } - - ejsLexRestoreInputState(ep, &bodyScript); - switch (ejsParse(ep, EJS_STATE_STMT, flags)) { - case EJS_STATE_RET: - return EJS_STATE_RET; - case EJS_STATE_STMT_DONE: - break; - default: - ejsLexFreeInputState(ep, &endScript); - ejsLexFreeInputState(ep, &bodyScript); - return -1; - } - } - vp = mprGetNextProperty(setVar, vp, MPR_ENUM_DATA); - } - } else { - ejsError(ep, "Variable \"%s\" is not an array or object", - setVar->name); - ejsLexFreeInputState(ep, &endScript); - ejsLexFreeInputState(ep, &bodyScript); - return -1; - } - } - ejsLexRestoreInputState(ep, &endScript); - - ejsLexFreeInputState(ep, &endScript); - ejsLexFreeInputState(ep, &bodyScript); - - return state; -} - -/******************************************************************************/ -/* - * Parse the for statement. Format for the expression is: - * - * for (initial; condition; incr) { - * body; - * } - */ - -static int parseFor(Ejs *ep, int state, int flags) -{ - EjsInput condScript, endScript, bodyScript, incrScript; - int forFlags, cond; - - ejsInitInputState(&endScript); - ejsInitInputState(&bodyScript); - ejsInitInputState(&incrScript); - ejsInitInputState(&condScript); - - mprAssert(ep); - - /* - * Evaluate the for loop initialization statement - */ - if (ejsParse(ep, EJS_STATE_EXPR, flags) != EJS_STATE_EXPR_DONE) { - return -1; - } - if (ejsLexGetToken(ep, state) != EJS_TOK_SEMI) { - return -1; - } - - /* - * The first time through, we save the current input context just prior - * to each step: prior to the conditional, the loop increment and - * the loop body. - */ - ejsLexSaveInputState(ep, &condScript); - if (ejsParse(ep, EJS_STATE_COND, flags) != EJS_STATE_COND_DONE) { - goto error; - } - cond = (ep->result.boolean != 0); - - if (ejsLexGetToken(ep, state) != EJS_TOK_SEMI) { - goto error; - } - - /* - * Don't execute the loop increment statement or the body - * first time. - */ - forFlags = flags & ~EJS_FLAGS_EXE; - ejsLexSaveInputState(ep, &incrScript); - if (ejsParse(ep, EJS_STATE_EXPR, forFlags) != EJS_STATE_EXPR_DONE) { - goto error; - } - if (ejsLexGetToken(ep, state) != EJS_TOK_RPAREN) { - goto error; - } - - /* - * Parse the body and remember the end of the body script - */ - ejsLexSaveInputState(ep, &bodyScript); - if (ejsParse(ep, EJS_STATE_STMT, forFlags) != EJS_STATE_STMT_DONE) { - goto error; - } - ejsLexSaveInputState(ep, &endScript); - - /* - * Now actually do the for loop. Note loop has been rotated - */ - while (cond && (flags & EJS_FLAGS_EXE)) { - /* - * Evaluate the body - */ - ejsLexRestoreInputState(ep, &bodyScript); - - switch (ejsParse(ep, EJS_STATE_STMT, flags)) { - case EJS_STATE_RET: - return EJS_STATE_RET; - case EJS_STATE_STMT_DONE: - break; - default: - goto error; - } - /* - * Evaluate the increment script - */ - ejsLexRestoreInputState(ep, &incrScript); - if (ejsParse(ep, EJS_STATE_EXPR, flags) != EJS_STATE_EXPR_DONE){ - goto error; - } - /* - * Evaluate the condition - */ - ejsLexRestoreInputState(ep, &condScript); - if (ejsParse(ep, EJS_STATE_COND, flags) != EJS_STATE_COND_DONE) { - goto error; - } - mprAssert(ep->result.type == MPR_TYPE_BOOL); - cond = (ep->result.boolean != 0); - } - - ejsLexRestoreInputState(ep, &endScript); - -done: - ejsLexFreeInputState(ep, &condScript); - ejsLexFreeInputState(ep, &incrScript); - ejsLexFreeInputState(ep, &endScript); - ejsLexFreeInputState(ep, &bodyScript); - return state; - -error: - state = EJS_STATE_ERR; - goto done; -} - -/******************************************************************************/ -/* - * Parse a function declaration - */ - -static int parseFunctionDec(Ejs *ep, int state, int flags) -{ - EjsInput endScript, bodyScript; - MprVar v, *currentObj, *vp; - char *procName; - int len, tid, bodyFlags; - - mprAssert(ep); - mprAssert(ejsPtr(ep->eid)); - - /* - * function (arg, arg, arg) { body }; - * function name(arg, arg, arg) { body }; - */ - - tid = ejsLexGetToken(ep, state); - if (tid == EJS_TOK_ID) { - procName = mprStrdup(ep->token); - tid = ejsLexGetToken(ep, state); - } else { - procName = 0; - } - if (tid != EJS_TOK_LPAREN) { - mprFree(procName); - return EJS_STATE_ERR; - } - - /* - * Hand craft the function value structure. - */ - v = mprCreateFunctionVar(0, 0, 0); - tid = ejsLexGetToken(ep, state); - while (tid == EJS_TOK_ID) { - mprAddToArray(v.function.args, mprStrdup(ep->token)); - tid = ejsLexGetToken(ep, state); - if (tid == EJS_TOK_RPAREN || tid != EJS_TOK_COMMA) { - break; - } - tid = ejsLexGetToken(ep, state); - } - if (tid != EJS_TOK_RPAREN) { - mprFree(procName); - mprDestroyVar(&v); - return EJS_STATE_ERR; - } - - /* Allow new lines before opening brace */ - do { - tid = ejsLexGetToken(ep, state); - } while (tid == EJS_TOK_NEWLINE); - - if (tid != EJS_TOK_LBRACE) { - mprFree(procName); - mprDestroyVar(&v); - return EJS_STATE_ERR; - } - - /* - * Register the function name early to allow for recursive - * function calls (see note in ECMA standard, page 71) - */ - if (!(flags & EJS_FLAGS_ASSIGNMENT)) { - currentObj = ejsFindObj(ep, 0, procName, flags); - vp = mprSetProperty(currentObj, procName, &v); - } - - /* - * Parse the function body. Turn execute off. - */ - bodyFlags = flags & ~EJS_FLAGS_EXE; - ejsLexSaveInputState(ep, &bodyScript); - - do { - state = ejsParse(ep, EJS_STATE_STMT, bodyFlags); - } while (state == EJS_STATE_STMT_DONE); - - tid = ejsLexGetToken(ep, state); - if (state != EJS_STATE_STMT_BLOCK_DONE || tid != EJS_TOK_RBRACE) { - mprFree(procName); - mprDestroyVar(&v); - ejsLexFreeInputState(ep, &bodyScript); - return EJS_STATE_ERR; - } - ejsLexSaveInputState(ep, &endScript); - - /* - * Save the function body between the starting and ending parse positions. - * Overwrite the trailing '}' with a null. - */ - len = endScript.scriptServp - bodyScript.scriptServp; - v.function.body = mprMalloc(len + 1); - memcpy(v.function.body, bodyScript.scriptServp, len); - - if (len <= 0) { - v.function.body[0] = '\0'; - } else { - v.function.body[len - 1] = '\0'; - } - ejsLexFreeInputState(ep, &bodyScript); - ejsLexFreeInputState(ep, &endScript); - - /* - * If we are in an assignment, don't register the function name, rather - * return the function structure in the parser result. - */ - if (flags & EJS_FLAGS_ASSIGNMENT) { - mprCopyVar(&ep->result, &v, MPR_SHALLOW_COPY); - } else { - currentObj = ejsFindObj(ep, 0, procName, flags); - vp = mprSetProperty(currentObj, procName, &v); - } - - mprFree(procName); - mprDestroyVar(&v); - - return EJS_STATE_STMT; -} - -/******************************************************************************/ -/* - * Parse a function name and invoke the function - */ - -static int parseFunction(Ejs *ep, int state, int flags, char *id) -{ - EjsProc proc, *saveProc; - MprVar *saveObj; - - /* - * Must save any current ep->proc value for the current stack frame - * to allow for recursive function calls. - */ - saveProc = (ep->proc) ? ep->proc: 0; - - memset(&proc, 0, sizeof(EjsProc)); - proc.procName = mprStrdup(id); - proc.fn = ep->currentProperty; - proc.args = mprCreateArray(); - ep->proc = &proc; - - mprDestroyVar(&ep->result); - - saveObj = ep->currentObj; - if (ejsParse(ep, EJS_STATE_ARG_LIST, flags) != EJS_STATE_ARG_LIST_DONE) { - freeProc(&proc); - ep->proc = saveProc; - return -1; - } - ep->currentObj = saveObj; - - /* - * Evaluate the function if required - */ - if (flags & EJS_FLAGS_EXE) { - if (evalFunction(ep, ep->currentObj, flags) < 0) { - freeProc(&proc); - ep->proc = saveProc; - return -1; - } - } - - freeProc(&proc); - ep->proc = saveProc; - - if (ejsLexGetToken(ep, state) != EJS_TOK_RPAREN) { - return -1; - } - return state; -} - -/******************************************************************************/ -/* - * Parse an identifier. This is a segment of a fully qualified variable. - * May come here for an initial identifier or for property names - * after a "." or "[...]". - */ - -static int parseId(Ejs *ep, int state, int flags, char **id, char **fullName, - int *fullNameLen, int *done) -{ - int tid; - - mprFree(*id); - *id = mprStrdup(ep->token); -#if BLD_DEBUG - *fullNameLen = mprReallocStrcat(fullName, MPR_MAX_VAR, *fullNameLen, - 0, *id, NULL); -#endif - if (ep->currentObj == 0) { - ep->currentObj = ejsFindObj(ep, state, *id, flags); - } - - /* - * Find the referenced variable and store it in currentProperty. - */ - ep->currentProperty = ejsFindProperty(ep, state, ep->currentObj, - *id, flags); - updateResult(ep, state, flags, ep->currentProperty); - -#if BLD_DEBUG - if (ep->currentProperty && (ep->currentProperty->name == 0 || - ep->currentProperty->name[0] == '\0')) { - mprSetVarName(ep->currentProperty, *id); - } -#endif - - tid = ejsLexGetToken(ep, state); - if (tid == EJS_TOK_LPAREN) { - if (ep->currentProperty == 0 && (flags & EJS_FLAGS_EXE)) { - ejsError(ep, "Function name not defined \"%s\"\n", *id); - return -1; - } - ejsLexPutbackToken(ep, EJS_TOK_FUNCTION_NAME, ep->token); - return state; - } - - if (tid == EJS_TOK_PERIOD || tid == EJS_TOK_LBRACKET || - tid == EJS_TOK_ASSIGNMENT || tid == EJS_TOK_INC_DEC) { - ejsLexPutbackToken(ep, tid, ep->token); - return state; - } - - /* - * Only come here for variable access and declarations. - * Assignment handled elsewhere. - */ - if (flags & EJS_FLAGS_EXE) { - if (state == EJS_STATE_DEC) { - /* - * Declare a variable. Standard allows: var x ; var x ; - */ -#if DISABLED - if (ep->currentProperty != 0) { - ejsError(ep, "Variable already defined \"%s\"\n", *id); - return -1; - } -#endif - /* - * Create or overwrite if it already exists - */ - mprSetPropertyValue(ep->currentObj, *id, - mprCreateUndefinedVar()); - ep->currentProperty = 0; - mprDestroyVar(&ep->result); - - } else if (flags & EJS_FLAGS_FOREACH) { - if (ep->currentProperty == 0) { - ep->currentProperty = - mprCreatePropertyValue(ep->currentObj, *id, - mprCreateUndefinedVar()); - } - - } else { - if (ep->currentProperty == 0) { - if (ep->currentObj == ep->global || - ep->currentObj == ep->local) { - ejsError(ep, "Undefined variable \"%s\"\n", *id); - return -1; - } - ep->currentProperty = mprCreatePropertyValue(ep->currentObj, - *id, mprCreateUndefinedVar()); - } - } - } - ejsLexPutbackToken(ep, tid, ep->token); - if (tid == EJS_TOK_RBRACKET || tid == EJS_TOK_COMMA || - tid == EJS_TOK_IN) { - *done = 1; - } - return state; -} - -/******************************************************************************/ -/* - * Parse an "if" statement - */ - -static int parseIf(Ejs *ep, int state, int flags, int *done) -{ - bool ifResult; - int thenFlags, elseFlags, tid; - - if (state != EJS_STATE_STMT) { - return -1; - } - if (ejsLexGetToken(ep, state) != EJS_TOK_LPAREN) { - return -1; - } - - /* - * Evaluate the entire condition list "(condition)" - */ - if (ejsParse(ep, EJS_STATE_COND, flags) != EJS_STATE_COND_DONE) { - return -1; - } - if (ejsLexGetToken(ep, state) != EJS_TOK_RPAREN) { - return -1; - } - - /* - * This is the "then" case. We need to always parse both cases and - * execute only the relevant case. - */ - ifResult = mprVarToBool(&ep->result); - if (ifResult) { - thenFlags = flags; - elseFlags = flags & ~EJS_FLAGS_EXE; - } else { - thenFlags = flags & ~EJS_FLAGS_EXE; - elseFlags = flags; - } - - /* - * Process the "then" case. - */ - switch (ejsParse(ep, EJS_STATE_STMT, thenFlags)) { - case EJS_STATE_RET: - state = EJS_STATE_RET; - return state; - case EJS_STATE_STMT_DONE: - break; - default: - return -1; - } - - /* - * Check to see if there is an "else" case - */ - removeNewlines(ep, state); - tid = ejsLexGetToken(ep, state); - if (tid != EJS_TOK_ELSE) { - ejsLexPutbackToken(ep, tid, ep->token); - *done = 1; - return state; - } - - /* - * Process the "else" case. - */ - switch (ejsParse(ep, EJS_STATE_STMT, elseFlags)) { - case EJS_STATE_RET: - state = EJS_STATE_RET; - return state; - case EJS_STATE_STMT_DONE: - break; - default: - return -1; - } - *done = 1; - return state; -} - -/******************************************************************************/ -/* - * Parse an "++" or "--" statement - */ - -static int parseInc(Ejs *ep, int state, int flags) -{ - MprVar one; - - if (! (flags & EJS_FLAGS_EXE)) { - return state; - } - - if (ep->currentProperty == 0) { - ejsError(ep, "Undefined variable \"%s\"\n", ep->token); - return -1; - } - one = mprCreateIntegerVar(1); - if (evalExpr(ep, ep->currentProperty, (int) *ep->token, - &one) < 0) { - return -1; - } - if (mprWriteProperty(ep->currentProperty, &ep->result) < 0) { - ejsError(ep, "Can't write to variable\n"); - return -1; - } - return state; -} - -/******************************************************************************/ -/* - * Evaluate a condition. Implements &&, ||, !. Returns with a boolean result - * in ep->result. Returns -1 on errors, zero if successful. - */ - -static int evalCond(Ejs *ep, MprVar *lhs, int rel, MprVar *rhs) -{ - bool l, r, lval; - - mprAssert(rel > 0); - - l = mprVarToBool(lhs); - r = mprVarToBool(rhs); - - switch (rel) { - case EJS_COND_AND: - lval = l && r; - break; - case EJS_COND_OR: - lval = l || r; - break; - default: - ejsError(ep, "Bad operator %d", rel); - return -1; - } - - mprCopyVarValue(&ep->result, mprCreateBoolVar(lval), 0); - return 0; -} - - -/* - return true if this string is a valid number -*/ -static int string_is_number(const char *s) -{ - char *endptr = NULL; - if (s == NULL || *s == 0) { - return 0; - } - strtod(s, &endptr); - if (endptr != NULL && *endptr == 0) { - return 1; - } - return 0; -} - -/******************************************************************************/ -/* - * Evaluate an operation. Returns with the result in ep->result. Returns -1 - * on errors, otherwise zero is returned. - */ - -static int evalExpr(Ejs *ep, MprVar *lhs, int rel, MprVar *rhs) -{ - char *str; - MprNum lval, num; - int rc; - - mprAssert(rel > 0); - str = 0; - lval = 0; - - /* - * Type conversion. This is tricky and must be according to the standard. - * Only numbers (including floats) and strings can be compared. All other - * types are first converted to numbers by preference and if that fails, - * to strings. - * - * First convert objects to comparable types. The "===" operator will - * test the sameness of object references. Here, we coerce to comparable - * types first. - */ - if (lhs->type == MPR_TYPE_OBJECT) { - if (ejsRunFunction(ep->eid, lhs, "toValue", 0) == 0) { - mprCopyVar(lhs, &ep->result, MPR_SHALLOW_COPY); - } else { - if (ejsRunFunction(ep->eid, lhs, "toString", 0) == 0) { - mprCopyVar(lhs, &ep->result, MPR_SHALLOW_COPY); - } - } - /* Nothing more can be done */ - } - - if (rhs->type == MPR_TYPE_OBJECT) { - if (ejsRunFunction(ep->eid, rhs, "toValue", 0) == 0) { - mprCopyVar(rhs, &ep->result, MPR_SHALLOW_COPY); - } else { - if (ejsRunFunction(ep->eid, rhs, "toString", 0) == 0) { - mprCopyVar(rhs, &ep->result, MPR_SHALLOW_COPY); - } - } - /* Nothing more can be done */ - } - - /* undefined and null are special, in that they don't get promoted when - comparing */ - if (rel == EJS_EXPR_EQ || rel == EJS_EXPR_NOTEQ) { - if (lhs->type == MPR_TYPE_UNDEFINED || rhs->type == MPR_TYPE_UNDEFINED) { - return evalBoolExpr(ep, - lhs->type == MPR_TYPE_UNDEFINED, - rel, - rhs->type == MPR_TYPE_UNDEFINED); - } - - if (lhs->type == MPR_TYPE_NULL || rhs->type == MPR_TYPE_NULL) { - return evalBoolExpr(ep, - lhs->type == MPR_TYPE_NULL, - rel, - rhs->type == MPR_TYPE_NULL); - } - } - - /* - * From here on, lhs and rhs may contain allocated data (strings), so - * we must always destroy before overwriting. - */ - - /* - * Only allow a few bool operations. Otherwise convert to number. - */ - if (lhs->type == MPR_TYPE_BOOL && rhs->type == MPR_TYPE_BOOL && - (rel != EJS_EXPR_EQ && rel != EJS_EXPR_NOTEQ && - rel != EJS_EXPR_BOOL_COMP)) { - num = mprVarToNumber(lhs); - mprDestroyVar(lhs); - *lhs = mprCreateNumberVar(num); - } - - /* - * Types do not match, so try to coerce the right operand to match the left - * But first, try to convert a left operand that is a numeric stored as a - * string, into a numeric. - */ - if (lhs->type != rhs->type) { - if (lhs->type == MPR_TYPE_STRING) { - if (string_is_number(lhs->string)) { - num = mprVarToNumber(lhs); - lhs->allocatedVar = 0; - mprDestroyVar(lhs); - *lhs = mprCreateNumberVar(num); - /* Examine further below */ - - } else { - /* - * Convert the RHS to a string - */ - mprVarToString(&str, MPR_MAX_STRING, 0, rhs); - rhs->allocatedVar = 0; - mprDestroyVar(rhs); - *rhs = mprCreateStringVar(str, 1); - mprFree(str); - } - -#if BLD_FEATURE_FLOATING_POINT - } else if (lhs->type == MPR_TYPE_FLOAT) { - /* - * Convert rhs to floating - */ - double f = mprVarToFloat(rhs); - mprDestroyVar(rhs); - *rhs = mprCreateFloatVar(f); - -#endif -#if BLD_FEATURE_INT64 - } else if (lhs->type == MPR_TYPE_INT64) { - /* - * Convert the rhs to 64 bit - */ - int64 n = mprVarToInteger64(rhs); - mprDestroyVar(rhs); - *rhs = mprCreateInteger64Var(n); -#endif - } else if (lhs->type == MPR_TYPE_BOOL || lhs->type == MPR_TYPE_INT) { - - if (rhs->type == MPR_TYPE_STRING) { - /* - * Convert to lhs to a string - */ - mprVarToString(&str, MPR_MAX_STRING, 0, lhs); - mprDestroyVar(lhs); - *lhs = mprCreateStringVar(str, 1); - mprFree(str); - -#if BLD_FEATURE_FLOATING_POINT - } else if (rhs->type == MPR_TYPE_FLOAT) { - /* - * Convert lhs to floating - */ - double f = mprVarToFloat(lhs); - mprDestroyVar(lhs); - *lhs = mprCreateFloatVar(f); -#endif - - } else { - /* - * Convert both operands to numbers - */ - num = mprVarToNumber(lhs); - mprDestroyVar(lhs); - *lhs = mprCreateNumberVar(num); - - num = mprVarToNumber(rhs); - mprDestroyVar(rhs); - *rhs = mprCreateNumberVar(num); - } - } - } - - /* - * We have failed to coerce the types to be the same. Special case here - * for undefined and null. We need to allow comparisions against these - * special values. - */ - if (lhs->type == MPR_TYPE_UNDEFINED || lhs->type == MPR_TYPE_NULL) { - switch (rel) { - case EJS_EXPR_EQ: - lval = lhs->type == rhs->type; - break; - case EJS_EXPR_NOTEQ: - lval = lhs->type != rhs->type; - break; - case EJS_EXPR_BOOL_COMP: - lval = ! mprVarToBool(rhs); - break; - default: - lval = 0; - } - mprCopyVarValue(&ep->result, mprCreateBoolVar((bool) lval), 0); - return 0; - } - - /* - * Types are the same here - */ - switch (lhs->type) { - default: - case MPR_TYPE_UNDEFINED: - case MPR_TYPE_NULL: - /* Should be handled above */ - mprAssert(0); - return 0; - - case MPR_TYPE_STRING_CFUNCTION: - case MPR_TYPE_CFUNCTION: - case MPR_TYPE_FUNCTION: - case MPR_TYPE_OBJECT: - mprCopyVarValue(&ep->result, mprCreateBoolVar(0), 0); - return 0; - - case MPR_TYPE_PTR: - rc = evalPtrExpr(ep, lhs->ptr, rel, rhs->ptr); - break; - - case MPR_TYPE_BOOL: - rc = evalBoolExpr(ep, lhs->boolean, rel, rhs->boolean); - break; - -#if BLD_FEATURE_FLOATING_POINT - case MPR_TYPE_FLOAT: - rc = evalFloatExpr(ep, lhs->floating, rel, rhs->floating); - break; -#endif - - case MPR_TYPE_INT: - rc = evalNumericExpr(ep, (MprNum) lhs->integer, rel, - (MprNum) rhs->integer); - break; - -#if BLD_FEATURE_INT64 - case MPR_TYPE_INT64: - rc = evalNumericExpr(ep, (MprNum) lhs->integer64, rel, - (MprNum) rhs->integer64); - break; -#endif - - case MPR_TYPE_STRING: - rc = evalStringExpr(ep, lhs, rel, rhs); - } - return rc; -} - -/******************************************************************************/ -#if BLD_FEATURE_FLOATING_POINT -/* - * Expressions with floating operands - */ - -static int evalFloatExpr(Ejs *ep, double l, int rel, double r) -{ - double lval; - bool logical; - - lval = 0; - logical = 0; - - switch (rel) { - case EJS_EXPR_PLUS: - lval = l + r; - break; - case EJS_EXPR_INC: - lval = l + 1; - break; - case EJS_EXPR_MINUS: - lval = l - r; - break; - case EJS_EXPR_DEC: - lval = l - 1; - break; - case EJS_EXPR_MUL: - lval = l * r; - break; - case EJS_EXPR_DIV: - lval = l / r; - break; - default: - logical++; - break; - } - - /* - * Logical operators - */ - if (logical) { - - switch (rel) { - case EJS_EXPR_EQ: - lval = l == r; - break; - case EJS_EXPR_NOTEQ: - lval = l != r; - break; - case EJS_EXPR_LESS: - lval = (l < r) ? 1 : 0; - break; - case EJS_EXPR_LESSEQ: - lval = (l <= r) ? 1 : 0; - break; - case EJS_EXPR_GREATER: - lval = (l > r) ? 1 : 0; - break; - case EJS_EXPR_GREATEREQ: - lval = (l >= r) ? 1 : 0; - break; - case EJS_EXPR_BOOL_COMP: - lval = (r == 0) ? 1 : 0; - break; - default: - ejsError(ep, "Bad operator %d", rel); - return -1; - } - mprCopyVarValue(&ep->result, mprCreateBoolVar(lval != 0), 0); - - } else { - mprCopyVarValue(&ep->result, mprCreateFloatVar(lval), 0); - } - return 0; -} - -#endif /* BLD_FEATURE_FLOATING_POINT */ -/******************************************************************************/ -/* - * Expressions with boolean operands - */ - -static int evalBoolExpr(Ejs *ep, bool l, int rel, bool r) -{ - bool lval; - - switch (rel) { - case EJS_EXPR_EQ: - lval = l == r; - break; - case EJS_EXPR_NOTEQ: - lval = l != r; - break; - case EJS_EXPR_BOOL_COMP: - lval = (r == 0) ? 1 : 0; - break; - default: - ejsError(ep, "Bad operator %d", rel); - return -1; - } - mprCopyVarValue(&ep->result, mprCreateBoolVar(lval), 0); - return 0; -} - -static int evalPtrExpr(Ejs *ep, void *l, int rel, void *r) -{ - bool lval; - - switch (rel) { - case EJS_EXPR_EQ: - lval = l == r; - break; - case EJS_EXPR_NOTEQ: - lval = l != r; - break; - case EJS_EXPR_BOOL_COMP: - lval = (r == NULL) ? 1 : 0; - break; - default: - ejsError(ep, "Bad operator %d", rel); - return -1; - } - mprCopyVarValue(&ep->result, mprCreateBoolVar(lval), 0); - return 0; -} - -/******************************************************************************/ -/* - * Expressions with numeric operands - */ - -static int evalNumericExpr(Ejs *ep, MprNum l, int rel, MprNum r) -{ - MprNum lval; - bool logical; - - lval = 0; - logical = 0; - - switch (rel) { - case EJS_EXPR_PLUS: - lval = l + r; - break; - case EJS_EXPR_INC: - lval = l + 1; - break; - case EJS_EXPR_MINUS: - lval = l - r; - break; - case EJS_EXPR_DEC: - lval = l - 1; - break; - case EJS_EXPR_MUL: - lval = l * r; - break; - case EJS_EXPR_DIV: - if (r != 0) { - lval = l / r; - } else { - ejsError(ep, "Divide by zero"); - return -1; - } - break; - case EJS_EXPR_MOD: - if (r != 0) { - lval = l % r; - } else { - ejsError(ep, "Modulo zero"); - return -1; - } - break; - case EJS_EXPR_LSHIFT: - lval = l << r; - break; - case EJS_EXPR_RSHIFT: - lval = l >> r; - break; - - default: - logical++; - break; - } - - /* - * Logical operators - */ - if (logical) { - - switch (rel) { - case EJS_EXPR_EQ: - lval = l == r; - break; - case EJS_EXPR_NOTEQ: - lval = l != r; - break; - case EJS_EXPR_LESS: - lval = (l < r) ? 1 : 0; - break; - case EJS_EXPR_LESSEQ: - lval = (l <= r) ? 1 : 0; - break; - case EJS_EXPR_GREATER: - lval = (l > r) ? 1 : 0; - break; - case EJS_EXPR_GREATEREQ: - lval = (l >= r) ? 1 : 0; - break; - case EJS_EXPR_BOOL_COMP: - lval = (r == 0) ? 1 : 0; - break; - default: - ejsError(ep, "Bad operator %d", rel); - return -1; - } - mprCopyVarValue(&ep->result, mprCreateBoolVar(lval != 0), 0); - - } else { - mprCopyVarValue(&ep->result, mprCreateNumberVar(lval), 0); - } - return 0; -} - -/******************************************************************************/ -/* - * Expressions with string operands - */ - -static int evalStringExpr(Ejs *ep, MprVar *lhs, int rel, MprVar *rhs) -{ - int lval; - - mprAssert(ep); - mprAssert(lhs); - mprAssert(rhs); - - switch (rel) { - case EJS_EXPR_LESS: - lval = strcmp(lhs->string, rhs->string) < 0; - break; - case EJS_EXPR_LESSEQ: - lval = strcmp(lhs->string, rhs->string) <= 0; - break; - case EJS_EXPR_GREATER: - lval = strcmp(lhs->string, rhs->string) > 0; - break; - case EJS_EXPR_GREATEREQ: - lval = strcmp(lhs->string, rhs->string) >= 0; - break; - case EJS_EXPR_EQ: - lval = strcmp(lhs->string, rhs->string) == 0; - break; - case EJS_EXPR_NOTEQ: - lval = strcmp(lhs->string, rhs->string) != 0; - break; - case EJS_EXPR_PLUS: - /* - * This differs from all the above operations. We append rhs to lhs. - */ - mprDestroyVar(&ep->result); - appendValue(&ep->result, lhs); - appendValue(&ep->result, rhs); - return 0; - - case EJS_EXPR_INC: - case EJS_EXPR_DEC: - case EJS_EXPR_MINUS: - case EJS_EXPR_DIV: - case EJS_EXPR_MOD: - case EJS_EXPR_LSHIFT: - case EJS_EXPR_RSHIFT: - default: - ejsError(ep, "Bad operator"); - return -1; - } - - mprCopyVarValue(&ep->result, mprCreateBoolVar(lval), 0); - return 0; -} - -/******************************************************************************/ -/* - * Evaluate a function. obj is set to the current object if a function is being - * run. - */ - -static int evalFunction(Ejs *ep, MprVar *obj, int flags) -{ - EjsProc *proc; - MprVar arguments, callee, thisObject, *prototype, **argValues; - MprArray *formalArgs, *actualArgs; - char buf[16], **argNames, **argBuf; - int i, rc, fid; - - mprAssert(ep); - mprAssert(ejsPtr(ep->eid)); - - rc = -1; - proc = ep->proc; - prototype = proc->fn; - actualArgs = proc->args; - argValues = (MprVar**) actualArgs->handles; - - /* - * Create a new variable stack frame. ie. new local variables. - */ - fid = ejsOpenBlock(ep->eid); - - if (flags & EJS_FLAGS_NEW) { - /* - * Create a new bare object and pass it into the constructor as the - * "this" local variable. - */ - thisObject = ejsCreateObj("this", EJS_OBJ_HASH_SIZE); - mprCreatePropertyValue(ep->local, "this", thisObject); - - } else if (obj) { - mprCreateProperty(ep->local, "this", obj); - } - - switch (prototype->type) { - default: - mprAssert(0); - break; - - case MPR_TYPE_STRING_CFUNCTION: - if (actualArgs->used > 0) { - argBuf = mprMalloc((1+actualArgs->used) * sizeof(char*)); - for (i = 0; i < actualArgs->used; i++) { - mprVarToString(&argBuf[i], MPR_MAX_STRING, 0, argValues[i]); - } - argBuf[i] = NULL; - } else { - argBuf = 0; - } - - /* - * Call the function depending on the various handle flags - */ - ep->thisPtr = prototype->cFunctionWithStrings.thisPtr; - if (prototype->flags & MPR_VAR_ALT_HANDLE) { - rc = ((EjsAltStringCFunction) prototype->cFunctionWithStrings.fn) - (ep->eid, ep->altHandle, actualArgs->used, argBuf); - } else if (prototype->flags & MPR_VAR_SCRIPT_HANDLE) { - rc = (prototype->cFunctionWithStrings.fn)(ep->eid, - actualArgs->used, argBuf); - } else { - rc = (prototype->cFunctionWithStrings.fn)(ep->primaryHandle, - actualArgs->used, argBuf); - } - - if (actualArgs->used > 0) { - for (i = 0; i < actualArgs->used; i++) { - mprFree(argBuf[i]); - } - mprFree(argBuf); - } - ep->thisPtr = 0; - break; - - case MPR_TYPE_CFUNCTION: - /* - * Call the function depending on the various handle flags - */ - ep->thisPtr = prototype->cFunction.thisPtr; - if (prototype->flags & MPR_VAR_ALT_HANDLE) { - rc = ((EjsAltCFunction) prototype->cFunction.fn) - (ep->eid, ep->altHandle, actualArgs->used, argValues); - } else if (prototype->flags & MPR_VAR_SCRIPT_HANDLE) { - rc = (prototype->cFunction.fn)(ep->eid, actualArgs->used, - argValues); - } else { - rc = (prototype->cFunction.fn)(ep->primaryHandle, - actualArgs->used, argValues); - } - ep->thisPtr = 0; - break; - - case MPR_TYPE_FUNCTION: - - formalArgs = prototype->function.args; - argNames = (char**) formalArgs->handles; - - if (formalArgs->used > actualArgs->used) { - ejsError(ep, "Bad number of args. Should be %d", - formalArgs->used); - return -1; - } - - /* - * Create the arguments and callee variables - */ - arguments = ejsCreateObj("arguments", EJS_SMALL_OBJ_HASH_SIZE); - callee = ejsCreateObj("callee", EJS_SMALL_OBJ_HASH_SIZE); - - /* - * Overwrite the length property - */ - mprCreatePropertyValue(&arguments, "length", - mprCreateIntegerVar(actualArgs->used)); - mprCreatePropertyValue(&callee, "length", - mprCreateIntegerVar(formalArgs->used)); - - /* - * Define all the agruments to be set to the actual parameters - */ - for (i = 0; i < formalArgs->used; i++) { - mprCreateProperty(ep->local, argNames[i], argValues[i]); - } - for (i = 0; i < actualArgs->used; i++) { - mprItoa(i, buf, sizeof(buf)); - mprCreateProperty(&arguments, buf, argValues[i]); - } - - mprCreateProperty(&arguments, "callee", &callee); - mprCreateProperty(ep->local, "arguments", &arguments); - - /* - * Can destroy our variables here as they are now referenced via - * "local" - */ - mprDestroyVar(&callee); - mprDestroyVar(&arguments); - - /* - * Actually run the function - */ - rc = ejsEvalScript(ep->eid, prototype->function.body, 0, 0); - break; - } - - ejsCloseBlock(ep->eid, fid); - - /* - * New statements return the newly created object as the result of the - * command - */ - if (flags & EJS_FLAGS_NEW) { - mprDestroyVar(&ep->result); - /* - * Don't copy, we want to assign the actual object into result. - * (mprCopyVar would inc the refCount to 2). - */ - ep->result = thisObject; - } - return rc; -} - -/******************************************************************************/ -/* - * Run a function - */ - -int ejsRunFunction(int eid, MprVar *obj, const char *functionName, - MprArray *args) -{ - EjsProc proc, *saveProc; - Ejs *ep; - int rc; - - mprAssert(obj); - mprAssert(functionName && *functionName); - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return MPR_ERR_NOT_FOUND; - } - saveProc = ep->proc; - ep->proc = &proc; - - memset(&proc, 0, sizeof(EjsProc)); - mprDestroyVar(&ep->result); - - proc.fn = mprGetProperty(obj, functionName, 0); - if (proc.fn == 0 || proc.fn->type == MPR_TYPE_UNDEFINED) { - ep->proc = saveProc; - return MPR_ERR_NOT_FOUND; - } - proc.procName = mprStrdup(functionName); - if (args == 0) { - proc.args = mprCreateArray(); - rc = evalFunction(ep, obj, 0); - } else { - proc.args = args; - rc = evalFunction(ep, obj, 0); - proc.args = 0; - } - - freeProc(&proc); - ep->proc = saveProc; - - return rc; -} - -/******************************************************************************/ -/* - * Find which object contains the property given the current context. - * Only used for top level properties. - */ - -MprVar *ejsFindObj(Ejs *ep, int state, const char *property, int flags) -{ - MprVar *obj; - - mprAssert(ep); - mprAssert(property && *property); - - if (flags & EJS_FLAGS_GLOBAL) { - obj = ep->global; - - } else if (state == EJS_STATE_DEC || flags & EJS_FLAGS_LOCAL) { - obj = ep->local; - - } else { - /* First look local, then look global */ - if (mprGetProperty(ep->local, property, 0)) { - obj = ep->local; - } else { - obj = ep->global; - } - } - return obj; -} - -/******************************************************************************/ -/* - * Find an object property given a object and a property name. We - * intelligently look in the local and global namespaces depending on - * our state. If not found in local or global, try base classes for function - * names only. Returns the property or NULL. - */ - -MprVar *ejsFindProperty(Ejs *ep, int state, MprVar *obj, char *property, - int flags) -{ - MprVar *vp; - - mprAssert(ep); - if (flags & EJS_FLAGS_EXE) { - mprAssert(property && *property); - } - - if (obj != 0) { -#if FUTURE && MB - op = obj; - do { - vp = mprGetProperty(op, property, 0); - if (vp != 0) { - if (op != obj && mprVarIsFunction(vp->type)) { - } - break; - } - op = op->baseObj; - } while (op); -#endif - vp = mprGetProperty(obj, property, 0); - - } else { - if (state == EJS_STATE_DEC) { - vp = mprGetProperty(ep->local, property, 0); - - } else { - /* Look local first, then global */ - vp = mprGetProperty(ep->local, property, 0); - if (vp == NULL) { - vp = mprGetProperty(ep->global, property, 0); - } - } - } - return vp; -} - -/******************************************************************************/ -/* - * Update result - */ - -static void updateResult(Ejs *ep, int state, int flags, MprVar *vp) -{ - if (flags & EJS_FLAGS_EXE && state != EJS_STATE_DEC) { - mprDestroyVar(&ep->result); - if (vp) { - mprCopyProperty(&ep->result, vp, MPR_SHALLOW_COPY); - } - } -} - -/******************************************************************************/ -/* - * Append to the pointer value - */ - -static void appendValue(MprVar *dest, MprVar *src) -{ - char *value, *oldBuf, *buf; - int len, oldLen; - - mprAssert(dest); - - mprVarToString(&value, MPR_MAX_STRING, 0, src); - - if (mprVarIsValid(dest)) { - len = strlen(value); - oldBuf = dest->string; - oldLen = strlen(oldBuf); - buf = mprRealloc(oldBuf, (len + oldLen + 1) * sizeof(char)); - dest->string = buf; - strcpy(&buf[oldLen], value); - - } else { - *dest = mprCreateStringVar(value, 1); - } - mprFree(value); -} - -/******************************************************************************/ -/* - * Exit with status - */ - -void ejsSetExitStatus(int eid, int status) -{ - Ejs *ep; - - if ((ep = ejsPtr(eid)) == NULL) { - mprAssert(ep); - return; - } - ep->exitStatus = status; - ep->flags |= EJS_FLAGS_EXIT; -} - -/******************************************************************************/ -/* - * Free an argument list - */ - -static void freeProc(EjsProc *proc) -{ - MprVar **argValues; - int i; - - if (proc->args) { - argValues = (MprVar**) proc->args->handles; - - for (i = 0; i < proc->args->max; i++) { - if (argValues[i]) { - mprDestroyVar(argValues[i]); - mprFree(argValues[i]); - mprRemoveFromArray(proc->args, i); - } - } - - mprDestroyArray(proc->args); - } - - if (proc->procName) { - mprFree(proc->procName); - proc->procName = NULL; - } -} - -/******************************************************************************/ -/* - * This function removes any new lines. Used for else cases, etc. - */ - -static void removeNewlines(Ejs *ep, int state) -{ - int tid; - - do { - tid = ejsLexGetToken(ep, state); - } while (tid == EJS_TOK_NEWLINE); - - ejsLexPutbackToken(ep, tid, ep->token); -} - -/******************************************************************************/ - -#else -void ejsParserDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/ejs/ejsProcs.c b/source4/lib/appweb/ejs/ejsProcs.c deleted file mode 100644 index 43fff4a40b..0000000000 --- a/source4/lib/appweb/ejs/ejsProcs.c +++ /dev/null @@ -1,704 +0,0 @@ -/* - * @file ejsProc.c - * @brief EJS support functions - */ -/********************************* Copyright **********************************/ -/* - * @copy default.g - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * Portions Copyright (c) GoAhead Software, 1995-2000. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "ejsInternal.h" - -#if BLD_FEATURE_EJS - -/****************************** Forward Declarations **************************/ -/* - * Object constructors - */ -static int objectConsProc(EjsHandle eid, int argc, MprVar **argv); -static int arrayConsProc(EjsHandle eid, int argc, MprVar **argv); -static int booleanConsProc(EjsHandle eid, int argc, MprVar **agv); -static int numberConsProc(EjsHandle eid, int argc, MprVar **argv); -static int stringConsProc(EjsHandle eid, int argc, MprVar **argv); - -/* - * Core functions - */ -static int toStringProc(EjsHandle eid, int argc, MprVar **argv); -static int valueOfProc(EjsHandle eid, int argc, MprVar **argv); - -/* - * Triggers - */ -static MprVarTriggerStatus lengthTrigger(MprVarTriggerOp op, - MprProperties *parentProperties, MprVar *prop, MprVar *newValue, - int copyRef); - -/******************************************************************************/ -/* - * Routine to create the base common to all object types - */ - -MprVar ejsCreateObj(const char *name, int hashSize) -{ - MprVar o; - - o = mprCreateObjVar(name, hashSize); - if (o.type == MPR_TYPE_UNDEFINED) { - mprAssert(0); - return o; - } - - mprCreatePropertyValue(&o, "toString", - mprCreateCFunctionVar(toStringProc, 0, MPR_VAR_SCRIPT_HANDLE)); - mprCreatePropertyValue(&o, "valueOf", - mprCreateCFunctionVar(valueOfProc, 0, MPR_VAR_SCRIPT_HANDLE)); - return o; -} - -/******************************************************************************/ -/* - * Routine to destroy a variable - */ - -bool ejsDestroyVar(MprVar *obj) -{ - return mprDestroyVar(obj); -} - -/******************************************************************************/ -/* - * Routine to create the base array type - */ - -MprVar ejsCreateArray(const char *name, int size) -{ - MprVar obj, *lp, undef; - char idx[16]; - int i; - - /* Sanity limit for size of hash table */ - - obj = ejsCreateObj(name, max(size, 503)); - if (obj.type == MPR_TYPE_UNDEFINED) { - mprAssert(0); - return obj; - } - - undef = mprCreateUndefinedVar(); - for (i = 0; i < size; i++) { - mprItoa(i, idx, sizeof(idx)); - mprCreateProperty(&obj, idx, &undef); - } - - lp = mprCreatePropertyValue(&obj, "length", mprCreateIntegerVar(size)); - mprAssert(lp); - - mprSetVarReadonly(lp, 1); - mprAddVarTrigger(lp, lengthTrigger); - - return obj; -} - -/******************************************************************************/ -/******************************** Constructors ********************************/ -/******************************************************************************/ -/* - * Object constructor. Nothing really done here. For future expansion. - */ - -static int objectConsProc(EjsHandle eid, int argc, MprVar **argv) -{ -#if XX_UNUSED_XX - MprVar *obj; - Ejs *ep; - - if((ep = ejsPtr(eid)) == NULL) { - return -1; - } - - obj = mprGetProperty(ep->local, "this", 0); - mprAssert(obj); -#endif - return 0; -} - -/******************************************************************************/ -/* - * Array constructor - */ - -static int arrayConsProc(EjsHandle eid, int argc, MprVar **argv) -{ - MprVar *obj, *lp, undef; - Ejs *ep; - char idx[16]; - int i, max; - - objectConsProc(eid, argc, argv); - - if((ep = ejsPtr(eid)) == NULL) { - return -1; - } - obj = mprGetProperty(ep->local, "this", 0); - mprAssert(obj); - - - if (argc == 1 && mprVarIsNumber(argv[0]->type)) { - /* - * x = new Array(size); - */ - undef = mprCreateUndefinedVar(); - max = (int) mprVarToInteger(argv[0]); - for (i = 0; i < max; i++) { - mprItoa(i, idx, sizeof(idx)); - mprCreateProperty(obj, idx, &undef); - } - } else { - /* - * x = new Array(element0, element1, ..., elementN): - */ - max = argc; - for (i = 0; i < max; i++) { - mprItoa(i, idx, sizeof(idx)); - mprCreateProperty(obj, idx, argv[i]); - } - } - - lp = mprCreatePropertyValue(obj, "length", mprCreateIntegerVar(max)); - mprAssert(lp); - - mprSetVarReadonly(lp, 1); - mprAddVarTrigger(lp, lengthTrigger); - - return 0; -} - -/******************************************************************************/ -/* - * Boolean constructor - */ - -static int booleanConsProc(EjsHandle eid, int argc, MprVar **argv) -{ - objectConsProc(eid, argc, argv); - return 0; -} - -/******************************************************************************/ -#if FUTURE -/* - * Date constructor - */ - -static int dateConsProc(EjsHandle eid, int argc, MprVar **argv) -{ - objectConsProc(eid, argc, argv); - return 0; -} - -#endif -/******************************************************************************/ -/* - * Number constructor - */ - -static int numberConsProc(EjsHandle eid, int argc, MprVar **argv) -{ - objectConsProc(eid, argc, argv); - return 0; -} - -/******************************************************************************/ -/* - * String constructor - */ - -static int stringConsProc(EjsHandle eid, int argc, MprVar **argv) -{ - objectConsProc(eid, argc, argv); - return 0; -} - -/******************************************************************************/ -/********************************** Functions *********************************/ -/******************************************************************************/ - -static int toStringProc(EjsHandle eid, int argc, MprVar **argv) -{ - MprVar *obj; - Ejs *ep; - char *buf; - int radix; - - if (argc == 0) { - radix = 10; - - } else if (argc == 1) { - radix = (int) mprVarToInteger(argv[0]); - - } else { - mprAssert(0); - return -1; - } - - if((ep = ejsPtr(eid)) == NULL) { - return -1; - } - - obj = mprGetProperty(ep->local, "this", 0); - mprAssert(obj); - - mprVarToString(&buf, MPR_MAX_STRING, 0, obj); - mprCopyVarValue(&ep->result, mprCreateStringVar(buf, 0), MPR_SHALLOW_COPY); - mprFree(buf); - - return 0; -} - -/******************************************************************************/ - -static int valueOfProc(EjsHandle eid, int argc, MprVar **argv) -{ - MprVar *obj; - Ejs *ep; - - if (argc != 0) { - mprAssert(0); - return -1; - } - - if((ep = ejsPtr(eid)) == NULL) { - return -1; - } - - obj = mprGetProperty(ep->local, "this", 0); - mprAssert(obj); - - switch (obj->type) { - default: - case MPR_TYPE_UNDEFINED: - case MPR_TYPE_NULL: - case MPR_TYPE_CFUNCTION: - case MPR_TYPE_OBJECT: - case MPR_TYPE_FUNCTION: - case MPR_TYPE_STRING_CFUNCTION: - case MPR_TYPE_PTR: - mprCopyVar(&ep->result, obj, MPR_SHALLOW_COPY); - break; - - case MPR_TYPE_STRING: - mprCopyVarValue(&ep->result, mprCreateIntegerVar(atoi(obj->string)), 0); - break; - - case MPR_TYPE_BOOL: - case MPR_TYPE_INT: -#if BLD_FEATURE_INT64 - case MPR_TYPE_INT64: -#endif -#if BLD_FEATURE_FLOATING_POINT - case MPR_TYPE_FLOAT: -#endif - mprCopyVar(&ep->result, obj, 0); - break; - } - return 0; -} - -/******************************************************************************/ -/* - * Var access trigger on the Array.length property. Return the count of - * enumerable properties (don't count functions). - */ - -static MprVarTriggerStatus lengthTrigger(MprVarTriggerOp op, - MprProperties *parentProperties, MprVar *prop, MprVar *newValue, - int copyRef) -{ - switch (op) { - case MPR_VAR_READ: - /* - * Subtract one for the length property - * FUTURE -- need an API to access parentProperties - * FUTURE -- contradiction to be read-only yet allow USE_NEW_VALUE. - * API needs finer control. - */ - *newValue = mprCreateIntegerVar(parentProperties->numDataItems - 1); - return MPR_TRIGGER_USE_NEW_VALUE; - - case MPR_VAR_WRITE: - return MPR_TRIGGER_ABORT; - - case MPR_VAR_CREATE_PROPERTY: - case MPR_VAR_DELETE_PROPERTY: - case MPR_VAR_DELETE: - default: - break; - } - return MPR_TRIGGER_PROCEED; -} - -/******************************************************************************/ -/**************************** Extension Functions *****************************/ -/******************************************************************************/ -/* - * Assert - */ - -static int assertProc(EjsHandle eid, int argc, MprVar **argv) -{ - bool b; - - if (argc < 1) { - ejsSetErrorMsg(eid, "usage: assert(condition)\n"); - return -1; - } - b = mprVarToBool(argv[0]); - if (b == 0) { - ejsSetErrorMsg(eid, "Assertion failure\n"); - return -1; - } - ejsSetReturnValue(eid, mprCreateBoolVar(b)); - return 0; -} - -/******************************************************************************/ -/* - * Exit - */ - -static int exitProc(EjsHandle eid, int argc, MprVar **argv) -{ - int status; - - if (argc < 1) { - ejsSetErrorMsg(eid, "usage: exit(status)\n"); - return -1; - } - status = (int) mprVarToInteger(argv[0]); - ejsSetExitStatus(eid, status); - - ejsSetReturnValue(eid, mprCreateStringVar("", 0)); - return 0; -} - -/******************************************************************************/ - -static void printVar(MprVar *vp, int recurseCount, int indent) -{ - MprVar *np; - char *buf; - int i; - - if (recurseCount > 5) { - write(1, "Skipping - recursion too deep\n", 29); - return; - } - - for (i = 0; i < indent; i++) { - write(1, " ", 2); - } - - if (vp->type == MPR_TYPE_OBJECT) { - if (vp->name) { - write(1, vp->name, strlen(vp->name)); - } else { - write(1, "unknown", 7); - } - write(1, ": {\n", 4); - np = mprGetFirstProperty(vp, MPR_ENUM_DATA); - while (np) { - if (strcmp(np->name, "local") == 0 || - strcmp(np->name, "global") == 0 || - strcmp(np->name, "this") == 0) { - np = mprGetNextProperty(vp, np, MPR_ENUM_DATA); - continue; - } - printVar(np, recurseCount + 1, indent + 1); - np = mprGetNextProperty(vp, np, MPR_ENUM_DATA); - if (np) { - write(1, ",\n", 2); - } - } - write(1, "\n", 1); - for (i = 0; i < indent; i++) { - write(1, " ", 2); - } - write(1, "}", 1); - - } else { - if (vp->name) { - write(1, vp->name, strlen(vp->name)); - } else { - write(1, "unknown", 7); - } - write(1, ": ", 2); - - /* FUTURE -- other types ? */ - mprVarToString(&buf, MPR_MAX_STRING, 0, vp); - if (vp->type == MPR_TYPE_STRING) { - write(1, "\"", 1); - } - write(1, buf, strlen(buf)); - if (vp->type == MPR_TYPE_STRING) { - write(1, "\"", 1); - } - mprFree(buf); - } -} - -/******************************************************************************/ -/* - * Print the args to stdout - */ - -static int printVarsProc(EjsHandle eid, int argc, MprVar **argv) -{ - MprVar *vp; - char *buf; - int i; - - for (i = 0; i < argc; i++) { - vp = argv[i]; - switch (vp->type) { - case MPR_TYPE_OBJECT: - printVar(vp, 0, 0); - break; - default: - mprVarToString(&buf, MPR_MAX_STRING, 0, vp); - write(1, buf, strlen(buf)); - mprFree(buf); - break; - } - } - write(1, "\n", 1); - - ejsSetReturnValue(eid, mprCreateStringVar("", 0)); - return 0; -} - -/******************************************************************************/ -/* - * Print the args to stdout - */ - -static int printProc(EjsHandle eid, int argc, MprVar **argv) -{ - char *buf; - int i; - - for (i = 0; i < argc; i++) { - mprVarToString(&buf, MPR_MAX_STRING, 0, argv[i]); - write(1, buf, strlen(buf)); - mprFree(buf); - } - return 0; -} - -/******************************************************************************/ -/* - * println - */ - -static int printlnProc(EjsHandle eid, int argc, MprVar **argv) -{ - printProc(eid, argc, argv); - write(1, "\n", 1); - return 0; -} - -/******************************************************************************/ -/* - * Trace - */ - -static int traceProc(EjsHandle eid, int argc, char **argv) -{ - if (argc == 1) { - mprLog(0, "%s", argv[0]); - - } else if (argc == 2) { - mprLog(atoi(argv[0]), "%s", argv[1]); - - } else { - ejsSetErrorMsg(eid, "Usage: trace([level], message)"); - return -1; - } - ejsSetReturnString(eid, ""); - return 0; -} - -/******************************************************************************/ -/* - * Return the object reference count - */ - -static int refCountProc(EjsHandle eid, int argc, MprVar **argv) -{ - MprVar *vp; - int count; - - vp = argv[0]; - if (vp->type == MPR_TYPE_OBJECT) { - count = mprGetVarRefCount(vp); - ejsSetReturnValue(eid, mprCreateIntegerVar(count)); - } else { - ejsSetReturnValue(eid, mprCreateIntegerVar(0)); - } - - return 0; -} - -/******************************************************************************/ -/* - * Evaluate a sub-script. It is evaluated in the same variable scope as - * the calling script / function. - */ - -static int evalScriptProc(EjsHandle eid, int argc, MprVar **argv) -{ - MprVar *arg; - char *emsg; - int i; - - ejsSetReturnValue(eid, mprCreateUndefinedVar()); - - for (i = 0; i < argc; i++) { - arg = argv[i]; - if (arg->type != MPR_TYPE_STRING) { - continue; - } - if (ejsEvalScript(eid, arg->string, 0, &emsg) < 0) { - ejsSetErrorMsg(eid, "%s", emsg); - mprFree(emsg); - return -1; - } - } - /* - * Return with the value of the last expression - */ - return 0; -} - -/******************************************************************************/ -/******************************************************************************/ -/******************************************************************************/ -/* - * Define the standard properties and functions inherited by all script engines. - */ - -int ejsDefineStandardProperties(MprVar *obj) -{ -#if BLD_FEATURE_FLOATING_POINT - double d = 0.0; - - /* FUTURE - this generates warnings on some systems. This is okay. */ - - mprCreatePropertyValue(obj, "NaN", mprCreateFloatVar(0.0 / d)); - d = MAX_FLOAT; - mprCreatePropertyValue(obj, "Infinity", mprCreateFloatVar(d * d)); -#endif - mprCreatePropertyValue(obj, "null", mprCreateNullVar()); - mprCreatePropertyValue(obj, "undefined", mprCreateUndefinedVar()); - mprCreatePropertyValue(obj, "true", mprCreateBoolVar(1)); - mprCreatePropertyValue(obj, "false", mprCreateBoolVar(0)); - mprCreatePropertyValue(obj, "NULL", mprCreatePtrVar(NULL)); - -#if BLD_FEATURE_LEGACY_API - /* - * DEPRECATED: 2.0. - * So that ESP/ASP can ignore "language=javascript" statements - */ - mprCreatePropertyValue(obj, "javascript", mprCreateIntegerVar(0)); -#endif - - /* - * Extension functions - */ - mprCreatePropertyValue(obj, "assert", - mprCreateCFunctionVar(assertProc, 0, MPR_VAR_SCRIPT_HANDLE)); - mprCreatePropertyValue(obj, "eval", - mprCreateCFunctionVar(evalScriptProc, 0, MPR_VAR_SCRIPT_HANDLE)); - mprCreatePropertyValue(obj, "exit", - mprCreateCFunctionVar(exitProc, 0, MPR_VAR_SCRIPT_HANDLE)); - mprCreatePropertyValue(obj, "refCount", - mprCreateCFunctionVar(refCountProc, 0, MPR_VAR_SCRIPT_HANDLE)); - mprCreatePropertyValue(obj, "print", - mprCreateCFunctionVar(printProc, 0, MPR_VAR_SCRIPT_HANDLE)); - mprCreatePropertyValue(obj, "println", - mprCreateCFunctionVar(printlnProc, 0, MPR_VAR_SCRIPT_HANDLE)); - mprCreatePropertyValue(obj, "printVars", - mprCreateCFunctionVar(printVarsProc,0, MPR_VAR_SCRIPT_HANDLE)); - mprCreatePropertyValue(obj, "trace", - mprCreateStringCFunctionVar(traceProc, 0, MPR_VAR_SCRIPT_HANDLE)); - - /* - * Constructors - */ - mprCreatePropertyValue(obj, "Array", - mprCreateCFunctionVar(arrayConsProc, 0, MPR_VAR_SCRIPT_HANDLE)); - mprCreatePropertyValue(obj, "Boolean", - mprCreateCFunctionVar(booleanConsProc, 0, MPR_VAR_SCRIPT_HANDLE)); - mprCreatePropertyValue(obj, "Object", - mprCreateCFunctionVar(objectConsProc, 0, MPR_VAR_SCRIPT_HANDLE)); - mprCreatePropertyValue(obj, "Number", - mprCreateCFunctionVar(numberConsProc, 0, MPR_VAR_SCRIPT_HANDLE)); - mprCreatePropertyValue(obj, "String", - mprCreateCFunctionVar(stringConsProc, 0, MPR_VAR_SCRIPT_HANDLE)); - - /* mprCreatePropertyValue(obj, "Date", - * mprCreateCFunctionVar(dateConsProc, 0, MPR_VAR_SCRIPT_HANDLE)); - * mprCreatePropertyValue(obj, "Regexp", - * mprCreateCFunctionVar(regexpConsProc, 0, MPR_VAR_SCRIPT_HANDLE)); - */ - - /* - * Can we use on var x = "string text"; - */ - return 0; -} - -/******************************************************************************/ - -#else -void ejsProcsDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_EJS */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/esp/esp.c b/source4/lib/appweb/esp/esp.c deleted file mode 100644 index 3e47503edf..0000000000 --- a/source4/lib/appweb/esp/esp.c +++ /dev/null @@ -1,1042 +0,0 @@ -/* - * @file esp.c - * @brief Embedded Server Pages (ESP) core processing. - * @overview Embedded Server Pages provides an efficient way to generate - * dynamic pages using server-side Javascript. This code provides - * core processing, and should be called by an associated web - * server URL handler. - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "esp.h" - -#if BLD_FEATURE_ESP_MODULE - -/*********************************** Locals ***********************************/ -/* - * Master ESP control interface with the web server - */ - -static const Esp *esp; - -/***************************** Forward Declarations ***************************/ - -static int buildScript(EspRequest *ep, char **jsBuf, char *input, char - **errMsg); - -/************************************ Code ************************************/ -/* - * Called at server initialization - */ - -int espOpen(const Esp *control) -{ - mprAssert(control); - -#if BLD_FEATURE_MULTITHREAD - ejsOpen(control->lock, control->unlock, control->lockData); -#else - ejsOpen(0, 0, 0); -#endif - - /* - * Register the standard procedures - */ - espRegisterProcs(); - - /* - * Just for brain dead systems that don't zero global memory - */ - esp = control; - return 0; -} - -/******************************************************************************/ -/* - * Called at server termination - */ - -void espClose() -{ - ejsClose(); -} - -/******************************************************************************/ -/* - * Create for new ESP request. Assumed that this is called after all the - * HTTP headers have been read but before POST data has been read. It is - * expected that any session cookies have been read and that "variables" - * contains references to all the environment objects including "session". - * requestHandle is the web server request handle. - */ - -EspRequest *espCreateRequest(EspHandle webServerRequestHandle, char *uri, - MprVar *variables) -{ - EspRequest *ep; - MprVar *global; -#if BLD_FEATURE_LEGACY_API - MprVar *np; - char keyBuf[ESP_MAX_HEADER]; - int i; -#endif - - mprAssert(variables); - - ep = mprMalloc(sizeof(EspRequest)); - if (ep == 0) { - return 0; - } - memset(ep, 0, sizeof(EspRequest)); - ep->requestHandle = webServerRequestHandle; - ep->esp = esp; - ep->uri = mprStrdup(uri); - ep->docPath = 0; - ep->variables = variables; - - /* - * The handle passed to ejsOpenEngine is passed to every C function - * called by JavaScript. - */ - ep->eid = ejsOpenEngine((EjsHandle) ep, (EjsHandle) webServerRequestHandle); - if (ep->eid < 0) { - mprFree(ep); - return 0; - } - - /* - * All these copies and SetProperties will only copy references - * They will increments the object ref counts. - */ - mprCopyVar(&variables[ESP_GLOBAL_OBJ], ejsGetGlobalObject(ep->eid), - MPR_SHALLOW_COPY); - mprCopyVar(&variables[ESP_LOCAL_OBJ], ejsGetLocalObject(ep->eid), - MPR_SHALLOW_COPY); - - global = &variables[ESP_GLOBAL_OBJ]; - mprCreateProperty(global, "application", &variables[ESP_APPLICATION_OBJ]); - mprCreateProperty(global, "cookies", &variables[ESP_COOKIES_OBJ]); - mprCreateProperty(global, "files", &variables[ESP_FILES_OBJ]); - mprCreateProperty(global, "form", &variables[ESP_FORM_OBJ]); - mprCreateProperty(global, "headers", &variables[ESP_HEADERS_OBJ]); - mprCreateProperty(global, "request", &variables[ESP_REQUEST_OBJ]); - - /* - * FUTURE -- could server be shared across all requests for a given host - * and be made read-only. - */ - mprCreateProperty(global, "server", &variables[ESP_SERVER_OBJ]); - -#if BLD_FEATURE_SESSION - mprCreateProperty(global, "session", &variables[ESP_SESSION_OBJ]); -#endif - -#if BLD_FEATURE_LEGACY_API - /* - * DEPRECATED: 2.0 - * Define variables as globals. headers[] are prefixed with "HTTP_". - * NOTE: MaRequest::setVar does not copy into globals, whereas espSetVar - * does if legacy_api is defined. So variables pre-defined by MaRequest - * must be copied here into globals[]. - * - * NOTE: if a variable is in session[] and in form[], the form[] will - * override being later in the variables[] list. Use mprSetProperty - * instead of mprCreateProperty to cover for this case. - */ - for (i = 0; i < ESP_OBJ_MAX; i++) { - if (i == ESP_GLOBAL_OBJ || i == ESP_LOCAL_OBJ) { - continue; - } - if (variables[i].type != MPR_TYPE_OBJECT) { - continue; - } - np = mprGetFirstProperty(&variables[i], MPR_ENUM_DATA); - while (np) { - if (i == ESP_HEADERS_OBJ) { - mprSprintf(keyBuf, sizeof(keyBuf) - 1, "HTTP_%s", np->name); - mprSetProperty(global, keyBuf, np); - } else { - mprSetProperty(global, np->name, np); - } - np = mprGetNextProperty(&variables[i], np, MPR_ENUM_DATA); - } - } -#endif - return ep; -} - -/******************************************************************************/ - -void espDestroyRequest(EspRequest *ep) -{ - mprAssert(ep); - mprAssert(ep->eid >= 0); - - mprFree(ep->uri); - mprFree(ep->docPath); - ejsCloseEngine(ep->eid); - mprFree(ep); -} - -/******************************************************************************/ -/* - * The callback function will be called: - * - * (fn)(EjsId eid, EspRequest *ep, argc, argv); - * - * Callers can get their web server handle by calling: - * - * rq = (requiredCast) espGetHandle(ep); - */ - -void espDefineCFunction(EspRequest *ep, const char *functionName, EspCFunction fn, - void *thisPtr) -{ - mprAssert(functionName && *functionName); - mprAssert(fn); - - if (ep) { - ejsDefineCFunction(ep->eid, functionName, (MprCFunction) fn, - thisPtr, 0); - } else { - ejsDefineCFunction(-1, functionName, (MprCFunction) fn, thisPtr, 0); - } -} - -/******************************************************************************/ - -void espDefineStringCFunction(EspRequest *ep, const char *functionName, - EspStringCFunction fn, void *thisPtr) -{ - mprAssert(functionName && *functionName); - mprAssert(fn); - - if (ep) { - ejsDefineStringCFunction(ep->eid, functionName, (MprStringCFunction) fn, - thisPtr, 0); - } else { - ejsDefineStringCFunction(-1, functionName, (MprStringCFunction) fn, - thisPtr, 0); - } -} - -/******************************************************************************/ - -void *espGetRequestHandle(EspRequest *ep) -{ - return ep->requestHandle; -} - -/******************************************************************************/ - -EjsId espGetScriptHandle(EspRequest *ep) -{ - return ep->eid; -} - -/******************************************************************************/ - -char *espGetStringVar(EspRequest *ep, EspEnvType oType, char *var, - char *defaultValue) -{ - MprVar value; - - if (espGetVar(ep, oType, var, &value) < 0 || - value.type != MPR_TYPE_STRING) { - return defaultValue; - } - return value.string; -} - -/******************************************************************************/ - -int espGetVar(EspRequest *ep, EspEnvType oType, char *var, MprVar *value) -{ - MprVar *vp; - - mprAssert(ep); - mprAssert(var); - - vp = mprGetProperty(&ep->variables[oType], var, 0); - if (vp == 0) { - return -1; - } - *value = *vp; - return 0; -} - -/******************************************************************************/ -/* - * Process the ESP page. docBuf holds the page already. We expect that - * ep->variables holds all the pertinent environment variables. - */ - -int espProcessRequest(EspRequest *ep, const char *docPath, char *docBuf, - char **errMsg) -{ - char *jsBuf; - - mprAssert(ep); - - ep->docPath = mprStrdup(docPath); - - jsBuf = 0; - if (buildScript(ep, &jsBuf, docBuf, errMsg) < 0) { - return MPR_ERR_CANT_COMPLETE; - } - - if (jsBuf) { - mprLog(7, "esp: script is:\n%s\n", jsBuf); - - /* - * Now evaluate the entire escript - * MOB could cache the script - */ - if (ejsEvalScript(ep->eid, jsBuf, 0, errMsg) < 0) { - return MPR_ERR_ABORTED; - } - - mprFree(jsBuf); - } - return 0; -} - -/******************************************************************************/ - -void espRedirect(EspRequest *ep, int code, char *url) -{ - mprAssert(ep); - mprAssert(url); - - ep->esp->redirect(ep->requestHandle, code, url); -} - -/******************************************************************************/ - -void espError(EspRequest *ep, const char *fmt, ...) -{ - va_list args; - char *buf; - - mprAssert(ep); - mprAssert(fmt); - - va_start(args, fmt); - mprAllocVsprintf(&buf, MPR_MAX_HEAP_SIZE, fmt, args); - ejsSetErrorMsg(ep->eid, "%s", buf); - mprFree(buf); - va_end(args); -} - -/******************************************************************************/ - -void espSetHeader(EspRequest *ep, char *header, bool allowMultiple) -{ - mprAssert(ep); - - ep->esp->setHeader(ep->requestHandle, header, allowMultiple); -} - -/******************************************************************************/ -/* - * Caller does not need to destroy the var - */ - -MprVar *espGetResult(EspRequest *ep) -{ - mprAssert(ep); - - return ejsGetReturnValue(ep->eid); -} - -/******************************************************************************/ - -void espSetReturn(EspRequest *ep, MprVar value) -{ - mprAssert(ep); - - ejsSetReturnValue(ep->eid, value); -} - -/******************************************************************************/ - -void espSetReturnString(EspRequest *ep, const char *str) -{ - mprAssert(ep); - - ejsSetReturnValue(ep->eid, mprCreateStringVar(str, 0)); -} - -/******************************************************************************/ - -void espSetResponseCode(EspRequest *ep, int code) -{ - mprAssert(ep); - - ep->esp->setResponseCode(ep->requestHandle, code); -} - -/******************************************************************************/ - -void espSetVar(EspRequest *ep, EspEnvType oType, char *var, MprVar value) -{ - mprCreatePropertyValue(&ep->variables[oType], var, value); -} - -/******************************************************************************/ - -void espSetStringVar(EspRequest *ep, EspEnvType oType, - const char *var, const char *value) -{ - /* - * Will create or update if already existing - */ - mprCreatePropertyValue(&ep->variables[oType], var, - mprCreateStringVar(value, 0)); -} - -/******************************************************************************/ - -int espUnsetVar(EspRequest *ep, EspEnvType oType, char *var) -{ - return mprDeleteProperty(&ep->variables[oType], var); -} - -/******************************************************************************/ - -int espWrite(EspRequest *ep, char *buf, int size) -{ - mprAssert(ep); - mprAssert(buf); - mprAssert(size >= 0); - - return ep->esp->writeBlock(ep->requestHandle, buf, size); -} - -/******************************************************************************/ - -int espWriteString(EspRequest *ep, char *buf) -{ - mprAssert(ep); - mprAssert(buf); - - return ep->esp->writeBlock(ep->requestHandle, buf, strlen(buf)); -} - -/******************************************************************************/ - -int espWriteFmt(EspRequest *ep, char *fmt, ...) -{ - va_list args; - char *buf; - int rc, len; - - mprAssert(ep); - mprAssert(fmt); - - va_start(args, fmt); - len = mprAllocVsprintf(&buf, MPR_MAX_HEAP_SIZE, fmt, args); - rc = ep->esp->writeBlock(ep->requestHandle, buf, len); - mprFree(buf); - va_end(args); - return rc; -} - -/******************************************************************************/ -/******************************************************************************/ -/******************************************************************************/ -/* - * Get a javascript identifier. Must allow x.y['abc'] or x.y["abc"]. - * Must be careful about quoting and only allow quotes inside []. - */ - -static int getIdentifier(EspParse *parse) -{ - int atQuote, prevC, c; - - mprAssert(parse); - - atQuote = 0; - prevC = 0; - c = *parse->inp++; - - while (isalnum(c) || c == '_' || c == '.' || c == '[' || - c == ']' || c == '\'' || c == '\"') { - if (c == '\'' || c == '\"') { - if (c == atQuote) { - atQuote = 0; - } else if (prevC == '[') { - atQuote = c; - } else { - break; - } - } - if (parse->tokp >= parse->endp) { - parse->token = (char*) mprRealloc(parse->token, - parse->tokLen + ESP_TOK_INCR); - if (parse->token == 0) { - return MPR_ERR_CANT_ALLOCATE; - } - parse->token[parse->tokLen] = '\0'; - parse->tokLen += ESP_TOK_INCR; - parse->endp = &parse->token[parse->tokLen - 1]; - } - *parse->tokp++ = c; - prevC = c; - c = *parse->inp++; - } - - parse->inp--; - *parse->tokp = '\0'; - - return 0; -} - -/******************************************************************************/ -/* - * Get the next ESP input token. input points to the next input token. - * parse->token will hold the parsed token. The function returns the token id. - */ - -static int getEspToken(int state, EspParse *parse) -{ - char *cp; - int tid, done, c, quoted; - - tid = ESP_TOK_LITERAL; - parse->tokp = parse->token; - parse->tokp[0] = '\0'; - quoted = 0; - - c = *parse->inp++; - for (done = 0; !done; c = *parse->inp++) { - - /* - * Get room for more characters in the token buffer - */ - if (parse->tokp >= parse->endp) { - parse->token = (char*) mprRealloc(parse->token, - parse->tokLen + ESP_TOK_INCR); - if (parse->token == 0) { - return ESP_TOK_ERR; - } - parse->token[parse->tokLen] = '\0'; - parse->tokp = &parse->token[parse->tokLen - 1]; - parse->tokLen += ESP_TOK_INCR; - parse->endp = &parse->token[parse->tokLen - 1]; - } - - switch (c) { - case 0: - if (*parse->token) { - done++; - parse->inp--; - break; - } - return ESP_TOK_EOF; - - default: - if (c == '\"' && state != ESP_STATE_IN_ESP_TAG) { - *parse->tokp++ = '\\'; - } - *parse->tokp++ = c; - quoted = 0; - break; - - case '\\': - quoted = 1; - *parse->tokp++ = c; - break; - - case '@': - if (*parse->inp == '@' && state != ESP_STATE_IN_ESP_TAG) { - if (quoted) { - parse->tokp--; - quoted = 0; - } else { - if (*parse->token) { - parse->inp--; - } else { - parse->inp++; - tid = ESP_TOK_ATAT; - if (getIdentifier(parse) < 0) { - return ESP_TOK_ERR; - } - } - done++; - break; - } - } - *parse->tokp++ = c; - break; - - case '<': - if (*parse->inp == '%' && state != ESP_STATE_IN_ESP_TAG) { - if (quoted) { - parse->tokp--; - quoted = 0; - *parse->tokp++ = c; - break; - } - if (*parse->token) { - parse->inp--; - done++; - break; - } - parse->inp++; - while (isspace((int) *parse->inp)) { - parse->inp++; - } - if (*parse->inp == '=') { - parse->inp++; - while (isspace((int) *parse->inp)) { - parse->inp++; - } - tid = ESP_TOK_EQUALS; - if (getIdentifier(parse) < 0) { - return ESP_TOK_ERR; - } - done++; - break; - } - if (*parse->inp == 'i' && - strncmp(parse->inp, "include", 7) == 0 && - isspace((int) parse->inp[7])) { - tid = ESP_TOK_INCLUDE; - parse->inp += 7; - while (isspace((int) *parse->inp)) { - parse->inp++; - } - while (*parse->inp && !isspace((int) *parse->inp) && - *parse->inp != '%' && parse->tokp < parse->endp) { - *parse->tokp++ = *parse->inp++; - } - *parse->tokp = '\0'; - if (parse->token[0] == '"') { - parse->tokp = parse->token; - for (cp = &parse->token[1]; *cp; ) { - *parse->tokp++ = *cp++; - } - if (cp[-1] == '"') { - parse->tokp--; - } - *parse->tokp = '\0'; - } - - } else { - tid = ESP_TOK_START_ESP; - } - done++; - break; - } - *parse->tokp++ = c; - break; - - case '%': - if (*parse->inp == '>' && state == ESP_STATE_IN_ESP_TAG) { - if (quoted) { - parse->tokp--; - quoted = 0; - } else { - if (*parse->token) { - parse->inp--; - } else { - tid = ESP_TOK_END_ESP; - parse->inp++; - } - done++; - break; - } - } - *parse->tokp++ = c; - break; - } - } - - *parse->tokp = '\0'; - parse->inp--; - return tid; -} - -/******************************************************************************/ -/* - * Convert an ESP page into a JavaScript. We also expand include files. - */ - -static int buildScript(EspRequest *ep, char **jsBuf, char *input, char **errMsg) -{ - EspParse parse; - char path[MPR_MAX_FNAME], dir[MPR_MAX_FNAME], incPath[MPR_MAX_FNAME]; - char *incBuf, *incText; - int state, tid, len, rc, maxScriptSize, incSize; - - mprAssert(ep); - mprAssert(jsBuf); - mprAssert(input); - - rc = 0; - len = 0; - state = ESP_STATE_BEGIN; - if (errMsg) { - *errMsg = 0; - } - - memset(&parse, 0, sizeof(parse)); - parse.token = (char*) mprMalloc(ESP_TOK_INCR); - if (parse.token == 0) { - return MPR_ERR_CANT_ALLOCATE; - } - parse.token[0] = '\0'; - parse.tokLen = ESP_TOK_INCR; - parse.endp = &parse.token[parse.tokLen - 1]; - parse.tokp = parse.token; - parse.inBuf = input; - parse.inp = parse.inBuf; - - maxScriptSize = esp->maxScriptSize; - - tid = getEspToken(state, &parse); - while (tid != ESP_TOK_EOF && len >= 0) { - - switch (tid) { - default: - case ESP_TOK_ERR: - mprFree(parse.token); - return MPR_ERR_BAD_SYNTAX; - - case ESP_TOK_LITERAL: - len = mprReallocStrcat(jsBuf, maxScriptSize, len, 0, - "write(\"", parse.token, "\");\n", NULL); - break; - - case ESP_TOK_ATAT: - /* - * Trick to get undefined variables to evaluate to "". - * Catenate with "" to cause toString to run. - */ - len = mprReallocStrcat(jsBuf, maxScriptSize, len, 0, - "write(\"\" + ", parse.token, ");\n", NULL); - break; - - case ESP_TOK_EQUALS: - len = mprReallocStrcat(jsBuf, maxScriptSize, len, 0, - "write(\"\" + ", parse.token, ");\n", NULL); - state = ESP_STATE_IN_ESP_TAG; - break; - - case ESP_TOK_START_ESP: - state = ESP_STATE_IN_ESP_TAG; - tid = getEspToken(state, &parse); - while (tid != ESP_TOK_EOF && tid != ESP_TOK_EOF && - tid != ESP_TOK_END_ESP && len >= 0) { - len = mprReallocStrcat(jsBuf, maxScriptSize, len, 0, - parse.token, NULL); - tid = getEspToken(state, &parse); - } - state = ESP_STATE_BEGIN; - break; - - case ESP_TOK_END_ESP: - state = ESP_STATE_BEGIN; - break; - - case ESP_TOK_INCLUDE: - if (parse.token[0] == '/') { - mprStrcpy(incPath, sizeof(incPath), parse.token); - } else { - mprGetDirName(dir, sizeof(dir), ep->uri); - mprSprintf(incPath, sizeof(incPath), "%s/%s", - dir, parse.token); - } - if (esp->mapToStorage(ep->requestHandle, path, sizeof(path), - incPath, 0) < 0) { - mprAllocSprintf(errMsg, MPR_MAX_STRING, - "Can't find include file: %s", path); - rc = MPR_ERR_CANT_OPEN; - break; - } - if (esp->readFile(ep->requestHandle, &incText, &incSize, path) < 0){ - mprAllocSprintf(errMsg, MPR_MAX_STRING, - "Can't read include file: %s", path); - rc = MPR_ERR_CANT_READ; - break; - } - incText[incSize] = '\0'; - - /* - * Recurse and process the include script - */ - incBuf = 0; - if ((rc = buildScript(ep, &incBuf, incText, errMsg)) < 0) { - mprFree(incText); - mprFree(parse.token); - return rc; - } - - len = mprReallocStrcat(jsBuf, maxScriptSize, len, 0, incBuf, NULL); - mprFree(incText); - mprFree(incBuf); - state = ESP_STATE_IN_ESP_TAG; - break; - } - tid = getEspToken(state, &parse); - } - mprFree(parse.token); - if (len < 0) { - mprAllocSprintf(errMsg, MPR_MAX_STRING, - "Script token is too big in %s.\nConfigured maximum is %d.", - path, maxScriptSize); - return MPR_ERR_WONT_FIT; - } - return rc; -} - -/******************************************************************************/ -/******************************* Wrapped Routines *****************************/ -/******************************************************************************/ - -int espCopyVar(EspRequest *ep, char *var, MprVar *value, int copyDepth) -{ - return ejsCopyVar(ep->eid, var, value, copyDepth); -} - -/******************************************************************************/ - -MprVar espCreateObjVar(char *name, int hashSize) -{ - return ejsCreateObj(name, hashSize); -} - -/******************************************************************************/ - -MprVar espCreateArrayVar(char *name, int size) -{ - return ejsCreateArray(name, size); -} - -/******************************************************************************/ - -bool espDestroyVar(MprVar *obj) -{ - return ejsDestroyVar(obj); -} - -/******************************************************************************/ - -MprVar *espCreateProperty(MprVar *obj, char *property, MprVar *newValue) -{ - return mprCreateProperty(obj, property, newValue); -} - -/******************************************************************************/ - -MprVar *espCreatePropertyValue(MprVar *obj, char *property, MprVar newValue) -{ - return mprCreatePropertyValue(obj, property, newValue); -} - -/******************************************************************************/ - -void espDefineFunction(EspRequest *ep, const char *functionName, char *args, char *body) -{ - ejsDefineFunction(ep->eid, functionName, args, body); -} - -/******************************************************************************/ - -int espDeleteProperty(MprVar *obj, char *property) -{ - return mprDeleteProperty(obj, property); -} - -/******************************************************************************/ - -int espDeleteVar(EspRequest *ep, char *var) -{ - return ejsDeleteVar(ep->eid, var); -} - -/******************************************************************************/ -int espEvalFile(EspRequest *ep, char *path, MprVar *result, char **emsg) -{ - return ejsEvalFile(ep->eid, path, result, emsg); -} - -/******************************************************************************/ - -int espEvalScript(EspRequest *ep, char *script, MprVar *result, char **emsg) -{ - return ejsEvalScript(ep->eid, script, result, emsg); -} - -/******************************************************************************/ - -int espGetPropertyCount(MprVar *obj, int includeFlags) -{ - if (obj->type != MPR_TYPE_OBJECT) { - return MPR_ERR_BAD_STATE; - } - return mprGetPropertyCount(obj, includeFlags); -} - -/******************************************************************************/ - -MprVar *espGetFirstProperty(MprVar *obj, int includeFlags) -{ - return mprGetFirstProperty(obj, includeFlags); -} - -/******************************************************************************/ - -MprVar *espGetGlobalObject(EspRequest *ep) -{ - return ejsGetGlobalObject(ep->eid); -} - -/******************************************************************************/ - -MprVar *espGetLocalObject(EspRequest *ep) -{ - return ejsGetLocalObject(ep->eid); -} - -/******************************************************************************/ - -MprVar *espGetNextProperty(MprVar *obj, MprVar *currentProperty, - int includeFlags) -{ - return mprGetNextProperty(obj, currentProperty, includeFlags); -} - -/******************************************************************************/ - -MprVar *espGetProperty(MprVar *obj, char *property, MprVar *value) -{ - return mprGetProperty(obj, property, value); -} - -/******************************************************************************/ - -void *espGetThisPtr(EspRequest *ep) -{ - return ejsGetThisPtr(ep->eid); -} - -/******************************************************************************/ -#if XX_UNUSED_XX - -int espReadProperty(MprVar *dest, MprVar *prop) -{ - mprAssert(prop); - mprAssert(dest); - - *dest = *prop; - return 0; -} - -#endif -/******************************************************************************/ - -int espReadVar(EspRequest *ep, char *var, MprVar *value) -{ - return ejsReadVar(ep->eid, var, value); -} - -/******************************************************************************/ - -int espRunFunction(EspRequest *ep, MprVar *obj, char *functionName, - MprArray *args) -{ - return ejsRunFunction(ep->eid, obj, functionName, args); -} - -/******************************************************************************/ - -MprVar *espSetProperty(MprVar *obj, char *property, MprVar *newValue) -{ - return mprSetProperty(obj, property, newValue); -} - -/******************************************************************************/ - -MprVar *espSetPropertyValue(MprVar *obj, char *property, MprVar newValue) -{ - return mprSetPropertyValue(obj, property, newValue); -} - -/******************************************************************************/ - -int espWriteVar(EspRequest *ep, char *var, MprVar *value) -{ - return ejsWriteVar(ep->eid, var, value); -} - -/******************************************************************************/ - -int espWriteVarValue(EspRequest *ep, char *var, MprVar value) -{ - return ejsWriteVarValue(ep->eid, var, value); -} - -/******************************************************************************/ -#if XX_UNUSED_XX - -int espWriteProperty(MprVar *prop, MprVar *newValue) -{ - return mprWriteProperty(prop, newValue); -} - -/******************************************************************************/ - -int espWritePropertyValue(MprVar *prop, MprVar newValue) -{ - return mprWritePropertyValue(prop, newValue); -} - -#endif -/******************************************************************************/ - -#else /* !BLD_FEATURE_ESP_MODULE */ -void espDummy() {} - -/******************************************************************************/ -#endif /* BLD_FEATURE_ESP_MODULE */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/esp/esp.h b/source4/lib/appweb/esp/esp.h deleted file mode 100644 index 3d9b7bf8dc..0000000000 --- a/source4/lib/appweb/esp/esp.h +++ /dev/null @@ -1,277 +0,0 @@ -/** - * @file esp.h - * @brief Header for Embedded Server Pages (ESP) - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#ifndef _h_ESP_h -#define _h_ESP_h 1 - -#include "lib/appweb/ejs/ejs.h" -#include "lib/appweb/esp/espEnv.h" -#include "lib/appweb/mpr/var.h" -#include "lib/appweb/mpr/miniMpr.h" - -/*********************************** Defines **********************************/ - -#if BLD_FEATURE_SQUEEZE -#define ESP_TOK_INCR 1024 -#define ESP_MAX_HEADER 1024 -#else -#define ESP_TOK_INCR 4096 -#define ESP_MAX_HEADER 4096 -#endif - -/* - * ESP lexical analyser tokens - */ -#define ESP_TOK_ERR -1 /* Any input error */ -#define ESP_TOK_EOF 0 /* End of file */ -#define ESP_TOK_START_ESP 1 /* <% */ -#define ESP_TOK_END_ESP 2 /* %> */ -#define ESP_TOK_ATAT 3 /* @@var */ -#define ESP_TOK_LITERAL 4 /* literal HTML */ -#define ESP_TOK_INCLUDE 5 /* include file.esp */ -#define ESP_TOK_EQUALS 6 /* = var */ - -/* - * ESP parser states - */ -#define ESP_STATE_BEGIN 1 /* Starting state */ -#define ESP_STATE_IN_ESP_TAG 2 /* Inside a <% %> group */ - -/*********************************** Types ************************************/ - -typedef void* EspHandle; /* Opaque Web server handle type */ - -/* - * Per request control block - */ -typedef struct EspRequest { - MprStr docPath; /* Physical path for ESP page */ - EjsId eid; /* EJS instance handle */ - const struct Esp *esp; /* Pointer to ESP control block */ - EspHandle requestHandle; /* Per request web server handle */ - MprStr uri; /* Request URI */ - MprVar *variables; /* Pointer to variables */ -} EspRequest; - -/* - * Master ESP control block. This defines the function callbacks for a - * web server handler to implement. ESP will call these functions as - * required. - */ -typedef struct Esp { - int maxScriptSize; - void (*createSession)(EspHandle handle, int timeout); - void (*destroySession)(EspHandle handle); - const char *(*getSessionId)(EspHandle handle); - int (*mapToStorage)(EspHandle handle, char *path, int len, const char *uri, - int flags); - int (*readFile)(EspHandle handle, char **buf, int *len, const char *path); - void (*redirect)(EspHandle handle, int code, char *url); - void (*setCookie)(EspHandle handle, const char *name, const char *value, - int lifetime, const char *path, bool secure); - void (*setHeader)(EspHandle handle, const char *value, bool allowMultiple); - void (*setResponseCode)(EspHandle handle, int code); - int (*writeBlock)(EspHandle handle, const char *buf, int size); - int (*writeFmt)(EspHandle handle, char *fmt, ...); -#if BLD_FEATURE_MULTITHREAD - void (*lock)(void *lockData); - void (*unlock)(void *lockData); - void *lockData; -#endif -} Esp; - - -/* - * ESP parse context - */ -typedef struct { - char *inBuf; /* Input data to parse */ - char *inp; /* Next character for input */ - char *endp; /* End of storage (allow for null) */ - char *tokp; /* Pointer to current parsed token */ - char *token; /* Storage buffer for token */ - int tokLen; /* Length of buffer */ -} EspParse; - - -/******************************** Private APIs ********************************/ - -extern void espRegisterProcs(void); - -/******************************** Published API *******************************/ -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Function callback signatures - */ -typedef int (*EspCFunction)(EspRequest *ep, int argc, - struct MprVar **argv); -typedef int (*EspStringCFunction)(EspRequest *ep, int argc, - char **argv); - -/* - * APIs for those hosting the ESP module - */ -extern int espOpen(const Esp *control); -extern void espClose(void); -extern EspRequest *espCreateRequest(EspHandle webServerRequestHandle, - char *uri, MprVar *envObj); -extern void espDestroyRequest(EspRequest *ep); -extern int espProcessRequest(EspRequest *ep, const char *docPath, - char *docBuf, char **errMsg); - -/* - * Method invocation - */ -extern void espDefineCFunction(EspRequest *ep, const char *functionName, - EspCFunction fn, void *thisPtr); -extern void espDefineFunction(EspRequest *ep, const char *functionName, - char *args, char *body); -extern void espDefineStringCFunction(EspRequest *ep, - const char *functionName, EspStringCFunction fn, - void *thisPtr); -extern int espRunFunction(EspRequest *ep, MprVar *obj, - char *functionName, MprArray *args); -extern void espSetResponseCode(EspRequest *ep, int code); -extern void espSetReturn(EspRequest *ep, MprVar value); -extern void *espGetThisPtr(EspRequest *ep); - -/* - * Utility routines to use in C methods - */ -extern void espError(EspRequest *ep, const char *fmt, ...) PRINTF_ATTRIBUTE(2,3); -extern int espEvalFile(EspRequest *ep, char *path, MprVar *result, - char **emsg); -extern int espEvalScript(EspRequest *ep, char *script, MprVar *result, - char **emsg); -extern MprVar *espGetLocalObject(EspRequest *ep); -extern MprVar *espGetGlobalObject(EspRequest *ep); -extern EspHandle espGetRequestHandle(EspRequest *ep); -extern MprVar *espGetResult(EspRequest *ep); -extern EjsId espGetScriptHandle(EspRequest *ep); -extern void espRedirect(EspRequest *ep, int code, char *url); -extern void espSetHeader(EspRequest *ep, char *header, - bool allowMultiple); -extern void espSetReturnString(EspRequest *ep, const char *str); -extern int espWrite(EspRequest *ep, char *buf, int size); -extern int espWriteString(EspRequest *ep, char *buf); -extern int espWriteFmt(EspRequest *ep, char *fmt, ...) PRINTF_ATTRIBUTE(2,3); - -/* - * ESP array[] variable access (set will update/create) - */ -extern int espGetVar(EspRequest *ep, EspEnvType oType, char *var, - MprVar *value); -extern char *espGetStringVar(EspRequest *ep, EspEnvType oType, - char *var, char *defaultValue); -extern void espSetVar(EspRequest *ep, EspEnvType oType, char *var, - MprVar value); -extern void espSetStringVar(EspRequest *ep, EspEnvType oType, - const char *var, const char *value); -extern int espUnsetVar(EspRequest *ep, EspEnvType oType, char *var); - -/* - * Object creation and management - */ -extern MprVar espCreateObjVar(char *name, int hashSize); -extern MprVar espCreateArrayVar(char *name, int size); -extern bool espDestroyVar(MprVar *var); -extern MprVar *espCreateProperty(MprVar *obj, char *property, - MprVar *newValue); -extern MprVar *espCreatePropertyValue(MprVar *obj, char *property, - MprVar newValue); -extern int espDeleteProperty(MprVar *obj, char *property); - -/* - * JavaScript variable management. Set will create/update a property. - * All return a property reference. GetProperty will optionally return the - * property in value. - */ -extern MprVar *espGetProperty(MprVar *obj, char *property, - MprVar *value); -extern MprVar *espSetProperty(MprVar *obj, char *property, - MprVar *newValue); -extern MprVar *espSetPropertyValue(MprVar *obj, char *property, - MprVar newValue); - -#if 0 -/* - * Low-level direct read and write of properties. - * FUTURE: -- Read is not (dest, src). MUST WARN IN DOC ABOUT COPY/READ - * Will still cause triggers to run. - */ -extern int espReadProperty(MprVar *dest, MprVar *prop); -extern int espWriteProperty(MprVar *prop, MprVar *newValue); -extern int espWritePropertyValue(MprVar *prop, MprVar newValue); -#endif - - -/* - * Access JavaScript variables by their full name. Can use "." or "[]". For - * example: "global.request['REQUEST_URI']" - * For Read/write, the variables must exist. - */ -extern int espCopyVar(EspRequest *ep, char *var, MprVar *value, - int copyDepth); -extern int espDeleteVar(EspRequest *ep, char *var); -extern int espReadVar(EspRequest *ep, char *var, MprVar *value); -extern int espWriteVar(EspRequest *ep, char *var, MprVar *value); -extern int espWriteVarValue(EspRequest *ep, char *var, MprVar value); - -/* - * Object property enumeration - */ -extern MprVar *espGetFirstProperty(MprVar *obj, int includeFlags); -extern MprVar *espGetNextProperty(MprVar *obj, MprVar *currentProperty, - int includeFlags); -extern int espGetPropertyCount(MprVar *obj, int includeFlags); - -#ifdef __cplusplus -} -#endif -/******************************************************************************/ -#endif /* _h_ESP_h */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/esp/espEnv.h b/source4/lib/appweb/esp/espEnv.h deleted file mode 100644 index a3c9d9f5c7..0000000000 --- a/source4/lib/appweb/esp/espEnv.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - * @file espEnv.h - * @brief ESP Environment Variables - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/******************************************************************************/ - -#ifndef _h_ESP_ENV_h -#define _h_ESP_ENV_h 1 - -/* - * @brief Scripting environment variable array types - */ -typedef enum EspEnvType { - ESP_UNDEFINED_OBJ = -1, - - /** - * Elements for server[]: - * DOCUMENT_ROOT GATEWAY_INTERFACE SERVER_ADDR SERVER_PORT SERVER_NAME - * SERVER_PROTOCOL SERVER_SOFTWARE SERVER_URL UPLOAD_DIR - * FUTURE: SERVER_ADMIN - * FUTURE: this could be shared across all hosts and be made read-only. - */ - ESP_SERVER_OBJ = 0, /*! server[] data */ - - /** - * Elements for session[]: are user defined - */ - ESP_SESSION_OBJ = 1, /*! session[] data */ - - /** - * Elements for request[]: - * AUTH_TYPE CONTENT_LENGTH CONTENT_TYPE QUERY_STRING PATH_INFO - * PATH_TRANSLATED REMOTE_ADDR REMOTE_HOST REMOTE_USER REQUEST_METHOD - * REQUEST_URI SCRIPT_FILENAME SCRIPT_NAME - * FUTURE: FILEPATH_INFO REDIRECT_URL SELF REMOTE_PORT AUTH_USER - * AUTH_GROUP AUTH_ACL - */ - ESP_REQUEST_OBJ = 2, /*! request[] data */ - - /** - * Elements for headers[]: - * HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_CONNECTION HTTP_HOST - * HTTP_REFERER HTTP_USER_AGENT and any other custom headers - */ - ESP_HEADERS_OBJ = 3, /*! header [] data */ - - /** - * Elements for cookies[]: are defined by the HTTP request - */ - ESP_COOKIES_OBJ = 4, /*! cookies[] data */ - - /** - * Elements for files[]: are defined by the HTTP request - * CLIENT_FILENAME CONTENT_TYPE FILENAME SIZE - */ - ESP_FILES_OBJ = 5, /*! files[] data */ - - /** - * Elements for form[]: are defined by the HTTP request - */ - ESP_FORM_OBJ = 6, /*! form[] data */ - - /** - * Elements for application[]: are user defined - */ - ESP_APPLICATION_OBJ = 7, /*! application[] data */ - - /** - * Elements for global[]: are defined by ESP/EJS - */ - ESP_GLOBAL_OBJ = 8, /*! global [] data */ - - /* - * Elements for local[]: are defined by ESP/EJS - */ - ESP_LOCAL_OBJ = 9, /*! local [] data */ -} EspEnvType; - -#define ESP_OBJ_MAX 10 /* Total objects */ - -#if BLD_SQUEEZE -#define ESP_HASH_SIZE 19 /* Size of hash tables */ -#else -#define ESP_HASH_SIZE 37 -#endif - -/******************************************************************************/ -#endif /* _h_ESP_ENV_h */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/esp/espProcs.c b/source4/lib/appweb/esp/espProcs.c deleted file mode 100644 index 7b5dfe680e..0000000000 --- a/source4/lib/appweb/esp/espProcs.c +++ /dev/null @@ -1,249 +0,0 @@ -/* - * @file espProcs.c - * @brief Embedded Server Pages (ESP) Procedures. - * @overview These ESP procedures can be used in ESP pages for common tasks. - */ -/********************************* Copyright **********************************/ -/* - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -/********************************** Includes **********************************/ - -#include "esp.h" - -/************************************ Code ************************************/ -#if BLD_FEATURE_ESP_MODULE -#if BLD_FEATURE_SESSION -/* - * destroySession - */ - -static int destroySessionProc(EspRequest *ep, int argc, char **argv) -{ - ep->esp->destroySession(ep->requestHandle); - return 0; -} - -#endif /* BLD_FEATURE_SESSION */ - -/******************************************************************************/ -/* - * include - * - * This includes javascript libraries. For example: - * - * <% include("file", ...); %> - * - * Don't confuse with ESP includes: - * - * <% include file.esp %> - * - * Filenames are relative to the base document including the file. - * FUTURE -- move back to EJS. Only here now because we need ep->readFile. - */ - -static int includeProc(EspRequest *ep, int argc, char **argv) -{ - const Esp *esp; - char path[MPR_MAX_FNAME], dir[MPR_MAX_FNAME]; - char *emsg=NULL, *buf; - int size, i; - - esp = ep->esp; - mprAssert(argv); - for (i = 0; i < argc; i++) { - const char *extension; - - if (argv[i][0] != '/') { - mprGetDirName(dir, sizeof(dir), ep->docPath); - mprSprintf(path, sizeof(path), "%s/%s", dir, argv[i]); - } else { - mprSprintf(path, sizeof(path), "%s", argv[i]); - } - - if (esp->readFile(ep->requestHandle, &buf, &size, path) < 0) { - espError(ep, "Can't read include file: %s", path); - return MPR_ERR_CANT_ACCESS; - } - buf[size] = '\0'; - - extension = strrchr(argv[i], '.'); - - /* - * Allow nested inclusion of ESP requests - */ - if (extension && mprStrCmpAnyCase(extension, ".esp") == 0) { - if (espProcessRequest(ep, path, buf, &emsg) != 0) { - espError(ep, "Cant evaluate script - %s", emsg?emsg:""); - mprFree(buf); - return -1; - } - } else { - if (ejsEvalScript(espGetScriptHandle(ep), buf, 0, &emsg) < 0) { - espError(ep, "Cant evaluate script - %s", emsg?emsg:""); - mprFree(buf); - return -1; - } - } - mprFree(buf); - } - return 0; -} - -/******************************************************************************/ -/* - * redirect - * - * This implemements <% redirect(url, code); %> command. The redirection - * code is optional. - */ - -static int redirectProc(EspRequest *ep, int argc, char **argv) -{ - char *url; - int code; - - if (argc < 1) { - espError(ep, "Bad args"); - return MPR_ERR_BAD_ARGS; - } - url = argv[0]; - if (argc == 2) { - code = atoi(argv[1]); - } else { - code = 302; - } - espRedirect(ep, code, url); - return 0; -} - -/******************************************************************************/ -#if BLD_FEATURE_SESSION -/* - * useSession - */ - -static int useSessionProc(EspRequest *ep, int argc, char **argv) -{ - int timeout; - - if (argc > 1) { - espError(ep, "Bad args"); - return MPR_ERR_BAD_ARGS; - - } else if (argc == 1) { - timeout = atoi(argv[0]); - } else { - timeout = 0; - } - - ep->esp->createSession(ep->requestHandle, timeout); - espSetReturnString(ep, ep->esp->getSessionId(ep->requestHandle)); - return 0; -} - -#endif /* BLD_FEATURE_SESSION */ -/******************************************************************************/ -/* - * setHeader - * - * This implemements <% setHeader("key: value", allowMultiple); %> command. - */ - -static int setHeaderProc(EspRequest *ep, int argc, char **argv) -{ - mprAssert(argv); - if (argc != 2) { - espError(ep, "Bad args"); - return MPR_ERR_BAD_ARGS; - } - ep->esp->setHeader(ep->requestHandle, argv[0], atoi(argv[1])); - return 0; -} - -/******************************************************************************/ -/* - * write - * - * This implemements <% write("text"); %> command. - */ - -static int writeProc(EspRequest *ep, int argc, char **argv) -{ - char *s; - int i, len; - - mprAssert(argv); - for (i = 0; i < argc; i++) { - s = argv[i]; - len = strlen(s); - if (len > 0) { - if (espWrite(ep, s, len) != len) { - espError(ep, "Can't write to client"); - return -1; - } - } - } - return 0; -} - -/******************************************************************************/ - -void espRegisterProcs() -{ - espDefineStringCFunction(0, "write", writeProc, 0); - espDefineStringCFunction(0, "setHeader", setHeaderProc, 0); - espDefineStringCFunction(0, "redirect", redirectProc, 0); - espDefineStringCFunction(0, "include", includeProc, 0); - -#if BLD_FEATURE_SESSION - /* - * Create and use are synonomous - */ - espDefineStringCFunction(0, "useSession", useSessionProc, 0); - espDefineStringCFunction(0, "createSession", useSessionProc, 0); - espDefineStringCFunction(0, "destroySession", destroySessionProc, 0); -#endif -} - -/******************************************************************************/ - -#else -void mprEspControlsDummy() {} - -#endif /* BLD_FEATURE_ESP_MODULE */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/mpr/miniMpr.c b/source4/lib/appweb/mpr/miniMpr.c deleted file mode 100644 index 381815eb23..0000000000 --- a/source4/lib/appweb/mpr/miniMpr.c +++ /dev/null @@ -1,522 +0,0 @@ -/* - * @file miniMpr.cpp - * @brief Mini Mbedthis Portable Runtime (MPR) - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -#include "miniMpr.h" -#include "param/param.h" -#include "lib/events/events.h" - -/************************************ Code ************************************/ -#if !BLD_APPWEB -#if !BLD_GOAHEAD_WEBSERVER - -static void *mpr_ctx; - -/* set the memory context to be used for all ejs variables */ -void mprSetCtx(TALLOC_CTX *ctx) -{ - mpr_ctx = ctx; -} - -/* return the memory context being used for all ejs variables */ -void *mprMemCtx(void) -{ - return mpr_ctx; -} - -struct event_context *mprEventCtx(void) -{ - return event_context_find(mprMemCtx()); -} - -/* return the loadparm context being used for all ejs variables */ -struct loadparm_context *mprLpCtx(void) -{ - return global_loadparm; -} - -void mprFree(void *ptr) -{ - talloc_free(ptr); -} - -void *mprMalloc(uint size) -{ - return talloc_size(mpr_ctx, size); -} - -/******************************************************************************/ - -void *mprRealloc(void *ptr, uint size) -{ - return talloc_realloc_size(mpr_ctx, ptr, size); -} - -/******************************************************************************/ - -char *mprStrdup(const char *str) -{ - if (str == 0) { - str = ""; - } - return talloc_strdup(mpr_ctx, str); -} - -/*****************************************************************************/ - -int mprAllocSprintf(char **msgbuf, int maxSize, const char *fmt, ...) -{ - va_list args; - char *buf; - int count; - - va_start(args, fmt); - buf = mprMalloc(maxSize + 1); - count = mtVsprintf(buf, maxSize, fmt, args); - *msgbuf = buf; - va_end(args); - return count; -} - -/*****************************************************************************/ - -int mprAllocVsprintf(char **msgbuf, int maxSize, const char *fmt, va_list args) -{ - char *buf; - int count; - - buf = mprMalloc(maxSize + 1); - count = mtVsprintf(buf, maxSize, fmt, args); - *msgbuf = buf; - return count; -} - - -/*****************************************************************************/ -/* - * Format a number as a string. FUTURE -- reverse args to be standard. - * ie. mprItoa(char *userBuf, int bufsize, int value); - */ - -char *mprItoa(int value, char *buf, int width) -{ - char numBuf[16]; - char *cp, *dp, *endp; - int negative; - - cp = &numBuf[sizeof(numBuf)]; - *--cp = '\0'; - - if (value < 0) { - negative = 1; - value = -value; - width--; - } else { - negative = 0; - } - - do { - *--cp = '0' + (value % 10); - value /= 10; - } while (value > 0); - - if (negative) { - *--cp = '-'; - } - - dp = buf; - endp = &buf[width]; - while (dp < endp && *cp) { - *dp++ = *cp++; - } - *dp++ = '\0'; - return buf; -} - -/*****************************************************************************/ - -void mprLog(int level, const char *fmt, ...) -{ - va_list args; - char *buf; - - if (DEBUGLVL(level)) { - va_start(args, fmt); - mprAllocVsprintf(&buf, MPR_MAX_STRING, fmt, args); - va_end(args); - DEBUG(level, ("mprLog: %s", buf)); - mprFree(buf); - } -} - -/*****************************************************************************/ - -void mprBreakpoint(const char *file, int line, const char *cond) -{ - char *buf; - mprAllocSprintf(&buf, MPR_MAX_STRING, "esp exception - ASSERT at %s:%d, %s\n", - file, line, cond); - ejs_exception(buf); -} - -#endif /* !BLD_GOAHEAD_WEBSERVER */ -/*****************************************************************************/ -/* - * Create a general growable array structure - */ - -MprArray *mprCreateArray() -{ - MprArray *array; - int size; - - array = (MprArray*) mprMalloc(sizeof(MprArray)); - if (array == 0) { - return 0; - } - memset(array, 0, sizeof(MprArray)); - - size = MPR_ARRAY_INCR * sizeof(void*); - array->handles = (void**) mprMalloc(size); - if (array->handles == 0) { - mprFree(array); - return 0; - } - memset(array->handles, 0, size); - array->max = MPR_ARRAY_INCR; - array->used = 0; - return array; -} - -/*****************************************************************************/ -/* - * Dispose of the array. Callers responsibility to dispose of handle entries. - */ - -void mprDestroyArray(MprArray *array) -{ - mprAssert(array); - mprAssert(array->max >= 0); - mprAssert(array->used >= 0); - - mprFree(array->handles); - mprFree(array); -} - -/*****************************************************************************/ -/* - * Add an item to the array - */ - -int mprAddToArray(MprArray *array, void *item) -{ - int memsize, idx, len; - - mprAssert(array); - mprAssert(array->max >= 0); - mprAssert(array->used >= 0); - - if (array->used < array->max) { - idx = array->used++; - mprAssert(idx >= 0 && idx < array->max); - mprAssert(array->handles[idx] == 0); - array->handles[idx] = item; - return idx; - } - - for (idx = array->used; idx < array->max; idx++) { - if (array->handles[idx] == 0) { - array->used++; - mprAssert(array->handles[idx] == 0); - array->handles[idx] = item; - return idx; - } - } - - len = array->max + MPR_ARRAY_INCR; - memsize = len * sizeof(void*); - array->handles = (void**) mprRealloc((void*) array->handles, memsize); - if (array->handles == NULL) { - return -1; - } - memset(&array->handles[array->max], 0, sizeof(void*) * MPR_ARRAY_INCR); - array->max = len; - array->used++; - - mprAssert(idx >= 0 && idx < array->max); - mprAssert(array->handles[idx] == 0); - - array->handles[idx] = item; - return idx; -} - -/*****************************************************************************/ -/* - * Remove from the array - */ - -int mprRemoveFromArray(MprArray *array, int idx) -{ - mprAssert(array); - mprAssert(array->max > 0); - mprAssert(idx >= 0 && idx < array->max); - mprAssert(array->handles[idx] != 0); - mprAssert(array->used > 0); - - array->handles[idx] = 0; - return --array->used; -} - -/*****************************************************************************/ -/* - * Thread-safe wrapping of strtok. Note "str" is modifed as per strtok() - */ - -char *mprStrTok(char *str, const char *delim, char **tok) -{ - char *start, *end; - int i; - - start = str ? str : *tok; - - if (start == 0) { - return 0; - } - - i = strspn(start, delim); - start += i; - if (*start == '\0') { - *tok = 0; - return 0; - } - end = strpbrk(start, delim); - if (end) { - *end++ = '\0'; - i = strspn(end, delim); - end += i; - } - *tok = end; - return start; -} - -/*****************************************************************************/ - -static int mprCoreStrcat(int alloc, char **destp, int destMax, int existingLen, - const char *delim, const char *src, va_list args) -{ - va_list ap; - char *dest, *dp; - const char *str; - int sepLen, addBytes, required; - - mprAssert(destp); - mprAssert(destMax > 0); - mprAssert(src); - - dest = *destp; - sepLen = (delim) ? strlen(delim) : 0; - - va_copy(ap, args); - addBytes = 0; - str = src; - while (str) { - addBytes += strlen(str) + sepLen; - str = va_arg(ap, const char*); - } - va_end(ap); - - if (existingLen > 0) { - addBytes += sepLen; - } - required = existingLen + addBytes + 1; - if (required >= destMax) { - mprAssert(0); - return MPR_ERR_WONT_FIT; - } - - if (alloc) { - if (dest == 0) { - dest = (char*) mprMalloc(required); - } else { - dest = (char*) mprRealloc(dest, required); - } - } else { - dest = (char*) *destp; - } - - dp = &dest[existingLen]; - if (delim) { - strcpy(dp, delim); - dp += sepLen; - } - - if (addBytes > 0) { - va_copy(ap, args); - str = src; - while (str) { - strcpy(dp, str); - dp += strlen(str); - str = va_arg(ap, char*); - if (delim && str) { - strcpy(dp, delim); - dp += sepLen; - } - } - va_end(ap); - } else if (dest == 0) { - dest = (char*) mprMalloc(1); - } - *dp = '\0'; - - *destp = dest; - mprAssert(dp < &dest[required]); - return required - 1; -} - -/***************************************************************************** - Note that this VARARGS function must be NULL (not 0, this must be a - pointer) terminated -*/ - -int mprReallocStrcat(char **destp, int destMax, int existingLen, - const char *delim, const char *src,...) -{ - va_list ap; - int rc; - - va_start(ap, src); - rc = mprCoreStrcat(1, destp, destMax, existingLen, delim, src, ap); - va_end(ap); - return rc; -} - -/*****************************************************************************/ -/* - * Return the directory portion of a pathname into the users buffer. - */ - -int mprGetDirName(char *buf, int bufsize, char *path) -{ - char *cp; - int dlen; - - mprAssert(path); - mprAssert(buf); - mprAssert(bufsize > 0); - - cp = strrchr(path, '/'); - if (cp == 0) { -#if WIN - cp = strrchr(path, '\\'); - if (cp == 0) -#endif - { - buf[0] = '\0'; - return 0; - } - } - - if (cp == path && cp[1] == '\0') { - strcpy(buf, "."); - return 0; - } - - dlen = cp - path; - if (dlen < bufsize) { - if (dlen == 0) { - dlen++; - } - mprMemcpy(buf, bufsize, path, dlen); - buf[dlen] = '\0'; - return 0; - } - return MPR_ERR_WONT_FIT; -} - -/*****************************************************************************/ - -int mprStrcpy(char *dest, int destMax, const char *src) -{ - int len; - - mprAssert(dest); - mprAssert(destMax > 0); - mprAssert(src); - - len = strlen(src); - if (len >= destMax && len > 0) { - mprAssert(0); - return MPR_ERR_WONT_FIT; - } - if (len > 0) { - memcpy(dest, src, len); - dest[len] = '\0'; - } else { - *dest = '\0'; - len = 0; - } - return len; -} - -/*****************************************************************************/ - -int mprMemcpy(char *dest, int destMax, const char *src, int nbytes) -{ - mprAssert(dest); - mprAssert(destMax > nbytes); - mprAssert(src); - mprAssert(nbytes > 0); - - if (nbytes > destMax) { - mprAssert(0); - return MPR_ERR_WONT_FIT; - } - if (nbytes > 0) { - memcpy(dest, src, nbytes); - return nbytes; - } else { - return 0; - } -} - -/*****************************************************************************/ -#else -void miniMprDummy() {} -#endif // !BLD_APPWEB && !BLD_GOAHEAD_WEBSERVER - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/mpr/miniMpr.h b/source4/lib/appweb/mpr/miniMpr.h deleted file mode 100644 index 2b8ff0af6a..0000000000 --- a/source4/lib/appweb/mpr/miniMpr.h +++ /dev/null @@ -1,301 +0,0 @@ -/* - * @file miniMpr.h - * @brief Mini Mbedthis Portable Runtime (MPR) Environment. - * @copy default - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ -#ifndef _h_MINI_MPR -#define _h_MINI_MPR 1 - -/********************************** Includes **********************************/ -/* - * Find out about our configuration - */ -#ifndef _INCLUDES_H - #include "includes.h" -#endif - -/* allow this library to use strcpy() */ -#undef strcpy - #include "lib/appweb/ejs/config.h" - -#if BLD_APPWEB - /* - * If building within AppWeb, use the full MPR - */ - #include "mpr.h" -#else - - #include - #include - #include - #include - #include - #include - #include - -#if !WIN - #include -#endif - -#if CE - #include - #include "CE/wincompat.h" -#endif - -#if LYNX - #include -#endif - -#if QNX4 - #include -#endif -#ifdef HAVE_MATH_H - #include -#endif -/********************************** Defines ***********************************/ - -#ifdef __cplusplus -extern "C" { -#endif - -#if BLD_FEATURE_SQUEEZE -/* - * Reasonable length of a file path name to use in most cases where you know - * the expected file name and it is certain to be less than this limit. - */ -#define MPR_MAX_FNAME 128 -#define MPR_MAX_STRING 512 -#define MPR_DEFAULT_HASH_SIZE 23 /* Default size of hash table index */ -#define MPR_MAX_HEAP_SIZE (32 * 1024) -#else -#define MPR_MAX_FNAME 256 -#define MPR_MAX_STRING 4096 -#define MPR_DEFAULT_HASH_SIZE 43 /* Default size of hash table index */ -#define MPR_MAX_HEAP_SIZE (64 * 1024) -#endif - -/* - * Useful for debugging - */ -#define MPR_L __FILE__, __LINE__ - -#if BLD_FEATURE_ASSERT -#define mprAssert(C) \ - if (C) ; else mprBreakpoint(__FILE__, __LINE__, #C) -#else - #define mprAssert(C) if (1) ; else -#endif - -/* - * Standard MPR return and error codes - */ -#define MPR_ERR_BASE (-200) /* Error code */ -#define MPR_ERR_GENERAL (MPR_ERR_BASE - 1) /* Error code */ -#define MPR_ERR_ABORTED (MPR_ERR_BASE - 2) /* Error code */ -#define MPR_ERR_ALREADY_EXISTS (MPR_ERR_BASE - 3) /* Error code */ -#define MPR_ERR_BAD_ARGS (MPR_ERR_BASE - 4) /* Error code */ -#define MPR_ERR_BAD_FORMAT (MPR_ERR_BASE - 5) /* Error code */ -#define MPR_ERR_BAD_HANDLE (MPR_ERR_BASE - 6) /* Error code */ -#define MPR_ERR_BAD_STATE (MPR_ERR_BASE - 7) /* Error code */ -#define MPR_ERR_BAD_SYNTAX (MPR_ERR_BASE - 8) /* Error code */ -#define MPR_ERR_BAD_TYPE (MPR_ERR_BASE - 9) /* Error code */ -#define MPR_ERR_BAD_VALUE (MPR_ERR_BASE - 10) /* Error code */ -#define MPR_ERR_BUSY (MPR_ERR_BASE - 11) /* Error code */ -#define MPR_ERR_CANT_ACCESS (MPR_ERR_BASE - 12) /* Error code */ -#define MPR_ERR_CANT_COMPLETE (MPR_ERR_BASE - 13) /* Error code */ -#define MPR_ERR_CANT_CREATE (MPR_ERR_BASE - 14) /* Error code */ -#define MPR_ERR_CANT_INITIALIZE (MPR_ERR_BASE - 15) /* Error code */ -#define MPR_ERR_CANT_OPEN (MPR_ERR_BASE - 16) /* Error code */ -#define MPR_ERR_CANT_READ (MPR_ERR_BASE - 17) /* Error code */ -#define MPR_ERR_CANT_WRITE (MPR_ERR_BASE - 18) /* Error code */ -#define MPR_ERR_DELETED (MPR_ERR_BASE - 19) /* Error code */ -#define MPR_ERR_NETWORK (MPR_ERR_BASE - 20) /* Error code */ -#define MPR_ERR_NOT_FOUND (MPR_ERR_BASE - 21) /* Error code */ -#define MPR_ERR_NOT_INITIALIZED (MPR_ERR_BASE - 22) /* Error code */ -#define MPR_ERR_NOT_READY (MPR_ERR_BASE - 23) /* Error code */ -#define MPR_ERR_READ_ONLY (MPR_ERR_BASE - 24) /* Error code */ -#define MPR_ERR_TIMEOUT (MPR_ERR_BASE - 25) /* Error code */ -#define MPR_ERR_TOO_MANY (MPR_ERR_BASE - 26) /* Error code */ -#define MPR_ERR_WONT_FIT (MPR_ERR_BASE - 27) /* Error code */ -#define MPR_ERR_WOULD_BLOCK (MPR_ERR_BASE - 28) /* Error code */ -#define MPR_ERR_CANT_ALLOCATE (MPR_ERR_BASE - 29) /* Error code */ -#define MPR_ERR_MAX (MPR_ERR_BASE - 30) /* Error code */ - -/* - * Standard error severity and trace levels. These are ored with the error - * severities below. The MPR_LOG_MASK is used to extract the trace level - * from a flags word. We expect most apps to run with level 2 trace. - */ -#define MPR_FATAL 0 /* Fatal error. Cant continue. */ -#define MPR_ERROR 1 /* Hard error */ -#define MPR_WARN 2 /* Soft warning */ -#define MPR_CONFIG 2 /* Essential configuration settings */ -#define MPR_INFO 3 /* Informational only */ -#define MPR_DEBUG 4 /* Debug information */ -#define MPR_VERBOSE 9 /* Highest level of trace */ -#define MPR_LOG_MASK 0xf /* Level mask */ - -/* - * Error flags. Specify where the error should be sent to. Note that the - * product.xml setting "headless" will modify how errors are reported. - * Assert errors are trapped when in DEV mode. Otherwise ignored. - */ -#define MPR_TRAP 0x10 /* Assert error -- trap in debugger */ -#define MPR_LOG 0x20 /* Log the error in the O/S event log */ -#define MPR_USER 0x40 /* Display to the user */ -#define MPR_ALERT 0x80 /* Send a management alert */ -#define MPR_TRACE 0x100 /* Trace */ - -/* - * Error format flags - */ -#define MPR_RAW 0x200 /* Raw trace output */ - -/* - * Error line number information - */ -#define MPR_L __FILE__, __LINE__ - -typedef char* MprStr; - -#ifndef __cplusplus -typedef unsigned char uchar; -#endif - -/* - * Porters: put other operating system type defines here - */ -#if WIN - typedef unsigned int uint; - typedef __int64 int64; - typedef unsigned __int64 uint64; -#else -#define O_BINARY 0 -#ifndef uint - #define uint unsigned -#endif - #define int64 int64_t - #define uint64 uint64_t -#endif - -/* - * Flexible array data type - */ -typedef struct { - int max; /* Size of the handles array */ - int used; /* Count of used entries in handles */ - void **handles; -} MprArray; - -#if BLD_FEATURE_SQUEEZE -#define MPR_ARRAY_INCR 8 -#else -#define MPR_ARRAY_INCR 16 -#endif - -#ifndef max -#define max(a,b) (((a) > (b)) ? (a) : (b)) -#endif - -/********************************* Prototypes *********************************/ -/* - * If running in the GoAhead WebServer, map some MPR routines to WebServer - * equivalents. - */ - -#if BLD_GOAHEAD_WEBSERVER -#include "uemf.h" -#define mprMalloc(size) balloc(B_L, size) -#define mprFree(ptr) bfreeSafe(B_L, ptr) -#define mprRealloc(ptr, size) brealloc(B_L, ptr, size) -#define mprStrdup(ptr) bstrdup(B_L, ptr) -#define mprAllocSprintf fmtAlloc -#define mprAllocVsprintf fmtValloc -#define mprSprintf fmtStatic -#define mprItoa stritoa -#define mprLog trace -#define mprBreakpoint(file, line, cond) \ - error(file, line, E_BLD_FEATURE_ASSERT, T("%s"), cond) - -#else /* !BLD_GOAHEAD_WEBSERVER */ -/* #define mprMalloc malloc */ -#define mprSprintf snprintf -#define mtVsprintf vsnprintf -extern void *mprMalloc(uint size); -extern void *mprRealloc(void *ptr, uint size); -extern void mprFree(void *ptr); -extern char *mprStrdup(const char *str); -extern int mprAllocVsprintf(char **msgbuf, int maxSize, const char *fmt, - va_list args) PRINTF_ATTRIBUTE(3,0); -extern int mprAllocSprintf(char **msgbuf, int maxSize, const char *fmt, ...) PRINTF_ATTRIBUTE(3,4); -extern char *mprItoa(int num, char *buf, int width); -extern void mprLog(int level, const char *fmt, ...) PRINTF_ATTRIBUTE(2,3); -extern void mprBreakpoint(const char *file, int line, const char *msg) _NORETURN_; -#endif /* BLD_GOAHEAD_WEBSERVER */ - -extern MprArray *mprCreateArray(void); -extern void mprDestroyArray(MprArray *array); -extern int mprAddToArray(MprArray *array, void *item); -extern int mprRemoveFromArray(MprArray *array, int idx); -extern char *mprStrTok(char *str, const char *delim, char **tok); - -extern int mprGetDirName(char *buf, int bufsize, char *path); -extern int mprReallocStrcat(char **dest, int max, int existingLen, - const char *delim, const char *src, ...); -extern int mprStrcpy(char *dest, int destMax, const char *src); -extern int mprMemcpy(char *dest, int destMax, const char *src, int nbytes); - -extern void mprSetCtx(void *ctx); -extern void *mprMemCtx(void); -struct loadparm_context; -extern struct loadparm_context *mprLpCtx(void); -struct event_context; -extern struct event_context *mprEventCtx(void); - -/* This function needs to be provided by anyone using ejs */ -void ejs_exception(const char *reason); - -#define mprStrCmpAnyCase(s1, s2) strcasecmp_m(s1, s2) - -#ifdef __cplusplus -} -#endif -#endif /* !BLD_APPWEB */ -#endif /* _h_MINI_MPR */ - -/*****************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/mpr/var.c b/source4/lib/appweb/mpr/var.c deleted file mode 100644 index e73da773ea..0000000000 --- a/source4/lib/appweb/mpr/var.c +++ /dev/null @@ -1,2215 +0,0 @@ -/* - * @file var.c - * @brief MPR Universal Variable Type - * @overview - * - * @copy default.m - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/******************************* Documentation ********************************/ - -/* - * This module is NOT multithreaded. - * - * Properties are variables that are stored in an object type variable. - * Properties can be primitive data types, other objects or functions. - * Properties are indexed by a character name. - */ - -/********************************** Includes **********************************/ - -#include "var.h" - -/*********************************** Locals ***********************************/ -#if VAR_DEBUG - -static MprProperties objectList; /* Dummy head of objects list */ -static int objectCount = -1; /* Count of objects */ - -#endif -/***************************** Forward Declarations ***************************/ - -static int adjustRefCount(MprProperties *pp, int adj); -static int adjustVarRefCount(MprVar *vp, int adj); -static MprVar *allocProperty(const char *propertyName); -static void copyVarCore(MprVar *dest, MprVar *src, int copyDepth); -static MprProperties - *createProperties(const char *name, int hashSize); -static bool freeVar(MprVar *vp, int force); -static bool freeVarStorage(MprVar *vp, int force); -static MprVar *getObjChain(MprProperties *pp, const char *property); -static int hash(MprProperties *pp, const char *property); -static bool releaseProperties(MprProperties *pp, int force); - -/*********************************** Code *************************************/ -/* - * Destroy a variable and all referenced variables. Release any referenced - * object regardless of whether other users still have references. Be VERY - * careful using this routine. - * - * Return TRUE if the underlying data is freed. Objects may not be freed if - * there are other users of the object. - */ - -bool mprDestroyAllVars(MprVar *vp) -{ - mprAssert(vp); - - if (vp->trigger) { - if ((vp->trigger)(MPR_VAR_DELETE, vp->parentProperties, vp, 0, 0) - == MPR_TRIGGER_ABORT) { - return 0; - } - } - - /* - * Free the actual value. If this var refers to an object, we will - * recurse through all the properties freeing all vars. - */ - return freeVar(vp, 1); -} - -/******************************************************************************/ -/* - * Destroy a variable. Release any referenced object (destroy if no other - * users are referencing). - * - * Return TRUE if the underlying data is freed. Objects may not be freed if - * there are other users of the object. - */ - -bool mprDestroyVar(MprVar *vp) -{ - mprAssert(vp); - - if (vp->trigger) { - if ((vp->trigger)(MPR_VAR_DELETE, vp->parentProperties, vp, 0, 0) - == MPR_TRIGGER_ABORT) { - return 0; - } - } - - /* - * Free the actual value. If this var refers to an object, we will - * recurse through all the properties freeing all that have no other - * references. - */ - return freeVar(vp, 0); -} - -/******************************************************************************/ -/* - * Free the value in a variable for primitive types. Release objects. - * - * Return TRUE if the underlying data is freed. Objects may not be freed if - * there are other users of the object. - */ - -static bool freeVar(MprVar *vp, int force) -{ - bool freed; - - mprAssert(vp); - - freed = freeVarStorage(vp, force); - - mprFree(vp->name); - mprFree(vp->fullName); - - if (vp->allocatedVar) { - mprFree(vp); - } else { - vp->name = 0; - vp->fullName = 0; - vp->type = MPR_TYPE_UNDEFINED; - } - return freed; -} - -/******************************************************************************/ -/* - * Free the value in a variable for primitive types. Release objects. - * - * Return TRUE if the underlying data is freed. Objects may not be freed if - * there are other users of the object. - */ - -static bool freeVarStorage(MprVar *vp, int force) -{ - MprArray *argList; - bool freed; - int i; - - freed = 1; - mprAssert(vp); - - switch (vp->type) { - default: - break; - - case MPR_TYPE_STRING: - if (vp->allocatedData && vp->string != 0) { - mprFree(vp->string); - vp->string = 0; - vp->allocatedData = 0; - } - break; - - case MPR_TYPE_PTR: - if (vp->allocatedData) { - vp->allocatedData = 0; - mprFree(vp->ptr); - } - break; - - case MPR_TYPE_OBJECT: -#if VAR_DEBUG - /* - * Recurse through all properties and release / delete. Release the - * properties hash table. - */ - if (vp->properties->refCount > 1) { - mprLog(7, "freeVar: ACT \"%s\", 0x%x, ref %d, force %d\n", - vp->name, vp->properties, vp->properties->refCount, force); - } else { - mprLog(7, "freeVar: DEL \"%s\", 0x%x, ref %d, force %d\n", - vp->name, vp->properties, vp->properties->refCount, force); - } -#endif - if (vp->allocatedData) { - freed = releaseProperties(vp->properties, force); - } - vp->properties = 0; - break; - - case MPR_TYPE_FUNCTION: - if (vp->allocatedData) { - argList = vp->function.args; - for (i = 0; i < argList->max; i++) { - if (argList->handles[i] != 0) { - mprFree(argList->handles[i]); - } - } - mprDestroyArray(argList); - vp->function.args = 0; - mprFree(vp->function.body); - vp->function.body = 0; - } - break; - } - - vp->type = MPR_TYPE_UNDEFINED; - return freed; -} - -/******************************************************************************/ -/* - * Adjust the object reference count and return the currrent count of - * users. - */ - -static int adjustVarRefCount(MprVar *vp, int adj) -{ - mprAssert(vp); - - if (vp->type != MPR_TYPE_OBJECT) { - mprAssert(vp->type == MPR_TYPE_OBJECT); - return 0; - } - return adjustRefCount(vp->properties, adj); -} - -/******************************************************************************/ -/* - * Get the object reference count - */ - -int mprGetVarRefCount(MprVar *vp) -{ - mprAssert(vp); - - if (vp->type != MPR_TYPE_OBJECT) { - mprAssert(vp->type == MPR_TYPE_OBJECT); - return 0; - } - return adjustRefCount(vp->properties, 0); -} - -/******************************************************************************/ -/* - * Update the variable's name - */ - -void mprSetVarName(MprVar *vp, char *name) -{ - mprAssert(vp); - - mprFree(vp->name); - vp->name = mprStrdup(name); -} - -/******************************************************************************/ -/* - * Append to the variable's full name - */ - -void mprSetVarFullName(MprVar *vp, char *name) -{ -#if VAR_DEBUG - mprAssert(vp); - - mprFree(vp->fullName); - vp->fullName = mprStrdup(name); - if (vp->type == MPR_TYPE_OBJECT) { - if (strcmp(vp->properties->name, "this") == 0) { - mprStrcpy(vp->properties->name, sizeof(vp->properties->name), name); - } - } -#endif -} - -/******************************************************************************/ -/* - * Make a var impervious to recursive forced deletes. - */ - -void mprSetVarDeleteProtect(MprVar *vp, int deleteProtect) -{ - mprAssert(vp); - - if (vp->type == MPR_TYPE_OBJECT && vp->properties) { - vp->properties->deleteProtect = deleteProtect; - } -} - -/******************************************************************************/ -/* - * Make a variable readonly. Can still be deleted. - */ - -void mprSetVarReadonly(MprVar *vp, int readonly) -{ - mprAssert(vp); - - vp->readonly = readonly; -} - -/******************************************************************************/ - -MprVarTrigger mprAddVarTrigger(MprVar *vp, MprVarTrigger fn) -{ - MprVarTrigger oldTrigger; - - mprAssert(vp); - mprAssert(fn); - - oldTrigger = vp->trigger; - vp->trigger = fn; - return oldTrigger; -} - -/******************************************************************************/ - -MprType mprGetVarType(MprVar *vp) -{ - mprAssert(vp); - - return vp->type; -} - -/******************************************************************************/ -/********************************** Properties ********************************/ -/******************************************************************************/ -/* - * Create a property in an object with a defined value. If the property - * already exists in the object, then just write its value. - */ - -MprVar *mprCreateProperty(MprVar *obj, const char *propertyName, - MprVar *newValue) -{ - MprVar *prop, *last; - int bucketIndex; - - mprAssert(obj); - mprAssert(propertyName && *propertyName); - - if (obj->type != MPR_TYPE_OBJECT) { - mprAssert(obj->type == MPR_TYPE_OBJECT); - return 0; - } - - /* - * See if property already exists and locate the bucket to hold the - * property reference. - */ - last = 0; - bucketIndex = hash(obj->properties, propertyName); - prop = obj->properties->buckets[bucketIndex]; - - /* - * Find the property in the hash chain if it exists - */ - for (last = 0; prop; last = prop, prop = prop->forw) { - if (prop->name[0] == propertyName[0] && - strcmp(prop->name, propertyName) == 0) { - break; - } - } - - if (prop) { - /* FUTURE -- remove. Just for debug. */ - mprAssert(prop == 0); - mprLog(0, "Attempting to create property %s in object %s\n", - propertyName, obj->name); - return 0; - } - - if (obj->trigger) { - if ((obj->trigger)(MPR_VAR_CREATE_PROPERTY, obj->properties, prop, - newValue, 0) == MPR_TRIGGER_ABORT) { - return 0; - } - } - - /* - * Create a new property - */ - prop = allocProperty(propertyName); - if (prop == 0) { - mprAssert(prop); - return 0; - } - - copyVarCore(prop, newValue, MPR_SHALLOW_COPY); - - prop->bucketIndex = bucketIndex; - if (last) { - last->forw = prop; - } else { - obj->properties->buckets[bucketIndex] = prop; - } - prop->parentProperties = obj->properties; - - /* - * Update the item counts - */ - obj->properties->numItems++; - if (! mprVarIsFunction(prop->type)) { - obj->properties->numDataItems++; - } - - return prop; -} - -/******************************************************************************/ -/* - * Create a property in an object with a defined value. If the property - * already exists in the object, then just write its value. Same as - * mprCreateProperty except that the new value is passed by value rather than - * by pointer. - */ - -MprVar *mprCreatePropertyValue(MprVar *obj, const char *propertyName, - MprVar newValue) -{ - return mprCreateProperty(obj, propertyName, &newValue); -} - -/******************************************************************************/ -/* - * Create a new property - */ - -static MprVar *allocProperty(const char *propertyName) -{ - MprVar *prop; - - prop = (MprVar*) mprMalloc(sizeof(MprVar)); - if (prop == 0) { - mprAssert(prop); - return 0; - } - memset(prop, 0, sizeof(MprVar)); - prop->allocatedVar = 1; - prop->name = mprStrdup(propertyName); - prop->forw = (MprVar*) 0; - - return prop; -} - -/******************************************************************************/ -/* - * Update a property in an object with a defined value. Create the property - * if it doesn not already exist. - */ - -MprVar *mprSetProperty(MprVar *obj, const char *propertyName, MprVar *newValue) -{ - MprVar *prop, triggerValue; - int rc; - - mprAssert(obj); - mprAssert(propertyName && *propertyName); - mprAssert(obj->type == MPR_TYPE_OBJECT); - - if (obj->type != MPR_TYPE_OBJECT) { - mprAssert(0); - return 0; - } - - prop = mprGetProperty(obj, propertyName, 0); - if (prop == 0) { - return mprCreateProperty(obj, propertyName, newValue); - } - - if (obj->trigger) { - /* - * Call the trigger before the update and pass it the new value. - */ - triggerValue = *newValue; - triggerValue.allocatedVar = 0; - triggerValue.allocatedData = 0; - rc = (obj->trigger)(MPR_VAR_WRITE, obj->properties, obj, - &triggerValue, 0); - if (rc == MPR_TRIGGER_ABORT) { - return 0; - - } else if (rc == MPR_TRIGGER_USE_NEW_VALUE) { - /* - * Trigger must copy to triggerValue a variable that is not - * a structure copy of the existing data. - */ - copyVarCore(prop, &triggerValue, MPR_SHALLOW_COPY); - mprDestroyVar(&triggerValue); - return prop; - } - } - copyVarCore(prop, newValue, MPR_SHALLOW_COPY); - return prop; -} - -/******************************************************************************/ -/* - * Update a property in an object with a defined value. Create the property - * if it does not already exist. Same as mprSetProperty except that the - * new value is passed by value rather than by pointer. - */ - -MprVar *mprSetPropertyValue(MprVar *obj, const char *propertyName, - MprVar newValue) -{ - return mprSetProperty(obj, propertyName, &newValue); -} - -/******************************************************************************/ -/* - * Delete a property from this object - */ - -int mprDeleteProperty(MprVar *obj, const char *property) -{ - MprVar *prop, *last; - char *cp; - int bucketIndex; - - mprAssert(obj); - mprAssert(property && *property); - mprAssert(obj->type == MPR_TYPE_OBJECT); - - if (obj->type != MPR_TYPE_OBJECT) { - mprAssert(obj->type == MPR_TYPE_OBJECT); - return 0; - } - - last = 0; - bucketIndex = hash(obj->properties, property); - if ((prop = obj->properties->buckets[bucketIndex]) != 0) { - for ( ; prop; prop = prop->forw) { - cp = prop->name; - if (cp[0] == property[0] && strcmp(cp, property) == 0) { - break; - } - last = prop; - } - } - if (prop == (MprVar*) 0) { - mprAssert(prop); - return MPR_ERR_NOT_FOUND; - } - if (prop->readonly) { - mprAssert(! prop->readonly); - return MPR_ERR_READ_ONLY; - } - - if (obj->trigger) { - if ((obj->trigger)(MPR_VAR_DELETE_PROPERTY, obj->properties, prop, 0, 0) - == MPR_TRIGGER_ABORT) { - return MPR_ERR_ABORTED; - } - } - - if (last) { - last->forw = prop->forw; - } else { - obj->properties->buckets[bucketIndex] = prop->forw; - } - - obj->properties->numItems--; - if (! mprVarIsFunction(prop->type)) { - obj->properties->numDataItems--; - } - - mprDestroyVar(prop); - - return 0; -} - -/******************************************************************************/ -/* - * Find a property in an object and return a pointer to it. If a value arg - * is supplied, then copy the data into the var. - */ - -MprVar *mprGetProperty(MprVar *obj, const char *property, MprVar *value) -{ - MprVar *prop, triggerValue; - int rc; - - if (obj == 0 || obj->type != MPR_TYPE_OBJECT || property == 0 || - *property == '\0') { - if (value) { - value->type = MPR_TYPE_UNDEFINED; - } - return 0; - } - - for (prop = getObjChain(obj->properties, property); prop; - prop = prop->forw) { - if (prop->name && - prop->name[0] == property[0] && strcmp(prop->name, property) == 0) { - break; - } - } - if (prop == 0) { - if (value) { - value->type = MPR_TYPE_UNDEFINED; - } - return 0; - } - if (value) { - if (prop->trigger) { - triggerValue = *prop; - triggerValue.allocatedVar = 0; - triggerValue.allocatedData = 0; - /* - * Pass the trigger the current read value and may receive - * a new value. - */ - rc = (prop->trigger)(MPR_VAR_READ, prop->parentProperties, prop, - &triggerValue, 0); - if (rc == MPR_TRIGGER_ABORT) { - if (value) { - value->type = MPR_TYPE_UNDEFINED; - } - return 0; - - } else if (rc == MPR_TRIGGER_USE_NEW_VALUE) { - copyVarCore(prop, &triggerValue, MPR_SHALLOW_COPY); - mprDestroyVar(&triggerValue); - } - } - /* - * Clone. No copy. - */ - *value = *prop; - } - return prop; -} - -/******************************************************************************/ -/* - * Read a properties value. This returns the property's value. It does not - * copy object/string data but returns a pointer directly into the variable. - * The caller does not and should not call mprDestroy on the returned value. - * If value is null, just read the property and run triggers. - */ - -int mprReadProperty(MprVar *prop, MprVar *value) -{ - MprVar triggerValue; - int rc; - - mprAssert(prop); - - if (prop->trigger) { - triggerValue = *prop; - triggerValue.allocatedVar = 0; - triggerValue.allocatedData = 0; - rc = (prop->trigger)(MPR_VAR_READ, prop->parentProperties, prop, - &triggerValue, 0); - - if (rc == MPR_TRIGGER_ABORT) { - return MPR_ERR_ABORTED; - - } else if (rc == MPR_TRIGGER_USE_NEW_VALUE) { - copyVarCore(prop, &triggerValue, MPR_SHALLOW_COPY); - mprDestroyVar(&triggerValue); - return 0; - } - } - if (value) { - *value = *prop; - - /* - * Just so that if the user calls mprDestroyVar on value, it will do no - * harm. - */ - value->allocatedVar = 0; - value->allocatedData = 0; - } - return 0; -} - -/******************************************************************************/ -/* - * Read a properties value. This returns a copy of the property variable. - * However, if the property is an object or string, it returns a copy of the - * reference to the underlying data. If copyDepth is set to MPR_DEEP_COPY, - * then the underlying objects and strings data will be copied as well. If - * copyDepth is set to MPR_SHALLOW_COPY, then only strings will be copied. If - * it is set to MPR_NO_COPY, then no data will be copied. In all cases, the - * user must call mprDestroyVar to free resources. This routine will run any - * registered triggers which may modify the value the user receives (without - * updating the properties real value). - * - * WARNING: the args are reversed to most other APIs. This conforms to the - * strcpy(dest, src) standard instead. - */ - -int mprCopyProperty(MprVar *dest, MprVar *prop, int copyDepth) -{ - MprVar triggerValue; - int rc; - - mprAssert(prop); - mprAssert(dest); - - if (prop->trigger) { - triggerValue = *prop; - triggerValue.allocatedVar = 0; - triggerValue.allocatedData = 0; - rc = (prop->trigger)(MPR_VAR_READ, prop->parentProperties, prop, - &triggerValue, copyDepth); - - if (rc == MPR_TRIGGER_ABORT) { - return MPR_ERR_ABORTED; - - } else if (rc == MPR_TRIGGER_USE_NEW_VALUE) { - copyVarCore(dest, &triggerValue, MPR_SHALLOW_COPY); - mprDestroyVar(&triggerValue); - return 0; - } - } - mprCopyVar(dest, prop, copyDepth); - return 0; -} - -/******************************************************************************/ -/* - * Write a new value into an existing property in an object. - */ - -int mprWriteProperty(MprVar *vp, MprVar *value) -{ - MprVar triggerValue; - int rc; - - mprAssert(vp); - mprAssert(value); - - if (vp->readonly) { - return MPR_ERR_READ_ONLY; - } - - if (vp->trigger) { - triggerValue = *value; - - rc = (vp->trigger)(MPR_VAR_WRITE, vp->parentProperties, vp, - &triggerValue, 0); - - if (rc == MPR_TRIGGER_ABORT) { - return MPR_ERR_ABORTED; - - } else if (rc == MPR_TRIGGER_USE_NEW_VALUE) { - copyVarCore(vp, &triggerValue, MPR_SHALLOW_COPY); - mprDestroyVar(&triggerValue); - return 0; - } - /* Fall through */ - } - - copyVarCore(vp, value, MPR_SHALLOW_COPY); - return 0; -} - -/******************************************************************************/ -/* - * Write a new value into an existing property in an object. - */ - -int mprWritePropertyValue(MprVar *vp, MprVar value) -{ - mprAssert(vp); - - return mprWriteProperty(vp, &value); -} - -/******************************************************************************/ -/* - * Get the count of properties. - */ - -int mprGetPropertyCount(MprVar *vp, int includeFlags) -{ - mprAssert(vp); - - if (vp->type != MPR_TYPE_OBJECT) { - return 0; - } - if (includeFlags == MPR_ENUM_DATA) { - return vp->properties->numDataItems; - } else { - return vp->properties->numItems; - } -} - -/******************************************************************************/ -/* - * Get the first property in an object. Used for walking all properties in an - * object. - */ - -MprVar *mprGetFirstProperty(MprVar *obj, int includeFlags) -{ - MprVar *prop; - int i; - - mprAssert(obj); - mprAssert(obj->type == MPR_TYPE_OBJECT); - - if (obj->type != MPR_TYPE_OBJECT) { - mprAssert(obj->type == MPR_TYPE_OBJECT); - return 0; - } - - for (i = 0; i < (int) obj->properties->hashSize; i++) { - for (prop = obj->properties->buckets[i]; prop; prop = prop->forw) { - if (prop) { - if (mprVarIsFunction(prop->type)) { - if (!(includeFlags & MPR_ENUM_FUNCTIONS)) { - continue; - } - } else { - if (!(includeFlags & MPR_ENUM_DATA)) { - continue; - } - } - return prop; - } - break; - } - } - return 0; -} - -/******************************************************************************/ -/* - * Get the next property in sequence. - */ - -MprVar *mprGetNextProperty(MprVar *obj, MprVar *last, int includeFlags) -{ - MprProperties *properties; - int i; - - mprAssert(obj); - mprAssert(obj->type == MPR_TYPE_OBJECT); - - if (obj->type != MPR_TYPE_OBJECT) { - mprAssert(obj->type == MPR_TYPE_OBJECT); - return 0; - } - properties = obj->properties; - - if (last->forw) { - return last->forw; - } - - for (i = last->bucketIndex + 1; i < (int) properties->hashSize; i++) { - for (last = properties->buckets[i]; last; last = last->forw) { - if (mprVarIsFunction(last->type)) { - if (!(includeFlags & MPR_ENUM_FUNCTIONS)) { - continue; - } - } else { - if (!(includeFlags & MPR_ENUM_DATA)) { - continue; - } - } - return last; - } - } - return 0; -} - -/******************************************************************************/ -/************************** Internal Support Routines *************************/ -/******************************************************************************/ -/* - * Create an hash table to hold and index properties. Properties are just - * variables which may contain primitive data types, functions or other - * objects. The hash table is the essence of an object. HashSize specifies - * the size of the hash table to use and should be a prime number. - */ - -static MprProperties *createProperties(const char *name, int hashSize) -{ - MprProperties *pp; - - if (hashSize < 7) { - hashSize = 7; - } - if ((pp = (MprProperties*) mprMalloc(sizeof(MprProperties))) == NULL) { - mprAssert(0); - return 0; - } - mprAssert(pp); - memset(pp, 0, sizeof(MprProperties)); - - pp->numItems = 0; - pp->numDataItems = 0; - pp->hashSize = hashSize; - pp->buckets = (MprVar**) mprMalloc(pp->hashSize * sizeof(MprVar*)); - mprAssert(pp->buckets); - memset(pp->buckets, 0, pp->hashSize * sizeof(MprVar*)); - pp->refCount = 1; - -#if VAR_DEBUG - if (objectCount == -1) { - objectCount = 0; - objectList.next = objectList.prev = &objectList; - } - - mprStrcpy(pp->name, sizeof(pp->name), name); - pp->next = &objectList; - pp->prev = objectList.prev; - objectList.prev->next = pp; - objectList.prev = pp; - objectCount++; -#endif - return pp; -} - -/******************************************************************************/ -/* - * Release an object's properties hash table. If this is the last person - * using it, free it. Return TRUE if the object is released. - */ - -static bool releaseProperties(MprProperties *obj, int force) -{ - MprProperties *pp; - MprVar *prop, *forw; - int i; - - mprAssert(obj); - mprAssert(obj->refCount > 0); - -#if VAR_DEBUG - /* - * Debug sanity check - */ - mprAssert(obj->refCount < 20); -#endif - - if (--obj->refCount > 0 && !force) { - return 0; - } - -#if VAR_DEBUG - mprAssert(obj->prev); - mprAssert(obj->next); - mprAssert(obj->next->prev); - mprAssert(obj->prev->next); - obj->next->prev = obj->prev; - obj->prev->next = obj->next; - objectCount--; -#endif - - for (i = 0; i < (int) obj->hashSize; i++) { - for (prop = obj->buckets[i]; prop; prop = forw) { - forw = prop->forw; - if (prop->type == MPR_TYPE_OBJECT) { - - if (prop->properties == obj) { - /* Self reference */ - continue; - } - pp = prop->properties; - if (pp->visited) { - continue; - } - - pp->visited = 1; - if (! freeVar(prop, pp->deleteProtect ? 0 : force)) { - pp->visited = 0; - } - - } else { - freeVar(prop, force); - } - } - } - - mprFree((void*) obj->buckets); - mprFree((void*) obj); - - return 1; -} - -/******************************************************************************/ -/* - * Adjust the reference count - */ - -static int adjustRefCount(MprProperties *pp, int adj) -{ - mprAssert(pp); - - /* - * Debug sanity check - */ - mprAssert(pp->refCount < 20); - - return pp->refCount += adj; -} - -/******************************************************************************/ -#if VAR_DEBUG -/* - * Print objects held - */ - -void mprPrintObjects(char *msg) -{ - MprProperties *pp, *np; - MprVar *prop, *forw; - char *buf; - int i; - - mprLog(7, "%s: Object Store. %d objects.\n", msg, objectCount); - pp = objectList.next; - while (pp != &objectList) { - mprLog(7, "%s: 0x%x, refCount %d, properties %d\n", - pp->name, pp, pp->refCount, pp->numItems); - for (i = 0; i < (int) pp->hashSize; i++) { - for (prop = pp->buckets[i]; prop; prop = forw) { - forw = prop->forw; - if (prop->properties == pp) { - /* Self reference */ - continue; - } - mprVarToString(&buf, MPR_MAX_STRING, 0, prop); - if (prop->type == MPR_TYPE_OBJECT) { - np = objectList.next; - while (np != &objectList) { - if (prop->properties == np) { - break; - } - np = np->next; - } - if (prop->properties == np) { - mprLog(7, " %s: OBJECT 0x%x, <%s>\n", - prop->name, prop->properties, prop->fullName); - } else { - mprLog(7, " %s: OBJECT NOT FOUND, %s <%s>\n", - prop->name, buf, prop->fullName); - } - } else { - mprLog(7, " %s: <%s> = %s\n", prop->name, - prop->fullName, buf); - } - mprFree(buf); - } - } - pp = pp->next; - } -} - -/******************************************************************************/ - -void mprPrintObjRefCount(MprVar *vp) -{ - mprLog(7, "OBJECT 0x%x, refCount %d\n", vp->properties, - vp->properties->refCount); -} - -#endif -/******************************************************************************/ -/* - * Get the bucket chain containing a property. - */ - -static MprVar *getObjChain(MprProperties *obj, const char *property) -{ - mprAssert(obj); - - return obj->buckets[hash(obj, property)]; -} - -/******************************************************************************/ -/* - * Fast hash. The history of this algorithm is part of lost computer science - * folk lore. - */ - -static int hash(MprProperties *pp, const char *property) -{ - uint sum; - - mprAssert(pp); - mprAssert(property); - - sum = 0; - while (*property) { - sum += (sum * 33) + *property++; - } - - return sum % pp->hashSize; -} - -/******************************************************************************/ -/*********************************** Constructors *****************************/ -/******************************************************************************/ -/* - * Initialize an undefined value. - */ - -MprVar mprCreateUndefinedVar() -{ - MprVar v; - - memset(&v, 0x0, sizeof(v)); - v.type = MPR_TYPE_UNDEFINED; - return v; -} - -/******************************************************************************/ -/* - * Initialize an null value. - */ - -MprVar mprCreateNullVar() -{ - MprVar v; - - memset(&v, 0x0, sizeof(v)); - v.type = MPR_TYPE_NULL; - return v; -} - -/******************************************************************************/ - -MprVar mprCreateBoolVar(bool value) -{ - MprVar v; - - memset(&v, 0x0, sizeof(v)); - v.type = MPR_TYPE_BOOL; - v.boolean = value; - return v; -} - -/******************************************************************************/ -/* - * Initialize a C function. - */ - -MprVar mprCreateCFunctionVar(MprCFunction fn, void *thisPtr, int flags) -{ - MprVar v; - - memset(&v, 0x0, sizeof(v)); - v.type = MPR_TYPE_CFUNCTION; - v.cFunction.fn = fn; - v.cFunction.thisPtr = thisPtr; - v.flags = flags; - - return v; -} - -/******************************************************************************/ -/* - * Initialize a C function. - */ - -MprVar mprCreateStringCFunctionVar(MprStringCFunction fn, void *thisPtr, - int flags) -{ - MprVar v; - - memset(&v, 0x0, sizeof(v)); - v.type = MPR_TYPE_STRING_CFUNCTION; - v.cFunctionWithStrings.fn = fn; - v.cFunctionWithStrings.thisPtr = thisPtr; - v.flags = flags; - - return v; -} - -/******************************************************************************/ -/* - * Initialize an opaque pointer. - */ - -MprVar mprCreatePtrVar(void *ptr) -{ - MprVar v; - - memset(&v, 0x0, sizeof(v)); - v.type = MPR_TYPE_PTR; - v.ptr = ptr; - - return v; -} - -/******************************************************************************/ -#if BLD_FEATURE_FLOATING_POINT -/* - * Initialize a floating value. - */ - -MprVar mprCreateFloatVar(double value) -{ - MprVar v; - - memset(&v, 0x0, sizeof(v)); - v.type = MPR_TYPE_FLOAT; - v.floating = value; - return v; -} - -#endif -/******************************************************************************/ -/* - * Initialize an integer value. - */ - -MprVar mprCreateIntegerVar(int value) -{ - MprVar v; - - memset(&v, 0x0, sizeof(v)); - v.type = MPR_TYPE_INT; - v.integer = value; - return v; -} - -/******************************************************************************/ -#if BLD_FEATURE_INT64 -/* - * Initialize a 64-bit integer value. - */ - -MprVar mprCreateInteger64Var(int64 value) -{ - MprVar v; - - memset(&v, 0x0, sizeof(v)); - v.type = MPR_TYPE_INT64; - v.integer64 = value; - return v; -} - -#endif /* BLD_FEATURE_INT64 */ -/******************************************************************************/ -/* - * Initialize an number variable. Type is defined by configure. - */ - -MprVar mprCreateNumberVar(MprNum value) -{ - MprVar v; - - memset(&v, 0x0, sizeof(v)); - v.type = BLD_FEATURE_NUM_TYPE_ID; -#if BLD_FEATURE_NUM_TYPE_ID == MPR_TYPE_INT64 - v.integer64 = value; -#elif BLD_FEATURE_NUM_TYPE_ID == MPR_TYPE_FLOAT - v.float = value; -#else - v.integer = value; -#endif - return v; -} - -/******************************************************************************/ -/* - * Initialize a (bare) JavaScript function. args and body can be null. - */ - -MprVar mprCreateFunctionVar(char *args, char *body, int flags) -{ - MprVar v; - char *cp, *arg, *last; - int aid; - - memset(&v, 0x0, sizeof(v)); - v.type = MPR_TYPE_FUNCTION; - v.flags = flags; - - v.function.args = mprCreateArray(); - - if (args) { - args = mprStrdup(args); - arg = mprStrTok(args, ",", &last); - while (arg) { - while (isspace((int) *arg)) - arg++; - for (cp = &arg[strlen(arg) - 1]; cp > arg; cp--) { - if (!isspace((int) *cp)) { - break; - } - } - cp[1] = '\0'; - - aid = mprAddToArray(v.function.args, mprStrdup(arg)); - arg = mprStrTok(0, ",", &last); - } - mprFree(args); - } - - if (body) { - v.function.body = mprStrdup(body); - } - v.allocatedData = 1; - return v; -} - -/******************************************************************************/ -/* - * Initialize an object variable. Return type == MPR_TYPE_UNDEFINED if the - * memory allocation for the properties table failed. - */ - -MprVar mprCreateObjVar(const char *name, int hashSize) -{ - MprVar v; - - mprAssert(name && *name); - - memset(&v, 0x0, sizeof(MprVar)); - v.type = MPR_TYPE_OBJECT; - if (hashSize <= 0) { - hashSize = MPR_DEFAULT_HASH_SIZE; - } - v.properties = createProperties(name, hashSize); - if (v.properties == 0) { - /* Indicate failed memory allocation */ - v.type = MPR_TYPE_UNDEFINED; - } - v.allocatedData = 1; - v.name = mprStrdup(name); - mprLog(7, "mprCreateObjVar %s, 0x%p\n", name, v.properties); - return v; -} - -/******************************************************************************/ -/* - * Initialize a string value. - */ - -MprVar mprCreateStringVar(const char *value, bool allocate) -{ - MprVar v; - - memset(&v, 0x0, sizeof(v)); - v.type = MPR_TYPE_STRING; - if (value == 0) { - v.string = (char*) ""; - } else if (allocate) { - v.string = mprStrdup(value); - v.allocatedData = 1; - } else { - v.string = (char*) value; - } - return v; -} - -/******************************************************************************/ -/* - * Copy an objects core value (only). This preserves the destination object's - * name. This implements copy by reference for objects and copy by value for - * strings and other types. Caller must free dest prior to calling. - */ - -static void copyVarCore(MprVar *dest, MprVar *src, int copyDepth) -{ - MprVarTrigger saveTrigger; - MprVar *srcProp, *destProp, *last; - char **srcArgs; - int i; - - mprAssert(dest); - mprAssert(src); - - if (dest == src) { - return; - } - - /* - * FUTURE: we should allow read-only triggers where the value is never - * stored in the object. Currently, triggers override the readonly - * status. - */ - - if (dest->type != MPR_TYPE_UNDEFINED && dest->readonly && !dest->trigger) { - mprAssert(0); - return; - } - - if (dest->type != MPR_TYPE_UNDEFINED) { - saveTrigger = dest->trigger; - freeVarStorage(dest, 0); - } else { - saveTrigger = 0; - } - - switch (src->type) { - default: - case MPR_TYPE_UNDEFINED: - case MPR_TYPE_NULL: - break; - - case MPR_TYPE_BOOL: - dest->boolean = src->boolean; - break; - - case MPR_TYPE_PTR: - /* we have to reference here so talloc structures survive a - copy */ - if (src->allocatedData) { - dest->ptr = talloc_reference(mprMemCtx(), src->ptr); - dest->allocatedData = 1; - } else { - dest->ptr = src->ptr; - } - break; - - case MPR_TYPE_STRING_CFUNCTION: - dest->cFunctionWithStrings = src->cFunctionWithStrings; - break; - - case MPR_TYPE_CFUNCTION: - dest->cFunction = src->cFunction; - break; - -#if BLD_FEATURE_FLOATING_POINT - case MPR_TYPE_FLOAT: - dest->floating = src->floating; - break; -#endif - - case MPR_TYPE_INT: - dest->integer = src->integer; - break; - -#if BLD_FEATURE_INT64 - case MPR_TYPE_INT64: - dest->integer64 = src->integer64; - break; -#endif - - case MPR_TYPE_OBJECT: - if (copyDepth == MPR_DEEP_COPY) { - - dest->properties = createProperties(src->name, - src->properties->hashSize); - dest->allocatedData = 1; - - for (i = 0; i < (int) src->properties->hashSize; i++) { - last = 0; - for (srcProp = src->properties->buckets[i]; srcProp; - srcProp = srcProp->forw) { - if (srcProp->visited) { - continue; - } - destProp = allocProperty(srcProp->name); - if (destProp == 0) { - mprAssert(destProp); - return; - } - - destProp->bucketIndex = i; - if (last) { - last->forw = destProp; - } else { - dest->properties->buckets[i] = destProp; - } - destProp->parentProperties = dest->properties; - - /* - * Recursively copy the object - */ - srcProp->visited = 1; - copyVarCore(destProp, srcProp, copyDepth); - srcProp->visited = 0; - last = destProp; - } - } - dest->properties->numItems = src->properties->numItems; - dest->properties->numDataItems = src->properties->numDataItems; - dest->allocatedData = 1; - - } else if (copyDepth == MPR_SHALLOW_COPY) { - dest->properties = src->properties; - adjustVarRefCount(src, 1); - dest->allocatedData = 1; - - } else { - dest->properties = src->properties; - dest->allocatedData = 0; - } - break; - - case MPR_TYPE_FUNCTION: - if (copyDepth != MPR_NO_COPY) { - dest->function.args = mprCreateArray(); - srcArgs = (char**) src->function.args->handles; - for (i = 0; i < src->function.args->max; i++) { - if (srcArgs[i]) { - mprAddToArray(dest->function.args, mprStrdup(srcArgs[i])); - } - } - dest->function.body = mprStrdup(src->function.body); - dest->allocatedData = 1; - } else { - dest->function.args = src->function.args; - dest->function.body = src->function.body; - dest->allocatedData = 0; - } - break; - - case MPR_TYPE_STRING: - if (src->string && copyDepth != MPR_NO_COPY) { - dest->string = mprStrdup(src->string); - dest->allocatedData = 1; - } else { - dest->string = src->string; - dest->allocatedData = 0; - } - break; - } - - dest->type = src->type; - dest->flags = src->flags; - dest->trigger = saveTrigger; - - /* - * Just for safety - */ - dest->spare = 0; -} - -/******************************************************************************/ -/* - * Copy an entire object including name. - */ - -void mprCopyVar(MprVar *dest, MprVar *src, int copyDepth) -{ - mprAssert(dest); - mprAssert(src); - - copyVarCore(dest, src, copyDepth); - - mprFree(dest->name); - dest->name = mprStrdup(src->name); - -#if VAR_DEBUG - if (src->type == MPR_TYPE_OBJECT) { - - mprFree(dest->fullName); - dest->fullName = mprStrdup(src->fullName); - - mprLog(7, "mprCopyVar: object \"%s\", FDQ \"%s\" 0x%x, refCount %d\n", - dest->name, dest->fullName, dest->properties, - dest->properties->refCount); - } -#endif -} - -/******************************************************************************/ -/* - * Copy an entire object including name. - */ - -void mprCopyVarValue(MprVar *dest, MprVar src, int copyDepth) -{ - mprAssert(dest); - - mprCopyVar(dest, &src, copyDepth); -} - -/******************************************************************************/ -/* - * Copy an object. This implements copy by reference for objects and copy by - * value for strings and other types. Caller must free dest prior to calling. - */ - -MprVar *mprDupVar(MprVar *src, int copyDepth) -{ - MprVar *dest; - - mprAssert(src); - - dest = (MprVar*) mprMalloc(sizeof(MprVar)); - memset(dest, 0, sizeof(MprVar)); - - mprCopyVar(dest, src, copyDepth); - return dest; -} - -/******************************************************************************/ -/* - * Convert a value to a text based representation of its value - * FUTURE -- conver this to use the format string in all cases. Allow - * arbitrary format strings. - */ - -void mprVarToString(char** out, int size, char *fmt, MprVar *obj) -{ - char *src; - - mprAssert(out); - - *out = NULL; - - if (obj->trigger) { - mprReadProperty(obj, 0); - } - - switch (obj->type) { - case MPR_TYPE_UNDEFINED: - /* FUTURE -- spec says convert to "undefined" */ - *out = mprStrdup(""); - break; - - case MPR_TYPE_NULL: - *out = mprStrdup("null"); - break; - - case MPR_TYPE_PTR: - mprAllocSprintf(out, size, "[Opaque Pointer %p]", obj->ptr); - break; - - case MPR_TYPE_BOOL: - if (obj->boolean) { - *out = mprStrdup("true"); - } else { - *out = mprStrdup("false"); - } - break; - -#if BLD_FEATURE_FLOATING_POINT - case MPR_TYPE_FLOAT: - if (fmt == NULL || *fmt == '\0') { - mprAllocSprintf(out, size, "%f", obj->floating); - } else { - mprAllocSprintf(out, size, fmt, obj->floating); - } - break; -#endif - - case MPR_TYPE_INT: - if (fmt == NULL || *fmt == '\0') { - mprAllocSprintf(out, size, "%d", obj->integer); - } else { - mprAllocSprintf(out, size, fmt, obj->integer); - } - break; - -#if BLD_FEATURE_INT64 - case MPR_TYPE_INT64: - if (fmt == NULL || *fmt == '\0') { -#if BLD_GOAHEAD_WEBSERVER - mprAllocSprintf(out, size, "%d", (int) obj->integer64); -#else - mprAllocSprintf(out, size, "%lld", (long long)obj->integer64); -#endif - } else { - mprAllocSprintf(out, size, fmt, obj->integer64); - } - break; -#endif - - case MPR_TYPE_CFUNCTION: - mprAllocSprintf(out, size, "[C Function]"); - break; - - case MPR_TYPE_STRING_CFUNCTION: - mprAllocSprintf(out, size, "[C StringFunction]"); - break; - - case MPR_TYPE_FUNCTION: - mprAllocSprintf(out, size, "[JavaScript Function]"); - break; - - case MPR_TYPE_OBJECT: - /* FUTURE -- really want: [object class: name] */ - mprAllocSprintf(out, size, "[object %s]", obj->name); - break; - - case MPR_TYPE_STRING: - src = obj->string; - - mprAssert(src); - if (fmt && *fmt) { - mprAllocSprintf(out, size, fmt, src); - - } else if (src == NULL) { - *out = mprStrdup("null"); - - } else { - *out = mprStrdup(src); - } - break; - - default: - mprAssert(0); - } -} - -/******************************************************************************/ -/* - * Parse a string based on formatting instructions and intelligently - * create a variable. - */ - -MprVar mprParseVar(char *buf, MprType preferredType) -{ - MprType type; - char *cp; - - mprAssert(buf); - - type = preferredType; - - if (preferredType == MPR_TYPE_UNDEFINED) { - if (*buf == '-') { - type = MPR_NUM_VAR; - - } else if (!isdigit((int) *buf)) { - if (strcmp(buf, "true") == 0 || strcmp(buf, "false") == 0) { - type = MPR_TYPE_BOOL; - } else { - type = MPR_TYPE_STRING; - } - - } else if (isdigit((int) *buf)) { - type = MPR_NUM_VAR; - cp = buf; - if (*cp && tolower(cp[1]) == 'x') { - cp = &cp[2]; - } - for (cp = buf; *cp; cp++) { - if (! isdigit((int) *cp)) { - break; - } - } - - if (*cp != '\0') { -#if BLD_FEATURE_FLOATING_POINT - if (*cp == '.' || tolower(*cp) == 'e') { - type = MPR_TYPE_FLOAT; - } else -#endif - { - type = MPR_NUM_VAR; - } - } - } - } - - switch (type) { - case MPR_TYPE_OBJECT: - case MPR_TYPE_UNDEFINED: - case MPR_TYPE_NULL: - case MPR_TYPE_PTR: - default: - break; - - case MPR_TYPE_BOOL: - return mprCreateBoolVar(buf[0] == 't' ? 1 : 0); - - case MPR_TYPE_INT: - return mprCreateIntegerVar(mprParseInteger(buf)); - -#if BLD_FEATURE_INT64 - case MPR_TYPE_INT64: - return mprCreateInteger64Var(mprParseInteger64(buf)); -#endif - - case MPR_TYPE_STRING: - if (strcmp(buf, "null") == 0) { - return mprCreateNullVar(); - } else if (strcmp(buf, "undefined") == 0) { - return mprCreateUndefinedVar(); - } - - return mprCreateStringVar(buf, 1); - -#if BLD_FEATURE_FLOATING_POINT - case MPR_TYPE_FLOAT: - return mprCreateFloatVar(atof(buf)); -#endif - - } - return mprCreateUndefinedVar(); -} - -/******************************************************************************/ -/* - * Convert the variable to a boolean. Only for primitive types. - */ - -bool mprVarToBool(const MprVar *vp) -{ - mprAssert(vp); - - switch (vp->type) { - case MPR_TYPE_UNDEFINED: - case MPR_TYPE_NULL: - case MPR_TYPE_STRING_CFUNCTION: - case MPR_TYPE_CFUNCTION: - case MPR_TYPE_FUNCTION: - case MPR_TYPE_OBJECT: - return 0; - - case MPR_TYPE_PTR: - return (vp->ptr != NULL); - - case MPR_TYPE_BOOL: - return vp->boolean; - -#if BLD_FEATURE_FLOATING_POINT - case MPR_TYPE_FLOAT: - return (vp->floating != 0 && !mprIsNan(vp->floating)); -#endif - - case MPR_TYPE_INT: - return (vp->integer != 0); - -#if BLD_FEATURE_INT64 - case MPR_TYPE_INT64: - return (vp->integer64 != 0); -#endif - - case MPR_TYPE_STRING: - mprAssert(vp->string); - return (vp->string[0] != '\0'); - } - - /* Not reached */ - return 0; -} - -/******************************************************************************/ -#if BLD_FEATURE_FLOATING_POINT -/* - * Convert the variable to a floating point number. Only for primitive types. - */ - -double mprVarToFloat(const MprVar *vp) -{ - mprAssert(vp); - - switch (vp->type) { - case MPR_TYPE_UNDEFINED: - case MPR_TYPE_NULL: - case MPR_TYPE_STRING_CFUNCTION: - case MPR_TYPE_CFUNCTION: - case MPR_TYPE_FUNCTION: - case MPR_TYPE_OBJECT: - case MPR_TYPE_PTR: - return 0; - - case MPR_TYPE_BOOL: - return (vp->boolean) ? 1.0 : 0.0; - - case MPR_TYPE_FLOAT: - return vp->floating; - - case MPR_TYPE_INT: - return (double) vp->integer; - -#if BLD_FEATURE_INT64 - case MPR_TYPE_INT64: - return (double) vp->integer64; -#endif - - case MPR_TYPE_STRING: - mprAssert(vp->string); - return atof(vp->string); - } - - /* Not reached */ - return 0; -} - -#endif -/******************************************************************************/ -/* - * Convert the variable to a number type. Only works for primitive types. - */ - -MprNum mprVarToNumber(const MprVar *vp) -{ -#if BLD_FEATURE_NUM_TYPE_ID == MPR_TYPE_INT64 - return mprVarToInteger64(vp); -#elif BLD_FEATURE_NUM_TYPE_ID == MPR_TYPE_FLOAT - return mprVarToFloat(vp); -#else - return mprVarToInteger(vp); -#endif -} - -/******************************************************************************/ -/* - * Convert the variable to a number type. Only works for primitive types. - */ - -MprNum mprParseNumber(char *s) -{ -#if BLD_FEATURE_NUM_TYPE_ID == MPR_TYPE_INT64 - return mprParseInteger64(s); -#elif BLD_FEATURE_NUM_TYPE_ID == MPR_TYPE_FLOAT - return mprParseFloat(s); -#else - return mprParseInteger(s); -#endif -} - -/******************************************************************************/ -#if BLD_FEATURE_INT64 -/* - * Convert the variable to an Integer64 type. Only works for primitive types. - */ - -int64 mprVarToInteger64(const MprVar *vp) -{ - mprAssert(vp); - - switch (vp->type) { - case MPR_TYPE_UNDEFINED: - case MPR_TYPE_NULL: - case MPR_TYPE_STRING_CFUNCTION: - case MPR_TYPE_CFUNCTION: - case MPR_TYPE_FUNCTION: - case MPR_TYPE_OBJECT: - case MPR_TYPE_PTR: - return 0; - - case MPR_TYPE_BOOL: - return (vp->boolean) ? 1 : 0; - -#if BLD_FEATURE_FLOATING_POINT - case MPR_TYPE_FLOAT: - if (mprIsNan(vp->floating)) { - return 0; - } - return (int64) vp->floating; -#endif - - case MPR_TYPE_INT: - return vp->integer; - - case MPR_TYPE_INT64: - return vp->integer64; - - case MPR_TYPE_STRING: - return mprParseInteger64(vp->string); - } - - /* Not reached */ - return 0; -} - -/******************************************************************************/ -/* - * Convert the string buffer to an Integer64. - */ - -int64 mprParseInteger64(char *str) -{ - char *cp; - int64 num64; - int radix, c, negative; - - mprAssert(str); - - cp = str; - num64 = 0; - negative = 0; - - if (*cp == '-') { - cp++; - negative = 1; - } - - /* - * Parse a number. Observe hex and octal prefixes (0x, 0) - */ - if (*cp != '0') { - /* - * Normal numbers (Radix 10) - */ - while (isdigit((int) *cp)) { - num64 = (*cp - '0') + (num64 * 10); - cp++; - } - } else { - cp++; - if (tolower(*cp) == 'x') { - cp++; - radix = 16; - while (*cp) { - c = tolower(*cp); - if (isdigit(c)) { - num64 = (c - '0') + (num64 * radix); - } else if (c >= 'a' && c <= 'f') { - num64 = (c - ('a' - 10)) + (num64 * radix); - } else { - break; - } - cp++; - } - - } else{ - radix = 8; - while (*cp) { - c = tolower(*cp); - if (isdigit(c) && c < '8') { - num64 = (c - '0') + (num64 * radix); - } else { - break; - } - cp++; - } - } - } - - if (negative) { - return 0 - num64; - } - return num64; -} - -#endif /* BLD_FEATURE_INT64 */ -/******************************************************************************/ -/* - * Convert the variable to an Integer type. Only works for primitive types. - */ - -int mprVarToInteger(const MprVar *vp) -{ - mprAssert(vp); - - switch (vp->type) { - case MPR_TYPE_UNDEFINED: - case MPR_TYPE_NULL: - case MPR_TYPE_STRING_CFUNCTION: - case MPR_TYPE_CFUNCTION: - case MPR_TYPE_FUNCTION: - case MPR_TYPE_OBJECT: - case MPR_TYPE_PTR: - return 0; - - case MPR_TYPE_BOOL: - return (vp->boolean) ? 1 : 0; - -#if BLD_FEATURE_FLOATING_POINT - case MPR_TYPE_FLOAT: - if (mprIsNan(vp->floating)) { - return 0; - } - return (int) vp->floating; -#endif - - case MPR_TYPE_INT: - return vp->integer; - -#if BLD_FEATURE_INT64 - case MPR_TYPE_INT64: - return (int) vp->integer64; -#endif - - case MPR_TYPE_STRING: - return mprParseInteger(vp->string); - } - - /* Not reached */ - return 0; -} - -/******************************************************************************/ -/* - * Convert the string buffer to an Integer. - */ - -int mprParseInteger(char *str) -{ - char *cp; - int num; - int radix, c, negative; - - mprAssert(str); - - cp = str; - num = 0; - negative = 0; - - if (*cp == '-') { - cp++; - negative = 1; - } - - /* - * Parse a number. Observe hex and octal prefixes (0x, 0) - */ - if (*cp != '0') { - /* - * Normal numbers (Radix 10) - */ - while (isdigit((int) *cp)) { - num = (*cp - '0') + (num * 10); - cp++; - } - } else { - cp++; - if (tolower(*cp) == 'x') { - cp++; - radix = 16; - while (*cp) { - c = tolower(*cp); - if (isdigit(c)) { - num = (c - '0') + (num * radix); - } else if (c >= 'a' && c <= 'f') { - num = (c - ('a' - 10)) + (num * radix); - } else { - break; - } - cp++; - } - - } else{ - radix = 8; - while (*cp) { - c = tolower(*cp); - if (isdigit(c) && c < '8') { - num = (c - '0') + (num * radix); - } else { - break; - } - cp++; - } - } - } - - if (negative) { - return 0 - num; - } - return num; -} - -/******************************************************************************/ -#if BLD_FEATURE_FLOATING_POINT -/* - * Convert the string buffer to an Floating. - */ - -double mprParseFloat(char *str) -{ - return atof(str); -} - -/******************************************************************************/ - -bool mprIsNan(double f) -{ -#if WIN - return _isnan(f); -#elif VXWORKS - /* FUTURE */ - return (0); -#elif defined(FP_NAN) - return (f == FP_NAN); -#else - return 0; -#endif -} -/******************************************************************************/ - -bool mprIsInfinite(double f) -{ -#if WIN - return !_finite(f); -#elif VXWORKS - /* FUTURE */ - return (0); -#elif defined(FP_INFINITE) - return (f == FP_INFINITE); -#else - return 0; -#endif -} - -#endif /* BLD_FEATURE_FLOATING_POINT */ -/******************************************************************************/ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/lib/appweb/mpr/var.h b/source4/lib/appweb/mpr/var.h deleted file mode 100644 index 98313c0476..0000000000 --- a/source4/lib/appweb/mpr/var.h +++ /dev/null @@ -1,487 +0,0 @@ -/* - * @file var.h - * @brief MPR Universal Variable Type - * @copy default.m - * - * Copyright (c) Mbedthis Software LLC, 2003-2005. All Rights Reserved. - * Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved. - * - * This software is distributed under commercial and open source licenses. - * You may use the GPL open source license described below or you may acquire - * a commercial license from Mbedthis Software. You agree to be fully bound - * by the terms of either license. Consult the LICENSE.TXT distributed with - * this software for full details. - * - * This software is open source; 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. See the GNU General Public License for more - * details at: http://www.mbedthis.com/downloads/gplLicense.html - * - * This program is distributed WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * This GPL license does NOT permit incorporating this software into - * proprietary programs. If you are unable to comply with the GPL, you must - * acquire a commercial license to use this software. Commercial licenses - * for this software and support services are available from Mbedthis - * Software at http://www.mbedthis.com - * - * @end - */ - -/******************************* Documentation ********************************/ -/* - * Variables can efficiently store primitive types and can hold references to - * objects. Objects can store properties which are themselves variables. - * Properties can be primitive data types, other objects or functions. - * Properties are indexed by a character name. A variable may store one of - * the following types: - * - * string, integer, integer-64bit, C function, C function with string args, - * Javascript function, Floating point number, boolean value, Undefined - * value and the Null value. - * - * Variables have names while objects may be referenced by multiple variables. - * Objects use reference counting for garbage collection. - * - * This module is not thread safe for performance and compactness. It relies - * on upper modules to provide thread synchronization as required. The API - * provides primitives to get variable/object references or to get copies of - * variables which will help minimize required lock times. - */ - -#ifndef _h_MPR_VAR -#define _h_MPR_VAR 1 - -/********************************* Includes ***********************************/ - -#include "miniMpr.h" - -/********************************** Defines ***********************************/ - -/* - * Define VAR_DEBUG if you want to track objects. However, this code is not - * thread safe and you need to run the server single threaded. - * - * #define VAR_DEBUG 1 - */ - -#ifdef __cplusplus -extern "C" { -#endif -/* - * Forward declare types - */ -struct MprProperties; -struct MprVar; - -/* - * Possible variable types. Don't use enum because we need to be able to - * do compile time conditional compilation on BLD_FEATURE_NUM_TYPE_ID. - */ -typedef int MprType; -#define MPR_TYPE_UNDEFINED 0 /* Undefined. No value has been set. */ -#define MPR_TYPE_NULL 1 /* Value defined to be null. */ -#define MPR_TYPE_BOOL 2 /* Boolean type. */ -#define MPR_TYPE_CFUNCTION 3 /* C function or C++ method */ -#define MPR_TYPE_FLOAT 4 /* Floating point number */ -#define MPR_TYPE_INT 5 /* Integer number */ -#define MPR_TYPE_INT64 6 /* 64-bit Integer number */ -#define MPR_TYPE_OBJECT 7 /* Object reference */ -#define MPR_TYPE_FUNCTION 8 /* JavaScript function */ -#define MPR_TYPE_STRING 9 /* String (immutable) */ -#define MPR_TYPE_STRING_CFUNCTION 10 /* C/C++ function with string args */ -#define MPR_TYPE_PTR 11 /* Opaque pointer */ - -/* - * Create a type for the default number type - * Config.h will define the default number type. For example: - * - * BLD_FEATURE_NUM_TYPE=int - * BLD_FEATURE_NUM_TYPE_ID=MPR_TYPE_INT - */ - -/** - * Set to the type used for MPR numeric variables. Will equate to int, int64 - * or double. - */ -typedef BLD_FEATURE_NUM_TYPE MprNum; - -/** - * Set to the MPR_TYPE used for MPR numeric variables. Will equate to - * MPR_TYPE_INT, MPR_TYPE_INT64 or MPR_TYPE_FLOAT. - */ -#define MPR_NUM_VAR BLD_FEATURE_NUM_TYPE_ID -#define MPR_TYPE_NUM BLD_FEATURE_NUM_TYPE_ID - -/* - * Return TRUE if a variable is a function type - */ -#define mprVarIsFunction(type) \ - (type == MPR_TYPE_FUNCTION || type == MPR_TYPE_STRING_CFUNCTION || \ - type == MPR_TYPE_CFUNCTION) - -/* - * Return TRUE if a variable is a numeric type - */ -#define mprVarIsNumber(type) \ - (type == MPR_TYPE_INT || type == MPR_TYPE_INT64 || type == MPR_TYPE_FLOAT) - -/* - * Return TRUE if a variable is a boolean - */ -#define mprVarIsBoolean(type) \ - (type == MPR_TYPE_BOOL) -#define mprVarIsString(type) \ - (type == MPR_TYPE_STRING) -#define mprVarIsObject(type) \ - (type == MPR_TYPE_OBJECT) -#define mprVarIsFloating(type) \ - (type == MPR_TYPE_FLOAT) -#define mprVarIsPtr(type) \ - (type == MPR_TYPE_PTR) -#define mprVarIsUndefined(var) \ - ((var)->type == MPR_TYPE_UNDEFINED) -#define mprVarIsNull(var) \ - ((var)->type == MPR_TYPE_NULL) -#define mprVarIsValid(var) \ - (((var)->type != MPR_TYPE_NULL) && ((var)->type != MPR_TYPE_UNDEFINED)) - -#define MPR_VAR_MAX_RECURSE 5 /* Max object loops */ - -#if BLD_FEATURE_SQUEEZE -#define MPR_MAX_VAR 64 /* Max var full name */ -#else -#define MPR_MAX_VAR 512 -#endif - -/* - * Function signatures - */ -typedef int MprVarHandle; -typedef int (*MprCFunction)(MprVarHandle userHandle, int argc, - struct MprVar **argv); -typedef int (*MprStringCFunction)(MprVarHandle userHandle, int argc, - char **argv); - -/* - * Triggers - */ -typedef enum { - MPR_VAR_WRITE, /* This property is being updated */ - MPR_VAR_READ, /* This property is being read */ - MPR_VAR_CREATE_PROPERTY, /* A property is being created */ - MPR_VAR_DELETE_PROPERTY, /* A property is being deleted */ - MPR_VAR_DELETE /* This object is being deleted */ -} MprVarTriggerOp; - -/* - * Trigger function return codes. - */ -typedef enum { - MPR_TRIGGER_ABORT, /* Abort the current operation */ - MPR_TRIGGER_USE_NEW_VALUE, /* Proceed and use the newValue */ - MPR_TRIGGER_PROCEED /* Proceed with the operation */ -} MprVarTriggerStatus; - -/* - * The MprVarTrigger arguments have the following meaning: - * - * op The operation being performed. See MprVarTriggerOp. - * parentProperties Pointer to the MprProperties structure. - * vp Pointer to the property that registered the trigger. - * newValue New value (see below for more details). - * copyDepth Specify what data items to copy. - * - * For VAR_READ, newVar is set to a temporary variable that the trigger - * function may assign a value to be returned instead of the actual - * property value. - * For VAR_WRITE, newValue holds the new value. The old existing value may be - * accessed via vp. - * For DELETE_PROPERTY, vp is the property being deleted. newValue is null. - * For ADD_PROPERTY, vp is set to the property being added and newValue holds - * the new value. - */ -typedef MprVarTriggerStatus (*MprVarTrigger)(MprVarTriggerOp op, - struct MprProperties *parentProperties, struct MprVar *vp, - struct MprVar *newValue, int copyDepth); - -/* - * mprCreateFunctionVar flags - */ -/** Use the alternate handle on function callbacks */ -#define MPR_VAR_ALT_HANDLE 0x1 - -/** Use the script handle on function callbacks */ -#define MPR_VAR_SCRIPT_HANDLE 0x2 - -/* - * Useful define for the copyDepth argument - */ -/** Don't copy any data. Copy only the variable name */ -#define MPR_NO_COPY 0 - -/** Copy strings. Increment object reference counts. */ -#define MPR_SHALLOW_COPY 1 - -/** Copy strings and do complete object copies. */ -#define MPR_DEEP_COPY 2 - -/* - * GetFirst / GetNext flags - */ -/** Step into data properties. */ -#define MPR_ENUM_DATA 0x1 - -/** Step into functions properties. */ -#define MPR_ENUM_FUNCTIONS 0x2 - -/* - * Collection type to hold properties in an object - */ -typedef struct MprProperties { /* Collection of properties */ -#if VAR_DEBUG - struct MprProperties *next; /* Linked list */ - struct MprProperties *prev; /* Linked list */ - char name[32]; /* Debug name */ -#endif - struct MprVar **buckets; /* Hash chains */ - int numItems; /* Total count of items */ - /* FUTURE - Better way of doing this */ - int numDataItems; /* Enumerable data items */ - uint hashSize : 8; /* Size of the hash table */ - /* FUTURE -- increase size of refCount */ - uint refCount : 8; /* References to this property*/ - /* FUTURE - make these flags */ - uint deleteProtect : 8; /* Don't recursively delete */ - uint visited : 8; /* Node has been processed */ -} MprProperties; - -/* - * Universal Variable Type - */ -typedef struct MprVar { - /* FUTURE - remove name to outside reference */ - MprStr name; /* Property name */ - /* FUTURE - remove */ - MprStr fullName; /* Full object name */ - /* FUTURE - make part of the union */ - MprProperties *properties; /* Pointer to properties */ - - /* - * Packed bit field - */ - MprType type : 8; /* Selector into union */ - uint bucketIndex : 8; /* Copy of bucket index */ - - uint flags : 5; /* Type specific flags */ - uint allocatedData : 1; /* Data needs freeing */ - uint readonly : 1; /* Unmodifiable */ - uint deleteProtect : 1; /* Don't recursively delete */ - - uint visited : 1; /* Node has been processed */ - uint allocatedVar : 1; /* Var needs freeing */ - uint spare : 6; /* Unused */ - - struct MprVar *forw; /* Hash table linkage */ - MprVarTrigger trigger; /* Trigger function */ - -#if UNUSED && KEEP - struct MprVar *baseClass; /* Pointer to class object */ -#endif - MprProperties *parentProperties; /* Pointer to parent object */ - - /* - * Union of primitive types. When debugging on Linux, don't use unions - * as the gdb debugger can't display them. - */ -#if 0 && !BLD_DEBUG && !LINUX && !VXWORKS - union { -#endif - bool boolean; -#if BLD_FEATURE_FLOATING_POINT - double floating; -#endif - int integer; -#if BLD_FEATURE_INT64 - int64 integer64; -#endif - struct { /* Javascript functions */ - MprArray *args; /* Null terminated */ - char *body; - } function; - struct { /* Function with MprVar args */ - MprCFunction fn; - void *thisPtr; - } cFunction; - struct { /* Function with string args */ - MprStringCFunction fn; - void *thisPtr; - } cFunctionWithStrings; - MprStr string; /* Allocated string */ - void *ptr; /* Opaque pointer */ -#if 0 && !BLD_DEBUG && !LINUX && !VXWORKS - }; -#endif -} MprVar; - -/* - * Define a field macro so code an use numbers in a "generic" fashion. - */ -#if MPR_NUM_VAR == MPR_TYPE_INT || DOXYGEN -/* Default numeric type */ -#define mprNumber integer -#endif -#if MPR_NUM_VAR == MPR_TYPE_INT64 -/* Default numeric type */ -#define mprNumber integer64 -#endif -#if MPR_NUM_VAR == MPR_TYPE_FLOAT -/* Default numeric type */ -#define mprNumber floating -#endif - -typedef BLD_FEATURE_NUM_TYPE MprNumber; - -/********************************* Prototypes *********************************/ -/* - * Variable constructors and destructors - */ -extern MprVar mprCreateObjVar(const char *name, int hashSize); -extern MprVar mprCreateBoolVar(bool value); -extern MprVar mprCreateCFunctionVar(MprCFunction fn, void *thisPtr, - int flags); -#if BLD_FEATURE_FLOATING_POINT -extern MprVar mprCreateFloatVar(double value); -#endif -extern MprVar mprCreateIntegerVar(int value); -#if BLD_FEATURE_INT64 -extern MprVar mprCreateInteger64Var(int64 value); -#endif -extern MprVar mprCreateFunctionVar(char *args, char *body, int flags); -extern MprVar mprCreateNullVar(void); -extern MprVar mprCreateNumberVar(MprNumber value); -extern MprVar mprCreateStringCFunctionVar(MprStringCFunction fn, - void *thisPtr, int flags); -extern MprVar mprCreateStringVar(const char *value, bool allocate); -extern MprVar mprCreateUndefinedVar(void); -extern MprVar mprCreatePtrVar(void *ptr); -extern bool mprDestroyVar(MprVar *vp); -extern bool mprDestroyAllVars(MprVar* vp); -extern MprType mprGetVarType(MprVar *vp); - -/* - * Copy - */ -extern void mprCopyVar(MprVar *dest, MprVar *src, int copyDepth); -extern void mprCopyVarValue(MprVar *dest, MprVar src, int copyDepth); -extern MprVar *mprDupVar(MprVar *src, int copyDepth); - -/* - * Manage vars - */ -extern MprVarTrigger - mprAddVarTrigger(MprVar *vp, MprVarTrigger fn); -extern int mprGetVarRefCount(MprVar *vp); -extern void mprSetVarDeleteProtect(MprVar *vp, int deleteProtect); -extern void mprSetVarFullName(MprVar *vp, char *name); -extern void mprSetVarReadonly(MprVar *vp, int readonly); -extern void mprSetVarName(MprVar *vp, char *name); - -/* - * Create properties and return a reference to the property. - */ -extern MprVar *mprCreateProperty(MprVar *obj, const char *property, - MprVar *newValue); -extern MprVar *mprCreatePropertyValue(MprVar *obj, const char *property, - MprVar newValue); -extern int mprDeleteProperty(MprVar *obj, const char *property); - -/* - * Get/Set properties. Set will update/create. - */ -extern MprVar *mprGetProperty(MprVar *obj, const char *property, - MprVar *value); -extern MprVar *mprSetProperty(MprVar *obj, const char *property, - MprVar *value); -extern MprVar *mprSetPropertyValue(MprVar *obj, const char *property, - MprVar value); - -/* - * Directly read/write property values (the property must already exist) - * For mprCopyProperty, mprDestroyVar must always called on the var. - */ -extern int mprReadProperty(MprVar *prop, MprVar *value); -extern int mprWriteProperty(MprVar *prop, MprVar *newValue); -extern int mprWritePropertyValue(MprVar *prop, MprVar newValue); - -/* - * Copy a property. NOTE: reverse of most other args: (dest, src) - */ -extern int mprCopyProperty(MprVar *dest, MprVar *prop, int copyDepth); - -/* - * Enumerate properties - */ -extern MprVar *mprGetFirstProperty(MprVar *obj, int includeFlags); -extern MprVar *mprGetNextProperty(MprVar *obj, MprVar *currentProperty, - int includeFlags); - -/* - * Query properties characteristics - */ -extern int mprGetPropertyCount(MprVar *obj, int includeFlags); - -/* - * Conversion routines - */ -extern MprVar mprParseVar(char *str, MprType prefType); -extern MprNum mprVarToNumber(const MprVar *vp); -extern int mprVarToInteger(const MprVar *vp); -#if BLD_FEATURE_INT64 -extern int64 mprVarToInteger64(const MprVar *vp); -#endif -extern bool mprVarToBool(const MprVar *vp); -#if BLD_FEATURE_FLOATING_POINT -extern double mprVarToFloat(const MprVar *vp); -#endif -extern void mprVarToString(char** buf, int size, char *fmt, MprVar *vp); - -/* - * Parsing and utility routines - */ -extern MprNum mprParseNumber(char *str); -extern int mprParseInteger(char *str); - -#if BLD_FEATURE_INT64 -extern int64 mprParseInteger64(char *str); -#endif - -#if BLD_FEATURE_FLOATING_POINT -extern double mprParseFloat(char *str); -extern bool mprIsInfinite(double f); -extern bool mprIsNan(double f); -#endif - -#if VAR_DEBUG -extern void mprPrintObjects(char *msg); -extern void mprPrintObjRefCount(MprVar *vp); -#endif - -#ifdef __cplusplus -} -#endif - -/*****************************************************************************/ -#endif /* _h_MPR_VAR */ - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim:tw=78 - * vim600: sw=4 ts=4 fdm=marker - * vim<600: sw=4 ts=4 - */ diff --git a/source4/main.mk b/source4/main.mk index 1fbffbd06e..ea410bd055 100644 --- a/source4/main.mk +++ b/source4/main.mk @@ -18,7 +18,6 @@ mkinclude lib/events/config.mk mkinclude lib/cmdline/config.mk mkinclude lib/socket_wrapper/config.mk mkinclude lib/nss_wrapper/config.mk -mkinclude lib/appweb/config.mk mkinclude lib/stream/config.mk mkinclude lib/util/config.mk mkinclude lib/tdr/config.mk @@ -47,6 +46,5 @@ mkinclude torture/config.mk mkinclude librpc/config.mk mkinclude client/config.mk mkinclude libcli/config.mk -mkinclude scripting/ejs/config.mk mkinclude scripting/python/config.mk mkinclude kdc/config.mk diff --git a/source4/pidl/lib/Parse/Pidl/Samba4/EJS.pm b/source4/pidl/lib/Parse/Pidl/Samba4/EJS.pm deleted file mode 100644 index efb3f2858d..0000000000 --- a/source4/pidl/lib/Parse/Pidl/Samba4/EJS.pm +++ /dev/null @@ -1,874 +0,0 @@ -################################################### -# EJS function wrapper generator -# Copyright jelmer@samba.org 2005 -# Copyright Andrew Tridgell 2005 -# released under the GNU GPL - -package Parse::Pidl::Samba4::EJS; - -use Exporter; -@ISA = qw(Exporter); -@EXPORT_OK = qw(check_null_pointer fn_declare TypeFunctionName); - -use strict; -use Parse::Pidl::Typelist qw(typeHasBody); -use Parse::Pidl::CUtil qw(get_pointer_to get_value_of); -use Parse::Pidl::Util qw(has_property ParseExpr); -use Parse::Pidl::NDR qw(GetPrevLevel GetNextLevel); -use Parse::Pidl::Samba4::Header qw(GenerateStructEnv GenerateFunctionInEnv - GenerateFunctionOutEnv); - -use vars qw($VERSION); -$VERSION = '0.01'; - -sub new($) { - my ($class) = @_; - my $self = { res => "", res_hdr => "", tabs => "", constants => {}}; - bless($self, $class); -} - -sub pidl_hdr ($$) -{ - my $self = shift; - $self->{res_hdr} .= shift; -} - -sub pidl($$) -{ - my ($self, $d) = @_; - if ($d) { - $self->{res} .= $self->{tabs}; - $self->{res} .= $d; - } - $self->{res} .= "\n"; -} - -sub indent($) -{ - my ($self) = @_; - $self->{tabs} .= "\t"; -} - -sub deindent($) -{ - my ($self) = @_; - $self->{tabs} = substr($self->{tabs}, 0, -1); -} - -##################################################################### -# check that a variable we get from ParseExpr isn't a null pointer -sub check_null_pointer($$) -{ - my ($self, $size) = @_; - if ($size =~ /^\*/) { - my $size2 = substr($size, 1); - $self->pidl("if ($size2 == NULL) return NT_STATUS_INVALID_PARAMETER_MIX;"); - } -} - -##################################################################### -# work out is a parse function should be declared static or not -sub fn_declare($$$) -{ - my ($self,$fn,$decl) = @_; - - if (has_property($fn, "public")) { - $self->pidl_hdr("$decl;\n"); - $self->pidl("_PUBLIC_ $decl"); - } else { - $self->pidl("static $decl"); - } -} - -########################### -# pull a scalar element -sub EjsPullScalar($$$$$$$) -{ - my ($self, $e, $l, $var, $name, $env) = @_; - - return if (has_property($e, "value")); - - if (ref($e->{TYPE}) eq "HASH" and not defined($e->{TYPE}->{NAME})) { - $self->EjsTypePull($e->{TYPE}, $var); - } else { - my $pl = Parse::Pidl::NDR::GetPrevLevel($e, $l); - $var = get_pointer_to($var); - # have to handle strings specially :( - if (Parse::Pidl::Typelist::scalar_is_reference($e->{TYPE}) - and (defined($pl) and $pl->{TYPE} eq "POINTER")) { - $var = get_pointer_to($var); - } - - my $t; - if (ref($e->{TYPE}) eq "HASH") { - $t = "$e->{TYPE}->{TYPE}_$e->{TYPE}->{NAME}"; - } else { - $t = $e->{TYPE}; - } - $self->pidl("EJS_CHECK(ejs_pull_$t(ejs, v, $name, $var));"); - } -} - -########################### -# pull a pointer element -sub EjsPullPointer($$$$$$) -{ - my ($self, $e, $l, $var, $name, $env) = @_; - $self->pidl("if (ejs_pull_null(ejs, v, $name)) {"); - $self->indent; - if ($l->{POINTER_TYPE} eq "ref") { - $self->pidl("return NT_STATUS_INVALID_PARAMETER_MIX;"); - } else { - $self->pidl("$var = NULL;"); - } - $self->deindent; - $self->pidl("} else {"); - $self->indent; - $self->pidl("EJS_ALLOC(ejs, $var);"); - $var = get_value_of($var); - $self->EjsPullElement($e, GetNextLevel($e, $l), $var, $name, $env); - $self->deindent; - $self->pidl("}"); -} - -########################### -# pull a string element -sub EjsPullString($$$$$$) -{ - my ($self, $e, $l, $var, $name, $env) = @_; - my $pl = GetPrevLevel($e, $l); - $var = get_pointer_to($var); - if (defined($pl) and $pl->{TYPE} eq "POINTER") { - $var = get_pointer_to($var); - } - $self->pidl("EJS_CHECK(ejs_pull_string(ejs, v, $name, $var));"); -} - -########################### -# pull an array element -sub EjsPullArray($$$$$$) -{ - my ($self, $e, $l, $var, $name, $env) = @_; - my $nl = GetNextLevel($e, $l); - my $length = ParseExpr($l->{LENGTH_IS}, $env, $e); - my $size = ParseExpr($l->{SIZE_IS}, $env, $e); - my $pl = GetPrevLevel($e, $l); - if ($pl && $pl->{TYPE} eq "POINTER") { - $var = get_pointer_to($var); - } - # uint8 arrays are treated as data blobs - if ($nl->{TYPE} eq 'DATA' && $e->{TYPE} eq 'uint8') { - if (!$l->{IS_FIXED}) { - $self->check_null_pointer($size); - $self->pidl("EJS_ALLOC_N(ejs, $var, $size);"); - } - $self->check_null_pointer($length); - $self->pidl("ejs_pull_array_uint8(ejs, v, $name, $var, $length);"); - return; - } - my $avar = $var . "[i]"; - $self->pidl("{"); - $self->indent; - $self->pidl("uint32_t i;"); - if (!$l->{IS_FIXED}) { - $self->pidl("EJS_ALLOC_N(ejs, $var, $size);"); - } - $self->pidl("for (i=0;i<$length;i++) {"); - $self->indent; - $self->pidl("char *id = talloc_asprintf(ejs, \"%s.%u\", $name, i);"); - $self->EjsPullElement($e, $nl, $avar, "id", $env); - $self->pidl("talloc_free(id);"); - $self->deindent; - $self->pidl("}"); - $self->pidl("ejs_push_uint32(ejs, v, $name \".length\", &i);"); - $self->deindent; - $self->pidl("}"); -} - -########################### -# pull a switch element -sub EjsPullSwitch($$$$$$) -{ - my ($self, $e, $l, $var, $name, $env) = @_; - my $switch_var = ParseExpr($l->{SWITCH_IS}, $env, $e); - $self->pidl("ejs_set_switch(ejs, $switch_var);"); - $self->EjsPullElement($e, GetNextLevel($e, $l), $var, $name, $env); -} - -########################### -# pull a structure element -sub EjsPullElement($$$$$$) -{ - my ($self, $e, $l, $var, $name, $env) = @_; - if (($l->{TYPE} eq "POINTER")) { - $self->EjsPullPointer($e, $l, $var, $name, $env); - } elsif (has_property($e, "charset")) { - $self->EjsPullString($e, $l, $var, $name, $env); - } elsif ($l->{TYPE} eq "ARRAY") { - $self->EjsPullArray($e, $l, $var, $name, $env); - } elsif ($l->{TYPE} eq "DATA") { - $self->EjsPullScalar($e, $l, $var, $name, $env); - } elsif (($l->{TYPE} eq "SWITCH")) { - $self->EjsPullSwitch($e, $l, $var, $name, $env); - } else { - $self->pidl("return ejs_panic(ejs, \"unhandled pull type $l->{TYPE}\");"); - } -} - -############################################# -# pull a structure/union element at top level -sub EjsPullElementTop($$$) -{ - my ($self, $e, $env) = @_; - my $l = $e->{LEVELS}[0]; - my $var = ParseExpr($e->{NAME}, $env, $e); - my $name = "\"$e->{NAME}\""; - $self->EjsPullElement($e, $l, $var, $name, $env); -} - -########################### -# pull a struct -sub EjsStructPull($$$) -{ - my ($self, $d, $varname) = @_; - my $env = GenerateStructEnv($d, $varname); - $self->pidl("EJS_CHECK(ejs_pull_struct_start(ejs, &v, name));"); - foreach my $e (@{$d->{ELEMENTS}}) { - $self->EjsPullElementTop($e, $env); - } -} - -########################### -# pull a union -sub EjsUnionPull($$$) -{ - my ($self, $d, $varname) = @_; - my $have_default = 0; - $self->pidl("EJS_CHECK(ejs_pull_struct_start(ejs, &v, name));"); - $self->pidl("switch (ejs->switch_var) {"); - $self->indent; - foreach my $e (@{$d->{ELEMENTS}}) { - if ($e->{CASE} eq "default") { - $have_default = 1; - } - $self->pidl("$e->{CASE}:"); - $self->indent; - if ($e->{TYPE} ne "EMPTY") { - $self->EjsPullElementTop($e, { $e->{NAME} => "$varname->$e->{NAME}"}); - } - $self->pidl("break;"); - $self->deindent; - } - if (! $have_default) { - $self->pidl("default:"); - $self->indent; - $self->pidl("return ejs_panic(ejs, \"Bad switch value\");"); - $self->deindent; - } - $self->deindent; - $self->pidl("}"); -} - -############################################## -# put the enum elements in the constants array -sub EjsEnumConstant($$) -{ - my ($self, $d) = @_; - return unless (defined($d->{ELEMENTS})); - my $v = 0; - foreach my $e (@{$d->{ELEMENTS}}) { - my $el = $e; - chomp $el; - if ($el =~ /^(.*)=\s*(.*)\s*$/) { - $el = $1; - $v = $2; - } - $self->{constants}->{$el} = $v; - $v++; - } -} - -########################### -# pull a enum -sub EjsEnumPull($$$) -{ - my ($self, $d, $varname) = @_; - $self->EjsEnumConstant($d); - $self->pidl("unsigned e;"); - $self->pidl("EJS_CHECK(ejs_pull_enum(ejs, v, name, &e));"); - $self->pidl("*$varname = e;"); -} - -########################### -# pull a bitmap -sub EjsBitmapPull($$$) -{ - my ($self, $d, $varname) = @_; - my $type_fn = $d->{BASE_TYPE}; - $self->pidl("EJS_CHECK(ejs_pull_$type_fn(ejs, v, name, $varname));"); -} - -sub EjsTypePullFunction($$$) -{ - sub EjsTypePullFunction($$$); - my ($self, $d, $name) = @_; - return if (has_property($d, "noejs")); - - if ($d->{TYPE} eq "TYPEDEF") { - $self->EjsTypePullFunction($d->{DATA}, $name); - return; - } - - if ($d->{TYPE} eq "STRUCT") { - $self->fn_declare($d, "NTSTATUS ejs_pull_$name(struct ejs_rpc *ejs, struct MprVar *v, const char *name, struct $name *r)"); - } elsif ($d->{TYPE} eq "UNION") { - $self->fn_declare($d, "NTSTATUS ejs_pull_$name(struct ejs_rpc *ejs, struct MprVar *v, const char *name, union $name *r)"); - } elsif ($d->{TYPE} eq "ENUM") { - $self->fn_declare($d, "NTSTATUS ejs_pull_$name(struct ejs_rpc *ejs, struct MprVar *v, const char *name, enum $name *r)"); - } elsif ($d->{TYPE} eq "BITMAP") { - my($type_decl) = Parse::Pidl::Typelist::mapTypeName($d->{BASE_TYPE}); - $self->fn_declare($d, "NTSTATUS ejs_pull_$name(struct ejs_rpc *ejs, struct MprVar *v, const char *name, $type_decl *r)"); - } - $self->pidl("{"); - $self->indent; - - $self->EjsTypePull($d, "r"); - - $self->pidl("return NT_STATUS_OK;"); - $self->deindent; - $self->pidl("}\n"); -} - -sub EjsTypePull($$$) -{ - my ($self, $d, $varname) = @_; - if ($d->{TYPE} eq 'STRUCT') { - $self->EjsStructPull($d, $varname); - } elsif ($d->{TYPE} eq 'UNION') { - $self->EjsUnionPull($d, $varname); - } elsif ($d->{TYPE} eq 'ENUM') { - $self->EjsEnumPull($d, $varname); - } elsif ($d->{TYPE} eq 'BITMAP') { - $self->EjsBitmapPull($d, $varname); - } else { - warn "Unhandled pull $varname of type $d->{TYPE}"; - } -} - -##################### -# generate a function -sub EjsPullFunction($$) -{ - my ($self, $d) = @_; - my $env = GenerateFunctionInEnv($d); - my $name = $d->{NAME}; - - $self->pidl("\nstatic NTSTATUS ejs_pull_$name(struct ejs_rpc *ejs, struct MprVar *v, struct $name *r)"); - $self->pidl("{"); - $self->indent; - $self->pidl("EJS_CHECK(ejs_pull_struct_start(ejs, &v, \"input\"));"); - - # we pull non-array elements before array elements as arrays - # may have length_is() or size_is() properties that depend - # on the non-array elements - foreach my $e (@{$d->{ELEMENTS}}) { - next unless (grep(/in/, @{$e->{DIRECTION}})); - next if (has_property($e, "length_is") || has_property($e, "size_is")); - $self->EjsPullElementTop($e, $env); - } - - foreach my $e (@{$d->{ELEMENTS}}) { - next unless (grep(/in/, @{$e->{DIRECTION}})); - next unless (has_property($e, "length_is") || has_property($e, "size_is")); - $self->EjsPullElementTop($e, $env); - } - - $self->pidl("return NT_STATUS_OK;"); - $self->deindent; - $self->pidl("}\n"); -} - -########################### -# push a scalar element -sub EjsPushScalar($$$$$$) -{ - my ($self, $e, $l, $var, $name, $env) = @_; - - if (ref($e->{TYPE}) eq "HASH" and not defined($e->{TYPE}->{NAME})) { - $self->EjsTypePush($e->{TYPE}, get_pointer_to($var)); - } else { - # have to handle strings specially :( - my $pl = GetPrevLevel($e, $l); - - if ((not Parse::Pidl::Typelist::scalar_is_reference($e->{TYPE})) - or (defined($pl) and $pl->{TYPE} eq "POINTER")) { - $var = get_pointer_to($var); - } - - $self->pidl("EJS_CHECK(".TypeFunctionName("ejs_push", $e->{TYPE})."(ejs, v, $name, $var));"); - } -} - -########################### -# push a string element -sub EjsPushString($$$$$$) -{ - my ($self, $e, $l, $var, $name, $env) = @_; - my $pl = GetPrevLevel($e, $l); - if (defined($pl) and $pl->{TYPE} eq "POINTER") { - $var = get_pointer_to($var); - } - $self->pidl("EJS_CHECK(ejs_push_string(ejs, v, $name, $var));"); -} - -########################### -# push a pointer element -sub EjsPushPointer($$$$$$) -{ - my ($self, $e, $l, $var, $name, $env) = @_; - $self->pidl("if (NULL == $var) {"); - $self->indent; - if ($l->{POINTER_TYPE} eq "ref") { - $self->pidl("return NT_STATUS_INVALID_PARAMETER_MIX;"); - } else { - $self->pidl("EJS_CHECK(ejs_push_null(ejs, v, $name));"); - } - $self->deindent; - $self->pidl("} else {"); - $self->indent; - $var = get_value_of($var); - $self->EjsPushElement($e, GetNextLevel($e, $l), $var, $name, $env); - $self->deindent; - $self->pidl("}"); -} - -########################### -# push a switch element -sub EjsPushSwitch($$$$$$) -{ - my ($self, $e, $l, $var, $name, $env) = @_; - my $switch_var = ParseExpr($l->{SWITCH_IS}, $env, $e); - $self->pidl("ejs_set_switch(ejs, $switch_var);"); - $self->EjsPushElement($e, GetNextLevel($e, $l), $var, $name, $env); -} - -########################### -# push an array element -sub EjsPushArray($$$$$$) -{ - my ($self, $e, $l, $var, $name, $env) = @_; - my $nl = GetNextLevel($e, $l); - my $length = ParseExpr($l->{LENGTH_IS}, $env, $e); - my $pl = GetPrevLevel($e, $l); - if ($pl && $pl->{TYPE} eq "POINTER") { - $var = get_pointer_to($var); - } - # uint8 arrays are treated as data blobs - if ($nl->{TYPE} eq 'DATA' && $e->{TYPE} eq 'uint8') { - $self->check_null_pointer($length); - $self->pidl("ejs_push_array_uint8(ejs, v, $name, $var, $length);"); - return; - } - my $avar = $var . "[i]"; - $self->pidl("{"); - $self->indent; - $self->pidl("uint32_t i;"); - $self->pidl("for (i=0;i<$length;i++) {"); - $self->indent; - $self->pidl("const char *id = talloc_asprintf(ejs, \"%s.%u\", $name, i);"); - $self->EjsPushElement($e, $nl, $avar, "id", $env); - $self->deindent; - $self->pidl("}"); - $self->pidl("ejs_push_uint32(ejs, v, $name \".length\", &i);"); - $self->deindent; - $self->pidl("}"); -} - -################################ -# push a structure/union element -sub EjsPushElement($$$$$$) -{ - my ($self, $e, $l, $var, $name, $env) = @_; - if (($l->{TYPE} eq "POINTER")) { - $self->EjsPushPointer($e, $l, $var, $name, $env); - } elsif (has_property($e, "charset")) { - $self->EjsPushString($e, $l, $var, $name, $env); - } elsif ($l->{TYPE} eq "ARRAY") { - $self->EjsPushArray($e, $l, $var, $name, $env); - } elsif ($l->{TYPE} eq "DATA") { - $self->EjsPushScalar($e, $l, $var, $name, $env); - } elsif (($l->{TYPE} eq "SWITCH")) { - $self->EjsPushSwitch($e, $l, $var, $name, $env); - } else { - $self->pidl("return ejs_panic(ejs, \"unhandled push type $l->{TYPE}\");"); - } -} - -############################################# -# push a structure/union element at top level -sub EjsPushElementTop($$$) -{ - my ($self, $e, $env) = @_; - my $l = $e->{LEVELS}[0]; - my $var = ParseExpr($e->{NAME}, $env, $e); - my $name = "\"$e->{NAME}\""; - $self->EjsPushElement($e, $l, $var, $name, $env); -} - -########################### -# push a struct -sub EjsStructPush($$$) -{ - my ($self, $d, $varname) = @_; - my $env = GenerateStructEnv($d, $varname); - $self->pidl("EJS_CHECK(ejs_push_struct_start(ejs, &v, name));"); - foreach my $e (@{$d->{ELEMENTS}}) { - $self->EjsPushElementTop($e, $env); - } -} - -########################### -# push a union -sub EjsUnionPush($$$) -{ - my ($self, $d, $varname) = @_; - my $have_default = 0; - $self->pidl("EJS_CHECK(ejs_push_struct_start(ejs, &v, name));"); - $self->pidl("switch (ejs->switch_var) {"); - $self->indent; - foreach my $e (@{$d->{ELEMENTS}}) { - if ($e->{CASE} eq "default") { - $have_default = 1; - } - $self->pidl("$e->{CASE}:"); - $self->indent; - if ($e->{TYPE} ne "EMPTY") { - $self->EjsPushElementTop($e, { $e->{NAME} => "$varname->$e->{NAME}"} ); - } - $self->pidl("break;"); - $self->deindent; - } - if (! $have_default) { - $self->pidl("default:"); - $self->indent; - $self->pidl("return ejs_panic(ejs, \"Bad switch value\");"); - $self->deindent; - } - $self->deindent; - $self->pidl("}"); -} - -########################### -# push a enum -sub EjsEnumPush($$$) -{ - my ($self, $d, $varname) = @_; - $self->EjsEnumConstant($d); - $self->pidl("unsigned e = ".get_value_of($varname).";"); - $self->pidl("EJS_CHECK(ejs_push_enum(ejs, v, name, &e));"); -} - -########################### -# push a bitmap -sub EjsBitmapPush($$$) -{ - my ($self, $d, $varname) = @_; - return unless (defined($d->{ELEMENTS})); - my $type_fn = $d->{BASE_TYPE}; - # put the bitmap elements in the constants array - foreach my $e (@{$d->{ELEMENTS}}) { - if ($e =~ /^(\w*)\s*(.*)\s*$/) { - my $bname = $1; - my $v = $2; - $self->{constants}->{$bname} = $v; - } - } - $self->pidl("EJS_CHECK(ejs_push_$type_fn(ejs, v, name, $varname));"); -} - -sub EjsTypePushFunction($$$) -{ - sub EjsTypePushFunction($$$); - my ($self, $d, $name) = @_; - return if (has_property($d, "noejs")); - - my $var = undef; - my $dt = $d; - if ($dt->{TYPE} eq "TYPEDEF") { - $dt = $dt->{DATA}; - } - if ($dt->{TYPE} eq "STRUCT") { - $var = "const struct $name *r"; - } elsif ($dt->{TYPE} eq "UNION") { - $var = "const union $name *r"; - } elsif ($dt->{TYPE} eq "ENUM") { - $var = "const enum $name *r"; - } elsif ($dt->{TYPE} eq "BITMAP") { - my($type_decl) = Parse::Pidl::Typelist::mapTypeName($dt->{BASE_TYPE}); - $var = "const $type_decl *r"; - } - $self->fn_declare($d, "NTSTATUS ".TypeFunctionName("ejs_push", $d) . "(struct ejs_rpc *ejs, struct MprVar *v, const char *name, $var)"); - $self->pidl("{"); - $self->indent; - $self->EjsTypePush($d, "r"); - $self->pidl("return NT_STATUS_OK;"); - $self->deindent; - $self->pidl("}\n"); -} - -sub EjsTypePush($$$) -{ - sub EjsTypePush($$$); - my ($self, $d, $varname) = @_; - - if ($d->{TYPE} eq 'STRUCT') { - $self->EjsStructPush($d, $varname); - } elsif ($d->{TYPE} eq 'UNION') { - $self->EjsUnionPush($d, $varname); - } elsif ($d->{TYPE} eq 'ENUM') { - $self->EjsEnumPush($d, $varname); - } elsif ($d->{TYPE} eq 'BITMAP') { - $self->EjsBitmapPush($d, $varname); - } elsif ($d->{TYPE} eq 'TYPEDEF') { - $self->EjsTypePush($d->{DATA}, $varname); - } else { - warn "Unhandled push $varname of type $d->{TYPE}"; - } -} - -##################### -# generate a function -sub EjsPushFunction($$) -{ - my ($self, $d) = @_; - my $env = GenerateFunctionOutEnv($d); - - $self->pidl("\nstatic NTSTATUS ejs_push_$d->{NAME}(struct ejs_rpc *ejs, struct MprVar *v, const struct $d->{NAME} *r)"); - $self->pidl("{"); - $self->indent; - $self->pidl("EJS_CHECK(ejs_push_struct_start(ejs, &v, \"output\"));"); - - foreach my $e (@{$d->{ELEMENTS}}) { - next unless (grep(/out/, @{$e->{DIRECTION}})); - $self->EjsPushElementTop($e, $env); - } - - if ($d->{RETURN_TYPE}) { - $self->pidl("EJS_CHECK(".TypeFunctionName("ejs_push", $d->{RETURN_TYPE})."(ejs, v, \"result\", &r->out.result));"); - } - - $self->pidl("return NT_STATUS_OK;"); - $self->deindent; - $self->pidl("}\n"); -} - -################################# -# generate a ejs mapping function -sub EjsFunction($$$) -{ - my ($self, $d, $iface) = @_; - my $name = $d->{NAME}; - my $callnum = uc("NDR_$name"); - my $table = "&ndr_table_$iface"; - - $self->pidl("static int ejs_$name(int eid, int argc, struct MprVar **argv)"); - $self->pidl("{"); - $self->indent; - $self->pidl("return ejs_rpc_call(eid, argc, argv, $table, $callnum, (ejs_pull_function_t)ejs_pull_$name, (ejs_push_function_t)ejs_push_$name);"); - $self->deindent; - $self->pidl("}\n"); -} - -################### -# handle a constant -sub EjsConst($$) -{ - my ($self, $const) = @_; - $self->{constants}->{$const->{NAME}} = $const->{VALUE}; -} - -sub EjsImport -{ - my $self = shift; - my @imports = @_; - foreach (@imports) { - s/\.idl\"$//; - s/^\"//; - $self->pidl_hdr("#include \"librpc/gen_ndr/ndr_$_\_ejs\.h\"\n"); - } -} - -##################################################################### -# parse the interface definitions -sub EjsInterface($$$) -{ - my($self,$interface,$needed) = @_; - my @fns = (); - my $name = $interface->{NAME}; - - $self->pidl_hdr("#ifndef _HEADER_EJS_$interface->{NAME}\n"); - $self->pidl_hdr("#define _HEADER_EJS_$interface->{NAME}\n\n"); - - $self->pidl_hdr("\n"); - - foreach my $d (@{$interface->{TYPES}}) { - next unless (typeHasBody($d)); - ($needed->{TypeFunctionName("ejs_push", $d)}) && $self->EjsTypePushFunction($d, $d->{NAME}); - ($needed->{TypeFunctionName("ejs_pull", $d)}) && $self->EjsTypePullFunction($d, $d->{NAME}); - } - - foreach my $d (@{$interface->{FUNCTIONS}}) { - next if not defined($d->{OPNUM}); - next if has_property($d, "noejs"); - - $self->EjsPullFunction($d); - $self->EjsPushFunction($d); - $self->EjsFunction($d, $name); - - push (@fns, $d->{NAME}); - } - - foreach my $d (@{$interface->{CONSTS}}) { - $self->EjsConst($d); - } - - $self->pidl("static int ejs_$name\_init(int eid, int argc, struct MprVar **argv)"); - $self->pidl("{"); - $self->indent; - $self->pidl("struct MprVar *obj = mprInitObject(eid, \"$name\", argc, argv);"); - foreach (@fns) { - $self->pidl("mprSetCFunction(obj, \"$_\", ejs_$_);"); - } - foreach my $v (keys %{$self->{constants}}) { - my $value = $self->{constants}->{$v}; - if (substr($value, 0, 1) eq "\"") { - $self->pidl("mprSetVar(obj, \"$v\", mprString($value));"); - } else { - $self->pidl("mprSetVar(obj, \"$v\", mprCreateNumberVar($value));"); - } - } - $self->pidl("return ejs_rpc_init(obj, \"$name\");"); - $self->deindent; - $self->pidl("}\n"); - - $self->pidl("NTSTATUS ejs_init_$name(void)"); - $self->pidl("{"); - $self->indent; - $self->pidl("ejsDefineCFunction(-1, \"$name\_init\", ejs_$name\_init, NULL, MPR_VAR_SCRIPT_HANDLE);"); - $self->pidl("return NT_STATUS_OK;"); - $self->deindent; - $self->pidl("}"); - - $self->pidl_hdr("\n"); - $self->pidl_hdr("#endif /* _HEADER_EJS_$interface->{NAME} */\n"); -} - -##################################################################### -# parse a parsed IDL into a C header -sub Parse($$$) -{ - my($self,$ndr,$hdr) = @_; - - my $ejs_hdr = $hdr; - $ejs_hdr =~ s/.h$/_ejs.h/; - - $self->pidl_hdr("/* header auto-generated by pidl */\n\n"); - - $self->pidl(" -/* EJS wrapper functions auto-generated by pidl */ -#include \"includes.h\" -#include \"librpc/rpc/dcerpc.h\" -#include \"lib/appweb/ejs/ejs.h\" -#include \"scripting/ejs/ejsrpc.h\" -#include \"scripting/ejs/smbcalls.h\" -#include \"librpc/gen_ndr/ndr_misc_ejs.h\" -#include \"$hdr\" -#include \"$ejs_hdr\" - -"); - - my %needed = (); - - foreach my $x (@{$ndr}) { - ($x->{TYPE} eq "INTERFACE") && NeededInterface($x, \%needed); - } - - foreach my $x (@$ndr) { - ($x->{TYPE} eq "INTERFACE") && $self->EjsInterface($x, \%needed); - ($x->{TYPE} eq "IMPORT") && $self->EjsImport(@{$x->{PATHS}}); - } - - return ($self->{res_hdr}, $self->{res}); -} - -sub NeededFunction($$) -{ - my ($fn,$needed) = @_; - - $needed->{"ejs_pull_$fn->{NAME}"} = 1; - $needed->{"ejs_push_$fn->{NAME}"} = 1; - - foreach (@{$fn->{ELEMENTS}}) { - next if (has_property($_, "subcontext")); #FIXME: Support subcontexts - if (grep(/in/, @{$_->{DIRECTION}})) { - $needed->{TypeFunctionName("ejs_pull", $_->{TYPE})} = 1; - } - if (grep(/out/, @{$_->{DIRECTION}})) { - $needed->{TypeFunctionName("ejs_push", $_->{TYPE})} = 1; - } - } -} - -sub NeededType($$$) -{ - sub NeededType($$$); - my ($t,$needed,$req) = @_; - - NeededType($t->{DATA}, $needed, $req) if ($t->{TYPE} eq "TYPEDEF"); - - return unless (($t->{TYPE} eq "STRUCT") or ($t->{TYPE} eq "UNION")); - - return unless(typeHasBody($t)); - - foreach (@{$t->{ELEMENTS}}) { - next if (has_property($_, "subcontext")); #FIXME: Support subcontexts - my $n; - if (ref($_->{TYPE}) ne "HASH" or defined($_->{TYPE}->{NAME})) { - $needed->{TypeFunctionName("ejs_$req", $_->{TYPE})} = 1; - } - NeededType($_->{TYPE}, $needed, $req) if (ref($_->{TYPE}) eq "HASH"); - } -} - -##################################################################### -# work out what parse functions are needed -sub NeededInterface($$) -{ - my ($interface,$needed) = @_; - - NeededFunction($_, $needed) foreach (@{$interface->{FUNCTIONS}}); - - foreach (reverse @{$interface->{TYPES}}) { - if (has_property($_, "public")) { - $needed->{TypeFunctionName("ejs_pull", $_)} = not has_property($_, "noejs"); - $needed->{TypeFunctionName("ejs_push", $_)} = not has_property($_, "noejs"); - } - - NeededType($_, $needed, "pull") if ($needed->{TypeFunctionName("ejs_pull", $_)}); - NeededType($_, $needed, "push") if ($needed->{TypeFunctionName("ejs_push", $_)}); - } -} - -sub TypeFunctionName($$) -{ - my ($prefix, $t) = @_; - - return "$prefix\_$t->{NAME}" if (ref($t) eq "HASH" and - $t->{TYPE} eq "TYPEDEF"); - return "$prefix\_$t->{TYPE}_$t->{NAME}" if (ref($t) eq "HASH"); - return "$prefix\_$t"; -} - - - -1; diff --git a/source4/pidl/pidl b/source4/pidl/pidl index e58442ba1b..577db0a53f 100755 --- a/source4/pidl/pidl +++ b/source4/pidl/pidl @@ -17,7 +17,7 @@ pidl - An IDL compiler written in Perl pidl --help -pidl [--outputdir[=OUTNAME]] [--includedir DIR...] [--parse-idl-tree] [--dump-idl-tree] [--dump-ndr-tree] [--header[=OUTPUT]] [--ejs[=OUTPUT]] [--python[=OUTPUT]] [--swig[=OUTPUT]] [--ndr-parser[=OUTPUT]] [--client] [--server] [--warn-compat] [--quiet] [--verbose] [--template] [--ws-parser[=OUTPUT]] [--diff] [--dump-idl] [--tdr-parser[=OUTPUT]] [--samba3-ndr-client[=OUTPUT]] [--samba3-ndr-server[=OUTPUT]] [--typelib=[OUTPUT]] [.idl]... +pidl [--outputdir[=OUTNAME]] [--includedir DIR...] [--parse-idl-tree] [--dump-idl-tree] [--dump-ndr-tree] [--header[=OUTPUT]] [--python[=OUTPUT]] [--swig[=OUTPUT]] [--ndr-parser[=OUTPUT]] [--client] [--server] [--warn-compat] [--quiet] [--verbose] [--template] [--ws-parser[=OUTPUT]] [--diff] [--dump-idl] [--tdr-parser[=OUTPUT]] [--samba3-ndr-client[=OUTPUT]] [--samba3-ndr-server[=OUTPUT]] [--typelib=[OUTPUT]] [.idl]... =head1 DESCRIPTION @@ -478,7 +478,6 @@ my($opt_ndr_parser); my($opt_tdr_parser); my($opt_ws_parser); my($opt_swig); -my($opt_ejs); my($opt_python); my($opt_quiet) = 0; my($opt_outputdir) = '.'; @@ -521,7 +520,6 @@ Samba 4 output: --ndr-parser[=OUTFILE] create a C NDR parser [ndr_BASENAME.c] --client[=OUTFILE] create a C NDR client [ndr_BASENAME_c.c] --tdr-parser[=OUTFILE] create a C TDR parser [tdr_BASENAME.c] - --ejs[=OUTFILE] create ejs wrapper file [BASENAME_ejs.c] --python[=OUTFILE] create python wrapper file [py_BASENAME.c] --swig[=OUTFILE] create swig wrapper file [BASENAME.i] --server[=OUTFILE] create server boilerplate [ndr_BASENAME_s.c] @@ -567,7 +565,6 @@ my $result = GetOptions ( 'ndr-parser:s' => \$opt_ndr_parser, 'client:s' => \$opt_client, 'ws-parser:s' => \$opt_ws_parser, - 'ejs' => \$opt_ejs, 'python' => \$opt_python, 'diff' => \$opt_diff, 'swig:s' => \$opt_swig, @@ -664,7 +661,6 @@ sub process_file($) defined($opt_server) or defined($opt_header) or defined($opt_ndr_parser) or - defined($opt_ejs) or defined($opt_python) or defined($opt_dump_ndr_tree) or defined($opt_samba3_header) or @@ -709,14 +705,6 @@ sub process_file($) FileSave($filename, $code); } - if (defined($opt_ejs)) { - require Parse::Pidl::Samba4::EJS; - my $generator = new Parse::Pidl::Samba4::EJS(); - my ($hdr,$prsr) = $generator->Parse($ndr, $h_filename); - FileSave("$outputdir/ndr_$basename\_ejs.c", $prsr); - FileSave("$outputdir/ndr_$basename\_ejs.h", $hdr); - } - if (defined($opt_python)) { require Parse::Pidl::Samba4::Python; my $generator = new Parse::Pidl::Samba4::Python(); diff --git a/source4/scripting/ejs/config.mk b/source4/scripting/ejs/config.mk deleted file mode 100644 index 34c0a9678e..0000000000 --- a/source4/scripting/ejs/config.mk +++ /dev/null @@ -1,63 +0,0 @@ -[MODULE::smbcalls_config] -OUTPUT_TYPE = MERGED_OBJ -SUBSYSTEM = smbcalls -INIT_FUNCTION = smb_setup_ejs_config - -smbcalls_config_OBJ_FILES = $(ejsscriptsrcdir)/smbcalls_config.o - -[MODULE::smbcalls_ldb] -OUTPUT_TYPE = MERGED_OBJ -SUBSYSTEM = smbcalls -INIT_FUNCTION = smb_setup_ejs_ldb -PRIVATE_DEPENDENCIES = LIBLDB SAMDB LIBNDR - -smbcalls_ldb_OBJ_FILES = $(ejsscriptsrcdir)/smbcalls_ldb.o - -[MODULE::smbcalls_auth] -OUTPUT_TYPE = MERGED_OBJ -SUBSYSTEM = smbcalls -INIT_FUNCTION = smb_setup_ejs_auth -PRIVATE_DEPENDENCIES = service_auth - -smbcalls_auth_OBJ_FILES = $(ejsscriptsrcdir)/smbcalls_auth.o - -smbcalls_auth_OBJ_FILES = $(ejsscriptsrcdir)/smbcalls_auth.o - -[MODULE::smbcalls_string] -SUBSYSTEM = smbcalls -OUTPUT_TYPE = MERGED_OBJ -INIT_FUNCTION = smb_setup_ejs_string - -smbcalls_string_OBJ_FILES = $(ejsscriptsrcdir)/smbcalls_string.o - -[MODULE::smbcalls_sys] -SUBSYSTEM = smbcalls -OUTPUT_TYPE = MERGED_OBJ -INIT_FUNCTION = smb_setup_ejs_system - -smbcalls_sys_OBJ_FILES = $(ejsscriptsrcdir)/smbcalls_sys.o - -[SUBSYSTEM::smbcalls] -PRIVATE_DEPENDENCIES = \ - EJS LIBSAMBA-UTIL \ - MESSAGING \ - LIBSAMBA-NET LIBCLI_SMB LIBPOPT \ - CREDENTIALS POPT_CREDENTIALS POPT_SAMBA \ - NDR_TABLE - -smbcalls_OBJ_FILES = $(addprefix $(ejsscriptsrcdir)/, \ - smbcalls.o \ - smbcalls_options.o \ - smbcalls_creds.o \ - mprutil.o) - -$(eval $(call proto_header_template,$(ejsscriptsrcdir)/proto.h,$(smbcalls_OBJ_FILES:.o=.c))) - -####################### -# Start BINARY SMBSCRIPT -[BINARY::smbscript] -PRIVATE_DEPENDENCIES = EJS LIBSAMBA-UTIL smbcalls LIBSAMBA-HOSTCONFIG -# End BINARY SMBSCRIPT -####################### - -smbscript_OBJ_FILES = $(ejsscriptsrcdir)/smbscript.o diff --git a/source4/scripting/ejs/mprutil.c b/source4/scripting/ejs/mprutil.c deleted file mode 100644 index 9143947fb8..0000000000 --- a/source4/scripting/ejs/mprutil.c +++ /dev/null @@ -1,494 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - utility functions for manipulating mpr variables in ejs calls - - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "includes.h" -#include "lib/appweb/ejs/ejs.h" -#include "lib/ldb/include/ldb.h" -#include "scripting/ejs/smbcalls.h" - -/* - return a default mpr object -*/ -struct MprVar mprObject(const char *name) -{ - return ejsCreateObj(name && *name?name:"(NULL)", MPR_DEFAULT_HASH_SIZE); -} - -/* - return a empty mpr array -*/ -struct MprVar mprArray(const char *name) -{ - return ejsCreateArray(name && *name?name:"(NULL)", 0); -} - -/* - find a mpr component, allowing for sub objects, using the '.' convention -*/ - NTSTATUS mprGetVar(struct MprVar **v, const char *name) -{ - const char *p = strchr(name, '.'); - char *objname; - NTSTATUS status; - if (p == NULL) { - *v = mprGetProperty(*v, name, NULL); - if (*v == NULL) { - DEBUG(1,("mprGetVar unable to find '%s'\n", name)); - return NT_STATUS_INVALID_PARAMETER; - } - return NT_STATUS_OK; - } - objname = talloc_strndup(mprMemCtx(), name, p-name); - NT_STATUS_HAVE_NO_MEMORY(objname); - *v = mprGetProperty(*v, objname, NULL); - NT_STATUS_HAVE_NO_MEMORY(*v); - status = mprGetVar(v, p+1); - talloc_free(objname); - return status; -} - - -/* - set a mpr component, allowing for sub objects, using the '.' convention - destroys 'val' after setting -*/ - NTSTATUS mprSetVar(struct MprVar *v, const char *name, struct MprVar val) -{ - const char *p = strchr(name, '.'); - char *objname; - struct MprVar *v2; - NTSTATUS status; - if (p == NULL) { - v2 = mprSetProperty(v, name, &val); - if (v2 == NULL) { - DEBUG(1,("mprSetVar unable to set '%s'\n", name)); - return NT_STATUS_INVALID_PARAMETER_MIX; - } - mprDestroyVar(&val); - return NT_STATUS_OK; - } - objname = talloc_strndup(mprMemCtx(), name, p-name); - if (objname == NULL) { - return NT_STATUS_NO_MEMORY; - } - v2 = mprGetProperty(v, objname, NULL); - if (v2 == NULL) { - mprSetVar(v, objname, mprObject(objname)); - v2 = mprGetProperty(v, objname, NULL); - } - status = mprSetVar(v2, p+1, val); - talloc_free(objname); - return status; -} - - - -/* - add an indexed array element to a property -*/ - void mprAddArray(struct MprVar *var, int i, struct MprVar v) -{ - char idx[16]; - mprItoa(i, idx, sizeof(idx)); - mprSetVar(var, idx, v); -} - -/* - construct a MprVar from a list -*/ -struct MprVar mprList(const char *name, const char **list) -{ - struct MprVar var; - int i; - - var = mprArray(name); - for (i=0;list && list[i];i++) { - mprAddArray(&var, i, mprString(list[i])); - } - return var; -} - -/* - construct a MprVar from a string, using NULL if needed -*/ -struct MprVar mprString(const char *s) -{ - if (s == NULL) { - return mprCreatePtrVar(NULL); - } - return mprCreateStringVar(s, true); -} - -/* - construct a string MprVar from a lump of data -*/ -struct MprVar mprData(const uint8_t *p, size_t length) -{ - struct MprVar var; - char *s = talloc_strndup(mprMemCtx(), (const char *)p, length); - if (s == NULL) { - return mprCreateUndefinedVar(); - } - var = mprString(s); - talloc_free(s); - return var; -} - -/* - turn a ldb_message into a ejs object variable -*/ -static struct MprVar mprLdbMessage(struct ldb_context *ldb, struct ldb_message *msg) -{ - struct MprVar var; - int i; - /* we force some attributes to always be an array in the - returned structure. This makes the scripting easier, as you don't - need a special case for the single value case */ - const char *multivalued[] = { "objectClass", "memberOf", "privilege", - "member", NULL }; - - var = mprObject(ldb_dn_alloc_linearized(msg, msg->dn)); - - for (i=0;inum_elements;i++) { - struct ldb_message_element *el = &msg->elements[i]; - struct MprVar val; - const struct ldb_schema_attribute *a; - struct ldb_val v; - - a = ldb_schema_attribute_by_name(ldb, el->name); - if (a == NULL) { - goto failed; - } - - if (el->num_values == 1 && - !str_list_check_ci(multivalued, el->name)) { - if (a->syntax->ldif_write_fn(ldb, msg, &el->values[0], &v) != 0) { - goto failed; - } - /* FIXME: nasty hack, remove me when ejs will support - * arbitrary string and does not truncate on \0 */ - if (strlen((char *)v.data) != v.length) { - val = mprDataBlob(v); - } else { - val = mprData(v.data, v.length); - } - } else { - int j; - val = mprArray(el->name); - for (j=0;jnum_values;j++) { - if (a->syntax->ldif_write_fn(ldb, msg, - &el->values[j], &v) != 0) { - goto failed; - } - /* FIXME: nasty hack, remove me when ejs will support - * arbitrary string and does not truncate on \0 */ - if (strlen((char *)v.data) != v.length) { - mprAddArray(&val, j, mprDataBlob(v)); - } else { - mprAddArray(&val, j, mprData(v.data, v.length)); - } - } - } - mprSetVar(&var, el->name, val); - } - - /* add the dn if it is not already specified */ - if (mprGetProperty(&var, "dn", 0) == 0) { - mprSetVar(&var, "dn", mprString(ldb_dn_alloc_linearized(msg, msg->dn))); - } - - return var; -failed: - return mprCreateUndefinedVar(); -} - - -/* - build a MprVar result object for ldb operations with lots of funky properties -*/ -struct MprVar mprLdbResult(struct ldb_context *ldb, int err, struct ldb_result *result) -{ - struct MprVar ret; - struct MprVar ary; - - ret = mprObject("ldbret"); - - mprSetVar(&ret, "error", mprCreateIntegerVar(err)); - mprSetVar(&ret, "errstr", mprString(ldb_errstring(ldb))); - - ary = mprArray("ldb_message"); - if (result) { - int i; - - for (i = 0; i < result->count; i++) { - mprAddArray(&ary, i, mprLdbMessage(ldb, result->msgs[i])); - } - } - - mprSetVar(&ret, "msgs", ary); - - /* TODO: add referrals, exteded ops, and controls */ - - return ret; -} - - -/* - turn a MprVar string variable into a const char * - */ -const char *mprToString(struct MprVar *v) -{ - if (v->trigger) { - mprReadProperty(v, 0); - } - if (!mprVarIsString(v->type)) return NULL; - return v->string; -} - -/* - turn a MprVar integer variable into an int - */ -int mprToInt(struct MprVar *v) -{ - if (v->trigger) { - mprReadProperty(v, 0); - } - if (!mprVarIsNumber(v->type)) return 0; - return mprVarToNumber(v); -} - -/* - turn a MprVar object variable into a string list - this assumes the object variable consists only of strings -*/ -const char **mprToList(TALLOC_CTX *mem_ctx, struct MprVar *v) -{ - const char **list = NULL; - struct MprVar *el; - - if (v->type != MPR_TYPE_OBJECT || - v->properties == NULL) { - return NULL; - } - for (el=mprGetFirstProperty(v, MPR_ENUM_DATA); - el; - el=mprGetNextProperty(v, el, MPR_ENUM_DATA)) { - const char *s = mprToString(el); - if (s) { - list = str_list_add(list, s); - } - } - talloc_steal(mem_ctx, list); - return list; -} - - -/* - turn a MprVar object variable into a string list - this assumes the object variable is an array of strings -*/ -const char **mprToArray(TALLOC_CTX *mem_ctx, struct MprVar *v) -{ - const char **list = NULL; - struct MprVar *len; - int length, i; - - len = mprGetProperty(v, "length", NULL); - if (len == NULL) { - return NULL; - } - length = mprToInt(len); - - for (i=0;itype != MPR_TYPE_STRING) { - talloc_free(list); - return NULL; - } - list = str_list_add(list, mprToString(vs)); - } - talloc_steal(mem_ctx, list); - return list; -} - -/* - turn a NTSTATUS into a MprVar object with lots of funky properties -*/ -struct MprVar mprNTSTATUS(NTSTATUS status) -{ - struct MprVar res; - - res = mprObject("ntstatus"); - - mprSetVar(&res, "errstr", mprString(nt_errstr(status))); - mprSetVar(&res, "v", mprCreateIntegerVar(NT_STATUS_V(status))); - mprSetVar(&res, "is_ok", mprCreateBoolVar(NT_STATUS_IS_OK(status))); - mprSetVar(&res, "is_err", mprCreateBoolVar(NT_STATUS_IS_ERR(status))); - - return res; -} - -/* - create a data-blob in a mpr variable -*/ -struct MprVar mprDataBlob(DATA_BLOB blob) -{ - struct MprVar res; - struct datablob *pblob = talloc(mprMemCtx(), struct datablob); - *pblob = data_blob_talloc(pblob, blob.data, blob.length); - - res = mprObject("DATA_BLOB"); - - mprSetVar(&res, "size", mprCreateIntegerVar(blob.length)); - mprSetPtrChild(&res, "blob", pblob); - - return res; -} - -/* - return a data blob from a mpr var created using mprDataBlob -*/ -struct datablob *mprToDataBlob(struct MprVar *v) -{ - return talloc_get_type(mprGetPtr(v, "blob"), struct datablob); -} - -/* - turn a WERROR into a MprVar object with lots of funky properties -*/ -struct MprVar mprWERROR(WERROR status) -{ - struct MprVar res; - - res = mprObject("werror"); - - mprSetVar(&res, "errstr", mprString(win_errstr(status))); - mprSetVar(&res, "v", mprCreateIntegerVar(W_ERROR_V(status))); - mprSetVar(&res, "is_ok", mprCreateBoolVar(W_ERROR_IS_OK(status))); - mprSetVar(&res, "is_err", mprCreateBoolVar(!W_ERROR_IS_OK(status))); - - return res; -} - - -/* - set a pointer in a existing MprVar -*/ -void mprSetPtr(struct MprVar *v, const char *propname, const void *p) -{ - mprSetVar(v, propname, mprCreatePtrVar(discard_const(p))); -} - -/* - set a pointer in a existing MprVar, freeing it when the property goes away -*/ -void mprSetPtrChild(struct MprVar *v, const char *propname, const void *p) -{ - mprSetVar(v, propname, mprCreatePtrVar(discard_const(p))); - v = mprGetProperty(v, propname, NULL); - v->allocatedData = 1; - talloc_steal(mprMemCtx(), p); -} - -/* - get a pointer from a MprVar -*/ -void *mprGetPtr(struct MprVar *v, const char *propname) -{ - struct MprVar *val; - val = mprGetProperty(v, propname, NULL); - if (val == NULL) { - return NULL; - } - if (val->type != MPR_TYPE_PTR) { - return NULL; - } - return val->ptr; -} - -/* - set the return value then free the variable -*/ - void mpr_Return(int eid, struct MprVar v) -{ - ejsSetReturnValue(eid, v); - mprDestroyVar(&v); -} - -/* - set the return value then free the variable -*/ -void mpr_ReturnString(int eid, const char *s) -{ - mpr_Return(eid, mprString(s)); -} - - -/* - set a C function in a variable -*/ - void mprSetCFunction(struct MprVar *obj, const char *name, MprCFunction fn) -{ - mprSetVar(obj, name, mprCreateCFunctionVar(fn, obj, MPR_VAR_SCRIPT_HANDLE)); -} - -/* - set a string C function in a variable -*/ - void mprSetStringCFunction(struct MprVar *obj, const char *name, MprStringCFunction fn) -{ - mprSetVar(obj, name, mprCreateStringCFunctionVar(fn, obj, MPR_VAR_SCRIPT_HANDLE)); -} - -/* - get a pointer in the current object -*/ -void *mprGetThisPtr(int eid, const char *name) -{ - struct MprVar *this = mprGetProperty(ejsGetLocalObject(eid), "this", 0); - return mprGetPtr(this, name); -} - -/* - set a pointer as a child of the local object -*/ -void mprSetThisPtr(int eid, const char *name, void *ptr) -{ - struct MprVar *this = mprGetProperty(ejsGetLocalObject(eid), "this", 0); - mprSetPtrChild(this, name, ptr); -} - -/* - used by object xxx_init() routines to allow for the caller - to supply a pre-existing object to add properties to, - or create a new object. This makes inheritance easy -*/ -struct MprVar *mprInitObject(int eid, const char *name, int argc, struct MprVar **argv) -{ - if (argc > 0 && mprVarIsObject(argv[0]->type)) { - return argv[0]; - } - mpr_Return(eid, mprObject(name)); - return ejsGetReturnValue(eid); -} diff --git a/source4/scripting/ejs/smbcalls.c b/source4/scripting/ejs/smbcalls.c deleted file mode 100644 index 4314b51455..0000000000 --- a/source4/scripting/ejs/smbcalls.c +++ /dev/null @@ -1,220 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide hooks into smbd C calls from ejs scripts - - Copyright (C) Andrew Tridgell 2005 - Copyright (C) Tim Potter 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 . -*/ - -#include "includes.h" -#include "param/param.h" -#include "scripting/ejs/smbcalls.h" -#include "version.h" - -/* - return the type of a variable -*/ -static int ejs_typeof(MprVarHandle eid, int argc, struct MprVar **argv) -{ - const struct { - MprType type; - const char *name; - } types[] = { - { MPR_TYPE_UNDEFINED, "undefined" }, - { MPR_TYPE_NULL, "object" }, - { MPR_TYPE_BOOL, "boolean" }, - { MPR_TYPE_CFUNCTION, "function" }, - { MPR_TYPE_FLOAT, "number" }, - { MPR_TYPE_INT, "number" }, - { MPR_TYPE_INT64, "number" }, - { MPR_TYPE_OBJECT, "object" }, - { MPR_TYPE_FUNCTION, "function" }, - { MPR_TYPE_STRING, "string" }, - { MPR_TYPE_STRING_CFUNCTION, "function" }, - { MPR_TYPE_PTR, "pointer" } - }; - int i; - const char *type = NULL; - - if (argc != 1) return -1; - - for (i=0;itype == types[i].type) { - type = types[i].name; - break; - } - } - if (type == NULL) return -1; - - mpr_ReturnString(eid, type); - return 0; -} - -/* - return the native type of a variable -*/ -static int ejs_typeof_native(MprVarHandle eid, int argc, struct MprVar **argv) -{ - const struct { - MprType type; - const char *name; - } types[] = { - { MPR_TYPE_UNDEFINED, "undefined" }, - { MPR_TYPE_NULL, "null" }, - { MPR_TYPE_BOOL, "boolean" }, - { MPR_TYPE_CFUNCTION, "c_function" }, - { MPR_TYPE_FLOAT, "float" }, - { MPR_TYPE_INT, "integer" }, - { MPR_TYPE_INT64, "integer64" }, - { MPR_TYPE_OBJECT, "object" }, - { MPR_TYPE_FUNCTION, "js_function" }, - { MPR_TYPE_STRING, "string" }, - { MPR_TYPE_STRING_CFUNCTION, "string_c_function" }, - { MPR_TYPE_PTR, "pointer" } - }; - int i; - const char *type = NULL; - - if (argc != 1) return -1; - - for (i=0;itype == types[i].type) { - type = types[i].name; - break; - } - } - if (type == NULL) return -1; - - mpr_ReturnString(eid, type); - return 0; -} - -/* - libinclude() allows you to include js files using a search path specified - in "js include =" in smb.conf. -*/ -static int ejs_libinclude(int eid, int argc, char **argv) -{ - int i, j; - const char **js_include = lp_js_include(mprLpCtx()); - - if (js_include == NULL || js_include[0] == NULL) { - ejsSetErrorMsg(eid, "js include path not set"); - return -1; - } - - for (i = 0; i < argc; i++) { - const char *script = argv[i]; - struct MprVar result; - char *path, *emsg; - int ret; - - /* use specfied path to search for requested file */ - for (j=0;js_include[j];j++) { - path = talloc_asprintf(mprMemCtx(), "%s/%s", js_include[j], script); - if (path == NULL) { - return -1; - } - if (file_exist(path)) { - - ret = ejsEvalFile(eid, path, &result, &emsg); - talloc_free(path); - if (ret < 0) { - ejsSetErrorMsg(eid, "%s: %s", script, emsg); - return -1; - } - break; - } - talloc_free(path); - } - - if (js_include[j] == NULL) { - ejsSetErrorMsg(eid, "unable to include '%s'", script); - return -1; - } - } - return 0; -} - -/* - return the current version -*/ -static int ejs_version(MprVarHandle eid, int argc, struct MprVar **argv) -{ - mpr_ReturnString(eid, SAMBA_VERSION_STRING); - return 0; -} - - -static void (*ejs_exception_handler) (const char *) = NULL; - -_PUBLIC_ void ejs_exception(const char *reason) -{ - ejs_exception_handler(reason); -} - -/* - setup C functions that be called from ejs -*/ -void smb_setup_ejs_functions(void (*exception_handler)(const char *)) -{ - extern NTSTATUS ejs_init_security(void); - extern NTSTATUS ejs_init_initshutdown(void); - extern NTSTATUS smb_setup_ejs_reg(void); - extern NTSTATUS smb_setup_ejs_string(void); - extern NTSTATUS ejs_init_lsarpc(void); - extern NTSTATUS ejs_init_rpcecho(void); - extern NTSTATUS ejs_init_winreg(void); - extern NTSTATUS smb_setup_ejs_random(void); - extern NTSTATUS smb_setup_ejs_config(void); - extern NTSTATUS ejs_init_misc(void); - extern NTSTATUS ejs_init_netdfs(void); - extern NTSTATUS smb_setup_ejs_datablob(void); - extern NTSTATUS smb_setup_ejs_auth(void); - extern NTSTATUS smb_setup_ejs_nss(void); - extern NTSTATUS ejs_init_samr(void); - extern NTSTATUS ejs_init_wkssvc(void); - extern NTSTATUS smb_setup_ejs_system(void); - extern NTSTATUS smb_setup_ejs_ldb(void); - extern NTSTATUS ejs_init_svcctl(void); - extern NTSTATUS smb_setup_ejs_net(void); - extern NTSTATUS ejs_init_srvsvc(void); - extern NTSTATUS ejs_init_netlogon(void); - extern NTSTATUS ejs_init_drsuapi(void); - extern NTSTATUS ejs_init_irpc(void); - extern NTSTATUS ejs_init_eventlog(void); - init_module_fn static_init[] = { STATIC_smbcalls_MODULES }; - init_module_fn *shared_init; - - ejs_exception_handler = exception_handler; - - smb_setup_ejs_options(); - smb_setup_ejs_credentials(); - - shared_init = load_samba_modules(NULL, mprLpCtx(), "smbcalls"); - - run_init_functions(static_init); - run_init_functions(shared_init); - - talloc_free(shared_init); - - ejsDefineCFunction(-1, "typeof", ejs_typeof, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineCFunction(-1, "nativeTypeOf", ejs_typeof_native, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineStringCFunction(-1, "libinclude", ejs_libinclude, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineCFunction(-1, "version", ejs_version, NULL, MPR_VAR_SCRIPT_HANDLE); -} - diff --git a/source4/scripting/ejs/smbcalls.h b/source4/scripting/ejs/smbcalls.h deleted file mode 100644 index 3aaf324b6e..0000000000 --- a/source4/scripting/ejs/smbcalls.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide hooks into smbd C calls from ejs scripts - - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "lib/appweb/ejs/ejs.h" -#include "lib/ldb/include/ldb.h" - -void mpr_Return(int eid, struct MprVar); -NTSTATUS mprSetVar(struct MprVar *v, const char *name, struct MprVar val); -NTSTATUS mprGetVar(struct MprVar **v, const char *name); -void mprAddArray(struct MprVar *var, int i, struct MprVar v); -void mprSetCFunction(struct MprVar *obj, const char *name, MprCFunction fn); -void mprSetStringCFunction(struct MprVar *obj, const char *name, MprStringCFunction fn); - -struct smbcalls_context { - struct event_context *event_ctx; - struct messaging_context *msg_ctx; -}; - -struct ldb_context; -struct ldb_message; -struct cli_credentials; - -#include "param/param.h" -#include "scripting/ejs/proto.h" diff --git a/source4/scripting/ejs/smbcalls_auth.c b/source4/scripting/ejs/smbcalls_auth.c deleted file mode 100644 index b67bb7ed5b..0000000000 --- a/source4/scripting/ejs/smbcalls_auth.c +++ /dev/null @@ -1,243 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - ejs auth functions - - Copyright (C) Simo Sorce 2005 - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "includes.h" -#include "lib/appweb/ejs/ejs.h" -#include "auth/auth.h" -#include "auth/credentials/credentials.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/events/events.h" -#include "lib/messaging/irpc.h" -#include "libcli/security/security.h" - -static int ejs_doauth(MprVarHandle eid, - TALLOC_CTX *tmp_ctx, struct MprVar *auth, - const char *username, const char *password, - const char *domain, const char *workstation, - struct socket_address *remote_host, - const char **auth_types) -{ - struct auth_usersupplied_info *user_info = NULL; - struct auth_serversupplied_info *server_info = NULL; - struct auth_session_info *session_info = NULL; - struct auth_context *auth_context; - struct MprVar *session_info_obj; - NTSTATUS nt_status; - bool set; - - struct smbcalls_context *c; - struct event_context *ev; - struct messaging_context *msg; - - /* Hope we can find an smbcalls_context somewhere up there... */ - c = talloc_find_parent_bytype(tmp_ctx, struct smbcalls_context); - if (c) { - ev = c->event_ctx; - msg = c->msg_ctx; - } else { - /* Hope we can find the event context somewhere up there... */ - ev = mprEventCtx(); - msg = messaging_client_init(tmp_ctx, lp_messaging_path(tmp_ctx, mprLpCtx()), - lp_iconv_convenience(mprLpCtx()), ev); - } - - if (auth_types) { - nt_status = auth_context_create_methods(tmp_ctx, auth_types, ev, msg, mprLpCtx(), &auth_context); - } else { - nt_status = auth_context_create(tmp_ctx, ev, msg, mprLpCtx(), &auth_context); - } - if (!NT_STATUS_IS_OK(nt_status)) { - mprSetPropertyValue(auth, "result", mprCreateBoolVar(false)); - mprSetPropertyValue(auth, "report", mprString("Auth System Failure")); - goto done; - } - - user_info = talloc(tmp_ctx, struct auth_usersupplied_info); - if (!user_info) { - mprSetPropertyValue(auth, "result", mprCreateBoolVar(false)); - mprSetPropertyValue(auth, "report", mprString("talloc failed")); - goto done; - } - - user_info->mapped_state = true; - user_info->client.account_name = username; - user_info->mapped.account_name = username; - user_info->client.domain_name = domain; - user_info->mapped.domain_name = domain; - - user_info->workstation_name = workstation; - - user_info->remote_host = remote_host; - - user_info->password_state = AUTH_PASSWORD_PLAIN; - user_info->password.plaintext = talloc_strdup(user_info, password); - - user_info->flags = USER_INFO_CASE_INSENSITIVE_USERNAME | - USER_INFO_DONT_CHECK_UNIX_ACCOUNT; - - user_info->logon_parameters = 0; - - nt_status = auth_check_password(auth_context, tmp_ctx, user_info, &server_info); - - /* Don't give the game away (any difference between no such - * user and wrong password) */ - nt_status = auth_nt_status_squash(nt_status); - - if (!NT_STATUS_IS_OK(nt_status)) { - mprSetPropertyValue(auth, "report", - mprString(talloc_strdup(mprMemCtx(), get_friendly_nt_error_msg(nt_status)))); - mprSetPropertyValue(auth, "result", mprCreateBoolVar(false)); - goto done; - } - - nt_status = auth_generate_session_info(tmp_ctx, mprEventCtx(), mprLpCtx(), server_info, &session_info); - if (!NT_STATUS_IS_OK(nt_status)) { - mprSetPropertyValue(auth, "report", mprString("Session Info generation failed")); - mprSetPropertyValue(auth, "result", mprCreateBoolVar(false)); - goto done; - } - - if (security_token_has_nt_authenticated_users(session_info->security_token)) { - mprSetPropertyValue(auth, "user_class", mprString("USER")); - set = true; - } - - if (security_token_has_builtin_administrators(session_info->security_token)) { - mprSetPropertyValue(auth, "user_class", mprString("ADMINISTRATOR")); - set = true; - } - - if (security_token_is_system(session_info->security_token)) { - mprSetPropertyValue(auth, "user_class", mprString("SYSTEM")); - set = true; - } - - if (security_token_is_anonymous(session_info->security_token)) { - mprSetPropertyValue(auth, "report", mprString("Anonymous login not permitted")); - mprSetPropertyValue(auth, "result", mprCreateBoolVar(false)); - goto done; - } - - if (!set) { - mprSetPropertyValue(auth, "report", mprString("Session Info generation failed")); - mprSetPropertyValue(auth, "result", mprCreateBoolVar(false)); - } - - session_info_obj = mprInitObject(eid, "session_info", 0, NULL); - - mprSetPtrChild(session_info_obj, "session_info", session_info); - talloc_steal(mprMemCtx(), session_info); - - mprSetProperty(auth, "session_info", session_info_obj); - mprSetPropertyValue(auth, "result", mprCreateBoolVar(server_info->authenticated)); - mprSetPropertyValue(auth, "username", mprString(server_info->account_name)); - mprSetPropertyValue(auth, "domain", mprString(server_info->domain_name)); - -done: - return 0; -} - -/* - perform user authentication, returning an array of results - -*/ -static int ejs_userAuth(MprVarHandle eid, int argc, struct MprVar **argv) -{ - TALLOC_CTX *tmp_ctx; - const char *username; - const char *password; - const char *domain; - const char *workstation; - struct MprVar auth; - struct cli_credentials *creds; - struct socket_address *remote_host; - const char *auth_types_unix[] = { "unix", NULL }; - - if (argc != 2 || argv[0]->type != MPR_TYPE_OBJECT || argv[1]->type != MPR_TYPE_OBJECT) { - ejsSetErrorMsg(eid, "userAuth invalid arguments, this function requires an object."); - return -1; - } - - /* get credential values from credentials object */ - creds = mprGetPtr(argv[0], "creds"); - if (creds == NULL) { - ejsSetErrorMsg(eid, "userAuth requires a 'creds' first parameter"); - return -1; - } - - remote_host = (struct socket_address *)mprGetPtr(argv[1], "socket_address"); - if (remote_host == NULL) { - ejsSetErrorMsg(eid, "userAuth requires a socket address second parameter"); - return -1; - } - - tmp_ctx = talloc_new(mprMemCtx()); - - username = cli_credentials_get_username(creds); - password = cli_credentials_get_password(creds); - domain = cli_credentials_get_domain(creds); - workstation = cli_credentials_get_workstation(creds); - - if (username == NULL || password == NULL || domain == NULL) { - mpr_Return(eid, mprCreateUndefinedVar()); - talloc_free(tmp_ctx); - return 0; - } - - auth = mprObject("auth"); - - if (domain && (strcmp("SYSTEM USER", domain) == 0)) { - ejs_doauth(eid, tmp_ctx, &auth, username, password, domain, workstation, remote_host, auth_types_unix); - } else { - ejs_doauth(eid, tmp_ctx, &auth, username, password, domain, workstation, remote_host, NULL); - } - - mpr_Return(eid, auth); - talloc_free(tmp_ctx); - return 0; -} - -/* - initialise credentials ejs object -*/ -static int ejs_system_session(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct MprVar *obj = mprInitObject(eid, "session_info", argc, argv); - struct auth_session_info *session_info = system_session(mprMemCtx(), mprLpCtx()); - - if (session_info == NULL) { - return -1; - } - - mprSetPtrChild(obj, "session_info", session_info); - return 0; -} - -/* - setup C functions that be called from ejs -*/ -NTSTATUS smb_setup_ejs_auth(void) -{ - ejsDefineCFunction(-1, "userAuth", ejs_userAuth, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineCFunction(-1, "system_session", ejs_system_session, NULL, MPR_VAR_SCRIPT_HANDLE); - return NT_STATUS_OK; -} diff --git a/source4/scripting/ejs/smbcalls_config.c b/source4/scripting/ejs/smbcalls_config.c deleted file mode 100644 index eb673b3a23..0000000000 --- a/source4/scripting/ejs/smbcalls_config.c +++ /dev/null @@ -1,228 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide hooks into smbd C calls from ejs scripts - - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "includes.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/appweb/ejs/ejs.h" -#include "param/loadparm.h" -#include "system/network.h" -#include "lib/socket/netif.h" -#include "param/param.h" - -/* - return a list of defined services -*/ -static int ejs_lpServices(MprVarHandle eid, int argc, char **argv) -{ - int i; - const char **list = NULL; - if (argc != 0) return -1; - - for (i=0;iclass == P_GLOBAL) { - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; - } - parm_ptr = lp_parm_ptr(mprLpCtx(), service, parm); - } else if (strchr(argv[0], ':')) { - /* its a global parametric option */ - const char *type = talloc_strndup(mprMemCtx(), - argv[0], strcspn(argv[0], ":")); - const char *option = strchr(argv[0], ':') + 1; - const char *value; - if (type == NULL || option == NULL) { - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; - } - value = lp_get_parametric(mprLpCtx(), NULL, type, option); - if (value == NULL) { - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; - } - mpr_ReturnString(eid, value); - return 0; - } else { - /* its a global parameter */ - parm = lp_parm_struct(argv[0]); - if (parm == NULL) { - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; - } - parm_ptr = lp_parm_ptr(mprLpCtx(), NULL, parm); - } - - if (parm == NULL || parm_ptr == NULL) { - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; - } - - /* construct and return the right type of ejs object */ - switch (parm->type) { - case P_STRING: - case P_USTRING: - mpr_ReturnString(eid, *(char **)parm_ptr); - break; - case P_BOOL: - mpr_Return(eid, mprCreateBoolVar(*(bool *)parm_ptr)); - break; - case P_INTEGER: - case P_OCTAL: - case P_BYTES: - mpr_Return(eid, mprCreateIntegerVar(*(int *)parm_ptr)); - break; - case P_ENUM: - for (i=0; parm->enum_list[i].name; i++) { - if (*(int *)parm_ptr == parm->enum_list[i].value) { - mpr_ReturnString(eid, parm->enum_list[i].name); - return 0; - } - } - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; - case P_LIST: - mpr_Return(eid, mprList(parm->label, *(const char ***)parm_ptr)); - break; - } - return 0; -} - -/* - v = lp.filename(); obtain filename -*/ -static int ejs_lpFilename(MprVarHandle eid, int argc, char **argv) -{ - mpr_ReturnString(eid, lp_configfile(mprLpCtx())); - return 0; -} - -/* - set a smb.conf parameter. Only sets in memory, not permanent - - can be called in 4 ways: - - ok = lp.set("parm", "value"); -*/ -static int ejs_lpSet(MprVarHandle eid, int argc, char **argv) -{ - if (argc != 2) { - ejsSetErrorMsg(eid, "lp.set invalid arguments"); - return -1; - } - - mpr_Return(eid, mprCreateBoolVar(lp_set_cmdline(mprLpCtx(), argv[0], argv[1]))); - return 0; -} - -/* - reload smb.conf - - ok = lp.reload(); -*/ -static int ejs_lpReload(MprVarHandle eid, int argc, char **argv) -{ - bool ret; - const char *filename = lp_configfile(mprLpCtx()); - - ret = lp_load(mprLpCtx(), filename); - mpr_Return(eid, mprCreateBoolVar(ret)); - return 0; -} - -/* - initialise loadparm ejs subsystem -*/ -static int ejs_loadparm_init(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct MprVar *obj = mprInitObject(eid, "loadparm", argc, argv); - - mprSetStringCFunction(obj, "get", ejs_lpGet); - mprSetStringCFunction(obj, "set", ejs_lpSet); - mprSetStringCFunction(obj, "reload", ejs_lpReload); - mprSetStringCFunction(obj, "services", ejs_lpServices); - mprSetStringCFunction(obj, "filename", ejs_lpFilename); - return 0; -} - -/* - setup C functions that be called from ejs -*/ -NTSTATUS smb_setup_ejs_config(void) -{ - ejsDefineCFunction(-1, "loadparm_init", ejs_loadparm_init, NULL, MPR_VAR_SCRIPT_HANDLE); - return NT_STATUS_OK; -} diff --git a/source4/scripting/ejs/smbcalls_creds.c b/source4/scripting/ejs/smbcalls_creds.c deleted file mode 100644 index fd73f0751f..0000000000 --- a/source4/scripting/ejs/smbcalls_creds.c +++ /dev/null @@ -1,275 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide hooks credentials calls - - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "includes.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/appweb/ejs/ejs.h" -#include "lib/cmdline/popt_common.h" -#include "auth/credentials/credentials.h" - -/* - helper function to get the local objects credentials ptr -*/ -static struct cli_credentials *ejs_creds_get_credentials(int eid) -{ - struct cli_credentials *creds = (struct cli_credentials *)mprGetThisPtr(eid, "creds"); - if (creds == NULL) { - ejsSetErrorMsg(eid, "NULL ejs credentials"); - } - return creds; -} - -/* - get a domain -*/ -static int ejs_creds_get_domain(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct cli_credentials *creds = ejs_creds_get_credentials(eid); - - mpr_Return(eid, mprString(cli_credentials_get_domain(creds))); - return 0; -} - - -/* - set a domain -*/ -static int ejs_creds_set_domain(MprVarHandle eid, int argc, char **argv) -{ - struct cli_credentials *creds = ejs_creds_get_credentials(eid); - if (argc != 1) { - ejsSetErrorMsg(eid, "bad arguments to set_domain"); - return -1; - } - - cli_credentials_set_domain(creds, argv[0], CRED_SPECIFIED); - mpr_Return(eid, mprCreateBoolVar(true)); - return 0; -} - - -/* - get a username -*/ -static int ejs_creds_get_username(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct cli_credentials *creds = ejs_creds_get_credentials(eid); - - mpr_Return(eid, mprString(cli_credentials_get_username(creds))); - return 0; -} - - -/* - set a username -*/ -static int ejs_creds_set_username(MprVarHandle eid, int argc, char **argv) -{ - struct cli_credentials *creds = ejs_creds_get_credentials(eid); - if (argc != 1) { - ejsSetErrorMsg(eid, "bad arguments to set_username"); - return -1; - } - - cli_credentials_set_username(creds, argv[0], CRED_SPECIFIED); - mpr_Return(eid, mprCreateBoolVar(true)); - return 0; -} - - -/* - get user password -*/ -static int ejs_creds_get_password(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct cli_credentials *creds = ejs_creds_get_credentials(eid); - - mpr_Return(eid, mprString(cli_credentials_get_password(creds))); - return 0; -} - - -/* - set user password -*/ -static int ejs_creds_set_password(MprVarHandle eid, int argc, char **argv) -{ - struct cli_credentials *creds = ejs_creds_get_credentials(eid); - if (argc != 1) { - ejsSetErrorMsg(eid, "bad arguments to set_password"); - return -1; - } - - cli_credentials_set_password(creds, argv[0], CRED_SPECIFIED); - mpr_Return(eid, mprCreateBoolVar(true)); - return 0; -} - - -/* - set realm -*/ -static int ejs_creds_set_realm(MprVarHandle eid, int argc, char **argv) -{ - struct cli_credentials *creds = ejs_creds_get_credentials(eid); - if (argc != 1) { - ejsSetErrorMsg(eid, "bad arguments to set_realm"); - return -1; - } - - cli_credentials_set_realm(creds, argv[0], CRED_SPECIFIED); - mpr_Return(eid, mprCreateBoolVar(true)); - return 0; -} - - -/* - get realm -*/ -static int ejs_creds_get_realm(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct cli_credentials *creds = ejs_creds_get_credentials(eid); - - mpr_Return(eid, mprString(cli_credentials_get_realm(creds))); - return 0; -} - - -/* - set workstation -*/ -static int ejs_creds_set_workstation(MprVarHandle eid, int argc, char **argv) -{ - struct cli_credentials *creds = ejs_creds_get_credentials(eid); - if (argc != 1) { - ejsSetErrorMsg(eid, "bad arguments to set_workstation"); - return -1; - } - - cli_credentials_set_workstation(creds, argv[0], CRED_SPECIFIED); - mpr_Return(eid, mprCreateBoolVar(true)); - return 0; -} - - -/* - get workstation -*/ -static int ejs_creds_get_workstation(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct cli_credentials *creds = ejs_creds_get_credentials(eid); - - mpr_Return(eid, mprString(cli_credentials_get_workstation(creds))); - return 0; -} - -/* - set machine account -*/ -static int ejs_creds_set_machine_account(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct cli_credentials *creds = ejs_creds_get_credentials(eid); - if (argc != 0) { - ejsSetErrorMsg(eid, "bad arguments to set_machine_account"); - return -1; - } - - if (NT_STATUS_IS_OK(cli_credentials_set_machine_account(creds, mprLpCtx()))) { - mpr_Return(eid, mprCreateBoolVar(true)); - } else { - mpr_Return(eid, mprCreateBoolVar(false)); - } - return 0; -} - - -/* - initialise credentials ejs object -*/ -static int ejs_credentials_obj(struct MprVar *obj, struct cli_credentials *creds) -{ - mprSetPtrChild(obj, "creds", creds); - - /* setup our object methods */ - mprSetCFunction(obj, "get_domain", ejs_creds_get_domain); - mprSetStringCFunction(obj, "set_domain", ejs_creds_set_domain); - mprSetCFunction(obj, "get_username", ejs_creds_get_username); - mprSetStringCFunction(obj, "set_username", ejs_creds_set_username); - mprSetCFunction(obj, "get_password", ejs_creds_get_password); - mprSetStringCFunction(obj, "set_password", ejs_creds_set_password); - mprSetCFunction(obj, "get_realm", ejs_creds_get_realm); - mprSetStringCFunction(obj, "set_realm", ejs_creds_set_realm); - mprSetCFunction(obj, "get_workstation", ejs_creds_get_workstation); - mprSetStringCFunction(obj, "set_workstation", ejs_creds_set_workstation); - mprSetCFunction(obj, "set_machine_account", ejs_creds_set_machine_account); - - return 0; -} - - -struct MprVar mprCredentials(struct cli_credentials *creds) -{ - struct MprVar mpv = mprObject("credentials"); - - ejs_credentials_obj(&mpv, creds); - - return mpv; -} - - -/* - initialise credentials ejs object -*/ -static int ejs_credentials_init(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct cli_credentials *creds; - struct MprVar *obj = mprInitObject(eid, "credentials", argc, argv); - - creds = cli_credentials_init(mprMemCtx()); - if (creds == NULL) { - return -1; - } - - cli_credentials_set_conf(creds, mprLpCtx()); - - return ejs_credentials_obj(obj, creds); -} - -/* - initialise cmdline credentials ejs object -*/ -int ejs_credentials_cmdline(int eid, int argc, struct MprVar **argv) -{ - struct MprVar *obj = mprInitObject(eid, "credentials", argc, argv); - if (talloc_reference(mprMemCtx(), cmdline_credentials) == NULL) { - return -1; - } - return ejs_credentials_obj(obj, cmdline_credentials); -} - -/* - setup C functions that be called from ejs -*/ -void smb_setup_ejs_credentials(void) -{ - ejsDefineCFunction(-1, "credentials_init", ejs_credentials_init, NULL, MPR_VAR_SCRIPT_HANDLE); -} - diff --git a/source4/scripting/ejs/smbcalls_ldb.c b/source4/scripting/ejs/smbcalls_ldb.c deleted file mode 100644 index 4a157945af..0000000000 --- a/source4/scripting/ejs/smbcalls_ldb.c +++ /dev/null @@ -1,772 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide hooks into smbd C calls from ejs scripts - - Copyright (C) Andrew Tridgell 2005 - Copyright (C) Jelmer Vernooij 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 . -*/ - -#include "includes.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/appweb/ejs/ejs.h" -#include "lib/ldb/include/ldb.h" -#include "lib/ldb/include/ldb_errors.h" -#include "ldb_wrap.h" -#include "dsdb/samdb/samdb.h" -#include "librpc/ndr/libndr.h" -#include "libcli/security/security.h" - -/* - get the connected db - */ -static struct ldb_context *ejs_get_ldb_context(int eid) -{ - struct ldb_context *ldb = (struct ldb_context *)mprGetThisPtr(eid, "db"); - if (ldb == NULL) { - ejsSetErrorMsg(eid, "invalid ldb connection"); - } - return ldb; -} - -/* - perform an ldb search, returning an array of results - - syntax: - res = ldb.search("expression"); - var attrs = new Array("attr1", "attr2", "attr3"); - ldb.search("expression", attrs); - var basedn = "cn=this,dc=is,dc=a,dc=test"; - ldb.search("expression", basedn, ldb.SCOPE_SUBTREE, attrs); - ldb.search("expression", basedn, ldb.SCOPE_SUBTREE, attrs, controls); -*/ -static int ejs_ldbSearch(MprVarHandle eid, int argc, struct MprVar **argv) -{ - const char **attrs = NULL; - const char *expression; - const char *base = NULL; - struct ldb_dn *basedn = NULL; - int scope = LDB_SCOPE_DEFAULT; - TALLOC_CTX *tmp_ctx = talloc_new(mprMemCtx()); - struct ldb_context *ldb; - int ret; - struct ldb_control **parsed_controls = NULL; - struct ldb_result *res=NULL; - struct ldb_request *req; - - /* validate arguments */ - if (argc < 1 || argc > 5) { - ejsSetErrorMsg(eid, "ldb.search invalid number of arguments"); - goto failed; - } - if (argc > 3 && argv[3]->type != MPR_TYPE_OBJECT) { - ejsSetErrorMsg(eid, "ldb.search attributes must be an object"); - goto failed; - } - - ldb = ejs_get_ldb_context(eid); - if (ldb == NULL) { - return -1; - } - - expression = mprToString(argv[0]); - if (argc > 1) { - base = mprToString(argv[1]); - /* a null basedn is valid */ - } - if (base != NULL) { - basedn = ldb_dn_new(tmp_ctx, ldb, base); - if ( ! ldb_dn_validate(basedn)) { - ejsSetErrorMsg(eid, "ldb.search malformed base dn"); - goto failed; - } - } else { - basedn = ldb_get_default_basedn(ldb); - } - if (argc > 2) { - scope = mprToInt(argv[2]); - switch (scope) { - case LDB_SCOPE_DEFAULT: - case LDB_SCOPE_BASE: - case LDB_SCOPE_ONELEVEL: - case LDB_SCOPE_SUBTREE: - break; /* ok */ - default: - ejsSetErrorMsg(eid, "ldb.search invalid scope"); - goto failed; - } - } - if (argc > 3) { - attrs = mprToList(tmp_ctx, argv[3]); - } - if (argc > 4) { - const char **controls; - controls = mprToList(tmp_ctx, argv[4]); - if (controls) { - parsed_controls = ldb_parse_control_strings(ldb, tmp_ctx, controls); - if (!parsed_controls) { - ejsSetErrorMsg(eid, "ldb.search cannot parse controls: %s", - ldb_errstring(ldb)); - goto failed; - } - } - } - - res = talloc_zero(tmp_ctx, struct ldb_result); - if (!res) { - return LDB_ERR_OPERATIONS_ERROR; - } - - ret = ldb_build_search_req(&req, ldb, tmp_ctx, - basedn, - scope, - expression, - attrs, - parsed_controls, - res, - ldb_search_default_callback); - - if (ret == LDB_SUCCESS) { - - ldb_set_timeout(ldb, req, 0); /* use default timeout */ - - ret = ldb_request(ldb, req); - - if (ret == LDB_SUCCESS) { - ret = ldb_wait(req->handle, LDB_WAIT_ALL); - } - } - - if (ret != LDB_SUCCESS) { - ejsSetErrorMsg(eid, "ldb.search failed - %s", ldb_errstring(ldb)); - mpr_Return(eid, mprLdbResult(ldb, ret, NULL)); - } else { - mpr_Return(eid, mprLdbResult(ldb, ret, res)); - } - - talloc_free(tmp_ctx); - return 0; - -failed: - talloc_free(tmp_ctx); - return -1; -} - - -/* - perform an ldb add or modify -*/ -static int ejs_ldbAddModify(MprVarHandle eid, int argc, struct MprVar **argv, - int fn(struct ldb_context *, const struct ldb_message *)) -{ - const char *ldifstring; - struct ldb_context *ldb; - struct ldb_ldif *ldif; - int ret = 0, count=0; - - if (argc != 1) { - ejsSetErrorMsg(eid, "ldb.add/modify invalid arguments"); - return -1; - } - - ldifstring = mprToString(argv[0]); - if (ldifstring == NULL) { - ejsSetErrorMsg(eid, "ldb.add/modify invalid arguments"); - return -1; - } - - ldb = ejs_get_ldb_context(eid); - if (ldb == NULL) { - return -1; - } - - while ((ldif = ldb_ldif_read_string(ldb, &ldifstring))) { - count++; - ret = fn(ldb, ldif->msg); - talloc_free(ldif); - if (ret != 0) break; - } - - if (count == 0) { - ejsSetErrorMsg(eid, "ldb.add/modify invalid ldif"); - return -1; - } - - mpr_Return(eid, mprLdbResult(ldb, ret, NULL)); - return 0; -} - - -/* - perform an ldb delete - usage: - ok = ldb.delete(dn); -*/ -static int ejs_ldbDelete(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct ldb_dn *dn; - struct ldb_context *ldb; - int ret; - - if (argc != 1) { - ejsSetErrorMsg(eid, "ldb.delete invalid arguments"); - return -1; - } - - ldb = ejs_get_ldb_context(eid); - if (ldb == NULL) { - return -1; - } - - dn = ldb_dn_new(ldb, ldb, mprToString(argv[0])); - if ( ! ldb_dn_validate(dn)) { - ejsSetErrorMsg(eid, "ldb.delete malformed dn"); - return -1; - } - - ret = ldb_delete(ldb, dn); - - talloc_free(dn); - - mpr_Return(eid, mprLdbResult(ldb, ret, NULL)); - return 0; -} - -/* - perform an ldb rename - usage: - ok = ldb.rename(dn1, dn2); -*/ -static int ejs_ldbRename(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct ldb_dn *dn1, *dn2; - struct ldb_context *ldb; - int ret; - - if (argc != 2) { - ejsSetErrorMsg(eid, "ldb.rename invalid arguments"); - return -1; - } - - ldb = ejs_get_ldb_context(eid); - if (ldb == NULL) { - return -1; - } - - dn1 = ldb_dn_new(ldb, ldb, mprToString(argv[0])); - dn2 = ldb_dn_new(ldb, ldb, mprToString(argv[1])); - if ( ! ldb_dn_validate(dn1) || ! ldb_dn_validate(dn2)) { - ejsSetErrorMsg(eid, "ldb.rename invalid or malformed arguments"); - return -1; - } - - ret = ldb_rename(ldb, dn1, dn2); - - talloc_free(dn1); - talloc_free(dn2); - - mpr_Return(eid, mprLdbResult(ldb, ret, NULL)); - return 0; -} - -/* - get last error message - usage: - ok = ldb.errstring(); -*/ -static int ejs_ldbErrstring(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct ldb_context *ldb; - - ldb = ejs_get_ldb_context(eid); - if (ldb == NULL) { - return -1; - } - - mpr_Return(eid, mprString(ldb_errstring(ldb))); - return 0; -} - -/* - base64 encode - usage: - dataout = ldb.encode(datain) - */ -static int ejs_base64encode(MprVarHandle eid, int argc, struct MprVar **argv) -{ - char *ret; - - if (argc != 1) { - ejsSetErrorMsg(eid, "ldb.base64encode invalid argument count"); - return -1; - } - - if (argv[0]->type == MPR_TYPE_STRING) { - const char *orig = mprToString(argv[0]); - ret = ldb_base64_encode(mprMemCtx(), orig, strlen(orig)); - } else { - DATA_BLOB *blob; - - blob = mprToDataBlob(argv[0]); - mprAssert(blob); - ret = ldb_base64_encode(mprMemCtx(), (char *)blob->data, blob->length); - } - - if (!ret) { - mpr_Return(eid, mprCreateUndefinedVar()); - } else { - mpr_Return(eid, mprString(ret)); - } - - talloc_free(ret); - - return 0; -} - -/* - base64 decode - usage: - dataout = ldb.decode(datain) - */ -static int ejs_base64decode(MprVarHandle eid, int argc, struct MprVar **argv) -{ - char *tmp; - int ret; - - if (argc != 1) { - ejsSetErrorMsg(eid, "ldb.base64encode invalid argument count"); - return -1; - } - - tmp = talloc_strdup(mprMemCtx(), mprToString(argv[0])); - ret = ldb_base64_decode(tmp); - if (ret == -1) { - mpr_Return(eid, mprCreateUndefinedVar()); - } else { - DATA_BLOB blob; - blob.data = (uint8_t *)tmp; - blob.length = ret; - mpr_Return(eid, mprDataBlob(blob)); - } - - talloc_free(tmp); - - return 0; -} - -/* - escape a DN - usage: - dataout = ldb.dn_escape(datain) - */ -static int ejs_dn_escape(MprVarHandle eid, int argc, struct MprVar **argv) -{ - char *ret; - struct ldb_val val; - - if (argc != 1) { - ejsSetErrorMsg(eid, "ldb.dn_escape invalid argument count"); - return -1; - } - - val = data_blob_string_const(mprToString(argv[0])); - - ret = ldb_dn_escape_value(mprMemCtx(), val); - if (ret == NULL) { - mpr_Return(eid, mprCreateUndefinedVar()); - } else { - mpr_Return(eid, mprString(ret)); - talloc_free(ret); - } - - return 0; -} - -/* - perform an ldb add - - syntax: - ok = ldb.add(ldifstring); -*/ -static int ejs_ldbAdd(MprVarHandle eid, int argc, struct MprVar **argv) -{ - return ejs_ldbAddModify(eid, argc, argv, ldb_add); -} - -/* - perform an ldb modify - - syntax: - ok = ldb.modify(ldifstring); -*/ -static int ejs_ldbModify(MprVarHandle eid, int argc, struct MprVar **argv) -{ - return ejs_ldbAddModify(eid, argc, argv, ldb_modify); -} - -/* - connect to a database - usage: - ok = ldb.connect(dbfile); - ok = ldb.connect(dbfile, "modules:modlist"); - - ldb.credentials or ldb.session_info may be setup first - -*/ -static int ejs_ldbConnect(MprVarHandle eid, int argc, char **argv) -{ - struct ldb_context *ldb; - struct auth_session_info *session_info = NULL; - struct cli_credentials *creds = NULL; - struct MprVar *credentials, *session; - struct MprVar *this = mprGetProperty(ejsGetLocalObject(eid), "this", 0); - - const char *dbfile; - - if (argc < 1) { - ejsSetErrorMsg(eid, "ldb.connect invalid arguments"); - return -1; - } - - credentials = mprGetProperty(this, "credentials", NULL); - if (credentials) { - creds = talloc_get_type(mprGetPtr(credentials, "creds"), struct cli_credentials); - } - - session = mprGetProperty(this, "session_info", NULL); - if (session) { - session_info = talloc_get_type(mprGetPtr(session, "session_info"), struct auth_session_info); - } - - dbfile = argv[0]; - - ldb = ldb_wrap_connect(mprMemCtx(), mprEventCtx(), mprLpCtx(), dbfile, - session_info, creds, - 0, (const char **)(argv+1)); - if (ldb == NULL) { - ejsSetErrorMsg(eid, "ldb.connect failed to open %s", dbfile); - } - - mprSetThisPtr(eid, "db", ldb); - mpr_Return(eid, mprCreateBoolVar(ldb != NULL)); - return 0; -} - - -/* - close a db connection -*/ -static int ejs_ldbClose(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct ldb_context *ldb; - - if (argc != 0) { - ejsSetErrorMsg(eid, "ldb.close invalid arguments"); - return -1; - } - - ldb = ejs_get_ldb_context(eid); - if (ldb == NULL) { - return -1; - } - - mprSetThisPtr(eid, "db", NULL); - mpr_Return(eid, mprCreateBoolVar(true)); - return 0; -} - - -/* - start a ldb transaction - usage: - ok = ldb.transaction_start(); -*/ -static int ejs_ldbTransactionStart(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct ldb_context *ldb; - int ret; - - if (argc != 0) { - ejsSetErrorMsg(eid, "ldb.transaction_start invalid arguments"); - return -1; - } - - ldb = ejs_get_ldb_context(eid); - if (ldb == NULL) { - return -1; - } - - ret = ldb_transaction_start(ldb); - - mpr_Return(eid, mprCreateBoolVar(ret == 0)); - return 0; -} - -/* - cancel a ldb transaction - usage: - ok = ldb.transaction_cancel(); -*/ -static int ejs_ldbTransactionCancel(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct ldb_context *ldb; - int ret; - - if (argc != 0) { - ejsSetErrorMsg(eid, "ldb.transaction_cancel invalid arguments"); - return -1; - } - - ldb = ejs_get_ldb_context(eid); - if (ldb == NULL) { - return -1; - } - - ret = ldb_transaction_cancel(ldb); - - mpr_Return(eid, mprCreateBoolVar(ret == 0)); - return 0; -} - -/* - commit a ldb transaction - usage: - ok = ldb.transaction_commit(); -*/ -static int ejs_ldbTransactionCommit(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct ldb_context *ldb; - int ret; - - if (argc != 0) { - ejsSetErrorMsg(eid, "ldb.transaction_commit invalid arguments"); - return -1; - } - - ldb = ejs_get_ldb_context(eid); - if (ldb == NULL) { - return -1; - } - - ret = ldb_transaction_commit(ldb); - - mpr_Return(eid, mprCreateBoolVar(ret == 0)); - return 0; -} - -/* - commit a ldb attach a dsdb_schema from ldif files - usage: - ok = ldb.attach_dsdb_schema_from_ldif("prefixMap ldif content", "definition ldif content") -*/ -static int ejs_ldb_attach_dsdb_schema_from_ldif(MprVarHandle eid, int argc, char **argv) -{ - struct ldb_context *ldb; - WERROR status; - const char *pf; - const char *df; - - if (argc != 2) { - ejsSetErrorMsg(eid, "ldb.attach_dsdb_schema_from_ldif invalid arguments"); - return -1; - } - - ldb = ejs_get_ldb_context(eid); - if (ldb == NULL) { - return -1; - } - - pf = argv[0]; - df = argv[1]; - - status = dsdb_attach_schema_from_ldif_file(ldb, pf, df); - - mpr_Return(eid, mprWERROR(status)); - return 0; -} - -/* - set a particular invocationId against the running LDB - usage: - ok = ldb.set_ntds_invocationId("7729aa4b-f990-41ad-b81a-8b6a14090f41"); -*/ -static int ejs_ldb_set_ntds_invocationId(MprVarHandle eid, int argc, char **argv) -{ - struct ldb_context *ldb; - NTSTATUS status; - struct GUID guid; - char *guid_str; - bool ok; - - if (argc != 1) { - ejsSetErrorMsg(eid, "ldb.set_ntds_invocationId invalid arguments"); - return -1; - } - - ldb = ejs_get_ldb_context(eid); - if (ldb == NULL) { - return -1; - } - - guid_str = argv[0]; - - status = GUID_from_string(guid_str, &guid); - if (!NT_STATUS_IS_OK(status)) { - ejsSetErrorMsg(eid, "ldb.set_ntds_invocationId - failed to parse GUID '%s' %s\n", - guid_str, nt_errstr(status)); - return -1; - } - - ok = samdb_set_ntds_invocation_id(ldb, &guid); - if (!ok) { - ejsSetErrorMsg(eid, "ldb.set_ntds_invocationId - failed to set cached ntds invocationId\n"); - return -1; - } - - mpr_Return(eid, mprCreateBoolVar(ok)); - return 0; -} - -/* - attach a particular ntds objectGUID against the current ldb - usage: - ok = ldb.set_ntds_objectGUID("7729aa4b-f990-41ad-b81a-8b6a14090f41"); -*/ -static int ejs_ldb_set_ntds_objectGUID(MprVarHandle eid, int argc, char **argv) -{ - struct ldb_context *ldb; - NTSTATUS status; - struct GUID guid; - char *guid_str; - bool ok; - - if (argc != 1) { - ejsSetErrorMsg(eid, "ldb.set_ntds_objectGUID invalid arguments"); - return -1; - } - - ldb = ejs_get_ldb_context(eid); - if (ldb == NULL) { - return -1; - } - - guid_str = argv[0]; - - status = GUID_from_string(guid_str, &guid); - if (!NT_STATUS_IS_OK(status)) { - ejsSetErrorMsg(eid, "ldb.set_ntds_objectGUID - failed to parse GUID '%s' %s\n", - guid_str, nt_errstr(status)); - return -1; - } - - ok = samdb_set_ntds_invocation_id(ldb, &guid); - if (!ok) { - ejsSetErrorMsg(eid, "ldb.set_ntds_objectGUID - failed to set cached ntds invocationId\n"); - return -1; - } - - mpr_Return(eid, mprCreateBoolVar(ok)); - return 0; -} - -/* - attach a particular domain SID against the current ldb - usage: - ok = ldb.set_domain_sid("S-S-1-5-21-3065342217-3567412576-2214182334"); -*/ -static int ejs_ldb_set_domain_sid(MprVarHandle eid, int argc, char **argv) -{ - struct ldb_context *ldb; - struct dom_sid *dom_sid; - char *dom_sid_str; - bool ok; - - if (argc != 1) { - ejsSetErrorMsg(eid, "ldb.set_domain_sid invalid arguments"); - return -1; - } - - ldb = ejs_get_ldb_context(eid); - if (ldb == NULL) { - return -1; - } - - dom_sid_str = argv[0]; - - dom_sid = dom_sid_parse_talloc(NULL, dom_sid_str); - if (!dom_sid) { - ejsSetErrorMsg(eid, "ldb.set_domain_sid - failed to parse domain sid '%s'\n", - dom_sid_str); - return -1; - } - - ok = samdb_set_domain_sid(ldb, dom_sid); - talloc_free(dom_sid); - if (!ok) { - ejsSetErrorMsg(eid, "ldb.set_domain_sid - failed to set cached ntds invocationId\n"); - return -1; - } - - mpr_Return(eid, mprCreateBoolVar(ok)); - return 0; -} - -/* - initialise ldb ejs subsystem -*/ -static int ejs_ldb_init(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct MprVar *ldb = mprInitObject(eid, "ldb", argc, argv); - - mprSetStringCFunction(ldb, "connect", ejs_ldbConnect); - mprSetCFunction(ldb, "search", ejs_ldbSearch); - mprSetCFunction(ldb, "add", ejs_ldbAdd); - mprSetCFunction(ldb, "modify", ejs_ldbModify); - mprSetCFunction(ldb, "del", ejs_ldbDelete); - mprSetCFunction(ldb, "rename", ejs_ldbRename); - mprSetCFunction(ldb, "errstring", ejs_ldbErrstring); - mprSetCFunction(ldb, "encode", ejs_base64encode); - mprSetCFunction(ldb, "decode", ejs_base64decode); - mprSetCFunction(ldb, "dn_escape", ejs_dn_escape); - mprSetCFunction(ldb, "close", ejs_ldbClose); - mprSetCFunction(ldb, "transaction_start", ejs_ldbTransactionStart); - mprSetCFunction(ldb, "transaction_cancel", ejs_ldbTransactionCancel); - mprSetCFunction(ldb, "transaction_commit", ejs_ldbTransactionCommit); - mprSetStringCFunction(ldb, "attach_dsdb_schema_from_ldif", - ejs_ldb_attach_dsdb_schema_from_ldif); - mprSetStringCFunction(ldb, "set_ntds_invocationId", - ejs_ldb_set_ntds_invocationId); - mprSetStringCFunction(ldb, "set_ntds_objectGUID", - ejs_ldb_set_ntds_objectGUID); - mprSetStringCFunction(ldb, "set_domain_sid", - ejs_ldb_set_domain_sid); - mprSetVar(ldb, "SCOPE_BASE", mprCreateNumberVar(LDB_SCOPE_BASE)); - mprSetVar(ldb, "SCOPE_ONE", mprCreateNumberVar(LDB_SCOPE_ONELEVEL)); - mprSetVar(ldb, "SCOPE_SUBTREE", mprCreateNumberVar(LDB_SCOPE_SUBTREE)); - mprSetVar(ldb, "SCOPE_DEFAULT", mprCreateNumberVar(LDB_SCOPE_DEFAULT)); - - return 0; -} - - -/* - setup C functions that be called from ejs -*/ -NTSTATUS smb_setup_ejs_ldb(void) -{ - ejsDefineCFunction(-1, "ldb_init", ejs_ldb_init, NULL, MPR_VAR_SCRIPT_HANDLE); - return NT_STATUS_OK; -} diff --git a/source4/scripting/ejs/smbcalls_options.c b/source4/scripting/ejs/smbcalls_options.c deleted file mode 100644 index 93872baa40..0000000000 --- a/source4/scripting/ejs/smbcalls_options.c +++ /dev/null @@ -1,193 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide a command line options parsing function for ejs - - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "includes.h" -#include "lib/cmdline/popt_common.h" -#include "scripting/ejs/smbcalls.h" - - -/* - usage: - options = GetOptions(argv, - "realm=s", - "enablexx", - "myint=i"); - - the special options POPT_COMMON_* options are recognised and replaced - with the Samba internal options - - resulting parsed options are placed in the options object - - additional command line arguments are placed in options.ARGV -*/ - -static int ejs_GetOptions(MprVarHandle eid, int argc, struct MprVar **argv) -{ - poptContext pc; - int opt; - struct { - const char *name; - struct poptOption *table; - const char *description; - } tables[] = { - { "POPT_AUTOHELP", poptHelpOptions, "Help options:" }, - { "POPT_COMMON_SAMBA", popt_common_samba, "Common Samba options:" }, - { "POPT_COMMON_CONNECTION", popt_common_connection, "Connection options:" }, - { "POPT_COMMON_CREDENTIALS", popt_common_credentials, "Authentication options:" }, - { "POPT_COMMON_VERSION", popt_common_version, "Common Samba options:" } - }; - - struct MprVar *options = mprInitObject(eid, "options", 0, NULL); - - TALLOC_CTX *tmp_ctx = talloc_new(mprMemCtx()); - struct poptOption *long_options = NULL; - int i, num_options = 0; - int opt_argc; - const char **opt_argv; - const char **opt_names = NULL; - const int BASE_OPTNUM = 0x100000; - - /* validate arguments */ - if (argc < 1 || argv[0]->type != MPR_TYPE_OBJECT) { - ejsSetErrorMsg(eid, "GetOptions invalid arguments"); - return -1; - } - - opt_argv = mprToArray(tmp_ctx, argv[0]); - opt_argc = str_list_length(opt_argv); - - long_options = talloc_array(tmp_ctx, struct poptOption, 1); - if (long_options == NULL) { - return -1; - } - - /* create the long_options array */ - for (i=1;itype != MPR_TYPE_STRING) { - ejsSetErrorMsg(eid, "GetOptions string argument"); - return -1; - } - - long_options = talloc_realloc(tmp_ctx, long_options, - struct poptOption, num_options+2); - if (long_options == NULL) { - return -1; - } - ZERO_STRUCT(long_options[num_options]); - - /* see if its one of the special samba option tables */ - for (t=0;t= num_options + BASE_OPTNUM) { - char *err; - err = talloc_asprintf(tmp_ctx, "%s: %s", - poptBadOption(pc, POPT_BADOPTION_NOALIAS), - poptStrerror(opt)); - mprSetVar(options, "ERROR", mprString(err)); - talloc_free(tmp_ctx); - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; - } - opt -= BASE_OPTNUM; - arg = poptGetOptArg(pc); - if (arg == NULL) { - mprSetVar(options, opt_names[opt], mprCreateBoolVar(1)); - } else if (long_options[opt].argInfo == POPT_ARG_INT) { - int v = strtol(arg, NULL, 0); - mprSetVar(options, opt_names[opt], mprCreateIntegerVar(v)); - } else { - mprSetVar(options, opt_names[opt], mprString(arg)); - } - } - - /* setup options.argv list */ - mprSetVar(options, "ARGV", mprList("ARGV", poptGetArgs(pc))); - - poptFreeContext(pc); - - talloc_free(tmp_ctx); - - /* setup methods */ - mprSetCFunction(options, "get_credentials", ejs_credentials_cmdline); - - return 0; -} - - - -/* - setup C functions that be called from ejs -*/ -void smb_setup_ejs_options(void) -{ - ejsDefineCFunction(-1, "GetOptions", ejs_GetOptions, NULL, MPR_VAR_SCRIPT_HANDLE); -} diff --git a/source4/scripting/ejs/smbcalls_string.c b/source4/scripting/ejs/smbcalls_string.c deleted file mode 100644 index 541303ff2d..0000000000 --- a/source4/scripting/ejs/smbcalls_string.c +++ /dev/null @@ -1,529 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide access to string functions - - Copyright (C) Andrew Tridgell 2005 - Copyright (C) Jelmer Vernooij 2005 (substr) - - 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 . -*/ - -#include "includes.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/appweb/ejs/ejs.h" - -/* - usage: - var len = strlen(str); -*/ -static int ejs_strlen(MprVarHandle eid, int argc, char **argv) -{ - if (argc != 1) { - ejsSetErrorMsg(eid, "strlen invalid arguments"); - return -1; - } - mpr_Return(eid, mprCreateIntegerVar(strlen_m(argv[0]))); - return 0; -} - -/* - usage: - var s = strlower("UPPER"); -*/ -static int ejs_strlower(MprVarHandle eid, int argc, char **argv) -{ - char *s; - if (argc != 1) { - ejsSetErrorMsg(eid, "strlower invalid arguments"); - return -1; - } - s = strlower_talloc(mprMemCtx(), argv[0]); - mpr_Return(eid, mprString(s)); - talloc_free(s); - return 0; -} - -/* - usage: - var s = strupper("lower"); -*/ -static int ejs_strupper(MprVarHandle eid, int argc, char **argv) -{ - char *s; - if (argc != 1) { - ejsSetErrorMsg(eid, "strupper invalid arguments"); - return -1; - } - s = strupper_talloc(mprMemCtx(), argv[0]); - mpr_Return(eid, mprString(s)); - talloc_free(s); - return 0; -} - -/* - usage: - var s = strstr(string, substring); -*/ -static int ejs_strstr(MprVarHandle eid, int argc, char **argv) -{ - char *s; - if (argc != 2) { - ejsSetErrorMsg(eid, "strstr invalid arguments"); - return -1; - } - s = strstr(argv[0], argv[1]); - mpr_Return(eid, mprString(s)); - return 0; -} - -/* - usage: - var s = strspn(string, legal_chars_string); -*/ -static int ejs_strspn(MprVarHandle eid, int argc, char **argv) -{ - int len; - if (argc != 2) { - ejsSetErrorMsg(eid, "strspn invalid arguments"); - return -1; - } - len = strspn(argv[0], argv[1]); - mpr_Return(eid, mprCreateIntegerVar(len)); - return 0; -} - -/* - usage: - list = split(".", "a.foo.bar"); - list = split(".", "a.foo.bar", count); - - count is an optional count of how many splits to make - - NOTE: does not take a regular expression, unlike perl split() -*/ -static int ejs_split(MprVarHandle eid, int argc, struct MprVar **argv) -{ - const char *separator, *s; - char *p; - struct MprVar ret; - int count = 0, maxcount=0; - TALLOC_CTX *tmp_ctx = talloc_new(mprMemCtx()); - if (argc < 2 || - argv[0]->type != MPR_TYPE_STRING || - argv[1]->type != MPR_TYPE_STRING) { - ejsSetErrorMsg(eid, "split invalid arguments"); - return -1; - } - separator = mprToString(argv[0]); - s = mprToString(argv[1]); - if (argc == 3) { - maxcount = mprToInt(argv[2]); - } - - ret = mprArray("list"); - - while ((p = strstr(s, separator))) { - char *s2 = talloc_strndup(tmp_ctx, s, (int)(p-s)); - mprAddArray(&ret, count++, mprString(s2)); - talloc_free(s2); - s = p + strlen(separator); - if (maxcount != 0 && count >= maxcount) { - break; - } - } - if (*s) { - mprAddArray(&ret, count++, mprString(s)); - } - talloc_free(tmp_ctx); - mpr_Return(eid, ret); - return 0; -} - -/* - usage: - str = substr(orig[, start_offset[, length]]); - - special cases: - if start_offset < 0 then start_offset+=strlen(orig) - if length < 0 then length+=strlen(orig)-start_offset - - (as found in many other languages) -*/ -static int ejs_substr(MprVarHandle eid, int argc, struct MprVar **argv) -{ - int start_offset = 0; - int length = 0; - const char *orig; - char *target; - - if (argc < 1 || argc > 3 || - argv[0]->type != MPR_TYPE_STRING) { - ejsSetErrorMsg(eid, "substr invalid arguments"); - return -1; - } - - if (argc == 1) { - mpr_Return(eid, *argv[0]); - return 0; - } - - orig = mprToString(argv[0]); - start_offset = mprToInt(argv[1]); - length = strlen(orig); - if (start_offset < 0) start_offset += strlen(orig); - if (start_offset < 0 || start_offset > strlen(orig)) { - ejsSetErrorMsg(eid, "substr arg 2 out of bounds ([%s], %d)", orig, start_offset); - return -1; - } - - if (argc == 3) { - length = mprToInt(argv[2]); - if (length < 0) length += strlen(orig) - start_offset; - if (length < 0 || length+start_offset > strlen(orig)) { - ejsSetErrorMsg(eid, "substr arg 3 out of bounds ([%s], %d, %d)", orig, start_offset, length); - return -1; - } - } - - target = talloc_strndup(mprMemCtx(), orig+start_offset, length); - - mpr_Return(eid, mprString(target)); - - talloc_free(target); - - return 0; -} - -/* - usage: - str = join("DC=", list); -*/ -static int ejs_join(MprVarHandle eid, int argc, struct MprVar **argv) -{ - int i; - const char *separator; - char *ret = NULL; - const char **list; - TALLOC_CTX *tmp_ctx = talloc_new(mprMemCtx()); - if (argc != 2 || - argv[0]->type != MPR_TYPE_STRING || - argv[1]->type != MPR_TYPE_OBJECT) { - ejsSetErrorMsg(eid, "join invalid arguments"); - return -1; - } - - separator = mprToString(argv[0]); - list = mprToArray(tmp_ctx, argv[1]); - - if (list == NULL || list[0] == NULL) { - talloc_free(tmp_ctx); - mpr_Return(eid, mprString(NULL)); - return 0; - } - - ret = talloc_strdup(tmp_ctx, list[0]); - if (ret == NULL) { - goto failed; - } - for (i=1;list[i];i++) { - ret = talloc_asprintf_append_buffer(ret, "%s%s", separator, list[i]); - if (ret == NULL) { - goto failed; - } - } - mpr_Return(eid, mprString(ret)); - talloc_free(tmp_ctx); - return 0; -failed: - ejsSetErrorMsg(eid, "out of memory"); - return -1; -} - - -/* - blergh, C certainly makes this hard! - usage: - str = sprintf("i=%d s=%7s", 7, "foo"); -*/ -typedef char *(*_asprintf_append_t)(char *, const char *, ...); -static int ejs_sprintf(MprVarHandle eid, int argc, struct MprVar **argv) -{ - const char *format; - const char *p; - char *ret; - int a = 1; - _asprintf_append_t _asprintf_append; - TALLOC_CTX *tmp_ctx; - if (argc < 1 || argv[0]->type != MPR_TYPE_STRING) { - ejsSetErrorMsg(eid, "sprintf invalid arguments"); - return -1; - } - format = mprToString(argv[0]); - tmp_ctx = talloc_new(mprMemCtx()); - ret = talloc_strdup(tmp_ctx, ""); - - /* avoid all the format string warnings */ - _asprintf_append = (_asprintf_append_t)talloc_asprintf_append_buffer; - - /* - hackity hack ... - */ - while ((p = strchr(format, '%'))) { - char *fmt2; - int len, len_count=0; - char *tstr; - ret = talloc_asprintf_append_buffer(ret, "%*.*s", - (int)(p-format), (int)(p-format), - format); - if (ret == NULL) goto failed; - format += (int)(p-format); - len = strcspn(p+1, "dxuiofgGpXeEFcs%") + 1; - fmt2 = talloc_strndup(tmp_ctx, p, len+1); - if (fmt2 == NULL) goto failed; - len_count = count_chars(fmt2, '*'); - /* find the type string */ - tstr = &fmt2[len]; - while (tstr > fmt2 && isalpha((unsigned char)tstr[-1])) { - tstr--; - } - if (strcmp(tstr, "%") == 0) { - ret = talloc_asprintf_append_buffer(ret, "%%"); - if (ret == NULL) { - goto failed; - } - format += len+1; - continue; - } - if (len_count > 2 || - argc < a + len_count + 1) { - ejsSetErrorMsg(eid, "sprintf: not enough arguments for format"); - goto failed; - } -#define FMT_ARG(fn, type) do { \ - switch (len_count) { \ - case 0: \ - ret = _asprintf_append(ret, fmt2, \ - (type)fn(argv[a])); \ - break; \ - case 1: \ - ret = _asprintf_append(ret, fmt2, \ - (int)mprVarToNumber(argv[a]), \ - (type)fn(argv[a+1])); \ - break; \ - case 2: \ - ret = _asprintf_append(ret, fmt2, \ - (int)mprVarToNumber(argv[a]), \ - (int)mprVarToNumber(argv[a+1]), \ - (type)fn(argv[a+2])); \ - break; \ - } \ - a += len_count + 1; \ - if (ret == NULL) { \ - goto failed; \ - } \ -} while (0) - - if (strcmp(tstr, "s")==0) FMT_ARG(mprToString, const char *); - else if (strcmp(tstr, "c")==0) FMT_ARG(*mprToString, char); - else if (strcmp(tstr, "d")==0) FMT_ARG(mprVarToNumber, int); - else if (strcmp(tstr, "ld")==0) FMT_ARG(mprVarToNumber, long); - else if (strcmp(tstr, "lld")==0) FMT_ARG(mprVarToNumber, long long); - else if (strcmp(tstr, "x")==0) FMT_ARG(mprVarToNumber, int); - else if (strcmp(tstr, "lx")==0) FMT_ARG(mprVarToNumber, long); - else if (strcmp(tstr, "llx")==0) FMT_ARG(mprVarToNumber, long long); - else if (strcmp(tstr, "X")==0) FMT_ARG(mprVarToNumber, int); - else if (strcmp(tstr, "lX")==0) FMT_ARG(mprVarToNumber, long); - else if (strcmp(tstr, "llX")==0) FMT_ARG(mprVarToNumber, long long); - else if (strcmp(tstr, "u")==0) FMT_ARG(mprVarToNumber, int); - else if (strcmp(tstr, "lu")==0) FMT_ARG(mprVarToNumber, long); - else if (strcmp(tstr, "llu")==0) FMT_ARG(mprVarToNumber, long long); - else if (strcmp(tstr, "i")==0) FMT_ARG(mprVarToNumber, int); - else if (strcmp(tstr, "li")==0) FMT_ARG(mprVarToNumber, long); - else if (strcmp(tstr, "lli")==0) FMT_ARG(mprVarToNumber, long long); - else if (strcmp(tstr, "o")==0) FMT_ARG(mprVarToNumber, int); - else if (strcmp(tstr, "lo")==0) FMT_ARG(mprVarToNumber, long); - else if (strcmp(tstr, "llo")==0) FMT_ARG(mprVarToNumber, long long); - else if (strcmp(tstr, "f")==0) FMT_ARG(mprVarToFloat, double); - else if (strcmp(tstr, "lf")==0) FMT_ARG(mprVarToFloat, double); - else if (strcmp(tstr, "g")==0) FMT_ARG(mprVarToFloat, double); - else if (strcmp(tstr, "lg")==0) FMT_ARG(mprVarToFloat, double); - else if (strcmp(tstr, "e")==0) FMT_ARG(mprVarToFloat, double); - else if (strcmp(tstr, "le")==0) FMT_ARG(mprVarToFloat, double); - else if (strcmp(tstr, "E")==0) FMT_ARG(mprVarToFloat, double); - else if (strcmp(tstr, "lE")==0) FMT_ARG(mprVarToFloat, double); - else if (strcmp(tstr, "F")==0) FMT_ARG(mprVarToFloat, double); - else if (strcmp(tstr, "lF")==0) FMT_ARG(mprVarToFloat, double); - else { - ejsSetErrorMsg(eid, "sprintf: unknown format string '%s'", fmt2); - goto failed; - } - format += len+1; - } - - ret = talloc_asprintf_append_buffer(ret, "%s", format); - mpr_Return(eid, mprString(ret)); - talloc_free(tmp_ctx); - return 0; - -failed: - talloc_free(tmp_ctx); - return -1; -} - -/* - used to build your own print function - str = vsprintf(args); -*/ -static int ejs_vsprintf(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct MprVar **args, *len, *v; - int i, ret, length; - if (argc != 1 || argv[0]->type != MPR_TYPE_OBJECT) { - ejsSetErrorMsg(eid, "vsprintf invalid arguments"); - return -1; - } - v = argv[0]; - len = mprGetProperty(v, "length", NULL); - if (len == NULL) { - ejsSetErrorMsg(eid, "vsprintf takes an array"); - return -1; - } - length = mprToInt(len); - args = talloc_array(mprMemCtx(), struct MprVar *, length); - if (args == NULL) { - return -1; - } - - for (i=0;i. -*/ - -#include "includes.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/appweb/ejs/ejs.h" -#include "lib/ldb/include/ldb.h" -#include "system/time.h" -#include "system/network.h" -#include "lib/socket/netif.h" - -/* - return the list of configured network interfaces -*/ -static int ejs_sys_interfaces(MprVarHandle eid, int argc, struct MprVar **argv) -{ - int i, count; - struct MprVar ret = mprArray("interfaces"); - struct interface *ifaces; - - load_interfaces(NULL, lp_interfaces(mprLpCtx()), &ifaces); - - count = iface_count(ifaces); - for (i=0;itype)) { - ejsSetErrorMsg(eid, "sys_unix2nttime invalid arguments"); - return -1; - } - unix_to_nt_time(&nt, mprVarToNumber(argv[0])); - v = mprCreateNumberVar(nt); - mpr_Return(eid, v); - return 0; -} - -/* - return the GMT time represented by the struct tm argument, as a time_t value -*/ -static int ejs_sys_gmmktime(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct MprVar *o; - struct tm tm; - if (argc != 1 || !mprVarIsObject(argv[0]->type)) { - ejsSetErrorMsg(eid, "sys_gmmktime invalid arguments"); - return -1; - } - - o = argv[0]; -#define TM_EL(n) tm.n = mprVarToNumber(mprGetProperty(o, #n, NULL)) - TM_EL(tm_sec); - TM_EL(tm_min); - TM_EL(tm_hour); - TM_EL(tm_mday); - TM_EL(tm_mon); - TM_EL(tm_year); - TM_EL(tm_wday); - TM_EL(tm_yday); - TM_EL(tm_isdst); -#undef TM_EL - - mpr_Return(eid, mprCreateIntegerVar(mktime(&tm))); - return 0; -} - -/* - return the given time as a gmtime structure -*/ -static int ejs_sys_gmtime(MprVarHandle eid, int argc, struct MprVar **argv) -{ - time_t t; - struct MprVar ret; - struct tm *tm; - if (argc != 1 || !mprVarIsNumber(argv[0]->type)) { - ejsSetErrorMsg(eid, "sys_gmtime invalid arguments"); - return -1; - } - t = (time_t) mprVarToNumber(argv[0]); - tm = gmtime(&t); - if (tm == NULL) { - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; - } - ret = mprObject("gmtime"); -#define TM_EL(n) mprSetVar(&ret, #n, mprCreateIntegerVar(tm->n)) - TM_EL(tm_sec); - TM_EL(tm_min); - TM_EL(tm_hour); - TM_EL(tm_mday); - TM_EL(tm_mon); - TM_EL(tm_year); - TM_EL(tm_wday); - TM_EL(tm_yday); - TM_EL(tm_isdst); -#undef TM_EL - - mpr_Return(eid, ret); - return 0; -} - -/* - return the given NT time as a time_t value -*/ -static int ejs_sys_nttime2unix(MprVarHandle eid, int argc, struct MprVar **argv) -{ - time_t t; - struct MprVar v; - if (argc != 1 || !mprVarIsNumber(argv[0]->type)) { - ejsSetErrorMsg(eid, "sys_ntgmtime invalid arguments"); - return -1; - } - t = nt_time_to_unix(mprVarToNumber(argv[0])); - v = mprCreateNumberVar(t); - mpr_Return(eid, v); - return 0; -} - -/* - return the given NT time as a gmtime structure -*/ -static int ejs_sys_ntgmtime(MprVarHandle eid, int argc, struct MprVar **argv) -{ - time_t t; - struct MprVar ret; - struct tm *tm; - if (argc != 1 || !mprVarIsNumber(argv[0]->type)) { - ejsSetErrorMsg(eid, "sys_ntgmtime invalid arguments"); - return -1; - } - t = nt_time_to_unix(mprVarToNumber(argv[0])); - tm = gmtime(&t); - if (tm == NULL) { - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; - } - ret = mprObject("gmtime"); -#define TM_EL(n) mprSetVar(&ret, #n, mprCreateIntegerVar(tm->n)) - TM_EL(tm_sec); - TM_EL(tm_min); - TM_EL(tm_hour); - TM_EL(tm_mday); - TM_EL(tm_mon); - TM_EL(tm_year); - TM_EL(tm_wday); - TM_EL(tm_yday); - TM_EL(tm_isdst); -#undef TM_EL - - mpr_Return(eid, ret); - return 0; -} - -/* - return a ldap time string from a nttime -*/ -static int ejs_sys_ldaptime(MprVarHandle eid, int argc, struct MprVar **argv) -{ - char *s; - time_t t; - if (argc != 1 || !mprVarIsNumber(argv[0]->type)) { - ejsSetErrorMsg(eid, "sys_ldaptime invalid arguments"); - return -1; - } - t = nt_time_to_unix(mprVarToNumber(argv[0])); - s = ldb_timestring(mprMemCtx(), t); - mpr_Return(eid, mprString(s)); - talloc_free(s); - return 0; -} - -/* - return a http time string from a nttime -*/ -static int ejs_sys_httptime(MprVarHandle eid, int argc, struct MprVar **argv) -{ - char *s; - time_t t; - if (argc != 1 || !mprVarIsNumber(argv[0]->type)) { - ejsSetErrorMsg(eid, "sys_httptime invalid arguments"); - return -1; - } - t = nt_time_to_unix(mprVarToNumber(argv[0])); - s = http_timestring(mprMemCtx(), t); - mpr_Return(eid, mprString(s)); - talloc_free(s); - return 0; -} - -/* - unlink a file - ok = sys.unlink(fname); -*/ -static int ejs_sys_unlink(MprVarHandle eid, int argc, char **argv) -{ - int ret; - if (argc != 1) { - ejsSetErrorMsg(eid, "sys_unlink invalid arguments"); - return -1; - } - ret = unlink(argv[0]); - mpr_Return(eid, mprCreateBoolVar(ret == 0)); - return 0; -} - -/* - load a file as a string - usage: - string = sys.file_load(filename); -*/ -static int ejs_sys_file_load(MprVarHandle eid, int argc, char **argv) -{ - char *s; - if (argc != 1) { - ejsSetErrorMsg(eid, "sys_file_load invalid arguments"); - return -1; - } - - s = file_load(argv[0], NULL, mprMemCtx()); - mpr_Return(eid, mprString(s)); - talloc_free(s); - return 0; -} - -/* - save a file from a string - usage: - ok = sys.file_save(filename, str); -*/ -static int ejs_sys_file_save(MprVarHandle eid, int argc, char **argv) -{ - bool ret; - if (argc != 2) { - ejsSetErrorMsg(eid, "sys_file_save invalid arguments"); - return -1; - } - ret = file_save(argv[0], argv[1], strlen(argv[1])); - mpr_Return(eid, mprCreateBoolVar(ret)); - return 0; -} - -/* - mkdir() - usage: - ok = sys.mkdir(dirname, mode); -*/ -static int ejs_sys_mkdir(MprVarHandle eid, int argc, struct MprVar **argv) -{ - bool ret; - char *name; - if (argc != 2) { - ejsSetErrorMsg(eid, "sys_mkdir invalid arguments, need mkdir(dirname, mode)"); - return -1; - } - if (!mprVarIsString(argv[0]->type)) { - ejsSetErrorMsg(eid, "sys_mkdir dirname not a string"); - return -1; - } - if (!mprVarIsNumber(argv[1]->type)) { - ejsSetErrorMsg(eid, "sys_mkdir mode not a number"); - return -1; - } - mprVarToString(&name, 0, NULL, argv[0]); - ret = mkdir(name, mprVarToNumber(argv[1])); - mpr_Return(eid, mprCreateBoolVar(ret == 0)); - return 0; -} - - -/* - return fields of a stat() call -*/ -static struct MprVar mpr_stat(struct stat *st) -{ - struct MprVar ret; - ret = mprObject("stat"); - -#define ST_EL(n) mprSetVar(&ret, #n, mprCreateNumberVar(st->n)) - ST_EL(st_dev); - ST_EL(st_ino); - ST_EL(st_mode); - ST_EL(st_nlink); - ST_EL(st_uid); - ST_EL(st_gid); - ST_EL(st_rdev); - ST_EL(st_size); - ST_EL(st_blksize); - ST_EL(st_blocks); - ST_EL(st_atime); - ST_EL(st_mtime); - ST_EL(st_ctime); - - return ret; -} - -/* - usage: - var st = sys.stat(filename); - returns an object containing struct stat elements -*/ -static int ejs_sys_stat(MprVarHandle eid, int argc, char **argv) -{ - struct stat st; - /* validate arguments */ - if (argc != 1) { - ejsSetErrorMsg(eid, "sys.stat invalid arguments"); - return -1; - } - if (stat(argv[0], &st) != 0) { - mpr_Return(eid, mprCreateUndefinedVar()); - } else { - mpr_Return(eid, mpr_stat(&st)); - } - return 0; -} - -/* - usage: - var st = sys.lstat(filename); - returns an object containing struct stat elements -*/ -static int ejs_sys_lstat(MprVarHandle eid, int argc, char **argv) -{ - struct stat st; - /* validate arguments */ - if (argc != 1) { - ejsSetErrorMsg(eid, "sys.stat invalid arguments"); - return -1; - } - if (lstat(argv[0], &st) != 0) { - mpr_Return(eid, mprCreateUndefinedVar()); - } else { - mpr_Return(eid, mpr_stat(&st)); - } - return 0; -} - -/* - bitwise AND - usage: - var z = sys.bitAND(x, 0x70); -*/ -static int ejs_sys_bitAND(MprVarHandle eid, int argc, struct MprVar **argv) -{ - int x, y, z; - - if (argc != 2 || - !mprVarIsNumber(argv[0]->type) || - !mprVarIsNumber(argv[1]->type)) { - ejsSetErrorMsg(eid, "bitand invalid arguments"); - return -1; - } - x = mprToInt(argv[0]); - y = mprToInt(argv[1]); - z = x & y; - - mpr_Return(eid, mprCreateIntegerVar(z)); - return 0; -} - -/* - bitwise OR - usage: - var z = sys.bitOR(x, 0x70); -*/ -static int ejs_sys_bitOR(MprVarHandle eid, int argc, struct MprVar **argv) -{ - int x, y, z; - - if (argc != 2 || - !mprVarIsNumber(argv[0]->type) || - !mprVarIsNumber(argv[1]->type)) { - ejsSetErrorMsg(eid, "bitand invalid arguments"); - return -1; - } - x = mprToInt(argv[0]); - y = mprToInt(argv[1]); - z = x | y; - - mpr_Return(eid, mprCreateIntegerVar(z)); - return 0; -} - -/* - initialise sys ejs subsystem -*/ -static int ejs_sys_init(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct MprVar *obj = mprInitObject(eid, "sys", argc, argv); - - mprSetCFunction(obj, "interfaces", ejs_sys_interfaces); - mprSetCFunction(obj, "hostname", ejs_sys_hostname); - mprSetCFunction(obj, "nttime", ejs_sys_nttime); - mprSetCFunction(obj, "gettimeofday", ejs_sys_gettimeofday); - mprSetCFunction(obj, "unix2nttime", ejs_sys_unix2nttime); - mprSetCFunction(obj, "gmmktime", ejs_sys_gmmktime); - mprSetCFunction(obj, "gmtime", ejs_sys_gmtime); - mprSetCFunction(obj, "nttime2unix", ejs_sys_nttime2unix); - mprSetCFunction(obj, "ntgmtime", ejs_sys_ntgmtime); - mprSetCFunction(obj, "ldaptime", ejs_sys_ldaptime); - mprSetCFunction(obj, "httptime", ejs_sys_httptime); - mprSetCFunction(obj, "mkdir", ejs_sys_mkdir); - mprSetStringCFunction(obj, "unlink", ejs_sys_unlink); - mprSetStringCFunction(obj, "file_load", ejs_sys_file_load); - mprSetStringCFunction(obj, "file_save", ejs_sys_file_save); - mprSetStringCFunction(obj, "stat", ejs_sys_stat); - mprSetStringCFunction(obj, "lstat", ejs_sys_lstat); - mprSetCFunction(obj, "bitAND", ejs_sys_bitAND); - mprSetCFunction(obj, "bitOR", ejs_sys_bitOR); - - return 0; -} - - -/* - setup C functions that be called from ejs -*/ -NTSTATUS smb_setup_ejs_system(void) -{ - ejsDefineCFunction(-1, "sys_init", ejs_sys_init, NULL, MPR_VAR_SCRIPT_HANDLE); - return NT_STATUS_OK; -} diff --git a/source4/scripting/ejs/smbscript.c b/source4/scripting/ejs/smbscript.c deleted file mode 100644 index db9fc9affa..0000000000 --- a/source4/scripting/ejs/smbscript.c +++ /dev/null @@ -1,129 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - Standalone client for ejs scripting. - - Copyright (C) Tim Potter 2005 - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "includes.h" -#include "lib/appweb/ejs/ejs.h" -#include "lib/appweb/ejs/ejsInternal.h" -#include "scripting/ejs/smbcalls.h" -#include "auth/gensec/gensec.h" -#include "ldb/include/ldb.h" -#include "dynconfig/dynconfig.h" - -static EjsId eid; - -_NORETURN_ static void smbscript_ejs_exception(const char *reason) -{ - Ejs *ep = ejsPtr(eid); - ejsSetErrorMsg(eid, "%s", reason); - fprintf(stderr, "%s", ep->error); - exit(127); -} - -int main(int argc, const char **argv) -{ - EjsHandle handle = 0; - MprVar result; - char *emsg, *script; - size_t script_size; - TALLOC_CTX *mem_ctx = talloc_new(NULL); - const char **argv_list = NULL; - const char *fname; - struct MprVar *return_var; - int exit_status, i; - struct loadparm_context *lp_ctx; - - fault_setup(argv[0]); - - global_loadparm = lp_ctx = loadparm_init(talloc_autofree_context()); - - if (getenv("SMB_CONF_PATH")) { - lp_load(lp_ctx, getenv("SMB_CONF_PATH")); - } else { - lp_load(lp_ctx, dyn_CONFIGFILE); - } - - gensec_init(lp_ctx); - mprSetCtx(mem_ctx); - - - if (argc < 2) { - fprintf(stderr, "You must supply a script name\n"); - exit(1); - } - - fname = argv[1]; - - if (ejsOpen(NULL, NULL, NULL) != 0) { - fprintf(stderr, "smbscript: ejsOpen(): unable to initialise " - "EJS subsystem\n"); - exit(127); - } - - smb_setup_ejs_functions(smbscript_ejs_exception); - - if ((eid = ejsOpenEngine(handle, 0)) == (EjsId)-1) { - fprintf(stderr, "smbscript: ejsOpenEngine(): unable to " - "initialise an EJS engine\n"); - exit(127); - } - - /* setup ARGV[] in the ejs environment */ - for (i=1;argv[i];i++) { - argv_list = str_list_add(argv_list, argv[i]); - } - talloc_steal(mem_ctx, argv_list); - mprSetVar(ejsGetGlobalObject(eid), "ARGV", mprList("ARGV", argv_list)); - - /* load the script and advance past interpreter line*/ - script = file_load(fname, &script_size, mem_ctx); - - if (!script) { - fprintf(stderr, "Unable to load script from '%s'\n", fname); - exit(1); - } - - /* allow scriptable js */ - if (strncmp(script, "#!", 2) == 0) { - script += strcspn(script, "\r\n"); - script += strspn(script, "\r\n"); - } - /* and this copes with the ugly exec hack */ - if (strncmp(script, "exec ", 5) == 0) { - script += strcspn(script, "\r\n"); - script += strspn(script, "\r\n"); - } - - /* run the script */ - if (ejsEvalScript(eid, script, &result, &emsg) == -1) { - fprintf(stderr, "smbscript: ejsEvalScript(): %s\n", emsg); - exit(127); - } - - return_var = ejsGetReturnValue(eid); - exit_status = mprVarToNumber(return_var); - - ejsClose(); - - talloc_free(mem_ctx); - - return exit_status; -} diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index fe78687794..02f686af0b 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -4,6 +4,7 @@ # Start SUBSYSTEM WEB [MODULE::WEB] INIT_FUNCTION = server_service_web_init +ENABLE = NO SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = ESP LIBTLS smbcalls process_model # End SUBSYSTEM WEB -- cgit From f594044d79346b0862336b9e23dc16736d16c9f7 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 16 Sep 2008 18:09:34 +0200 Subject: Remove remaining JavaScript code. --- source4/librpc/config.mk | 1 - source4/scripting/libjs/base.js | 50 ------------- testprogs/ejs/bugs.js | 155 ---------------------------------------- testprogs/ejs/sprintf.js | 31 -------- 4 files changed, 237 deletions(-) delete mode 100644 source4/scripting/libjs/base.js delete mode 100644 testprogs/ejs/bugs.js delete mode 100755 testprogs/ejs/sprintf.js diff --git a/source4/librpc/config.mk b/source4/librpc/config.mk index 8b1cec46b3..8ace68fdb2 100644 --- a/source4/librpc/config.mk +++ b/source4/librpc/config.mk @@ -743,7 +743,6 @@ python_dcerpc_security_OBJ_FILES = $(gen_ndrsrcdir)/py_security.o $(IDL_HEADER_FILES) $(IDL_NDR_PARSE_H_FILES) $(IDL_NDR_PARSE_C_FILES) \ $(IDL_NDR_CLIENT_C_FILES) $(IDL_NDR_CLIENT_H_FILES) \ $(IDL_NDR_SERVER_C_FILES) $(IDL_SWIG_FILES) \ - $(IDL_NDR_EJS_C_FILES) $(IDL_NDR_EJS_H_FILES) \ $(IDL_NDR_PY_C_FILES) $(IDL_NDR_PY_H_FILES): idl idl_full:: $(pidldir)/lib/Parse/Pidl/IDL.pm $(pidldir)/lib/Parse/Pidl/Expr.pm diff --git a/source4/scripting/libjs/base.js b/source4/scripting/libjs/base.js deleted file mode 100644 index 790dfeb3e0..0000000000 --- a/source4/scripting/libjs/base.js +++ /dev/null @@ -1,50 +0,0 @@ -/* - base js library functions - Copyright Andrew Tridgell 2005 - released under the GNU GPL version 3 or later -*/ - -if (global["HAVE_BASE_JS"] != undefined) { - return; -} -HAVE_BASE_JS=1 - -/* bring the string functions into the global frame */ -string_init(global); - -/* - an essential function! -*/ -function printf() -{ - print(vsprintf(arguments)); -} - -/* - substitute strings of the form ${NAME} in str, replacing - with substitutions from subobj -*/ -function substitute_var(str, subobj) -{ - var list = split("${", str); - var i; - for (i=1;i -*/ - - -/**************************************** -demo a bug in constructing arrays -fix at http://build.samba.org/build.pl?function=diff;tree=samba4;revision=7124 -status: FIXED -*****************************************/ -function arraybug() { - var a; - - println("First with 3 elements"); - a = new Array("one", "two", "three"); - printVars(a); - assert(a.length == 3); - assert(a[0] == "one"); - assert(a[1] == "two"); - assert(a[2] == "three"); - - println("with a array length"); - a = new Array(5); - printVars(a); - assert(a.length == 5); - - println("\nNow with 1 element"); - a = new Array("one"); - printVars(a); - assert(a.length == 1); - assert(a[0] == "one"); - - println("ALL OK"); -} - - -/**************************************** -demo a bug in variable arguments -fix at http://build.samba.org/build.pl?function=diff;tree=samba4;revision=7085 -status: FIXED -*****************************************/ -function argsbug() { - println("we should have been called with 3 arguments"); - assert(arguments.length == 3); - assert(arguments[0] == "one"); - assert(arguments[1] == "two"); - assert(arguments[2] == "three"); -} - - -/**************************************** -demo a bug in constructing objects -no fix available yet -status: SUBMITTED -*****************************************/ -function MyObj() { - var o = new Object(); - o.test = 42; - return o; -} - -function objbug() { - println("the docs say you should use 'new'"); - var o1 = new MyObj(); - var o2 = MyObj(); - printVars(o1); - printVars(o2); - assert(o1.test == 42); - assert(o2.test == 42); -} - -/* - demo a expression handling bug - status: FIXED -*/ -function exprbug() { - var a = new Array(10); - var i; - for (i=0;i<4;i++) { - a[1+(i*2)] = i; - a[2+(i*2)] = i*2; - } -} - -/**************************************** -demo lack of recursion -fix in http://build.samba.org/build.pl?function=diff;tree=samba4;revision=7127 -status: FIXED -*****************************************/ -function fibonacci(n) { - if (n < 3) { - return 1; - } - return fibonacci(n-1) + fibonacci(n-2); -} - -function recursebug() { - println("First 10 fibonacci numbers:"); - for (i=0;i<10;i++) { - println("fibonacci(" + i + ")=" + fibonacci(i)); - } -} - -/**************************************** -demo lack of function variables inside functions -status: FIXED IN SAMBA -*****************************************/ -function callback() -{ - return "testing"; -} - -function fnbug(c) -{ - s = c(); - assert(s == "testing"); -} - -/**************************************** -demo incorrect handling of reserved words in strings -status: SUBMITTED -*****************************************/ -function reservedbug() -{ - assert("funct" + "ion" == 'function'); -} - - -/**************************************** -demo incorrect handling of boolean functions -status: SUBMITTED -*****************************************/ -function no() -{ - return false; -} - -function boolbug() -{ - assert(false == no()); - assert(!no()); -} - - -/* run the tests */ -arraybug(); -argsbug("one", "two", "three"); -recursebug(); -exprbug(); -fnbug(callback); -reservedbug(); -boolbug(); -objbug(); diff --git a/testprogs/ejs/sprintf.js b/testprogs/ejs/sprintf.js deleted file mode 100755 index 6ae8605718..0000000000 --- a/testprogs/ejs/sprintf.js +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env smbscript -/* - test sprintf function -*/ - -string_init(local); - -function check_result(s, v) -{ - if (s != v) { - println("expected '" + v + "' but got '" + s + "'"); - } - assert(s == v); -} - -function xprintf() -{ - return "XX{" + vsprintf(arguments) + "}XX"; -} - -check_result(sprintf("%d", 7), "7"); -check_result(sprintf("%04d", 42), "0042"); -check_result(sprintf("my string=%7.2s", "foo%7"), "my string= fo"); -check_result(sprintf("blah=0x%*x", 4, 19), "blah=0x 13"); -check_result(sprintf("blah=0x%0*x", 4, 19), "blah=0x0013"); -check_result(sprintf("blah=%.0f", 1032), "blah=1032"); -check_result(sprintf("%4.2f%%", 72.32), "72.32%"); - -check_result(xprintf("%4.2f%% and %s", 72.32, "foo"),"XX{72.32% and foo}XX"); - -println("ALL OK"); -- cgit From f3a517a92eb6e9a4d6f315882706f0d8569abeda Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 16 Sep 2008 18:13:56 +0200 Subject: Remove minschema js tests. --- testdata/minschema_classes.txt | 41 ++ testprogs/ejs/ldb.js | 385 ----------------- testprogs/ejs/minschema.js | 804 ------------------------------------ testprogs/ejs/minschema_classes.txt | 41 -- 4 files changed, 41 insertions(+), 1230 deletions(-) create mode 100644 testdata/minschema_classes.txt delete mode 100755 testprogs/ejs/ldb.js delete mode 100755 testprogs/ejs/minschema.js delete mode 100644 testprogs/ejs/minschema_classes.txt diff --git a/testdata/minschema_classes.txt b/testdata/minschema_classes.txt new file mode 100644 index 0000000000..30f5b8ce96 --- /dev/null +++ b/testdata/minschema_classes.txt @@ -0,0 +1,41 @@ +applicationSettings +builtinDomain +classSchema +computer +configuration +container +crossRef +crossRefContainer +dMD +domain +domainDNS +foreignSecurityPrincipal +group +infrastructureUpdate +leaf +nTDSDSA +nTDSService +organizationalPerson +organizationalUnit +person +primaryDomain +rIDManager +secret +server +serversContainer +site +sitesContainer +subSchema +user +displaySpecifier +foreignSecurityPrincipal +trustedDomain +attributeSchema +subSchema +queryPolicy +groupPolicyContainer +ipsecPolicy +ipsecISAKMPPolicy +ipsecNFA +ipsecFilter +ipsecNegotiationPolicy diff --git a/testprogs/ejs/ldb.js b/testprogs/ejs/ldb.js deleted file mode 100755 index 8c71994805..0000000000 --- a/testprogs/ejs/ldb.js +++ /dev/null @@ -1,385 +0,0 @@ -#!/bin/sh -exec smbscript "$0" ${1+"$@"} -/* - demonstrate access to ldb databases from ejs -*/ - - -var ldb = ldb_init(); -var sys; -var options = GetOptions(ARGV, - "POPT_AUTOHELP", - "POPT_COMMON_SAMBA"); -if (options == undefined) { - println("Failed to parse options"); - return -1; -} - -libinclude("base.js"); - -if (options.ARGV.length != 1) { - println("Usage: ldb.js "); - return -1; -} - -prefix = options.ARGV[0]; - -function basic_tests(ldb) -{ - println("Running basic tests"); - ok = ldb.add(" -dn: cn=x,cn=test -objectClass: foo -x: 3 -"); - assert(ok.error == 0); - - println("Testing ldb.search"); - var res = ldb.search("(objectClass=*)"); - assert(res.msgs[0].objectClass[0] == "foo"); - assert(res.msgs[0].dn == "cn=x,cn=test"); - assert(res.msgs[0].x == 3); - - ok = ldb.add(" -dn: cn=x2,cn=test -objectClass: foo -x: 4 -"); - assert(ok.error == 0); - var attrs = new Array("x"); - res = ldb.search("x=4", NULL, ldb.SCOPE_DEFAULT, attrs); - assert(res.msgs[0].x == 4); - assert(res.msgs[0].objectClass == undefined); - assert(res.msgs[0].dn == "cn=x2,cn=test"); - - ok = ldb.del("cn=x,cn=test"); - assert(ok.error == 0); - - ok = ldb.rename("cn=x2,cn=test", "cn=x3,cn=test"); - assert(ok.error == 0); - res = ldb.search("x=4", NULL, ldb.SCOPE_DEFAULT, attrs); - assert(res.msgs[0].dn == "cn=x3,cn=test"); - - ok = ldb.rename("cn=x3,cn=test", "cn=X3,cn=test"); - assert(ok.error == 0); - res = ldb.search("x=4", NULL, ldb.SCOPE_DEFAULT, attrs); - assert(res.msgs[0].dn == "cn=X3,cn=test"); - - ok = ldb.modify(" -dn: cn=x3,cn=test -changetype: modify -add: x -x: 7 -"); - - res = ldb.search("x=7"); - assert(res.msgs.length == 1); - assert(res.msgs[0].x.length == 2); - - /* Check a few things before we add modules */ - assert(res.msgs[0].objectGUID == undefined); - assert(res.msgs[0].createTimestamp == undefined); - assert(res.msgs[0].whenCreated == undefined); - -} - -function setup_modules(ldb) -{ - ok = ldb.add(" -dn: @MODULES -@LIST: rootdse,operational,rdn_name,partition - -dn: @ROOTDSE -defaultNamingContext: cn=Test - -dn: @PARTITION -partition: cn=SideTest:" + prefix + "/" + "testside.ldb -partition: cn=Sub,cn=PartTest:" + prefix + "/" + "testsub.ldb -partition: cn=PartTest:" + prefix + "/" + "testpartition.ldb -partition: cn=Sub,cn=Sub,cn=PartTest:" + prefix + "/" + "testsubsub.ldb -replicateEntries: @ATTRIBUTES -replicateEntries: @INDEXLIST -modules: cn=PartTest:objectguid -"); -} - -/* Test the basic operation of the timestamps,objectguid and name_rdn - modules */ - -function modules_test(ldb, parttestldb) -{ - println("Running modules tests"); - - ok = ldb.add(" -dn: @ATTRIBUTES -cn: CASE_INSENSITIVE -caseattr: CASE_INSENSITIVE -"); - if (ok.error != 0) { - println("Failed to add: " + ok.errstr); - assert(ok.error == 0); - } - - /* Confirm that the attributes were replicated */ - var res_attrs = parttestldb.search("cn=*", "@ATTRIBUTES", parttestldb.SCOPE_BASE); - assert(res_attrs.msgs[0].cn == "CASE_INSENSITIVE"); - - ok = ldb.add(" -dn: cn=x8,cn=PartTest -objectClass: foo -x: 8 -"); - if (ok.error != 0) { - println("Failed to add: " + ok.errstr); - assert(ok.error == 0); - } - - ok = ldb.add(" -dn: cn=x9,cn=PartTest -objectClass: foo -x: 9 -cn: X9 -"); - if (ok.error != 0) { - println("Failed to add: " + ok.errstr); - assert(ok.error == 0); - } - - ok = ldb.add(" -dn: cn=X9,cn=PartTest -objectClass: foo -x: 9 -cn: X9 -"); - if (ok.error == 0) { - println("Should have failed to add cn=X9,cn=PartTest"); - assert(ok.error != 0); - } - - var res = ldb.search("x=8", "cn=PartTest", ldb.SCOPE_DEFAULT); - assert(res.msgs[0].objectGUID != undefined); - assert(res.msgs[0].uSNCreated != undefined); - assert(res.msgs[0].uSNChanged != undefined); - assert(res.msgs[0].createTimestamp == undefined); - assert(res.msgs[0].whenCreated != undefined); - assert(res.msgs[0].name == "x8"); - assert(res.msgs[0].cn == "x8"); - - /* Confirm that this ended up in the correct LDB */ - var res_otherldb = parttestldb.search("x=8", "cn=PartTest", parttestldb.SCOPE_DEFAULT); - assert(res_otherldb.msgs[0].objectGUID != undefined); - assert(res_otherldb.msgs[0].createTimestamp == undefined); - assert(res_otherldb.msgs[0].whenCreated != undefined); - assert(res_otherldb.msgs[0].name == "x8"); - assert(res_otherldb.msgs[0].cn == "x8"); - - var attrs = new Array("*", "createTimestamp"); - var res2 = ldb.search("x=9", "cn=PartTest", ldb.SCOPE_DEFAULT, attrs); - assert(res2.msgs[0].objectGUID != undefined); - assert(res2.msgs[0].createTimestamp != undefined); - assert(res2.msgs[0].whenCreated != undefined); - assert(res2.msgs[0].name == "x9"); - assert(res2.msgs[0].cn == "x9"); - - assert(res.msgs[0].objectGUID != res2.msgs[0].objectGUID); - - var attrs = new Array("*"); - var res3 = ldb.search("", "", ldb.SCOPE_BASE, attrs); - assert(res3.msgs[0].cn == undefined); - assert(res3.msgs[0].distinguishedName == undefined); - assert(res3.msgs[0].name == undefined); - assert(res3.msgs[0].currentTime != undefined); - assert(res3.msgs[0].highestCommittedUSN != undefined); - - assert(res3.msgs[0].namingContexts[0] == "cn=Sub,cn=Sub,cn=PartTest"); - assert(res3.msgs[0].namingContexts[1] == "cn=Sub,cn=PartTest"); - assert(res3.msgs[0].namingContexts[2] == "cn=PartTest"); - assert(res3.msgs[0].namingContexts[3] == "cn=SideTest"); - var usn = res3.msgs[0].highestCommittedUSN; - - /* Start a transaction. We are going to abort it later, to - * show we clean up all partitions */ - - ok = ldb.transaction_start() - if (!ok) { - println("Failed to start a transaction: " + ok.errstr); - assert(ok.error == 0); - } - - - ok = ldb.add(" -dn: cn=x10,cn=parttest -objectClass: foo -x: 10 -"); - if (ok.error != 0) { - println("Failed to add: " + ok.errstr); - assert(ok.error == 0); - } - - var attrs = new Array("highestCommittedUSN"); - var res4 = ldb.search("", "", ldb.SCOPE_BASE, attrs); - var usn2 = res4.msgs[0].highestCommittedUSN; - assert(usn < res4.msgs[0].highestCommittedUSN); - - ok = ldb.add(" -dn: cn=x11,cn=sub,cn=parttest -objectClass: foo -x: 11 -"); - if (ok.error != 0) { - println("Failed to add: " + ok.errstr); - assert(ok.error == 0); - } - - var attrs = new Array("highestCommittedUSN"); - var res5 = ldb.search("", "", ldb.SCOPE_BASE, attrs); - assert(usn2 < res5.msgs[0].highestCommittedUSN); - - var attrs = new Array("*", "createTimestamp"); - var res6 = ldb.search("x=11", "cn=parttest", ldb.SCOPE_SUB, attrs); - assert(res6.msgs.length == 0); - - var attrs = new Array("*", "createTimestamp"); - var res7 = ldb.search("x=10", "cn=sub,cn=parttest", ldb.SCOPE_DEFAULT, attrs); - assert(res7.msgs.length == 0); - - var res8 = ldb.search("x=11", "cn=sub,cn=parttest", ldb.SCOPE_DEFAULT, attrs); - - assert(res8.msgs[0].objectGUID == undefined); /* The objectGUID module is not loaded here */ - assert(res8.msgs[0].uSNCreated == undefined); /* The objectGUID module is not loaded here */ - assert(res8.msgs[0].name == "x11"); - assert(res8.msgs[0].cn == "x11"); - - ok = ldb.add(" -dn: caseattr=XY,cn=PartTest -objectClass: foo -x: Y -"); - if (ok.error != 0) { - println("Failed to add: " + ok.errstr); - assert(ok.error == 0); - } - - ok = ldb.add(" -dn: caseattr=XZ,cn=PartTest -objectClass: foo -x: Z -caseattr: XZ -"); - if (ok.error != 0) { - println("Failed to add: " + ok.errstr); - assert(ok.error == 0); - } - - ok = ldb.add(" -dn: caseattr=xz,cn=PartTest -objectClass: foo -x: Z -caseattr: xz -"); - if (ok.error == 0) { - println("Should have failed to add caseattr=xz,cn=PartTest"); - assert(ok.error != 0); - } - - ok = ldb.add(" -dn: caseattr2=XZ,cn=PartTest -objectClass: foo -x: Z -caseattr2: XZ -"); - if (ok.error != 0) { - println("Failed to add: " + ok.errstr); - assert(ok.error == 0); - } - - ok = ldb.add(" -dn: caseattr2=Xz,cn=PartTest -objectClass: foo -x: Z -caseattr2: Xz -"); - if (ok.error != 0) { - println("Failed to add: " + ok.errstr); - assert(ok.error == 0); - } - - var resX = ldb.search("caseattr=xz", "cn=parttest", ldb.SCOPE_DEFAULT, attrs); - assert(resX.msgs.length == 1); - assert(resX.msgs[0].objectGUID != undefined); - assert(resX.msgs[0].createTimestamp != undefined); - assert(resX.msgs[0].whenCreated != undefined); - assert(resX.msgs[0].name == "XZ"); - - var rescount = ldb.search("(|(caseattr=*)(cn=*))", "cn=parttest", ldb.SCOPE_DEFAULT, attrs); - assert(rescount.msgs.length == 5); - - /* Check this attribute is *not* case sensitive */ - var resXcount = ldb.search("caseattr=x*", "cn=parttest", ldb.SCOPE_DEFAULT, attrs); - assert(resXcount.msgs.length == 2); - - /* Check that this attribute *is* case sensitive */ - var resXcount2 = ldb.search("caseattr2=xz", "cn=parttest", ldb.SCOPE_DEFAULT, attrs); - assert(resXcount2.msgs.length == 0); - - - /* Now abort the transaction to show that even with - * partitions, it is aborted everywhere */ - ok = ldb.transaction_cancel(); - if (!ok) { - println("Failed to cancel a transaction: " + ok.errstr); - assert(ok); - } - - /* now check it all went away */ - - var attrs = new Array("highestCommittedUSN"); - var res9 = ldb.search("", "", ldb.SCOPE_BASE, attrs); - assert(usn == res9.msgs[0].highestCommittedUSN); - - var attrs = new Array("*"); - var res10 = ldb.search("x=11", "cn=sub,cn=parttest", ldb.SCOPE_DEFAULT, attrs); - assert(res10.msgs.length == 0); - - var attrs = new Array("*"); - var res11 = ldb.search("x=10", "cn=parttest", ldb.SCOPE_DEFAULT, attrs); - assert(res11.msgs.length == 0); - - var attrs = new Array("*"); - var res12 = ldb.search("caseattr=*", "cn=parttest", ldb.SCOPE_DEFAULT, attrs); - assert(res12.msgs.length == 0); - -} - -sys = sys_init(); -var dbfile = "test.ldb"; - -sys.unlink(prefix + "/" + dbfile); -sys.unlink(prefix + "/" + "testpartition.ldb"); -sys.unlink(prefix + "/" + "testsub.ldb"); -sys.unlink(prefix + "/" + "testsubsub.ldb"); -sys.unlink(prefix + "/" + "testside.ldb"); - -var ok = ldb.connect("tdb://" + prefix + "/" + dbfile); -assert(ok); - -basic_tests(ldb); - -setup_modules(ldb); -ldb = ldb_init(); -var ok = ldb.connect("tdb://" + prefix + "/" + dbfile); -assert(ok); - -parttestldb = ldb_init(); -var ok = parttestldb.connect("tdb://" + prefix + "/" + "testpartition.ldb"); -assert(ok); - -modules_test(ldb, parttestldb); - -sys.unlink(prefix + "/" + dbfile); -sys.unlink(prefix + "/" + "testpartition.ldb"); -sys.unlink(prefix + "/" + "testsub.ldb"); -sys.unlink(prefix + "/" + "testsubsub.ldb"); -sys.unlink(prefix + "/" + "testside.ldb"); -return 0; diff --git a/testprogs/ejs/minschema.js b/testprogs/ejs/minschema.js deleted file mode 100755 index f088501c1d..0000000000 --- a/testprogs/ejs/minschema.js +++ /dev/null @@ -1,804 +0,0 @@ -#!/bin/sh -exec smbscript "$0" ${1+"$@"} -/* - work out the minimal schema for a set of objectclasses -*/ - -libinclude("base.js"); - -var ldb = ldb_init(); - -var options = GetOptions(ARGV, - "POPT_AUTOHELP", - "POPT_COMMON_SAMBA", - "POPT_COMMON_CREDENTIALS", - "verbose", - "classes", - "attributes"); -if (options == undefined) { - println("Failed to parse options"); - return -1; -} -verbose = options["verbose"]; -dump_all = "yes"; -dump_classes = options["classes"]; -dump_attributes = options["attributes"]; - -if (dump_classes != undefined) { - dump_all = undefined; -} -if (dump_attributes != undefined) { - dump_all = undefined; -} -if (dump_all != undefined) { - dump_classes = "yes"; - dump_attributes = "yes"; -} - -if (options.ARGV.length != 2) { - println("Usage: minschema.js "); - return -1; -} - -var url = options.ARGV[0]; -var classfile = options.ARGV[1]; - -/* use command line creds if available */ -ldb.credentials = options.get_credentials(); - -var ok = ldb.connect(url); -assert(ok); - -objectclasses = new Object(); -attributes = new Object(); -rootDse = new Object(); - -objectclasses_expanded = new Object(); - -/* the attributes we need for objectclasses */ -class_attrs = new Array("objectClass", - "subClassOf", - "governsID", - "possSuperiors", - "possibleInferiors", - "mayContain", - "mustContain", - "auxiliaryClass", - "rDNAttID", - "showInAdvancedViewOnly", - "adminDisplayName", - "adminDescription", - "objectClassCategory", - "lDAPDisplayName", - "schemaIDGUID", - "systemOnly", - "systemPossSuperiors", - "systemMayContain", - "systemMustContain", - "systemAuxiliaryClass", - "defaultSecurityDescriptor", - "systemFlags", - "defaultHidingValue", - "defaultObjectCategory", - - /* this attributes are not used by w2k3 */ - "schemaFlagsEx", - "msDs-IntId", - "msDs-Schema-Extensions", - "classDisplayName", - "isDefunct"); - - -attrib_attrs = new Array("objectClass", - "attributeID", - "attributeSyntax", - "isSingleValued", - "rangeLower", - "rangeUpper", - "mAPIID", - "linkID", - "showInAdvancedViewOnly", - "adminDisplayName", - "oMObjectClass", - "adminDescription", - "oMSyntax", - "searchFlags", - "extendedCharsAllowed", - "lDAPDisplayName", - "schemaIDGUID", - "attributeSecurityGUID", - "systemOnly", - "systemFlags", - "isMemberOfPartialAttributeSet", - - /* this attributes are not used by w2k3 */ - "schemaFlagsEx", - "msDs-IntId", - "msDs-Schema-Extensions", - "classDisplayName", - "isEphemeral", - "isDefunct"); - -/* - notes: - - objectClassCategory - 1: structural - 2: abstract - 3: auxiliary -*/ - - -/* - print only if verbose is set -*/ -function dprintf() { - if (verbose != undefined) { - print(vsprintf(arguments)); - } -} - -function get_object_cn(ldb, name) { - var attrs = new Array("cn"); - - var res = ldb.search(sprintf("(ldapDisplayName=%s)", name), rootDse.schemaNamingContext, ldb.SCOPE_SUBTREE, attrs); - assert(res != undefined); - assert(res.msgs.length == 1); - - var cn = res.msgs[0]["cn"]; - assert(cn != undefined); - if (typeof(cn) == "string") { - return cn; - } - return cn[0]; -} -/* - create an objectclass object -*/ -function obj_objectClass(ldb, name) { - var o = new Object(); - o.name = name; - o.cn = get_object_cn(ldb, name); - return o; -} - -/* - create an attribute object -*/ -function obj_attribute(ldb, name) { - var o = new Object(); - o.name = name; - o.cn = get_object_cn(ldb, name); - return o; -} - - -syntaxmap = new Object(); - -syntaxmap['2.5.5.1'] = '1.3.6.1.4.1.1466.115.121.1.12'; -syntaxmap['2.5.5.2'] = '1.3.6.1.4.1.1466.115.121.1.38'; -syntaxmap['2.5.5.3'] = '1.2.840.113556.1.4.1362'; -syntaxmap['2.5.5.4'] = '1.2.840.113556.1.4.905'; -syntaxmap['2.5.5.5'] = '1.3.6.1.4.1.1466.115.121.1.26'; -syntaxmap['2.5.5.6'] = '1.3.6.1.4.1.1466.115.121.1.36'; -syntaxmap['2.5.5.7'] = '1.2.840.113556.1.4.903'; -syntaxmap['2.5.5.8'] = '1.3.6.1.4.1.1466.115.121.1.7'; -syntaxmap['2.5.5.9'] = '1.3.6.1.4.1.1466.115.121.1.27'; -syntaxmap['2.5.5.10'] = '1.3.6.1.4.1.1466.115.121.1.40'; -syntaxmap['2.5.5.11'] = '1.3.6.1.4.1.1466.115.121.1.24'; -syntaxmap['2.5.5.12'] = '1.3.6.1.4.1.1466.115.121.1.15'; -syntaxmap['2.5.5.13'] = '1.3.6.1.4.1.1466.115.121.1.43'; -syntaxmap['2.5.5.14'] = '1.2.840.113556.1.4.904'; -syntaxmap['2.5.5.15'] = '1.2.840.113556.1.4.907'; -syntaxmap['2.5.5.16'] = '1.2.840.113556.1.4.906'; -syntaxmap['2.5.5.17'] = '1.3.6.1.4.1.1466.115.121.1.40'; - -/* - map some attribute syntaxes from some apparently MS specific - syntaxes to the standard syntaxes -*/ -function map_attribute_syntax(s) { - if (syntaxmap[s] != undefined) { - return syntaxmap[s]; - } - return s; -} - - -/* - fix a string DN to use ${SCHEMADN} -*/ -function fix_dn(dn) { - var s = strstr(dn, rootDse.schemaNamingContext); - if (s == NULL) { - return dn; - } - return substr(dn, 0, strlen(dn) - strlen(s)) + "${SCHEMADN}"; -} - -/* - dump an object as ldif -*/ -function write_ldif_one(o, attrs) { - var i; - printf("dn: CN=%s,${SCHEMADN}\n", o.cn); - for (i=0;i Date: Thu, 18 Sep 2008 16:57:44 +0200 Subject: Remove jsdir. --- source4/Makefile | 5 +---- source4/param/loadparm.c | 5 ----- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/source4/Makefile b/source4/Makefile index 546eb072d8..1c4c2611b0 100644 --- a/source4/Makefile +++ b/source4/Makefile @@ -13,7 +13,6 @@ pidldir := $(srcdir)/pidl BASEDIR = $(prefix) TORTUREDIR = $(libdir)/torture SWATDIR = $(datadir)/swat -JSDIR = $(datadir)/js SETUPDIR = $(datadir)/setup NCALRPCDIR = $(localstatedir)/ncalrpc @@ -98,7 +97,6 @@ ntvfssrcdir := ntvfs ntptrsrcdir := ntptr librpcsrcdir := librpc libclisrcdir := libcli -ejsscriptsrcdir := scripting/ejs pyscriptsrcdir := $(srcdir)/scripting/python kdcsrcdir := kdc ntp_signdsrcdir := ntp_signd @@ -163,7 +161,6 @@ showlayout:: @echo ' lockdir: $(lockdir)' @echo ' logfilebase: $(logfilebase)' @echo ' setupdir: $(SETUPDIR)' - @echo ' jsdir: $(JSDIR)' @echo ' swatdir: $(SWATDIR)' @echo ' mandir: $(mandir)' @echo ' torturedir: $(TORTUREDIR)' @@ -233,7 +230,7 @@ installman:: manpages installdirs @$(SHELL) $(srcdir)/script/installman.sh $(DESTDIR)$(mandir) $(MANPAGES) installmisc:: installdirs - @$(SHELL) $(srcdir)/script/installmisc.sh $(srcdir) $(DESTDIR)$(JSDIR) $(DESTDIR)$(SETUPDIR) $(DESTDIR)$(bindir) + @$(SHELL) $(srcdir)/script/installmisc.sh $(srcdir) $(DESTDIR)$(SETUPDIR) $(DESTDIR)$(bindir) installpc:: installdirs @$(SHELL) $(srcdir)/script/installpc.sh $(builddir) $(DESTDIR)$(PKGCONFIGDIR) $(PC_FILES) diff --git a/source4/param/loadparm.c b/source4/param/loadparm.c index e63a7aa8a1..15edbd1f89 100644 --- a/source4/param/loadparm.c +++ b/source4/param/loadparm.c @@ -97,8 +97,6 @@ struct loadparm_global char *szWINS_CONFIG_URL; char *szWINS_URL; char *szPrivateDir; - const char **jsInclude; - char *jsonrpcServicesDir; const char **szPasswordServers; char *szSocketOptions; char *szRealm; @@ -469,7 +467,6 @@ static struct parm_struct parm_table[] = { {"lock directory", P_STRING, P_GLOBAL, GLOBAL_VAR(szLockDir), NULL, NULL}, {"modules dir", P_STRING, P_GLOBAL, GLOBAL_VAR(szModulesDir), NULL, NULL}, {"pid directory", P_STRING, P_GLOBAL, GLOBAL_VAR(szPidDir), NULL, NULL}, - {"js include", P_LIST, P_GLOBAL, GLOBAL_VAR(jsInclude), NULL, NULL}, {"setup directory", P_STRING, P_GLOBAL, GLOBAL_VAR(szSetupDir), NULL, NULL}, {"socket address", P_STRING, P_GLOBAL, GLOBAL_VAR(szSocketAddress), NULL, NULL}, @@ -702,7 +699,6 @@ _PUBLIC_ FN_GLOBAL_INTEGER(lp_cli_minprotocol, cli_minprotocol) _PUBLIC_ FN_GLOBAL_INTEGER(lp_security, security) _PUBLIC_ FN_GLOBAL_BOOL(lp_paranoid_server_security, paranoid_server_security) _PUBLIC_ FN_GLOBAL_INTEGER(lp_announce_as, announce_as) -_PUBLIC_ FN_GLOBAL_LIST(lp_js_include, jsInclude) const char *lp_servicename(const struct loadparm_service *service) { return lp_string((const char *)service->szService); @@ -2413,7 +2409,6 @@ struct loadparm_context *loadparm_init(TALLOC_CTX *mem_ctx) lp_do_global_parameter(lp_ctx, "tls keyfile", "tls/key.pem"); lp_do_global_parameter(lp_ctx, "tls certfile", "tls/cert.pem"); lp_do_global_parameter(lp_ctx, "tls cafile", "tls/ca.pem"); - lp_do_global_parameter_var(lp_ctx, "js include", "%s", dyn_JSDIR); lp_do_global_parameter_var(lp_ctx, "setup directory", "%s", dyn_SETUPDIR); -- cgit From 900768067831f773b7cdeec03e095956bccb961e Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 18 Sep 2008 19:56:25 +0200 Subject: Remove obsolete script. --- source4/script/build_smb_interfaces.pl | 161 --------------------------------- 1 file changed, 161 deletions(-) delete mode 100755 source4/script/build_smb_interfaces.pl diff --git a/source4/script/build_smb_interfaces.pl b/source4/script/build_smb_interfaces.pl deleted file mode 100755 index 5fac94ca6e..0000000000 --- a/source4/script/build_smb_interfaces.pl +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/perl -# -# Create ejs interfaces for structures in a C header file -# - -use File::Basename; -use Data::Dumper; - -# -# Generate parse tree for header file -# - -my $file = shift; -require smb_interfaces; -my $parser = new smb_interfaces; -$header = $parser->parse($file); - -# -# Make second pass over tree to make it easier to process. -# - -sub flatten_structs($) { - my $obj = shift; - my $s = { %$obj }; - - # Map NAME, STRUCT_NAME and UNION_NAME elements into a more likeable - # property. - - if (defined($obj->{STRUCT_NAME}) or defined($obj->{UNION_NAME})) { - - $s->{TYPE_DEFINED} = defined($obj->{STRUCT_NAME}) ? $obj->{STRUCT_NAME} - : $obj->{UNION_NAME}; - - delete $s->{STRUCT_NAME}; - delete $s->{UNION_NAME}; - } - - # Create a new list of structure fields with flattened names - - foreach my $elt (@{$obj->{DATA}}) { - foreach my $name (@{$elt->{NAME}}) { - my $new_elt = { %$elt }; - $new_elt->{NAME} = $name; -# $new_elt->{PARENT} = $s; - push(@{$s->{FIELDS}}, flatten_structs($new_elt)); - } - } - - delete $s->{DATA}; - - return $s; -} - -@newheader = map { flatten_structs($_) } @{$header}; - -# -# Generate implementation -# - -my $basename = basename($file, ".h"); -stat "libcli/gen_raw" || mkdir("libcli/gen_raw") || die("mkdir"); - -open(FILE, ">libcli/gen_raw/ejs_${basename}.c"); - -print FILE "/* EJS wrapper functions auto-generated by build_smb_interfaces.pl */\n\n"; - -print FILE "#include \"includes.h\"\n"; -print FILE "#include \"scripting/ejs/smbcalls.h\"\n"; -print FILE "#include \"lib/appweb/ejs/ejs.h\"\n"; -print FILE "#include \"scripting/ejs/ejsrpc.h\"\n"; # TODO: remove this -print FILE "\n"; - -sub transfer_element($$$) { - my $dir = shift; - my $prefix = shift; - my $elt = shift; - - $type = $elt->{TYPE}; - $type =~ s/_t$//; - - print FILE "\tNDR_CHECK(ejs_${dir}_$type(ejs, v, \"$prefix.$elt->{NAME}\"));\n"; -} - -sub transfer_struct($$) { - my $dir = shift; - my $struct = shift; - - foreach my $field (@{$struct->{FIELDS}}) { - next if $dir eq "pull" and $field->{NAME} eq "out"; - next if $dir eq "push" and $field->{NAME} eq "in"; - - if ($field->{TYPE} eq "struct") { - foreach $subfield (@{$field->{FIELDS}}) { - transfer_element($dir, $field->{NAME}, $subfield); - } - } else { - transfer_element($dir, $struct->{NAME}, $field); - } - } -} - -# Top level call functions - -foreach my $s (@newheader) { - - if ($s->{TYPE} eq "struct") { - - # Push/pull top level struct - - print FILE "NTSTATUS ejs_pull_$s->{TYPE_DEFINED}(struct ejs_rpc *ejs, struct MprVar *v, struct $s->{TYPE_DEFINED} *r)\n"; - print FILE "{\n"; - - transfer_struct("pull", $s); - - print FILE "\n\treturn NT_STATUS_OK;\n"; - print FILE "}\n\n"; - - print FILE "NTSTATUS ejs_push_$s->{TYPE_DEFINED}(struct ejs_rpc *ejs, struct MprVar *v, const struct $s->{TYPE_DEFINED} *r)\n"; - print FILE "{\n"; - - transfer_struct("push", $s); - - print FILE "\n\treturn NT_STATUS_OK;\n"; - print FILE "}\n\n"; - - # Function call - - print FILE "static int ejs_$s->{TYPE_DEFINED}(int eid, int argc, struct MprVar **argv)\n"; - print FILE "{\n"; - print FILE "\treturn ejs_raw_call(eid, argc, argv, (ejs_pull_function_t)ejs_pull_$s->{TYPE_DEFINED}, (ejs_push_function_t)ejs_push_$s->{TYPE_DEFINED});\n"; - print FILE "}\n\n"; - - } else { - - # Top level union - - foreach my $arm (@{$s->{FIELDS}}) { - - # Push/pull union arm - - print FILE "NTSTATUS ejs_pull_$s->{TYPE_DEFINED}_$arm->{NAME}(struct ejs_rpc *ejs, struct MprVar *v, union $s->{TYPE_DEFINED} *r)\n"; - print FILE "{\n"; - - transfer_struct("pull", $arm); - - print FILE "\n\treturn NT_STATUS_OK;\n"; - print FILE "}\n\n"; - - print FILE "NTSTATUS ejs_push_$s->{TYPE_DEFINED}_$arm->{NAME}(struct ejs_rpc *ejs, struct MprVar *v, const union $s->{TYPE_DEFINED} *r)\n"; - print FILE "{\n"; - - transfer_struct("push", $arm); - - print FILE "\n\treturn NT_STATUS_OK;\n"; - print FILE "}\n\n"; - - } - } -} - -close(FILE); -- cgit From fc7050e54c69919d754ca0adf3f2f741a501fec4 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 18 Sep 2008 19:58:47 +0200 Subject: Add header. --- source4/script/harness2subunit.pl | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source4/script/harness2subunit.pl b/source4/script/harness2subunit.pl index 9f2391ad6c..45f515540b 100755 --- a/source4/script/harness2subunit.pl +++ b/source4/script/harness2subunit.pl @@ -1,4 +1,8 @@ #!/usr/bin/perl +# Simple script that converts Perl test harness output to +# Subunit +# Copyright (C) 2008 Jelmer Vernooij +# Published under the GNU GPL, v3 or later my $firstline = 1; my $error = 0; -- cgit From 88ad1a936ccd2451d6dbf542a0a746ad71a3e968 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 18 Sep 2008 20:28:42 +0200 Subject: Remove EJS tests. --- source4/samba4-skip | 1 - source4/selftest/samba4_tests.sh | 8 -------- 2 files changed, 9 deletions(-) diff --git a/source4/samba4-skip b/source4/samba4-skip index b1313adea0..5fa40ee706 100644 --- a/source4/samba4-skip +++ b/source4/samba4-skip @@ -58,6 +58,5 @@ samba4.ntvfs.cifs.raw. ^samba4.net.domopen.*$ # Hangs for some reason ^samba4.net.api.become.dc.*$ # Fails nss.test # Fails -samba4.samba3sam.python # Conversion from EJS not yet finished raw.offline # Samba 4 doesn't have much offline support yet winreg* #Does not authenticate against the target server diff --git a/source4/selftest/samba4_tests.sh b/source4/selftest/samba4_tests.sh index 6f6ffbba60..a13c596f6d 100755 --- a/source4/selftest/samba4_tests.sh +++ b/source4/selftest/samba4_tests.sh @@ -60,12 +60,8 @@ $incdir/../bin/smbtorture -V samba4srcdir=$incdir/.. samba4bindir=$samba4srcdir/bin -SCRIPTDIR=$samba4srcdir/../testprogs/ejs smb4torture="$samba4bindir/smbtorture $TORTURE_OPTIONS" -plantest "js.base" dc "$SCRIPTDIR/base.js" $CONFIGURATION -plantest "js.ldb" none "$SCRIPTDIR/ldb.js" `pwd` $CONFIGURATION -d 10 - # Simple tests for LDAP and CLDAP for options in "" "--option=socket:testnonblock=true" "-U\$USERNAME%\$PASSWORD --option=socket:testnonblock=true" "-U\$USERNAME%\$PASSWORD"; do @@ -286,10 +282,6 @@ for t in "BASE-RW1"; do plantest "ntvfs.simple.`normalize_testname $t`" dc $VALGRIND $smb4torture $ADDARGS //\$SERVER/simple -U"\$USERNAME"%"\$PASSWORD" $t done -DATADIR=$samba4srcdir/../testdata - -plantest "js.samba3sam" none $samba4bindir/smbscript $SCRIPTDIR/samba3sam.js $CONFIGURATION `pwd` $DATADIR/samba3/ - # Domain Member Tests plantest "rpc.echo against member server with local creds" member $VALGRIND $smb4torture ncacn_np:"\$NETBIOSNAME" -U"\$NETBIOSNAME/\$USERNAME"%"\$PASSWORD" RPC-ECHO "$*" -- cgit From acffa3ddbfe982ee0c2f8d1eb45993fd655db674 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 18 Sep 2008 20:48:09 +0200 Subject: Stop writing js include dir in selftest. --- source4/selftest/selftest.pl | 1 - source4/selftest/target/Samba4.pm | 1 - 2 files changed, 2 deletions(-) diff --git a/source4/selftest/selftest.pl b/source4/selftest/selftest.pl index e86ccbe468..b6a31ac20e 100755 --- a/source4/selftest/selftest.pl +++ b/source4/selftest/selftest.pl @@ -576,7 +576,6 @@ sub write_clientconf($$) } print CF " private dir = $prefix_abs/client/private - js include = $srcdir_abs/scripting/libjs name resolve order = bcast panic action = $srcdir_abs/script/gdb_backtrace \%PID\% \%PROG\% max xmit = 32K diff --git a/source4/selftest/target/Samba4.pm b/source4/selftest/target/Samba4.pm index 8835f69c6c..992e251c35 100644 --- a/source4/selftest/target/Samba4.pm +++ b/source4/selftest/target/Samba4.pm @@ -555,7 +555,6 @@ sub provision($$$$$$) lock dir = $lockdir setup directory = $self->{setupdir} modules dir = $self->{bindir}/modules - js include = $srcdir/scripting/libjs winbindd socket directory = $winbindd_socket_dir winbindd privileged socket directory = $winbindd_privileged_socket_dir ntp signd socket directory = $ntp_signd_socket_dir -- cgit From a48f19b6c2c954e743438e9f2814289247ba3fc6 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 18 Sep 2008 21:32:30 +0200 Subject: Remove python extension, simplify some code. --- source4/scripting/bin/autoidl | 161 ++++++++++ source4/scripting/bin/autoidl.py | 161 ---------- source4/scripting/bin/epdump | 24 ++ source4/scripting/bin/epdump.py | 24 -- source4/scripting/bin/minschema | 585 +++++++++++++++++++++++++++++++++++++ source4/scripting/bin/minschema.py | 585 ------------------------------------- source4/scripting/bin/smbstatus | 6 +- 7 files changed, 773 insertions(+), 773 deletions(-) create mode 100755 source4/scripting/bin/autoidl delete mode 100755 source4/scripting/bin/autoidl.py create mode 100755 source4/scripting/bin/epdump delete mode 100644 source4/scripting/bin/epdump.py create mode 100755 source4/scripting/bin/minschema delete mode 100755 source4/scripting/bin/minschema.py diff --git a/source4/scripting/bin/autoidl b/source4/scripting/bin/autoidl new file mode 100755 index 0000000000..eed4ba3a80 --- /dev/null +++ b/source4/scripting/bin/autoidl @@ -0,0 +1,161 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Unix SMB/CIFS implementation. +# Copyright © Jelmer Vernooij 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 . +# + +import sys + +MAX_OPNUM = 1000 +MAX_BASE_SIZE = 0x1000 +MAX_IFACE_VERSION = 1000 + +DCERPC_FAULT_OP_RNG_ERROR = 0x1c010002 +DCERPC_FAULT_NDR = 0x6f7 +NT_STATUS_NET_WRITE_FAULT = -1073741614 + + +sys.path.insert(0, "bin/python") + +from samba.dcerpc import ClientConnection + +def find_num_funcs(conn): + for i in xrange(MAX_OPNUM): + try: + conn.request(i, "") + except RuntimeError, (num, msg): + if num == DCERPC_FAULT_OP_RNG_ERROR: + return i + raise Exception("More than %d functions" % MAX_OPNUM) + +class Function: + def __init__(self, conn, opnum): + self.conn = conn + self.opnum = opnum + + def request(self, data): + assert isinstance(data, str) + self.conn.request(self.opnum, data) + + def valid_ndr(self, data): + try: + self.request(data) + except RuntimeError, (num, msg): + if num == DCERPC_FAULT_NDR: + return False + return True + + def find_base_request(self, start=""): + """Find the smallest possible request that we can do that is + valid. + + This generally means sending all zeroes so we get NULL pointers where + possible.""" + # TODO: Don't try with just 0's as there may be switch_is() variables + # for which 0 is not a valid value or variables with range() set + # See how much input bytes we need + for i in range(MAX_BASE_SIZE): + data = start + chr(0) * i + if self.valid_ndr(data): + return data + return None + + def check_decision_byte(self, base_request, i): + """Check whether the specified byte is a possible "decision" byte, + e.g. a byte that is part of a pointer, array size variable or + discriminant. + + Note that this function only checks if a byte is definitely a decision + byte. It may return False in some cases while the byte is actually + a decision byte.""" + data = list(base_request) + data[i] = chr(1) + return not self.valid_ndr("".join(data)) + + def find_deferrant_data(self, base_request, idx): + data = list(base_request) + data[idx*4] = chr(1) + # Just check that this is a pointer to something non-empty: + assert not self.valid_ndr("".join(data)) + + newdata = self.find_base_request("".join(data)) + + if newdata is None: + return None + + assert newdata.startswith(data) + + return newdata[len(data):] + + def find_idl(self): + base_request = self.find_base_request() + + if base_request is None: + raise Exception("Unable to determine base size for opnum %d" % self.opnum) + + print "\tBase request is %r" % base_request + + decision_byte_map = map(lambda x: self.check_decision_byte(base_request, x), range(len(base_request))) + + print decision_byte_map + + # find pointers + possible_pointers = map(all, + [decision_byte_map[i*4:(i+1)*4] for i in range(int(len(base_request)/4))]) + print possible_pointers + + pointer_deferrant_bases = map( + lambda x: self.find_deferrant_data(base_request, x) if possible_pointers[x] else None, range(len(possible_pointers))) + + print pointer_deferrant_bases + + +if len(sys.argv) < 3: + print "Usage: autoidl []" + sys.exit(1) + +(binding, uuid) = sys.argv[1:3] +if len(sys.argv) == 4: + version = sys.argv[3] +else: + version = None + +if version is None: + for i in range(MAX_IFACE_VERSION): + try: + conn = ClientConnection(binding, (uuid, i)) + except RuntimeError, (num, msg): + if num == NT_STATUS_NET_WRITE_FAULT: + continue + raise + else: + break +else: + conn = ClientConnection(binding, (uuid, version)) + +print "Figuring out number of connections...", +num_funcs = find_num_funcs(conn) +print "%d" % num_funcs + +# Figure out the syntax for each one +for i in range(num_funcs): + print "Function %d" % i + data = Function(conn, i) + try: + data.find_idl() + except Exception, e: + print "Error: %r" % e diff --git a/source4/scripting/bin/autoidl.py b/source4/scripting/bin/autoidl.py deleted file mode 100755 index eed4ba3a80..0000000000 --- a/source4/scripting/bin/autoidl.py +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# Unix SMB/CIFS implementation. -# Copyright © Jelmer Vernooij 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 . -# - -import sys - -MAX_OPNUM = 1000 -MAX_BASE_SIZE = 0x1000 -MAX_IFACE_VERSION = 1000 - -DCERPC_FAULT_OP_RNG_ERROR = 0x1c010002 -DCERPC_FAULT_NDR = 0x6f7 -NT_STATUS_NET_WRITE_FAULT = -1073741614 - - -sys.path.insert(0, "bin/python") - -from samba.dcerpc import ClientConnection - -def find_num_funcs(conn): - for i in xrange(MAX_OPNUM): - try: - conn.request(i, "") - except RuntimeError, (num, msg): - if num == DCERPC_FAULT_OP_RNG_ERROR: - return i - raise Exception("More than %d functions" % MAX_OPNUM) - -class Function: - def __init__(self, conn, opnum): - self.conn = conn - self.opnum = opnum - - def request(self, data): - assert isinstance(data, str) - self.conn.request(self.opnum, data) - - def valid_ndr(self, data): - try: - self.request(data) - except RuntimeError, (num, msg): - if num == DCERPC_FAULT_NDR: - return False - return True - - def find_base_request(self, start=""): - """Find the smallest possible request that we can do that is - valid. - - This generally means sending all zeroes so we get NULL pointers where - possible.""" - # TODO: Don't try with just 0's as there may be switch_is() variables - # for which 0 is not a valid value or variables with range() set - # See how much input bytes we need - for i in range(MAX_BASE_SIZE): - data = start + chr(0) * i - if self.valid_ndr(data): - return data - return None - - def check_decision_byte(self, base_request, i): - """Check whether the specified byte is a possible "decision" byte, - e.g. a byte that is part of a pointer, array size variable or - discriminant. - - Note that this function only checks if a byte is definitely a decision - byte. It may return False in some cases while the byte is actually - a decision byte.""" - data = list(base_request) - data[i] = chr(1) - return not self.valid_ndr("".join(data)) - - def find_deferrant_data(self, base_request, idx): - data = list(base_request) - data[idx*4] = chr(1) - # Just check that this is a pointer to something non-empty: - assert not self.valid_ndr("".join(data)) - - newdata = self.find_base_request("".join(data)) - - if newdata is None: - return None - - assert newdata.startswith(data) - - return newdata[len(data):] - - def find_idl(self): - base_request = self.find_base_request() - - if base_request is None: - raise Exception("Unable to determine base size for opnum %d" % self.opnum) - - print "\tBase request is %r" % base_request - - decision_byte_map = map(lambda x: self.check_decision_byte(base_request, x), range(len(base_request))) - - print decision_byte_map - - # find pointers - possible_pointers = map(all, - [decision_byte_map[i*4:(i+1)*4] for i in range(int(len(base_request)/4))]) - print possible_pointers - - pointer_deferrant_bases = map( - lambda x: self.find_deferrant_data(base_request, x) if possible_pointers[x] else None, range(len(possible_pointers))) - - print pointer_deferrant_bases - - -if len(sys.argv) < 3: - print "Usage: autoidl []" - sys.exit(1) - -(binding, uuid) = sys.argv[1:3] -if len(sys.argv) == 4: - version = sys.argv[3] -else: - version = None - -if version is None: - for i in range(MAX_IFACE_VERSION): - try: - conn = ClientConnection(binding, (uuid, i)) - except RuntimeError, (num, msg): - if num == NT_STATUS_NET_WRITE_FAULT: - continue - raise - else: - break -else: - conn = ClientConnection(binding, (uuid, version)) - -print "Figuring out number of connections...", -num_funcs = find_num_funcs(conn) -print "%d" % num_funcs - -# Figure out the syntax for each one -for i in range(num_funcs): - print "Function %d" % i - data = Function(conn, i) - try: - data.find_idl() - except Exception, e: - print "Error: %r" % e diff --git a/source4/scripting/bin/epdump b/source4/scripting/bin/epdump new file mode 100755 index 0000000000..15dee33774 --- /dev/null +++ b/source4/scripting/bin/epdump @@ -0,0 +1,24 @@ +#!/usr/bin/python + +# Unix SMB/CIFS implementation. +# Copyright (C) Jelmer Vernooij 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 . +# + +import sys + +if len(sys.argv) < 2: + print "Usage: %s " % sys.argv[0] + sys.exit(1) diff --git a/source4/scripting/bin/epdump.py b/source4/scripting/bin/epdump.py deleted file mode 100644 index 15dee33774..0000000000 --- a/source4/scripting/bin/epdump.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/python - -# Unix SMB/CIFS implementation. -# Copyright (C) Jelmer Vernooij 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 . -# - -import sys - -if len(sys.argv) < 2: - print "Usage: %s " % sys.argv[0] - sys.exit(1) diff --git a/source4/scripting/bin/minschema b/source4/scripting/bin/minschema new file mode 100755 index 0000000000..111557126d --- /dev/null +++ b/source4/scripting/bin/minschema @@ -0,0 +1,585 @@ +#!/usr/bin/python +# +# work out the minimal schema for a set of objectclasses +# + +import optparse + +import os, sys + +# Find right directory when running from source tree +sys.path.insert(0, "bin/python") + +import samba +from samba import getopt as options +import sys + +parser = optparse.OptionParser("minschema ") +sambaopts = options.SambaOptions(parser) +parser.add_option_group(sambaopts) +credopts = options.CredentialsOptions(parser) +parser.add_option_group(credopts) +parser.add_option_group(options.VersionOptions(parser)) +parser.add_option("--verbose", help="Be verbose", action="store_true") +parser.add_option("--dump-classes", action="store_true") +parser.add_option("--dump-attributes", action="store_true") +parser.add_option("--dump-subschema", action="store_true") +parser.add_option("--dump-subschema-auto", action="store_true") + +opts, args = parser.parse_args() +opts.dump_all = True + +if opts.dump_classes: + opts.dump_all = False +if opts.dump_attributes: + opts.dump_all = False +if opts.dump_subschema: + opts.dump_all = False +if opts.dump_subschema_auto: + opts.dump_all = False + opts.dump_subschema = True +if opts.dump_all: + opts.dump_classes = True + opts.dump_attributes = True + opts.dump_subschema = True + opts.dump_subschema_auto = True + +if len(args) != 2: + parser.print_usage() + sys.exit(1) + +(url, classfile) = args + +creds = credopts.get_credentials() +ldb = Ldb(url, credentials=creds) + +objectclasses = [] +attributes = [] + +objectclasses_expanded = set() + +# the attributes we need for objectclasses +class_attrs = ["objectClass", + "subClassOf", + "governsID", + "possSuperiors", + "possibleInferiors", + "mayContain", + "mustContain", + "auxiliaryClass", + "rDNAttID", + "showInAdvancedViewOnly", + "adminDisplayName", + "adminDescription", + "objectClassCategory", + "lDAPDisplayName", + "schemaIDGUID", + "systemOnly", + "systemPossSuperiors", + "systemMayContain", + "systemMustContain", + "systemAuxiliaryClass", + "defaultSecurityDescriptor", + "systemFlags", + "defaultHidingValue", + "objectCategory", + "defaultObjectCategory", + + # this attributes are not used by w2k3 + "schemaFlagsEx", + "msDs-IntId", + "msDs-Schema-Extensions", + "classDisplayName", + "isDefunct"] + +attrib_attrs = ["objectClass", + "attributeID", + "attributeSyntax", + "isSingleValued", + "rangeLower", + "rangeUpper", + "mAPIID", + "linkID", + "showInAdvancedViewOnly", + "adminDisplayName", + "oMObjectClass", + "adminDescription", + "oMSyntax", + "searchFlags", + "extendedCharsAllowed", + "lDAPDisplayName", + "schemaIDGUID", + "attributeSecurityGUID", + "systemOnly", + "systemFlags", + "isMemberOfPartialAttributeSet", + "objectCategory", + + # this attributes are not used by w2k3 + "schemaFlagsEx", + "msDs-IntId", + "msDs-Schema-Extensions", + "classDisplayName", + "isEphemeral", + "isDefunct"] + +# +# notes: +# +# objectClassCategory +# 1: structural +# 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) + assert len(res) == 1 + + return res[0]["cn"] + +class Objectclass: + def __init__(self, ldb, name): + """create an objectclass object""" + self.name = name + self.cn = get_object_cn(ldb, name) + + +class Attribute: + def __init__(self, ldb, name): + """create an attribute object""" + self.name = name + self.cn = get_object_cn(ldb, name) + + +syntaxmap = dict() + +syntaxmap['2.5.5.1'] = '1.3.6.1.4.1.1466.115.121.1.12' +syntaxmap['2.5.5.2'] = '1.3.6.1.4.1.1466.115.121.1.38' +syntaxmap['2.5.5.3'] = '1.2.840.113556.1.4.1362' +syntaxmap['2.5.5.4'] = '1.2.840.113556.1.4.905' +syntaxmap['2.5.5.5'] = '1.3.6.1.4.1.1466.115.121.1.26' +syntaxmap['2.5.5.6'] = '1.3.6.1.4.1.1466.115.121.1.36' +syntaxmap['2.5.5.7'] = '1.2.840.113556.1.4.903' +syntaxmap['2.5.5.8'] = '1.3.6.1.4.1.1466.115.121.1.7' +syntaxmap['2.5.5.9'] = '1.3.6.1.4.1.1466.115.121.1.27' +syntaxmap['2.5.5.10'] = '1.3.6.1.4.1.1466.115.121.1.40' +syntaxmap['2.5.5.11'] = '1.3.6.1.4.1.1466.115.121.1.24' +syntaxmap['2.5.5.12'] = '1.3.6.1.4.1.1466.115.121.1.15' +syntaxmap['2.5.5.13'] = '1.3.6.1.4.1.1466.115.121.1.43' +syntaxmap['2.5.5.14'] = '1.2.840.113556.1.4.904' +syntaxmap['2.5.5.15'] = '1.2.840.113556.1.4.907' +syntaxmap['2.5.5.16'] = '1.2.840.113556.1.4.906' +syntaxmap['2.5.5.17'] = '1.3.6.1.4.1.1466.115.121.1.40' + + +def map_attribute_syntax(s): + """map some attribute syntaxes from some apparently MS specific + syntaxes to the standard syntaxes""" + if syntaxmap.has_key(s): + return syntaxmap[s] + return s + + +def fix_dn(dn): + """fix a string DN to use ${SCHEMADN}""" + return dn.replace(rootDse["schemaNamingContext"], "${SCHEMADN}") + + +def write_ldif_one(o, attrs): + """dump an object as ldif""" + print "dn: CN=%s,${SCHEMADN}\n" % o["cn"] + for a in attrs: + if not o.has_key(a): + continue + # special case for oMObjectClass, which is a binary object + if a == "oMObjectClass": + print "%s:: %s\n" % (a, o[a]) + continue + v = o[a] + if isinstance(v, str): + v = [v] + for j in v: + print "%s: %s\n" % (a, fix_dn(j)) + print "\n" + +def write_ldif(o, attrs): + """dump an array of objects as ldif""" + for i in o: + write_ldif_one(i, attrs) + + +def create_testdn(exampleDN): + """create a testDN based an an example DN + the idea is to ensure we obey any structural rules""" + a = exampleDN.split(",") + a[0] = "CN=TestDN" + return ",".join(a) + + +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) + assert(len(res) == 1) + msg = res[0] + for a in msg: + o[a] = msg[a] + +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, + attrs=attrib_attrs) + assert(len(res) == 1) + msg = res[0] + for a in msg: + # special case for oMObjectClass, which is a binary object + if a == "oMObjectClass": + o[a] = ldb.encode(msg[a]) + continue + o[a] = msg[a] + + +def find_objectclass_auto(ldb, o): + """find the auto-created properties of an objectclass. Only works for + classes that can be created using just a DN and the objectclass""" + if not o.has_key("exampleDN"): + return + testdn = create_testdn(o.exampleDN) + + print "testdn is '%s'\n" % testdn + + ldif = "dn: " + testdn + ldif += "\nobjectClass: " + o.name + try: + ldb.add(ldif) + except LdbError, e: + print "error adding %s: %s\n" % (o.name, e) + print "%s\n" % ldif + return + + res = ldb.search("", testdn, ldb.SCOPE_BASE) + ldb.delete(testdn) + + for a in res.msgs[0]: + attributes[a].autocreate = True + + +def expand_objectclass(ldb, o): + """look at auxiliary information from a class to intuit the existance of + more classes needed for a minimal schema""" + attrs = ["auxiliaryClass", "systemAuxiliaryClass", + "possSuperiors", "systemPossSuperiors", + "subClassOf"] + res = ldb.search( + expression="(&(objectClass=classSchema)(ldapDisplayName=%s))" % o.name, + basedn=rootDse["schemaNamingContext"], scope=ldb.SCOPE_SUBTREE, + attrs=attrs) + print "Expanding class %s\n" % o.name + assert(len(res) == 1) + msg = res[0] + for a in attrs: + if not msg.has_key(aname): + continue + list = msg[aname] + if isinstance(list, str): + list = [msg[aname]] + for name in list: + if not objectclasses.has_key(name): + print "Found new objectclass '%s'\n" % name + objectclasses[name] = Objectclass(ldb, name) + + +def add_objectclass_attributes(ldb, objectclass): + """add the must and may attributes from an objectclass to the full list + of attributes""" + attrs = ["mustContain", "systemMustContain", + "mayContain", "systemMayContain"] + for aname in attrs: + if not objectclass.has_key(aname): + continue + alist = objectclass[aname] + if isinstance(alist, str): + alist = [alist] + for a in alist: + if not attributes.has_key(a): + attributes[a] = Attribute(ldb, a) + + +def walk_dn(ldb, dn): + """process an individual record, working out what attributes it has""" + # get a list of all possible attributes for this object + attrs = ["allowedAttributes"] + try: + res = ldb.search("objectClass=*", dn, ldb.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) + except LdbError, e: + print "Unable to fetch all attributes for '%s' - %s\n" % (dn, e) + return + msg = res[0] + for a in msg: + if not attributes.has_key(a): + attributes[a] = Attribute(ldb, a) + +def walk_naming_context(ldb, namingContext): + """walk a naming context, looking for all records""" + try: + res = ldb.search("objectClass=*", namingContext, ldb.SCOPE_DEFAULT, + ["objectClass"]) + except LdbError, e: + print "Unable to fetch objectClasses for '%s' - %s\n" % (namingContext, e) + return + for msg in res: + msg = res.msgs[r]["objectClass"] + for objectClass in msg: + if not objectclasses.has_key(objectClass): + objectclasses[objectClass] = Objectclass(ldb, objectClass) + objectclasses[objectClass].exampleDN = res.msgs[r]["dn"] + walk_dn(ldb, res.msgs[r].dn) + +def trim_objectclass_attributes(ldb, objectclass): + """trim the may attributes for an objectClass""" + # trim possibleInferiors, + # include only the classes we extracted + if objectclass.has_key("possibleInferiors"): + possinf = objectclass["possibleInferiors"] + newpossinf = [] + if isinstance(possinf, str): + possinf = [possinf] + for x in possinf: + if objectclasses.has_key(x): + newpossinf[n] = x + n+=1 + objectclass["possibleInferiors"] = newpossinf + + # trim systemMayContain, + # remove duplicates + if objectclass.has_key("systemMayContain"): + sysmay = objectclass["systemMayContain"] + newsysmay = [] + if isinstance(sysmay, str): + sysmay = [sysmay] + for x in sysmay: + if not x in newsysmay: + newsysmay.append(x) + objectclass["systemMayContain"] = newsysmay + + # trim mayContain, + # remove duplicates + if not objectclass.has_key("mayContain"): + may = objectclass["mayContain"] + newmay = [] + if isinstance(may, str): + may = [may] + for x in may: + if not x in newmay: + newmay.append(x) + objectclass["mayContain"] = newmay + +def build_objectclass(ldb, name): + """load the basic attributes of an objectClass""" + attrs = ["name"] + try: + res = ldb.search( + expression="(&(objectClass=classSchema)(ldapDisplayName=%s))" % name, + basedn=rootDse["schemaNamingContext"], scope=ldb.SCOPE_SUBTREE, + attrs=attrs) + except LdbError, e: + print "unknown class '%s'\n" % name + return None + if len(res) == 0: + print "unknown class '%s'\n" % name + return None + return Objectclass(ldb, name) + +def attribute_list(objectclass, attr1, attr2): + """form a coalesced attribute list""" + a1 = objectclass[attr1] + a2 = objectclass[attr2] + if isinstance(a1, str): + a1 = [a1] + if isinstance(a2, str): + a2 = [a2] + return a1 + a2 + +def aggregate_list(name, list): + """write out a list in aggregate form""" + if list is None: + return + print "%s ( %s )" % (name, "$ ".join(list)) + +def write_aggregate_objectclass(objectclass): + """write the aggregate record for an objectclass""" + print "objectClasses: ( %s NAME '%s' " % (objectclass.governsID, objectclass.name) + if not objectclass.has_key('subClassOf'): + print "SUP %s " % objectclass['subClassOf'] + if objectclass.objectClassCategory == 1: + print "STRUCTURAL " + elif objectclass.objectClassCategory == 2: + print "ABSTRACT " + elif objectclass.objectClassCategory == 3: + print "AUXILIARY " + + list = attribute_list(objectclass, "systemMustContain", "mustContain") + aggregate_list("MUST", list) + + list = attribute_list(objectclass, "systemMayContain", "mayContain") + aggregate_list("MAY", list) + + print ")\n" + + +def write_aggregate_ditcontentrule(objectclass): + """write the aggregate record for an ditcontentrule""" + list = attribute_list(objectclass, "auxiliaryClass", "systemAuxiliaryClass") + if list is None: + return + + print "dITContentRules: ( %s NAME '%s' " % (objectclass.governsID, objectclass.name) + + aggregate_list("AUX", list) + + may_list = None + must_list = None + + for c in list: + list2 = attribute_list(objectclasses[c], + "mayContain", "systemMayContain") + may_list = may_list + list2 + list2 = attribute_list(objectclasses[c], + "mustContain", "systemMustContain") + must_list = must_list + list2 + + aggregate_list("MUST", must_list) + aggregate_list("MAY", may_list) + + print ")\n" + +def write_aggregate_attribute(attrib): + """write the aggregate record for an attribute""" + print "attributeTypes: ( %s NAME '%s' SYNTAX '%s' " % ( + attrib.attributeID, attrib.name, + map_attribute_syntax(attrib.attributeSyntax)) + if attrib['isSingleValued'] == "TRUE": + print "SINGLE-VALUE " + if attrib['systemOnly'] == "TRUE": + print "NO-USER-MODIFICATION " + + print ")\n" + + +def write_aggregate(): + """write the aggregate record""" + print "dn: CN=Aggregate,${SCHEMADN}\n" + print """objectClass: top +objectClass: subSchema +objectCategory: CN=SubSchema,${SCHEMADN} +""" + if not opts.dump_subschema_auto: + return + + for objectclass in objectclasses: + write_aggregate_objectclass(objectclass) + for attr in attributes: + write_aggregate_attribute(attr) + for objectclass in objectclasses: + write_aggregate_ditcontentrule(objectclass) + +def load_list(file): + """load a list from a file""" + return open(file, 'r').splitlines() + +# get the rootDSE +res = ldb.search("", "", ldb.SCOPE_BASE) +rootDse = res[0] + +# load the list of classes we are interested in +classes = load_list(classfile) +for classname in classes: + objectclass = build_objectclass(ldb, classname) + if objectclass is not None: + objectclasses[classname] = objectclass + + +# +# expand the objectclass list as needed +# +expanded = 0 + +# so EJS do not have while nor the break statement +# cannot find any other way than doing more loops +# than necessary to recursively expand all classes +# +for inf in range(500): + for n in objectclasses: + if not n in objectclasses_expanded: + expand_objectclass(ldb, objectclasses[i]) + objectclasses_expanded.add(n) + +# +# find objectclass properties +# +for objectclass in objectclasses: + find_objectclass_properties(ldb, objectclass) + + +# +# form the full list of attributes +# +for objectclass in objectclasses: + add_objectclass_attributes(ldb, objectclass) + +# and attribute properties +for attr in attributes: + find_attribute_properties(ldb, attr) + +# +# trim the 'may' attribute lists to those really needed +# +for objectclass in objectclasses: + trim_objectclass_attributes(ldb, objectclass) + +# +# dump an ldif form of the attributes and objectclasses +# +if opts.dump_attributes: + write_ldif(attributes, attrib_attrs) +if opts.dump_classes: + write_ldif(objectclasses, class_attrs) +if opts.dump_subschema: + write_aggregate() + +if not opts.verbose: + sys.exit(0) + +# +# dump list of objectclasses +# +print "objectClasses:\n" +for objectclass in objectclasses: + print "\t%s\n" % objectclass + +print "attributes:\n" +for attr in attributes: + print "\t%s\n" % attr + +print "autocreated attributes:\n" +for attr in attributes: + if attr.autocreate: + print "\t%s\n" % i diff --git a/source4/scripting/bin/minschema.py b/source4/scripting/bin/minschema.py deleted file mode 100755 index 111557126d..0000000000 --- a/source4/scripting/bin/minschema.py +++ /dev/null @@ -1,585 +0,0 @@ -#!/usr/bin/python -# -# work out the minimal schema for a set of objectclasses -# - -import optparse - -import os, sys - -# Find right directory when running from source tree -sys.path.insert(0, "bin/python") - -import samba -from samba import getopt as options -import sys - -parser = optparse.OptionParser("minschema ") -sambaopts = options.SambaOptions(parser) -parser.add_option_group(sambaopts) -credopts = options.CredentialsOptions(parser) -parser.add_option_group(credopts) -parser.add_option_group(options.VersionOptions(parser)) -parser.add_option("--verbose", help="Be verbose", action="store_true") -parser.add_option("--dump-classes", action="store_true") -parser.add_option("--dump-attributes", action="store_true") -parser.add_option("--dump-subschema", action="store_true") -parser.add_option("--dump-subschema-auto", action="store_true") - -opts, args = parser.parse_args() -opts.dump_all = True - -if opts.dump_classes: - opts.dump_all = False -if opts.dump_attributes: - opts.dump_all = False -if opts.dump_subschema: - opts.dump_all = False -if opts.dump_subschema_auto: - opts.dump_all = False - opts.dump_subschema = True -if opts.dump_all: - opts.dump_classes = True - opts.dump_attributes = True - opts.dump_subschema = True - opts.dump_subschema_auto = True - -if len(args) != 2: - parser.print_usage() - sys.exit(1) - -(url, classfile) = args - -creds = credopts.get_credentials() -ldb = Ldb(url, credentials=creds) - -objectclasses = [] -attributes = [] - -objectclasses_expanded = set() - -# the attributes we need for objectclasses -class_attrs = ["objectClass", - "subClassOf", - "governsID", - "possSuperiors", - "possibleInferiors", - "mayContain", - "mustContain", - "auxiliaryClass", - "rDNAttID", - "showInAdvancedViewOnly", - "adminDisplayName", - "adminDescription", - "objectClassCategory", - "lDAPDisplayName", - "schemaIDGUID", - "systemOnly", - "systemPossSuperiors", - "systemMayContain", - "systemMustContain", - "systemAuxiliaryClass", - "defaultSecurityDescriptor", - "systemFlags", - "defaultHidingValue", - "objectCategory", - "defaultObjectCategory", - - # this attributes are not used by w2k3 - "schemaFlagsEx", - "msDs-IntId", - "msDs-Schema-Extensions", - "classDisplayName", - "isDefunct"] - -attrib_attrs = ["objectClass", - "attributeID", - "attributeSyntax", - "isSingleValued", - "rangeLower", - "rangeUpper", - "mAPIID", - "linkID", - "showInAdvancedViewOnly", - "adminDisplayName", - "oMObjectClass", - "adminDescription", - "oMSyntax", - "searchFlags", - "extendedCharsAllowed", - "lDAPDisplayName", - "schemaIDGUID", - "attributeSecurityGUID", - "systemOnly", - "systemFlags", - "isMemberOfPartialAttributeSet", - "objectCategory", - - # this attributes are not used by w2k3 - "schemaFlagsEx", - "msDs-IntId", - "msDs-Schema-Extensions", - "classDisplayName", - "isEphemeral", - "isDefunct"] - -# -# notes: -# -# objectClassCategory -# 1: structural -# 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) - assert len(res) == 1 - - return res[0]["cn"] - -class Objectclass: - def __init__(self, ldb, name): - """create an objectclass object""" - self.name = name - self.cn = get_object_cn(ldb, name) - - -class Attribute: - def __init__(self, ldb, name): - """create an attribute object""" - self.name = name - self.cn = get_object_cn(ldb, name) - - -syntaxmap = dict() - -syntaxmap['2.5.5.1'] = '1.3.6.1.4.1.1466.115.121.1.12' -syntaxmap['2.5.5.2'] = '1.3.6.1.4.1.1466.115.121.1.38' -syntaxmap['2.5.5.3'] = '1.2.840.113556.1.4.1362' -syntaxmap['2.5.5.4'] = '1.2.840.113556.1.4.905' -syntaxmap['2.5.5.5'] = '1.3.6.1.4.1.1466.115.121.1.26' -syntaxmap['2.5.5.6'] = '1.3.6.1.4.1.1466.115.121.1.36' -syntaxmap['2.5.5.7'] = '1.2.840.113556.1.4.903' -syntaxmap['2.5.5.8'] = '1.3.6.1.4.1.1466.115.121.1.7' -syntaxmap['2.5.5.9'] = '1.3.6.1.4.1.1466.115.121.1.27' -syntaxmap['2.5.5.10'] = '1.3.6.1.4.1.1466.115.121.1.40' -syntaxmap['2.5.5.11'] = '1.3.6.1.4.1.1466.115.121.1.24' -syntaxmap['2.5.5.12'] = '1.3.6.1.4.1.1466.115.121.1.15' -syntaxmap['2.5.5.13'] = '1.3.6.1.4.1.1466.115.121.1.43' -syntaxmap['2.5.5.14'] = '1.2.840.113556.1.4.904' -syntaxmap['2.5.5.15'] = '1.2.840.113556.1.4.907' -syntaxmap['2.5.5.16'] = '1.2.840.113556.1.4.906' -syntaxmap['2.5.5.17'] = '1.3.6.1.4.1.1466.115.121.1.40' - - -def map_attribute_syntax(s): - """map some attribute syntaxes from some apparently MS specific - syntaxes to the standard syntaxes""" - if syntaxmap.has_key(s): - return syntaxmap[s] - return s - - -def fix_dn(dn): - """fix a string DN to use ${SCHEMADN}""" - return dn.replace(rootDse["schemaNamingContext"], "${SCHEMADN}") - - -def write_ldif_one(o, attrs): - """dump an object as ldif""" - print "dn: CN=%s,${SCHEMADN}\n" % o["cn"] - for a in attrs: - if not o.has_key(a): - continue - # special case for oMObjectClass, which is a binary object - if a == "oMObjectClass": - print "%s:: %s\n" % (a, o[a]) - continue - v = o[a] - if isinstance(v, str): - v = [v] - for j in v: - print "%s: %s\n" % (a, fix_dn(j)) - print "\n" - -def write_ldif(o, attrs): - """dump an array of objects as ldif""" - for i in o: - write_ldif_one(i, attrs) - - -def create_testdn(exampleDN): - """create a testDN based an an example DN - the idea is to ensure we obey any structural rules""" - a = exampleDN.split(",") - a[0] = "CN=TestDN" - return ",".join(a) - - -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) - assert(len(res) == 1) - msg = res[0] - for a in msg: - o[a] = msg[a] - -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, - attrs=attrib_attrs) - assert(len(res) == 1) - msg = res[0] - for a in msg: - # special case for oMObjectClass, which is a binary object - if a == "oMObjectClass": - o[a] = ldb.encode(msg[a]) - continue - o[a] = msg[a] - - -def find_objectclass_auto(ldb, o): - """find the auto-created properties of an objectclass. Only works for - classes that can be created using just a DN and the objectclass""" - if not o.has_key("exampleDN"): - return - testdn = create_testdn(o.exampleDN) - - print "testdn is '%s'\n" % testdn - - ldif = "dn: " + testdn - ldif += "\nobjectClass: " + o.name - try: - ldb.add(ldif) - except LdbError, e: - print "error adding %s: %s\n" % (o.name, e) - print "%s\n" % ldif - return - - res = ldb.search("", testdn, ldb.SCOPE_BASE) - ldb.delete(testdn) - - for a in res.msgs[0]: - attributes[a].autocreate = True - - -def expand_objectclass(ldb, o): - """look at auxiliary information from a class to intuit the existance of - more classes needed for a minimal schema""" - attrs = ["auxiliaryClass", "systemAuxiliaryClass", - "possSuperiors", "systemPossSuperiors", - "subClassOf"] - res = ldb.search( - expression="(&(objectClass=classSchema)(ldapDisplayName=%s))" % o.name, - basedn=rootDse["schemaNamingContext"], scope=ldb.SCOPE_SUBTREE, - attrs=attrs) - print "Expanding class %s\n" % o.name - assert(len(res) == 1) - msg = res[0] - for a in attrs: - if not msg.has_key(aname): - continue - list = msg[aname] - if isinstance(list, str): - list = [msg[aname]] - for name in list: - if not objectclasses.has_key(name): - print "Found new objectclass '%s'\n" % name - objectclasses[name] = Objectclass(ldb, name) - - -def add_objectclass_attributes(ldb, objectclass): - """add the must and may attributes from an objectclass to the full list - of attributes""" - attrs = ["mustContain", "systemMustContain", - "mayContain", "systemMayContain"] - for aname in attrs: - if not objectclass.has_key(aname): - continue - alist = objectclass[aname] - if isinstance(alist, str): - alist = [alist] - for a in alist: - if not attributes.has_key(a): - attributes[a] = Attribute(ldb, a) - - -def walk_dn(ldb, dn): - """process an individual record, working out what attributes it has""" - # get a list of all possible attributes for this object - attrs = ["allowedAttributes"] - try: - res = ldb.search("objectClass=*", dn, ldb.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) - except LdbError, e: - print "Unable to fetch all attributes for '%s' - %s\n" % (dn, e) - return - msg = res[0] - for a in msg: - if not attributes.has_key(a): - attributes[a] = Attribute(ldb, a) - -def walk_naming_context(ldb, namingContext): - """walk a naming context, looking for all records""" - try: - res = ldb.search("objectClass=*", namingContext, ldb.SCOPE_DEFAULT, - ["objectClass"]) - except LdbError, e: - print "Unable to fetch objectClasses for '%s' - %s\n" % (namingContext, e) - return - for msg in res: - msg = res.msgs[r]["objectClass"] - for objectClass in msg: - if not objectclasses.has_key(objectClass): - objectclasses[objectClass] = Objectclass(ldb, objectClass) - objectclasses[objectClass].exampleDN = res.msgs[r]["dn"] - walk_dn(ldb, res.msgs[r].dn) - -def trim_objectclass_attributes(ldb, objectclass): - """trim the may attributes for an objectClass""" - # trim possibleInferiors, - # include only the classes we extracted - if objectclass.has_key("possibleInferiors"): - possinf = objectclass["possibleInferiors"] - newpossinf = [] - if isinstance(possinf, str): - possinf = [possinf] - for x in possinf: - if objectclasses.has_key(x): - newpossinf[n] = x - n+=1 - objectclass["possibleInferiors"] = newpossinf - - # trim systemMayContain, - # remove duplicates - if objectclass.has_key("systemMayContain"): - sysmay = objectclass["systemMayContain"] - newsysmay = [] - if isinstance(sysmay, str): - sysmay = [sysmay] - for x in sysmay: - if not x in newsysmay: - newsysmay.append(x) - objectclass["systemMayContain"] = newsysmay - - # trim mayContain, - # remove duplicates - if not objectclass.has_key("mayContain"): - may = objectclass["mayContain"] - newmay = [] - if isinstance(may, str): - may = [may] - for x in may: - if not x in newmay: - newmay.append(x) - objectclass["mayContain"] = newmay - -def build_objectclass(ldb, name): - """load the basic attributes of an objectClass""" - attrs = ["name"] - try: - res = ldb.search( - expression="(&(objectClass=classSchema)(ldapDisplayName=%s))" % name, - basedn=rootDse["schemaNamingContext"], scope=ldb.SCOPE_SUBTREE, - attrs=attrs) - except LdbError, e: - print "unknown class '%s'\n" % name - return None - if len(res) == 0: - print "unknown class '%s'\n" % name - return None - return Objectclass(ldb, name) - -def attribute_list(objectclass, attr1, attr2): - """form a coalesced attribute list""" - a1 = objectclass[attr1] - a2 = objectclass[attr2] - if isinstance(a1, str): - a1 = [a1] - if isinstance(a2, str): - a2 = [a2] - return a1 + a2 - -def aggregate_list(name, list): - """write out a list in aggregate form""" - if list is None: - return - print "%s ( %s )" % (name, "$ ".join(list)) - -def write_aggregate_objectclass(objectclass): - """write the aggregate record for an objectclass""" - print "objectClasses: ( %s NAME '%s' " % (objectclass.governsID, objectclass.name) - if not objectclass.has_key('subClassOf'): - print "SUP %s " % objectclass['subClassOf'] - if objectclass.objectClassCategory == 1: - print "STRUCTURAL " - elif objectclass.objectClassCategory == 2: - print "ABSTRACT " - elif objectclass.objectClassCategory == 3: - print "AUXILIARY " - - list = attribute_list(objectclass, "systemMustContain", "mustContain") - aggregate_list("MUST", list) - - list = attribute_list(objectclass, "systemMayContain", "mayContain") - aggregate_list("MAY", list) - - print ")\n" - - -def write_aggregate_ditcontentrule(objectclass): - """write the aggregate record for an ditcontentrule""" - list = attribute_list(objectclass, "auxiliaryClass", "systemAuxiliaryClass") - if list is None: - return - - print "dITContentRules: ( %s NAME '%s' " % (objectclass.governsID, objectclass.name) - - aggregate_list("AUX", list) - - may_list = None - must_list = None - - for c in list: - list2 = attribute_list(objectclasses[c], - "mayContain", "systemMayContain") - may_list = may_list + list2 - list2 = attribute_list(objectclasses[c], - "mustContain", "systemMustContain") - must_list = must_list + list2 - - aggregate_list("MUST", must_list) - aggregate_list("MAY", may_list) - - print ")\n" - -def write_aggregate_attribute(attrib): - """write the aggregate record for an attribute""" - print "attributeTypes: ( %s NAME '%s' SYNTAX '%s' " % ( - attrib.attributeID, attrib.name, - map_attribute_syntax(attrib.attributeSyntax)) - if attrib['isSingleValued'] == "TRUE": - print "SINGLE-VALUE " - if attrib['systemOnly'] == "TRUE": - print "NO-USER-MODIFICATION " - - print ")\n" - - -def write_aggregate(): - """write the aggregate record""" - print "dn: CN=Aggregate,${SCHEMADN}\n" - print """objectClass: top -objectClass: subSchema -objectCategory: CN=SubSchema,${SCHEMADN} -""" - if not opts.dump_subschema_auto: - return - - for objectclass in objectclasses: - write_aggregate_objectclass(objectclass) - for attr in attributes: - write_aggregate_attribute(attr) - for objectclass in objectclasses: - write_aggregate_ditcontentrule(objectclass) - -def load_list(file): - """load a list from a file""" - return open(file, 'r').splitlines() - -# get the rootDSE -res = ldb.search("", "", ldb.SCOPE_BASE) -rootDse = res[0] - -# load the list of classes we are interested in -classes = load_list(classfile) -for classname in classes: - objectclass = build_objectclass(ldb, classname) - if objectclass is not None: - objectclasses[classname] = objectclass - - -# -# expand the objectclass list as needed -# -expanded = 0 - -# so EJS do not have while nor the break statement -# cannot find any other way than doing more loops -# than necessary to recursively expand all classes -# -for inf in range(500): - for n in objectclasses: - if not n in objectclasses_expanded: - expand_objectclass(ldb, objectclasses[i]) - objectclasses_expanded.add(n) - -# -# find objectclass properties -# -for objectclass in objectclasses: - find_objectclass_properties(ldb, objectclass) - - -# -# form the full list of attributes -# -for objectclass in objectclasses: - add_objectclass_attributes(ldb, objectclass) - -# and attribute properties -for attr in attributes: - find_attribute_properties(ldb, attr) - -# -# trim the 'may' attribute lists to those really needed -# -for objectclass in objectclasses: - trim_objectclass_attributes(ldb, objectclass) - -# -# dump an ldif form of the attributes and objectclasses -# -if opts.dump_attributes: - write_ldif(attributes, attrib_attrs) -if opts.dump_classes: - write_ldif(objectclasses, class_attrs) -if opts.dump_subschema: - write_aggregate() - -if not opts.verbose: - sys.exit(0) - -# -# dump list of objectclasses -# -print "objectClasses:\n" -for objectclass in objectclasses: - print "\t%s\n" % objectclass - -print "attributes:\n" -for attr in attributes: - print "\t%s\n" % attr - -print "autocreated attributes:\n" -for attr in attributes: - if attr.autocreate: - print "\t%s\n" % i diff --git a/source4/scripting/bin/smbstatus b/source4/scripting/bin/smbstatus index bbd0e84826..a9265ead6a 100755 --- a/source4/scripting/bin/smbstatus +++ b/source4/scripting/bin/smbstatus @@ -22,7 +22,7 @@ def show_sessions(conn): sessions = conn.smbsrv_information(irpc.SMBSRV_INFO_SESSIONS).next() print "User Client Connected at" - print "-------------------------------------------------------------------------------" + print "-" * 79 for session in sessions: fulluser = "%s/%s" % (session.account_name, session.domain_name) print "%-30s %16s %s" % (fulluser, session.client_ip, sys.httptime(session.connect_time)) @@ -33,7 +33,7 @@ def show_tcons(open_connection): conn = open_connection("smb_server") tcons = conn.smbsrv_information(irpc.SMBSRV_INFO_TCONS).next() print "Share Client Connected at" - print "-------------------------------------------------------------------------------" + print "-" * 79 for tcon in tcons: print "%-30s %16s %s" % (tcon.share_name, tcon.client_ip, sys.httptime(tcon.connect_time)) @@ -76,7 +76,7 @@ else: try: conn = open_connection("smb_server") except RuntimeError, (num, msg): - if msg == 'NT_STATUS_OBJECT_NAME_NOT_FOUND': + if msg == 'NT_STATUS_OBJECT_NAME_NOT_FOUND': print "No active connections" else: show_sessions(conn) -- cgit From deba4e8deda54f0c815d4bd2e3d73e0821b004b5 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 18 Sep 2008 21:53:08 +0200 Subject: Fix some tests. --- source4/dsdb/samdb/ldb_modules/tests/samba3sam.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py index 428e6b4d4b..dbf8584b11 100644 --- a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py +++ b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py @@ -32,6 +32,9 @@ from samba.tests import LdbTestCase, TestCaseInTempDir datadir = os.path.join(os.path.dirname(__file__), "../../../../../testdata/samba3") +def ldb_debug(l, text): + print text + class MapBaseTestCase(TestCaseInTempDir): def setup_data(self, obj, ldif): self.assertTrue(ldif is not None) @@ -189,13 +192,14 @@ class Samba3SamTestCase(MapBaseTestCase): print "Checking for existence of record (local || remote)" msg = self.ldb.search(expression="(|(unixName=bin)(sambaUnicodePwd=geheim))", attrs=['unixName','cn','dn', 'sambaUnicodePwd']) - print "got " + len(msg) + " replies" + print "got %d replies" % len(msg) self.assertEquals(len(msg), 1) # TODO: should check with more records self.assertEquals(msg[0]["cn"], "Niemand") - self.assertEquals(msg[0]["unixName"] == "bin" or msg[0]["sambaUnicodePwd"], "geheim") + self.assertEquals(msg[0]["unixName"], "bin") + self.assertEquals(msg[0]["sambaUnicodePwd"], "geheim") print "Checking for data in destination database" - msg = s3.db.search("(cn=Niemand)") + msg = self.samba3.db.search(expression="(cn=Niemand)") self.assertTrue(len(msg) >= 1) self.assertEquals(msg[0]["sambaSID"], "S-1-5-21-4231626423-2410014848-2360679739-2001") self.assertEquals(msg[0]["displayName"], "Niemand") @@ -237,7 +241,7 @@ delete: description print "Checking whether changes are no longer there..." msg = self.ldb.search(expression="(cn=Niemand)") self.assertTrue(len(msg) >= 1) - self.assertTrue(not "description" in res[0]) + self.assertTrue(not "description" in msg[0]) print "Renaming record..." self.ldb.rename("cn=Niemand,cn=Users,dc=vernstok,dc=nl", "cn=Niemand2,cn=Users,dc=vernstok,dc=nl") @@ -290,7 +294,12 @@ lastLogon: x description: x objectSid: S-1-5-21-4231626423-2410014848-2360679739-552 primaryGroupID: 1-5-21-4231626423-2410014848-2360679739-512 +""" + print ldif + self.ldb.add_ldif(substitute_var(ldif, self.samba4.substvars)) + + ldif = """ dn: """ + self.samba4.dn("cn=Y") + """ objectClass: top cn: Y @@ -300,7 +309,10 @@ dnsHostName: y nextRid: y lastLogon: y description: x +""" + self.ldb.add_ldif(substitute_var(ldif, self.samba4.substvars)) + ldif = """ dn: """ + self.samba4.dn("cn=Z") + """ objectClass: top cn: Z -- cgit From 41c645bde26a66360f4427be752c9720d1adff7b Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 18 Sep 2008 22:56:58 +0200 Subject: Fix tests, be less verbose. --- source4/dsdb/samdb/ldb_modules/tests/samba3sam.py | 70 +++++++++++------------ 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py index dbf8584b11..76f534ebc8 100644 --- a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py +++ b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py @@ -65,7 +65,6 @@ class MapBaseTestCase(TestCaseInTempDir): self.ldburl = "tdb://" + self.ldbfile tempdir = self.tempdir - print tempdir class Target: """Simple helper class that contains data for a specific SAM connection.""" @@ -110,40 +109,41 @@ class Samba3SamTestCase(MapBaseTestCase): self.setup_modules(ldb, self.samba3, self.samba4) self.ldb = Ldb(self.ldburl) - def test_s3sam_search(self): - print "Looking up by non-mapped attribute" + def test_search_non_mapped(self): + """Looking up by non-mapped attribute""" msg = self.ldb.search(expression="(cn=Administrator)") self.assertEquals(len(msg), 1) self.assertEquals(msg[0]["cn"], "Administrator") - print "Looking up by mapped attribute" + def test_search_non_mapped(self): + """Looking up by mapped attribute""" msg = self.ldb.search(expression="(name=Backup Operators)") self.assertEquals(len(msg), 1) self.assertEquals(msg[0]["name"], "Backup Operators") - print "Looking up by old name of renamed attribute" + def test_old_name_of_renamed(self): + """Looking up by old name of renamed attribute""" msg = self.ldb.search(expression="(displayName=Backup Operators)") self.assertEquals(len(msg), 0) - print "Looking up mapped entry containing SID" + def test_mapped_containing_sid(self): + """Looking up mapped entry containing SID""" msg = self.ldb.search(expression="(cn=Replicator)") self.assertEquals(len(msg), 1) - print msg[0].dn self.assertEquals(str(msg[0].dn), "cn=Replicator,ou=Groups,dc=vernstok,dc=nl") self.assertEquals(msg[0]["objectSid"], "S-1-5-21-4231626423-2410014848-2360679739-552") - - print "Checking mapping of objectClass" + # Check mapping of objectClass oc = set(msg[0]["objectClass"]) self.assertTrue(oc is not None) for i in oc: self.assertEquals(oc[i] == "posixGroup" or oc[i], "group") - print "Looking up by objectClass" + def test_search_by_objclass(self): + """Looking up by objectClass""" msg = self.ldb.search(expression="(|(objectClass=user)(cn=Administrator))") self.assertEquals(len(msg), 2) for i in range(len(msg)): - self.assertEquals((str(msg[i].dn), "unixName=Administrator,ou=Users,dc=vernstok,dc=nl") or - (str(msg[i].dn) == "unixName=nobody,ou=Users,dc=vernstok,dc=nl")) + self.assertTrue((str(msg[i].dn) == "unixName=Administrator,ou=Users,dc=vernstok,dc=nl") or (str(msg[i].dn) == "unixName=nobody,ou=Users,dc=vernstok,dc=nl")) def test_s3sam_modify(self): @@ -167,21 +167,21 @@ class Samba3SamTestCase(MapBaseTestCase): self.assertEquals(msg[0]["foo"], "bar") self.assertEquals(msg[0]["blah"], "Blie") - print "Adding record that will be mapped" + # Adding record that will be mapped self.ldb.add({"dn": "cn=Niemand,cn=Users,dc=vernstok,dc=nl", "objectClass": "user", "unixName": "bin", "sambaUnicodePwd": "geheim", "cn": "Niemand"}) - print "Checking for existence of record (remote)" + # Checking for existence of record (remote) msg = self.ldb.search(expression="(unixName=bin)", attrs=['unixName','cn','dn', 'sambaUnicodePwd']) self.assertEquals(len(msg), 1) self.assertEquals(msg[0]["cn"], "Niemand") self.assertEquals(msg[0]["sambaUnicodePwd"], "geheim") - print "Checking for existence of record (local && remote)" + # Checking for existence of record (local && remote) msg = self.ldb.search(expression="(&(unixName=bin)(sambaUnicodePwd=geheim))", attrs=['unixName','cn','dn', 'sambaUnicodePwd']) self.assertEquals(len(msg), 1) # TODO: should check with more records @@ -189,22 +189,22 @@ class Samba3SamTestCase(MapBaseTestCase): self.assertEquals(msg[0]["unixName"], "bin") self.assertEquals(msg[0]["sambaUnicodePwd"], "geheim") - print "Checking for existence of record (local || remote)" + # Checking for existence of record (local || remote) msg = self.ldb.search(expression="(|(unixName=bin)(sambaUnicodePwd=geheim))", attrs=['unixName','cn','dn', 'sambaUnicodePwd']) - print "got %d replies" % len(msg) + #print "got %d replies" % len(msg) self.assertEquals(len(msg), 1) # TODO: should check with more records self.assertEquals(msg[0]["cn"], "Niemand") self.assertEquals(msg[0]["unixName"], "bin") self.assertEquals(msg[0]["sambaUnicodePwd"], "geheim") - print "Checking for data in destination database" + # Checking for data in destination database msg = self.samba3.db.search(expression="(cn=Niemand)") self.assertTrue(len(msg) >= 1) self.assertEquals(msg[0]["sambaSID"], "S-1-5-21-4231626423-2410014848-2360679739-2001") self.assertEquals(msg[0]["displayName"], "Niemand") - print "Adding attribute..." + # Adding attribute... self.ldb.modify_ldif(""" dn: cn=Niemand,cn=Users,dc=vernstok,dc=nl changetype: modify @@ -212,13 +212,13 @@ add: description description: Blah """) - print "Checking whether changes are still there..." + # Checking whether changes are still there... msg = self.ldb.search(expression="(cn=Niemand)") self.assertTrue(len(msg) >= 1) self.assertEquals(msg[0]["cn"], "Niemand") self.assertEquals(msg[0]["description"], "Blah") - print "Modifying attribute..." + # Modifying attribute... self.ldb.modify_ldif(""" dn: cn=Niemand,cn=Users,dc=vernstok,dc=nl changetype: modify @@ -226,35 +226,35 @@ replace: description description: Blie """) - print "Checking whether changes are still there..." + # Checking whether changes are still there... msg = self.ldb.search(expression="(cn=Niemand)") self.assertTrue(len(msg) >= 1) self.assertEquals(msg[0]["description"], "Blie") - print "Deleting attribute..." + # Deleting attribute... self.ldb.modify_ldif(""" dn: cn=Niemand,cn=Users,dc=vernstok,dc=nl changetype: modify delete: description """) - print "Checking whether changes are no longer there..." + # Checking whether changes are no longer there... msg = self.ldb.search(expression="(cn=Niemand)") self.assertTrue(len(msg) >= 1) self.assertTrue(not "description" in msg[0]) - print "Renaming record..." + # Renaming record... self.ldb.rename("cn=Niemand,cn=Users,dc=vernstok,dc=nl", "cn=Niemand2,cn=Users,dc=vernstok,dc=nl") - print "Checking whether DN has changed..." + # Checking whether DN has changed... msg = self.ldb.search(expression="(cn=Niemand2)") self.assertEquals(len(msg), 1) self.assertEquals(str(msg[0].dn), "cn=Niemand2,cn=Users,dc=vernstok,dc=nl") - print "Deleting record..." + # Deleting record... self.ldb.delete("cn=Niemand2,cn=Users,dc=vernstok,dc=nl") - print "Checking whether record is gone..." + # Checking whether record is gone... msg = self.ldb.search(expression="(cn=Niemand2)") self.assertEquals(len(msg), 0) @@ -271,7 +271,7 @@ class MapTestCase(MapBaseTestCase): self.ldb = Ldb(self.ldburl) def test_map_search(self): - print "Running search tests on mapped data" + """Running search tests on mapped data.""" ldif = """ dn: """ + "sambaDomainName=TESTS,""" + self.samba3.basedn + """ objectclass: sambaDomain @@ -281,7 +281,7 @@ sambaNextRid: 2000 sambaDomainName: TESTS""" self.samba3.db.add_ldif(substitute_var(ldif, self.samba3.substvars)) - print "Add a set of split records" + # Add a set of split records ldif = """ dn: """ + self.samba4.dn("cn=X") + """ objectClass: user @@ -296,7 +296,6 @@ objectSid: S-1-5-21-4231626423-2410014848-2360679739-552 primaryGroupID: 1-5-21-4231626423-2410014848-2360679739-512 """ - print ldif self.ldb.add_ldif(substitute_var(ldif, self.samba4.substvars)) ldif = """ @@ -326,7 +325,7 @@ description: y self.ldb.add_ldif(substitute_var(ldif, self.samba4.substvars)) - print "Add a set of remote records" + # Add a set of remote records ldif = """ dn: """ + self.samba3.dn("cn=A") + """ @@ -357,7 +356,7 @@ description: y """ self.samba3.add_ldif(substitute_var(ldif, self.samba3.substvars)) - print "Testing search by DN" + # Testing search by DN # Search remote record by local DN dn = self.samba4.dn("cn=A") @@ -397,7 +396,7 @@ description: y self.assertTrue(not "lastLogon" in res[0]) self.assertEquals(res[0]["sambaLogonTime"], "x") - print "Testing search by attribute" + # Testing search by attribute # Search by ignored attribute attrs = ["dnsHostName", "lastLogon"] @@ -886,7 +885,7 @@ badPwdCount: 4 # Delete remote record self.ldb.delete(dn) - # Check in mapped db + # Check in mapped db that it's removed res = self.ldb.search(dn, scope=SCOPE_BASE) self.assertEquals(len(res), 0) # Check in remote db @@ -911,6 +910,7 @@ add: revision revision: 1 replace: description description: test + """ self.ldb.modify_ldif(ldif) # Check in mapped db -- cgit From 21897a0539e31c81bb7105fc5da7829a7d58f41e Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 18 Sep 2008 23:46:58 +0200 Subject: Improve formatting. --- source4/dsdb/samdb/ldb_modules/tests/samba3sam.py | 120 ++++++++++------------ 1 file changed, 54 insertions(+), 66 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py index 76f534ebc8..1b51636c28 100644 --- a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py +++ b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py @@ -36,6 +36,8 @@ def ldb_debug(l, text): print text class MapBaseTestCase(TestCaseInTempDir): + """Base test case for mapping tests.""" + def setup_data(self, obj, ldif): self.assertTrue(ldif is not None) obj.db.add_ldif(substitute_var(ldif, obj.substvars)) @@ -131,7 +133,8 @@ class Samba3SamTestCase(MapBaseTestCase): msg = self.ldb.search(expression="(cn=Replicator)") self.assertEquals(len(msg), 1) self.assertEquals(str(msg[0].dn), "cn=Replicator,ou=Groups,dc=vernstok,dc=nl") - self.assertEquals(msg[0]["objectSid"], "S-1-5-21-4231626423-2410014848-2360679739-552") + self.assertEquals(msg[0]["objectSid"], + "S-1-5-21-4231626423-2410014848-2360679739-552") # Check mapping of objectClass oc = set(msg[0]["objectClass"]) self.assertTrue(oc is not None) @@ -161,7 +164,9 @@ class Samba3SamTestCase(MapBaseTestCase): # TODO: Actually, this version should work as well but doesn't... # # - msg = self.ldb.search(expression="(cn=Foo)", base="cn=Foo", scope=SCOPE_BASE, attrs=['foo','blah','cn','showInAdvancedViewOnly']) + msg = self.ldb.search(expression="(cn=Foo)", base="cn=Foo", + scope=SCOPE_BASE, + attrs=['foo','blah','cn','showInAdvancedViewOnly']) self.assertEquals(len(msg), 1) self.assertEquals(msg[0]["showInAdvancedViewOnly"], "TRUE") self.assertEquals(msg[0]["foo"], "bar") @@ -201,7 +206,8 @@ class Samba3SamTestCase(MapBaseTestCase): # Checking for data in destination database msg = self.samba3.db.search(expression="(cn=Niemand)") self.assertTrue(len(msg) >= 1) - self.assertEquals(msg[0]["sambaSID"], "S-1-5-21-4231626423-2410014848-2360679739-2001") + self.assertEquals(msg[0]["sambaSID"], + "S-1-5-21-4231626423-2410014848-2360679739-2001") self.assertEquals(msg[0]["displayName"], "Niemand") # Adding attribute... @@ -244,7 +250,8 @@ delete: description self.assertTrue(not "description" in msg[0]) # Renaming record... - self.ldb.rename("cn=Niemand,cn=Users,dc=vernstok,dc=nl", "cn=Niemand2,cn=Users,dc=vernstok,dc=nl") + self.ldb.rename("cn=Niemand,cn=Users,dc=vernstok,dc=nl", + "cn=Niemand2,cn=Users,dc=vernstok,dc=nl") # Checking whether DN has changed... msg = self.ldb.search(expression="(cn=Niemand2)") @@ -360,8 +367,8 @@ description: y # Search remote record by local DN dn = self.samba4.dn("cn=A") - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(dn, scope=SCOPE_BASE, attrs=attrs) + res = self.ldb.search(dn, scope=SCOPE_BASE, + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 1) self.assertEquals(str(str(res[0].dn)), dn) self.assertTrue(not "dnsHostName" in res[0]) @@ -369,8 +376,8 @@ description: y # Search remote record by remote DN dn = self.samba3.dn("cn=A") - attrs = ["dnsHostName", "lastLogon", "sambaLogonTime"] - res = self.samba3.db.search(dn, scope=SCOPE_BASE, attrs=attrs) + res = self.samba3.db.search(dn, scope=SCOPE_BASE, + attrs=["dnsHostName", "lastLogon", "sambaLogonTime"]) self.assertEquals(len(res), 1) self.assertEquals(str(str(res[0].dn)), dn) self.assertTrue(not "dnsHostName" in res[0]) @@ -379,8 +386,8 @@ description: y # Search split record by local DN dn = self.samba4.dn("cn=X") - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(dn, scope=SCOPE_BASE, attrs=attrs) + res = self.ldb.search(dn, scope=SCOPE_BASE, + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 1) self.assertEquals(str(str(res[0].dn)), dn) self.assertEquals(res[0]["dnsHostName"], "x") @@ -388,8 +395,8 @@ description: y # Search split record by remote DN dn = self.samba3.dn("cn=X") - attrs = ["dnsHostName", "lastLogon", "sambaLogonTime"] - res = self.samba3.db.search(dn, scope=SCOPE_BASE, attrs=attrs) + res = self.samba3.db.search(dn, scope=SCOPE_BASE, + attrs=["dnsHostName", "lastLogon", "sambaLogonTime"]) self.assertEquals(len(res), 1) self.assertEquals(str(str(res[0].dn)), dn) self.assertTrue(not "dnsHostName" in res[0]) @@ -399,8 +406,8 @@ description: y # Testing search by attribute # Search by ignored attribute - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(revision=x)", scope=SCOPE_DEFAULT, attrs=attrs) + res = self.ldb.search(expression="(revision=x)", scope=SCOPE_DEFAULT, + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) self.assertEquals(str(str(res[0].dn)), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") @@ -410,8 +417,8 @@ description: y self.assertEquals(res[1]["lastLogon"], "x") # Search by kept attribute - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(description=y)", scope=SCOPE_DEFAULT, attrs=attrs) + res = self.ldb.search(expression="(description=y)", + scope=SCOPE_DEFAULT, attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) self.assertEquals(str(str(res[0].dn)), self.samba4.dn("cn=Z")) self.assertEquals(res[0]["dnsHostName"], "z") @@ -421,8 +428,7 @@ description: y self.assertEquals(res[1]["lastLogon"], "z") # Search by renamed attribute - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(badPwdCount=x)", scope=SCOPE_DEFAULT, attrs=attrs) + res = self.ldb.search(expression="(badPwdCount=x)", scope=SCOPE_DEFAULT, attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) @@ -432,12 +438,11 @@ description: y self.assertEquals(res[1]["lastLogon"], "x") # Search by converted attribute - attrs = ["dnsHostName", "lastLogon", "objectSid"] # TODO: # Using the SID directly in the parse tree leads to conversion # errors, letting the search fail with no results. #res = self.ldb.search("(objectSid=S-1-5-21-4231626423-2410014848-2360679739-552)", scope=SCOPE_DEFAULT, attrs) - res = self.ldb.search(expression="(objectSid=*)", attrs=attrs) + res = self.ldb.search(expression="(objectSid=*)", attrs=["dnsHostName", "lastLogon", "objectSid"]) self.assertEquals(len(res), 3) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=X")) self.assertEquals(res[0]["dnsHostName"], "x") @@ -451,8 +456,7 @@ description: y # Search by generated attribute # In most cases, this even works when the mapping is missing # a `convert_operator' by enumerating the remote db. - attrs = ["dnsHostName", "lastLogon", "primaryGroupID"] - res = self.ldb.search(expression="(primaryGroupID=512)", attrs=attrs) + res = self.ldb.search(expression="(primaryGroupID=512)", attrs=["dnsHostName", "lastLogon", "primaryGroupID"]) self.assertEquals(len(res), 1) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=A")) self.assertTrue(not "dnsHostName" in res[0]) @@ -474,8 +478,7 @@ description: y # # Search by remote name of renamed attribute */ - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(sambaBadPasswordCount=*)", attrs=attrs) + res = self.ldb.search(expression="(sambaBadPasswordCount=*)", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 0) # Search by objectClass @@ -516,8 +519,7 @@ description: y print "Testing search by parse tree" # Search by conjunction of local attributes - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(&(codePage=x)(revision=x))", attrs=attrs) + res = self.ldb.search(expression="(&(codePage=x)(revision=x))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") @@ -527,8 +529,7 @@ description: y self.assertEquals(res[1]["lastLogon"], "x") # Search by conjunction of remote attributes - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(&(lastLogon=x)(description=x))", attrs=attrs) + res = self.ldb.search(expression="(&(lastLogon=x)(description=x))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=X")) self.assertEquals(res[0]["dnsHostName"], "x") @@ -538,8 +539,7 @@ description: y self.assertEquals(res[1]["lastLogon"], "x") # Search by conjunction of local and remote attribute - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(&(codePage=x)(description=x))", attrs=attrs) + res = self.ldb.search(expression="(&(codePage=x)(description=x))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") @@ -556,8 +556,7 @@ description: y self.assertEquals(len(res), 0) # Search by disjunction of local attributes - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(|(revision=x)(dnsHostName=x))", attrs=attrs) + res = self.ldb.search(expression="(|(revision=x)(dnsHostName=x))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") @@ -567,8 +566,7 @@ description: y self.assertEquals(res[1]["lastLogon"], "x") # Search by disjunction of remote attributes - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(|(badPwdCount=x)(lastLogon=x))", attrs=attrs) + res = self.ldb.search(expression="(|(badPwdCount=x)(lastLogon=x))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 3) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue("dnsHostName" in res[0]) @@ -581,8 +579,7 @@ description: y self.assertEquals(res[2]["lastLogon"], "x") # Search by disjunction of local and remote attribute - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(|(revision=x)(lastLogon=y))", attrs=attrs) + res = self.ldb.search(expression="(|(revision=x)(lastLogon=y))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 3) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") @@ -595,13 +592,11 @@ description: y self.assertEquals(res[2]["lastLogon"], "x") # Search by disjunction of local and remote attribute w/o match - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(|(codePage=y)(nextRid=z))", attrs=attrs) + res = self.ldb.search(expression="(|(codePage=y)(nextRid=z))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 0) # Search by negated local attribute - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(!(revision=x))", attrs=attrs) + res = self.ldb.search(expression="(!(revision=x))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 5) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) @@ -617,8 +612,7 @@ description: y self.assertEquals(res[3]["lastLogon"], "z") # Search by negated remote attribute - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(!(description=x))", attrs=attrs) + res = self.ldb.search(expression="(!(description=x))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 3) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Z")) self.assertEquals(res[0]["dnsHostName"], "z") @@ -628,8 +622,7 @@ description: y self.assertEquals(res[1]["lastLogon"], "z") # Search by negated conjunction of local attributes - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(!(&(codePage=x)(revision=x)))", attrs=attrs) + res = self.ldb.search(expression="(!(&(codePage=x)(revision=x)))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 5) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) @@ -645,8 +638,7 @@ description: y self.assertEquals(res[3]["lastLogon"], "z") # Search by negated conjunction of remote attributes - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(!(&(lastLogon=x)(description=x)))", attrs=attrs) + res = self.ldb.search(expression="(!(&(lastLogon=x)(description=x)))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 5) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") @@ -662,8 +654,7 @@ description: y self.assertEquals(res[3]["lastLogon"], "z") # Search by negated conjunction of local and remote attribute - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(!(&(codePage=x)(description=x)))", attrs=attrs) + res = self.ldb.search(expression="(!(&(codePage=x)(description=x)))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 5) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) @@ -679,8 +670,7 @@ description: y self.assertEquals(res[3]["lastLogon"], "z") # Search by negated disjunction of local attributes - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(!(|(revision=x)(dnsHostName=x)))", attrs=attrs) + res = self.ldb.search(expression="(!(|(revision=x)(dnsHostName=x)))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) self.assertEquals(res[0]["lastLogon"], "y") @@ -695,8 +685,7 @@ description: y self.assertEquals(res[3]["lastLogon"], "z") # Search by negated disjunction of remote attributes - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(!(|(badPwdCount=x)(lastLogon=x)))", attrs=attrs) + res = self.ldb.search(expression="(!(|(badPwdCount=x)(lastLogon=x)))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 4) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") @@ -709,8 +698,8 @@ description: y self.assertEquals(res[2]["lastLogon"], "z") # Search by negated disjunction of local and remote attribute - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(!(|(revision=x)(lastLogon=y)))", attrs=attrs) + res = self.ldb.search(expression="(!(|(revision=x)(lastLogon=y)))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 4) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=A")) self.assertTrue(not "dnsHostName" in res[0]) @@ -723,8 +712,7 @@ description: y self.assertEquals(res[2]["lastLogon"], "z") print "Search by complex parse tree" - attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(|(&(revision=x)(dnsHostName=x))(!(&(description=x)(nextRid=y)))(badPwdCount=y))", attrs=attrs) + res = self.ldb.search(expression="(|(&(revision=x)(dnsHostName=x))(!(&(description=x)(nextRid=y)))(badPwdCount=y))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 6) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) @@ -816,8 +804,8 @@ description: foo "sambaBadPasswordCount": "3", "sambaNextRid": "1001"}) # Check it's there - attrs = ["description", "sambaBadPasswordCount", "sambaNextRid"] - res = self.samba3.db.search(dn2, scope=SCOPE_BASE, attrs=attrs) + res = self.samba3.db.search(dn2, scope=SCOPE_BASE, + attrs=["description", "sambaBadPasswordCount", "sambaNextRid"]) self.assertEquals(len(res), 1) self.assertEquals(str(res[0].dn), dn2) self.assertEquals(res[0]["description"], "foo") @@ -845,16 +833,16 @@ badPwdCount: 4 """ self.ldb.modify_ldif(ldif) # Check in mapped db - attrs = ["description", "badPwdCount", "nextRid"] - res = self.ldb.search(dn, scope=SCOPE_BASE, attrs=attrs) + res = self.ldb.search(dn, scope=SCOPE_BASE, + attrs=["description", "badPwdCount", "nextRid"]) self.assertEquals(len(res), 1) self.assertEquals(str(res[0].dn), dn) self.assertEquals(res[0]["description"], "test") self.assertEquals(res[0]["badPwdCount"], "4") self.assertEquals(res[0]["nextRid"], "1001") # Check in remote db - attrs = ["description", "sambaBadPasswordCount", "sambaNextRid"] - res = self.samba3.db.search(dn2, scope=SCOPE_BASE, attrs=attrs) + res = self.samba3.db.search(dn2, scope=SCOPE_BASE, + attrs=["description", "sambaBadPasswordCount", "sambaNextRid"]) self.assertEquals(len(res), 1) self.assertEquals(str(res[0].dn), dn2) self.assertEquals(res[0]["description"], "test") @@ -866,8 +854,8 @@ badPwdCount: 4 self.ldb.rename(dn, dn2) # Check in mapped db dn = dn2 - attrs = ["description", "badPwdCount", "nextRid"] - res = self.ldb.search(dn, scope=SCOPE_BASE, attrs=attrs) + res = self.ldb.search(dn, scope=SCOPE_BASE, + attrs=["description", "badPwdCount", "nextRid"]) self.assertEquals(len(res), 1) self.assertEquals(str(res[0].dn), dn) self.assertEquals(res[0]["description"], "test") @@ -875,8 +863,8 @@ badPwdCount: 4 self.assertEquals(res[0]["nextRid"], "1001") # Check in remote db dn2 = self.samba3.dn("cn=toast") - attrs = ["description", "sambaBadPasswordCount", "sambaNextRid"] - res = self.samba3.db.search(dn2, scope=SCOPE_BASE, attrs=attrs) + res = self.samba3.db.search(dn2, scope=SCOPE_BASE, + attrs=["description", "sambaBadPasswordCount", "sambaNextRid"]) self.assertEquals(len(res), 1) self.assertEquals(str(res[0].dn), dn2) self.assertEquals(res[0]["description"], "test") -- cgit From ec80fe4b214e311952ab67b3fd8b1cb1551c3b5c Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 18 Sep 2008 23:54:53 +0200 Subject: Implement __repr__ for Sid. --- source4/libcli/security/security.i | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/source4/libcli/security/security.i b/source4/libcli/security/security.i index 1d964cc3d5..6ba106bb5f 100644 --- a/source4/libcli/security/security.i +++ b/source4/libcli/security/security.i @@ -27,8 +27,8 @@ typedef struct security_token security_token; typedef struct security_descriptor security_descriptor; %} -%import "../../lib/talloc/talloc.i" -%import "../util/errors.i" +%import "../lib/talloc/talloc.i" +%include "../util/errors.i" %import "stdint.i" enum sec_privilege { @@ -117,6 +117,10 @@ typedef struct dom_sid { #endif bool equal(const struct dom_sid *other); } +%pythoncode { + def __repr__(self): + return "Sid(%r)" % str(self) +} } dom_sid; %feature("docstring") random_sid "random_sid() -> sid\n" \ -- cgit From 6f6e42ce60e3f9adfebffa7db04eafe717942c1b Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 18 Sep 2008 23:55:50 +0200 Subject: Generate with 1.3.36. --- source4/auth/auth.py | 2 +- source4/auth/auth_wrap.c | 14 ++-- source4/auth/credentials/credentials.py | 2 +- source4/auth/credentials/credentials_wrap.c | 47 +++++++------ source4/lib/events/events.i | 2 +- source4/lib/events/events.py | 2 +- source4/lib/events/events_wrap.c | 17 +++-- source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c | 4 ++ source4/lib/registry/registry.i | 2 +- source4/libcli/security/security.py | 5 +- source4/libcli/security/security_wrap.c | 62 ++++++++--------- source4/libcli/swig/libcli_smb.i | 2 +- source4/libcli/swig/libcli_smb.py | 2 +- source4/libcli/swig/libcli_smb_wrap.c | 14 ++-- source4/param/param.py | 2 +- source4/param/param_wrap.c | 100 ++++++++++++++-------------- source4/scripting/python/config.m4 | 2 +- source4/scripting/python/misc.i | 2 +- 18 files changed, 158 insertions(+), 125 deletions(-) diff --git a/source4/auth/auth.py b/source4/auth/auth.py index 226175a75b..1e5d68804b 100644 --- a/source4/auth/auth.py +++ b/source4/auth/auth.py @@ -1,5 +1,5 @@ # This file was automatically generated by SWIG (http://www.swig.org). -# Version 1.3.35 +# Version 1.3.36 # # Don't modify this file, modify the SWIG interface instead. diff --git a/source4/auth/auth_wrap.c b/source4/auth/auth_wrap.c index dea76ef87d..c514821c72 100644 --- a/source4/auth/auth_wrap.c +++ b/source4/auth/auth_wrap.c @@ -1,6 +1,6 @@ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). - * Version 1.3.35 + * Version 1.3.36 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make @@ -52,6 +52,12 @@ # endif #endif +#ifndef SWIG_MSC_UNSUPPRESS_4505 +# if defined(_MSC_VER) +# pragma warning(disable : 4505) /* unreferenced local function has been removed */ +# endif +#endif + #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) @@ -2523,7 +2529,7 @@ static swig_module_info swig_module = {swig_types, 16, 0, 0, 0, 0}; #define SWIG_name "_auth" -#define SWIGVERSION 0x010335 +#define SWIGVERSION 0x010336 #define SWIG_VERSION SWIGVERSION @@ -2548,13 +2554,13 @@ SWIGINTERN PyObject *_wrap_system_session(PyObject *SWIGUNUSEDPARM(self), PyObje PyObject *resultobj = 0; TALLOC_CTX *arg1 = (TALLOC_CTX *) 0 ; struct loadparm_context *arg2 = (struct loadparm_context *) 0 ; - struct auth_session_info *result = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "lp_ctx", NULL }; + struct auth_session_info *result = 0 ; arg2 = loadparm_init(NULL); arg1 = NULL; @@ -2578,13 +2584,13 @@ SWIGINTERN PyObject *_wrap_system_session_anon(PyObject *SWIGUNUSEDPARM(self), P PyObject *resultobj = 0; TALLOC_CTX *arg1 = (TALLOC_CTX *) 0 ; struct loadparm_context *arg2 = (struct loadparm_context *) 0 ; - struct auth_session_info *result = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "lp_ctx", NULL }; + struct auth_session_info *result = 0 ; arg2 = loadparm_init(NULL); arg1 = NULL; diff --git a/source4/auth/credentials/credentials.py b/source4/auth/credentials/credentials.py index 2cd56c3599..fe21dd2ba2 100644 --- a/source4/auth/credentials/credentials.py +++ b/source4/auth/credentials/credentials.py @@ -1,5 +1,5 @@ # This file was automatically generated by SWIG (http://www.swig.org). -# Version 1.3.35 +# Version 1.3.36 # # Don't modify this file, modify the SWIG interface instead. diff --git a/source4/auth/credentials/credentials_wrap.c b/source4/auth/credentials/credentials_wrap.c index 81ba426e45..260451d0fc 100644 --- a/source4/auth/credentials/credentials_wrap.c +++ b/source4/auth/credentials/credentials_wrap.c @@ -1,6 +1,6 @@ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). - * Version 1.3.35 + * Version 1.3.36 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make @@ -52,6 +52,12 @@ # endif #endif +#ifndef SWIG_MSC_UNSUPPRESS_4505 +# if defined(_MSC_VER) +# pragma warning(disable : 4505) /* unreferenced local function has been removed */ +# endif +#endif + #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) @@ -2524,7 +2530,7 @@ static swig_module_info swig_module = {swig_types, 17, 0, 0, 0, 0}; #define SWIG_name "_credentials" -#define SWIGVERSION 0x010335 +#define SWIGVERSION 0x010336 #define SWIG_VERSION SWIGVERSION @@ -2839,13 +2845,13 @@ fail: SWIGINTERN PyObject *_wrap_Credentials_get_username(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; cli_credentials *arg1 = (cli_credentials *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + char *result = 0 ; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_get_username",kwnames,&obj0)) SWIG_fail; @@ -2869,7 +2875,6 @@ SWIGINTERN PyObject *_wrap_Credentials_set_username(PyObject *SWIGUNUSEDPARM(sel cli_credentials *arg1 = (cli_credentials *) 0 ; char *arg2 = (char *) 0 ; enum credentials_obtained arg3 = (enum credentials_obtained) CRED_SPECIFIED ; - bool result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -2883,6 +2888,7 @@ SWIGINTERN PyObject *_wrap_Credentials_set_username(PyObject *SWIGUNUSEDPARM(sel char * kwnames[] = { (char *) "self",(char *) "value",(char *) "obtained", NULL }; + bool result; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OOO:Credentials_set_username",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; @@ -2920,13 +2926,13 @@ fail: SWIGINTERN PyObject *_wrap_Credentials_get_password(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; cli_credentials *arg1 = (cli_credentials *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + char *result = 0 ; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_get_password",kwnames,&obj0)) SWIG_fail; @@ -2950,7 +2956,6 @@ SWIGINTERN PyObject *_wrap_Credentials_set_password(PyObject *SWIGUNUSEDPARM(sel cli_credentials *arg1 = (cli_credentials *) 0 ; char *arg2 = (char *) 0 ; enum credentials_obtained arg3 = (enum credentials_obtained) CRED_SPECIFIED ; - bool result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -2964,6 +2969,7 @@ SWIGINTERN PyObject *_wrap_Credentials_set_password(PyObject *SWIGUNUSEDPARM(sel char * kwnames[] = { (char *) "self",(char *) "val",(char *) "obtained", NULL }; + bool result; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OOO:Credentials_set_password",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; @@ -3001,13 +3007,13 @@ fail: SWIGINTERN PyObject *_wrap_Credentials_get_domain(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; cli_credentials *arg1 = (cli_credentials *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + char *result = 0 ; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_get_domain",kwnames,&obj0)) SWIG_fail; @@ -3031,7 +3037,6 @@ SWIGINTERN PyObject *_wrap_Credentials_set_domain(PyObject *SWIGUNUSEDPARM(self) cli_credentials *arg1 = (cli_credentials *) 0 ; char *arg2 = (char *) 0 ; enum credentials_obtained arg3 = (enum credentials_obtained) CRED_SPECIFIED ; - bool result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3045,6 +3050,7 @@ SWIGINTERN PyObject *_wrap_Credentials_set_domain(PyObject *SWIGUNUSEDPARM(self) char * kwnames[] = { (char *) "self",(char *) "val",(char *) "obtained", NULL }; + bool result; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OOO:Credentials_set_domain",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; @@ -3082,13 +3088,13 @@ fail: SWIGINTERN PyObject *_wrap_Credentials_get_realm(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; cli_credentials *arg1 = (cli_credentials *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + char *result = 0 ; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_get_realm",kwnames,&obj0)) SWIG_fail; @@ -3112,7 +3118,6 @@ SWIGINTERN PyObject *_wrap_Credentials_set_realm(PyObject *SWIGUNUSEDPARM(self), cli_credentials *arg1 = (cli_credentials *) 0 ; char *arg2 = (char *) 0 ; enum credentials_obtained arg3 = (enum credentials_obtained) CRED_SPECIFIED ; - bool result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3126,6 +3131,7 @@ SWIGINTERN PyObject *_wrap_Credentials_set_realm(PyObject *SWIGUNUSEDPARM(self), char * kwnames[] = { (char *) "self",(char *) "val",(char *) "obtained", NULL }; + bool result; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OOO:Credentials_set_realm",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; @@ -3253,13 +3259,13 @@ fail: SWIGINTERN PyObject *_wrap_Credentials_get_bind_dn(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; cli_credentials *arg1 = (cli_credentials *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + char *result = 0 ; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_get_bind_dn",kwnames,&obj0)) SWIG_fail; @@ -3282,7 +3288,6 @@ SWIGINTERN PyObject *_wrap_Credentials_set_bind_dn(PyObject *SWIGUNUSEDPARM(self PyObject *resultobj = 0; cli_credentials *arg1 = (cli_credentials *) 0 ; char *arg2 = (char *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3293,6 +3298,7 @@ SWIGINTERN PyObject *_wrap_Credentials_set_bind_dn(PyObject *SWIGUNUSEDPARM(self char * kwnames[] = { (char *) "self",(char *) "bind_dn", NULL }; + bool result; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OO:Credentials_set_bind_dn",kwnames,&obj0,&obj1)) SWIG_fail; @@ -3350,13 +3356,13 @@ fail: SWIGINTERN PyObject *_wrap_Credentials_get_workstation(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; cli_credentials *arg1 = (cli_credentials *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + char *result = 0 ; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_get_workstation",kwnames,&obj0)) SWIG_fail; @@ -3380,7 +3386,6 @@ SWIGINTERN PyObject *_wrap_Credentials_set_workstation(PyObject *SWIGUNUSEDPARM( cli_credentials *arg1 = (cli_credentials *) 0 ; char *arg2 = (char *) 0 ; enum credentials_obtained arg3 = (enum credentials_obtained) CRED_SPECIFIED ; - bool result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3394,6 +3399,7 @@ SWIGINTERN PyObject *_wrap_Credentials_set_workstation(PyObject *SWIGUNUSEDPARM( char * kwnames[] = { (char *) "self",(char *) "workstation",(char *) "obtained", NULL }; + bool result; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OOO:Credentials_set_workstation",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; @@ -3432,7 +3438,6 @@ SWIGINTERN PyObject *_wrap_Credentials_set_machine_account(PyObject *SWIGUNUSEDP PyObject *resultobj = 0; cli_credentials *arg1 = (cli_credentials *) 0 ; struct loadparm_context *arg2 = (struct loadparm_context *) 0 ; - NTSTATUS result; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -3442,6 +3447,7 @@ SWIGINTERN PyObject *_wrap_Credentials_set_machine_account(PyObject *SWIGUNUSEDP char * kwnames[] = { (char *) "self",(char *) "lp_ctx", NULL }; + NTSTATUS result; arg1 = NULL; arg2 = loadparm_init(NULL); @@ -3510,13 +3516,13 @@ fail: SWIGINTERN PyObject *_wrap_Credentials_is_anonymous(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; cli_credentials *arg1 = (cli_credentials *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + bool result; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_is_anonymous",kwnames,&obj0)) SWIG_fail; @@ -3539,13 +3545,13 @@ SWIGINTERN PyObject *_wrap_Credentials_get_nt_hash(PyObject *SWIGUNUSEDPARM(self PyObject *resultobj = 0; cli_credentials *arg1 = (cli_credentials *) 0 ; TALLOC_CTX *arg2 = (TALLOC_CTX *) 0 ; - struct samr_Password *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + struct samr_Password *result = 0 ; arg1 = NULL; arg2 = NULL; @@ -3568,13 +3574,13 @@ fail: SWIGINTERN PyObject *_wrap_Credentials_authentication_requested(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; cli_credentials *arg1 = (cli_credentials *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + bool result; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_authentication_requested",kwnames,&obj0)) SWIG_fail; @@ -3596,13 +3602,13 @@ fail: SWIGINTERN PyObject *_wrap_Credentials_wrong_password(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; cli_credentials *arg1 = (cli_credentials *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + bool result; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_wrong_password",kwnames,&obj0)) SWIG_fail; @@ -3624,13 +3630,13 @@ fail: SWIGINTERN PyObject *_wrap_Credentials_set_cmdline_callbacks(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; cli_credentials *arg1 = (cli_credentials *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + bool result; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_set_cmdline_callbacks",kwnames,&obj0)) SWIG_fail; @@ -3669,7 +3675,6 @@ SWIGINTERN PyObject *_wrap_delete_Credentials(PyObject *SWIGUNUSEDPARM(self), Py arg1 = (cli_credentials *)(argp1); } delete_cli_credentials(arg1); - resultobj = SWIG_Py_Void(); return resultobj; fail: diff --git a/source4/lib/events/events.i b/source4/lib/events/events.i index 5f790aeac5..8a0d9c4b6f 100644 --- a/source4/lib/events/events.i +++ b/source4/lib/events/events.i @@ -18,7 +18,7 @@ %module(docstring="Event management.",package="samba.events") events; -%import "../talloc/talloc.i"; +%import "../../../lib/talloc/talloc.i"; %{ #include "events.h" diff --git a/source4/lib/events/events.py b/source4/lib/events/events.py index f217c29d78..c15ea8b9e5 100644 --- a/source4/lib/events/events.py +++ b/source4/lib/events/events.py @@ -1,5 +1,5 @@ # This file was automatically generated by SWIG (http://www.swig.org). -# Version 1.3.33 +# Version 1.3.36 # # Don't modify this file, modify the SWIG interface instead. diff --git a/source4/lib/events/events_wrap.c b/source4/lib/events/events_wrap.c index ccaeab7ad6..335652101b 100644 --- a/source4/lib/events/events_wrap.c +++ b/source4/lib/events/events_wrap.c @@ -1,6 +1,6 @@ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). - * Version 1.3.35 + * Version 1.3.36 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make @@ -52,6 +52,12 @@ # endif #endif +#ifndef SWIG_MSC_UNSUPPRESS_4505 +# if defined(_MSC_VER) +# pragma warning(disable : 4505) /* unreferenced local function has been removed */ +# endif +#endif + #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) @@ -2511,7 +2517,7 @@ static swig_module_info swig_module = {swig_types, 4, 0, 0, 0, 0}; #define SWIG_name "_events" -#define SWIGVERSION 0x010335 +#define SWIGVERSION 0x010336 #define SWIG_VERSION SWIGVERSION @@ -2623,10 +2629,10 @@ fail: SWIGINTERN PyObject *_wrap_event_loop_once(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; event *arg1 = (event *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -2646,10 +2652,10 @@ fail: SWIGINTERN PyObject *_wrap_event_loop_wait(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; event *arg1 = (event *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -2681,7 +2687,6 @@ SWIGINTERN PyObject *_wrap_delete_event(PyObject *SWIGUNUSEDPARM(self), PyObject } arg1 = (event *)(argp1); delete_event(arg1); - resultobj = SWIG_Py_Void(); return resultobj; fail: @@ -2704,7 +2709,6 @@ SWIGINTERN PyObject *_wrap_event_context_init_byname(PyObject *SWIGUNUSEDPARM(se PyObject *resultobj = 0; TALLOC_CTX *arg1 = (TALLOC_CTX *) 0 ; char *arg2 = (char *) 0 ; - struct event_context *result = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; @@ -2712,6 +2716,7 @@ SWIGINTERN PyObject *_wrap_event_context_init_byname(PyObject *SWIGUNUSEDPARM(se char * kwnames[] = { (char *) "name", NULL }; + struct event_context *result = 0 ; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:event_context_init_byname",kwnames,&obj0)) SWIG_fail; diff --git a/source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c b/source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c index 654574cd2f..4fea43c8c8 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c +++ b/source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c @@ -64,6 +64,10 @@ static void ltdb_log_fn(struct tdb_context *tdb, enum tdb_debug_level level, con struct ldb_context *ldb = talloc_get_type(tdb_get_logging_private(tdb), struct ldb_context); enum ldb_debug_level ldb_level; char *message; + + if (ldb == NULL) + return; + va_start(ap, fmt); message = talloc_vasprintf(ldb, fmt, ap); va_end(ap); diff --git a/source4/lib/registry/registry.i b/source4/lib/registry/registry.i index c55197c3d0..fe3a81d889 100644 --- a/source4/lib/registry/registry.i +++ b/source4/lib/registry/registry.i @@ -43,7 +43,7 @@ typedef struct hive_key hive_key; } %import "stdint.i" -%import "../../lib/talloc/talloc.i" +%import "../../../lib/talloc/talloc.i" %import "../../auth/credentials/credentials.i" %import "../../param/param.i" %import "../events/events.i" diff --git a/source4/libcli/security/security.py b/source4/libcli/security/security.py index 065c7a19e4..c310dde56b 100644 --- a/source4/libcli/security/security.py +++ b/source4/libcli/security/security.py @@ -1,5 +1,5 @@ # This file was automatically generated by SWIG (http://www.swig.org). -# Version 1.3.35 +# Version 1.3.36 # # Don't modify this file, modify the SWIG interface instead. @@ -149,6 +149,9 @@ class Sid(object): __repr__ = _swig_repr def __init__(self, *args, **kwargs): _security.Sid_swiginit(self,_security.new_Sid(*args, **kwargs)) + def __repr__(self): + return "Sid(%r)" % str(self) + __swig_destroy__ = _security.delete_Sid Sid.__str__ = new_instancemethod(_security.Sid___str__,None,Sid) Sid.__eq__ = new_instancemethod(_security.Sid___eq__,None,Sid) diff --git a/source4/libcli/security/security_wrap.c b/source4/libcli/security/security_wrap.c index a10626c043..b7d66b5aec 100644 --- a/source4/libcli/security/security_wrap.c +++ b/source4/libcli/security/security_wrap.c @@ -1,6 +1,6 @@ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). - * Version 1.3.35 + * Version 1.3.36 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make @@ -52,6 +52,12 @@ # endif #endif +#ifndef SWIG_MSC_UNSUPPRESS_4505 +# if defined(_MSC_VER) +# pragma warning(disable : 4505) /* unreferenced local function has been removed */ +# endif +#endif + #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) @@ -2521,7 +2527,7 @@ static swig_module_info swig_module = {swig_types, 14, 0, 0, 0, 0}; #define SWIG_name "_security" -#define SWIGVERSION 0x010335 +#define SWIGVERSION 0x010336 #define SWIG_VERSION SWIGVERSION @@ -2537,6 +2543,9 @@ typedef struct security_token security_token; typedef struct security_descriptor security_descriptor; +#include "libcli/util/pyerrors.h" + + #define SWIG_From_long PyInt_FromLong @@ -2834,7 +2843,6 @@ SWIGINTERN PyObject *_wrap_SecurityToken_is_sid(PyObject *SWIGUNUSEDPARM(self), PyObject *resultobj = 0; security_token *arg1 = (security_token *) 0 ; struct dom_sid *arg2 = (struct dom_sid *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -2844,6 +2852,7 @@ SWIGINTERN PyObject *_wrap_SecurityToken_is_sid(PyObject *SWIGUNUSEDPARM(self), char * kwnames[] = { (char *) "self",(char *) "sid", NULL }; + bool result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:SecurityToken_is_sid",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_security_token, 0 | 0 ); @@ -2867,10 +2876,10 @@ fail: SWIGINTERN PyObject *_wrap_SecurityToken_is_system(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; security_token *arg1 = (security_token *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + bool result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -2890,10 +2899,10 @@ fail: SWIGINTERN PyObject *_wrap_SecurityToken_is_anonymous(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; security_token *arg1 = (security_token *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + bool result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -2914,7 +2923,6 @@ SWIGINTERN PyObject *_wrap_SecurityToken_has_sid(PyObject *SWIGUNUSEDPARM(self), PyObject *resultobj = 0; security_token *arg1 = (security_token *) 0 ; struct dom_sid *arg2 = (struct dom_sid *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -2924,6 +2932,7 @@ SWIGINTERN PyObject *_wrap_SecurityToken_has_sid(PyObject *SWIGUNUSEDPARM(self), char * kwnames[] = { (char *) "self",(char *) "sid", NULL }; + bool result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:SecurityToken_has_sid",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_security_token, 0 | 0 ); @@ -2947,10 +2956,10 @@ fail: SWIGINTERN PyObject *_wrap_SecurityToken_has_builtin_administrators(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; security_token *arg1 = (security_token *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + bool result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -2970,10 +2979,10 @@ fail: SWIGINTERN PyObject *_wrap_SecurityToken_has_nt_authenticated_users(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; security_token *arg1 = (security_token *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + bool result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -2994,7 +3003,6 @@ SWIGINTERN PyObject *_wrap_SecurityToken_has_privilege(PyObject *SWIGUNUSEDPARM( PyObject *resultobj = 0; security_token *arg1 = (security_token *) 0 ; enum sec_privilege arg2 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; int val2 ; @@ -3004,6 +3012,7 @@ SWIGINTERN PyObject *_wrap_SecurityToken_has_privilege(PyObject *SWIGUNUSEDPARM( char * kwnames[] = { (char *) "self",(char *) "privilege", NULL }; + bool result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:SecurityToken_has_privilege",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_security_token, 0 | 0 ); @@ -3072,7 +3081,6 @@ SWIGINTERN PyObject *_wrap_delete_SecurityToken(PyObject *SWIGUNUSEDPARM(self), } arg1 = (security_token *)(argp1); delete_security_token(arg1); - resultobj = SWIG_Py_Void(); return resultobj; fail: @@ -3110,7 +3118,6 @@ SWIGINTERN PyObject *_wrap_security_descriptor_sacl_add(PyObject *SWIGUNUSEDPARM PyObject *resultobj = 0; security_descriptor *arg1 = (security_descriptor *) 0 ; struct security_ace *arg2 = (struct security_ace *) 0 ; - NTSTATUS result; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -3120,6 +3127,7 @@ SWIGINTERN PyObject *_wrap_security_descriptor_sacl_add(PyObject *SWIGUNUSEDPARM char * kwnames[] = { (char *) "self",(char *) "ace", NULL }; + NTSTATUS result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:security_descriptor_sacl_add",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_security_descriptor, 0 | 0 ); @@ -3134,8 +3142,7 @@ SWIGINTERN PyObject *_wrap_security_descriptor_sacl_add(PyObject *SWIGUNUSEDPARM arg2 = (struct security_ace *)(argp2); result = security_descriptor_sacl_add(arg1,(struct security_ace const *)arg2); if (NT_STATUS_IS_ERR(result)) { - PyObject *obj = Py_BuildValue((char *)"(i,s)", NT_STATUS_V(result), nt_errstr(result)); - PyErr_SetObject(PyExc_RuntimeError, obj); + PyErr_SetNTSTATUS(result); SWIG_fail; } else if (resultobj == NULL) { resultobj = Py_None; @@ -3150,7 +3157,6 @@ SWIGINTERN PyObject *_wrap_security_descriptor_dacl_add(PyObject *SWIGUNUSEDPARM PyObject *resultobj = 0; security_descriptor *arg1 = (security_descriptor *) 0 ; struct security_ace *arg2 = (struct security_ace *) 0 ; - NTSTATUS result; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -3160,6 +3166,7 @@ SWIGINTERN PyObject *_wrap_security_descriptor_dacl_add(PyObject *SWIGUNUSEDPARM char * kwnames[] = { (char *) "self",(char *) "ace", NULL }; + NTSTATUS result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:security_descriptor_dacl_add",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_security_descriptor, 0 | 0 ); @@ -3174,8 +3181,7 @@ SWIGINTERN PyObject *_wrap_security_descriptor_dacl_add(PyObject *SWIGUNUSEDPARM arg2 = (struct security_ace *)(argp2); result = security_descriptor_dacl_add(arg1,(struct security_ace const *)arg2); if (NT_STATUS_IS_ERR(result)) { - PyObject *obj = Py_BuildValue((char *)"(i,s)", NT_STATUS_V(result), nt_errstr(result)); - PyErr_SetObject(PyExc_RuntimeError, obj); + PyErr_SetNTSTATUS(result); SWIG_fail; } else if (resultobj == NULL) { resultobj = Py_None; @@ -3190,7 +3196,6 @@ SWIGINTERN PyObject *_wrap_security_descriptor_dacl_del(PyObject *SWIGUNUSEDPARM PyObject *resultobj = 0; security_descriptor *arg1 = (security_descriptor *) 0 ; struct dom_sid *arg2 = (struct dom_sid *) 0 ; - NTSTATUS result; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -3200,6 +3205,7 @@ SWIGINTERN PyObject *_wrap_security_descriptor_dacl_del(PyObject *SWIGUNUSEDPARM char * kwnames[] = { (char *) "self",(char *) "trustee", NULL }; + NTSTATUS result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:security_descriptor_dacl_del",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_security_descriptor, 0 | 0 ); @@ -3214,8 +3220,7 @@ SWIGINTERN PyObject *_wrap_security_descriptor_dacl_del(PyObject *SWIGUNUSEDPARM arg2 = (struct dom_sid *)(argp2); result = security_descriptor_dacl_del(arg1,(struct dom_sid const *)arg2); if (NT_STATUS_IS_ERR(result)) { - PyObject *obj = Py_BuildValue((char *)"(i,s)", NT_STATUS_V(result), nt_errstr(result)); - PyErr_SetObject(PyExc_RuntimeError, obj); + PyErr_SetNTSTATUS(result); SWIG_fail; } else if (resultobj == NULL) { resultobj = Py_None; @@ -3230,7 +3235,6 @@ SWIGINTERN PyObject *_wrap_security_descriptor_sacl_del(PyObject *SWIGUNUSEDPARM PyObject *resultobj = 0; security_descriptor *arg1 = (security_descriptor *) 0 ; struct dom_sid *arg2 = (struct dom_sid *) 0 ; - NTSTATUS result; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -3240,6 +3244,7 @@ SWIGINTERN PyObject *_wrap_security_descriptor_sacl_del(PyObject *SWIGUNUSEDPARM char * kwnames[] = { (char *) "self",(char *) "trustee", NULL }; + NTSTATUS result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:security_descriptor_sacl_del",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_security_descriptor, 0 | 0 ); @@ -3254,8 +3259,7 @@ SWIGINTERN PyObject *_wrap_security_descriptor_sacl_del(PyObject *SWIGUNUSEDPARM arg2 = (struct dom_sid *)(argp2); result = security_descriptor_sacl_del(arg1,(struct dom_sid const *)arg2); if (NT_STATUS_IS_ERR(result)) { - PyObject *obj = Py_BuildValue((char *)"(i,s)", NT_STATUS_V(result), nt_errstr(result)); - PyErr_SetObject(PyExc_RuntimeError, obj); + PyErr_SetNTSTATUS(result); SWIG_fail; } else if (resultobj == NULL) { resultobj = Py_None; @@ -3270,7 +3274,6 @@ SWIGINTERN PyObject *_wrap_security_descriptor___eq__(PyObject *SWIGUNUSEDPARM(s PyObject *resultobj = 0; security_descriptor *arg1 = (security_descriptor *) 0 ; struct security_descriptor *arg2 = (struct security_descriptor *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -3280,6 +3283,7 @@ SWIGINTERN PyObject *_wrap_security_descriptor___eq__(PyObject *SWIGUNUSEDPARM(s char * kwnames[] = { (char *) "self",(char *) "other", NULL }; + bool result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:security_descriptor___eq__",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_security_descriptor, 0 | 0 ); @@ -3315,7 +3319,6 @@ SWIGINTERN PyObject *_wrap_delete_security_descriptor(PyObject *SWIGUNUSEDPARM(s } arg1 = (security_descriptor *)(argp1); delete_security_descriptor(arg1); - resultobj = SWIG_Py_Void(); return resultobj; fail: @@ -3338,7 +3341,6 @@ SWIGINTERN PyObject *_wrap_new_Sid(PyObject *SWIGUNUSEDPARM(self), PyObject *arg PyObject *resultobj = 0; TALLOC_CTX *arg1 = (TALLOC_CTX *) 0 ; char *arg2 = (char *) 0 ; - dom_sid *result = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; @@ -3346,6 +3348,7 @@ SWIGINTERN PyObject *_wrap_new_Sid(PyObject *SWIGUNUSEDPARM(self), PyObject *arg char * kwnames[] = { (char *) "text", NULL }; + dom_sid *result = 0 ; arg1 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:new_Sid",kwnames,&obj0)) SWIG_fail; @@ -3368,10 +3371,10 @@ SWIGINTERN PyObject *_wrap_Sid___str__(PyObject *SWIGUNUSEDPARM(self), PyObject PyObject *resultobj = 0; dom_sid *arg1 = (dom_sid *) 0 ; TALLOC_CTX *arg2 = (TALLOC_CTX *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + char *result = 0 ; arg2 = NULL; if (!args) SWIG_fail; @@ -3393,7 +3396,6 @@ SWIGINTERN PyObject *_wrap_Sid___eq__(PyObject *SWIGUNUSEDPARM(self), PyObject * PyObject *resultobj = 0; dom_sid *arg1 = (dom_sid *) 0 ; struct dom_sid *arg2 = (struct dom_sid *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -3403,6 +3405,7 @@ SWIGINTERN PyObject *_wrap_Sid___eq__(PyObject *SWIGUNUSEDPARM(self), PyObject * char * kwnames[] = { (char *) "self",(char *) "other", NULL }; + bool result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:Sid___eq__",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_dom_sid, 0 | 0 ); @@ -3438,7 +3441,6 @@ SWIGINTERN PyObject *_wrap_delete_Sid(PyObject *SWIGUNUSEDPARM(self), PyObject * } arg1 = (dom_sid *)(argp1); delete_dom_sid(arg1); - resultobj = SWIG_Py_Void(); return resultobj; fail: @@ -3475,13 +3477,13 @@ fail: SWIGINTERN PyObject *_wrap_privilege_name(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; enum sec_privilege arg1 ; - char *result = 0 ; int val1 ; int ecode1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "privilege", NULL }; + char *result = 0 ; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:privilege_name",kwnames,&obj0)) SWIG_fail; ecode1 = SWIG_AsVal_int(obj0, &val1); @@ -3500,7 +3502,6 @@ fail: SWIGINTERN PyObject *_wrap_privilege_id(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; char *arg1 = (char *) 0 ; - enum sec_privilege result; int res1 ; char *buf1 = 0 ; int alloc1 = 0 ; @@ -3508,6 +3509,7 @@ SWIGINTERN PyObject *_wrap_privilege_id(PyObject *SWIGUNUSEDPARM(self), PyObject char * kwnames[] = { (char *) "name", NULL }; + enum sec_privilege result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:privilege_id",kwnames,&obj0)) SWIG_fail; res1 = SWIG_AsCharPtrAndSize(obj0, &buf1, NULL, &alloc1); diff --git a/source4/libcli/swig/libcli_smb.i b/source4/libcli/swig/libcli_smb.i index 4125bcf5a9..0162b7b66a 100644 --- a/source4/libcli/swig/libcli_smb.i +++ b/source4/libcli/swig/libcli_smb.i @@ -1,6 +1,6 @@ %module libcli_smb -%import "../../lib/talloc/talloc.i" +%import "../../../lib/talloc/talloc.i" %import "../../lib/events/events.i" %{ diff --git a/source4/libcli/swig/libcli_smb.py b/source4/libcli/swig/libcli_smb.py index 6e4fe036c7..4662618fd3 100644 --- a/source4/libcli/swig/libcli_smb.py +++ b/source4/libcli/swig/libcli_smb.py @@ -1,5 +1,5 @@ # This file was automatically generated by SWIG (http://www.swig.org). -# Version 1.3.35 +# Version 1.3.36 # # Don't modify this file, modify the SWIG interface instead. diff --git a/source4/libcli/swig/libcli_smb_wrap.c b/source4/libcli/swig/libcli_smb_wrap.c index a3ea079b83..99bbdc7f96 100644 --- a/source4/libcli/swig/libcli_smb_wrap.c +++ b/source4/libcli/swig/libcli_smb_wrap.c @@ -1,6 +1,6 @@ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). - * Version 1.3.35 + * Version 1.3.36 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make @@ -52,6 +52,12 @@ # endif #endif +#ifndef SWIG_MSC_UNSUPPRESS_4505 +# if defined(_MSC_VER) +# pragma warning(disable : 4505) /* unreferenced local function has been removed */ +# endif +#endif + #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) @@ -2513,7 +2519,7 @@ static swig_module_info swig_module = {swig_types, 6, 0, 0, 0, 0}; #define SWIG_name "_libcli_smb" -#define SWIGVERSION 0x010335 +#define SWIGVERSION 0x010336 #define SWIG_VERSION SWIGVERSION @@ -2603,7 +2609,6 @@ SWIGINTERN PyObject *_wrap_smbcli_sock_connect_byname(PyObject *SWIGUNUSEDPARM(s TALLOC_CTX *arg3 = (TALLOC_CTX *) 0 ; struct resolve_context *arg4 = (struct resolve_context *) 0 ; struct event_context *arg5 = (struct event_context *) 0 ; - struct smbcli_socket *result = 0 ; int res1 ; char *buf1 = 0 ; int alloc1 = 0 ; @@ -2620,8 +2625,9 @@ SWIGINTERN PyObject *_wrap_smbcli_sock_connect_byname(PyObject *SWIGUNUSEDPARM(s char * kwnames[] = { (char *) "host",(char *) "ports",(char *) "resolve_ctx",(char *) "event_ctx", NULL }; + struct smbcli_socket *result = 0 ; - arg5 = s4_event_context_init(NULL); + arg5 = event_context_init(NULL); arg3 = NULL; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO|O:smbcli_sock_connect_byname",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail; res1 = SWIG_AsCharPtrAndSize(obj0, &buf1, NULL, &alloc1); diff --git a/source4/param/param.py b/source4/param/param.py index 46c75cef97..4117db6f28 100644 --- a/source4/param/param.py +++ b/source4/param/param.py @@ -1,5 +1,5 @@ # This file was automatically generated by SWIG (http://www.swig.org). -# Version 1.3.35 +# Version 1.3.36 # # Don't modify this file, modify the SWIG interface instead. diff --git a/source4/param/param_wrap.c b/source4/param/param_wrap.c index 48fd752f0e..eef7a06605 100644 --- a/source4/param/param_wrap.c +++ b/source4/param/param_wrap.c @@ -1,6 +1,6 @@ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). - * Version 1.3.35 + * Version 1.3.36 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make @@ -52,6 +52,12 @@ # endif #endif +#ifndef SWIG_MSC_UNSUPPRESS_4505 +# if defined(_MSC_VER) +# pragma warning(disable : 4505) /* unreferenced local function has been removed */ +# endif +#endif + #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) @@ -2479,7 +2485,7 @@ SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) #define SWIGTYPE_p_int swig_types[2] #define SWIGTYPE_p_loadparm_context swig_types[3] #define SWIGTYPE_p_loadparm_service swig_types[4] -#define SWIGTYPE_p_long swig_types[5] +#define SWIGTYPE_p_long_long swig_types[5] #define SWIGTYPE_p_param_context swig_types[6] #define SWIGTYPE_p_param_opt swig_types[7] #define SWIGTYPE_p_param_section swig_types[8] @@ -2487,7 +2493,7 @@ SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) #define SWIGTYPE_p_signed_char swig_types[10] #define SWIGTYPE_p_unsigned_char swig_types[11] #define SWIGTYPE_p_unsigned_int swig_types[12] -#define SWIGTYPE_p_unsigned_long swig_types[13] +#define SWIGTYPE_p_unsigned_long_long swig_types[13] #define SWIGTYPE_p_unsigned_short swig_types[14] static swig_type_info *swig_types[16]; static swig_module_info swig_module = {swig_types, 15, 0, 0, 0, 0}; @@ -2522,7 +2528,7 @@ static swig_module_info swig_module = {swig_types, 15, 0, 0, 0, 0}; #define SWIG_name "_param" -#define SWIGVERSION 0x010335 +#define SWIGVERSION 0x010336 #define SWIG_VERSION SWIGVERSION @@ -2830,13 +2836,13 @@ fail: SWIGINTERN PyObject *_wrap_LoadParm_default_service(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; loadparm_context *arg1 = (loadparm_context *) 0 ; - struct loadparm_service *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + struct loadparm_service *result = 0 ; arg1 = loadparm_init(NULL); if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:LoadParm_default_service",kwnames,&obj0)) SWIG_fail; @@ -2859,7 +2865,6 @@ SWIGINTERN PyObject *_wrap_LoadParm_load(PyObject *SWIGUNUSEDPARM(self), PyObjec PyObject *resultobj = 0; loadparm_context *arg1 = (loadparm_context *) 0 ; char *arg2 = (char *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -2870,6 +2875,7 @@ SWIGINTERN PyObject *_wrap_LoadParm_load(PyObject *SWIGUNUSEDPARM(self), PyObjec char * kwnames[] = { (char *) "self",(char *) "filename", NULL }; + bool result; arg1 = loadparm_init(NULL); if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OO:LoadParm_load",kwnames,&obj0,&obj1)) SWIG_fail; @@ -2900,13 +2906,13 @@ fail: SWIGINTERN PyObject *_wrap_LoadParm_load_default(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; loadparm_context *arg1 = (loadparm_context *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + bool result; arg1 = loadparm_init(NULL); if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:LoadParm_load_default",kwnames,&obj0)) SWIG_fail; @@ -2928,13 +2934,13 @@ fail: SWIGINTERN PyObject *_wrap_LoadParm___len__(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; loadparm_context *arg1 = (loadparm_context *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + int result; arg1 = loadparm_init(NULL); if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:LoadParm___len__",kwnames,&obj0)) SWIG_fail; @@ -2957,7 +2963,6 @@ SWIGINTERN PyObject *_wrap_LoadParm___getitem__(PyObject *SWIGUNUSEDPARM(self), PyObject *resultobj = 0; loadparm_context *arg1 = (loadparm_context *) 0 ; char *arg2 = (char *) 0 ; - struct loadparm_service *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -2968,6 +2973,7 @@ SWIGINTERN PyObject *_wrap_LoadParm___getitem__(PyObject *SWIGUNUSEDPARM(self), char * kwnames[] = { (char *) "self",(char *) "name", NULL }; + struct loadparm_service *result = 0 ; arg1 = loadparm_init(NULL); if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OO:LoadParm___getitem__",kwnames,&obj0,&obj1)) SWIG_fail; @@ -2998,13 +3004,13 @@ fail: SWIGINTERN PyObject *_wrap_LoadParm_configfile(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; loadparm_context *arg1 = (loadparm_context *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "self", NULL }; + char *result = 0 ; arg1 = loadparm_init(NULL); if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:LoadParm_configfile",kwnames,&obj0)) SWIG_fail; @@ -3027,7 +3033,6 @@ SWIGINTERN PyObject *_wrap_LoadParm_is_mydomain(PyObject *SWIGUNUSEDPARM(self), PyObject *resultobj = 0; loadparm_context *arg1 = (loadparm_context *) 0 ; char *arg2 = (char *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3038,6 +3043,7 @@ SWIGINTERN PyObject *_wrap_LoadParm_is_mydomain(PyObject *SWIGUNUSEDPARM(self), char * kwnames[] = { (char *) "self",(char *) "domain", NULL }; + bool result; arg1 = loadparm_init(NULL); if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OO:LoadParm_is_mydomain",kwnames,&obj0,&obj1)) SWIG_fail; @@ -3069,7 +3075,6 @@ SWIGINTERN PyObject *_wrap_LoadParm_is_myname(PyObject *SWIGUNUSEDPARM(self), Py PyObject *resultobj = 0; loadparm_context *arg1 = (loadparm_context *) 0 ; char *arg2 = (char *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3080,6 +3085,7 @@ SWIGINTERN PyObject *_wrap_LoadParm_is_myname(PyObject *SWIGUNUSEDPARM(self), Py char * kwnames[] = { (char *) "self",(char *) "name", NULL }; + bool result; arg1 = loadparm_init(NULL); if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OO:LoadParm_is_myname",kwnames,&obj0,&obj1)) SWIG_fail; @@ -3111,7 +3117,6 @@ SWIGINTERN PyObject *_wrap_LoadParm_use(PyObject *SWIGUNUSEDPARM(self), PyObject PyObject *resultobj = 0; loadparm_context *arg1 = (loadparm_context *) 0 ; struct param_context *arg2 = (struct param_context *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -3121,6 +3126,7 @@ SWIGINTERN PyObject *_wrap_LoadParm_use(PyObject *SWIGUNUSEDPARM(self), PyObject char * kwnames[] = { (char *) "self",(char *) "param_ctx", NULL }; + int result; arg1 = loadparm_init(NULL); if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OO:LoadParm_use",kwnames,&obj0,&obj1)) SWIG_fail; @@ -3151,7 +3157,6 @@ SWIGINTERN PyObject *_wrap_LoadParm_set(PyObject *SWIGUNUSEDPARM(self), PyObject loadparm_context *arg1 = (loadparm_context *) 0 ; char *arg2 = (char *) 0 ; char *arg3 = (char *) 0 ; - bool result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3166,6 +3171,7 @@ SWIGINTERN PyObject *_wrap_LoadParm_set(PyObject *SWIGUNUSEDPARM(self), PyObject char * kwnames[] = { (char *) "self",(char *) "parm_name",(char *) "parm_value", NULL }; + bool result; arg1 = loadparm_init(NULL); if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OOO:LoadParm_set",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; @@ -3207,7 +3213,6 @@ SWIGINTERN PyObject *_wrap_LoadParm_get(PyObject *SWIGUNUSEDPARM(self), PyObject loadparm_context *arg1 = (loadparm_context *) 0 ; char *arg2 = (char *) 0 ; char *arg3 = (char *) 0 ; - PyObject *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3222,6 +3227,7 @@ SWIGINTERN PyObject *_wrap_LoadParm_get(PyObject *SWIGUNUSEDPARM(self), PyObject char * kwnames[] = { (char *) "self",(char *) "param_name",(char *) "service_name", NULL }; + PyObject *result = 0 ; arg1 = loadparm_init(NULL); if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OOO:LoadParm_get",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; @@ -3278,7 +3284,6 @@ SWIGINTERN PyObject *_wrap_delete_LoadParm(PyObject *SWIGUNUSEDPARM(self), PyObj arg1 = (loadparm_context *)(argp1); } delete_loadparm_context(arg1); - resultobj = SWIG_Py_Void(); return resultobj; fail: @@ -3301,7 +3306,6 @@ SWIGINTERN PyObject *_wrap_loadparm_service_volume_label(PyObject *SWIGUNUSEDPAR PyObject *resultobj = 0; loadparm_service *arg1 = (loadparm_service *) 0 ; struct loadparm_service *arg2 = (struct loadparm_service *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -3311,6 +3315,7 @@ SWIGINTERN PyObject *_wrap_loadparm_service_volume_label(PyObject *SWIGUNUSEDPAR char * kwnames[] = { (char *) "self",(char *) "sDefault", NULL }; + char *result = 0 ; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:loadparm_service_volume_label",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_loadparm_service, 0 | 0 ); @@ -3335,7 +3340,6 @@ SWIGINTERN PyObject *_wrap_loadparm_service_printername(PyObject *SWIGUNUSEDPARM PyObject *resultobj = 0; loadparm_service *arg1 = (loadparm_service *) 0 ; struct loadparm_service *arg2 = (struct loadparm_service *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -3345,6 +3349,7 @@ SWIGINTERN PyObject *_wrap_loadparm_service_printername(PyObject *SWIGUNUSEDPARM char * kwnames[] = { (char *) "self",(char *) "sDefault", NULL }; + char *result = 0 ; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:loadparm_service_printername",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_loadparm_service, 0 | 0 ); @@ -3369,7 +3374,6 @@ SWIGINTERN PyObject *_wrap_loadparm_service_maxprintjobs(PyObject *SWIGUNUSEDPAR PyObject *resultobj = 0; loadparm_service *arg1 = (loadparm_service *) 0 ; struct loadparm_service *arg2 = (struct loadparm_service *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -3379,6 +3383,7 @@ SWIGINTERN PyObject *_wrap_loadparm_service_maxprintjobs(PyObject *SWIGUNUSEDPAR char * kwnames[] = { (char *) "self",(char *) "sDefault", NULL }; + int result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:loadparm_service_maxprintjobs",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_loadparm_service, 0 | 0 ); @@ -3425,7 +3430,6 @@ SWIGINTERN PyObject *_wrap_ParamFile_get_section(PyObject *SWIGUNUSEDPARM(self), PyObject *resultobj = 0; param *arg1 = (param *) 0 ; char *arg2 = (char *) 0 ; - struct param_section *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3436,6 +3440,7 @@ SWIGINTERN PyObject *_wrap_ParamFile_get_section(PyObject *SWIGUNUSEDPARM(self), char * kwnames[] = { (char *) "self",(char *) "name", NULL }; + struct param_section *result = 0 ; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:ParamFile_get_section",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_param_context, 0 | 0 ); @@ -3462,7 +3467,6 @@ SWIGINTERN PyObject *_wrap_ParamFile_add_section(PyObject *SWIGUNUSEDPARM(self), PyObject *resultobj = 0; param *arg1 = (param *) 0 ; char *arg2 = (char *) 0 ; - struct param_section *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3473,6 +3477,7 @@ SWIGINTERN PyObject *_wrap_ParamFile_add_section(PyObject *SWIGUNUSEDPARM(self), char * kwnames[] = { (char *) "self",(char *) "name", NULL }; + struct param_section *result = 0 ; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:ParamFile_add_section",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_param_context, 0 | 0 ); @@ -3500,7 +3505,6 @@ SWIGINTERN PyObject *_wrap_ParamFile_get(PyObject *SWIGUNUSEDPARM(self), PyObjec param *arg1 = (param *) 0 ; char *arg2 = (char *) 0 ; char *arg3 = (char *) "global" ; - struct param_opt *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3515,6 +3519,7 @@ SWIGINTERN PyObject *_wrap_ParamFile_get(PyObject *SWIGUNUSEDPARM(self), PyObjec char * kwnames[] = { (char *) "self",(char *) "name",(char *) "section_name", NULL }; + struct param_opt *result = 0 ; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO|O:ParamFile_get",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_param_context, 0 | 0 ); @@ -3551,7 +3556,6 @@ SWIGINTERN PyObject *_wrap_ParamFile_get_string(PyObject *SWIGUNUSEDPARM(self), param *arg1 = (param *) 0 ; char *arg2 = (char *) 0 ; char *arg3 = (char *) "global" ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3566,6 +3570,7 @@ SWIGINTERN PyObject *_wrap_ParamFile_get_string(PyObject *SWIGUNUSEDPARM(self), char * kwnames[] = { (char *) "self",(char *) "name",(char *) "section_name", NULL }; + char *result = 0 ; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO|O:ParamFile_get_string",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_param_context, 0 | 0 ); @@ -3603,7 +3608,6 @@ SWIGINTERN PyObject *_wrap_ParamFile_set_string(PyObject *SWIGUNUSEDPARM(self), char *arg2 = (char *) 0 ; char *arg3 = (char *) 0 ; char *arg4 = (char *) "global" ; - int result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3622,6 +3626,7 @@ SWIGINTERN PyObject *_wrap_ParamFile_set_string(PyObject *SWIGUNUSEDPARM(self), char * kwnames[] = { (char *) "self",(char *) "param",(char *) "value",(char *) "section", NULL }; + int result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO|O:ParamFile_set_string",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_param_context, 0 | 0 ); @@ -3666,7 +3671,6 @@ SWIGINTERN PyObject *_wrap_ParamFile_set(PyObject *SWIGUNUSEDPARM(self), PyObjec char *arg2 = (char *) 0 ; PyObject *arg3 = (PyObject *) 0 ; char *arg4 = (char *) "global" ; - int result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3682,6 +3686,7 @@ SWIGINTERN PyObject *_wrap_ParamFile_set(PyObject *SWIGUNUSEDPARM(self), PyObjec char * kwnames[] = { (char *) "self",(char *) "parameter",(char *) "ob",(char *) "section_name", NULL }; + int result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO|O:ParamFile_set",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_param_context, 0 | 0 ); @@ -3717,10 +3722,10 @@ fail: SWIGINTERN PyObject *_wrap_ParamFile_first_section(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; param *arg1 = (param *) 0 ; - struct param_section *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + struct param_section *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3741,7 +3746,6 @@ SWIGINTERN PyObject *_wrap_ParamFile_next_section(PyObject *SWIGUNUSEDPARM(self) PyObject *resultobj = 0; param *arg1 = (param *) 0 ; struct param_section *arg2 = (struct param_section *) 0 ; - struct param_section *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -3751,6 +3755,7 @@ SWIGINTERN PyObject *_wrap_ParamFile_next_section(PyObject *SWIGUNUSEDPARM(self) char * kwnames[] = { (char *) "self",(char *) "s", NULL }; + struct param_section *result = 0 ; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:ParamFile_next_section",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_param_context, 0 | 0 ); @@ -3775,7 +3780,6 @@ SWIGINTERN PyObject *_wrap_ParamFile_read(PyObject *SWIGUNUSEDPARM(self), PyObje PyObject *resultobj = 0; param *arg1 = (param *) 0 ; char *arg2 = (char *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3786,6 +3790,7 @@ SWIGINTERN PyObject *_wrap_ParamFile_read(PyObject *SWIGUNUSEDPARM(self), PyObje char * kwnames[] = { (char *) "self",(char *) "fn", NULL }; + int result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:ParamFile_read",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_param_context, 0 | 0 ); @@ -3812,7 +3817,6 @@ SWIGINTERN PyObject *_wrap_ParamFile_write(PyObject *SWIGUNUSEDPARM(self), PyObj PyObject *resultobj = 0; param *arg1 = (param *) 0 ; char *arg2 = (char *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -3823,6 +3827,7 @@ SWIGINTERN PyObject *_wrap_ParamFile_write(PyObject *SWIGUNUSEDPARM(self), PyObj char * kwnames[] = { (char *) "self",(char *) "fn", NULL }; + int result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:ParamFile_write",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_param_context, 0 | 0 ); @@ -3860,7 +3865,6 @@ SWIGINTERN PyObject *_wrap_delete_ParamFile(PyObject *SWIGUNUSEDPARM(self), PyOb } arg1 = (param *)(argp1); delete_param(arg1); - resultobj = SWIG_Py_Void(); return resultobj; fail: @@ -3882,10 +3886,10 @@ SWIGINTERN PyObject *ParamFile_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject SWIGINTERN PyObject *_wrap_param_opt_key_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; param_opt *arg1 = (param_opt *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + char *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3905,10 +3909,10 @@ fail: SWIGINTERN PyObject *_wrap_param_opt_value_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; param_opt *arg1 = (param_opt *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + char *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3928,10 +3932,10 @@ fail: SWIGINTERN PyObject *_wrap_param_opt___str__(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; param_opt *arg1 = (param_opt *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + char *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3963,7 +3967,6 @@ SWIGINTERN PyObject *_wrap_delete_param_opt(PyObject *SWIGUNUSEDPARM(self), PyOb } arg1 = (param_opt *)(argp1); delete_param_opt(arg1); - resultobj = SWIG_Py_Void(); return resultobj; fail: @@ -3981,10 +3984,10 @@ SWIGINTERN PyObject *param_opt_swigregister(PyObject *SWIGUNUSEDPARM(self), PyOb SWIGINTERN PyObject *_wrap_param_section_name_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; param_section *arg1 = (param_section *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + char *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; @@ -4005,7 +4008,6 @@ SWIGINTERN PyObject *_wrap_param_section_get(PyObject *SWIGUNUSEDPARM(self), PyO PyObject *resultobj = 0; param_section *arg1 = (param_section *) 0 ; char *arg2 = (char *) 0 ; - struct param_opt *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; @@ -4016,6 +4018,7 @@ SWIGINTERN PyObject *_wrap_param_section_get(PyObject *SWIGUNUSEDPARM(self), PyO char * kwnames[] = { (char *) "self",(char *) "name", NULL }; + struct param_opt *result = 0 ; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:param_section_get",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_param_section, 0 | 0 ); @@ -4041,10 +4044,10 @@ fail: SWIGINTERN PyObject *_wrap_param_section_first_parameter(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; param_section *arg1 = (param_section *) 0 ; - struct param_opt *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + struct param_opt *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; @@ -4065,7 +4068,6 @@ SWIGINTERN PyObject *_wrap_param_section_next_parameter(PyObject *SWIGUNUSEDPARM PyObject *resultobj = 0; param_section *arg1 = (param_section *) 0 ; struct param_opt *arg2 = (struct param_opt *) 0 ; - struct param_opt *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -4075,6 +4077,7 @@ SWIGINTERN PyObject *_wrap_param_section_next_parameter(PyObject *SWIGUNUSEDPARM char * kwnames[] = { (char *) "self",(char *) "s", NULL }; + struct param_opt *result = 0 ; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:param_section_next_parameter",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_param_section, 0 | 0 ); @@ -4123,7 +4126,6 @@ SWIGINTERN PyObject *_wrap_delete_param_section(PyObject *SWIGUNUSEDPARM(self), } arg1 = (param_section *)(argp1); free((char *) arg1); - resultobj = SWIG_Py_Void(); return resultobj; fail: @@ -4250,18 +4252,18 @@ static PyMethodDef SwigMethods[] = { static swig_type_info _swigt__p_TALLOC_CTX = {"_p_TALLOC_CTX", "TALLOC_CTX *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; -static swig_type_info _swigt__p_int = {"_p_int", "int *|int_least32_t *|int32_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_int = {"_p_int", "intptr_t *|int *|int_least32_t *|int_fast32_t *|int32_t *|int_fast16_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_loadparm_context = {"_p_loadparm_context", "struct loadparm_context *|loadparm_context *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_loadparm_service = {"_p_loadparm_service", "struct loadparm_service *|loadparm_service *", 0, 0, (void*)0, 0}; -static swig_type_info _swigt__p_long = {"_p_long", "intptr_t *|int_least64_t *|int_fast32_t *|int_fast64_t *|int64_t *|long *|int_fast16_t *|intmax_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_long_long = {"_p_long_long", "int_least64_t *|int_fast64_t *|int64_t *|long long *|intmax_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_param_context = {"_p_param_context", "struct param_context *|param *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_param_opt = {"_p_param_opt", "struct param_opt *|param_opt *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_param_section = {"_p_param_section", "struct param_section *|param_section *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_short = {"_p_short", "short *|int_least16_t *|int16_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_signed_char = {"_p_signed_char", "signed char *|int_least8_t *|int_fast8_t *|int8_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_unsigned_char = {"_p_unsigned_char", "unsigned char *|uint_least8_t *|uint_fast8_t *|uint8_t *", 0, 0, (void*)0, 0}; -static swig_type_info _swigt__p_unsigned_int = {"_p_unsigned_int", "uint_least32_t *|uint32_t *|unsigned int *", 0, 0, (void*)0, 0}; -static swig_type_info _swigt__p_unsigned_long = {"_p_unsigned_long", "uintptr_t *|uint_least64_t *|uint_fast32_t *|uint_fast64_t *|uint64_t *|unsigned long *|uint_fast16_t *|uintmax_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_unsigned_int = {"_p_unsigned_int", "uintptr_t *|uint_least32_t *|uint_fast32_t *|uint32_t *|unsigned int *|uint_fast16_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_unsigned_long_long = {"_p_unsigned_long_long", "uint_least64_t *|uint_fast64_t *|uint64_t *|unsigned long long *|uintmax_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_unsigned_short = {"_p_unsigned_short", "unsigned short *|uint_least16_t *|uint16_t *", 0, 0, (void*)0, 0}; static swig_type_info *swig_type_initial[] = { @@ -4270,7 +4272,7 @@ static swig_type_info *swig_type_initial[] = { &_swigt__p_int, &_swigt__p_loadparm_context, &_swigt__p_loadparm_service, - &_swigt__p_long, + &_swigt__p_long_long, &_swigt__p_param_context, &_swigt__p_param_opt, &_swigt__p_param_section, @@ -4278,7 +4280,7 @@ static swig_type_info *swig_type_initial[] = { &_swigt__p_signed_char, &_swigt__p_unsigned_char, &_swigt__p_unsigned_int, - &_swigt__p_unsigned_long, + &_swigt__p_unsigned_long_long, &_swigt__p_unsigned_short, }; @@ -4287,7 +4289,7 @@ static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, static swig_cast_info _swigc__p_int[] = { {&_swigt__p_int, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_loadparm_context[] = { {&_swigt__p_loadparm_context, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_loadparm_service[] = { {&_swigt__p_loadparm_service, 0, 0, 0},{0, 0, 0, 0}}; -static swig_cast_info _swigc__p_long[] = { {&_swigt__p_long, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_long_long[] = { {&_swigt__p_long_long, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_param_context[] = { {&_swigt__p_param_context, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_param_opt[] = { {&_swigt__p_param_opt, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_param_section[] = { {&_swigt__p_param_section, 0, 0, 0},{0, 0, 0, 0}}; @@ -4295,7 +4297,7 @@ static swig_cast_info _swigc__p_short[] = { {&_swigt__p_short, 0, 0, 0},{0, 0, static swig_cast_info _swigc__p_signed_char[] = { {&_swigt__p_signed_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_char[] = { {&_swigt__p_unsigned_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_int[] = { {&_swigt__p_unsigned_int, 0, 0, 0},{0, 0, 0, 0}}; -static swig_cast_info _swigc__p_unsigned_long[] = { {&_swigt__p_unsigned_long, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_unsigned_long_long[] = { {&_swigt__p_unsigned_long_long, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_short[] = { {&_swigt__p_unsigned_short, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { @@ -4304,7 +4306,7 @@ static swig_cast_info *swig_cast_initial[] = { _swigc__p_int, _swigc__p_loadparm_context, _swigc__p_loadparm_service, - _swigc__p_long, + _swigc__p_long_long, _swigc__p_param_context, _swigc__p_param_opt, _swigc__p_param_section, @@ -4312,7 +4314,7 @@ static swig_cast_info *swig_cast_initial[] = { _swigc__p_signed_char, _swigc__p_unsigned_char, _swigc__p_unsigned_int, - _swigc__p_unsigned_long, + _swigc__p_unsigned_long_long, _swigc__p_unsigned_short, }; diff --git a/source4/scripting/python/config.m4 b/source4/scripting/python/config.m4 index aaf32c5e4e..843c3f7873 100644 --- a/source4/scripting/python/config.m4 +++ b/source4/scripting/python/config.m4 @@ -5,7 +5,7 @@ AC_ARG_VAR([PYTHON_VERSION],[The installed Python will be appended to the Python interpreter canonical name.]) -AC_PROG_SWIG(1.3.35) +AC_PROG_SWIG(1.3.36) AC_PATH_PROG([PYTHON],[python[$PYTHON_VERSION]]) if test -z "$PYTHON"; then diff --git a/source4/scripting/python/misc.i b/source4/scripting/python/misc.i index 81be7d5c16..f40e88c6cd 100644 --- a/source4/scripting/python/misc.i +++ b/source4/scripting/python/misc.i @@ -31,7 +31,7 @@ %import "stdint.i" %include "exception.i" -%import "../../lib/talloc/talloc.i" +%import "../../../lib/talloc/talloc.i" %import "../../lib/ldb/ldb.i" %import "../../auth/credentials/credentials.i" %import "../../param/param.i" -- cgit From ba5fe7122586d8b382bf78f1e1cb5dbe4293c27b Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 19 Sep 2008 00:05:34 +0200 Subject: Add test for Sid.__repr__. --- source4/libcli/security/tests/bindings.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source4/libcli/security/tests/bindings.py b/source4/libcli/security/tests/bindings.py index 82ce7aeba8..b539de833d 100644 --- a/source4/libcli/security/tests/bindings.py +++ b/source4/libcli/security/tests/bindings.py @@ -65,6 +65,10 @@ class DomSidTests(unittest.TestCase): sid = security.random_sid() self.assertTrue(str(sid).startswith("S-1-5-21-")) + def test_repr(self): + sid = security.random_sid() + self.assertTrue(repr(sid).startswith("Sid('S-1-5-21-")) + class PrivilegeTests(unittest.TestCase): def test_privilege_name(self): -- cgit From 714669f17239230e325cb90ce57ce34f75f9461f Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 19 Sep 2008 01:43:04 +0200 Subject: Fix objectclass tests. --- source4/dsdb/samdb/ldb_modules/tests/samba3sam.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py index 1b51636c28..14ebc986c7 100644 --- a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py +++ b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py @@ -133,13 +133,12 @@ class Samba3SamTestCase(MapBaseTestCase): msg = self.ldb.search(expression="(cn=Replicator)") self.assertEquals(len(msg), 1) self.assertEquals(str(msg[0].dn), "cn=Replicator,ou=Groups,dc=vernstok,dc=nl") - self.assertEquals(msg[0]["objectSid"], - "S-1-5-21-4231626423-2410014848-2360679739-552") + self.assertTrue("objectSid" in msg[0]) + # self.assertEquals(msg[0]["objectSid"], "S-1-5-21-4231626423-2410014848-2360679739-552") # Check mapping of objectClass oc = set(msg[0]["objectClass"]) self.assertTrue(oc is not None) - for i in oc: - self.assertEquals(oc[i] == "posixGroup" or oc[i], "group") + self.assertEquals(oc, set(["group"])) def test_search_by_objclass(self): """Looking up by objectClass""" -- cgit From 495758a73e125e59921092c893c6e32ba7091fe1 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 19 Sep 2008 02:27:40 +0200 Subject: Fix COM compilation, add framework for COM python module. --- source4/lib/com/com.h | 2 ++ source4/lib/com/config.mk | 9 +++++- source4/lib/com/main.c | 22 +-------------- source4/lib/com/pycom.c | 70 +++++++++++++++++++++++++++++++++++++++++++++++ source4/lib/com/rot.c | 1 + 5 files changed, 82 insertions(+), 22 deletions(-) create mode 100644 source4/lib/com/pycom.c diff --git a/source4/lib/com/com.h b/source4/lib/com/com.h index 2074bd11ca..5d594ad41b 100644 --- a/source4/lib/com/com.h +++ b/source4/lib/com/com.h @@ -47,4 +47,6 @@ WERROR com_create_object(struct com_context *ctx, struct GUID *clsid, int num_if WERROR com_get_class_object(struct com_context *ctx, struct GUID *clsid, struct GUID *iid, struct IUnknown **ip); NTSTATUS com_init(void); +typedef struct IUnknown *(*get_class_object_function) (const struct GUID *clsid); + #endif /* __SAMBA_COM_H__ */ diff --git a/source4/lib/com/config.mk b/source4/lib/com/config.mk index 5c8e98dc46..c5c5a35003 100644 --- a/source4/lib/com/config.mk +++ b/source4/lib/com/config.mk @@ -1,9 +1,10 @@ [SUBSYSTEM::COM] +PRIVATE_DEPENDENCIES = LIBSAMBA-UTIL LIBSAMBA-HOSTCONFIG LIBEVENTS LIBNDR COM_OBJ_FILES = $(addprefix lib/com/, tables.o rot.o main.o) [SUBSYSTEM::DCOM] -PUBLIC_DEPENDENCIES = com DCOM_PROXY_DCOM RPC_NDR_REMACT \ +PUBLIC_DEPENDENCIES = COM DCOM_PROXY_DCOM RPC_NDR_REMACT \ RPC_NDR_OXIDRESOLVER DCOM_OBJ_FILES = $(addprefix lib/com/dcom/, main.o tables.o) @@ -13,3 +14,9 @@ SUBSYSTEM = COM INIT_FUNCTION = com_simple_init com_simple_OBJ_FILES = lib/com/classes/simple.o + +[PYTHON::pycom] +LIBRARY_REALNAME = samba/com.$(SHLIBEXT) +PRIVATE_DEPENDENCIES = COM + +pycom_OBJ_FILES = lib/com/pycom.o diff --git a/source4/lib/com/main.c b/source4/lib/com/main.c index 882b479cfe..bcc5fa393a 100644 --- a/source4/lib/com/main.c +++ b/source4/lib/com/main.c @@ -42,7 +42,7 @@ WERROR com_create_object(struct com_context *ctx, struct GUID *clsid, int num_if int i; struct GUID classfact_iid; - GUID_from_string(DCERPC_ICLASSFACTORY_UUID, &classfact_iid); + GUID_from_string(NDR_ICLASSFACTORY_UUID, &classfact_iid); /* Obtain class object */ error = com_get_class_object(ctx, clsid, &classfact_iid, (struct IUnknown **)&factory); @@ -88,23 +88,3 @@ WERROR com_get_class_object(struct com_context *ctx, struct GUID *clsid, struct return IUnknown_QueryInterface(iu, ctx, iid, ip); } - -NTSTATUS com_init(void) -{ - static BOOL initialized = False; - - init_module_fn static_init[] = STATIC_com_MODULES; - init_module_fn *shared_init; - - if (initialized) return NT_STATUS_OK; - initialized = True; - - shared_init = load_samba_modules(NULL, "com"); - - run_init_functions(static_init); - run_init_functions(shared_init); - - talloc_free(shared_init); - - return NT_STATUS_OK; -} diff --git a/source4/lib/com/pycom.c b/source4/lib/com/pycom.c new file mode 100644 index 0000000000..b6d6b772a8 --- /dev/null +++ b/source4/lib/com/pycom.c @@ -0,0 +1,70 @@ +/* + Unix SMB/CIFS implementation. + Python bindings for COM library. + Copyright (C) Jelmer Vernooij 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 . +*/ + +#include "includes.h" +#include +#include "lib/com/com.h" + +static PyObject *py_get_class_object(PyObject *self, PyObject *args) +{ + char *s_clsid, *s_iid; + struct GUID clsid, iid; + struct IUnknown *object; + + if (!PyArg_ParseTuple(args, "ss", &s_clsid, &s_iid)) + return NULL; + + status = GUID_from_string(s_clsid, &clsid); + if (!NT_STATUS_IS_OK(status)) { + PyErr_FromNTSTATUS(status); + return NULL; + } + + status = GUID_from_string(s_iid, &iid); + if (!NT_STATUS_IS_OK(status)) { + PyErr_FromNTSTATUS(status); + return NULL; + } + + error = com_get_class_object(ctx, &clsid, &iid, &object); + if (!W_ERROR_IS_OK(error)) { + PyErr_FromWERROR(error); + return NULL; + } + + /* FIXME: Magic, integrate with stubs generated by pidl. */ + + return Py_None; +} + +static struct PyMethodDef com_methods[] = { + { "get_class_object", (PyCFunction)py_get_class_object, METH_VARARGS, "S.get_class_object(clsid, iid) -> instance" }, + { NULL }, +}; + +void initcom(void) +{ + PyObject *m; + + /* FIXME: Initialize COM context and attach it to m. */ + + m = Py_InitModule3("com", com_methods, "Simple COM implementation"); + if (m == NULL) + return; +} diff --git a/source4/lib/com/rot.c b/source4/lib/com/rot.c index 34a5671f5b..0180a92f1b 100644 --- a/source4/lib/com/rot.c +++ b/source4/lib/com/rot.c @@ -21,6 +21,7 @@ */ #include "includes.h" +#include "lib/com/com.h" struct dcom_interface_p *dcom_get_local_iface_p(struct GUID *ipid) { -- cgit From b5e8d8d22ae599778e889a8df5a18c07c9180af5 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 19 Sep 2008 02:39:03 +0200 Subject: initialize a COM context. --- source4/lib/com/pycom.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/source4/lib/com/pycom.c b/source4/lib/com/pycom.c index b6d6b772a8..9222be438d 100644 --- a/source4/lib/com/pycom.c +++ b/source4/lib/com/pycom.c @@ -20,12 +20,18 @@ #include "includes.h" #include #include "lib/com/com.h" +#include "librpc/ndr/libndr.h" +#include "libcli/util/pyerrors.h" + +static struct com_context *py_com_ctx = NULL; /* FIXME: evil global */ static PyObject *py_get_class_object(PyObject *self, PyObject *args) { char *s_clsid, *s_iid; struct GUID clsid, iid; struct IUnknown *object; + NTSTATUS status; + WERROR error; if (!PyArg_ParseTuple(args, "ss", &s_clsid, &s_iid)) return NULL; @@ -42,7 +48,7 @@ static PyObject *py_get_class_object(PyObject *self, PyObject *args) return NULL; } - error = com_get_class_object(ctx, &clsid, &iid, &object); + error = com_get_class_object(py_com_ctx, &clsid, &iid, &object); if (!W_ERROR_IS_OK(error)) { PyErr_FromWERROR(error); return NULL; @@ -61,8 +67,13 @@ static struct PyMethodDef com_methods[] = { void initcom(void) { PyObject *m; + WERROR error; - /* FIXME: Initialize COM context and attach it to m. */ + error = com_init_ctx(&py_com_ctx, NULL); + if (!W_ERROR_IS_OK(error)) { + PyErr_FromWERROR(error); + return; + } m = Py_InitModule3("com", com_methods, "Simple COM implementation"); if (m == NULL) -- cgit From 62b5f1886d06edb94bbb799c07470803cbd9988b Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 19 Sep 2008 10:56:35 +0200 Subject: Make sure modify operations succeed. --- testprogs/ejs/samba3sam.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/testprogs/ejs/samba3sam.js b/testprogs/ejs/samba3sam.js index e5639b8ec8..244074743d 100644 --- a/testprogs/ejs/samba3sam.js +++ b/testprogs/ejs/samba3sam.js @@ -914,6 +914,10 @@ replace: badPwdCount badPwdCount: 4 "; ok = ldb.modify(ldif); + if (ok.error != 0) { + println(ok.errstr); + assert(ok.error == 0); + } /* Check in mapped db */ attrs = new Array("description", "badPwdCount", "nextRid"); res = ldb.search("", dn, ldb.SCOPE_BASE, attrs); @@ -992,6 +996,10 @@ replace: description description: test "; ok = ldb.modify(ldif); + if (ok.error != 0) { + println(ok.errstr); + assert(ok.error == 0); + } /* Check in mapped db */ attrs = new Array("revision", "description"); res = ldb.search("", dn, ldb.SCOPE_BASE, attrs); -- cgit From 87afa77eac72b84bccd292cba53ebec85dfd120c Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 19 Sep 2008 11:04:18 +0200 Subject: find_unused_makefilevars: Support parsing simple includes. --- source4/script/find_unused_makefilevars.pl | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/source4/script/find_unused_makefilevars.pl b/source4/script/find_unused_makefilevars.pl index 1bed1228ec..23fc36ef6a 100755 --- a/source4/script/find_unused_makefilevars.pl +++ b/source4/script/find_unused_makefilevars.pl @@ -13,17 +13,26 @@ my %defines; # First, make a list of defines in configure $in = shift; -open(IN, $in); -while() { - my $line = $_; - while($line =~ /^\b([a-zA-Z0-9_][a-zA-Z0-9_]*)\b[ \t]*=.*/sgm) { - $defines{$1} = 1; - } - while($line =~ /\$\(([a-zA-Z0-9_][a-zA-Z0-9_]*)\)/sgm) { - $references{$1} = 1; +sub process_file($) +{ + my ($fn) = @_; + open(IN, $fn); + while() { + my $line = $_; + while($line =~ /^\b([a-zA-Z0-9_][a-zA-Z0-9_]*)\b[ \t]*=.*/sgm) { + $defines{$1} = 1; + } + while($line =~ /\$\(([a-zA-Z0-9_][a-zA-Z0-9_]*)\)/sgm) { + $references{$1} = 1; + } + while ($line =~ /^include (.*)/sgm) { + process_file($1); + } } + close IN; } -close IN; + +process_file($in); print "##### DEFINED BUT UNUSED: #####\n"; foreach(%defines) { -- cgit From 53be14a19b0cecd5e2269c03ff4cab8f02b109e9 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 19 Sep 2008 11:05:19 +0200 Subject: Remove unused scripts. --- source4/script/installmodules.sh | 33 -------------------------- source4/script/installscripts.sh | 47 -------------------------------------- source4/script/uninstallmodules.sh | 37 ------------------------------ source4/script/uninstallscripts.sh | 36 ----------------------------- 4 files changed, 153 deletions(-) delete mode 100755 source4/script/installmodules.sh delete mode 100755 source4/script/installscripts.sh delete mode 100755 source4/script/uninstallmodules.sh delete mode 100755 source4/script/uninstallscripts.sh diff --git a/source4/script/installmodules.sh b/source4/script/installmodules.sh deleted file mode 100755 index fb0ad90c14..0000000000 --- a/source4/script/installmodules.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/sh - -INSTALLPERMS=$1 -LIBDIR=$2 -shift -shift -shift - -if [ ! -d $LIBDIR ]; then -mkdir $LIBDIR -if [ ! -d $LIBDIR ]; then - echo Failed to make directory $LIBDIR - exit 1 -fi -fi - -for p in $*; do - p2=`basename $p` - echo Installing $p as $LIBDIR/$p2 - cp -f $p $LIBDIR/ - chmod $INSTALLPERMS $LIBDIR/$p2 -done - - -cat << EOF -====================================================================== -The modules are installed. You may uninstall the modules using the -command "make uninstallmodules" or "make uninstall" to uninstall -binaries, man pages, shell scripts and modules. -====================================================================== -EOF - -exit 0 diff --git a/source4/script/installscripts.sh b/source4/script/installscripts.sh deleted file mode 100755 index bff5423e7c..0000000000 --- a/source4/script/installscripts.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/sh -# this script courtesy of James_K._Foote.PARC@xerox.com -# 5 July 96 Dan.Shearer@UniSA.Edu.Au Don't hardcode script names, get from Make - -INSTALLPERMS=$1 -BINDIR=$2 - -shift -shift - -echo Installing scripts in $BINDIR - -for d in $BINDIR; do - if [ ! -d $d ]; then - mkdir $d - if [ ! -d $d ]; then - echo Failed to make directory $d - echo Have you run installbin first? - exit 1 - fi - fi -done - -for p in $*; do - p2=`basename $p` - echo Installing $BINDIR/$p2 - if [ -f $BINDIR/$p2 ]; then - rm -f $BINDIR/$p2.old - mv $BINDIR/$p2 $BINDIR/$p2.old - fi - cp $p $BINDIR/ - chmod $INSTALLPERMS $BINDIR/$p2 - if [ ! -f $BINDIR/$p2 ]; then - echo Cannot copy $p2... does $USER have privileges? - fi -done - -cat << EOF -====================================================================== -The scripts have been installed. You may uninstall them using -the command "make uninstallscripts" or "make install" to install binaries, -man pages and shell scripts. You may recover the previous version (if any -by "make revert". -====================================================================== -EOF - -exit 0 diff --git a/source4/script/uninstallmodules.sh b/source4/script/uninstallmodules.sh deleted file mode 100755 index 30582a39fa..0000000000 --- a/source4/script/uninstallmodules.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/sh -#4 July 96 Dan.Shearer@UniSA.edu.au - -INSTALLPERMS=$1 -BASEDIR=$2 -LIBDIR=$3 -shift -shift -shift - -if [ ! -d $LIBDIR ]; then - echo Directory $LIBDIR does not exist! - echo Do a "make installmodules" or "make install" first. - exit 1 -fi - -for p in $*; do - p2=`basename $p` - if [ -f $LIBDIR/$p2 ]; then - echo Removing $LIBDIR/$p2 - rm -f $LIBDIR/$p2 - if [ -f $LIBDIR/$p2 ]; then - echo Cannot remove $LIBDIR/$p2 ... does $USER have privileges? - fi - fi -done - - -cat << EOF -====================================================================== -The modules have been uninstalled. You may restore the modules using -the command "make installmodules" or "make install" to install -binaries, modules, man pages and shell scripts. -====================================================================== -EOF - -exit 0 diff --git a/source4/script/uninstallscripts.sh b/source4/script/uninstallscripts.sh deleted file mode 100755 index 13104acedd..0000000000 --- a/source4/script/uninstallscripts.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/sh -# 5 July 96 Dan.Shearer@UniSA.Edu.Au - almost identical to uninstallbin.sh - -INSTALLPERMS=$1 -BINDIR=$2 - -shift -shift - -if [ ! -d $BINDIR ]; then - echo Directory $BINDIR does not exist! - echo Do a "make installscripts" or "make install" first. - exit 1 -fi - -for p in $*; do - p2=`basename $p` - if [ -f $BINDIR/$p2 ]; then - echo Removing $BINDIR/$p2 - rm -f $BINDIR/$p2 - if [ -f $BINDIR/$p2 ]; then - echo Cannot remove $BINDIR/$p2 ... does $USER have privileges? - fi - fi -done - -cat << EOF -====================================================================== -The scripts have been uninstalled. You may reinstall them using -the command "make installscripts" or "make install" to install binaries, -man pages and shell scripts. You may recover a previous version (if any -with "make revert". -====================================================================== -EOF - -exit 0 -- cgit From 0c193b7a1041015b1e6254aedff805469ba0eab4 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 19 Sep 2008 12:04:13 +0200 Subject: Simplify code, remove print statements. --- source4/dsdb/samdb/ldb_modules/tests/samba3sam.py | 71 ++++++++++++++--------- 1 file changed, 42 insertions(+), 29 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py index 14ebc986c7..a37cfdcf60 100644 --- a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py +++ b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py @@ -1,7 +1,7 @@ #!/usr/bin/python # Unix SMB/CIFS implementation. -# Copyright (C) Jelmer Vernooij 2005-2007 +# Copyright (C) Jelmer Vernooij 2005-2008 # Copyright (C) Martin Kuehl 2006 # # This is a Python port of the original in testprogs/ejs/samba3sam.js @@ -35,13 +35,10 @@ datadir = os.path.join(os.path.dirname(__file__), "../../../../../testdata/samba def ldb_debug(l, text): print text + class MapBaseTestCase(TestCaseInTempDir): """Base test case for mapping tests.""" - def setup_data(self, obj, ldif): - self.assertTrue(ldif is not None) - obj.db.add_ldif(substitute_var(ldif, obj.substvars)) - def setup_modules(self, ldb, s3, s4): ldb.add({"dn": "@MAP=samba3sam", "@FROM": s4.basedn, @@ -54,6 +51,7 @@ class MapBaseTestCase(TestCaseInTempDir): "partition": [s4.basedn + ":" + s4.url, s3.basedn + ":" + s3.url], "replicateEntries": ["@ATTRIBUTES", "@INDEXLIST"]}) + def setUp(self): super(MapBaseTestCase, self).setUp() @@ -84,6 +82,19 @@ class MapBaseTestCase(TestCaseInTempDir): def connect(self): return self.db.connect(self.url) + def setup_data(self, path): + ldif = open(os.path.join(datadir, path), 'r').read() + self.add_ldif(ldif) + + def subst(self, text): + return substitute_var(text, self.substvars) + + def add_ldif(self, ldif): + self.db.add_ldif(self.subst(ldif)) + + def modify_ldif(self, ldif): + self.db.modify_ldif(self.subst(ldif)) + self.samba4 = Target("samba4.ldb", "dc=vernstok,dc=nl", make_s4dn) self.samba3 = Target("samba3.ldb", "cn=Samba3Sam", make_dn) self.templates = Target("templates.ldb", "cn=templates", None) @@ -104,10 +115,10 @@ class Samba3SamTestCase(MapBaseTestCase): def setUp(self): super(Samba3SamTestCase, self).setUp() ldb = Ldb(self.ldburl) - self.setup_data(self.samba3, open(os.path.join(datadir, "samba3.ldif"), 'r').read()) - self.setup_data(self.templates, open(os.path.join(datadir, "provision_samba3sam_templates.ldif"), 'r').read()) + self.samba3.setup_data("samba3.ldif") + self.templates.setup_data("provision_samba3sam_templates.ldif") ldif = open(os.path.join(datadir, "provision_samba3sam.ldif"), 'r').read() - ldb.add_ldif(substitute_var(ldif, self.samba4.substvars)) + ldb.add_ldif(self.samba4.subst(ldif)) self.setup_modules(ldb, self.samba3, self.samba4) self.ldb = Ldb(self.ldburl) @@ -134,7 +145,9 @@ class Samba3SamTestCase(MapBaseTestCase): self.assertEquals(len(msg), 1) self.assertEquals(str(msg[0].dn), "cn=Replicator,ou=Groups,dc=vernstok,dc=nl") self.assertTrue("objectSid" in msg[0]) - # self.assertEquals(msg[0]["objectSid"], "S-1-5-21-4231626423-2410014848-2360679739-552") + # 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 oc = set(msg[0]["objectClass"]) self.assertTrue(oc is not None) @@ -143,13 +156,11 @@ class Samba3SamTestCase(MapBaseTestCase): def test_search_by_objclass(self): """Looking up by objectClass""" msg = self.ldb.search(expression="(|(objectClass=user)(cn=Administrator))") - self.assertEquals(len(msg), 2) - for i in range(len(msg)): - self.assertTrue((str(msg[i].dn) == "unixName=Administrator,ou=Users,dc=vernstok,dc=nl") or (str(msg[i].dn) == "unixName=nobody,ou=Users,dc=vernstok,dc=nl")) - + self.assertEquals(set([str(m.dn) for m in msg]), + set(["unixName=Administrator,ou=Users,dc=vernstok,dc=nl", "unixName=nobody,ou=Users,dc=vernstok,dc=nl"])) def test_s3sam_modify(self): - print "Adding a record that will be fallbacked" + # Adding a record that will be fallbacked self.ldb.add({"dn": "cn=Foo", "foo": "bar", "blah": "Blie", @@ -157,7 +168,7 @@ class Samba3SamTestCase(MapBaseTestCase): "showInAdvancedViewOnly": "TRUE"} ) - print "Checking for existence of record (local)" + # Checking for existence of record (local) # TODO: This record must be searched in the local database, which is currently only supported for base searches # msg = ldb.search(expression="(cn=Foo)", ['foo','blah','cn','showInAdvancedViewOnly')] # TODO: Actually, this version should work as well but doesn't... @@ -270,22 +281,23 @@ class MapTestCase(MapBaseTestCase): def setUp(self): super(MapTestCase, self).setUp() ldb = Ldb(self.ldburl) - self.setup_data(self.templates, open(os.path.join(datadir, "provision_samba3sam_templates.ldif"), 'r').read()) + self.samba3.setup_data("samba3.ldif") + self.templates.setup_data("provision_samba3sam_templates.ldif") ldif = open(os.path.join(datadir, "provision_samba3sam.ldif"), 'r').read() - ldb.add_ldif(substitute_var(ldif, self.samba4.substvars)) + ldb.add_ldif(self.samba4.subst(ldif)) self.setup_modules(ldb, self.samba3, self.samba4) self.ldb = Ldb(self.ldburl) def test_map_search(self): """Running search tests on mapped data.""" ldif = """ -dn: """ + "sambaDomainName=TESTS,""" + self.samba3.basedn + """ +dn: sambaDomainName=TESTS,""" + self.samba3.basedn + """ objectclass: sambaDomain objectclass: top sambaSID: S-1-5-21-4231626423-2410014848-2360679739 sambaNextRid: 2000 sambaDomainName: TESTS""" - self.samba3.db.add_ldif(substitute_var(ldif, self.samba3.substvars)) + self.samba3.add_ldif(ldif) # Add a set of split records ldif = """ @@ -302,7 +314,7 @@ objectSid: S-1-5-21-4231626423-2410014848-2360679739-552 primaryGroupID: 1-5-21-4231626423-2410014848-2360679739-512 """ - self.ldb.add_ldif(substitute_var(ldif, self.samba4.substvars)) + self.ldb.add_ldif(self.samba4.subst(ldif)) ldif = """ dn: """ + self.samba4.dn("cn=Y") + """ @@ -315,7 +327,7 @@ nextRid: y lastLogon: y description: x """ - self.ldb.add_ldif(substitute_var(ldif, self.samba4.substvars)) + self.ldb.add_ldif(self.samba4.subst(ldif)) ldif = """ dn: """ + self.samba4.dn("cn=Z") + """ @@ -329,7 +341,7 @@ lastLogon: z description: y """ - self.ldb.add_ldif(substitute_var(ldif, self.samba4.substvars)) + self.ldb.add_ldif(self.samba4.subst(ldif)) # Add a set of remote records @@ -360,7 +372,7 @@ sambaBadPasswordCount: y sambaLogonTime: z description: y """ - self.samba3.add_ldif(substitute_var(ldif, self.samba3.substvars)) + self.samba3.add_ldif(ldif) # Testing search by DN @@ -502,8 +514,7 @@ description: y self.assertTrue(not "dnsHostName" in res[0]) self.assertEquals(res[0]["lastLogon"], "y") self.assertTrue(res[0]["objectClass"] is not None) - for oc in set(res[0]["objectClass"]): - self.assertEquals(oc, "user") + self.assertEquals(set(res[0]["objectClass"]), set(["user"])) self.assertEquals(str(res[1].dn), self.samba4.dn("cn=X")) self.assertEquals(res[1]["dnsHostName"], "x") self.assertEquals(res[1]["lastLogon"], "x") @@ -515,7 +526,7 @@ description: y self.assertTrue(res[2]["objectClass"] is not None) self.assertEquals(res[2]["objectClass"][0], "user") - print "Testing search by parse tree" + # Testing search by parse tree # Search by conjunction of local attributes res = self.ldb.search(expression="(&(codePage=x)(revision=x))", attrs=["dnsHostName", "lastLogon"]) @@ -710,7 +721,7 @@ description: y self.assertTrue(not "dnsHostName" in res[2]) self.assertEquals(res[2]["lastLogon"], "z") - print "Search by complex parse tree" + # Search by complex parse tree res = self.ldb.search(expression="(|(&(revision=x)(dnsHostName=x))(!(&(description=x)(nextRid=y)))(badPwdCount=y))", attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 6) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) @@ -752,10 +763,12 @@ description: y self.assertEquals(res[0]["revision"], "1") self.assertEquals(res[0]["description"], "test") # Check it's not in the local db - res = self.samba4.db.search(expression="(cn=test)", scope=SCOPE_DEFAULT, attrs=attrs) + res = self.samba4.db.search(expression="(cn=test)", + scope=SCOPE_DEFAULT, attrs=attrs) self.assertEquals(len(res), 0) # Check it's not in the remote db - res = self.samba3.db.search(expression="(cn=test)", scope=SCOPE_DEFAULT, attrs=attrs) + res = self.samba3.db.search(expression="(cn=test)", + scope=SCOPE_DEFAULT, attrs=attrs) self.assertEquals(len(res), 0) # Modify local record -- cgit From c7d069a4833548e249a74837d6fce02dd09f473c Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 19 Sep 2008 12:07:03 +0200 Subject: Fix path to ndrdump in blackbox test, don't start smb server for ndrdump tests. --- source4/librpc/tests/test_ndrdump.sh | 4 ++-- source4/selftest/samba4_tests.sh | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/source4/librpc/tests/test_ndrdump.sh b/source4/librpc/tests/test_ndrdump.sh index dddfc0eae1..511856061c 100755 --- a/source4/librpc/tests/test_ndrdump.sh +++ b/source4/librpc/tests/test_ndrdump.sh @@ -8,9 +8,9 @@ failed=0 -samba4bindir=`dirname $0`/../../source4/bin +samba4bindir=`dirname $0`/../../bin ndrdump=$samba4bindir/ndrdump -files=`dirname $0`/ndrdump +files=`dirname $0`/ testit "ndrdump with in" $VALGRIND $ndrdump samr samr_CreateUser in $files/samr-CreateUser-in.dat $@ || failed=`expr $failed + 1` testit "ndrdump with out" $VALGRIND $ndrdump samr samr_CreateUser out $files/samr-CreateUser-out.dat $@ || failed=`expr $failed + 1` diff --git a/source4/selftest/samba4_tests.sh b/source4/selftest/samba4_tests.sh index 3c2bb134b0..a72024e9e1 100755 --- a/source4/selftest/samba4_tests.sh +++ b/source4/selftest/samba4_tests.sh @@ -269,7 +269,7 @@ fi bbdir=$incdir/../../testprogs/blackbox -plantest "blackbox.ndrdump" dc $samba4srcdir/librpc/tests/test_ndrdump.sh +plantest "blackbox.ndrdump" none $samba4srcdir/librpc/tests/test_ndrdump.sh plantest "blackbox.net" dc $samba4srcdir/utils/tests/test_net.sh "\$SERVER" "\$USERNAME" "\$PASSWORD" "\$DOMAIN" plantest "blackbox.kinit" dc $bbdir/test_kinit.sh "\$SERVER" "\$USERNAME" "\$PASSWORD" "\$REALM" "\$DOMAIN" "$PREFIX" $CONFIGURATION plantest "blackbox.cifsdd" dc $samba4srcdir/client/tests/test_cifsdd.sh "\$SERVER" "\$USERNAME" "\$PASSWORD" "\$DOMAIN" -- cgit From 3fbcc2149e6d6acee30be32f3bb1ff82155f76a1 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 19 Sep 2008 12:44:00 +0200 Subject: Fix formatting. --- source4/dsdb/samdb/ldb_modules/tests/samba3sam.py | 98 +++++++++++++++-------- 1 file changed, 63 insertions(+), 35 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py index a37cfdcf60..e85a730ded 100644 --- a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py +++ b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py @@ -51,7 +51,6 @@ class MapBaseTestCase(TestCaseInTempDir): "partition": [s4.basedn + ":" + s4.url, s3.basedn + ":" + s3.url], "replicateEntries": ["@ATTRIBUTES", "@INDEXLIST"]}) - def setUp(self): super(MapBaseTestCase, self).setUp() @@ -67,7 +66,8 @@ class MapBaseTestCase(TestCaseInTempDir): tempdir = self.tempdir class Target: - """Simple helper class that contains data for a specific SAM connection.""" + """Simple helper class that contains data for a specific SAM + connection.""" def __init__(self, file, basedn, dn): self.file = os.path.join(tempdir, file) self.url = "tdb://" + self.file @@ -143,7 +143,8 @@ class Samba3SamTestCase(MapBaseTestCase): """Looking up mapped entry containing SID""" msg = self.ldb.search(expression="(cn=Replicator)") self.assertEquals(len(msg), 1) - self.assertEquals(str(msg[0].dn), "cn=Replicator,ou=Groups,dc=vernstok,dc=nl") + 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"], @@ -157,7 +158,8 @@ class Samba3SamTestCase(MapBaseTestCase): """Looking up by objectClass""" msg = self.ldb.search(expression="(|(objectClass=user)(cn=Administrator))") self.assertEquals(set([str(m.dn) for m in msg]), - set(["unixName=Administrator,ou=Users,dc=vernstok,dc=nl", "unixName=nobody,ou=Users,dc=vernstok,dc=nl"])) + set(["unixName=Administrator,ou=Users,dc=vernstok,dc=nl", + "unixName=nobody,ou=Users,dc=vernstok,dc=nl"])) def test_s3sam_modify(self): # Adding a record that will be fallbacked @@ -169,7 +171,8 @@ class Samba3SamTestCase(MapBaseTestCase): ) # Checking for existence of record (local) - # TODO: This record must be searched in the local database, which is currently only supported for base searches + # TODO: This record must be searched in the local database, which is + # currently only supported for base searches # msg = ldb.search(expression="(cn=Foo)", ['foo','blah','cn','showInAdvancedViewOnly')] # TODO: Actually, this version should work as well but doesn't... # @@ -266,7 +269,8 @@ delete: description # Checking whether DN has changed... msg = self.ldb.search(expression="(cn=Niemand2)") self.assertEquals(len(msg), 1) - self.assertEquals(str(msg[0].dn), "cn=Niemand2,cn=Users,dc=vernstok,dc=nl") + self.assertEquals(str(msg[0].dn), + "cn=Niemand2,cn=Users,dc=vernstok,dc=nl") # Deleting record... self.ldb.delete("cn=Niemand2,cn=Users,dc=vernstok,dc=nl") @@ -276,12 +280,10 @@ delete: description self.assertEquals(len(msg), 0) - class MapTestCase(MapBaseTestCase): def setUp(self): super(MapTestCase, self).setUp() ldb = Ldb(self.ldburl) - self.samba3.setup_data("samba3.ldif") self.templates.setup_data("provision_samba3sam_templates.ldif") ldif = open(os.path.join(datadir, "provision_samba3sam.ldif"), 'r').read() ldb.add_ldif(self.samba4.subst(ldif)) @@ -439,7 +441,8 @@ description: y self.assertEquals(res[1]["lastLogon"], "z") # Search by renamed attribute - res = self.ldb.search(expression="(badPwdCount=x)", scope=SCOPE_DEFAULT, attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(badPwdCount=x)", scope=SCOPE_DEFAULT, + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) @@ -453,21 +456,25 @@ description: y # Using the SID directly in the parse tree leads to conversion # errors, letting the search fail with no results. #res = self.ldb.search("(objectSid=S-1-5-21-4231626423-2410014848-2360679739-552)", scope=SCOPE_DEFAULT, attrs) - res = self.ldb.search(expression="(objectSid=*)", attrs=["dnsHostName", "lastLogon", "objectSid"]) + res = self.ldb.search(expression="(objectSid=*)", + attrs=["dnsHostName", "lastLogon", "objectSid"]) self.assertEquals(len(res), 3) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=X")) self.assertEquals(res[0]["dnsHostName"], "x") self.assertEquals(res[0]["lastLogon"], "x") - self.assertEquals(res[0]["objectSid"], "S-1-5-21-4231626423-2410014848-2360679739-552") + self.assertEquals(res[0]["objectSid"], + "S-1-5-21-4231626423-2410014848-2360679739-552") self.assertEquals(str(res[1].dn), self.samba4.dn("cn=A")) self.assertTrue(not "dnsHostName" in res[1]) self.assertEquals(res[1]["lastLogon"], "x") - self.assertEquals(res[1]["objectSid"], "S-1-5-21-4231626423-2410014848-2360679739-552") + self.assertEquals(res[1]["objectSid"], + "S-1-5-21-4231626423-2410014848-2360679739-552") # Search by generated attribute # In most cases, this even works when the mapping is missing # a `convert_operator' by enumerating the remote db. - res = self.ldb.search(expression="(primaryGroupID=512)", attrs=["dnsHostName", "lastLogon", "primaryGroupID"]) + res = self.ldb.search(expression="(primaryGroupID=512)", + attrs=["dnsHostName", "lastLogon", "primaryGroupID"]) self.assertEquals(len(res), 1) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=A")) self.assertTrue(not "dnsHostName" in res[0]) @@ -489,7 +496,8 @@ description: y # # Search by remote name of renamed attribute */ - res = self.ldb.search(expression="(sambaBadPasswordCount=*)", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(sambaBadPasswordCount=*)", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 0) # Search by objectClass @@ -508,7 +516,8 @@ description: y self.assertEquals(res[1]["objectClass"][0], "user") # Prove that the objectClass is actually used for the search - res = self.ldb.search(expression="(|(objectClass=user)(badPwdCount=x))", attrs=attrs) + res = self.ldb.search(expression="(|(objectClass=user)(badPwdCount=x))", + attrs=attrs) self.assertEquals(len(res), 3) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) @@ -529,7 +538,8 @@ description: y # Testing search by parse tree # Search by conjunction of local attributes - res = self.ldb.search(expression="(&(codePage=x)(revision=x))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(&(codePage=x)(revision=x))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") @@ -539,7 +549,8 @@ description: y self.assertEquals(res[1]["lastLogon"], "x") # Search by conjunction of remote attributes - res = self.ldb.search(expression="(&(lastLogon=x)(description=x))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(&(lastLogon=x)(description=x))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=X")) self.assertEquals(res[0]["dnsHostName"], "x") @@ -549,7 +560,8 @@ description: y self.assertEquals(res[1]["lastLogon"], "x") # Search by conjunction of local and remote attribute - res = self.ldb.search(expression="(&(codePage=x)(description=x))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(&(codePage=x)(description=x))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") @@ -560,13 +572,16 @@ description: y # Search by conjunction of local and remote attribute w/o match attrs = ["dnsHostName", "lastLogon"] - res = self.ldb.search(expression="(&(codePage=x)(nextRid=x))", attrs=attrs) + res = self.ldb.search(expression="(&(codePage=x)(nextRid=x))", + attrs=attrs) self.assertEquals(len(res), 0) - res = self.ldb.search(expression="(&(revision=x)(lastLogon=z))", attrs=attrs) + res = self.ldb.search(expression="(&(revision=x)(lastLogon=z))", + attrs=attrs) self.assertEquals(len(res), 0) # Search by disjunction of local attributes - res = self.ldb.search(expression="(|(revision=x)(dnsHostName=x))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(|(revision=x)(dnsHostName=x))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") @@ -576,7 +591,8 @@ description: y self.assertEquals(res[1]["lastLogon"], "x") # Search by disjunction of remote attributes - res = self.ldb.search(expression="(|(badPwdCount=x)(lastLogon=x))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(|(badPwdCount=x)(lastLogon=x))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 3) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue("dnsHostName" in res[0]) @@ -589,7 +605,8 @@ description: y self.assertEquals(res[2]["lastLogon"], "x") # Search by disjunction of local and remote attribute - res = self.ldb.search(expression="(|(revision=x)(lastLogon=y))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(|(revision=x)(lastLogon=y))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 3) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") @@ -602,11 +619,13 @@ description: y self.assertEquals(res[2]["lastLogon"], "x") # Search by disjunction of local and remote attribute w/o match - res = self.ldb.search(expression="(|(codePage=y)(nextRid=z))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(|(codePage=y)(nextRid=z))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 0) # Search by negated local attribute - res = self.ldb.search(expression="(!(revision=x))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(!(revision=x))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 5) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) @@ -622,7 +641,8 @@ description: y self.assertEquals(res[3]["lastLogon"], "z") # Search by negated remote attribute - res = self.ldb.search(expression="(!(description=x))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(!(description=x))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 3) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Z")) self.assertEquals(res[0]["dnsHostName"], "z") @@ -632,7 +652,8 @@ description: y self.assertEquals(res[1]["lastLogon"], "z") # Search by negated conjunction of local attributes - res = self.ldb.search(expression="(!(&(codePage=x)(revision=x)))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(!(&(codePage=x)(revision=x)))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 5) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) @@ -648,7 +669,8 @@ description: y self.assertEquals(res[3]["lastLogon"], "z") # Search by negated conjunction of remote attributes - res = self.ldb.search(expression="(!(&(lastLogon=x)(description=x)))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(!(&(lastLogon=x)(description=x)))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 5) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") @@ -664,7 +686,8 @@ description: y self.assertEquals(res[3]["lastLogon"], "z") # Search by negated conjunction of local and remote attribute - res = self.ldb.search(expression="(!(&(codePage=x)(description=x)))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(!(&(codePage=x)(description=x)))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 5) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) @@ -680,7 +703,8 @@ description: y self.assertEquals(res[3]["lastLogon"], "z") # Search by negated disjunction of local attributes - res = self.ldb.search(expression="(!(|(revision=x)(dnsHostName=x)))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(!(|(revision=x)(dnsHostName=x)))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) self.assertEquals(res[0]["lastLogon"], "y") @@ -695,7 +719,8 @@ description: y self.assertEquals(res[3]["lastLogon"], "z") # Search by negated disjunction of remote attributes - res = self.ldb.search(expression="(!(|(badPwdCount=x)(lastLogon=x)))", attrs=["dnsHostName", "lastLogon"]) + res = self.ldb.search(expression="(!(|(badPwdCount=x)(lastLogon=x)))", + attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 4) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") @@ -966,7 +991,8 @@ description: test self.assertTrue(not "nextRid" in res[0]) self.assertEquals(res[0]["revision"], "1") # Check in remote db - attrs = ["description", "sambaBadPasswordCount", "sambaNextRid", "revision"] + attrs = ["description", "sambaBadPasswordCount", "sambaNextRid", + "revision"] res = self.samba3.db.search(dn2, scope=SCOPE_BASE, attrs=attrs) self.assertEquals(len(res), 1) self.assertEquals(str(res[0].dn), dn2) @@ -1004,7 +1030,8 @@ revision: 2 self.assertTrue(not "nextRid" in res[0]) self.assertEquals(res[0]["revision"], "2") # Check in remote db - attrs = ["description", "sambaBadPasswordCount", "sambaNextRid", "revision"] + attrs = ["description", "sambaBadPasswordCount", "sambaNextRid", + "revision"] res = self.samba3.db.search(dn2, scope=SCOPE_BASE, attrs=attrs) self.assertEquals(len(res), 1) self.assertEquals(str(res[0].dn), dn2) @@ -1036,8 +1063,9 @@ revision: 2 self.assertEquals(res[0]["revision"], "2") # Check in remote db dn2 = self.samba3.dn("cn=toast") - attrs = ["description", "sambaBadPasswordCount", "sambaNextRid", "revision"] - res = self.samba3.db.search(dn2, scope=SCOPE_BASE, attrs=attrs) + res = self.samba3.db.search(dn2, scope=SCOPE_BASE, + attrs=["description", "sambaBadPasswordCount", "sambaNextRid", + "revision"] self.assertEquals(len(res), 1) self.assertEquals(str(res[0].dn), dn2) self.assertEquals(res[0]["description"], "test") -- cgit From 186d2d83cbfea5c54bf787299f7bb0a90953af63 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 19 Sep 2008 12:47:52 +0200 Subject: Provide tdb.open and ldb.open python functions. --- lib/tdb/tdb.i | 5 +++++ lib/tdb/tdb.py | 5 ++++- lib/tdb/tdb_wrap.c | 59 +++++++++++++++++++++++++++----------------------- source4/lib/ldb/ldb.i | 1 + source4/lib/ldb/ldb.py | 1 + 5 files changed, 43 insertions(+), 28 deletions(-) diff --git a/lib/tdb/tdb.i b/lib/tdb/tdb.i index 3d8b697732..4b529913d7 100644 --- a/lib/tdb/tdb.i +++ b/lib/tdb/tdb.i @@ -321,3 +321,8 @@ typedef struct tdb_context { # TODO: any other missing methods for container types } } tdb; + +%pythoncode { +__docformat__ = 'restructuredText' +open = Tdb +} diff --git a/lib/tdb/tdb.py b/lib/tdb/tdb.py index 9f306bab8c..42129d2091 100644 --- a/lib/tdb/tdb.py +++ b/lib/tdb/tdb.py @@ -1,5 +1,5 @@ # This file was automatically generated by SWIG (http://www.swig.org). -# Version 1.3.35 +# Version 1.3.36 # # Don't modify this file, modify the SWIG interface instead. @@ -337,5 +337,8 @@ Tdb.name = new_instancemethod(_tdb.Tdb_name,None,Tdb) Tdb_swigregister = _tdb.Tdb_swigregister Tdb_swigregister(Tdb) +__docformat__ = 'restructuredText' +open = Tdb + diff --git a/lib/tdb/tdb_wrap.c b/lib/tdb/tdb_wrap.c index 32665d79fd..e997e88572 100644 --- a/lib/tdb/tdb_wrap.c +++ b/lib/tdb/tdb_wrap.c @@ -1,6 +1,6 @@ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). - * Version 1.3.35 + * Version 1.3.36 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make @@ -52,6 +52,12 @@ # endif #endif +#ifndef SWIG_MSC_UNSUPPRESS_4505 +# if defined(_MSC_VER) +# pragma warning(disable : 4505) /* unreferenced local function has been removed */ +# endif +#endif + #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) @@ -2518,7 +2524,7 @@ static swig_module_info swig_module = {swig_types, 11, 0, 0, 0, 0}; #define SWIG_name "_tdb" -#define SWIGVERSION 0x010335 +#define SWIGVERSION 0x010336 #define SWIG_VERSION SWIGVERSION @@ -2818,7 +2824,6 @@ SWIGINTERN PyObject *_wrap_new_Tdb(PyObject *SWIGUNUSEDPARM(self), PyObject *arg int arg3 ; int arg4 ; mode_t arg5 ; - tdb *result = 0 ; int res1 ; char *buf1 = 0 ; int alloc1 = 0 ; @@ -2838,6 +2843,7 @@ SWIGINTERN PyObject *_wrap_new_Tdb(PyObject *SWIGUNUSEDPARM(self), PyObject *arg char * kwnames[] = { (char *) "name",(char *) "hash_size",(char *) "tdb_flags",(char *) "flags",(char *) "mode", NULL }; + tdb *result = 0 ; arg2 = 0; arg3 = TDB_DEFAULT; @@ -2895,10 +2901,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_error(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - enum TDB_ERROR result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + enum TDB_ERROR result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -2930,7 +2936,6 @@ SWIGINTERN PyObject *_wrap_delete_Tdb(PyObject *SWIGUNUSEDPARM(self), PyObject * } arg1 = (tdb *)(argp1); delete_tdb(arg1); - resultobj = SWIG_Py_Void(); return resultobj; fail: @@ -2941,10 +2946,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_close(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -2966,7 +2971,6 @@ SWIGINTERN PyObject *_wrap_Tdb_append(PyObject *SWIGUNUSEDPARM(self), PyObject * tdb *arg1 = (tdb *) 0 ; TDB_DATA arg2 ; TDB_DATA arg3 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; @@ -2975,6 +2979,7 @@ SWIGINTERN PyObject *_wrap_Tdb_append(PyObject *SWIGUNUSEDPARM(self), PyObject * char * kwnames[] = { (char *) "self",(char *) "key",(char *) "new_dbuf", NULL }; + int result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:Tdb_append",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tdb_context, 0 | 0 ); @@ -3013,10 +3018,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_errorstr(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + char *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3037,7 +3042,6 @@ SWIGINTERN PyObject *_wrap_Tdb_get(PyObject *SWIGUNUSEDPARM(self), PyObject *arg PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; TDB_DATA arg2 ; - TDB_DATA result; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; @@ -3045,6 +3049,7 @@ SWIGINTERN PyObject *_wrap_Tdb_get(PyObject *SWIGUNUSEDPARM(self), PyObject *arg char * kwnames[] = { (char *) "self",(char *) "key", NULL }; + TDB_DATA result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:Tdb_get",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tdb_context, 0 | 0 ); @@ -3079,7 +3084,6 @@ SWIGINTERN PyObject *_wrap_Tdb_delete(PyObject *SWIGUNUSEDPARM(self), PyObject * PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; TDB_DATA arg2 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; @@ -3087,6 +3091,7 @@ SWIGINTERN PyObject *_wrap_Tdb_delete(PyObject *SWIGUNUSEDPARM(self), PyObject * char * kwnames[] = { (char *) "self",(char *) "key", NULL }; + int result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:Tdb_delete",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tdb_context, 0 | 0 ); @@ -3118,7 +3123,6 @@ SWIGINTERN PyObject *_wrap_Tdb_store(PyObject *SWIGUNUSEDPARM(self), PyObject *a TDB_DATA arg2 ; TDB_DATA arg3 ; int arg4 ; - int result; void *argp1 = 0 ; int res1 = 0 ; int val4 ; @@ -3130,6 +3134,7 @@ SWIGINTERN PyObject *_wrap_Tdb_store(PyObject *SWIGUNUSEDPARM(self), PyObject *a char * kwnames[] = { (char *) "self",(char *) "key",(char *) "dbuf",(char *) "flag", NULL }; + int result; arg4 = TDB_REPLACE; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO|O:Tdb_store",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail; @@ -3177,7 +3182,6 @@ SWIGINTERN PyObject *_wrap_Tdb_exists(PyObject *SWIGUNUSEDPARM(self), PyObject * PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; TDB_DATA arg2 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; @@ -3185,6 +3189,7 @@ SWIGINTERN PyObject *_wrap_Tdb_exists(PyObject *SWIGUNUSEDPARM(self), PyObject * char * kwnames[] = { (char *) "self",(char *) "key", NULL }; + int result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:Tdb_exists",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tdb_context, 0 | 0 ); @@ -3213,10 +3218,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_firstkey(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - TDB_DATA result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + TDB_DATA result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3242,7 +3247,6 @@ SWIGINTERN PyObject *_wrap_Tdb_nextkey(PyObject *SWIGUNUSEDPARM(self), PyObject PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; TDB_DATA arg2 ; - TDB_DATA result; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; @@ -3250,6 +3254,7 @@ SWIGINTERN PyObject *_wrap_Tdb_nextkey(PyObject *SWIGUNUSEDPARM(self), PyObject char * kwnames[] = { (char *) "self",(char *) "key", NULL }; + TDB_DATA result; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:Tdb_nextkey",kwnames,&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tdb_context, 0 | 0 ); @@ -3283,10 +3288,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_lock_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3306,10 +3311,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_unlock_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3329,10 +3334,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_read_lock_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3352,10 +3357,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_read_unlock_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3375,10 +3380,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_reopen(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3398,10 +3403,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_transaction_start(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3421,10 +3426,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_transaction_commit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3444,10 +3449,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_transaction_cancel(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3467,10 +3472,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_transaction_recover(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3490,10 +3495,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_hash_size(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3513,10 +3518,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_map_size(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - size_t result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + size_t result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3536,10 +3541,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_get_flags(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - int result; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + int result; if (!args) SWIG_fail; swig_obj[0] = args; @@ -3592,10 +3597,10 @@ fail: SWIGINTERN PyObject *_wrap_Tdb_name(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tdb *arg1 = (tdb *) 0 ; - char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; + char *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; diff --git a/source4/lib/ldb/ldb.i b/source4/lib/ldb/ldb.i index 4b61ddba5b..89676d4f01 100644 --- a/source4/lib/ldb/ldb.i +++ b/source4/lib/ldb/ldb.i @@ -928,4 +928,5 @@ ldb_int_error ldb_register_module(const struct ldb_module_ops *); %pythoncode { __docformat__ = "restructuredText" +open = Ldb } diff --git a/source4/lib/ldb/ldb.py b/source4/lib/ldb/ldb.py index 5826c6b752..9885765e2d 100644 --- a/source4/lib/ldb/ldb.py +++ b/source4/lib/ldb/ldb.py @@ -472,6 +472,7 @@ def register_module(*args, **kwargs): """ return _ldb.register_module(*args, **kwargs) __docformat__ = "restructuredText" +open = Ldb -- cgit From 9e8881414bc055a8f25763362d1cd695c74db0d9 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 19 Sep 2008 13:00:11 +0200 Subject: Fix dependencies for nbt python module. --- source4/librpc/config.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/librpc/config.mk b/source4/librpc/config.mk index 8b1cec46b3..05848bc3a4 100644 --- a/source4/librpc/config.mk +++ b/source4/librpc/config.mk @@ -682,7 +682,7 @@ python_atsvc_OBJ_FILES = $(gen_ndrsrcdir)/py_atsvc.o [PYTHON::python_dcerpc_nbt] LIBRARY_REALNAME = samba/nbt.$(SHLIBEXT) -PRIVATE_DEPENDENCIES = NDR_NBT PYTALLOC param swig_credentials python_dcerpc +PRIVATE_DEPENDENCIES = NDR_NBT PYTALLOC param swig_credentials python_dcerpc python_dcerpc_misc python_dcerpc_security python_dcerpc_nbt_OBJ_FILES = $(gen_ndrsrcdir)/py_nbt.o -- cgit From acae07bc17d3e8dbafa5667711d25616f99a91a9 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 19 Sep 2008 16:17:52 +0200 Subject: Add support for implementing LDB modules in Python. --- source4/lib/ldb/include/ldb_private.h | 1 + source4/lib/ldb/ldb.i | 358 ++++++++++++- source4/lib/ldb/ldb.py | 30 ++ source4/lib/ldb/ldb_wrap.c | 940 +++++++++++++++++++++++++++++++++- source4/lib/ldb/tests/python/api.py | 31 +- 5 files changed, 1327 insertions(+), 33 deletions(-) diff --git a/source4/lib/ldb/include/ldb_private.h b/source4/lib/ldb/include/ldb_private.h index e1026ab781..30adadcfdc 100644 --- a/source4/lib/ldb/include/ldb_private.h +++ b/source4/lib/ldb/include/ldb_private.h @@ -70,6 +70,7 @@ struct ldb_module_ops { 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; }; diff --git a/source4/lib/ldb/ldb.i b/source4/lib/ldb/ldb.i index 89676d4f01..8cd39b5690 100644 --- a/source4/lib/ldb/ldb.i +++ b/source4/lib/ldb/ldb.i @@ -46,6 +46,7 @@ typedef struct ldb_context ldb; typedef struct ldb_dn ldb_dn; typedef struct ldb_ldif ldb_ldif; typedef struct ldb_message_element ldb_message_element; +typedef struct ldb_module ldb_module; typedef int ldb_error; typedef int ldb_int_error; @@ -189,7 +190,7 @@ PyObject *ldb_val_to_py_object(struct ldb_context *ldb_ctx, #endif -%types(struct ldb_result *); +%types(struct ldb_result *, struct ldb_parse_tree *); /* * Wrap struct ldb_dn @@ -685,6 +686,20 @@ PyObject *PyExc_LdbError; /* Top-level ldb operations */ typedef struct ldb_context { + %rename(firstmodule) modules; + struct ldb_module *modules; + + %pythoncode { + def itermodules(self): + m = self.firstmodule + while m is not None: + yield m + m = m.next + + def modules(self): + return list(self.itermodules()) + } + %extend { ldb(void) { return ldb_init(NULL, event_context_init(NULL)); @@ -915,10 +930,349 @@ static char *timestring(time_t t) "Parse a LDAP time string into a UNIX timestamp."; time_t ldb_string_to_time(const char *s); +typedef struct ldb_module { + struct ldb_module *prev, *next; + + %extend { +#ifdef SWIGPYTHON + const char *__str__() { + return $self->ops->name; + } + char *__repr__() { + char *ret; + asprintf(&ret, "", $self->ops->name); + return ret; + } +#endif + int search(struct ldb_request *req) { + return $self->ops->search($self, req); + } + ldb_error add(struct ldb_request *req) { + return $self->ops->add($self, req); + } + ldb_error modify(struct ldb_request *req) { + return $self->ops->modify($self, req); + } + ldb_error delete(struct ldb_request *req) { + return $self->ops->del($self, req); + } + ldb_error rename(struct ldb_request *req) { + return $self->ops->rename($self, req); + } + ldb_error start_transaction() { + return $self->ops->start_transaction($self); + } + ldb_error end_transaction() { + return $self->ops->end_transaction($self); + } + ldb_error del_transaction() { + return $self->ops->del_transaction($self); + } + } +} ldb_module; + +%{ +int py_module_search(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result, *py_base, *py_attrs, *py_tree; + + py_base = SWIG_NewPointerObj(req->op.search.base, SWIGTYPE_p_ldb_dn, 0); + + if (py_base == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + py_tree = SWIG_NewPointerObj(req->op.search.tree, SWIGTYPE_p_ldb_parse_tree, 0); + + if (py_tree == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + if (req->op.search.attrs == NULL) { + py_attrs = Py_None; + } else { + int i, len; + for (len = 0; req->op.search.attrs[len]; len++); + py_attrs = PyList_New(len); + for (i = 0; i < len; i++) + PyList_SetItem(py_attrs, i, PyString_FromString(req->op.search.attrs[i])); + } + + py_result = PyObject_CallMethod(py_ldb, "search", "OiOO", py_base, req->op.search.scope, py_tree, py_attrs); + + Py_DECREF(py_attrs); + Py_DECREF(py_tree); + Py_DECREF(py_base); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + if (SWIG_ConvertPtr(py_result, &req->op.search.res, SWIGTYPE_p_ldb_result, 0) != 0) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_add(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result, *py_msg; + + py_msg = SWIG_NewPointerObj(req->op.add.message, SWIGTYPE_p_ldb_message, 0); + + if (py_msg == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + py_result = PyObject_CallMethod(py_ldb, "add", "O", py_msg); + + Py_DECREF(py_msg); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_modify(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result, *py_msg; + + py_msg = SWIG_NewPointerObj(req->op.mod.message, SWIGTYPE_p_ldb_message, 0); + + if (py_msg == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + py_result = PyObject_CallMethod(py_ldb, "modify", "O", py_msg); + + Py_DECREF(py_msg); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_del(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result, *py_dn; + + py_dn = SWIG_NewPointerObj(req->op.del.dn, SWIGTYPE_p_ldb_dn, 0); + + if (py_dn == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + py_result = PyObject_CallMethod(py_ldb, "delete", "O", py_dn); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_rename(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result, *py_olddn, *py_newdn; + + py_olddn = SWIG_NewPointerObj(req->op.rename.olddn, SWIGTYPE_p_ldb_dn, 0); + + if (py_olddn == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + py_newdn = SWIG_NewPointerObj(req->op.rename.newdn, SWIGTYPE_p_ldb_dn, 0); + + if (py_newdn == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + py_result = PyObject_CallMethod(py_ldb, "rename", "OO", py_olddn, py_newdn); + + Py_DECREF(py_olddn); + Py_DECREF(py_newdn); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_request(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result; + + py_result = PyObject_CallMethod(py_ldb, "request", ""); + + return LDB_ERR_OPERATIONS_ERROR; +} + +int py_module_extended(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result; + + py_result = PyObject_CallMethod(py_ldb, "extended", ""); + + return LDB_ERR_OPERATIONS_ERROR; +} + +int py_module_start_transaction(struct ldb_module *mod) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result; + + py_result = PyObject_CallMethod(py_ldb, "start_transaction", ""); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_end_transaction(struct ldb_module *mod) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result; + + py_result = PyObject_CallMethod(py_ldb, "end_transaction", ""); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_del_transaction(struct ldb_module *mod) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result; + + py_result = PyObject_CallMethod(py_ldb, "del_transaction", ""); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + 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; + PyObject *py_result; + int ret; + + py_result = PyObject_CallMethod(py_ldb, "sequence_number", "ili", req->op.seq_num.type, req->op.seq_num.seq_num, req->op.seq_num.flags); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + ret = PyInt_AsLong(py_result); + + Py_DECREF(py_result); + + return ret; +} + +static int py_module_destructor(void *_mod) +{ + struct ldb_module *mod = _mod; + Py_DECREF((PyObject *)mod->private_data); + return 0; +} + +int py_module_init (struct ldb_module *mod) +{ + PyObject *py_class = mod->ops->private_data; + PyObject *py_result, *py_next, *py_ldb; + + py_ldb = SWIG_NewPointerObj(mod->ldb, SWIGTYPE_p_ldb_context, 0); + + if (py_ldb == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + py_next = SWIG_NewPointerObj(mod->next, SWIGTYPE_p_ldb_module, 0); + + if (py_next == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + py_result = PyObject_CallFunction(py_class, "OO", py_ldb, py_next); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + mod->private_data = py_result; + + talloc_set_destructor (mod, py_module_destructor); + + return ldb_next_init(mod); +} +%} + %typemap(in,noblock=1) const struct ldb_module_ops * { $1 = talloc_zero(talloc_autofree_context(), struct ldb_module_ops); - $1->name = (char *)PyObject_GetAttrString($input, (char *)"name"); + $1->name = talloc_strdup($1, PyString_AsString(PyObject_GetAttrString($input, (char *)"name"))); + + Py_INCREF($input); + $1->private_data = $input; + $1->init_context = py_module_init; + $1->search = py_module_search; + $1->add = py_module_add; + $1->modify = py_module_modify; + $1->del = py_module_del; + $1->rename = py_module_rename; + $1->request = py_module_request; + $1->extended = py_module_extended; + $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; } %feature("docstring") ldb_register_module "S.register_module(module) -> None\n" diff --git a/source4/lib/ldb/ldb.py b/source4/lib/ldb/ldb.py index 9885765e2d..4cf36441fd 100644 --- a/source4/lib/ldb/ldb.py +++ b/source4/lib/ldb/ldb.py @@ -281,6 +281,16 @@ LDB_ERR_OTHER = _ldb.LDB_ERR_OTHER class Ldb(object): """Connection to a LDB database.""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + firstmodule = _swig_property(_ldb.Ldb_firstmodule_get, _ldb.Ldb_firstmodule_set) + def itermodules(self): + m = self.firstmodule + while m is not None: + yield m + m = m.next + + def modules(self): + return list(self.itermodules()) + def __init__(self, *args, **kwargs): _ldb.Ldb_swiginit(self,_ldb.new_Ldb(*args, **kwargs)) def connect(*args, **kwargs): @@ -464,6 +474,26 @@ def string_to_time(*args, **kwargs): Parse a LDAP time string into a UNIX timestamp. """ return _ldb.string_to_time(*args, **kwargs) +class ldb_module(object): + thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + prev = _swig_property(_ldb.ldb_module_prev_get, _ldb.ldb_module_prev_set) + next = _swig_property(_ldb.ldb_module_next_get, _ldb.ldb_module_next_set) + def __init__(self, *args, **kwargs): + _ldb.ldb_module_swiginit(self,_ldb.new_ldb_module(*args, **kwargs)) + __swig_destroy__ = _ldb.delete_ldb_module +ldb_module.__str__ = new_instancemethod(_ldb.ldb_module___str__,None,ldb_module) +ldb_module.__repr__ = new_instancemethod(_ldb.ldb_module___repr__,None,ldb_module) +ldb_module.search = new_instancemethod(_ldb.ldb_module_search,None,ldb_module) +ldb_module.add = new_instancemethod(_ldb.ldb_module_add,None,ldb_module) +ldb_module.modify = new_instancemethod(_ldb.ldb_module_modify,None,ldb_module) +ldb_module.delete = new_instancemethod(_ldb.ldb_module_delete,None,ldb_module) +ldb_module.rename = new_instancemethod(_ldb.ldb_module_rename,None,ldb_module) +ldb_module.start_transaction = new_instancemethod(_ldb.ldb_module_start_transaction,None,ldb_module) +ldb_module.end_transaction = new_instancemethod(_ldb.ldb_module_end_transaction,None,ldb_module) +ldb_module.del_transaction = new_instancemethod(_ldb.ldb_module_del_transaction,None,ldb_module) +ldb_module_swigregister = _ldb.ldb_module_swigregister +ldb_module_swigregister(ldb_module) + def register_module(*args, **kwargs): """ diff --git a/source4/lib/ldb/ldb_wrap.c b/source4/lib/ldb/ldb_wrap.c index c9dd9dccd8..7a6d4517ce 100644 --- a/source4/lib/ldb/ldb_wrap.c +++ b/source4/lib/ldb/ldb_wrap.c @@ -2492,23 +2492,26 @@ SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) #define SWIGTYPE_p_ldb_ldif swig_types[6] #define SWIGTYPE_p_ldb_message swig_types[7] #define SWIGTYPE_p_ldb_message_element swig_types[8] -#define SWIGTYPE_p_ldb_module_ops swig_types[9] -#define SWIGTYPE_p_ldb_result swig_types[10] -#define SWIGTYPE_p_ldb_val swig_types[11] -#define SWIGTYPE_p_long_long swig_types[12] -#define SWIGTYPE_p_p_char swig_types[13] -#define SWIGTYPE_p_p_ldb_control swig_types[14] -#define SWIGTYPE_p_p_ldb_result swig_types[15] -#define SWIGTYPE_p_short swig_types[16] -#define SWIGTYPE_p_signed_char swig_types[17] -#define SWIGTYPE_p_unsigned_char swig_types[18] -#define SWIGTYPE_p_unsigned_int swig_types[19] -#define SWIGTYPE_p_unsigned_long swig_types[20] -#define SWIGTYPE_p_unsigned_long_long swig_types[21] -#define SWIGTYPE_p_unsigned_short swig_types[22] -#define SWIGTYPE_p_void swig_types[23] -static swig_type_info *swig_types[25]; -static swig_module_info swig_module = {swig_types, 24, 0, 0, 0, 0}; +#define SWIGTYPE_p_ldb_module swig_types[9] +#define SWIGTYPE_p_ldb_module_ops swig_types[10] +#define SWIGTYPE_p_ldb_parse_tree swig_types[11] +#define SWIGTYPE_p_ldb_request swig_types[12] +#define SWIGTYPE_p_ldb_result swig_types[13] +#define SWIGTYPE_p_ldb_val swig_types[14] +#define SWIGTYPE_p_long_long swig_types[15] +#define SWIGTYPE_p_p_char swig_types[16] +#define SWIGTYPE_p_p_ldb_control swig_types[17] +#define SWIGTYPE_p_p_ldb_result swig_types[18] +#define SWIGTYPE_p_short swig_types[19] +#define SWIGTYPE_p_signed_char swig_types[20] +#define SWIGTYPE_p_unsigned_char swig_types[21] +#define SWIGTYPE_p_unsigned_int swig_types[22] +#define SWIGTYPE_p_unsigned_long swig_types[23] +#define SWIGTYPE_p_unsigned_long_long swig_types[24] +#define SWIGTYPE_p_unsigned_short swig_types[25] +#define SWIGTYPE_p_void swig_types[26] +static swig_type_info *swig_types[28]; +static swig_module_info swig_module = {swig_types, 27, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) @@ -2562,6 +2565,7 @@ typedef struct ldb_context ldb; typedef struct ldb_dn ldb_dn; typedef struct ldb_ldif ldb_ldif; typedef struct ldb_message_element ldb_message_element; +typedef struct ldb_module ldb_module; typedef int ldb_error; typedef int ldb_int_error; @@ -3226,6 +3230,319 @@ static char *timestring(time_t t) return result; } +SWIGINTERN char const *ldb_module___str__(ldb_module *self){ + return self->ops->name; + } +SWIGINTERN char *ldb_module___repr__(ldb_module *self){ + char *ret; + asprintf(&ret, "", self->ops->name); + return ret; + } +SWIGINTERN int ldb_module_search(ldb_module *self,struct ldb_request *req){ + return self->ops->search(self, req); + } +SWIGINTERN ldb_error ldb_module_add(ldb_module *self,struct ldb_request *req){ + return self->ops->add(self, req); + } +SWIGINTERN ldb_error ldb_module_modify(ldb_module *self,struct ldb_request *req){ + return self->ops->modify(self, req); + } +SWIGINTERN ldb_error ldb_module_delete(ldb_module *self,struct ldb_request *req){ + return self->ops->del(self, req); + } +SWIGINTERN ldb_error ldb_module_rename(ldb_module *self,struct ldb_request *req){ + return self->ops->rename(self, req); + } +SWIGINTERN ldb_error ldb_module_start_transaction(ldb_module *self){ + return self->ops->start_transaction(self); + } +SWIGINTERN ldb_error ldb_module_end_transaction(ldb_module *self){ + return self->ops->end_transaction(self); + } +SWIGINTERN ldb_error ldb_module_del_transaction(ldb_module *self){ + return self->ops->del_transaction(self); + } + +int py_module_search(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result, *py_base, *py_attrs, *py_tree; + + py_base = SWIG_NewPointerObj(req->op.search.base, SWIGTYPE_p_ldb_dn, 0); + + if (py_base == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + py_tree = SWIG_NewPointerObj(req->op.search.tree, SWIGTYPE_p_ldb_parse_tree, 0); + + if (py_tree == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + if (req->op.search.attrs == NULL) { + py_attrs = Py_None; + } else { + int i, len; + for (len = 0; req->op.search.attrs[len]; len++); + py_attrs = PyList_New(len); + for (i = 0; i < len; i++) + PyList_SetItem(py_attrs, i, PyString_FromString(req->op.search.attrs[i])); + } + + py_result = PyObject_CallMethod(py_ldb, "search", "OiOO", py_base, req->op.search.scope, py_tree, py_attrs); + + Py_DECREF(py_attrs); + Py_DECREF(py_tree); + Py_DECREF(py_base); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + if (SWIG_ConvertPtr(py_result, &req->op.search.res, SWIGTYPE_p_ldb_result, 0) != 0) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_add(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result, *py_msg; + + py_msg = SWIG_NewPointerObj(req->op.add.message, SWIGTYPE_p_ldb_message, 0); + + if (py_msg == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + py_result = PyObject_CallMethod(py_ldb, "add", "O", py_msg); + + Py_DECREF(py_msg); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_modify(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result, *py_msg; + + py_msg = SWIG_NewPointerObj(req->op.mod.message, SWIGTYPE_p_ldb_message, 0); + + if (py_msg == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + py_result = PyObject_CallMethod(py_ldb, "modify", "O", py_msg); + + Py_DECREF(py_msg); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_del(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result, *py_dn; + + py_dn = SWIG_NewPointerObj(req->op.del.dn, SWIGTYPE_p_ldb_dn, 0); + + if (py_dn == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + py_result = PyObject_CallMethod(py_ldb, "delete", "O", py_dn); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_rename(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result, *py_olddn, *py_newdn; + + py_olddn = SWIG_NewPointerObj(req->op.rename.olddn, SWIGTYPE_p_ldb_dn, 0); + + if (py_olddn == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + py_newdn = SWIG_NewPointerObj(req->op.rename.newdn, SWIGTYPE_p_ldb_dn, 0); + + if (py_newdn == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + py_result = PyObject_CallMethod(py_ldb, "rename", "OO", py_olddn, py_newdn); + + Py_DECREF(py_olddn); + Py_DECREF(py_newdn); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_request(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result; + + py_result = PyObject_CallMethod(py_ldb, "request", ""); + + return LDB_ERR_OPERATIONS_ERROR; +} + +int py_module_extended(struct ldb_module *mod, struct ldb_request *req) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result; + + py_result = PyObject_CallMethod(py_ldb, "extended", ""); + + return LDB_ERR_OPERATIONS_ERROR; +} + +int py_module_start_transaction(struct ldb_module *mod) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result; + + py_result = PyObject_CallMethod(py_ldb, "start_transaction", ""); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_end_transaction(struct ldb_module *mod) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result; + + py_result = PyObject_CallMethod(py_ldb, "end_transaction", ""); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + return LDB_SUCCESS; +} + +int py_module_del_transaction(struct ldb_module *mod) +{ + PyObject *py_ldb = mod->private_data; + PyObject *py_result; + + py_result = PyObject_CallMethod(py_ldb, "del_transaction", ""); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + Py_DECREF(py_result); + + 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; + PyObject *py_result; + int ret; + + py_result = PyObject_CallMethod(py_ldb, "sequence_number", "ili", req->op.seq_num.type, req->op.seq_num.seq_num, req->op.seq_num.flags); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + ret = PyInt_AsLong(py_result); + + Py_DECREF(py_result); + + return ret; +} + +static int py_module_destructor(void *_mod) +{ + struct ldb_module *mod = _mod; + Py_DECREF((PyObject *)mod->private_data); + return 0; +} + +int py_module_init (struct ldb_module *mod) +{ + PyObject *py_class = mod->ops->private_data; + PyObject *py_result, *py_next, *py_ldb; + + py_ldb = SWIG_NewPointerObj(mod->ldb, SWIGTYPE_p_ldb_context, 0); + + if (py_ldb == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + py_next = SWIG_NewPointerObj(mod->next, SWIGTYPE_p_ldb_module, 0); + + if (py_next == NULL) + return LDB_ERR_OPERATIONS_ERROR; + + py_result = PyObject_CallFunction(py_class, "OO", py_ldb, py_next); + + if (py_result == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + mod->private_data = py_result; + + talloc_set_destructor (mod, py_module_destructor); + + return ldb_next_init(mod); +} + #ifdef __cplusplus extern "C" { #endif @@ -4433,6 +4750,64 @@ fail: } +SWIGINTERN PyObject *_wrap_Ldb_firstmodule_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ldb *arg1 = (ldb *) 0 ; + struct ldb_module *arg2 = (struct ldb_module *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject *swig_obj[2] ; + + if (!SWIG_Python_UnpackTuple(args,"Ldb_firstmodule_set",2,2,swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ldb_context, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Ldb_firstmodule_set" "', argument " "1"" of type '" "ldb *""'"); + } + arg1 = (ldb *)(argp1); + res2 = SWIG_ConvertPtr(swig_obj[1], &argp2,SWIGTYPE_p_ldb_module, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Ldb_firstmodule_set" "', argument " "2"" of type '" "struct ldb_module *""'"); + } + arg2 = (struct ldb_module *)(argp2); + if (arg1 == NULL) + SWIG_exception(SWIG_ValueError, + "ldb context must be non-NULL"); + if (arg1) (arg1)->modules = arg2; + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Ldb_firstmodule_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ldb *arg1 = (ldb *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + struct ldb_module *result = 0 ; + + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ldb_context, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Ldb_firstmodule_get" "', argument " "1"" of type '" "ldb *""'"); + } + arg1 = (ldb *)(argp1); + if (arg1 == NULL) + SWIG_exception(SWIG_ValueError, + "ldb context must be non-NULL"); + result = (struct ldb_module *) ((arg1)->modules); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ldb_module, 0 | 0 ); + return resultobj; +fail: + return NULL; +} + + SWIGINTERN PyObject *_wrap_new_Ldb(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ldb *result = 0 ; @@ -5707,19 +6082,498 @@ fail: } -SWIGINTERN PyObject *_wrap_register_module(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { +SWIGINTERN PyObject *_wrap_ldb_module_prev_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; - struct ldb_module_ops *arg1 = (struct ldb_module_ops *) 0 ; - PyObject * obj0 = 0 ; - char * kwnames[] = { - (char *)"arg1", NULL - }; - ldb_int_error result; + ldb_module *arg1 = (ldb_module *) 0 ; + struct ldb_module *arg2 = (struct ldb_module *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject *swig_obj[2] ; - if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:register_module",kwnames,&obj0)) SWIG_fail; - arg1 = talloc_zero(talloc_autofree_context(), struct ldb_module_ops); + if (!SWIG_Python_UnpackTuple(args,"ldb_module_prev_set",2,2,swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_prev_set" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + res2 = SWIG_ConvertPtr(swig_obj[1], &argp2,SWIGTYPE_p_ldb_module, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_prev_set" "', argument " "2"" of type '" "struct ldb_module *""'"); + } + arg2 = (struct ldb_module *)(argp2); + if (arg1) (arg1)->prev = arg2; + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ldb_module_prev_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + struct ldb_module *result = 0 ; + + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_prev_get" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + result = (struct ldb_module *) ((arg1)->prev); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ldb_module, 0 | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ldb_module_next_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + struct ldb_module *arg2 = (struct ldb_module *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject *swig_obj[2] ; + + if (!SWIG_Python_UnpackTuple(args,"ldb_module_next_set",2,2,swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_next_set" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + res2 = SWIG_ConvertPtr(swig_obj[1], &argp2,SWIGTYPE_p_ldb_module, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_next_set" "', argument " "2"" of type '" "struct ldb_module *""'"); + } + arg2 = (struct ldb_module *)(argp2); + if (arg1) (arg1)->next = arg2; + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ldb_module_next_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + struct ldb_module *result = 0 ; + + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_next_get" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + result = (struct ldb_module *) ((arg1)->next); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ldb_module, 0 | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ldb_module___str__(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + char *result = 0 ; + + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module___str__" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + result = (char *)ldb_module___str__(arg1); + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ldb_module___repr__(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + char *result = 0 ; + + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module___repr__" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + result = (char *)ldb_module___repr__(arg1); + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ldb_module_search(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + struct ldb_request *arg2 = (struct ldb_request *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "req", NULL + }; + int result; + + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:ldb_module_search",kwnames,&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_search" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_request, 0 | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_search" "', argument " "2"" of type '" "struct ldb_request *""'"); + } + arg2 = (struct ldb_request *)(argp2); + result = (int)ldb_module_search(arg1,arg2); + resultobj = SWIG_From_int((int)(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ldb_module_add(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + struct ldb_request *arg2 = (struct ldb_request *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "req", NULL + }; + ldb_error result; + + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:ldb_module_add",kwnames,&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_add" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_request, 0 | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_add" "', argument " "2"" of type '" "struct ldb_request *""'"); + } + arg2 = (struct ldb_request *)(argp2); + result = ldb_module_add(arg1,arg2); + if (result != 0) { + PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", result, ldb_errstring(arg1))); + SWIG_fail; + } + resultobj = Py_None; + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ldb_module_modify(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + struct ldb_request *arg2 = (struct ldb_request *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "req", NULL + }; + ldb_error result; + + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:ldb_module_modify",kwnames,&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_modify" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_request, 0 | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_modify" "', argument " "2"" of type '" "struct ldb_request *""'"); + } + arg2 = (struct ldb_request *)(argp2); + result = ldb_module_modify(arg1,arg2); + if (result != 0) { + PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", result, ldb_errstring(arg1))); + SWIG_fail; + } + resultobj = Py_None; + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ldb_module_delete(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + struct ldb_request *arg2 = (struct ldb_request *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "req", NULL + }; + ldb_error result; + + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:ldb_module_delete",kwnames,&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_delete" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_request, 0 | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_delete" "', argument " "2"" of type '" "struct ldb_request *""'"); + } + arg2 = (struct ldb_request *)(argp2); + result = ldb_module_delete(arg1,arg2); + if (result != 0) { + PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", result, ldb_errstring(arg1))); + SWIG_fail; + } + resultobj = Py_None; + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ldb_module_rename(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + struct ldb_request *arg2 = (struct ldb_request *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "req", NULL + }; + ldb_error result; + + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:ldb_module_rename",kwnames,&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_rename" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_request, 0 | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_rename" "', argument " "2"" of type '" "struct ldb_request *""'"); + } + arg2 = (struct ldb_request *)(argp2); + result = ldb_module_rename(arg1,arg2); + if (result != 0) { + PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", result, ldb_errstring(arg1))); + SWIG_fail; + } + resultobj = Py_None; + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ldb_module_start_transaction(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + ldb_error result; + + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_start_transaction" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + result = ldb_module_start_transaction(arg1); + if (result != 0) { + PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", result, ldb_errstring(arg1))); + SWIG_fail; + } + resultobj = Py_None; + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ldb_module_end_transaction(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + ldb_error result; + + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_end_transaction" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + result = ldb_module_end_transaction(arg1); + if (result != 0) { + PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", result, ldb_errstring(arg1))); + SWIG_fail; + } + resultobj = Py_None; + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ldb_module_del_transaction(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + ldb_error result; + + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_del_transaction" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + result = ldb_module_del_transaction(arg1); + if (result != 0) { + PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", result, ldb_errstring(arg1))); + SWIG_fail; + } + resultobj = Py_None; + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_new_ldb_module(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ldb_module *result = 0 ; + + if (!SWIG_Python_UnpackTuple(args,"new_ldb_module",0,0,0)) SWIG_fail; + result = (ldb_module *)calloc(1, sizeof(ldb_module)); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ldb_module, SWIG_POINTER_NEW | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_delete_ldb_module(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ldb_module *arg1 = (ldb_module *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ldb_module, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_ldb_module" "', argument " "1"" of type '" "ldb_module *""'"); + } + arg1 = (ldb_module *)(argp1); + free((char *) arg1); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *ldb_module_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *obj; + if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_ldb_module, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject *ldb_module_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + return SWIG_Python_InitShadowInstance(args); +} + +SWIGINTERN PyObject *_wrap_register_module(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + struct ldb_module_ops *arg1 = (struct ldb_module_ops *) 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *)"arg1", NULL + }; + ldb_int_error result; + + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:register_module",kwnames,&obj0)) SWIG_fail; + arg1 = talloc_zero(talloc_autofree_context(), struct ldb_module_ops); + + arg1->name = talloc_strdup(arg1, PyString_AsString(PyObject_GetAttrString(obj0, (char *)"name"))); - arg1->name = (char *)PyObject_GetAttrString(obj0, (char *)"name"); + Py_INCREF(obj0); + arg1->private_data = obj0; + arg1->init_context = py_module_init; + arg1->search = py_module_search; + arg1->add = py_module_add; + arg1->modify = py_module_modify; + arg1->del = py_module_del; + arg1->rename = py_module_rename; + arg1->request = py_module_request; + arg1->extended = py_module_extended; + 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) { PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", result, ldb_strerror(result))); @@ -5804,6 +6658,8 @@ static PyMethodDef SwigMethods[] = { { (char *)"Message_swigregister", Message_swigregister, METH_VARARGS, NULL}, { (char *)"Message_swiginit", Message_swiginit, METH_VARARGS, NULL}, { (char *)"ldb_ldif_to_pyobject", (PyCFunction) _wrap_ldb_ldif_to_pyobject, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"Ldb_firstmodule_set", _wrap_Ldb_firstmodule_set, METH_VARARGS, NULL}, + { (char *)"Ldb_firstmodule_get", (PyCFunction)_wrap_Ldb_firstmodule_get, METH_O, NULL}, { (char *)"new_Ldb", (PyCFunction)_wrap_new_Ldb, METH_NOARGS, NULL}, { (char *)"Ldb_connect", (PyCFunction) _wrap_Ldb_connect, METH_VARARGS | METH_KEYWORDS, (char *)"\n" "S.connect(url,flags=0,options=None) -> None\n" @@ -5892,6 +6748,24 @@ static PyMethodDef SwigMethods[] = { "S.string_to_time(string) -> int\n" "Parse a LDAP time string into a UNIX timestamp.\n" ""}, + { (char *)"ldb_module_prev_set", _wrap_ldb_module_prev_set, METH_VARARGS, NULL}, + { (char *)"ldb_module_prev_get", (PyCFunction)_wrap_ldb_module_prev_get, METH_O, NULL}, + { (char *)"ldb_module_next_set", _wrap_ldb_module_next_set, METH_VARARGS, NULL}, + { (char *)"ldb_module_next_get", (PyCFunction)_wrap_ldb_module_next_get, METH_O, NULL}, + { (char *)"ldb_module___str__", (PyCFunction)_wrap_ldb_module___str__, METH_O, NULL}, + { (char *)"ldb_module___repr__", (PyCFunction)_wrap_ldb_module___repr__, METH_O, NULL}, + { (char *)"ldb_module_search", (PyCFunction) _wrap_ldb_module_search, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"ldb_module_add", (PyCFunction) _wrap_ldb_module_add, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"ldb_module_modify", (PyCFunction) _wrap_ldb_module_modify, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"ldb_module_delete", (PyCFunction) _wrap_ldb_module_delete, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"ldb_module_rename", (PyCFunction) _wrap_ldb_module_rename, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"ldb_module_start_transaction", (PyCFunction)_wrap_ldb_module_start_transaction, METH_O, NULL}, + { (char *)"ldb_module_end_transaction", (PyCFunction)_wrap_ldb_module_end_transaction, METH_O, NULL}, + { (char *)"ldb_module_del_transaction", (PyCFunction)_wrap_ldb_module_del_transaction, METH_O, NULL}, + { (char *)"new_ldb_module", (PyCFunction)_wrap_new_ldb_module, METH_NOARGS, NULL}, + { (char *)"delete_ldb_module", (PyCFunction)_wrap_delete_ldb_module, METH_O, NULL}, + { (char *)"ldb_module_swigregister", ldb_module_swigregister, METH_VARARGS, NULL}, + { (char *)"ldb_module_swiginit", ldb_module_swiginit, METH_VARARGS, NULL}, { (char *)"register_module", (PyCFunction) _wrap_register_module, METH_VARARGS | METH_KEYWORDS, (char *)"\n" "S.register_module(module) -> None\n" "Register a LDB module.\n" @@ -5911,7 +6785,10 @@ static swig_type_info _swigt__p_ldb_dn = {"_p_ldb_dn", "struct ldb_dn *|ldb_dn * static swig_type_info _swigt__p_ldb_ldif = {"_p_ldb_ldif", "struct ldb_ldif *|ldb_ldif *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ldb_message = {"_p_ldb_message", "ldb_msg *|struct ldb_message *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ldb_message_element = {"_p_ldb_message_element", "struct ldb_message_element *|ldb_message_element *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_ldb_module = {"_p_ldb_module", "struct ldb_module *|ldb_module *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ldb_module_ops = {"_p_ldb_module_ops", "struct ldb_module_ops *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_ldb_parse_tree = {"_p_ldb_parse_tree", "struct ldb_parse_tree *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_ldb_request = {"_p_ldb_request", "struct ldb_request *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ldb_result = {"_p_ldb_result", "struct ldb_result *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ldb_val = {"_p_ldb_val", "struct ldb_val *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_long_long = {"_p_long_long", "int_least64_t *|int_fast64_t *|int64_t *|long long *|intmax_t *", 0, 0, (void*)0, 0}; @@ -5937,7 +6814,10 @@ static swig_type_info *swig_type_initial[] = { &_swigt__p_ldb_ldif, &_swigt__p_ldb_message, &_swigt__p_ldb_message_element, + &_swigt__p_ldb_module, &_swigt__p_ldb_module_ops, + &_swigt__p_ldb_parse_tree, + &_swigt__p_ldb_request, &_swigt__p_ldb_result, &_swigt__p_ldb_val, &_swigt__p_long_long, @@ -5963,7 +6843,10 @@ static swig_cast_info _swigc__p_ldb_dn[] = { {&_swigt__p_ldb_dn, 0, 0, 0},{0, 0 static swig_cast_info _swigc__p_ldb_ldif[] = { {&_swigt__p_ldb_ldif, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ldb_message[] = { {&_swigt__p_ldb_message, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ldb_message_element[] = { {&_swigt__p_ldb_message_element, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_ldb_module[] = { {&_swigt__p_ldb_module, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ldb_module_ops[] = { {&_swigt__p_ldb_module_ops, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_ldb_parse_tree[] = { {&_swigt__p_ldb_parse_tree, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_ldb_request[] = { {&_swigt__p_ldb_request, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ldb_result[] = { {&_swigt__p_ldb_result, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ldb_val[] = { {&_swigt__p_ldb_val, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_long_long[] = { {&_swigt__p_long_long, 0, 0, 0},{0, 0, 0, 0}}; @@ -5989,7 +6872,10 @@ static swig_cast_info *swig_cast_initial[] = { _swigc__p_ldb_ldif, _swigc__p_ldb_message, _swigc__p_ldb_message_element, + _swigc__p_ldb_module, _swigc__p_ldb_module_ops, + _swigc__p_ldb_parse_tree, + _swigc__p_ldb_request, _swigc__p_ldb_result, _swigc__p_ldb_val, _swigc__p_long_long, diff --git a/source4/lib/ldb/tests/python/api.py b/source4/lib/ldb/tests/python/api.py index 99ad1a9e66..bc3bbc1c8c 100755 --- a/source4/lib/ldb/tests/python/api.py +++ b/source4/lib/ldb/tests/python/api.py @@ -48,6 +48,14 @@ class SimpleLdb(unittest.TestCase): x = ldb.Ldb() x.set_modules_dir("/tmp") + def test_modules_none(self): + x = ldb.Ldb() + self.assertEquals([], x.modules()) + + def test_modules_tdb(self): + x = ldb.Ldb("bar.ldb") + self.assertEquals("[]", repr(x.modules())) + def test_search(self): l = ldb.Ldb("foo.ldb") self.assertEquals(len(l.search()), 1) @@ -451,12 +459,27 @@ class MessageElementTests(unittest.TestCase): x = ldb.MessageElement(["foo"]) self.assertEquals("foo", x) -class ExampleModule: - name = "example" - class ModuleTests(unittest.TestCase): def test_register_module(self): - ldb.register_module(ExampleModule()) + class ExampleModule: + name = "example" + ldb.register_module(ExampleModule) + + def test_use_module(self): + ops = [] + class ExampleModule: + name = "bla" + + def __init__(self, ldb, next): + ops.append("init") + + ldb.register_module(ExampleModule) + l = ldb.Ldb("usemodule.ldb") + l.add({"dn": "@MODULES", + "@LIST": "bla"}) + self.assertEquals([], ops) + l = ldb.Ldb("usemodule.ldb") + self.assertEquals(["init"], ops) if __name__ == '__main__': import unittest -- cgit From d173644f1080b8dc575998c1202018930320f635 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Wed, 17 Sep 2008 17:55:52 +0200 Subject: NTLMSSP Server: Correctly fills in the DNS server name and server domain Don't rely on "get*" system calls but rather on SAMBA "lp_*" calls. Signed-off-by: Stefan Metzmacher --- source4/auth/ntlmssp/ntlmssp_server.c | 38 ++++++++++++++++------------------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/source4/auth/ntlmssp/ntlmssp_server.c b/source4/auth/ntlmssp/ntlmssp_server.c index 838596ee98..bf91be3e24 100644 --- a/source4/auth/ntlmssp/ntlmssp_server.c +++ b/source4/auth/ntlmssp/ntlmssp_server.c @@ -25,7 +25,6 @@ #include "auth/ntlmssp/ntlmssp.h" #include "auth/ntlmssp/msrpc_parse.h" #include "lib/crypto/crypto.h" -#include "system/filesys.h" #include "libcli/auth/libcli_auth.h" #include "auth/credentials/credentials.h" #include "auth/gensec/gensec.h" @@ -125,8 +124,6 @@ NTSTATUS ntlmssp_server_negotiate(struct gensec_security *gensec_security, { struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; DATA_BLOB struct_blob; - char dnsname[MAXHOSTNAMELEN], dnsdomname[MAXHOSTNAMELEN]; - const char *p; uint32_t neg_flags = 0; uint32_t ntlmssp_command, chal_flags; const uint8_t *cryptkey; @@ -183,25 +180,24 @@ NTSTATUS ntlmssp_server_negotiate(struct gensec_security *gensec_security, gensec_ntlmssp_state->chal = data_blob_talloc(gensec_ntlmssp_state, cryptkey, 8); gensec_ntlmssp_state->internal_chal = data_blob_talloc(gensec_ntlmssp_state, cryptkey, 8); - dnsname[0] = '\0'; - if (gethostname(dnsname, sizeof(dnsname)) == -1) { - DEBUG(0,("gethostname failed\n")); - return NT_STATUS_UNSUCCESSFUL; - } - - /* This should be a 'netbios domain -> DNS domain' mapping */ - p = strchr(dnsname, '.'); - if (p != NULL) { - safe_strcpy(dnsdomname, p+1, sizeof(dnsdomname)); - strlower_m(dnsdomname); - } else { - dnsdomname[0] = '\0'; - } - /* This creates the 'blob' of names that appears at the end of the packet */ - if (chal_flags & NTLMSSP_CHAL_TARGET_INFO) - { + if (chal_flags & NTLMSSP_CHAL_TARGET_INFO) { + char dnsdomname[MAXHOSTNAMELEN], dnsname[MAXHOSTNAMELEN]; const char *target_name_dns = ""; + + /* Find out the DNS domain name */ + dnsdomname[0] = '\0'; + safe_strcpy(dnsdomname, lp_realm(gensec_security->lp_ctx), sizeof(dnsdomname) - 1); + strlower_m(dnsdomname); + + /* Find out the DNS host name */ + safe_strcpy(dnsname, gensec_ntlmssp_state->server_name, sizeof(dnsname) - 1); + if (dnsdomname[0] != '\0') { + safe_strcat(dnsname, ".", sizeof(dnsname) - 1); + safe_strcat(dnsname, dnsdomname, sizeof(dnsname) - 1); + } + strlower_m(dnsname); + if (chal_flags |= NTLMSSP_TARGET_TYPE_DOMAIN) { target_name_dns = dnsdomname; } else if (chal_flags |= NTLMSSP_TARGET_TYPE_SERVER) { @@ -221,7 +217,7 @@ NTSTATUS ntlmssp_server_negotiate(struct gensec_security *gensec_security, } { - /* Marshel the packet in the right format, be it unicode or ASCII */ + /* Marshal the packet in the right format, be it unicode or ASCII */ const char *gen_string; if (gensec_ntlmssp_state->unicode) { gen_string = "CdUdbddB"; -- cgit From 8ac5db124630586605bd3972975ea47ee1cb34c0 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Wed, 17 Sep 2008 17:55:02 +0200 Subject: LDAP Server: Don't create the SASL SECBLOB output object twice Removes one "talloc" creation of the output object. Signed-off-by: Stefan Metzmacher --- source4/ldap_server/ldap_bind.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/source4/ldap_server/ldap_bind.c b/source4/ldap_server/ldap_bind.c index f37ef31c0a..8357251a8f 100644 --- a/source4/ldap_server/ldap_bind.c +++ b/source4/ldap_server/ldap_bind.c @@ -180,9 +180,6 @@ static NTSTATUS ldapsrv_BindSASL(struct ldapsrv_call *call) input = *req->creds.SASL.secblob; } - resp->SASL.secblob = talloc(reply, DATA_BLOB); - NT_STATUS_HAVE_NO_MEMORY(resp->SASL.secblob); - status = gensec_update(conn->gensec, reply, input, &output); -- cgit From 7d391c09eea0197d6ea298afff66ae13d6398fdb Mon Sep 17 00:00:00 2001 From: "Gerald (Jerry) Carter" Date: Thu, 18 Sep 2008 14:49:46 -0500 Subject: idmap: Increment the interface number after Volker's rewrite. --- source3/include/idmap.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/include/idmap.h b/source3/include/idmap.h index 95c3e4c0c2..5548eae0ca 100644 --- a/source3/include/idmap.h +++ b/source3/include/idmap.h @@ -32,7 +32,7 @@ /* Updated to 4, completely new interface, SSS */ -#define SMB_IDMAP_INTERFACE_VERSION 4 +#define SMB_IDMAP_INTERFACE_VERSION 5 struct idmap_domain { const char *name; -- cgit From 258cec7756952f552ca2c4213a6724af546a3eab Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Fri, 19 Sep 2008 13:51:40 -0400 Subject: Add comment to explain version bump --- source3/include/idmap.h | 1 + 1 file changed, 1 insertion(+) diff --git a/source3/include/idmap.h b/source3/include/idmap.h index 5548eae0ca..4322192155 100644 --- a/source3/include/idmap.h +++ b/source3/include/idmap.h @@ -31,6 +31,7 @@ Updated to 3 for enum types by JRA. */ /* Updated to 4, completely new interface, SSS */ +/* Updated to 5, simplified interface by Volker */ #define SMB_IDMAP_INTERFACE_VERSION 5 -- cgit From 49b89633f175b81d7415f835009b6d14f6e10933 Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Fri, 19 Sep 2008 15:12:28 -0400 Subject: Fix standalone builds adjusting to new relative path. Add shared-build target to libreplace. Useful to build multiple standalone libraries that depend on each other without having to install them to the final install dir during the build. --- lib/replace/Makefile.in | 13 ++++++++++--- lib/replace/build_macros.m4 | 14 ++++++++++++++ lib/replace/configure.ac | 3 +++ lib/replace/libreplace.m4 | 4 ++-- lib/replace/test/testsuite.c | 3 ++- 5 files changed, 31 insertions(+), 6 deletions(-) create mode 100644 lib/replace/build_macros.m4 diff --git a/lib/replace/Makefile.in b/lib/replace/Makefile.in index c989835a8d..c889a0e457 100644 --- a/lib/replace/Makefile.in +++ b/lib/replace/Makefile.in @@ -9,7 +9,8 @@ libdir = @libdir@ VPATH = @libreplacedir@ srcdir = @srcdir@ builddir = @builddir@ -INSTALL = @INSTALL@ +sharedbuilddir = @sharedbuilddir@ +INSTALLCMD = @INSTALL@ LIBS = @LIBS@ .PHONY: test all showflags install installcheck clean distclean realdistclean @@ -29,8 +30,14 @@ showflags: @echo ' LIBS = $(LIBS)' install: all - mkdir -p $(libdir) - $(INSTALL) libreplace.a $(libdir) + ${INSTALLCMD} -d $(libdir) + ${INSTALLCMD} -m 644 libreplace.a $(libdir) + +shared-build: all + ${INSTALLCMD} -d $(sharedbuilddir)/include + ${INSTALLCMD} -m 644 replace.h $(sharedbuilddir)/include + ${INSTALLCMD} -d $(sharedbuilddir)/lib + ${INSTALLCMD} -m 644 libreplace.a $(sharedbuilddir)/lib libreplace.a: $(OBJS) ar -rcsv $@ $(OBJS) diff --git a/lib/replace/build_macros.m4 b/lib/replace/build_macros.m4 new file mode 100644 index 0000000000..c036668cd1 --- /dev/null +++ b/lib/replace/build_macros.m4 @@ -0,0 +1,14 @@ +AC_DEFUN(BUILD_WITH_SHARED_BUILD_DIR, + [ AC_ARG_WITH([shared-build-dir], + [AC_HELP_STRING([--with-shared-build-dir=DIR], + [temporary build directory where libraries are installed [$srcdir/sharedbuild]])]) + + sharedbuilddir="$srcdir/sharedbuild" + if test x"$with_shared_build_dir" != x; then + sharedbuilddir=$with_shared_build_dir + CFLAGS="$CFLAGS -I$with_shared_build_dir/include" + LDFLAGS="$LDFLAGS -L$with_shared_build_dir/lib" + fi + AC_SUBST(sharedbuilddir) + ]) + diff --git a/lib/replace/configure.ac b/lib/replace/configure.ac index 81997e09b7..0361825a02 100644 --- a/lib/replace/configure.ac +++ b/lib/replace/configure.ac @@ -22,6 +22,9 @@ if test "$ac_cv_prog_gcc" = yes; then CFLAGS="$CFLAGS -Wno-format-y2k" fi +m4_include(build_macros.m4) +BUILD_WITH_SHARED_BUILD_DIR + LIBS="${LIBREPLACE_NETWORK_LIBS}" AC_SUBST(LIBS) diff --git a/lib/replace/libreplace.m4 b/lib/replace/libreplace.m4 index dc7d88e6e1..e563acfd79 100644 --- a/lib/replace/libreplace.m4 +++ b/lib/replace/libreplace.m4 @@ -5,7 +5,7 @@ echo "LIBREPLACE_LOCATION_CHECKS: START" dnl find the libreplace sources. This is meant to work both for dnl libreplace standalone builds, and builds of packages using libreplace libreplacedir="" -libreplacepaths="$srcdir $srcdir/lib/replace $srcdir/libreplace $srcdir/../libreplace $srcdir/../replace $srcdir/../lib/replace" +libreplacepaths="$srcdir $srcdir/lib/replace $srcdir/libreplace $srcdir/../libreplace $srcdir/../replace $srcdir/../lib/replace $srcdir/../../../lib/replace" for d in $libreplacepaths; do if test -f "$d/replace.c"; then libreplacedir="$d" @@ -34,7 +34,7 @@ echo "LIBREPLACE_BROKEN_CHECKS: START" dnl find the libreplace sources. This is meant to work both for dnl libreplace standalone builds, and builds of packages using libreplace libreplacedir="" -libreplacepaths="$srcdir $srcdir/lib/replace $srcdir/libreplace $srcdir/../libreplace $srcdir/../replace $srcdir/../lib/replace" +libreplacepaths="$srcdir $srcdir/lib/replace $srcdir/libreplace $srcdir/../libreplace $srcdir/../replace $srcdir/../lib/replace $srcdir/../../../lib/replace" for d in $libreplacepaths; do if test -f "$d/replace.c"; then libreplacedir="$d" diff --git a/lib/replace/test/testsuite.c b/lib/replace/test/testsuite.c index 1e8290906e..dcb05fbbf4 100644 --- a/lib/replace/test/testsuite.c +++ b/lib/replace/test/testsuite.c @@ -1069,7 +1069,8 @@ bool torture_local_replace(struct torture_context *ctx) return ret; } -#if _SAMBA_BUILD_<4 +#if _SAMBA_BUILD_>3 +#else int main(void) { bool ret = torture_local_replace(NULL); -- cgit From e07400525fd955b9fb9524edda3f8e6bc7567847 Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Fri, 19 Sep 2008 15:15:21 -0400 Subject: Add shared-build target to talloc. Useful to build multiple standalone libraries that depend on each other without having to install them to the final install dir during the build. --- lib/talloc/Makefile.in | 10 ++++++++++ lib/talloc/build_macros.m4 | 14 ++++++++++++++ lib/talloc/configure.ac | 3 +++ lib/talloc/talloc.mk | 4 ++-- 4 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 lib/talloc/build_macros.m4 diff --git a/lib/talloc/Makefile.in b/lib/talloc/Makefile.in index 07b8fd4ff0..c28693e2db 100644 --- a/lib/talloc/Makefile.in +++ b/lib/talloc/Makefile.in @@ -9,6 +9,7 @@ mandir = @mandir@ VPATH = @srcdir@:@libreplacedir@ srcdir = @srcdir@ builddir = @builddir@ +sharedbuilddir = @sharedbuilddir@ XSLTPROC = @XSLTPROC@ INSTALLCMD = @INSTALL@ CC = @CC@ @@ -31,6 +32,15 @@ include $(tallocdir)/talloc.mk $(TALLOC_SOLIB): $(LIBOBJ) $(SHLD) $(SHLD_FLAGS) -o $@ $(LIBOBJ) @SONAMEFLAG@$(TALLOC_SONAME) +shared-build: all + ${INSTALLCMD} -d $(sharedbuilddir)/lib + ${INSTALLCMD} -m 644 libtalloc.a $(sharedbuilddir)/lib + ${INSTALLCMD} -m 755 $(TALLOC_SOLIB) $(sharedbuilddir)/lib + ln -sf $(TALLOC_SOLIB) $(sharedbuilddir)/lib/$(TALLOC_SONAME) + ln -sf $(TALLOC_SOLIB) $(sharedbuilddir)/lib/libtalloc.so + ${INSTALLCMD} -d $(sharedbuilddir)/include + ${INSTALLCMD} -m 644 $(srcdir)/talloc.h $(sharedbuilddir)/include + check: test installcheck:: test install diff --git a/lib/talloc/build_macros.m4 b/lib/talloc/build_macros.m4 new file mode 100644 index 0000000000..c036668cd1 --- /dev/null +++ b/lib/talloc/build_macros.m4 @@ -0,0 +1,14 @@ +AC_DEFUN(BUILD_WITH_SHARED_BUILD_DIR, + [ AC_ARG_WITH([shared-build-dir], + [AC_HELP_STRING([--with-shared-build-dir=DIR], + [temporary build directory where libraries are installed [$srcdir/sharedbuild]])]) + + sharedbuilddir="$srcdir/sharedbuild" + if test x"$with_shared_build_dir" != x; then + sharedbuilddir=$with_shared_build_dir + CFLAGS="$CFLAGS -I$with_shared_build_dir/include" + LDFLAGS="$LDFLAGS -L$with_shared_build_dir/lib" + fi + AC_SUBST(sharedbuilddir) + ]) + diff --git a/lib/talloc/configure.ac b/lib/talloc/configure.ac index 4719aa04b5..d2538f9222 100644 --- a/lib/talloc/configure.ac +++ b/lib/talloc/configure.ac @@ -21,4 +21,7 @@ AC_LD_SONAMEFLAG AC_LIBREPLACE_SHLD AC_LIBREPLACE_SHLD_FLAGS +m4_include(build_macros.m4) +BUILD_WITH_SHARED_BUILD_DIR + AC_OUTPUT(Makefile talloc.pc) diff --git a/lib/talloc/talloc.mk b/lib/talloc/talloc.mk index e1fe88c84b..23331b6365 100644 --- a/lib/talloc/talloc.mk +++ b/lib/talloc/talloc.mk @@ -22,8 +22,8 @@ install:: all ${INSTALLCMD} -m 644 talloc.pc $(DESTDIR)$(libdir)/pkgconfig if [ -f talloc.3 ];then ${INSTALLCMD} -d $(DESTDIR)$(mandir)/man3; fi if [ -f talloc.3 ];then ${INSTALLCMD} -m 644 talloc.3 $(DESTDIR)$(mandir)/man3; fi - which swig >/dev/null 2>&1 && ${INSTALLCMD} -d $(DESTDIR)`swig -swiglib` || true - which swig >/dev/null 2>&1 && ${INSTALLCMD} -m 644 talloc.i $(DESTDIR)`swig -swiglib` || true + which swig >/dev/null 2>&1 && ${INSTALLCMD} -d $(DESTDIR)$(prefix)`swig -swiglib` || true + which swig >/dev/null 2>&1 && ${INSTALLCMD} -m 644 talloc.i $(DESTDIR)$(prefix)`swig -swiglib` || true doc:: talloc.3 talloc.3.html -- cgit From 3235e25425dddb9ba6d0f8d7cfff94ea9d7c5bdd Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Fri, 19 Sep 2008 15:15:46 -0400 Subject: Add shared-build target to tdb. Useful to build multiple standalone libraries that depend on each other without having to install them to the final install dir during the build. --- lib/tdb/Makefile.in | 11 +++++++++++ lib/tdb/build_macros.m4 | 14 ++++++++++++++ lib/tdb/configure.ac | 4 ++++ lib/tdb/include/tdb.h | 1 + 4 files changed, 30 insertions(+) create mode 100644 lib/tdb/build_macros.m4 diff --git a/lib/tdb/Makefile.in b/lib/tdb/Makefile.in index 090bb6e2dc..9915d88264 100644 --- a/lib/tdb/Makefile.in +++ b/lib/tdb/Makefile.in @@ -12,6 +12,8 @@ libdir = @libdir@ VPATH = @srcdir@:@libreplacedir@ srcdir = @srcdir@ builddir = @builddir@ +sharedbuilddir = @sharedbuilddir@ +INSTALLCMD = @INSTALL@ CPPFLAGS = @CPPFLAGS@ -I$(srcdir)/include -Iinclude CFLAGS = $(CPPFLAGS) @CFLAGS@ LDFLAGS = @LDFLAGS@ @@ -43,6 +45,15 @@ install:: all $(TDB_SOLIB): $(TDB_OBJ) $(SHLD) $(SHLD_FLAGS) -o $@ $(TDB_OBJ) @SONAMEFLAG@$(TDB_SONAME) +shared-build: all + ${INSTALLCMD} -d $(sharedbuilddir)/lib + ${INSTALLCMD} -m 644 libtdb.a $(sharedbuilddir)/lib + ${INSTALLCMD} -m 755 $(TDB_SOLIB) $(sharedbuilddir)/lib + ln -sf $(TDB_SOLIB) $(sharedbuilddir)/lib/$(TDB_SONAME) + ln -sf $(TDB_SOLIB) $(sharedbuilddir)/lib/libtdb.so + ${INSTALLCMD} -d $(sharedbuilddir)/include + ${INSTALLCMD} -m 644 $(srcdir)/include/tdb.h $(sharedbuilddir)/include + check: test test:: $(PYTHON_CHECK_TARGET) diff --git a/lib/tdb/build_macros.m4 b/lib/tdb/build_macros.m4 new file mode 100644 index 0000000000..c036668cd1 --- /dev/null +++ b/lib/tdb/build_macros.m4 @@ -0,0 +1,14 @@ +AC_DEFUN(BUILD_WITH_SHARED_BUILD_DIR, + [ AC_ARG_WITH([shared-build-dir], + [AC_HELP_STRING([--with-shared-build-dir=DIR], + [temporary build directory where libraries are installed [$srcdir/sharedbuild]])]) + + sharedbuilddir="$srcdir/sharedbuild" + if test x"$with_shared_build_dir" != x; then + sharedbuilddir=$with_shared_build_dir + CFLAGS="$CFLAGS -I$with_shared_build_dir/include" + LDFLAGS="$LDFLAGS -L$with_shared_build_dir/lib" + fi + AC_SUBST(sharedbuilddir) + ]) + diff --git a/lib/tdb/configure.ac b/lib/tdb/configure.ac index eaf70d30b4..4bf2e98e8f 100644 --- a/lib/tdb/configure.ac +++ b/lib/tdb/configure.ac @@ -27,4 +27,8 @@ if test -z "$PYTHON_CONFIG"; then PYTHON_INSTALL_TARGET="" PYTHON_CHECK_TARGET="" fi + +m4_include(build_macros.m4) +BUILD_WITH_SHARED_BUILD_DIR + AC_OUTPUT(Makefile tdb.pc) diff --git a/lib/tdb/include/tdb.h b/lib/tdb/include/tdb.h index 0008085de5..c41c9941f0 100644 --- a/lib/tdb/include/tdb.h +++ b/lib/tdb/include/tdb.h @@ -30,6 +30,7 @@ extern "C" { #endif +#include "signal.h" /* flags to tdb_store() */ #define TDB_REPLACE 1 /* Unused */ -- cgit From 474de0f2172ebe55e6cafb4ad7e81fe662eacadc Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Fri, 19 Sep 2008 15:20:47 -0400 Subject: Fix libevents standalone build Make sure to build against libtalloc.a and not individual talloc objects, so that the library can be also built against libtalloc.so and use it as a shared library instead of statically compiling talloc. Also add shared-build target to the events library. Useful to build multiple standalone libraries that depend on each other without having to install them to the final install dir during the build. --- source4/lib/events/Makefile.in | 35 ++++++--- source4/lib/events/autogen.sh | 3 +- source4/lib/events/build_macros.m4 | 14 ++++ source4/lib/events/configure.ac | 9 ++- source4/lib/events/events.mk | 4 +- source4/lib/events/libevents.m4 | 2 +- source4/lib/events/libtalloc.m4 | 7 ++ source4/lib/events/pkg.m4 | 156 +++++++++++++++++++++++++++++++++++++ 8 files changed, 213 insertions(+), 17 deletions(-) create mode 100644 source4/lib/events/build_macros.m4 create mode 100644 source4/lib/events/libtalloc.m4 create mode 100644 source4/lib/events/pkg.m4 diff --git a/source4/lib/events/Makefile.in b/source4/lib/events/Makefile.in index 0a0df9bef9..4257119849 100644 --- a/source4/lib/events/Makefile.in +++ b/source4/lib/events/Makefile.in @@ -9,9 +9,11 @@ exec_prefix = @exec_prefix@ bindir = @bindir@ includedir = @includedir@ libdir = @libdir@ -VPATH = @srcdir@:@tallocdir@:@libreplacedir@ +VPATH = @srcdir@:@libreplacedir@ srcdir = @srcdir@ builddir = @builddir@ +sharedbuilddir = @sharedbuilddir@ +INSTALLCMD = @INSTALL@ CPPFLAGS = @CPPFLAGS@ -I$(srcdir)/include -Iinclude -I. LDFLAGS = @LDFLAGS@ EXEEXT = @EXEEXT@ @@ -28,26 +30,40 @@ PYTHON_INSTALL_TARGET = @PYTHON_INSTALL_TARGET@ PYTHON_CHECK_TARGET = @PYTHON_CHECK_TARGET@ LIB_PATH_VAR = @LIB_PATH_VAR@ eventsdir = @eventsdir@ -tallocdir = @tallocdir@ -TALLOC_LIBS = @TALLOC_LIBS@ TALLOC_CFLAGS = @TALLOC_CFLAGS@ -TALLOC_OBJ = @TALLOC_OBJ@ +TALLOC_LDFLAGS = @TALLOC_CFLAGS@ +TALLOC_LIBS = @TALLOC_LIBS@ -CFLAGS = $(CPPFLAGS) $(TALLOC_CFLAGS) @CFLAGS@ +EVENTS_CFLAGS = @EVENTS_CFLAGS@ +EVENTS_LDFLAGS = @EVENTS_CFLAGS@ +EVENTS_LIBS = @EVENTS_LIBS@ -EVENTS_OBJ = @EVENTS_OBJ@ $(TALLOC_OBJ) @LIBREPLACEOBJ@ +CFLAGS = $(CPPFLAGS) $(TALLOC_CFLAGS) $(EVENTS_CFLAGS) @CFLAGS@ +LDFLAGS = $(TALLOC_LDFLAGS) $(EVENTS_LDFLAGS) @LDFLAGS@ +LIBS = $(TALLOC_LIBS) $(EVENTS_LIBS) @LIBS@ + +EVENTS_OBJ = @EVENTS_OBJ@ @LIBREPLACEOBJ@ default: all include $(eventsdir)/events.mk include $(eventsdir)/rules.mk -all:: showflags dirs $(PROGS) $(LIBEVENTS_SOLIB) libevents.a $(PYTHON_BUILD_TARGET) +all:: showflags dirs $(PROGS) $(EVENTS_SOLIB) libevents.a $(PYTHON_BUILD_TARGET) install:: all -$(LIBEVENTS_SOLIB): $(EVENTS_OBJ) - $(SHLD) $(SHLD_FLAGS) -o $@ $(EVENTS_OBJ) $(TALLOC_LIBS) @SONAMEFLAG@$(LIBEVENTS_SONAME) +$(EVENTS_SOLIB): $(EVENTS_OBJ) + $(SHLD) $(SHLD_FLAGS) $(LDFLAGS) $(LIBS) -o $@ $(EVENTS_OBJ) @SONAMEFLAG@$(EVENTS_SONAME) + +shared-build: all + ${INSTALLCMD} -d $(sharedbuilddir)/lib + ${INSTALLCMD} -m 644 libevents.a $(sharedbuilddir)/lib + ${INSTALLCMD} -m 755 $(EVENTS_SOLIB) $(sharedbuilddir)/lib + ln -sf $(EVENTS_SOLIB) $(sharedbuilddir)/lib/$(EVENTS_SONAME) + ln -sf $(EVENTS_SOLIB) $(sharedbuilddir)/lib/libevents.so + ${INSTALLCMD} -d $(sharedbuilddir)/include + ${INSTALLCMD} -m 644 $(srcdir)/events.h $(sharedbuilddir)/include check: test @@ -56,7 +72,6 @@ installcheck:: test install clean:: rm -f *.o *.a */*.o - rm -f $(TALLOC_OBJ) distclean:: clean rm -f config.log config.status include/config.h config.cache diff --git a/source4/lib/events/autogen.sh b/source4/lib/events/autogen.sh index b13a4b685d..fec05f54d4 100755 --- a/source4/lib/events/autogen.sh +++ b/source4/lib/events/autogen.sh @@ -3,8 +3,7 @@ rm -rf autom4te.cache rm -f configure config.h.in -IPATHS="-I libreplace -I lib/replace -I ../libreplace -I ../replace" -IPATHS="$IPATHS -I lib/talloc -I talloc -I ../talloc" +IPATHS="-I libreplace -I lib/replace -I ../libreplace -I ../replace -I ../../../lib/replace" autoconf $IPATHS || exit 1 autoheader $IPATHS || exit 1 diff --git a/source4/lib/events/build_macros.m4 b/source4/lib/events/build_macros.m4 new file mode 100644 index 0000000000..c036668cd1 --- /dev/null +++ b/source4/lib/events/build_macros.m4 @@ -0,0 +1,14 @@ +AC_DEFUN(BUILD_WITH_SHARED_BUILD_DIR, + [ AC_ARG_WITH([shared-build-dir], + [AC_HELP_STRING([--with-shared-build-dir=DIR], + [temporary build directory where libraries are installed [$srcdir/sharedbuild]])]) + + sharedbuilddir="$srcdir/sharedbuild" + if test x"$with_shared_build_dir" != x; then + sharedbuilddir=$with_shared_build_dir + CFLAGS="$CFLAGS -I$with_shared_build_dir/include" + LDFLAGS="$LDFLAGS -L$with_shared_build_dir/lib" + fi + AC_SUBST(sharedbuilddir) + ]) + diff --git a/source4/lib/events/configure.ac b/source4/lib/events/configure.ac index fbd23b10e5..895f2a1daa 100644 --- a/source4/lib/events/configure.ac +++ b/source4/lib/events/configure.ac @@ -8,8 +8,6 @@ AC_CONFIG_SRCDIR([events.c]) AC_CONFIG_HEADER(config.h) AC_LIBREPLACE_ALL_CHECKS -m4_include(libtalloc.m4) - AC_LD_EXPORT_DYNAMIC AC_LD_SONAMEFLAG AC_LD_PICFLAG @@ -17,6 +15,13 @@ AC_LD_SHLIBEXT AC_LIBREPLACE_SHLD AC_LIBREPLACE_SHLD_FLAGS AC_LIBREPLACE_RUNTIME_LIB_PATH_VAR + +m4_include(build_macros.m4) +BUILD_WITH_SHARED_BUILD_DIR + +m4_include(pkg.m4) +m4_include(libtalloc.m4) + m4_include(libevents.m4) AC_PATH_PROGS([PYTHON_CONFIG], [python2.6-config python2.5-config python2.4-config python-config]) AC_PATH_PROGS([PYTHON], [python2.6 python2.5 python2.4 python]) diff --git a/source4/lib/events/events.mk b/source4/lib/events/events.mk index f4b02eae83..2bc6221689 100644 --- a/source4/lib/events/events.mk +++ b/source4/lib/events/events.mk @@ -5,7 +5,7 @@ EVENTS_SOLIB = libevents.$(SHLIBEXT).$(PACKAGE_VERSION) libevents.a: $(EVENTS_OBJ) ar -rv libevents.a $(EVENTS_OBJ) -libevents.$(SHLIBEXT): $(LIBEVENTS_SOLIB) +libevents.$(SHLIBEXT): $(EVENTS_SOLIB) ln -fs $< $@ $(EVENTS_SONAME): $(EVENTS_SOLIB) @@ -24,7 +24,7 @@ installheaders:: installdirs installlibs:: installdirs cp events.pc $(DESTDIR)$(libdir)/pkgconfig - cp libevents.a $(LIBEVENTS_SOLIB) $(DESTDIR)$(libdir) + cp libevents.a $(EVENTS_SOLIB) $(DESTDIR)$(libdir) install:: all installdirs installheaders installlibs $(PYTHON_INSTALL_TARGET) diff --git a/source4/lib/events/libevents.m4 b/source4/lib/events/libevents.m4 index d17da64b32..ed76b03d4f 100644 --- a/source4/lib/events/libevents.m4 +++ b/source4/lib/events/libevents.m4 @@ -43,7 +43,7 @@ SMB_EXT_LIB(LIBAIO_LINUX, $AIO_LIBS) EVENTS_CFLAGS="-I$eventsdir" AC_SUBST(EVENTS_CFLAGS) -EVENTS_LIBS="" +EVENTS_LIBS="$AIO_LIBS" AC_SUBST(EVENTS_LIBS) diff --git a/source4/lib/events/libtalloc.m4 b/source4/lib/events/libtalloc.m4 new file mode 100644 index 0000000000..a4c5b8a9d9 --- /dev/null +++ b/source4/lib/events/libtalloc.m4 @@ -0,0 +1,7 @@ +AC_SUBST(TALLOC_OBJ) +AC_SUBST(TALLOC_CFLAGS) +AC_SUBST(TALLOC_LIBS) + +AC_CHECK_HEADER(talloc.h, + [AC_CHECK_LIB(talloc, talloc_init, [TALLOC_LIBS="-ltalloc"]) ], + [PKG_CHECK_MODULES(TALLOC, talloc)]) diff --git a/source4/lib/events/pkg.m4 b/source4/lib/events/pkg.m4 new file mode 100644 index 0000000000..a8b3d06c81 --- /dev/null +++ b/source4/lib/events/pkg.m4 @@ -0,0 +1,156 @@ +# pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*- +# +# Copyright © 2004 Scott James Remnant . +# +# 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 . +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# PKG_PROG_PKG_CONFIG([MIN-VERSION]) +# ---------------------------------- +AC_DEFUN([PKG_PROG_PKG_CONFIG], +[m4_pattern_forbid([^_?PKG_[A-Z_]+$]) +m4_pattern_allow([^PKG_CONFIG(_PATH)?$]) +AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])dnl +if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then + AC_PATH_TOOL([PKG_CONFIG], [pkg-config]) +fi +if test -n "$PKG_CONFIG"; then + _pkg_min_version=m4_default([$1], [0.9.0]) + AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version]) + if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + PKG_CONFIG="" + fi + +fi[]dnl +])# PKG_PROG_PKG_CONFIG + +# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) +# +# Check to see whether a particular set of modules exists. Similar +# to PKG_CHECK_MODULES(), but does not set variables or print errors. +# +# +# Similar to PKG_CHECK_MODULES, make sure that the first instance of +# this or PKG_CHECK_MODULES is called, or make sure to call +# PKG_CHECK_EXISTS manually +# -------------------------------------------------------------- +AC_DEFUN([PKG_CHECK_EXISTS], +[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl +if test -n "$PKG_CONFIG" && \ + AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then + m4_ifval([$2], [$2], [:]) +m4_ifvaln([$3], [else + $3])dnl +fi]) + + +# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES]) +# --------------------------------------------- +m4_define([_PKG_CONFIG], +[if test -n "$PKG_CONFIG"; then + if test -n "$$1"; then + pkg_cv_[]$1="$$1" + else + PKG_CHECK_EXISTS([$3], + [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`], + [pkg_failed=yes]) + fi +else + pkg_failed=untried +fi[]dnl +])# _PKG_CONFIG + +# _PKG_SHORT_ERRORS_SUPPORTED +# ----------------------------- +AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED], +[AC_REQUIRE([PKG_PROG_PKG_CONFIG]) +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi[]dnl +])# _PKG_SHORT_ERRORS_SUPPORTED + + +# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND], +# [ACTION-IF-NOT-FOUND]) +# +# +# Note that if there is a possibility the first call to +# PKG_CHECK_MODULES might not happen, you should be sure to include an +# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac +# +# +# -------------------------------------------------------------- +AC_DEFUN([PKG_CHECK_MODULES], +[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl +AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl +AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl + +pkg_failed=no +AC_MSG_CHECKING([for $1]) + +_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2]) +_PKG_CONFIG([$1][_LIBS], [libs], [$2]) + +m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS +and $1[]_LIBS to avoid the need to call pkg-config. +See the pkg-config man page for more details.]) + +if test $pkg_failed = yes; then + _PKG_SHORT_ERRORS_SUPPORTED + if test $_pkg_short_errors_supported = yes; then + $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --errors-to-stdout --print-errors "$2"` + else + $1[]_PKG_ERRORS=`$PKG_CONFIG --errors-to-stdout --print-errors "$2"` + fi + # Put the nasty error message in config.log where it belongs + echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD + + ifelse([$4], , [AC_MSG_ERROR(dnl +[Package requirements ($2) were not met: + +$$1_PKG_ERRORS + +Consider adjusting the PKG_CONFIG_PATH environment variable if you +installed software in a non-standard prefix. + +_PKG_TEXT +])], + [AC_MSG_RESULT([no]) + $4]) +elif test $pkg_failed = untried; then + ifelse([$4], , [AC_MSG_FAILURE(dnl +[The pkg-config script could not be found or is too old. Make sure it +is in your PATH or set the PKG_CONFIG environment variable to the full +path to pkg-config. + +_PKG_TEXT + +To get pkg-config, see .])], + [$4]) +else + $1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS + $1[]_LIBS=$pkg_cv_[]$1[]_LIBS + AC_MSG_RESULT([yes]) + ifelse([$3], , :, [$3]) +fi[]dnl +])# PKG_CHECK_MODULES -- cgit From e42caab6f91369a981619d0b711071cd1c724d5d Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Fri, 19 Sep 2008 15:49:39 -0400 Subject: Fix ldb standalone build. Add shared-build target to the ldb library, and make it possible to build it against libtalloc, libevents, libtdb as shared libraries. --- source4/lib/ldb/Makefile.in | 42 +++++++++++++++++++++++------------ source4/lib/ldb/autogen.sh | 9 +------- source4/lib/ldb/build_macros.m4 | 14 ++++++++++++ source4/lib/ldb/configure.ac | 4 ++++ source4/lib/ldb/external/libevents.m4 | 9 +++++--- source4/lib/ldb/external/libtalloc.m4 | 9 +++++--- source4/lib/ldb/external/libtdb.m4 | 9 +++++--- source4/lib/ldb/ldb.mk | 29 +++++++++++------------- 8 files changed, 78 insertions(+), 47 deletions(-) create mode 100644 source4/lib/ldb/build_macros.m4 diff --git a/source4/lib/ldb/Makefile.in b/source4/lib/ldb/Makefile.in index ecb6b6516b..8d95dae7ea 100644 --- a/source4/lib/ldb/Makefile.in +++ b/source4/lib/ldb/Makefile.in @@ -11,9 +11,11 @@ includedir = @includedir@ libdir = @libdir@ bindir = @bindir@ mandir = @mandir@ -VPATH = @srcdir@:@tdbdir@:@tallocdir@:@libreplacedir@:@poptdir@:@eventsdir@ +VPATH = @srcdir@:@libreplacedir@ srcdir = @srcdir@ builddir = @builddir@ +sharedbuilddir = @sharedbuilddir@ +INSTALLCMD = @INSTALL@ SLAPD = @SLAPD@ SWIG = swig EXTRA_OBJ=@EXTRA_OBJ@ @@ -21,9 +23,7 @@ TESTS=test-tdb.sh @TESTS@ PACKAGE_VERSION = @PACKAGE_VERSION@ PYTHON = @PYTHON@ PYTHON_CONFIG = @PYTHON_CONFIG@ -tdbdir = @tdbdir@ ldbdir = $(srcdir) -tallocdir = @tallocdir@ TALLOC_LIBS = @TALLOC_LIBS@ TALLOC_CFLAGS = @TALLOC_CFLAGS@ @@ -33,6 +33,7 @@ TDB_LIBS = @TDB_LIBS@ TDB_CFLAGS = @TDB_CFLAGS@ TDB_OBJ = @TDB_OBJ@ +EVENTS_LIBS = @EVENTS_LIBS@ EVENTS_CFLAGS = @EVENTS_CFLAGS@ EVENTS_OBJ = @EVENTS_OBJ@ @@ -65,7 +66,7 @@ OBJS = $(MODULES_OBJ) $(COMMON_OBJ) $(LDB_TDB_OBJ) $(TDB_OBJ) $(EVENTS_OBJ) $(TA headers = $(srcdir)/include/ldb.h $(srcdir)/include/ldb_errors.h $(srcdir)/include/ldb_handlers.h -BINS = bin/ldbadd bin/ldbsearch bin/ldbdel bin/ldbmodify bin/ldbedit bin/ldbrename bin/ldbtest bin/oLschema2ldif +BINS = bin/ldbadd bin/ldbsearch bin/ldbdel bin/ldbmodify bin/ldbedit bin/ldbrename bin/ldbtest EXAMPLES = examples/ldbreader examples/ldifreader @@ -81,24 +82,37 @@ nssdir: @mkdir -p $(NSSDIR) SONAME = libldb.$(SHLIBEXT).0 -SOLIB = lib/libldb.$(SHLIBEXT).$(PACKAGE_VERSION) +SOLIB = libldb.$(SHLIBEXT).$(PACKAGE_VERSION) +LIBSOLIB = lib/$(SOLIB) STATICLIB = lib/libldb.a -lib/$(SONAME): $(SOLIB) +lib/$(SONAME): $(LIBSOLIB) ln -fs libldb.$(SHLIBEXT).$(PACKAGE_VERSION) $@ -lib/libldb.$(SHLIBEXT): $(SOLIB) +lib/libldb.$(SHLIBEXT): $(LIBSOLIB) ln -fs libldb.$(SHLIBEXT).$(PACKAGE_VERSION) $@ -lib/libnss_ldb.$(SHLIBEXT).2: $(NSS_OBJ) $(SOLIB) - $(SHLD) $(SHLD_FLAGS) -o $@ $(NSS_OBJ) $(LDFLAGS) $(SOLIB) @SONAMEFLAG@libnss_ldb.$(SHLIBEXT).2 +lib/libnss_ldb.$(SHLIBEXT).2: $(NSS_OBJ) $(LIBSOLIB) + $(SHLD) $(SHLD_FLAGS) -o $@ $(NSS_OBJ) $(LDFLAGS) $(LIBSOLIB) @SONAMEFLAG@libnss_ldb.$(SHLIBEXT).2 -$(SOLIB): $(OBJS) - $(SHLD) $(SHLD_FLAGS) -o $@ $(OBJS) $(LDFLAGS) $(LIBS) $(TALLOC_LIBS) $(TDB_LIBS) $(LIBDL) $(LDAP_LIBS) @SONAMEFLAG@$(SONAME) +$(LIBSOLIB): $(OBJS) + $(SHLD) $(SHLD_FLAGS) -o $@ $(OBJS) $(LDFLAGS) $(LIBS) $(TALLOC_LIBS) $(TDB_LIBS) $(EVENTS_LIBS) $(LIBDL) $(LDAP_LIBS) @SONAMEFLAG@$(SONAME) + ln -sf libldb.$(SHLIBEXT).$(PACKAGE_VERSION) lib/libldb.$(SHLIBEXT) -all: showflags dirs $(OBJS) $(STATICLIB) $(SOLIB) $(BINS) $(EXAMPLES) manpages \ +all: showflags dirs $(OBJS) $(STATICLIB) $(LIBSOLIB) $(BINS) $(EXAMPLES) manpages \ @PYTHON_BUILD_TARGET@ +shared-build: all + ${INSTALLCMD} -d $(sharedbuilddir)/lib + ${INSTALLCMD} -m 644 $(STATICLIB) $(sharedbuilddir)/lib + ${INSTALLCMD} -m 755 $(LIBSOLIB) $(sharedbuilddir)/lib + ln -sf $(SOLIB) $(sharedbuilddir)/lib/$(SONAME) + ln -sf $(SOLIB) $(sharedbuilddir)/lib/libldb.so + ${INSTALLCMD} -d $(sharedbuilddir)/include + ${INSTALLCMD} -m 644 $(srcdir)/include/ldb.h $(sharedbuilddir)/include + ${INSTALLCMD} -m 644 $(srcdir)/include/ldb_errors.h $(sharedbuilddir)/include + ${INSTALLCMD} -m 644 $(srcdir)/include/ldb_handlers.h $(sharedbuilddir)/include + dirs: @mkdir -p $(DIRS) @@ -110,7 +124,7 @@ doxygen:: clean:: rm -f *.o */*.o *.gcov */*.gc?? tdbtest.ldb* - rm -f $(BINS) $(TDB_OBJ) $(TALLOC_OBJ) $(STATICLIB) $(NSS_LIB) $(SOLIB) + rm -f $(BINS) $(TDB_OBJ) $(TALLOC_OBJ) $(STATICLIB) $(NSS_LIB) $(LIBSOLIB) rm -f $(POPT_OBJ) rm -f man/*.1 man/*.3 man/*.html rm -f $(EXAMPLES) @@ -149,7 +163,7 @@ installheaders:: installdirs cp $(headers) $(DESTDIR)$(includedir) installlibs:: installdirs - cp $(STATICLIB) $(SOLIB) $(DESTDIR)$(libdir) + cp $(STATICLIB) $(LIBSOLIB) $(DESTDIR)$(libdir) cp ldb.pc $(DESTDIR)$(libdir)/pkgconfig installbin:: installdirs diff --git a/source4/lib/ldb/autogen.sh b/source4/lib/ldb/autogen.sh index b81e5b094e..52fc8b63e2 100755 --- a/source4/lib/ldb/autogen.sh +++ b/source4/lib/ldb/autogen.sh @@ -3,14 +3,7 @@ rm -rf autom4te.cache rm -f configure config.h.in -IPATHS="-I libreplace -I lib/replace -I ../libreplace -I ../replace" -IPATHS="$IPATHS -I lib/events -I events -I ../events" -IPATHS="$IPATHS -I lib/talloc -I talloc -I ../talloc" -IPATHS="$IPATHS -I lib/tdb -I tdb -I ../tdb" -IPATHS="$IPATHS -I lib/popt -I popt -I ../popt" - -# Always keep this listed last, so the built-in versions of tdb and talloc -# get used if available. +IPATHS="-I libreplace -I lib/replace -I ../libreplace -I ../replace -I ../../../lib/replace" IPATHS="$IPATHS -I ./external" autoheader $IPATHS || exit 1 diff --git a/source4/lib/ldb/build_macros.m4 b/source4/lib/ldb/build_macros.m4 new file mode 100644 index 0000000000..c036668cd1 --- /dev/null +++ b/source4/lib/ldb/build_macros.m4 @@ -0,0 +1,14 @@ +AC_DEFUN(BUILD_WITH_SHARED_BUILD_DIR, + [ AC_ARG_WITH([shared-build-dir], + [AC_HELP_STRING([--with-shared-build-dir=DIR], + [temporary build directory where libraries are installed [$srcdir/sharedbuild]])]) + + sharedbuilddir="$srcdir/sharedbuild" + if test x"$with_shared_build_dir" != x; then + sharedbuilddir=$with_shared_build_dir + CFLAGS="$CFLAGS -I$with_shared_build_dir/include" + LDFLAGS="$LDFLAGS -L$with_shared_build_dir/lib" + fi + AC_SUBST(sharedbuilddir) + ]) + diff --git a/source4/lib/ldb/configure.ac b/source4/lib/ldb/configure.ac index 4a703e8139..095caa5e92 100644 --- a/source4/lib/ldb/configure.ac +++ b/source4/lib/ldb/configure.ac @@ -43,6 +43,10 @@ AC_SUBST(LDB_MODULESDIR) TESTS="" EXTRA_OBJ="" +m4_include(build_macros.m4) +BUILD_WITH_SHARED_BUILD_DIR + +m4_include(pkg.m4) m4_include(libpopt.m4) m4_include(libtalloc.m4) m4_include(libtdb.m4) diff --git a/source4/lib/ldb/external/libevents.m4 b/source4/lib/ldb/external/libevents.m4 index f0f80e9d8e..4fd2e71ec2 100644 --- a/source4/lib/ldb/external/libevents.m4 +++ b/source4/lib/ldb/external/libevents.m4 @@ -1,4 +1,7 @@ -m4_include(pkg.m4) -EVENTS_OBJ="" AC_SUBST(EVENTS_OBJ) -PKG_CHECK_MODULES(EVENTS, events) +AC_SUBST(EVENTS_CFLAGS) +AC_SUBST(EVENTS_LIBS) + +AC_CHECK_HEADER(events.h, + [AC_CHECK_LIB(events, event_context_init, [EVENTS_LIBS="-levents"]) ], + [PKG_CHECK_MODULES(EVENTS, events)]) diff --git a/source4/lib/ldb/external/libtalloc.m4 b/source4/lib/ldb/external/libtalloc.m4 index d08bd42065..a4c5b8a9d9 100644 --- a/source4/lib/ldb/external/libtalloc.m4 +++ b/source4/lib/ldb/external/libtalloc.m4 @@ -1,4 +1,7 @@ -m4_include(pkg.m4) -TALLOC_OBJ="" AC_SUBST(TALLOC_OBJ) -PKG_CHECK_MODULES(TALLOC, talloc) +AC_SUBST(TALLOC_CFLAGS) +AC_SUBST(TALLOC_LIBS) + +AC_CHECK_HEADER(talloc.h, + [AC_CHECK_LIB(talloc, talloc_init, [TALLOC_LIBS="-ltalloc"]) ], + [PKG_CHECK_MODULES(TALLOC, talloc)]) diff --git a/source4/lib/ldb/external/libtdb.m4 b/source4/lib/ldb/external/libtdb.m4 index 4c1f4b530e..8c2cab702f 100644 --- a/source4/lib/ldb/external/libtdb.m4 +++ b/source4/lib/ldb/external/libtdb.m4 @@ -1,4 +1,7 @@ -m4_include(pkg.m4) -TDB_OBJ="" AC_SUBST(TDB_OBJ) -PKG_CHECK_MODULES(TDB, tdb >= 1.1.0) +AC_SUBST(TDB_CFLAGS) +AC_SUBST(TDB_LIBS) + +AC_CHECK_HEADER(tdb.h, + [AC_CHECK_LIB(tdb, tdb_open, [TDB_LIBS="-ltdb"]) ], + [PKG_CHECK_MODULES(TDB, tdb >= 1.1.0)]) diff --git a/source4/lib/ldb/ldb.mk b/source4/lib/ldb/ldb.mk index df11e9d2ab..a7b1cb0c69 100644 --- a/source4/lib/ldb/ldb.mk +++ b/source4/lib/ldb/ldb.mk @@ -1,7 +1,7 @@ -LDB_LIB = $(STATICLIB) +LDB_LIB = -Llib -lldb -LIB_FLAGS=$(LDFLAGS) -Llib $(LDB_LIB) $(LIBS) $(POPT_LIBS) $(TALLOC_LIBS) \ - $(TDB_LIBS) $(LDAP_LIBS) $(LIBDL) +LIB_FLAGS=$(LDFLAGS) $(LIBS) $(LDB_LIB) $(POPT_LIBS) $(TALLOC_LIBS) \ + $(TDB_LIBS) $(EVENTS_LIBS) $(LDAP_LIBS) $(LIBDL) LDB_TDB_DIR=ldb_tdb LDB_TDB_OBJ=$(LDB_TDB_DIR)/ldb_tdb.o \ @@ -34,34 +34,31 @@ lib/libldb.a: $(OBJS) sample.$(SHLIBEXT): tests/sample_module.o $(MDLD) $(MDLD_FLAGS) -o $@ tests/sample_module.o -bin/ldbadd: tools/ldbadd.o tools/cmdline.o $(LIBS) +bin/ldbadd: tools/ldbadd.o tools/cmdline.o $(CC) -o bin/ldbadd tools/ldbadd.o tools/cmdline.o $(LIB_FLAGS) $(LD_EXPORT_DYNAMIC) -bin/ldbsearch: tools/ldbsearch.o tools/cmdline.o $(LIBS) +bin/ldbsearch: tools/ldbsearch.o tools/cmdline.o $(CC) -o bin/ldbsearch tools/ldbsearch.o tools/cmdline.o $(LIB_FLAGS) $(LD_EXPORT_DYNAMIC) -bin/ldbdel: tools/ldbdel.o tools/cmdline.o $(LIBS) +bin/ldbdel: tools/ldbdel.o tools/cmdline.o $(CC) -o bin/ldbdel tools/ldbdel.o tools/cmdline.o $(LIB_FLAGS) $(LD_EXPORT_DYNAMIC) -bin/ldbmodify: tools/ldbmodify.o tools/cmdline.o $(LIBS) +bin/ldbmodify: tools/ldbmodify.o tools/cmdline.o $(CC) -o bin/ldbmodify tools/ldbmodify.o tools/cmdline.o $(LIB_FLAGS) $(LD_EXPORT_DYNAMIC) -bin/ldbedit: tools/ldbedit.o tools/cmdline.o $(LIBS) +bin/ldbedit: tools/ldbedit.o tools/cmdline.o $(CC) -o bin/ldbedit tools/ldbedit.o tools/cmdline.o $(LIB_FLAGS) $(LD_EXPORT_DYNAMIC) -bin/ldbrename: tools/ldbrename.o tools/cmdline.o $(LIBS) +bin/ldbrename: tools/ldbrename.o tools/cmdline.o $(CC) -o bin/ldbrename tools/ldbrename.o tools/cmdline.o $(LIB_FLAGS) $(LD_EXPORT_DYNAMIC) -bin/ldbtest: tools/ldbtest.o tools/cmdline.o $(LIBS) +bin/ldbtest: tools/ldbtest.o tools/cmdline.o $(CC) -o bin/ldbtest tools/ldbtest.o tools/cmdline.o $(LIB_FLAGS) $(LD_EXPORT_DYNAMIC) -bin/oLschema2ldif: tools/oLschema2ldif.o tools/cmdline.o tools/convert.o $(LIBS) - $(CC) -o bin/oLschema2ldif tools/oLschema2ldif.o tools/cmdline.o tools/convert.o $(LIB_FLAGS) - -examples/ldbreader: examples/ldbreader.o $(LIBS) +examples/ldbreader: examples/ldbreader.o $(CC) -o examples/ldbreader examples/ldbreader.o $(LIB_FLAGS) -examples/ldifreader: examples/ldifreader.o $(LIBS) +examples/ldifreader: examples/ldifreader.o $(CC) -o examples/ldifreader examples/ldifreader.o $(LIB_FLAGS) # Python bindings @@ -70,7 +67,7 @@ build-python:: _ldb.$(SHLIBEXT) ldb_wrap.o: $(ldbdir)/ldb_wrap.c $(CC) $(PICFLAG) -c $(ldbdir)/ldb_wrap.c $(CFLAGS) `$(PYTHON_CONFIG) --cflags` -_ldb.$(SHLIBEXT): $(LIBS) ldb_wrap.o +_ldb.$(SHLIBEXT): ldb_wrap.o $(SHLD) $(SHLD_FLAGS) -o _ldb.$(SHLIBEXT) ldb_wrap.o $(LIB_FLAGS) `$(PYTHON_CONFIG) --ldflags` install-python:: build-python -- cgit From f63c83deef52afcbe27c1664031a5eed009f3a44 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sat, 20 Sep 2008 14:35:21 +0200 Subject: More code simplifications. --- source4/dsdb/samdb/ldb_modules/tests/samba3sam.py | 49 ++++++++++++----------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py index e85a730ded..7b8eceb5de 100644 --- a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py +++ b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py @@ -23,14 +23,16 @@ """Tests for the samba3sam LDB module, which maps Samba3 LDAP to AD LDAP.""" import os -import sys -import samba import ldb from ldb import SCOPE_DEFAULT, SCOPE_BASE, SCOPE_SUBTREE from samba import Ldb, substitute_var from samba.tests import LdbTestCase, TestCaseInTempDir -datadir = os.path.join(os.path.dirname(__file__), "../../../../../testdata/samba3") +datadir = os.path.join(os.path.dirname(__file__), + "../../../../../testdata/samba3") + +def read_datafile(filename): + return open(os.path.join(datadir, filename), 'r').read() def ldb_debug(l, text): print text @@ -48,7 +50,8 @@ class MapBaseTestCase(TestCaseInTempDir): "@LIST": "rootdse,paged_results,server_sort,extended_dn,asq,samldb,password_hash,operational,objectguid,rdn_name,samba3sam,partition"}) ldb.add({"dn": "@PARTITION", - "partition": [s4.basedn + ":" + s4.url, s3.basedn + ":" + s3.url], + "partition": ["%s:%s" % (s4.basedn, s4.url), + "%s:%s" % (s3.basedn, s3.url)], "replicateEntries": ["@ATTRIBUTES", "@INDEXLIST"]}) def setUp(self): @@ -83,8 +86,7 @@ class MapBaseTestCase(TestCaseInTempDir): return self.db.connect(self.url) def setup_data(self, path): - ldif = open(os.path.join(datadir, path), 'r').read() - self.add_ldif(ldif) + self.add_ldif(read_datafile(path)) def subst(self, text): return substitute_var(text, self.substvars) @@ -112,14 +114,16 @@ class MapBaseTestCase(TestCaseInTempDir): class Samba3SamTestCase(MapBaseTestCase): + def setUp(self): super(Samba3SamTestCase, self).setUp() ldb = Ldb(self.ldburl) self.samba3.setup_data("samba3.ldif") self.templates.setup_data("provision_samba3sam_templates.ldif") - ldif = open(os.path.join(datadir, "provision_samba3sam.ldif"), 'r').read() + 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) def test_search_non_mapped(self): @@ -151,7 +155,6 @@ class Samba3SamTestCase(MapBaseTestCase): # "S-1-5-21-4231626423-2410014848-2360679739-552") # Check mapping of objectClass oc = set(msg[0]["objectClass"]) - self.assertTrue(oc is not None) self.assertEquals(oc, set(["group"])) def test_search_by_objclass(self): @@ -281,13 +284,15 @@ delete: description class MapTestCase(MapBaseTestCase): + def setUp(self): super(MapTestCase, self).setUp() ldb = Ldb(self.ldburl) self.templates.setup_data("provision_samba3sam_templates.ldif") - ldif = open(os.path.join(datadir, "provision_samba3sam.ldif"), 'r').read() + 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) def test_map_search(self): @@ -383,7 +388,7 @@ description: y res = self.ldb.search(dn, scope=SCOPE_BASE, attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 1) - self.assertEquals(str(str(res[0].dn)), dn) + self.assertEquals(str(res[0].dn), dn) self.assertTrue(not "dnsHostName" in res[0]) self.assertEquals(res[0]["lastLogon"], "x") @@ -392,7 +397,7 @@ description: y res = self.samba3.db.search(dn, scope=SCOPE_BASE, attrs=["dnsHostName", "lastLogon", "sambaLogonTime"]) self.assertEquals(len(res), 1) - self.assertEquals(str(str(res[0].dn)), dn) + self.assertEquals(str(res[0].dn), dn) self.assertTrue(not "dnsHostName" in res[0]) self.assertTrue(not "lastLogon" in res[0]) self.assertEquals(res[0]["sambaLogonTime"], "x") @@ -402,7 +407,7 @@ description: y res = self.ldb.search(dn, scope=SCOPE_BASE, attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 1) - self.assertEquals(str(str(res[0].dn)), dn) + self.assertEquals(str(res[0].dn), dn) self.assertEquals(res[0]["dnsHostName"], "x") self.assertEquals(res[0]["lastLogon"], "x") @@ -411,7 +416,7 @@ description: y res = self.samba3.db.search(dn, scope=SCOPE_BASE, attrs=["dnsHostName", "lastLogon", "sambaLogonTime"]) self.assertEquals(len(res), 1) - self.assertEquals(str(str(res[0].dn)), dn) + self.assertEquals(str(res[0].dn), dn) self.assertTrue(not "dnsHostName" in res[0]) self.assertTrue(not "lastLogon" in res[0]) self.assertEquals(res[0]["sambaLogonTime"], "x") @@ -422,10 +427,10 @@ description: y res = self.ldb.search(expression="(revision=x)", scope=SCOPE_DEFAULT, attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) - self.assertEquals(str(str(res[0].dn)), self.samba4.dn("cn=Y")) + self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Y")) self.assertEquals(res[0]["dnsHostName"], "y") self.assertEquals(res[0]["lastLogon"], "y") - self.assertEquals(str(str(res[1].dn)), self.samba4.dn("cn=X")) + self.assertEquals(str(res[1].dn), self.samba4.dn("cn=X")) self.assertEquals(res[1]["dnsHostName"], "x") self.assertEquals(res[1]["lastLogon"], "x") @@ -433,10 +438,10 @@ description: y res = self.ldb.search(expression="(description=y)", scope=SCOPE_DEFAULT, attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 2) - self.assertEquals(str(str(res[0].dn)), self.samba4.dn("cn=Z")) + self.assertEquals(str(res[0].dn), self.samba4.dn("cn=Z")) self.assertEquals(res[0]["dnsHostName"], "z") self.assertEquals(res[0]["lastLogon"], "z") - self.assertEquals(str(str(res[1].dn)), self.samba4.dn("cn=C")) + self.assertEquals(str(res[1].dn), self.samba4.dn("cn=C")) self.assertTrue(not "dnsHostName" in res[1]) self.assertEquals(res[1]["lastLogon"], "z") @@ -507,12 +512,10 @@ description: y self.assertEquals(str(res[0].dn), self.samba4.dn("cn=X")) self.assertEquals(res[0]["dnsHostName"], "x") self.assertEquals(res[0]["lastLogon"], "x") - self.assertTrue(res[0]["objectClass"] is not None) self.assertEquals(res[0]["objectClass"][0], "user") self.assertEquals(str(res[1].dn), self.samba4.dn("cn=A")) self.assertTrue(not "dnsHostName" in res[1]) self.assertEquals(res[1]["lastLogon"], "x") - self.assertTrue(res[1]["objectClass"] is not None) self.assertEquals(res[1]["objectClass"][0], "user") # Prove that the objectClass is actually used for the search @@ -522,17 +525,14 @@ description: y self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) self.assertEquals(res[0]["lastLogon"], "y") - self.assertTrue(res[0]["objectClass"] is not None) self.assertEquals(set(res[0]["objectClass"]), set(["user"])) self.assertEquals(str(res[1].dn), self.samba4.dn("cn=X")) self.assertEquals(res[1]["dnsHostName"], "x") self.assertEquals(res[1]["lastLogon"], "x") - self.assertTrue(res[1]["objectClass"] is not None) self.assertEquals(res[1]["objectClass"][0], "user") self.assertEquals(str(res[2].dn), self.samba4.dn("cn=A")) self.assertTrue(not "dnsHostName" in res[2]) self.assertEquals(res[2]["lastLogon"], "x") - self.assertTrue(res[2]["objectClass"] is not None) self.assertEquals(res[2]["objectClass"][0], "user") # Testing search by parse tree @@ -848,9 +848,10 @@ description: foo self.assertEquals(res[0]["description"], "foo") self.assertEquals(res[0]["sambaBadPasswordCount"], "3") self.assertEquals(res[0]["sambaNextRid"], "1001") + import pdb; pdb.set_trace() # Check in mapped db attrs = ["description", "badPwdCount", "nextRid"] - res = self.ldb.search(dn, scope=SCOPE_BASE, attrs=attrs) + res = self.ldb.search(dn, scope=SCOPE_BASE, attrs=attrs, expression="") self.assertEquals(len(res), 1) self.assertEquals(str(res[0].dn), dn) self.assertEquals(res[0]["description"], "foo") @@ -1065,7 +1066,7 @@ revision: 2 dn2 = self.samba3.dn("cn=toast") res = self.samba3.db.search(dn2, scope=SCOPE_BASE, attrs=["description", "sambaBadPasswordCount", "sambaNextRid", - "revision"] + "revision"]) self.assertEquals(len(res), 1) self.assertEquals(str(res[0].dn), dn2) self.assertEquals(res[0]["description"], "test") -- cgit From 0e2928f94651c53d653a3ad83bbda5608b4d4c24 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sat, 20 Sep 2008 15:06:26 +0200 Subject: Don't expose ldb_request in the Python API but rather use regular parameters. --- source4/lib/ldb/ldb.i | 71 +++++++++--- source4/lib/ldb/ldb_wrap.c | 220 +++++++++++++++++++++++++----------- source4/lib/ldb/tests/python/api.py | 11 +- 3 files changed, 218 insertions(+), 84 deletions(-) diff --git a/source4/lib/ldb/ldb.i b/source4/lib/ldb/ldb.i index 8cd39b5690..e9496b503b 100644 --- a/source4/lib/ldb/ldb.i +++ b/source4/lib/ldb/ldb.i @@ -153,17 +153,21 @@ PyObject *ldb_val_to_py_object(struct ldb_context *ldb_ctx, * Wrap struct ldb_result */ -%typemap(in,noblock=1,numinputs=0) struct ldb_result **OUT (struct ldb_result *temp_ldb_result) { +%typemap(in,noblock=1,numinputs=0) struct ldb_result ** (struct ldb_result *temp_ldb_result) { $1 = &temp_ldb_result; } #ifdef SWIGPYTHON %typemap(argout,noblock=1) struct ldb_result ** (int i) { - $result = PyList_New((*$1)->count); - for (i = 0; i < (*$1)->count; i++) { - PyList_SetItem($result, i, - SWIG_NewPointerObj((*$1)->msgs[i], SWIGTYPE_p_ldb_message, 0) - ); + if ($1 == NULL) { + $result = Py_None; + } else { + $result = PyList_New((*$1)->count); + for (i = 0; i < (*$1)->count; i++) { + PyList_SetItem($result, i, + SWIG_NewPointerObj((*$1)->msgs[i], SWIGTYPE_p_ldb_message, 0) + ); + } } } @@ -944,20 +948,55 @@ typedef struct ldb_module { return ret; } #endif - int search(struct ldb_request *req) { - return $self->ops->search($self, req); + int search(struct ldb_dn *base, enum ldb_scope scope, struct ldb_parse_tree *tree, const char * const * attrs, struct ldb_result **res) { + int ret; + struct ldb_request *req = talloc_zero(NULL, struct ldb_request); + + req->operation = LDB_SEARCH; + req->op.search.base = base; + req->op.search.scope = scope; + req->op.search.tree = tree; + req->op.search.attrs = attrs; + + req->op.search.res = talloc_zero(NULL, struct ldb_result); + + ret = $self->ops->search($self, req); + + *res = req->op.search.res; + + talloc_free(req); + + return ret; } - ldb_error add(struct ldb_request *req) { - return $self->ops->add($self, req); + ldb_error add(struct ldb_message *message) { + struct ldb_request *req = talloc_zero(NULL, struct ldb_request); + req->operation = LDB_ADD; + req->op.add.message = message; + + return $self->ops->add($self, &req); } - ldb_error modify(struct ldb_request *req) { - return $self->ops->modify($self, req); + ldb_error modify(struct ldb_message *message) { + struct ldb_request *req = talloc_zero(NULL, struct ldb_request); + req->operation = LDB_MODIFY; + req->op.mod.message = message; + + return $self->ops->modify($self, &req); } - ldb_error delete(struct ldb_request *req) { - return $self->ops->del($self, req); + ldb_error delete(struct ldb_dn *dn) { + struct ldb_request *req = talloc_zero(NULL, struct ldb_request); + req->operation = LDB_DELETE; + req->op.del.dn = dn; + + return $self->ops->del($self, &req); + } - ldb_error rename(struct ldb_request *req) { - return $self->ops->rename($self, req); + ldb_error rename(struct ldb_dn *olddn, struct ldb_dn *newdn) { + struct ldb_request *req = talloc_zero(NULL, struct ldb_request); + req->operation = LDB_RENAME; + req->op.rename.olddn = olddn; + req->op.rename.olddn = newdn; + + return $self->ops->rename($self, &req); } ldb_error start_transaction() { return $self->ops->start_transaction($self); diff --git a/source4/lib/ldb/ldb_wrap.c b/source4/lib/ldb/ldb_wrap.c index 7a6d4517ce..84e68d460e 100644 --- a/source4/lib/ldb/ldb_wrap.c +++ b/source4/lib/ldb/ldb_wrap.c @@ -2495,23 +2495,22 @@ SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) #define SWIGTYPE_p_ldb_module swig_types[9] #define SWIGTYPE_p_ldb_module_ops swig_types[10] #define SWIGTYPE_p_ldb_parse_tree swig_types[11] -#define SWIGTYPE_p_ldb_request swig_types[12] -#define SWIGTYPE_p_ldb_result swig_types[13] -#define SWIGTYPE_p_ldb_val swig_types[14] -#define SWIGTYPE_p_long_long swig_types[15] -#define SWIGTYPE_p_p_char swig_types[16] -#define SWIGTYPE_p_p_ldb_control swig_types[17] -#define SWIGTYPE_p_p_ldb_result swig_types[18] -#define SWIGTYPE_p_short swig_types[19] -#define SWIGTYPE_p_signed_char swig_types[20] -#define SWIGTYPE_p_unsigned_char swig_types[21] -#define SWIGTYPE_p_unsigned_int swig_types[22] -#define SWIGTYPE_p_unsigned_long swig_types[23] -#define SWIGTYPE_p_unsigned_long_long swig_types[24] -#define SWIGTYPE_p_unsigned_short swig_types[25] -#define SWIGTYPE_p_void swig_types[26] -static swig_type_info *swig_types[28]; -static swig_module_info swig_module = {swig_types, 27, 0, 0, 0, 0}; +#define SWIGTYPE_p_ldb_result swig_types[12] +#define SWIGTYPE_p_ldb_val swig_types[13] +#define SWIGTYPE_p_long_long swig_types[14] +#define SWIGTYPE_p_p_char swig_types[15] +#define SWIGTYPE_p_p_ldb_control swig_types[16] +#define SWIGTYPE_p_p_ldb_result swig_types[17] +#define SWIGTYPE_p_short swig_types[18] +#define SWIGTYPE_p_signed_char swig_types[19] +#define SWIGTYPE_p_unsigned_char swig_types[20] +#define SWIGTYPE_p_unsigned_int swig_types[21] +#define SWIGTYPE_p_unsigned_long swig_types[22] +#define SWIGTYPE_p_unsigned_long_long swig_types[23] +#define SWIGTYPE_p_unsigned_short swig_types[24] +#define SWIGTYPE_p_void swig_types[25] +static swig_type_info *swig_types[27]; +static swig_module_info swig_module = {swig_types, 26, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) @@ -3238,20 +3237,55 @@ SWIGINTERN char *ldb_module___repr__(ldb_module *self){ asprintf(&ret, "", self->ops->name); return ret; } -SWIGINTERN int ldb_module_search(ldb_module *self,struct ldb_request *req){ - return self->ops->search(self, req); +SWIGINTERN int ldb_module_search(ldb_module *self,struct ldb_dn *base,enum ldb_scope scope,struct ldb_parse_tree *tree,char const *const *attrs,struct ldb_result **res){ + int ret; + struct ldb_request *req = talloc_zero(NULL, struct ldb_request); + + req->operation = LDB_SEARCH; + req->op.search.base = base; + req->op.search.scope = scope; + req->op.search.tree = tree; + req->op.search.attrs = attrs; + + req->op.search.res = talloc_zero(NULL, struct ldb_result); + + ret = self->ops->search(self, req); + + *res = req->op.search.res; + + talloc_free(req); + + return ret; } -SWIGINTERN ldb_error ldb_module_add(ldb_module *self,struct ldb_request *req){ - return self->ops->add(self, req); +SWIGINTERN ldb_error ldb_module_add(ldb_module *self,struct ldb_message *message){ + struct ldb_request *req = talloc_zero(NULL, struct ldb_request); + req->operation = LDB_ADD; + req->op.add.message = message; + + return self->ops->add(self, &req); } -SWIGINTERN ldb_error ldb_module_modify(ldb_module *self,struct ldb_request *req){ - return self->ops->modify(self, req); +SWIGINTERN ldb_error ldb_module_modify(ldb_module *self,struct ldb_message *message){ + struct ldb_request *req = talloc_zero(NULL, struct ldb_request); + req->operation = LDB_MODIFY; + req->op.mod.message = message; + + return self->ops->modify(self, &req); } -SWIGINTERN ldb_error ldb_module_delete(ldb_module *self,struct ldb_request *req){ - return self->ops->del(self, req); +SWIGINTERN ldb_error ldb_module_delete(ldb_module *self,struct ldb_dn *dn){ + struct ldb_request *req = talloc_zero(NULL, struct ldb_request); + req->operation = LDB_DELETE; + req->op.del.dn = dn; + + return self->ops->del(self, &req); + } -SWIGINTERN ldb_error ldb_module_rename(ldb_module *self,struct ldb_request *req){ - return self->ops->rename(self, req); +SWIGINTERN ldb_error ldb_module_rename(ldb_module *self,struct ldb_dn *olddn,struct ldb_dn *newdn){ + struct ldb_request *req = talloc_zero(NULL, struct ldb_request); + req->operation = LDB_RENAME; + req->op.rename.olddn = olddn; + req->op.rename.olddn = newdn; + + return self->ops->rename(self, &req); } SWIGINTERN ldb_error ldb_module_start_transaction(ldb_module *self){ return self->ops->start_transaction(self); @@ -5000,11 +5034,15 @@ SWIGINTERN PyObject *_wrap_Ldb_search_ex(PyObject *SWIGUNUSEDPARM(self), PyObjec SWIG_fail; } resultobj = Py_None; - resultobj = PyList_New((*arg8)->count); - for (i8 = 0; i8 < (*arg8)->count; i8++) { - PyList_SetItem(resultobj, i8, - SWIG_NewPointerObj((*arg8)->msgs[i8], SWIGTYPE_p_ldb_message, 0) - ); + if (arg8 == NULL) { + resultobj = Py_None; + } else { + resultobj = PyList_New((*arg8)->count); + for (i8 = 0; i8 < (*arg8)->count; i8++) { + PyList_SetItem(resultobj, i8, + SWIG_NewPointerObj((*arg8)->msgs[i8], SWIGTYPE_p_ldb_message, 0) + ); + } } talloc_free(arg3); if (alloc5 == SWIG_NEWOBJ) free((char*)buf5); @@ -6235,33 +6273,80 @@ fail: SWIGINTERN PyObject *_wrap_ldb_module_search(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; ldb_module *arg1 = (ldb_module *) 0 ; - struct ldb_request *arg2 = (struct ldb_request *) 0 ; + struct ldb_dn *arg2 = (struct ldb_dn *) 0 ; + enum ldb_scope arg3 ; + struct ldb_parse_tree *arg4 = (struct ldb_parse_tree *) 0 ; + char **arg5 = (char **) 0 ; + struct ldb_result **arg6 = (struct ldb_result **) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; + int val3 ; + int ecode3 = 0 ; + void *argp4 = 0 ; + int res4 = 0 ; + struct ldb_result *temp_ldb_result6 ; + int i6 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; char * kwnames[] = { - (char *) "self",(char *) "req", NULL + (char *) "self",(char *) "base",(char *) "scope",(char *) "tree",(char *) "attrs", NULL }; int result; - if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:ldb_module_search",kwnames,&obj0,&obj1)) SWIG_fail; + arg6 = &temp_ldb_result6; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOOOO:ldb_module_search",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_search" "', argument " "1"" of type '" "ldb_module *""'"); } arg1 = (ldb_module *)(argp1); - res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_request, 0 | 0 ); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_dn, 0 | 0 ); if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_search" "', argument " "2"" of type '" "struct ldb_request *""'"); + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_search" "', argument " "2"" of type '" "struct ldb_dn *""'"); } - arg2 = (struct ldb_request *)(argp2); - result = (int)ldb_module_search(arg1,arg2); + arg2 = (struct ldb_dn *)(argp2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "ldb_module_search" "', argument " "3"" of type '" "enum ldb_scope""'"); + } + arg3 = (enum ldb_scope)(val3); + res4 = SWIG_ConvertPtr(obj3, &argp4,SWIGTYPE_p_ldb_parse_tree, 0 | 0 ); + if (!SWIG_IsOK(res4)) { + SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "ldb_module_search" "', argument " "4"" of type '" "struct ldb_parse_tree *""'"); + } + arg4 = (struct ldb_parse_tree *)(argp4); + if (obj4 == Py_None) { + arg5 = NULL; + } else if (PySequence_Check(obj4)) { + int i; + arg5 = talloc_array(NULL, char *, PySequence_Size(obj4)+1); + for(i = 0; i < PySequence_Size(obj4); i++) + arg5[i] = PyString_AsString(PySequence_GetItem(obj4, i)); + arg5[i] = NULL; + } else { + SWIG_exception(SWIG_TypeError, "expected sequence"); + } + result = (int)ldb_module_search(arg1,arg2,arg3,arg4,(char const *const *)arg5,arg6); resultobj = SWIG_From_int((int)(result)); + if (arg6 == NULL) { + resultobj = Py_None; + } else { + resultobj = PyList_New((*arg6)->count); + for (i6 = 0; i6 < (*arg6)->count; i6++) { + PyList_SetItem(resultobj, i6, + SWIG_NewPointerObj((*arg6)->msgs[i6], SWIGTYPE_p_ldb_message, 0) + ); + } + } + talloc_free(arg5); return resultobj; fail: + talloc_free(arg5); return NULL; } @@ -6269,7 +6354,7 @@ fail: SWIGINTERN PyObject *_wrap_ldb_module_add(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; ldb_module *arg1 = (ldb_module *) 0 ; - struct ldb_request *arg2 = (struct ldb_request *) 0 ; + struct ldb_message *arg2 = (struct ldb_message *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -6277,7 +6362,7 @@ SWIGINTERN PyObject *_wrap_ldb_module_add(PyObject *SWIGUNUSEDPARM(self), PyObje PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { - (char *) "self",(char *) "req", NULL + (char *) "self",(char *) "message", NULL }; ldb_error result; @@ -6287,11 +6372,11 @@ SWIGINTERN PyObject *_wrap_ldb_module_add(PyObject *SWIGUNUSEDPARM(self), PyObje SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_add" "', argument " "1"" of type '" "ldb_module *""'"); } arg1 = (ldb_module *)(argp1); - res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_request, 0 | 0 ); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_message, 0 | 0 ); if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_add" "', argument " "2"" of type '" "struct ldb_request *""'"); + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_add" "', argument " "2"" of type '" "struct ldb_message *""'"); } - arg2 = (struct ldb_request *)(argp2); + arg2 = (struct ldb_message *)(argp2); result = ldb_module_add(arg1,arg2); if (result != 0) { PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", result, ldb_errstring(arg1))); @@ -6307,7 +6392,7 @@ fail: SWIGINTERN PyObject *_wrap_ldb_module_modify(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; ldb_module *arg1 = (ldb_module *) 0 ; - struct ldb_request *arg2 = (struct ldb_request *) 0 ; + struct ldb_message *arg2 = (struct ldb_message *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -6315,7 +6400,7 @@ SWIGINTERN PyObject *_wrap_ldb_module_modify(PyObject *SWIGUNUSEDPARM(self), PyO PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { - (char *) "self",(char *) "req", NULL + (char *) "self",(char *) "message", NULL }; ldb_error result; @@ -6325,11 +6410,11 @@ SWIGINTERN PyObject *_wrap_ldb_module_modify(PyObject *SWIGUNUSEDPARM(self), PyO SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_modify" "', argument " "1"" of type '" "ldb_module *""'"); } arg1 = (ldb_module *)(argp1); - res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_request, 0 | 0 ); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_message, 0 | 0 ); if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_modify" "', argument " "2"" of type '" "struct ldb_request *""'"); + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_modify" "', argument " "2"" of type '" "struct ldb_message *""'"); } - arg2 = (struct ldb_request *)(argp2); + arg2 = (struct ldb_message *)(argp2); result = ldb_module_modify(arg1,arg2); if (result != 0) { PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", result, ldb_errstring(arg1))); @@ -6345,7 +6430,7 @@ fail: SWIGINTERN PyObject *_wrap_ldb_module_delete(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; ldb_module *arg1 = (ldb_module *) 0 ; - struct ldb_request *arg2 = (struct ldb_request *) 0 ; + struct ldb_dn *arg2 = (struct ldb_dn *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; @@ -6353,7 +6438,7 @@ SWIGINTERN PyObject *_wrap_ldb_module_delete(PyObject *SWIGUNUSEDPARM(self), PyO PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { - (char *) "self",(char *) "req", NULL + (char *) "self",(char *) "dn", NULL }; ldb_error result; @@ -6363,11 +6448,11 @@ SWIGINTERN PyObject *_wrap_ldb_module_delete(PyObject *SWIGUNUSEDPARM(self), PyO SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_delete" "', argument " "1"" of type '" "ldb_module *""'"); } arg1 = (ldb_module *)(argp1); - res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_request, 0 | 0 ); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_dn, 0 | 0 ); if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_delete" "', argument " "2"" of type '" "struct ldb_request *""'"); + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_delete" "', argument " "2"" of type '" "struct ldb_dn *""'"); } - arg2 = (struct ldb_request *)(argp2); + arg2 = (struct ldb_dn *)(argp2); result = ldb_module_delete(arg1,arg2); if (result != 0) { PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", result, ldb_errstring(arg1))); @@ -6383,30 +6468,39 @@ fail: SWIGINTERN PyObject *_wrap_ldb_module_rename(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; ldb_module *arg1 = (ldb_module *) 0 ; - struct ldb_request *arg2 = (struct ldb_request *) 0 ; + struct ldb_dn *arg2 = (struct ldb_dn *) 0 ; + struct ldb_dn *arg3 = (struct ldb_dn *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; + void *argp3 = 0 ; + int res3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; char * kwnames[] = { - (char *) "self",(char *) "req", NULL + (char *) "self",(char *) "olddn",(char *) "newdn", NULL }; ldb_error result; - if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:ldb_module_rename",kwnames,&obj0,&obj1)) SWIG_fail; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:ldb_module_rename",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ldb_module, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ldb_module_rename" "', argument " "1"" of type '" "ldb_module *""'"); } arg1 = (ldb_module *)(argp1); - res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_request, 0 | 0 ); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ldb_dn, 0 | 0 ); if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_rename" "', argument " "2"" of type '" "struct ldb_request *""'"); + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ldb_module_rename" "', argument " "2"" of type '" "struct ldb_dn *""'"); + } + arg2 = (struct ldb_dn *)(argp2); + res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_ldb_dn, 0 | 0 ); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "ldb_module_rename" "', argument " "3"" of type '" "struct ldb_dn *""'"); } - arg2 = (struct ldb_request *)(argp2); - result = ldb_module_rename(arg1,arg2); + arg3 = (struct ldb_dn *)(argp3); + result = ldb_module_rename(arg1,arg2,arg3); if (result != 0) { PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", result, ldb_errstring(arg1))); SWIG_fail; @@ -6788,7 +6882,6 @@ static swig_type_info _swigt__p_ldb_message_element = {"_p_ldb_message_element", static swig_type_info _swigt__p_ldb_module = {"_p_ldb_module", "struct ldb_module *|ldb_module *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ldb_module_ops = {"_p_ldb_module_ops", "struct ldb_module_ops *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ldb_parse_tree = {"_p_ldb_parse_tree", "struct ldb_parse_tree *", 0, 0, (void*)0, 0}; -static swig_type_info _swigt__p_ldb_request = {"_p_ldb_request", "struct ldb_request *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ldb_result = {"_p_ldb_result", "struct ldb_result *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ldb_val = {"_p_ldb_val", "struct ldb_val *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_long_long = {"_p_long_long", "int_least64_t *|int_fast64_t *|int64_t *|long long *|intmax_t *", 0, 0, (void*)0, 0}; @@ -6817,7 +6910,6 @@ static swig_type_info *swig_type_initial[] = { &_swigt__p_ldb_module, &_swigt__p_ldb_module_ops, &_swigt__p_ldb_parse_tree, - &_swigt__p_ldb_request, &_swigt__p_ldb_result, &_swigt__p_ldb_val, &_swigt__p_long_long, @@ -6846,7 +6938,6 @@ static swig_cast_info _swigc__p_ldb_message_element[] = { {&_swigt__p_ldb_messa static swig_cast_info _swigc__p_ldb_module[] = { {&_swigt__p_ldb_module, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ldb_module_ops[] = { {&_swigt__p_ldb_module_ops, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ldb_parse_tree[] = { {&_swigt__p_ldb_parse_tree, 0, 0, 0},{0, 0, 0, 0}}; -static swig_cast_info _swigc__p_ldb_request[] = { {&_swigt__p_ldb_request, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ldb_result[] = { {&_swigt__p_ldb_result, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ldb_val[] = { {&_swigt__p_ldb_val, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_long_long[] = { {&_swigt__p_long_long, 0, 0, 0},{0, 0, 0, 0}}; @@ -6875,7 +6966,6 @@ static swig_cast_info *swig_cast_initial[] = { _swigc__p_ldb_module, _swigc__p_ldb_module_ops, _swigc__p_ldb_parse_tree, - _swigc__p_ldb_request, _swigc__p_ldb_result, _swigc__p_ldb_val, _swigc__p_long_long, diff --git a/source4/lib/ldb/tests/python/api.py b/source4/lib/ldb/tests/python/api.py index bc3bbc1c8c..4b3501839f 100755 --- a/source4/lib/ldb/tests/python/api.py +++ b/source4/lib/ldb/tests/python/api.py @@ -2,7 +2,7 @@ # Simple tests for the ldb python bindings. # Copyright (C) 2007 Jelmer Vernooij -import sys +import os, sys import unittest # Required for the standalone LDB build @@ -472,11 +472,16 @@ class ModuleTests(unittest.TestCase): def __init__(self, ldb, next): ops.append("init") + self.next = next + + def search(self, *args, **kwargs): + return self.next.search(*args, **kwargs) ldb.register_module(ExampleModule) + if os.path.exists("usemodule.ldb"): + os.unlink("usemodule.ldb") l = ldb.Ldb("usemodule.ldb") - l.add({"dn": "@MODULES", - "@LIST": "bla"}) + l.add({"dn": "@MODULES", "@LIST": "bla"}) self.assertEquals([], ops) l = ldb.Ldb("usemodule.ldb") self.assertEquals(["init"], ops) -- cgit From db6bd2a3d6311cf34a6af044ec37f31f7741c144 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 03:42:27 +0200 Subject: Fix DNs - only one more samba3sam test failing now. --- source4/dsdb/samdb/ldb_modules/tests/samba3sam.py | 152 ++++++++++------------ source4/scripting/python/misc_wrap.c | 46 ++++--- 2 files changed, 100 insertions(+), 98 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py index 7b8eceb5de..8ea566c7b3 100644 --- a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py +++ b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py @@ -58,10 +58,10 @@ class MapBaseTestCase(TestCaseInTempDir): super(MapBaseTestCase, self).setUp() def make_dn(basedn, rdn): - return rdn + ",sambaDomainName=TESTS," + basedn + return "%s,sambaDomainName=TESTS,%s" % (rdn, basedn) def make_s4dn(basedn, rdn): - return rdn + "," + basedn + return "%s,%s" % (rdn, basedn) self.ldbfile = os.path.join(self.tempdir, "test.ldb") self.ldburl = "tdb://" + self.ldbfile @@ -80,7 +80,7 @@ class MapBaseTestCase(TestCaseInTempDir): self._dn = dn def dn(self, rdn): - return self._dn(rdn, self.basedn) + return self._dn(self.basedn, rdn) def connect(self): return self.db.connect(self.url) @@ -298,88 +298,81 @@ class MapTestCase(MapBaseTestCase): def test_map_search(self): """Running search tests on mapped data.""" ldif = """ -dn: sambaDomainName=TESTS,""" + self.samba3.basedn + """ -objectclass: sambaDomain -objectclass: top -sambaSID: S-1-5-21-4231626423-2410014848-2360679739 -sambaNextRid: 2000 -sambaDomainName: TESTS""" - self.samba3.add_ldif(ldif) - - # Add a set of split records - ldif = """ -dn: """ + self.samba4.dn("cn=X") + """ -objectClass: user -cn: X -codePage: x -revision: x -dnsHostName: x -nextRid: y -lastLogon: x -description: x -objectSid: S-1-5-21-4231626423-2410014848-2360679739-552 -primaryGroupID: 1-5-21-4231626423-2410014848-2360679739-512 """ + self.samba3.db.add({ + "dn": "sambaDomainName=TESTS," + self.samba3.basedn, + "objectclass": ["sambaDomain", "top"], + "sambaSID": "S-1-5-21-4231626423-2410014848-2360679739", + "sambaNextRid": "2000", + "sambaDomainName": "TESTS" + }) - self.ldb.add_ldif(self.samba4.subst(ldif)) - - ldif = """ -dn: """ + self.samba4.dn("cn=Y") + """ -objectClass: top -cn: Y -codePage: x -revision: x -dnsHostName: y -nextRid: y -lastLogon: y -description: x -""" - self.ldb.add_ldif(self.samba4.subst(ldif)) + # Add a set of split records + self.ldb.add({ + "dn": self.samba4.dn("cn=X"), + "objectClass": "user", + "cn": "X", + "codePage": "x", + "revision": "x", + "dnsHostName": "x", + "nextRid": "y", + "lastLogon": "x", + "description": "x", + "objectSid": "S-1-5-21-4231626423-2410014848-2360679739-552", + "primaryGroupID": "1-5-21-4231626423-2410014848-2360679739-512"}) - ldif = """ -dn: """ + self.samba4.dn("cn=Z") + """ -objectClass: top -cn: Z -codePage: x -revision: y -dnsHostName: z -nextRid: y -lastLogon: z -description: y -""" + self.ldb.add({ + "dn": self.samba4.dn("cn=Y"), + "objectClass": "top", + "cn": "Y", + "codePage": "x", + "revision": "x", + "dnsHostName": "y", + "nextRid": "y", + "lastLogon": "y", + "description": "x"}) - self.ldb.add_ldif(self.samba4.subst(ldif)) + self.ldb.add({ + "dn": self.samba4.dn("cn=Z"), + "objectClass": "top", + "cn": "Z", + "codePage": "x", + "revision": "y", + "dnsHostName": "z", + "nextRid": "y", + "lastLogon": "z", + "description": "y"}) # Add a set of remote records - ldif = """ -dn: """ + self.samba3.dn("cn=A") + """ -objectClass: posixAccount -cn: A -sambaNextRid: x -sambaBadPasswordCount: x -sambaLogonTime: x -description: x -sambaSID: S-1-5-21-4231626423-2410014848-2360679739-552 -sambaPrimaryGroupSID: S-1-5-21-4231626423-2410014848-2360679739-512 - -dn: """ + self.samba3.dn("cn=B") + """ -objectClass: top -cn:B -sambaNextRid: x -sambaBadPasswordCount: x -sambaLogonTime: y -description: x - -dn: """ + self.samba3.dn("cn=C") + """ -objectClass: top -cn: C -sambaNextRid: x -sambaBadPasswordCount: y -sambaLogonTime: z -description: y -""" - self.samba3.add_ldif(ldif) + self.samba3.db.add({ + "dn": self.samba3.dn("cn=A"), + "objectClass": "posixAccount", + "cn": "A", + "sambaNextRid": "x", + "sambaBadPasswordCount": "x", + "sambaLogonTime": "x", + "description": "x", + "sambaSID": "S-1-5-21-4231626423-2410014848-2360679739-552", + "sambaPrimaryGroupSID": "S-1-5-21-4231626423-2410014848-2360679739-512"}) + + self.samba3.db.add({ + "dn": self.samba3.dn("cn=B"), + "objectClass": "top", + "cn": "B", + "sambaNextRid": "x", + "sambaBadPasswordCount": "x", + "sambaLogonTime": "y", + "description": "x"}) + + self.samba3.db.add({ + "dn": self.samba3.dn("cn=C"), + "objectClass": "top", + "cn": "C", + "sambaNextRid": "x", + "sambaBadPasswordCount": "y", + "sambaLogonTime": "z", + "description": "y"}) # Testing search by DN @@ -461,7 +454,7 @@ description: y # Using the SID directly in the parse tree leads to conversion # errors, letting the search fail with no results. #res = self.ldb.search("(objectSid=S-1-5-21-4231626423-2410014848-2360679739-552)", scope=SCOPE_DEFAULT, attrs) - res = self.ldb.search(expression="(objectSid=*)", + res = self.ldb.search(expression="(objectSid=*)", base=None, attrs=["dnsHostName", "lastLogon", "objectSid"]) self.assertEquals(len(res), 3) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=X")) @@ -848,7 +841,6 @@ description: foo self.assertEquals(res[0]["description"], "foo") self.assertEquals(res[0]["sambaBadPasswordCount"], "3") self.assertEquals(res[0]["sambaNextRid"], "1001") - import pdb; pdb.set_trace() # Check in mapped db attrs = ["description", "badPwdCount", "nextRid"] res = self.ldb.search(dn, scope=SCOPE_BASE, attrs=attrs, expression="") diff --git a/source4/scripting/python/misc_wrap.c b/source4/scripting/python/misc_wrap.c index 3aee83f72c..b669f3e801 100644 --- a/source4/scripting/python/misc_wrap.c +++ b/source4/scripting/python/misc_wrap.c @@ -2494,24 +2494,26 @@ SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) #define SWIGTYPE_p_ldb_ldif swig_types[8] #define SWIGTYPE_p_ldb_message swig_types[9] #define SWIGTYPE_p_ldb_message_element swig_types[10] -#define SWIGTYPE_p_ldb_result swig_types[11] -#define SWIGTYPE_p_loadparm_context swig_types[12] -#define SWIGTYPE_p_loadparm_service swig_types[13] -#define SWIGTYPE_p_long_long swig_types[14] -#define SWIGTYPE_p_param_context swig_types[15] -#define SWIGTYPE_p_param_opt swig_types[16] -#define SWIGTYPE_p_param_section swig_types[17] -#define SWIGTYPE_p_security_descriptor swig_types[18] -#define SWIGTYPE_p_security_token swig_types[19] -#define SWIGTYPE_p_short swig_types[20] -#define SWIGTYPE_p_signed_char swig_types[21] -#define SWIGTYPE_p_unsigned_char swig_types[22] -#define SWIGTYPE_p_unsigned_int swig_types[23] -#define SWIGTYPE_p_unsigned_long swig_types[24] -#define SWIGTYPE_p_unsigned_long_long swig_types[25] -#define SWIGTYPE_p_unsigned_short swig_types[26] -static swig_type_info *swig_types[28]; -static swig_module_info swig_module = {swig_types, 27, 0, 0, 0, 0}; +#define SWIGTYPE_p_ldb_module swig_types[11] +#define SWIGTYPE_p_ldb_parse_tree swig_types[12] +#define SWIGTYPE_p_ldb_result swig_types[13] +#define SWIGTYPE_p_loadparm_context swig_types[14] +#define SWIGTYPE_p_loadparm_service swig_types[15] +#define SWIGTYPE_p_long_long swig_types[16] +#define SWIGTYPE_p_param_context swig_types[17] +#define SWIGTYPE_p_param_opt swig_types[18] +#define SWIGTYPE_p_param_section swig_types[19] +#define SWIGTYPE_p_security_descriptor swig_types[20] +#define SWIGTYPE_p_security_token swig_types[21] +#define SWIGTYPE_p_short swig_types[22] +#define SWIGTYPE_p_signed_char swig_types[23] +#define SWIGTYPE_p_unsigned_char swig_types[24] +#define SWIGTYPE_p_unsigned_int swig_types[25] +#define SWIGTYPE_p_unsigned_long swig_types[26] +#define SWIGTYPE_p_unsigned_long_long swig_types[27] +#define SWIGTYPE_p_unsigned_short swig_types[28] +static swig_type_info *swig_types[30]; +static swig_module_info swig_module = {swig_types, 29, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) @@ -3340,6 +3342,8 @@ static swig_type_info _swigt__p_ldb_dn = {"_p_ldb_dn", "struct ldb_dn *|ldb_dn * static swig_type_info _swigt__p_ldb_ldif = {"_p_ldb_ldif", "struct ldb_ldif *|ldb_ldif *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ldb_message = {"_p_ldb_message", "ldb_msg *|struct ldb_message *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ldb_message_element = {"_p_ldb_message_element", "struct ldb_message_element *|ldb_message_element *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_ldb_module = {"_p_ldb_module", "struct ldb_module *|ldb_module *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_ldb_parse_tree = {"_p_ldb_parse_tree", "struct ldb_parse_tree *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ldb_result = {"_p_ldb_result", "struct ldb_result *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_loadparm_context = {"_p_loadparm_context", "struct loadparm_context *|loadparm_context *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_loadparm_service = {"_p_loadparm_service", "struct loadparm_service *|loadparm_service *", 0, 0, (void*)0, 0}; @@ -3369,6 +3373,8 @@ static swig_type_info *swig_type_initial[] = { &_swigt__p_ldb_ldif, &_swigt__p_ldb_message, &_swigt__p_ldb_message_element, + &_swigt__p_ldb_module, + &_swigt__p_ldb_parse_tree, &_swigt__p_ldb_result, &_swigt__p_loadparm_context, &_swigt__p_loadparm_service, @@ -3398,6 +3404,8 @@ static swig_cast_info _swigc__p_ldb_dn[] = { {&_swigt__p_ldb_dn, 0, 0, 0},{0, 0 static swig_cast_info _swigc__p_ldb_ldif[] = { {&_swigt__p_ldb_ldif, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ldb_message[] = { {&_swigt__p_ldb_message, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ldb_message_element[] = { {&_swigt__p_ldb_message_element, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_ldb_module[] = { {&_swigt__p_ldb_module, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_ldb_parse_tree[] = { {&_swigt__p_ldb_parse_tree, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ldb_result[] = { {&_swigt__p_ldb_result, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_loadparm_context[] = { {&_swigt__p_loadparm_context, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_loadparm_service[] = { {&_swigt__p_loadparm_service, 0, 0, 0},{0, 0, 0, 0}}; @@ -3427,6 +3435,8 @@ static swig_cast_info *swig_cast_initial[] = { _swigc__p_ldb_ldif, _swigc__p_ldb_message, _swigc__p_ldb_message_element, + _swigc__p_ldb_module, + _swigc__p_ldb_parse_tree, _swigc__p_ldb_result, _swigc__p_loadparm_context, _swigc__p_loadparm_service, -- cgit From 9f178f5b6716e8a130717976646388f1a8018146 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 05:21:56 +0200 Subject: Fix last samba3sam.py test. --- source4/dsdb/samdb/ldb_modules/tests/samba3sam.py | 52 ++++++++++++----------- 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py index 8ea566c7b3..2ca5b80c67 100644 --- a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py +++ b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py @@ -297,8 +297,6 @@ class MapTestCase(MapBaseTestCase): def test_map_search(self): """Running search tests on mapped data.""" - ldif = """ -""" self.samba3.db.add({ "dn": "sambaDomainName=TESTS," + self.samba3.basedn, "objectclass": ["sambaDomain", "top"], @@ -308,18 +306,20 @@ class MapTestCase(MapBaseTestCase): }) # Add a set of split records - self.ldb.add({ - "dn": self.samba4.dn("cn=X"), - "objectClass": "user", - "cn": "X", - "codePage": "x", - "revision": "x", - "dnsHostName": "x", - "nextRid": "y", - "lastLogon": "x", - "description": "x", - "objectSid": "S-1-5-21-4231626423-2410014848-2360679739-552", - "primaryGroupID": "1-5-21-4231626423-2410014848-2360679739-512"}) + self.ldb.add_ldif(""" +dn: """+ self.samba4.dn("cn=X") + """ +objectClass: user +cn: X +codePage: x +revision: x +dnsHostName: x +nextRid: y +lastLogon: x +description: x +objectSid: S-1-5-21-4231626423-2410014848-2360679739-552 +primaryGroupID: 1-5-21-4231626423-2410014848-2360679739-512 + +""") self.ldb.add({ "dn": self.samba4.dn("cn=Y"), @@ -454,19 +454,23 @@ class MapTestCase(MapBaseTestCase): # Using the SID directly in the parse tree leads to conversion # errors, letting the search fail with no results. #res = self.ldb.search("(objectSid=S-1-5-21-4231626423-2410014848-2360679739-552)", scope=SCOPE_DEFAULT, attrs) - res = self.ldb.search(expression="(objectSid=*)", base=None, - attrs=["dnsHostName", "lastLogon", "objectSid"]) + res = self.ldb.search(expression="(objectSid=*)", base=None, scope=SCOPE_DEFAULT, attrs=["dnsHostName", "lastLogon", "objectSid"]) self.assertEquals(len(res), 3) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=X")) self.assertEquals(res[0]["dnsHostName"], "x") self.assertEquals(res[0]["lastLogon"], "x") - self.assertEquals(res[0]["objectSid"], - "S-1-5-21-4231626423-2410014848-2360679739-552") + # 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.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") - self.assertEquals(res[1]["objectSid"], - "S-1-5-21-4231626423-2410014848-2360679739-552") + # FIXME: Properly compare sid,see above + #self.assertEquals(res[1]["objectSid"], + # "S-1-5-21-4231626423-2410014848-2360679739-552") + self.assertTrue("objectSid" in res[1]) # Search by generated attribute # In most cases, this even works when the mapping is missing @@ -518,7 +522,7 @@ class MapTestCase(MapBaseTestCase): self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) self.assertTrue(not "dnsHostName" in res[0]) self.assertEquals(res[0]["lastLogon"], "y") - self.assertEquals(set(res[0]["objectClass"]), set(["user"])) + self.assertEquals(set(res[0]["objectClass"]), set(["top"])) self.assertEquals(str(res[1].dn), self.samba4.dn("cn=X")) self.assertEquals(res[1]["dnsHostName"], "x") self.assertEquals(res[1]["lastLogon"], "x") @@ -588,13 +592,13 @@ class MapTestCase(MapBaseTestCase): attrs=["dnsHostName", "lastLogon"]) self.assertEquals(len(res), 3) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=B")) - self.assertTrue("dnsHostName" in res[0]) + self.assertFalse("dnsHostName" in res[0]) self.assertEquals(res[0]["lastLogon"], "y") self.assertEquals(str(res[1].dn), self.samba4.dn("cn=X")) self.assertEquals(res[1]["dnsHostName"], "x") self.assertEquals(res[1]["lastLogon"], "x") self.assertEquals(str(res[2].dn), self.samba4.dn("cn=A")) - self.assertTrue("dnsHostName" in res[2]) + self.assertFalse("dnsHostName" in res[2]) self.assertEquals(res[2]["lastLogon"], "x") # Search by disjunction of local and remote attribute @@ -605,7 +609,7 @@ class MapTestCase(MapBaseTestCase): self.assertEquals(res[0]["dnsHostName"], "y") self.assertEquals(res[0]["lastLogon"], "y") self.assertEquals(str(res[1].dn), self.samba4.dn("cn=B")) - self.assertTrue("dnsHostName" in res[1]) + self.assertFalse("dnsHostName" in res[1]) self.assertEquals(res[1]["lastLogon"], "y") self.assertEquals(str(res[2].dn), self.samba4.dn("cn=X")) self.assertEquals(res[2]["dnsHostName"], "x") -- cgit From 8fd66feb88f2756dd8b4b3d586178eac746cfa1e Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 05:43:39 +0200 Subject: Remove remaining obsolete EJS tests. --- testprogs/ejs/base.js | 23 - testprogs/ejs/samba3sam.js | 1263 -------------------------------------------- 2 files changed, 1286 deletions(-) delete mode 100755 testprogs/ejs/base.js delete mode 100644 testprogs/ejs/samba3sam.js diff --git a/testprogs/ejs/base.js b/testprogs/ejs/base.js deleted file mode 100755 index 3c998ee4f8..0000000000 --- a/testprogs/ejs/base.js +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/sh -exec smbscript "$0" ${1+"$@"} - -var options = GetOptions(ARGV, - "POPT_COMMON_SAMBA"); -if (options == undefined) { - println("Failed to parse options"); - return -1; -} - -libinclude("base.js"); - -var obj = new Object(); -obj.FOO = "foo"; -obj.BAR = "bar"; -var str1 = "${FOO}:${BAR}"; -var str2 = "${FOO}:${BAR} "; // note the space after the brace -var sub1 = substitute_var(str1, obj); -var sub2 = substitute_var(str2, obj); - -assert(str1 + " " == str2); -assert(sub1 + " " == sub2); -exit(0); diff --git a/testprogs/ejs/samba3sam.js b/testprogs/ejs/samba3sam.js deleted file mode 100644 index 244074743d..0000000000 --- a/testprogs/ejs/samba3sam.js +++ /dev/null @@ -1,1263 +0,0 @@ -#!/usr/bin/env smbscript -/* - (C) Jelmer Vernooij 2005 - (C) Martin Kuehl 2006 - Published under the GNU GPL - Sponsored by Google Summer of Code - */ - -var sys; -var options = GetOptions(ARGV, "POPT_AUTOHELP", "POPT_COMMON_SAMBA"); -if (options == undefined) { - println("Failed to parse options"); - return -1; -} - -libinclude("base.js"); - -if (options.ARGV.length != 2) { - println("Usage: samba3sam.js "); - return -1; -} - -var prefix = options.ARGV[0]; -var datadir = options.ARGV[1]; - -function setup_data(obj, ldif) -{ - assert(ldif != undefined); - ldif = substitute_var(ldif, obj); - assert(ldif != undefined); - var ok = obj.db.add(ldif); - assert(ok.error == 0); -} - -function setup_modules(ldb, s3, s4, ldif) -{ - assert(ldif != undefined); - ldif = substitute_var(ldif, s4); - assert(ldif != undefined); - var ok = ldb.add(ldif); - assert(ok.error == 0); - - var ldif = " -dn: @MAP=samba3sam -@FROM: " + s4.BASEDN + " -@TO: sambaDomainName=TESTS," + s3.BASEDN + " - -dn: @MODULES -@LIST: rootdse,paged_results,server_sort,extended_dn,asq,samldb,password_hash,operational,objectguid,rdn_name,samba3sam,partition - -dn: @PARTITION -partition: " + s4.BASEDN + ":" + s4.url + " -partition: " + s3.BASEDN + ":" + s3.url + " -replicateEntries: @SUBCLASSES -replicateEntries: @ATTRIBUTES -replicateEntries: @INDEXLIST -"; - var ok = ldb.add(ldif); - assert(ok.error == 0); -} - -function test_s3sam_search(ldb) -{ - println("Looking up by non-mapped attribute"); - var msg = ldb.search("(cn=Administrator)"); - assert(msg.error == 0); - assert(msg.msgs.length == 1); - assert(msg.msgs[0].cn == "Administrator"); - - println("Looking up by mapped attribute"); - var msg = ldb.search("(name=Backup Operators)"); - assert(msg.error == 0); - assert(msg.msgs.length == 1); - assert(msg.msgs[0].name == "Backup Operators"); - - println("Looking up by old name of renamed attribute"); - var msg = ldb.search("(displayName=Backup Operators)"); - assert(msg.msgs.length == 0); - - println("Looking up mapped entry containing SID"); - var msg = ldb.search("(cn=Replicator)"); - assert(msg.error == 0); - assert(msg.msgs.length == 1); - println(msg.msgs[0].dn); - assert(msg.msgs[0].dn == "cn=Replicator,ou=Groups,dc=vernstok,dc=nl"); - assert(msg.msgs[0].objectSid == "S-1-5-21-4231626423-2410014848-2360679739-552"); - - println("Checking mapping of objectClass"); - var oc = msg.msgs[0].objectClass; - assert(oc != undefined); - for (var i in oc) { - assert(oc[i] == "posixGroup" || oc[i] == "group"); - } - - println("Looking up by objectClass"); - var msg = ldb.search("(|(objectClass=user)(cn=Administrator))"); - assert(msg.error == 0); - assert(msg.msgs.length == 2); - for (var i = 0; i < msg.msgs.length; i++) { - assert((msg.msgs[i].dn == "unixName=Administrator,ou=Users,dc=vernstok,dc=nl") || - (msg.msgs[i].dn == "unixName=nobody,ou=Users,dc=vernstok,dc=nl")); - } -} - -function test_s3sam_modify(ldb, s3) -{ - var msg, ok; - println("Adding a record that will be fallbacked"); - ok = ldb.add(" -dn: cn=Foo -foo: bar -blah: Blie -cn: Foo -showInAdvancedViewOnly: TRUE -"); - if (ok.error != 0) { - println(ok.errstr); - assert(ok.error == 0); - } - - println("Checking for existence of record (local)"); - /* TODO: This record must be searched in the local database, which is currently only supported for base searches - * msg = ldb.search("(cn=Foo)", new Array('foo','blah','cn','showInAdvancedViewOnly')); - * TODO: Actually, this version should work as well but doesn't... - * - */ - var attrs = new Array('foo','blah','cn','showInAdvancedViewOnly'); - msg = ldb.search("(cn=Foo)", "cn=Foo", ldb.LDB_SCOPE_BASE, attrs); - assert(msg.error == 0); - assert(msg.msgs.length == 1); - assert(msg.msgs[0].showInAdvancedViewOnly == "TRUE"); - assert(msg.msgs[0].foo == "bar"); - assert(msg.msgs[0].blah == "Blie"); - - println("Adding record that will be mapped"); - ok = ldb.add(" -dn: cn=Niemand,cn=Users,dc=vernstok,dc=nl -objectClass: user -unixName: bin -sambaUnicodePwd: geheim -cn: Niemand -"); - if (ok.error != 0) { - println(ok.errstr); - assert(ok.error == 0); - } - assert(ok.error == 0); - - println("Checking for existence of record (remote)"); - msg = ldb.search("(unixName=bin)", new Array('unixName','cn','dn', 'sambaUnicodePwd')); - assert(msg.error == 0); - assert(msg.msgs.length == 1); - assert(msg.msgs[0].cn == "Niemand"); - assert(msg.msgs[0].sambaUnicodePwd == "geheim"); - - println("Checking for existence of record (local && remote)"); - msg = ldb.search("(&(unixName=bin)(sambaUnicodePwd=geheim))", new Array('unixName','cn','dn', 'sambaUnicodePwd')); - assert(msg.error == 0); - assert(msg.msgs.length == 1); // TODO: should check with more records - assert(msg.msgs[0].cn == "Niemand"); - assert(msg.msgs[0].unixName == "bin"); - assert(msg.msgs[0].sambaUnicodePwd == "geheim"); - - println("Checking for existence of record (local || remote)"); - msg = ldb.search("(|(unixName=bin)(sambaUnicodePwd=geheim))", new Array('unixName','cn','dn', 'sambaUnicodePwd')); - println("got " + msg.msgs.length + " replies"); - assert(msg.error == 0); - assert(msg.msgs.length == 1); // TODO: should check with more records - assert(msg.msgs[0].cn == "Niemand"); - assert(msg.msgs[0].unixName == "bin" || msg.msgs[0].sambaUnicodePwd == "geheim"); - - println("Checking for data in destination database"); - msg = s3.db.search("(cn=Niemand)"); - assert(msg.error == 0); - assert(msg.msgs.length >= 1); - assert(msg.msgs[0].sambaSID == "S-1-5-21-4231626423-2410014848-2360679739-2001"); - assert(msg.msgs[0].displayName == "Niemand"); - - println("Adding attribute..."); - ok = ldb.modify(" -dn: cn=Niemand,cn=Users,dc=vernstok,dc=nl -changetype: modify -add: description -description: Blah -"); - if (ok.error != 0) { - println(ok.errstr); - assert(ok.error == 0); - } - assert(ok.error == 0); - - println("Checking whether changes are still there..."); - msg = ldb.search("(cn=Niemand)"); - assert(msg.error == 0); - assert(msg.msgs.length >= 1); - assert(msg.msgs[0].cn == "Niemand"); - assert(msg.msgs[0].description == "Blah"); - - println("Modifying attribute..."); - ok = ldb.modify(" -dn: cn=Niemand,cn=Users,dc=vernstok,dc=nl -changetype: modify -replace: description -description: Blie -"); - if (ok.error != 0) { - println(ok.errstr); - assert(ok.error == 0); - } - assert(ok.error == 0); - - println("Checking whether changes are still there..."); - msg = ldb.search("(cn=Niemand)"); - assert(msg.error == 0); - assert(msg.msgs.length >= 1); - assert(msg.msgs[0].description == "Blie"); - - println("Deleting attribute..."); - ok = ldb.modify(" -dn: cn=Niemand,cn=Users,dc=vernstok,dc=nl -changetype: modify -delete: description -"); - if (ok.error != 0) { - println(ok.errstr); - assert(ok.error == 0); - } - assert(ok.error == 0); - - println("Checking whether changes are no longer there..."); - msg = ldb.search("(cn=Niemand)"); - assert(msg.error == 0); - assert(msg.msgs.length >= 1); - assert(msg.msgs[0].description == undefined); - - println("Renaming record..."); - ok = ldb.rename("cn=Niemand,cn=Users,dc=vernstok,dc=nl", "cn=Niemand2,cn=Users,dc=vernstok,dc=nl"); - assert(ok.error == 0); - - println("Checking whether DN has changed..."); - msg = ldb.search("(cn=Niemand2)"); - assert(msg.error == 0); - assert(msg.msgs.length == 1); - assert(msg.msgs[0].dn == "cn=Niemand2,cn=Users,dc=vernstok,dc=nl"); - - println("Deleting record..."); - ok = ldb.del("cn=Niemand2,cn=Users,dc=vernstok,dc=nl"); - if (ok.error != 0) { - println(ok.errstr); - assert(ok.error == 0); - } - - println("Checking whether record is gone..."); - msg = ldb.search("(cn=Niemand2)"); - assert(msg.error == 0); - assert(msg.msgs.length == 0); -} - -function test_map_search(ldb, s3, s4) -{ - println("Running search tests on mapped data"); - var res; - var dn; - var attrs; - - - var ldif = " -dn: " + "sambaDomainName=TESTS," + s3.BASEDN + " -objectclass: sambaDomain -objectclass: top -sambaSID: S-1-5-21-4231626423-2410014848-2360679739 -sambaNextRid: 2000 -sambaDomainName: TESTS" - ldif = substitute_var(ldif, s3); - assert(ldif != undefined); - var ok = s3.db.add(ldif); - assert(ok.error == 0); - - printf("Add a set of split records"); - var ldif = " -dn: " + s4.dn("cn=X") + " -objectClass: user -cn: X -codePage: x -revision: x -dnsHostName: x -nextRid: y -lastLogon: x -description: x -objectSid: S-1-5-21-4231626423-2410014848-2360679739-552 -primaryGroupID: 1-5-21-4231626423-2410014848-2360679739-512 - -dn: " + s4.dn("cn=Y") + " -objectClass: top -cn: Y -codePage: x -revision: x -dnsHostName: y -nextRid: y -lastLogon: y -description: x - -dn: " + s4.dn("cn=Z") + " -objectClass: top -cn: Z -codePage: x -revision: y -dnsHostName: z -nextRid: y -lastLogon: z -description: y -"; - - ldif = substitute_var(ldif, s4); - assert(ldif != undefined); - var ok = ldb.add(ldif); - if (ok.error != 0) { - println(ok.errstr); - assert(ok.error == 0); - } - - println("Add a set of remote records"); - - var ldif = " -dn: " + s3.dn("cn=A") + " -objectClass: posixAccount -cn: A -sambaNextRid: x -sambaBadPasswordCount: x -sambaLogonTime: x -description: x -sambaSID: S-1-5-21-4231626423-2410014848-2360679739-552 -sambaPrimaryGroupSID: S-1-5-21-4231626423-2410014848-2360679739-512 - -dn: " + s3.dn("cn=B") + " -objectClass: top -cn:B -sambaNextRid: x -sambaBadPasswordCount: x -sambaLogonTime: y -description: x - -dn: " + s3.dn("cn=C") + " -objectClass: top -cn: C -sambaNextRid: x -sambaBadPasswordCount: y -sambaLogonTime: z -description: y -"; - ldif = substitute_var(ldif, s3); - assert(ldif != undefined); - var ok = s3.db.add(ldif); - assert(ok.error == 0); - - println("Testing search by DN"); - - /* Search remote record by local DN */ - dn = s4.dn("cn=A"); - attrs = new Array("dnsHostName", "lastLogon"); - res = ldb.search("", dn, ldb.SCOPE_BASE, attrs); - assert(res.error == 0); - assert(res.msgs.length == 1); - assert(res.msgs[0].dn == dn); - assert(res.msgs[0].dnsHostName == undefined); - assert(res.msgs[0].lastLogon == "x"); - - /* Search remote record by remote DN */ - dn = s3.dn("cn=A"); - attrs = new Array("dnsHostName", "lastLogon", "sambaLogonTime"); - res = s3.db.search("", dn, ldb.SCOPE_BASE, attrs); - assert(res.error == 0); - assert(res.msgs.length == 1); - assert(res.msgs[0].dn == dn); - assert(res.msgs[0].dnsHostName == undefined); - assert(res.msgs[0].lastLogon == undefined); - assert(res.msgs[0].sambaLogonTime == "x"); - - /* Search split record by local DN */ - dn = s4.dn("cn=X"); - attrs = new Array("dnsHostName", "lastLogon"); - res = ldb.search("", dn, ldb.SCOPE_BASE, attrs); - assert(res.error == 0); - assert(res.msgs.length == 1); - assert(res.msgs[0].dn == dn); - assert(res.msgs[0].dnsHostName == "x"); - assert(res.msgs[0].lastLogon == "x"); - - /* Search split record by remote DN */ - dn = s3.dn("cn=X"); - attrs = new Array("dnsHostName", "lastLogon", "sambaLogonTime"); - res = s3.db.search("", dn, ldb.SCOPE_BASE, attrs); - assert(res.error == 0); - assert(res.msgs.length == 1); - assert(res.msgs[0].dn == dn); - assert(res.msgs[0].dnsHostName == undefined); - assert(res.msgs[0].lastLogon == undefined); - assert(res.msgs[0].sambaLogonTime == "x"); - - println("Testing search by attribute"); - - /* Search by ignored attribute */ - attrs = new Array("dnsHostName", "lastLogon"); - res = ldb.search("(revision=x)", NULL, ldb. SCOPE_DEFAULT, attrs); - assert(res.error == 0); - assert(res.msgs.length == 2); - assert(res.msgs[0].dn == s4.dn("cn=Y")); - assert(res.msgs[0].dnsHostName == "y"); - assert(res.msgs[0].lastLogon == "y"); - assert(res.msgs[1].dn == s4.dn("cn=X")); - assert(res.msgs[1].dnsHostName == "x"); - assert(res.msgs[1].lastLogon == "x"); - - /* Search by kept attribute */ - attrs = new Array("dnsHostName", "lastLogon"); - res = ldb.search("(description=y)", NULL, ldb. SCOPE_DEFAULT, attrs); - assert(res.error == 0); - assert(res.msgs.length == 2); - assert(res.msgs[0].dn == s4.dn("cn=Z")); - assert(res.msgs[0].dnsHostName == "z"); - assert(res.msgs[0].lastLogon == "z"); - assert(res.msgs[1].dn == s4.dn("cn=C")); - assert(res.msgs[1].dnsHostName == undefined); - assert(res.msgs[1].lastLogon == "z"); - - /* Search by renamed attribute */ - attrs = new Array("dnsHostName", "lastLogon"); - res = ldb.search("(badPwdCount=x)", NULL, ldb. SCOPE_DEFAULT, attrs); - assert(res.error == 0); - assert(res.msgs.length == 2); - assert(res.msgs[0].dn == s4.dn("cn=B")); - assert(res.msgs[0].dnsHostName == undefined); - assert(res.msgs[0].lastLogon == "y"); - assert(res.msgs[1].dn == s4.dn("cn=A")); - assert(res.msgs[1].dnsHostName == undefined); - assert(res.msgs[1].lastLogon == "x"); - - /* Search by converted attribute */ - attrs = new Array("dnsHostName", "lastLogon", "objectSid"); - /* TODO: - Using the SID directly in the parse tree leads to conversion - errors, letting the search fail with no results. - res = ldb.search("(objectSid=S-1-5-21-4231626423-2410014848-2360679739-552)", NULL, ldb. SCOPE_DEFAULT, attrs); - */ - res = ldb.search("(objectSid=*)", NULL, ldb. SCOPE_DEFAULT, attrs); - assert(res.error == 0); - assert(res.msgs.length == 3); - assert(res.msgs[0].dn == s4.dn("cn=X")); - assert(res.msgs[0].dnsHostName == "x"); - assert(res.msgs[0].lastLogon == "x"); - assert(res.msgs[0].objectSid == "S-1-5-21-4231626423-2410014848-2360679739-552"); - assert(res.msgs[1].dn == s4.dn("cn=A")); - assert(res.msgs[1].dnsHostName == undefined); - assert(res.msgs[1].lastLogon == "x"); - assert(res.msgs[1].objectSid == "S-1-5-21-4231626423-2410014848-2360679739-552"); - - /* Search by generated attribute */ - /* In most cases, this even works when the mapping is missing - * a `convert_operator' by enumerating the remote db. */ - attrs = new Array("dnsHostName", "lastLogon", "primaryGroupID"); - res = ldb.search("(primaryGroupID=512)", NULL, ldb. SCOPE_DEFAULT, attrs); - assert(res.error == 0); - assert(res.msgs.length == 1); - assert(res.msgs[0].dn == s4.dn("cn=A")); - assert(res.msgs[0].dnsHostName == undefined); - assert(res.msgs[0].lastLogon == "x"); - assert(res.msgs[0].primaryGroupID == "512"); - - /* TODO: There should actually be two results, A and X. The - * primaryGroupID of X seems to get corrupted somewhere, and the - * objectSid isn't available during the generation of remote (!) data, - * which can be observed with the following search. Also note that Xs - * objectSid seems to be fine in the previous search for objectSid... */ - /* - res = ldb.search("(primaryGroupID=*)", NULL, ldb. SCOPE_DEFAULT, attrs); - println(res.msgs.length + " results found"); - for (i=0;i Date: Sun, 21 Sep 2008 15:08:16 +0200 Subject: Stop installing JS libraries. --- source4/script/installmisc.sh | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/source4/script/installmisc.sh b/source4/script/installmisc.sh index 5f7e11f083..eb347307ba 100755 --- a/source4/script/installmisc.sh +++ b/source4/script/installmisc.sh @@ -2,16 +2,11 @@ # install miscellaneous files SRCDIR="$1" -JSDIR="$2" -SETUPDIR="$3" -BINDIR="$4" +SETUPDIR="$2" +BINDIR="$3" cd $SRCDIR || exit 1 -echo "Installing js libs" -mkdir -p $JSDIR || exit 1 -cp scripting/libjs/*.js $JSDIR || exit 1 - echo "Installing setup templates" mkdir -p $SETUPDIR || exit 1 cp setup/schema-map-* $SETUPDIR || exit 1 -- cgit From da987d8fb407a1386462e295f61ff7dcfb757d1d Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 15:55:08 +0200 Subject: No longer set PATH during selftest, was only required for smbscript. --- source4/selftest/selftest.pl | 2 -- 1 file changed, 2 deletions(-) diff --git a/source4/selftest/selftest.pl b/source4/selftest/selftest.pl index b6a31ac20e..51a354c7a4 100755 --- a/source4/selftest/selftest.pl +++ b/source4/selftest/selftest.pl @@ -417,8 +417,6 @@ sub prefix_pathvar($$) } } prefix_pathvar("PKG_CONFIG_PATH", "$old_pwd/bin/pkgconfig"); -# Required for smbscript: -prefix_pathvar("PATH", "$old_pwd/bin"); prefix_pathvar("PYTHONPATH", "$old_pwd/bin/python"); if ($opt_socket_wrapper_keep_pcap) { -- cgit From ef5a04485ae256f9b803da9173d6194ced82e358 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 23 May 2008 20:40:05 +0200 Subject: Rename http to esp, in preparation of adding a python backend. --- source4/web_server/config.mk | 2 +- source4/web_server/esp.c | 1030 +++++++++++++++++++++++++++++++++++++++ source4/web_server/http.c | 1030 --------------------------------------- source4/web_server/web_server.c | 4 +- 4 files changed, 1033 insertions(+), 1033 deletions(-) create mode 100644 source4/web_server/esp.c delete mode 100644 source4/web_server/http.c diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index 02f686af0b..4094d6be07 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -10,6 +10,6 @@ PRIVATE_DEPENDENCIES = ESP LIBTLS smbcalls process_model # End SUBSYSTEM WEB ####################### -WEB_OBJ_FILES = $(addprefix $(web_serversrcdir)/, web_server.o http.o) +WEB_OBJ_FILES = $(addprefix $(web_serversrcdir)/, web_server.o esp.o) $(eval $(call proto_header_template,$(web_serversrcdir)/proto.h,$(WEB_OBJ_FILES:.o=.c))) diff --git a/source4/web_server/esp.c b/source4/web_server/esp.c new file mode 100644 index 0000000000..901a1558c4 --- /dev/null +++ b/source4/web_server/esp.c @@ -0,0 +1,1030 @@ +/* + Unix SMB/CIFS implementation. + + http handling code + + Copyright (C) Andrew Tridgell 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 . +*/ + +#include "includes.h" +#include "smbd/service_task.h" +#include "web_server/web_server.h" +#include "smbd/service_stream.h" +#include "smbd/service.h" +#include "lib/events/events.h" +#include "system/time.h" +#include "system/wait.h" +#include "lib/appweb/esp/esp.h" +#include "lib/appweb/ejs/ejsInternal.h" +#include "lib/util/dlinklist.h" +#include "lib/tls/tls.h" +#include "scripting/ejs/smbcalls.h" +#include "param/param.h" + +#define SAMBA_SESSION_KEY "SambaSessionId" +#define HTTP_PREAUTH_URI "/scripting/preauth.esp" + +/* state of the esp subsystem for a specific request */ +struct esp_state { + struct websrv_context *web; + struct EspRequest *req; + struct MprVar variables[ESP_OBJ_MAX]; + struct session_data *session; +}; + +/* + output the http headers +*/ +static void http_output_headers(struct websrv_context *web) +{ + int i; + char *s; + DATA_BLOB b; + uint32_t content_length = 0; + const char *response_string = "Unknown Code"; + const struct { + unsigned code; + const char *response_string; + } codes[] = { + { 200, "OK" }, + { 301, "Moved" }, + { 302, "Found" }, + { 303, "Method" }, + { 304, "Not Modified" }, + { 400, "Bad request" }, + { 401, "Unauthorized" }, + { 403, "Forbidden" }, + { 404, "Not Found" }, + { 500, "Internal Server Error" }, + { 501, "Not implemented" } + }; + for (i=0;ioutput.response_code) { + response_string = codes[i].response_string; + } + } + + if (web->output.headers == NULL) return; + s = talloc_asprintf(web, "HTTP/1.0 %u %s\r\n", + web->output.response_code, response_string); + if (s == NULL) return; + for (i=0;web->output.headers[i];i++) { + s = talloc_asprintf_append_buffer(s, "%s\r\n", web->output.headers[i]); + } + + /* work out the content length */ + content_length = web->output.content.length; + if (web->output.fd != -1) { + struct stat st; + fstat(web->output.fd, &st); + content_length += st.st_size; + } + s = talloc_asprintf_append_buffer(s, "Content-Length: %u\r\n\r\n", content_length); + if (s == NULL) return; + + b = web->output.content; + web->output.content = data_blob_string_const(s); + data_blob_append(web, &web->output.content, b.data, b.length); + data_blob_free(&b); +} + +/* + return the local path for a URL +*/ +static const char *http_local_path(struct websrv_context *web, + const char *url, + const char *base_dir) +{ + int i; + char *path; + + /* check that the url is OK */ + if (url[0] != '/') return NULL; + + for (i=0;url[i];i++) { + if ((!isalnum((unsigned char)url[i]) && !strchr("./_-", url[i])) || + (url[i] == '.' && strchr("/.", url[i+1]))) { + return NULL; + } + } + + path = talloc_asprintf(web, "%s/%s", base_dir, url+1); + if (path == NULL) return NULL; + + if (directory_exist(path)) { + path = talloc_asprintf_append_buffer(path, "/index.esp"); + } + return path; +} + +/* + called when esp wants to read a file to support include() calls +*/ +static int http_readFile(EspHandle handle, + char **buf, + int *len, + const char *path, + const char *base_dir) +{ + struct websrv_context *web = talloc_get_type(handle, + struct websrv_context); + int fd = -1; + struct stat st; + *buf = NULL; + + path = http_local_path(web, path, base_dir); + if (path == NULL) goto failed; + + fd = open(path, O_RDONLY); + if (fd == -1 || fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) goto failed; + + *buf = talloc_array(handle, char, st.st_size+1); + if (*buf == NULL) goto failed; + + if (read(fd, *buf, st.st_size) != st.st_size) goto failed; + + (*buf)[st.st_size] = 0; + + close(fd); + *len = st.st_size; + return 0; + +failed: + DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno))); + if (fd != -1) close(fd); + talloc_free(*buf); + *buf = NULL; + return -1; +} + +static int http_readFileFromSwatDir(EspHandle handle, char **buf, int *len, + const char *path) +{ + return http_readFile(handle, buf, len, path, + lp_swat_directory(global_loadparm)); +} + + + +/* + called when esp wants to find the real path of a file +*/ +static int http_mapToStorage(EspHandle handle, char *path, int len, const char *uri, int flags) +{ + if (uri == NULL || strlen(uri) >= len) return -1; + strncpy(path, uri, len); + return 0; +} + +/* + called when esp wants to output something +*/ +static int http_writeBlock(EspHandle handle, const char *buf, int size) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + if (!data_blob_append(web, &web->output.content, buf, size)) + return -1; + return size; +} + + +/* + set a http header +*/ +static void http_setHeader(EspHandle handle, const char *value, bool allowMultiple) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + char *p = strchr(value, ':'); + + if (p && !allowMultiple && web->output.headers) { + int i; + for (i=0;web->output.headers[i];i++) { + if (strncmp(web->output.headers[i], value, (p+1)-value) == 0) { + web->output.headers[i] = talloc_strdup(web, value); + return; + } + } + } + + web->output.headers = str_list_add(web->output.headers, value); + talloc_steal(web, web->output.headers); +} + +/* + set a http response code +*/ +static void http_setResponseCode(EspHandle handle, int code) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + web->output.response_code = code; +} + +/* + redirect to another web page + */ +static void http_redirect(EspHandle handle, int code, char *url) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + const char *host = web->input.host; + + /* form the full url, unless it already looks like a url */ + if (strchr(url, ':') == NULL) { + if (host == NULL) { + struct socket_address *socket_address = socket_get_my_addr(web->conn->socket, web); + if (socket_address == NULL) goto internal_error; + host = talloc_asprintf(web, "%s:%u", + socket_address->addr, socket_address->port); + } + if (host == NULL) goto internal_error; + if (url[0] != '/') { + char *p = strrchr(web->input.url, '/'); + if (p == web->input.url) { + url = talloc_asprintf(web, "http%s://%s/%s", + tls_enabled(web->conn->socket)?"s":"", + host, url); + } else { + int dirlen = p - web->input.url; + url = talloc_asprintf(web, "http%s://%s%*.*s/%s", + tls_enabled(web->conn->socket)?"s":"", + host, + dirlen, dirlen, web->input.url, + url); + } + if (url == NULL) goto internal_error; + } + } + + http_setHeader(handle, talloc_asprintf(web, "Location: %s", url), 0); + + /* make sure we give a valid redirect code */ + if (code >= 300 && code < 400) { + http_setResponseCode(handle, code); + } else { + http_setResponseCode(handle, 302); + } + return; + +internal_error: + http_error(web, 500, "Internal server error"); +} + + +/* + setup a cookie +*/ +static void http_setCookie(EspHandle handle, const char *name, const char *value, + int lifetime, const char *path, bool secure) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + char *buf; + + if (lifetime > 0) { + buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; Expires=%s; %s", + name, value, path?path:"/", + http_timestring(web, time(NULL)+lifetime), + secure?"secure":""); + } else { + buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; %s", + name, value, path?path:"/", + secure?"secure":""); + } + http_setHeader(handle, "Cache-control: no-cache=\"set-cookie\"", 0); + http_setHeader(handle, buf, 0); + talloc_free(buf); +} + +/* + return the session id +*/ +static const char *http_getSessionId(EspHandle handle) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + return web->session->id; +} + +/* + setup a session +*/ +static void http_createSession(EspHandle handle, int timeout) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + if (web->session) { + web->session->lifetime = timeout; + http_setCookie(web, SAMBA_SESSION_KEY, web->session->id, + web->session->lifetime, "/", 0); + } +} + +/* + destroy a session +*/ +static void http_destroySession(EspHandle handle) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + talloc_free(web->session); + web->session = NULL; +} + + +/* + setup for a raw http level error +*/ +void http_error(struct websrv_context *web, int code, const char *info) +{ + char *s; + s = talloc_asprintf(web,"Error %u

Error %u

%s

\r\n\r\n", + code, code, info); + if (s == NULL) { + stream_terminate_connection(web->conn, "http_error: out of memory"); + return; + } + http_writeBlock(web, s, strlen(s)); + http_setResponseCode(web, code); + http_output_headers(web); + EVENT_FD_NOT_READABLE(web->conn->event.fde); + EVENT_FD_WRITEABLE(web->conn->event.fde); + web->output.output_pending = true; +} + +/* + map a unix error code to a http error +*/ +void http_error_unix(struct websrv_context *web, const char *info) +{ + int code = 500; + switch (errno) { + case ENOENT: + case EISDIR: + code = 404; + break; + case EACCES: + code = 403; + break; + } + info = talloc_asprintf(web, "%s

%s

\n", info, strerror(errno)); + http_error(web, code, info); +} + + +/* + a simple file request +*/ +static void http_simple_request(struct websrv_context *web) +{ + const char *url = web->input.url; + const char *path; + struct stat st; + + path = http_local_path(web, url, lp_swat_directory(web->task->lp_ctx)); + if (path == NULL) goto invalid; + + /* looks ok */ + web->output.fd = open(path, O_RDONLY); + if (web->output.fd == -1) { + DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno))); + http_error_unix(web, path); + return; + } + + if (fstat(web->output.fd, &st) != 0 || !S_ISREG(st.st_mode)) { + close(web->output.fd); + goto invalid; + } + + return; + +invalid: + http_error(web, 400, "Malformed URL"); +} + +/* + setup the standard ESP arrays +*/ +static void http_setup_arrays(struct esp_state *esp) +{ + struct websrv_context *web = esp->web; + struct esp_data *edata = talloc_get_type(web->task->private, struct esp_data); + struct EspRequest *req = esp->req; + struct socket_address *socket_address = socket_get_my_addr(web->conn->socket, esp); + struct socket_address *peer_address = socket_get_peer_addr(web->conn->socket, esp); + char *p; + +#define SETVAR(type, name, value) do { \ + const char *v = value; \ + if (v) espSetStringVar(req, type, name, v); \ +} while (0) + + SETVAR(ESP_REQUEST_OBJ, "CONTENT_LENGTH", + talloc_asprintf(esp, "%u", web->input.content_length)); + SETVAR(ESP_REQUEST_OBJ, "QUERY_STRING", web->input.query_string); + SETVAR(ESP_REQUEST_OBJ, "POST_DATA", + talloc_strndup(esp, + web->input.partial.data, + web->input.partial.length)); + SETVAR(ESP_REQUEST_OBJ, "REQUEST_METHOD", web->input.post_request?"POST":"GET"); + SETVAR(ESP_REQUEST_OBJ, "REQUEST_URI", web->input.url); + p = strrchr(web->input.url, '/'); + SETVAR(ESP_REQUEST_OBJ, "SCRIPT_NAME", p+1); + SETVAR(ESP_REQUEST_OBJ, "SCRIPT_FILENAME", web->input.url); + if (peer_address) { + struct MprVar mpv = mprObject("socket_address"); + mprSetPtrChild(&mpv, "socket_address", peer_address); + espSetVar(req, ESP_REQUEST_OBJ, "REMOTE_SOCKET_ADDRESS", mpv); + SETVAR(ESP_REQUEST_OBJ, "REMOTE_ADDR", peer_address->addr); + } + p = socket_get_peer_name(web->conn->socket, esp); + SETVAR(ESP_REQUEST_OBJ, "REMOTE_HOST", p); + SETVAR(ESP_REQUEST_OBJ, "REMOTE_USER", ""); + SETVAR(ESP_REQUEST_OBJ, "CONTENT_TYPE", web->input.content_type); + if (web->session) { + SETVAR(ESP_REQUEST_OBJ, "SESSION_ID", web->session->id); + } + SETVAR(ESP_REQUEST_OBJ, "COOKIE_SUPPORT", web->input.cookie?"true":"false"); + + SETVAR(ESP_HEADERS_OBJ, "HTTP_REFERER", web->input.referer); + SETVAR(ESP_HEADERS_OBJ, "HOST", web->input.host); + SETVAR(ESP_HEADERS_OBJ, "ACCEPT_ENCODING", web->input.accept_encoding); + SETVAR(ESP_HEADERS_OBJ, "ACCEPT_LANGUAGE", web->input.accept_language); + SETVAR(ESP_HEADERS_OBJ, "ACCEPT_CHARSET", web->input.accept_charset); + SETVAR(ESP_HEADERS_OBJ, "COOKIE", web->input.cookie); + SETVAR(ESP_HEADERS_OBJ, "USER_AGENT", web->input.user_agent); + + if (socket_address) { + SETVAR(ESP_SERVER_OBJ, "SERVER_ADDR", socket_address->addr); + SETVAR(ESP_SERVER_OBJ, "SERVER_NAME", socket_address->addr); + SETVAR(ESP_SERVER_OBJ, "SERVER_HOST", socket_address->addr); + SETVAR(ESP_SERVER_OBJ, "SERVER_PORT", + talloc_asprintf(esp, "%u", socket_address->port)); + } + + SETVAR(ESP_SERVER_OBJ, "DOCUMENT_ROOT", lp_swat_directory(esp->web->task->lp_ctx)); + SETVAR(ESP_SERVER_OBJ, "SERVER_PROTOCOL", tls_enabled(web->conn->socket)?"https":"http"); + SETVAR(ESP_SERVER_OBJ, "SERVER_SOFTWARE", "SAMBA"); + SETVAR(ESP_SERVER_OBJ, "GATEWAY_INTERFACE", "CGI/1.1"); + SETVAR(ESP_SERVER_OBJ, "TLS_SUPPORT", tls_support(edata->tls_params)?"true":"false"); +} + +#if HAVE_SETJMP_H +/* the esp scripting lirary generates exceptions when + it hits a major error. We need to catch these and + report a internal server error via http +*/ +static jmp_buf ejs_exception_buf; +static const char *exception_reason; + +static void web_server_ejs_exception(const char *reason) +{ + Ejs *ep = ejsPtr(0); + if (ep) { + ejsSetErrorMsg(0, "%s", reason); + exception_reason = ep->error; + } else { + exception_reason = reason; + } + DEBUG(0,("%s", exception_reason)); + longjmp(ejs_exception_buf, -1); +} +#else +static void web_server_ejs_exception(const char *reason) +{ + DEBUG(0,("%s", reason)); + smb_panic(reason); +} +#endif + +/* + process a esp request +*/ +static void esp_request(struct esp_state *esp, const char *url) +{ + struct websrv_context *web = esp->web; + int size; + int res; + char *emsg = NULL, *buf; + + if (http_readFile(web, &buf, &size, url, lp_swat_directory(esp->web->task->lp_ctx)) != 0) { + http_error_unix(web, url); + return; + } + +#if HAVE_SETJMP_H + if (setjmp(ejs_exception_buf) != 0) { + http_error(web, 500, exception_reason); + return; + } +#endif + + res = espProcessRequest(esp->req, url, buf, &emsg); + if (res != 0 && emsg) { + http_writeBlock(web, "

", 5);
+		http_writeBlock(web, emsg, strlen(emsg));
+		http_writeBlock(web, "
", 6); + } + talloc_free(buf); +} + +/* + perform pre-authentication on every page if /scripting/preauth.esp + exists. If this script generates any non-whitepace output at all, + then we don't run the requested URL. + + note that the preauth is run even for static pages such as images +*/ +static bool http_preauth(struct esp_state *esp) +{ + const char *path = http_local_path(esp->web, + HTTP_PREAUTH_URI, + lp_swat_directory(esp->web->task->lp_ctx)); + int i; + if (path == NULL) { + http_error(esp->web, 500, "Internal server error"); + return false; + } + if (!file_exist(path)) { + /* if the preath script is not installed then allow access */ + return true; + } + esp_request(esp, HTTP_PREAUTH_URI); + for (i=0;iweb->output.content.length;i++) { + if (!isspace(esp->web->output.content.data[i])) { + /* if the preauth has generated content, then force it + to be html, so that we can show the login page for + failed access to images */ + http_setHeader(esp->web, "Content-Type: text/html", 0); + return false; + } + } + data_blob_free(&esp->web->output.content); + return true; +} + + +/* + handling of + and % escapes in http variables +*/ +static const char *http_unescape(TALLOC_CTX *mem_ctx, const char *p) +{ + char *s0 = talloc_strdup(mem_ctx, p); + char *s = s0; + if (s == NULL) return NULL; + + while (*s) { + unsigned v; + if (*s == '+') *s = ' '; + if (*s == '%' && sscanf(s+1, "%02x", &v) == 1) { + *s = (char)v; + memmove(s+1, s+3, strlen(s+3)+1); + } + s++; + } + + return s0; +} + +/* + set a form or GET variable +*/ +static void esp_putvar(struct esp_state *esp, const char *var, const char *value) +{ + if (strcasecmp(var, SAMBA_SESSION_KEY) == 0) { + /* special case support for browsers without cookie + support */ + esp->web->input.session_key = talloc_strdup(esp, value); + } else { + mprSetPropertyValue(&esp->variables[ESP_FORM_OBJ], + http_unescape(esp, var), + mprCreateStringVar(http_unescape(esp, value), 0)); + } +} + + +/* + parse the variables in a POST style request +*/ +static NTSTATUS http_parse_post(struct esp_state *esp) +{ + DATA_BLOB b = esp->web->input.partial; + + while (b.length) { + char *p, *line; + size_t len; + + p = memchr(b.data, '&', b.length); + if (p == NULL) { + len = b.length; + } else { + len = p - (char *)b.data; + } + line = talloc_strndup(esp, (char *)b.data, len); + NT_STATUS_HAVE_NO_MEMORY(line); + + p = strchr(line,'='); + if (p) { + *p = 0; + esp_putvar(esp, line, p+1); + } + talloc_free(line); + b.length -= len; + b.data += len; + if (b.length > 0) { + b.length--; + b.data++; + } + } + + return NT_STATUS_OK; +} + +/* + parse the variables in a GET style request +*/ +static NTSTATUS http_parse_get(struct esp_state *esp) +{ + struct websrv_context *web = esp->web; + char *p, *s, *tok; + char *pp; + + p = strchr(web->input.url, '?'); + web->input.query_string = p+1; + *p = 0; + + s = talloc_strdup(esp, esp->web->input.query_string); + NT_STATUS_HAVE_NO_MEMORY(s); + + for (tok=strtok_r(s,"&;", &pp);tok;tok=strtok_r(NULL,"&;", &pp)) { + p = strchr(tok,'='); + if (p) { + *p = 0; + esp_putvar(esp, tok, p+1); + } + } + return NT_STATUS_OK; +} + +/* + called when a session times out +*/ +static void session_timeout(struct event_context *ev, struct timed_event *te, + struct timeval t, void *private) +{ + struct session_data *s = talloc_get_type(private, struct session_data); + talloc_free(s); +} + +/* + destroy a session + */ +static int session_destructor(struct session_data *s) +{ + DLIST_REMOVE(s->edata->sessions, s); + return 0; +} + +/* + setup the session for this request +*/ +static void http_setup_session(struct esp_state *esp) +{ + const char *session_key = SAMBA_SESSION_KEY; + char *p; + const char *cookie = esp->web->input.cookie; + const char *key = NULL; + struct esp_data *edata = talloc_get_type(esp->web->task->private, struct esp_data); + struct session_data *s; + bool generated_key = false; + + /* look for our session key */ + if (cookie && (p = strstr(cookie, session_key)) && + p[strlen(session_key)] == '=') { + p += strlen(session_key)+1; + key = talloc_strndup(esp, p, strcspn(p, ";")); + } + + if (key == NULL && esp->web->input.session_key) { + key = esp->web->input.session_key; + } else if (key == NULL) { + key = generate_random_str_list(esp, 16, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + generated_key = true; + } + + /* try to find this session in the existing session list */ + for (s=edata->sessions;s;s=s->next) { + if (strcmp(key, s->id) == 0) { + break; + } + } + + if (s == NULL) { + /* create a new session */ + s = talloc_zero(edata, struct session_data); + s->id = talloc_steal(s, key); + s->data = NULL; + s->te = NULL; + s->edata = edata; + s->lifetime = lp_parm_int(esp->web->task->lp_ctx, NULL, "web", "sessiontimeout", 900); + DLIST_ADD(edata->sessions, s); + talloc_set_destructor(s, session_destructor); + if (!generated_key) { + mprSetPropertyValue(&esp->variables[ESP_REQUEST_OBJ], + "SESSION_EXPIRED", mprCreateStringVar("true", 0)); + } + } + + http_setCookie(esp->web, session_key, key, s->lifetime, "/", 0); + + if (s->data) { + mprCopyVar(&esp->variables[ESP_SESSION_OBJ], s->data, MPR_DEEP_COPY); + } + + esp->web->session = s; +} + + +/* callbacks for esp processing */ +static const struct Esp esp_control = { + .maxScriptSize = 60000, + .writeBlock = http_writeBlock, + .setHeader = http_setHeader, + .redirect = http_redirect, + .setResponseCode = http_setResponseCode, + .readFile = http_readFileFromSwatDir, + .mapToStorage = http_mapToStorage, + .setCookie = http_setCookie, + .createSession = http_createSession, + .destroySession = http_destroySession, + .getSessionId = http_getSessionId +}; + +/* + process a complete http request +*/ +void http_process_input(struct websrv_context *web) +{ + NTSTATUS status; + struct esp_state *esp = NULL; + struct esp_data *edata = talloc_get_type(web->task->private, struct esp_data); + struct smbcalls_context *smbcalls_ctx; + char *p; + void *save_mpr_ctx = mprMemCtx(); + void *ejs_save = ejs_save_state(); + int i; + const char *file_type = NULL; + enum page_type { + page_type_simple, + page_type_esp + }; + enum page_type page_type; + const struct { + const char *extension; + const char *mime_type; + enum page_type page_type; + } mime_types[] = { + {"gif", "image/gif"}, + {"png", "image/png"}, + {"jpg", "image/jpeg"}, + {"txt", "text/plain"}, + {"ico", "image/x-icon"}, + {"css", "text/css"}, + {"esp", "text/html", true} + }; + + /* + * give the smbcalls a chance to find the event context + * and messaging context + */ + smbcalls_ctx = talloc(web, struct smbcalls_context); + if (smbcalls_ctx == NULL) goto internal_error; + smbcalls_ctx->event_ctx = web->conn->event.ctx; + smbcalls_ctx->msg_ctx = web->conn->msg_ctx; + + esp = talloc_zero(smbcalls_ctx, struct esp_state); + if (esp == NULL) goto internal_error; + + esp->web = web; + + mprSetCtx(esp); + + if (espOpen(&esp_control) != 0) goto internal_error; + + for (i=0;ivariables);i++) { + esp->variables[i] = mprCreateUndefinedVar(); + } + esp->variables[ESP_HEADERS_OBJ] = mprCreateObjVar("headers", ESP_HASH_SIZE); + esp->variables[ESP_FORM_OBJ] = mprCreateObjVar("form", ESP_HASH_SIZE); + esp->variables[ESP_APPLICATION_OBJ] = mprCreateObjVar("application", ESP_HASH_SIZE); + esp->variables[ESP_COOKIES_OBJ] = mprCreateObjVar("cookies", ESP_HASH_SIZE); + esp->variables[ESP_FILES_OBJ] = mprCreateObjVar("files", ESP_HASH_SIZE); + esp->variables[ESP_REQUEST_OBJ] = mprCreateObjVar("request", ESP_HASH_SIZE); + esp->variables[ESP_SERVER_OBJ] = mprCreateObjVar("server", ESP_HASH_SIZE); + esp->variables[ESP_SESSION_OBJ] = mprCreateObjVar("session", ESP_HASH_SIZE); + + if (edata->application_data) { + mprCopyVar(&esp->variables[ESP_APPLICATION_OBJ], + edata->application_data, MPR_DEEP_COPY); + } + + smb_setup_ejs_functions(web_server_ejs_exception); + + if (web->input.url == NULL) { + http_error(web, 400, "You must specify a GET or POST request"); + mprSetCtx(save_mpr_ctx); + ejs_restore_state(ejs_save); + return; + } + + /* parse any form or get variables */ + if (web->input.post_request) { + status = http_parse_post(esp); + if (!NT_STATUS_IS_OK(status)) { + http_error(web, 400, "Malformed POST data"); + mprSetCtx(save_mpr_ctx); + ejs_restore_state(ejs_save); + return; + } + } + if (strchr(web->input.url, '?')) { + status = http_parse_get(esp); + if (!NT_STATUS_IS_OK(status)) { + http_error(web, 400, "Malformed GET data"); + mprSetCtx(save_mpr_ctx); + ejs_restore_state(ejs_save); + return; + } + } + + http_setup_session(esp); + + esp->req = espCreateRequest(web, web->input.url, esp->variables); + if (esp->req == NULL) goto internal_error; + + p = strrchr(web->input.url, '.'); + if (p == NULL) { + page_type = page_type_esp; + file_type = "text/html"; + } + for (i=0;p && iinput.url); + } + break; + } + + if (web->conn == NULL) { + /* the connection has been terminated above us, probably + via a timeout */ + goto internal_error; + } + + if (!web->output.output_pending) { + http_output_headers(web); + EVENT_FD_WRITEABLE(web->conn->event.fde); + web->output.output_pending = true; + } + + /* copy any application data to long term storage in edata */ + talloc_free(edata->application_data); + edata->application_data = talloc_zero(edata, struct MprVar); + mprSetCtx(edata->application_data); + mprCopyVar(edata->application_data, &esp->variables[ESP_APPLICATION_OBJ], + MPR_DEEP_COPY); + mprSetCtx(esp); + + /* copy any session data */ + if (web->session) { + talloc_free(web->session->data); + web->session->data = talloc_zero(web->session, struct MprVar); + if (esp->variables[ESP_SESSION_OBJ].properties == NULL || + esp->variables[ESP_SESSION_OBJ].properties[0].numItems == 0) { + talloc_free(web->session); + web->session = NULL; + } else { + mprSetCtx(web->session->data); + mprCopyVar(web->session->data, &esp->variables[ESP_SESSION_OBJ], + MPR_DEEP_COPY); + /* setup the timeout for the session data */ + mprSetCtx(esp); + talloc_free(web->session->te); + web->session->te = event_add_timed(web->conn->event.ctx, web->session, + timeval_current_ofs(web->session->lifetime, 0), + session_timeout, web->session); + } + } + + talloc_free(esp); + mprSetCtx(save_mpr_ctx); + ejs_restore_state(ejs_save); + return; + +internal_error: + mprSetCtx(esp); + talloc_free(esp); + if (web->conn != NULL) { + http_error(web, 500, "Internal server error"); + } + mprSetCtx(save_mpr_ctx); + ejs_restore_state(ejs_save); +} + + +/* + parse one line of header input +*/ +NTSTATUS http_parse_header(struct websrv_context *web, const char *line) +{ + if (line[0] == 0) { + web->input.end_of_headers = true; + } else if (strncasecmp(line,"GET ", 4)==0) { + web->input.url = talloc_strndup(web, &line[4], strcspn(&line[4], " \t")); + } else if (strncasecmp(line,"POST ", 5)==0) { + web->input.post_request = true; + web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t")); + } else if (strchr(line, ':') == NULL) { + http_error(web, 400, "This server only accepts GET and POST requests"); + return NT_STATUS_INVALID_PARAMETER; + } else if (strncasecmp(line,"Content-Length: ", 16)==0) { + web->input.content_length = strtoul(&line[16], NULL, 10); + } else { +#define PULL_HEADER(v, s) do { \ + if (strncmp(line, s, strlen(s)) == 0) { \ + web->input.v = talloc_strdup(web, &line[strlen(s)]); \ + return NT_STATUS_OK; \ + } \ +} while (0) + PULL_HEADER(content_type, "Content-Type: "); + PULL_HEADER(user_agent, "User-Agent: "); + PULL_HEADER(referer, "Referer: "); + PULL_HEADER(host, "Host: "); + PULL_HEADER(accept_encoding, "Accept-Encoding: "); + PULL_HEADER(accept_language, "Accept-Language: "); + PULL_HEADER(accept_charset, "Accept-Charset: "); + PULL_HEADER(cookie, "Cookie: "); + } + + /* ignore all other headers for now */ + return NT_STATUS_OK; +} + + +/* + setup the esp processor - called at task initialisation +*/ +struct esp_data *http_setup_esp(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx) +{ + struct esp_data *edata; + + edata = talloc_zero(mem_ctx, struct esp_data); + if (edata == NULL) + return NULL; + + edata->tls_params = tls_initialise(edata, lp_ctx); + if (edata->tls_params == NULL) + return NULL; + + return edata; +} diff --git a/source4/web_server/http.c b/source4/web_server/http.c deleted file mode 100644 index bd6efa9262..0000000000 --- a/source4/web_server/http.c +++ /dev/null @@ -1,1030 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - http handling code - - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "includes.h" -#include "smbd/service_task.h" -#include "web_server/web_server.h" -#include "smbd/service_stream.h" -#include "smbd/service.h" -#include "lib/events/events.h" -#include "system/time.h" -#include "system/wait.h" -#include "lib/appweb/esp/esp.h" -#include "lib/appweb/ejs/ejsInternal.h" -#include "lib/util/dlinklist.h" -#include "lib/tls/tls.h" -#include "scripting/ejs/smbcalls.h" -#include "param/param.h" - -#define SAMBA_SESSION_KEY "SambaSessionId" -#define HTTP_PREAUTH_URI "/scripting/preauth.esp" - -/* state of the esp subsystem for a specific request */ -struct esp_state { - struct websrv_context *web; - struct EspRequest *req; - struct MprVar variables[ESP_OBJ_MAX]; - struct session_data *session; -}; - -/* - output the http headers -*/ -static void http_output_headers(struct websrv_context *web) -{ - int i; - char *s; - DATA_BLOB b; - uint32_t content_length = 0; - const char *response_string = "Unknown Code"; - const struct { - unsigned code; - const char *response_string; - } codes[] = { - { 200, "OK" }, - { 301, "Moved" }, - { 302, "Found" }, - { 303, "Method" }, - { 304, "Not Modified" }, - { 400, "Bad request" }, - { 401, "Unauthorized" }, - { 403, "Forbidden" }, - { 404, "Not Found" }, - { 500, "Internal Server Error" }, - { 501, "Not implemented" } - }; - for (i=0;ioutput.response_code) { - response_string = codes[i].response_string; - } - } - - if (web->output.headers == NULL) return; - s = talloc_asprintf(web, "HTTP/1.0 %u %s\r\n", - web->output.response_code, response_string); - if (s == NULL) return; - for (i=0;web->output.headers[i];i++) { - s = talloc_asprintf_append_buffer(s, "%s\r\n", web->output.headers[i]); - } - - /* work out the content length */ - content_length = web->output.content.length; - if (web->output.fd != -1) { - struct stat st; - fstat(web->output.fd, &st); - content_length += st.st_size; - } - s = talloc_asprintf_append_buffer(s, "Content-Length: %u\r\n\r\n", content_length); - if (s == NULL) return; - - b = web->output.content; - web->output.content = data_blob_string_const(s); - data_blob_append(web, &web->output.content, b.data, b.length); - data_blob_free(&b); -} - -/* - return the local path for a URL -*/ -static const char *http_local_path(struct websrv_context *web, - const char *url, - const char *base_dir) -{ - int i; - char *path; - - /* check that the url is OK */ - if (url[0] != '/') return NULL; - - for (i=0;url[i];i++) { - if ((!isalnum((unsigned char)url[i]) && !strchr("./_-", url[i])) || - (url[i] == '.' && strchr("/.", url[i+1]))) { - return NULL; - } - } - - path = talloc_asprintf(web, "%s/%s", base_dir, url+1); - if (path == NULL) return NULL; - - if (directory_exist(path)) { - path = talloc_asprintf_append_buffer(path, "/index.esp"); - } - return path; -} - -/* - called when esp wants to read a file to support include() calls -*/ -static int http_readFile(EspHandle handle, - char **buf, - int *len, - const char *path, - const char *base_dir) -{ - struct websrv_context *web = talloc_get_type(handle, - struct websrv_context); - int fd = -1; - struct stat st; - *buf = NULL; - - path = http_local_path(web, path, base_dir); - if (path == NULL) goto failed; - - fd = open(path, O_RDONLY); - if (fd == -1 || fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) goto failed; - - *buf = talloc_array(handle, char, st.st_size+1); - if (*buf == NULL) goto failed; - - if (read(fd, *buf, st.st_size) != st.st_size) goto failed; - - (*buf)[st.st_size] = 0; - - close(fd); - *len = st.st_size; - return 0; - -failed: - DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno))); - if (fd != -1) close(fd); - talloc_free(*buf); - *buf = NULL; - return -1; -} - -static int http_readFileFromSwatDir(EspHandle handle, char **buf, int *len, - const char *path) -{ - return http_readFile(handle, buf, len, path, - lp_swat_directory(global_loadparm)); -} - - - -/* - called when esp wants to find the real path of a file -*/ -static int http_mapToStorage(EspHandle handle, char *path, int len, const char *uri, int flags) -{ - if (uri == NULL || strlen(uri) >= len) return -1; - strncpy(path, uri, len); - return 0; -} - -/* - called when esp wants to output something -*/ -static int http_writeBlock(EspHandle handle, const char *buf, int size) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - if (!data_blob_append(web, &web->output.content, buf, size)) - return -1; - return size; -} - - -/* - set a http header -*/ -static void http_setHeader(EspHandle handle, const char *value, bool allowMultiple) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - char *p = strchr(value, ':'); - - if (p && !allowMultiple && web->output.headers) { - int i; - for (i=0;web->output.headers[i];i++) { - if (strncmp(web->output.headers[i], value, (p+1)-value) == 0) { - web->output.headers[i] = talloc_strdup(web, value); - return; - } - } - } - - web->output.headers = str_list_add(web->output.headers, value); - talloc_steal(web, web->output.headers); -} - -/* - set a http response code -*/ -static void http_setResponseCode(EspHandle handle, int code) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - web->output.response_code = code; -} - -/* - redirect to another web page - */ -static void http_redirect(EspHandle handle, int code, char *url) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - const char *host = web->input.host; - - /* form the full url, unless it already looks like a url */ - if (strchr(url, ':') == NULL) { - if (host == NULL) { - struct socket_address *socket_address = socket_get_my_addr(web->conn->socket, web); - if (socket_address == NULL) goto internal_error; - host = talloc_asprintf(web, "%s:%u", - socket_address->addr, socket_address->port); - } - if (host == NULL) goto internal_error; - if (url[0] != '/') { - char *p = strrchr(web->input.url, '/'); - if (p == web->input.url) { - url = talloc_asprintf(web, "http%s://%s/%s", - tls_enabled(web->conn->socket)?"s":"", - host, url); - } else { - int dirlen = p - web->input.url; - url = talloc_asprintf(web, "http%s://%s%*.*s/%s", - tls_enabled(web->conn->socket)?"s":"", - host, - dirlen, dirlen, web->input.url, - url); - } - if (url == NULL) goto internal_error; - } - } - - http_setHeader(handle, talloc_asprintf(web, "Location: %s", url), 0); - - /* make sure we give a valid redirect code */ - if (code >= 300 && code < 400) { - http_setResponseCode(handle, code); - } else { - http_setResponseCode(handle, 302); - } - return; - -internal_error: - http_error(web, 500, "Internal server error"); -} - - -/* - setup a cookie -*/ -static void http_setCookie(EspHandle handle, const char *name, const char *value, - int lifetime, const char *path, bool secure) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - char *buf; - - if (lifetime > 0) { - buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; Expires=%s; %s", - name, value, path?path:"/", - http_timestring(web, time(NULL)+lifetime), - secure?"secure":""); - } else { - buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; %s", - name, value, path?path:"/", - secure?"secure":""); - } - http_setHeader(handle, "Cache-control: no-cache=\"set-cookie\"", 0); - http_setHeader(handle, buf, 0); - talloc_free(buf); -} - -/* - return the session id -*/ -static const char *http_getSessionId(EspHandle handle) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - return web->session->id; -} - -/* - setup a session -*/ -static void http_createSession(EspHandle handle, int timeout) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - if (web->session) { - web->session->lifetime = timeout; - http_setCookie(web, SAMBA_SESSION_KEY, web->session->id, - web->session->lifetime, "/", 0); - } -} - -/* - destroy a session -*/ -static void http_destroySession(EspHandle handle) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - talloc_free(web->session); - web->session = NULL; -} - - -/* - setup for a raw http level error -*/ -void http_error(struct websrv_context *web, int code, const char *info) -{ - char *s; - s = talloc_asprintf(web,"Error %u

Error %u

%s

\r\n\r\n", - code, code, info); - if (s == NULL) { - stream_terminate_connection(web->conn, "http_error: out of memory"); - return; - } - http_writeBlock(web, s, strlen(s)); - http_setResponseCode(web, code); - http_output_headers(web); - EVENT_FD_NOT_READABLE(web->conn->event.fde); - EVENT_FD_WRITEABLE(web->conn->event.fde); - web->output.output_pending = true; -} - -/* - map a unix error code to a http error -*/ -void http_error_unix(struct websrv_context *web, const char *info) -{ - int code = 500; - switch (errno) { - case ENOENT: - case EISDIR: - code = 404; - break; - case EACCES: - code = 403; - break; - } - info = talloc_asprintf(web, "%s

%s

\n", info, strerror(errno)); - http_error(web, code, info); -} - - -/* - a simple file request -*/ -static void http_simple_request(struct websrv_context *web) -{ - const char *url = web->input.url; - const char *path; - struct stat st; - - path = http_local_path(web, url, lp_swat_directory(web->task->lp_ctx)); - if (path == NULL) goto invalid; - - /* looks ok */ - web->output.fd = open(path, O_RDONLY); - if (web->output.fd == -1) { - DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno))); - http_error_unix(web, path); - return; - } - - if (fstat(web->output.fd, &st) != 0 || !S_ISREG(st.st_mode)) { - close(web->output.fd); - goto invalid; - } - - return; - -invalid: - http_error(web, 400, "Malformed URL"); -} - -/* - setup the standard ESP arrays -*/ -static void http_setup_arrays(struct esp_state *esp) -{ - struct websrv_context *web = esp->web; - struct esp_data *edata = talloc_get_type(web->task->private, struct esp_data); - struct EspRequest *req = esp->req; - struct socket_address *socket_address = socket_get_my_addr(web->conn->socket, esp); - struct socket_address *peer_address = socket_get_peer_addr(web->conn->socket, esp); - char *p; - -#define SETVAR(type, name, value) do { \ - const char *v = value; \ - if (v) espSetStringVar(req, type, name, v); \ -} while (0) - - SETVAR(ESP_REQUEST_OBJ, "CONTENT_LENGTH", - talloc_asprintf(esp, "%u", web->input.content_length)); - SETVAR(ESP_REQUEST_OBJ, "QUERY_STRING", web->input.query_string); - SETVAR(ESP_REQUEST_OBJ, "POST_DATA", - talloc_strndup(esp, - web->input.partial.data, - web->input.partial.length)); - SETVAR(ESP_REQUEST_OBJ, "REQUEST_METHOD", web->input.post_request?"POST":"GET"); - SETVAR(ESP_REQUEST_OBJ, "REQUEST_URI", web->input.url); - p = strrchr(web->input.url, '/'); - SETVAR(ESP_REQUEST_OBJ, "SCRIPT_NAME", p+1); - SETVAR(ESP_REQUEST_OBJ, "SCRIPT_FILENAME", web->input.url); - if (peer_address) { - struct MprVar mpv = mprObject("socket_address"); - mprSetPtrChild(&mpv, "socket_address", peer_address); - espSetVar(req, ESP_REQUEST_OBJ, "REMOTE_SOCKET_ADDRESS", mpv); - SETVAR(ESP_REQUEST_OBJ, "REMOTE_ADDR", peer_address->addr); - } - p = socket_get_peer_name(web->conn->socket, esp); - SETVAR(ESP_REQUEST_OBJ, "REMOTE_HOST", p); - SETVAR(ESP_REQUEST_OBJ, "REMOTE_USER", ""); - SETVAR(ESP_REQUEST_OBJ, "CONTENT_TYPE", web->input.content_type); - if (web->session) { - SETVAR(ESP_REQUEST_OBJ, "SESSION_ID", web->session->id); - } - SETVAR(ESP_REQUEST_OBJ, "COOKIE_SUPPORT", web->input.cookie?"true":"false"); - - SETVAR(ESP_HEADERS_OBJ, "HTTP_REFERER", web->input.referer); - SETVAR(ESP_HEADERS_OBJ, "HOST", web->input.host); - SETVAR(ESP_HEADERS_OBJ, "ACCEPT_ENCODING", web->input.accept_encoding); - SETVAR(ESP_HEADERS_OBJ, "ACCEPT_LANGUAGE", web->input.accept_language); - SETVAR(ESP_HEADERS_OBJ, "ACCEPT_CHARSET", web->input.accept_charset); - SETVAR(ESP_HEADERS_OBJ, "COOKIE", web->input.cookie); - SETVAR(ESP_HEADERS_OBJ, "USER_AGENT", web->input.user_agent); - - if (socket_address) { - SETVAR(ESP_SERVER_OBJ, "SERVER_ADDR", socket_address->addr); - SETVAR(ESP_SERVER_OBJ, "SERVER_NAME", socket_address->addr); - SETVAR(ESP_SERVER_OBJ, "SERVER_HOST", socket_address->addr); - SETVAR(ESP_SERVER_OBJ, "SERVER_PORT", - talloc_asprintf(esp, "%u", socket_address->port)); - } - - SETVAR(ESP_SERVER_OBJ, "DOCUMENT_ROOT", lp_swat_directory(esp->web->task->lp_ctx)); - SETVAR(ESP_SERVER_OBJ, "SERVER_PROTOCOL", tls_enabled(web->conn->socket)?"https":"http"); - SETVAR(ESP_SERVER_OBJ, "SERVER_SOFTWARE", "SAMBA"); - SETVAR(ESP_SERVER_OBJ, "GATEWAY_INTERFACE", "CGI/1.1"); - SETVAR(ESP_SERVER_OBJ, "TLS_SUPPORT", tls_support(edata->tls_params)?"true":"false"); -} - -#if HAVE_SETJMP_H -/* the esp scripting lirary generates exceptions when - it hits a major error. We need to catch these and - report a internal server error via http -*/ -static jmp_buf ejs_exception_buf; -static const char *exception_reason; - -static void web_server_ejs_exception(const char *reason) -{ - Ejs *ep = ejsPtr(0); - if (ep) { - ejsSetErrorMsg(0, "%s", reason); - exception_reason = ep->error; - } else { - exception_reason = reason; - } - DEBUG(0,("%s", exception_reason)); - longjmp(ejs_exception_buf, -1); -} -#else -static void web_server_ejs_exception(const char *reason) -{ - DEBUG(0,("%s", reason)); - smb_panic(reason); -} -#endif - -/* - process a esp request -*/ -static void esp_request(struct esp_state *esp, const char *url) -{ - struct websrv_context *web = esp->web; - int size; - int res; - char *emsg = NULL, *buf; - - if (http_readFile(web, &buf, &size, url, lp_swat_directory(esp->web->task->lp_ctx)) != 0) { - http_error_unix(web, url); - return; - } - -#if HAVE_SETJMP_H - if (setjmp(ejs_exception_buf) != 0) { - http_error(web, 500, exception_reason); - return; - } -#endif - - res = espProcessRequest(esp->req, url, buf, &emsg); - if (res != 0 && emsg) { - http_writeBlock(web, "

", 5);
-		http_writeBlock(web, emsg, strlen(emsg));
-		http_writeBlock(web, "
", 6); - } - talloc_free(buf); -} - -/* - perform pre-authentication on every page if /scripting/preauth.esp - exists. If this script generates any non-whitepace output at all, - then we don't run the requested URL. - - note that the preauth is run even for static pages such as images -*/ -static bool http_preauth(struct esp_state *esp) -{ - const char *path = http_local_path(esp->web, - HTTP_PREAUTH_URI, - lp_swat_directory(esp->web->task->lp_ctx)); - int i; - if (path == NULL) { - http_error(esp->web, 500, "Internal server error"); - return false; - } - if (!file_exist(path)) { - /* if the preath script is not installed then allow access */ - return true; - } - esp_request(esp, HTTP_PREAUTH_URI); - for (i=0;iweb->output.content.length;i++) { - if (!isspace(esp->web->output.content.data[i])) { - /* if the preauth has generated content, then force it - to be html, so that we can show the login page for - failed access to images */ - http_setHeader(esp->web, "Content-Type: text/html", 0); - return false; - } - } - data_blob_free(&esp->web->output.content); - return true; -} - - -/* - handling of + and % escapes in http variables -*/ -static const char *http_unescape(TALLOC_CTX *mem_ctx, const char *p) -{ - char *s0 = talloc_strdup(mem_ctx, p); - char *s = s0; - if (s == NULL) return NULL; - - while (*s) { - unsigned v; - if (*s == '+') *s = ' '; - if (*s == '%' && sscanf(s+1, "%02x", &v) == 1) { - *s = (char)v; - memmove(s+1, s+3, strlen(s+3)+1); - } - s++; - } - - return s0; -} - -/* - set a form or GET variable -*/ -static void esp_putvar(struct esp_state *esp, const char *var, const char *value) -{ - if (strcasecmp(var, SAMBA_SESSION_KEY) == 0) { - /* special case support for browsers without cookie - support */ - esp->web->input.session_key = talloc_strdup(esp, value); - } else { - mprSetPropertyValue(&esp->variables[ESP_FORM_OBJ], - http_unescape(esp, var), - mprCreateStringVar(http_unescape(esp, value), 0)); - } -} - - -/* - parse the variables in a POST style request -*/ -static NTSTATUS http_parse_post(struct esp_state *esp) -{ - DATA_BLOB b = esp->web->input.partial; - - while (b.length) { - char *p, *line; - size_t len; - - p = memchr(b.data, '&', b.length); - if (p == NULL) { - len = b.length; - } else { - len = p - (char *)b.data; - } - line = talloc_strndup(esp, (char *)b.data, len); - NT_STATUS_HAVE_NO_MEMORY(line); - - p = strchr(line,'='); - if (p) { - *p = 0; - esp_putvar(esp, line, p+1); - } - talloc_free(line); - b.length -= len; - b.data += len; - if (b.length > 0) { - b.length--; - b.data++; - } - } - - return NT_STATUS_OK; -} - -/* - parse the variables in a GET style request -*/ -static NTSTATUS http_parse_get(struct esp_state *esp) -{ - struct websrv_context *web = esp->web; - char *p, *s, *tok; - char *pp; - - p = strchr(web->input.url, '?'); - web->input.query_string = p+1; - *p = 0; - - s = talloc_strdup(esp, esp->web->input.query_string); - NT_STATUS_HAVE_NO_MEMORY(s); - - for (tok=strtok_r(s,"&;", &pp);tok;tok=strtok_r(NULL,"&;", &pp)) { - p = strchr(tok,'='); - if (p) { - *p = 0; - esp_putvar(esp, tok, p+1); - } - } - return NT_STATUS_OK; -} - -/* - called when a session times out -*/ -static void session_timeout(struct event_context *ev, struct timed_event *te, - struct timeval t, void *private) -{ - struct session_data *s = talloc_get_type(private, struct session_data); - talloc_free(s); -} - -/* - destroy a session - */ -static int session_destructor(struct session_data *s) -{ - DLIST_REMOVE(s->edata->sessions, s); - return 0; -} - -/* - setup the session for this request -*/ -static void http_setup_session(struct esp_state *esp) -{ - const char *session_key = SAMBA_SESSION_KEY; - char *p; - const char *cookie = esp->web->input.cookie; - const char *key = NULL; - struct esp_data *edata = talloc_get_type(esp->web->task->private, struct esp_data); - struct session_data *s; - bool generated_key = false; - - /* look for our session key */ - if (cookie && (p = strstr(cookie, session_key)) && - p[strlen(session_key)] == '=') { - p += strlen(session_key)+1; - key = talloc_strndup(esp, p, strcspn(p, ";")); - } - - if (key == NULL && esp->web->input.session_key) { - key = esp->web->input.session_key; - } else if (key == NULL) { - key = generate_random_str_list(esp, 16, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - generated_key = true; - } - - /* try to find this session in the existing session list */ - for (s=edata->sessions;s;s=s->next) { - if (strcmp(key, s->id) == 0) { - break; - } - } - - if (s == NULL) { - /* create a new session */ - s = talloc_zero(edata, struct session_data); - s->id = talloc_steal(s, key); - s->data = NULL; - s->te = NULL; - s->edata = edata; - s->lifetime = lp_parm_int(esp->web->task->lp_ctx, NULL, "web", "sessiontimeout", 900); - DLIST_ADD(edata->sessions, s); - talloc_set_destructor(s, session_destructor); - if (!generated_key) { - mprSetPropertyValue(&esp->variables[ESP_REQUEST_OBJ], - "SESSION_EXPIRED", mprCreateStringVar("true", 0)); - } - } - - http_setCookie(esp->web, session_key, key, s->lifetime, "/", 0); - - if (s->data) { - mprCopyVar(&esp->variables[ESP_SESSION_OBJ], s->data, MPR_DEEP_COPY); - } - - esp->web->session = s; -} - - -/* callbacks for esp processing */ -static const struct Esp esp_control = { - .maxScriptSize = 60000, - .writeBlock = http_writeBlock, - .setHeader = http_setHeader, - .redirect = http_redirect, - .setResponseCode = http_setResponseCode, - .readFile = http_readFileFromSwatDir, - .mapToStorage = http_mapToStorage, - .setCookie = http_setCookie, - .createSession = http_createSession, - .destroySession = http_destroySession, - .getSessionId = http_getSessionId -}; - -/* - process a complete http request -*/ -void http_process_input(struct websrv_context *web) -{ - NTSTATUS status; - struct esp_state *esp = NULL; - struct esp_data *edata = talloc_get_type(web->task->private, struct esp_data); - struct smbcalls_context *smbcalls_ctx; - char *p; - void *save_mpr_ctx = mprMemCtx(); - void *ejs_save = ejs_save_state(); - int i; - const char *file_type = NULL; - enum page_type { - page_type_simple, - page_type_esp - }; - enum page_type page_type; - const struct { - const char *extension; - const char *mime_type; - enum page_type page_type; - } mime_types[] = { - {"gif", "image/gif"}, - {"png", "image/png"}, - {"jpg", "image/jpeg"}, - {"txt", "text/plain"}, - {"ico", "image/x-icon"}, - {"css", "text/css"}, - {"esp", "text/html", true} - }; - - /* - * give the smbcalls a chance to find the event context - * and messaging context - */ - smbcalls_ctx = talloc(web, struct smbcalls_context); - if (smbcalls_ctx == NULL) goto internal_error; - smbcalls_ctx->event_ctx = web->conn->event.ctx; - smbcalls_ctx->msg_ctx = web->conn->msg_ctx; - - esp = talloc_zero(smbcalls_ctx, struct esp_state); - if (esp == NULL) goto internal_error; - - esp->web = web; - - mprSetCtx(esp); - - if (espOpen(&esp_control) != 0) goto internal_error; - - for (i=0;ivariables);i++) { - esp->variables[i] = mprCreateUndefinedVar(); - } - esp->variables[ESP_HEADERS_OBJ] = mprCreateObjVar("headers", ESP_HASH_SIZE); - esp->variables[ESP_FORM_OBJ] = mprCreateObjVar("form", ESP_HASH_SIZE); - esp->variables[ESP_APPLICATION_OBJ] = mprCreateObjVar("application", ESP_HASH_SIZE); - esp->variables[ESP_COOKIES_OBJ] = mprCreateObjVar("cookies", ESP_HASH_SIZE); - esp->variables[ESP_FILES_OBJ] = mprCreateObjVar("files", ESP_HASH_SIZE); - esp->variables[ESP_REQUEST_OBJ] = mprCreateObjVar("request", ESP_HASH_SIZE); - esp->variables[ESP_SERVER_OBJ] = mprCreateObjVar("server", ESP_HASH_SIZE); - esp->variables[ESP_SESSION_OBJ] = mprCreateObjVar("session", ESP_HASH_SIZE); - - if (edata->application_data) { - mprCopyVar(&esp->variables[ESP_APPLICATION_OBJ], - edata->application_data, MPR_DEEP_COPY); - } - - smb_setup_ejs_functions(web_server_ejs_exception); - - if (web->input.url == NULL) { - http_error(web, 400, "You must specify a GET or POST request"); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - } - - /* parse any form or get variables */ - if (web->input.post_request) { - status = http_parse_post(esp); - if (!NT_STATUS_IS_OK(status)) { - http_error(web, 400, "Malformed POST data"); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - } - } - if (strchr(web->input.url, '?')) { - status = http_parse_get(esp); - if (!NT_STATUS_IS_OK(status)) { - http_error(web, 400, "Malformed GET data"); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - } - } - - http_setup_session(esp); - - esp->req = espCreateRequest(web, web->input.url, esp->variables); - if (esp->req == NULL) goto internal_error; - - p = strrchr(web->input.url, '.'); - if (p == NULL) { - page_type = page_type_esp; - file_type = "text/html"; - } - for (i=0;p && iinput.url); - } - break; - } - - if (web->conn == NULL) { - /* the connection has been terminated above us, probably - via a timeout */ - goto internal_error; - } - - if (!web->output.output_pending) { - http_output_headers(web); - EVENT_FD_WRITEABLE(web->conn->event.fde); - web->output.output_pending = true; - } - - /* copy any application data to long term storage in edata */ - talloc_free(edata->application_data); - edata->application_data = talloc_zero(edata, struct MprVar); - mprSetCtx(edata->application_data); - mprCopyVar(edata->application_data, &esp->variables[ESP_APPLICATION_OBJ], - MPR_DEEP_COPY); - mprSetCtx(esp); - - /* copy any session data */ - if (web->session) { - talloc_free(web->session->data); - web->session->data = talloc_zero(web->session, struct MprVar); - if (esp->variables[ESP_SESSION_OBJ].properties == NULL || - esp->variables[ESP_SESSION_OBJ].properties[0].numItems == 0) { - talloc_free(web->session); - web->session = NULL; - } else { - mprSetCtx(web->session->data); - mprCopyVar(web->session->data, &esp->variables[ESP_SESSION_OBJ], - MPR_DEEP_COPY); - /* setup the timeout for the session data */ - mprSetCtx(esp); - talloc_free(web->session->te); - web->session->te = event_add_timed(web->conn->event.ctx, web->session, - timeval_current_ofs(web->session->lifetime, 0), - session_timeout, web->session); - } - } - - talloc_free(esp); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - -internal_error: - mprSetCtx(esp); - talloc_free(esp); - if (web->conn != NULL) { - http_error(web, 500, "Internal server error"); - } - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); -} - - -/* - parse one line of header input -*/ -NTSTATUS http_parse_header(struct websrv_context *web, const char *line) -{ - if (line[0] == 0) { - web->input.end_of_headers = true; - } else if (strncasecmp(line,"GET ", 4)==0) { - web->input.url = talloc_strndup(web, &line[4], strcspn(&line[4], " \t")); - } else if (strncasecmp(line,"POST ", 5)==0) { - web->input.post_request = true; - web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t")); - } else if (strchr(line, ':') == NULL) { - http_error(web, 400, "This server only accepts GET and POST requests"); - return NT_STATUS_INVALID_PARAMETER; - } else if (strncasecmp(line,"Content-Length: ", 16)==0) { - web->input.content_length = strtoul(&line[16], NULL, 10); - } else { -#define PULL_HEADER(v, s) do { \ - if (strncmp(line, s, strlen(s)) == 0) { \ - web->input.v = talloc_strdup(web, &line[strlen(s)]); \ - return NT_STATUS_OK; \ - } \ -} while (0) - PULL_HEADER(content_type, "Content-Type: "); - PULL_HEADER(user_agent, "User-Agent: "); - PULL_HEADER(referer, "Referer: "); - PULL_HEADER(host, "Host: "); - PULL_HEADER(accept_encoding, "Accept-Encoding: "); - PULL_HEADER(accept_language, "Accept-Language: "); - PULL_HEADER(accept_charset, "Accept-Charset: "); - PULL_HEADER(cookie, "Cookie: "); - } - - /* ignore all other headers for now */ - return NT_STATUS_OK; -} - - -/* - setup the esp processor - called at task initialisation -*/ -NTSTATUS http_setup_esp(struct task_server *task) -{ - struct esp_data *edata; - - edata = talloc_zero(task, struct esp_data); - NT_STATUS_HAVE_NO_MEMORY(edata); - - task->private = edata; - - edata->tls_params = tls_initialise(edata, task->lp_ctx); - NT_STATUS_HAVE_NO_MEMORY(edata->tls_params); - - return NT_STATUS_OK; -} diff --git a/source4/web_server/web_server.c b/source4/web_server/web_server.c index ac83a3384d..bfbd254d9e 100644 --- a/source4/web_server/web_server.c +++ b/source4/web_server/web_server.c @@ -280,8 +280,8 @@ static void websrv_task_init(struct task_server *task) /* startup the esp processor - unfortunately we can't do this per connection as that wouldn't allow for session variables */ - status = http_setup_esp(task); - if (!NT_STATUS_IS_OK(status)) goto failed; + task->private = http_setup_esp(task, task->lp_ctx); + if (task->private == NULL) goto failed; return; -- cgit From 4bb17b60ef608b10284ccd2146c9344cc43b8637 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 23 May 2008 21:21:07 +0200 Subject: Add initial work on WSGI support in the web server. --- source4/web_server/config.mk | 2 +- source4/web_server/wsgi.c | 69 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 source4/web_server/wsgi.c diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index 4094d6be07..810cc7f430 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -10,6 +10,6 @@ PRIVATE_DEPENDENCIES = ESP LIBTLS smbcalls process_model # End SUBSYSTEM WEB ####################### -WEB_OBJ_FILES = $(addprefix $(web_serversrcdir)/, web_server.o esp.o) +WEB_OBJ_FILES = $(addprefix $(web_serversrcdir)/, web_server.o esp.o wsgi.o) $(eval $(call proto_header_template,$(web_serversrcdir)/proto.h,$(WEB_OBJ_FILES:.o=.c))) diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c new file mode 100644 index 0000000000..50f8599869 --- /dev/null +++ b/source4/web_server/wsgi.c @@ -0,0 +1,69 @@ +/* + Unix SMB/CIFS implementation. + Samba utility functions + Copyright © Jelmer Vernooij 2008 + + Implementation of the WSGI interface described in PEP0333 + (http://www.python.org/dev/peps/pep-0333) + + 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 . +*/ + +#include "includes.h" +#include + +static PyObject *start_response(PyObject *args, PyObject *kwargs) +{ + PyObject *response_header, *exc_info; + char *status; + const char *kwnames[] = { + "status", "response_header", "exc_info", NULL + }; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *)"sOO:start_response", (char **)kwnames, &status, &response_header, &exc_info)) { + return NULL; + } + + /* FIXME: response_header, exc_info */ + + /* FIXME: Wrap stdout */ + return NULL; +} + +static PyObject *create_environ(void) +{ + PyObject *env, *osmodule, *osenviron; + + osmodule = PyImport_ImportModule("os"); + if (osmodule == NULL) + return NULL; + + osenviron = PyObject_CallMethod(osmodule, "environ", NULL); + + env = PyDict_Copy(osenviron); + + PyDict_SetItemString(env, "wsgi.input", NULL); /* FIXME */ + PyDict_SetItemString(env, "wsgi.errors", NULL); /* FIXME */ + PyDict_SetItemString(env, "wsgi.version", Py_BuildValue("(i,i)", 1, 0)); + PyDict_SetItemString(env, "wsgi.multithread", Py_False); + PyDict_SetItemString(env, "wsgi.multiprocess", Py_True); + PyDict_SetItemString(env, "wsgi.run_once", Py_False); + + /* FIXME: + PyDict_SetItemString(env, "wsgi.url_scheme", "http"); + PyDict_SetItemString(env, "wsgi.url_scheme", "https"); + */ + + return env; +} -- cgit From a4e8ff7429db8620a4d91e901295413560be6c91 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sat, 24 May 2008 03:54:47 +0200 Subject: Add more parts of the WSGI implementation. --- source4/web_server/wsgi.c | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 50f8599869..3253873de2 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -41,9 +41,32 @@ static PyObject *start_response(PyObject *args, PyObject *kwargs) return NULL; } +/* + * read(size) input 1 + * readline() input 1,2 + * readlines(hint) input 1,3 + * __iter__() input + * flush() errors 4 + * write(str) errors + * writelines(seq) errors + */ + +static PyObject *Py_InputHttpStream(void *foo) +{ + /* FIXME */ + return NULL; +} + +static PyObject *Py_ErrorHttpStream(void) +{ + /* FIXME */ + return NULL; +} + static PyObject *create_environ(void) { PyObject *env, *osmodule, *osenviron; + PyObject *inputstream, *errorstream; osmodule = PyImport_ImportModule("os"); if (osmodule == NULL) @@ -53,8 +76,23 @@ static PyObject *create_environ(void) env = PyDict_Copy(osenviron); - PyDict_SetItemString(env, "wsgi.input", NULL); /* FIXME */ - PyDict_SetItemString(env, "wsgi.errors", NULL); /* FIXME */ + Py_DECREF(env); + + inputstream = Py_InputHttpStream(NULL); /* FIXME */ + if (inputstream == NULL) { + Py_DECREF(env); + return NULL; + } + + errorstream = Py_ErrorHttpStream(); + if (errorstream == NULL) { + Py_DECREF(env); + Py_DECREF(inputstream); + return NULL; + } + + PyDict_SetItemString(env, "wsgi.input", inputstream); + PyDict_SetItemString(env, "wsgi.errors", errorstream); PyDict_SetItemString(env, "wsgi.version", Py_BuildValue("(i,i)", 1, 0)); PyDict_SetItemString(env, "wsgi.multithread", Py_False); PyDict_SetItemString(env, "wsgi.multiprocess", Py_True); -- cgit From 2df040d8995b3198be8d3e1099eeb89860a3222d Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sat, 24 May 2008 15:43:37 +0200 Subject: Add input / error stream objects in WSGI implementation. --- source4/web_server/wsgi.c | 113 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 100 insertions(+), 13 deletions(-) diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 3253873de2..54adeb0943 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -41,28 +41,115 @@ static PyObject *start_response(PyObject *args, PyObject *kwargs) return NULL; } -/* - * read(size) input 1 - * readline() input 1,2 - * readlines(hint) input 1,3 - * __iter__() input - * flush() errors 4 - * write(str) errors - * writelines(seq) errors - */ +typedef struct { + PyObject_HEAD +} error_Stream_Object; -static PyObject *Py_InputHttpStream(void *foo) +static PyObject *py_error_flush(PyObject *self, PyObject *args, PyObject *kwargs) +{ + /* Nothing to do here */ + return Py_None; +} + +static PyObject *py_error_write(PyObject *self, PyObject *args, PyObject *kwargs) +{ + const char *kwnames[] = { "str", NULL }; + char *str = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *)"s:write", (char **)kwnames, &str)) { + return NULL; + } + + DEBUG(0, ("WSGI App: %s", str)); + + return Py_None; +} + +static PyObject *py_error_writelines(PyObject *self, PyObject *args, PyObject *kwargs) +{ + const char *kwnames[] = { "seq", NULL }; + PyObject *seq = NULL, *item; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *)"O:writelines", (char **)kwnames, &seq)) { + return NULL; + } + + while ((item = PyIter_Next(seq))) { + char *str = PyString_AsString(item); + + DEBUG(0, ("WSGI App: %s", str)); + } + + return Py_None; +} + +static PyMethodDef error_Stream_methods[] = { + { "flush", (PyCFunction)py_error_flush, METH_VARARGS|METH_KEYWORDS, NULL }, + { "write", (PyCFunction)py_error_write, METH_VARARGS|METH_KEYWORDS, NULL }, + { "writelines", (PyCFunction)py_error_writelines, METH_VARARGS|METH_KEYWORDS, NULL }, + { NULL, NULL, 0, NULL } +}; + +PyTypeObject error_Stream_Type = { + PyObject_HEAD_INIT(NULL) 0, + .tp_name = "wsgi.ErrorStream", + .tp_basicsize = sizeof(error_Stream_Object), + .tp_methods = error_Stream_methods, + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, +}; + +typedef struct { + PyObject_HEAD +} input_Stream_Object; + +static PyObject *py_input_read(PyObject *self, PyObject *args, PyObject *kwargs) { - /* FIXME */ return NULL; } -static PyObject *Py_ErrorHttpStream(void) +static PyObject *py_input_readline(PyObject *self, PyObject *args, PyObject *kwargs) +{ + return NULL; +} + +static PyObject *py_input_readlines(PyObject *self, PyObject *args, PyObject *kwargs) +{ + return NULL; +} + +static PyObject *py_input___iter__(PyObject *self, PyObject *args, PyObject *kwargs) { - /* FIXME */ return NULL; } +static PyMethodDef input_Stream_methods[] = { + { "read", (PyCFunction)py_input_read, METH_VARARGS|METH_KEYWORDS, NULL }, + { "readline", (PyCFunction)py_input_readline, METH_VARARGS|METH_KEYWORDS, NULL }, + { "readlines", (PyCFunction)py_input_readlines, METH_VARARGS|METH_KEYWORDS, NULL }, + { "__iter__", (PyCFunction)py_input___iter__, METH_VARARGS|METH_KEYWORDS, NULL }, + { NULL, NULL, 0, NULL } +}; + +PyTypeObject input_Stream_Type = { + PyObject_HEAD_INIT(NULL) 0, + .tp_name = "wsgi.InputStream", + .tp_basicsize = sizeof(input_Stream_Object), + .tp_methods = input_Stream_methods, + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, +}; + +static PyObject *Py_InputHttpStream(void *foo) +{ + PyObject *ret = PyObject_New(input_Stream_Object, &input_Stream_Type); + return ret; +} + +static PyObject *Py_ErrorHttpStream(void) +{ + PyObject *ret = PyObject_New(error_Stream_Object, &error_Stream_Type); + return ret; +} + static PyObject *create_environ(void) { PyObject *env, *osmodule, *osenviron; -- cgit From fda85985e91179f8e03538581335326f54456f4f Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sat, 24 May 2008 18:13:30 +0200 Subject: Remove some dependencies of the web server on esp. --- source4/web_server/esp.c | 38 +++++++++++++++++++++++++------------- source4/web_server/web_server.c | 20 +++++++++++++++----- source4/web_server/web_server.h | 23 ++++++----------------- source4/web_server/wsgi.c | 24 +++++++++++++++--------- 4 files changed, 61 insertions(+), 44 deletions(-) diff --git a/source4/web_server/esp.c b/source4/web_server/esp.c index 901a1558c4..29bda2a965 100644 --- a/source4/web_server/esp.c +++ b/source4/web_server/esp.c @@ -37,6 +37,24 @@ #define SAMBA_SESSION_KEY "SambaSessionId" #define HTTP_PREAUTH_URI "/scripting/preauth.esp" +/* + context for long term storage in the web server, to support session[] + and application[] data. Stored in task->private. +*/ +struct esp_data { + struct session_data { + struct session_data *next, *prev; + struct esp_data *edata; + const char *id; + struct MprVar *data; + struct timed_event *te; + int lifetime; + } *sessions; + struct MprVar *application_data; +}; + + + /* state of the esp subsystem for a specific request */ struct esp_state { struct websrv_context *web; @@ -413,10 +431,9 @@ invalid: /* setup the standard ESP arrays */ -static void http_setup_arrays(struct esp_state *esp) +static void http_setup_arrays(struct web_server_data *wdata, struct esp_state *esp) { struct websrv_context *web = esp->web; - struct esp_data *edata = talloc_get_type(web->task->private, struct esp_data); struct EspRequest *req = esp->req; struct socket_address *socket_address = socket_get_my_addr(web->conn->socket, esp); struct socket_address *peer_address = socket_get_peer_addr(web->conn->socket, esp); @@ -474,7 +491,7 @@ static void http_setup_arrays(struct esp_state *esp) SETVAR(ESP_SERVER_OBJ, "SERVER_PROTOCOL", tls_enabled(web->conn->socket)?"https":"http"); SETVAR(ESP_SERVER_OBJ, "SERVER_SOFTWARE", "SAMBA"); SETVAR(ESP_SERVER_OBJ, "GATEWAY_INTERFACE", "CGI/1.1"); - SETVAR(ESP_SERVER_OBJ, "TLS_SUPPORT", tls_support(edata->tls_params)?"true":"false"); + SETVAR(ESP_SERVER_OBJ, "TLS_SUPPORT", tls_support(wdata->tls_params)?"true":"false"); } #if HAVE_SETJMP_H @@ -696,13 +713,12 @@ static int session_destructor(struct session_data *s) /* setup the session for this request */ -static void http_setup_session(struct esp_state *esp) +static void http_setup_session(struct esp_data *edata, struct esp_state *esp) { const char *session_key = SAMBA_SESSION_KEY; char *p; const char *cookie = esp->web->input.cookie; const char *key = NULL; - struct esp_data *edata = talloc_get_type(esp->web->task->private, struct esp_data); struct session_data *s; bool generated_key = false; @@ -771,11 +787,11 @@ static const struct Esp esp_control = { /* process a complete http request */ -void http_process_input(struct websrv_context *web) +void esp_process_http_input(struct web_server_data *wdata, struct websrv_context *web) { NTSTATUS status; struct esp_state *esp = NULL; - struct esp_data *edata = talloc_get_type(web->task->private, struct esp_data); + struct esp_data *edata = talloc_get_type(wdata->private, struct esp_data); struct smbcalls_context *smbcalls_ctx; char *p; void *save_mpr_ctx = mprMemCtx(); @@ -865,7 +881,7 @@ void http_process_input(struct websrv_context *web) } } - http_setup_session(esp); + http_setup_session(edata, esp); esp->req = espCreateRequest(web, web->input.url, esp->variables); if (esp->req == NULL) goto internal_error; @@ -894,7 +910,7 @@ void http_process_input(struct websrv_context *web) http_setHeader(web, "Connection: close", 0); http_setHeader(web, talloc_asprintf(esp, "Content-Type: %s", file_type), 0); - http_setup_arrays(esp); + http_setup_arrays(wdata, esp); /* * Do pre-authentication. If pre-authentication succeeds, do @@ -1022,9 +1038,5 @@ struct esp_data *http_setup_esp(TALLOC_CTX *mem_ctx, struct loadparm_context *lp if (edata == NULL) return NULL; - edata->tls_params = tls_initialise(edata, lp_ctx); - if (edata->tls_params == NULL) - return NULL; - return edata; } diff --git a/source4/web_server/web_server.c b/source4/web_server/web_server.c index bfbd254d9e..6d8b2a2758 100644 --- a/source4/web_server/web_server.c +++ b/source4/web_server/web_server.c @@ -123,7 +123,7 @@ static void websrv_recv(struct stream_connection *conn, uint16_t flags) destroy the stack variables being used by that rendering process when we handle the timeout. */ if (!talloc_reference(web->task, web)) goto failed; - http_process_input(web); + web->http_process_input(web); talloc_unlink(web->task, web); } return; @@ -192,13 +192,14 @@ static void websrv_send(struct stream_connection *conn, uint16_t flags) static void websrv_accept(struct stream_connection *conn) { struct task_server *task = talloc_get_type(conn->private, struct task_server); - struct esp_data *edata = talloc_get_type(task->private, struct esp_data); + struct web_server_data *wdata = talloc_get_type(task->private, struct web_server_data); struct websrv_context *web; struct socket_context *tls_socket; web = talloc_zero(conn, struct websrv_context); if (web == NULL) goto failed; + web->http_process_input = esp_process_http_input; web->task = task; web->conn = conn; conn->private = web; @@ -210,7 +211,7 @@ static void websrv_accept(struct stream_connection *conn) websrv_timeout, web); /* Overwrite the socket with a (possibly) TLS socket */ - tls_socket = tls_init_server(edata->tls_params, conn->socket, + tls_socket = tls_init_server(wdata->tls_params, conn->socket, conn->event.fde, "GPHO"); /* We might not have TLS, or it might not have initilised */ if (tls_socket) { @@ -243,6 +244,7 @@ static void websrv_task_init(struct task_server *task) NTSTATUS status; uint16_t port = lp_web_port(task->lp_ctx); const struct model_ops *model_ops; + struct web_server_data *wdata; task_server_set_title(task, "task[websrv]"); @@ -280,8 +282,16 @@ static void websrv_task_init(struct task_server *task) /* startup the esp processor - unfortunately we can't do this per connection as that wouldn't allow for session variables */ - task->private = http_setup_esp(task, task->lp_ctx); - if (task->private == NULL) goto failed; + wdata = talloc_zero(task, struct web_server_data); + if (wdata == NULL)goto failed; + + task->private = wdata; + + wdata->tls_params = tls_initialise(wdata, task->lp_ctx); + if (wdata->tls_params == NULL) goto failed; + + wdata->private = http_setup_esp(task, task->lp_ctx); + if (wdata->private == NULL) goto failed; return; diff --git a/source4/web_server/web_server.h b/source4/web_server/web_server.h index 52aff05dcc..0ce68bdd17 100644 --- a/source4/web_server/web_server.h +++ b/source4/web_server/web_server.h @@ -19,12 +19,18 @@ #include "smbd/process_model.h" +struct web_server_data { + struct tls_params *tls_params; + void *private; +}; + /* context of one open web connection */ struct websrv_context { struct task_server *task; struct stream_connection *conn; + void (*http_process_input)(struct websrv_context *web); struct { bool tls_detect; bool tls_first_char; @@ -57,22 +63,5 @@ struct websrv_context { }; -/* - context for long term storage in the web server, to support session[] - and application[] data. Stored in task->private. -*/ -struct esp_data { - struct session_data { - struct session_data *next, *prev; - struct esp_data *edata; - const char *id; - struct MprVar *data; - struct timed_event *te; - int lifetime; - } *sessions; - struct MprVar *application_data; - struct tls_params *tls_params; -}; - #include "web_server/proto.h" diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 54adeb0943..32b1f0dbc2 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -21,9 +21,10 @@ */ #include "includes.h" +#include "web_server/web_server.h" #include -static PyObject *start_response(PyObject *args, PyObject *kwargs) +static PyObject *start_response(PyObject *self, PyObject *args, PyObject *kwargs) { PyObject *response_header, *exc_info; char *status; @@ -84,9 +85,9 @@ static PyObject *py_error_writelines(PyObject *self, PyObject *args, PyObject *k } static PyMethodDef error_Stream_methods[] = { - { "flush", (PyCFunction)py_error_flush, METH_VARARGS|METH_KEYWORDS, NULL }, - { "write", (PyCFunction)py_error_write, METH_VARARGS|METH_KEYWORDS, NULL }, - { "writelines", (PyCFunction)py_error_writelines, METH_VARARGS|METH_KEYWORDS, NULL }, + { "flush", (PyCFunction)py_error_flush, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "write", (PyCFunction)py_error_write, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "writelines", (PyCFunction)py_error_writelines, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, { NULL, NULL, 0, NULL } }; @@ -123,10 +124,10 @@ static PyObject *py_input___iter__(PyObject *self, PyObject *args, PyObject *kwa } static PyMethodDef input_Stream_methods[] = { - { "read", (PyCFunction)py_input_read, METH_VARARGS|METH_KEYWORDS, NULL }, - { "readline", (PyCFunction)py_input_readline, METH_VARARGS|METH_KEYWORDS, NULL }, - { "readlines", (PyCFunction)py_input_readlines, METH_VARARGS|METH_KEYWORDS, NULL }, - { "__iter__", (PyCFunction)py_input___iter__, METH_VARARGS|METH_KEYWORDS, NULL }, + { "read", (PyCFunction)py_input_read, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "readline", (PyCFunction)py_input_readline, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "readlines", (PyCFunction)py_input_readlines, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "__iter__", (PyCFunction)py_input___iter__, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, { NULL, NULL, 0, NULL } }; @@ -165,7 +166,7 @@ static PyObject *create_environ(void) Py_DECREF(env); - inputstream = Py_InputHttpStream(NULL); /* FIXME */ + inputstream = Py_InputHttpStream(NULL); if (inputstream == NULL) { Py_DECREF(env); return NULL; @@ -192,3 +193,8 @@ static PyObject *create_environ(void) return env; } + +void wsgi_process_http_input(struct websrv_context *web) +{ + +} -- cgit From 2009229c84e101bf7549276a7a5ac0cbe15d661c Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sat, 13 Sep 2008 19:41:42 +0200 Subject: Make use of TALLOC_ZERO_P --- source3/libsmb/clientgen.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/source3/libsmb/clientgen.c b/source3/libsmb/clientgen.c index 9d65fb4e94..8a5aedfde5 100644 --- a/source3/libsmb/clientgen.c +++ b/source3/libsmb/clientgen.c @@ -464,13 +464,11 @@ struct cli_state *cli_initialise(void) return NULL; } - cli = talloc(NULL, struct cli_state); + cli = TALLOC_ZERO_P(NULL, struct cli_state); if (!cli) { return NULL; } - ZERO_STRUCTP(cli); - cli->port = 0; cli->fd = -1; cli->cnum = -1; -- cgit From 1271066234fed0e5f0e28a1e75420482abd20887 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 16:53:29 +0200 Subject: Remove support for ESP in the web server. --- source4/web_server/config.mk | 5 +- source4/web_server/esp.c | 1042 --------------------------------------- source4/web_server/web_server.c | 63 ++- source4/web_server/web_server.h | 18 +- source4/web_server/wsgi.c | 14 +- 5 files changed, 76 insertions(+), 1066 deletions(-) delete mode 100644 source4/web_server/esp.c diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index 810cc7f430..af3ac5f544 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -4,12 +4,11 @@ # Start SUBSYSTEM WEB [MODULE::WEB] INIT_FUNCTION = server_service_web_init -ENABLE = NO SUBSYSTEM = smbd -PRIVATE_DEPENDENCIES = ESP LIBTLS smbcalls process_model +PRIVATE_DEPENDENCIES = LIBTLS smbcalls process_model LIBPYTHON # End SUBSYSTEM WEB ####################### -WEB_OBJ_FILES = $(addprefix $(web_serversrcdir)/, web_server.o esp.o wsgi.o) +WEB_OBJ_FILES = $(addprefix $(web_serversrcdir)/, web_server.o wsgi.o) $(eval $(call proto_header_template,$(web_serversrcdir)/proto.h,$(WEB_OBJ_FILES:.o=.c))) diff --git a/source4/web_server/esp.c b/source4/web_server/esp.c deleted file mode 100644 index 29bda2a965..0000000000 --- a/source4/web_server/esp.c +++ /dev/null @@ -1,1042 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - http handling code - - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "includes.h" -#include "smbd/service_task.h" -#include "web_server/web_server.h" -#include "smbd/service_stream.h" -#include "smbd/service.h" -#include "lib/events/events.h" -#include "system/time.h" -#include "system/wait.h" -#include "lib/appweb/esp/esp.h" -#include "lib/appweb/ejs/ejsInternal.h" -#include "lib/util/dlinklist.h" -#include "lib/tls/tls.h" -#include "scripting/ejs/smbcalls.h" -#include "param/param.h" - -#define SAMBA_SESSION_KEY "SambaSessionId" -#define HTTP_PREAUTH_URI "/scripting/preauth.esp" - -/* - context for long term storage in the web server, to support session[] - and application[] data. Stored in task->private. -*/ -struct esp_data { - struct session_data { - struct session_data *next, *prev; - struct esp_data *edata; - const char *id; - struct MprVar *data; - struct timed_event *te; - int lifetime; - } *sessions; - struct MprVar *application_data; -}; - - - -/* state of the esp subsystem for a specific request */ -struct esp_state { - struct websrv_context *web; - struct EspRequest *req; - struct MprVar variables[ESP_OBJ_MAX]; - struct session_data *session; -}; - -/* - output the http headers -*/ -static void http_output_headers(struct websrv_context *web) -{ - int i; - char *s; - DATA_BLOB b; - uint32_t content_length = 0; - const char *response_string = "Unknown Code"; - const struct { - unsigned code; - const char *response_string; - } codes[] = { - { 200, "OK" }, - { 301, "Moved" }, - { 302, "Found" }, - { 303, "Method" }, - { 304, "Not Modified" }, - { 400, "Bad request" }, - { 401, "Unauthorized" }, - { 403, "Forbidden" }, - { 404, "Not Found" }, - { 500, "Internal Server Error" }, - { 501, "Not implemented" } - }; - for (i=0;ioutput.response_code) { - response_string = codes[i].response_string; - } - } - - if (web->output.headers == NULL) return; - s = talloc_asprintf(web, "HTTP/1.0 %u %s\r\n", - web->output.response_code, response_string); - if (s == NULL) return; - for (i=0;web->output.headers[i];i++) { - s = talloc_asprintf_append_buffer(s, "%s\r\n", web->output.headers[i]); - } - - /* work out the content length */ - content_length = web->output.content.length; - if (web->output.fd != -1) { - struct stat st; - fstat(web->output.fd, &st); - content_length += st.st_size; - } - s = talloc_asprintf_append_buffer(s, "Content-Length: %u\r\n\r\n", content_length); - if (s == NULL) return; - - b = web->output.content; - web->output.content = data_blob_string_const(s); - data_blob_append(web, &web->output.content, b.data, b.length); - data_blob_free(&b); -} - -/* - return the local path for a URL -*/ -static const char *http_local_path(struct websrv_context *web, - const char *url, - const char *base_dir) -{ - int i; - char *path; - - /* check that the url is OK */ - if (url[0] != '/') return NULL; - - for (i=0;url[i];i++) { - if ((!isalnum((unsigned char)url[i]) && !strchr("./_-", url[i])) || - (url[i] == '.' && strchr("/.", url[i+1]))) { - return NULL; - } - } - - path = talloc_asprintf(web, "%s/%s", base_dir, url+1); - if (path == NULL) return NULL; - - if (directory_exist(path)) { - path = talloc_asprintf_append_buffer(path, "/index.esp"); - } - return path; -} - -/* - called when esp wants to read a file to support include() calls -*/ -static int http_readFile(EspHandle handle, - char **buf, - int *len, - const char *path, - const char *base_dir) -{ - struct websrv_context *web = talloc_get_type(handle, - struct websrv_context); - int fd = -1; - struct stat st; - *buf = NULL; - - path = http_local_path(web, path, base_dir); - if (path == NULL) goto failed; - - fd = open(path, O_RDONLY); - if (fd == -1 || fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) goto failed; - - *buf = talloc_array(handle, char, st.st_size+1); - if (*buf == NULL) goto failed; - - if (read(fd, *buf, st.st_size) != st.st_size) goto failed; - - (*buf)[st.st_size] = 0; - - close(fd); - *len = st.st_size; - return 0; - -failed: - DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno))); - if (fd != -1) close(fd); - talloc_free(*buf); - *buf = NULL; - return -1; -} - -static int http_readFileFromSwatDir(EspHandle handle, char **buf, int *len, - const char *path) -{ - return http_readFile(handle, buf, len, path, - lp_swat_directory(global_loadparm)); -} - - - -/* - called when esp wants to find the real path of a file -*/ -static int http_mapToStorage(EspHandle handle, char *path, int len, const char *uri, int flags) -{ - if (uri == NULL || strlen(uri) >= len) return -1; - strncpy(path, uri, len); - return 0; -} - -/* - called when esp wants to output something -*/ -static int http_writeBlock(EspHandle handle, const char *buf, int size) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - if (!data_blob_append(web, &web->output.content, buf, size)) - return -1; - return size; -} - - -/* - set a http header -*/ -static void http_setHeader(EspHandle handle, const char *value, bool allowMultiple) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - char *p = strchr(value, ':'); - - if (p && !allowMultiple && web->output.headers) { - int i; - for (i=0;web->output.headers[i];i++) { - if (strncmp(web->output.headers[i], value, (p+1)-value) == 0) { - web->output.headers[i] = talloc_strdup(web, value); - return; - } - } - } - - web->output.headers = str_list_add(web->output.headers, value); - talloc_steal(web, web->output.headers); -} - -/* - set a http response code -*/ -static void http_setResponseCode(EspHandle handle, int code) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - web->output.response_code = code; -} - -/* - redirect to another web page - */ -static void http_redirect(EspHandle handle, int code, char *url) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - const char *host = web->input.host; - - /* form the full url, unless it already looks like a url */ - if (strchr(url, ':') == NULL) { - if (host == NULL) { - struct socket_address *socket_address = socket_get_my_addr(web->conn->socket, web); - if (socket_address == NULL) goto internal_error; - host = talloc_asprintf(web, "%s:%u", - socket_address->addr, socket_address->port); - } - if (host == NULL) goto internal_error; - if (url[0] != '/') { - char *p = strrchr(web->input.url, '/'); - if (p == web->input.url) { - url = talloc_asprintf(web, "http%s://%s/%s", - tls_enabled(web->conn->socket)?"s":"", - host, url); - } else { - int dirlen = p - web->input.url; - url = talloc_asprintf(web, "http%s://%s%*.*s/%s", - tls_enabled(web->conn->socket)?"s":"", - host, - dirlen, dirlen, web->input.url, - url); - } - if (url == NULL) goto internal_error; - } - } - - http_setHeader(handle, talloc_asprintf(web, "Location: %s", url), 0); - - /* make sure we give a valid redirect code */ - if (code >= 300 && code < 400) { - http_setResponseCode(handle, code); - } else { - http_setResponseCode(handle, 302); - } - return; - -internal_error: - http_error(web, 500, "Internal server error"); -} - - -/* - setup a cookie -*/ -static void http_setCookie(EspHandle handle, const char *name, const char *value, - int lifetime, const char *path, bool secure) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - char *buf; - - if (lifetime > 0) { - buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; Expires=%s; %s", - name, value, path?path:"/", - http_timestring(web, time(NULL)+lifetime), - secure?"secure":""); - } else { - buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; %s", - name, value, path?path:"/", - secure?"secure":""); - } - http_setHeader(handle, "Cache-control: no-cache=\"set-cookie\"", 0); - http_setHeader(handle, buf, 0); - talloc_free(buf); -} - -/* - return the session id -*/ -static const char *http_getSessionId(EspHandle handle) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - return web->session->id; -} - -/* - setup a session -*/ -static void http_createSession(EspHandle handle, int timeout) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - if (web->session) { - web->session->lifetime = timeout; - http_setCookie(web, SAMBA_SESSION_KEY, web->session->id, - web->session->lifetime, "/", 0); - } -} - -/* - destroy a session -*/ -static void http_destroySession(EspHandle handle) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - talloc_free(web->session); - web->session = NULL; -} - - -/* - setup for a raw http level error -*/ -void http_error(struct websrv_context *web, int code, const char *info) -{ - char *s; - s = talloc_asprintf(web,"Error %u

Error %u

%s

\r\n\r\n", - code, code, info); - if (s == NULL) { - stream_terminate_connection(web->conn, "http_error: out of memory"); - return; - } - http_writeBlock(web, s, strlen(s)); - http_setResponseCode(web, code); - http_output_headers(web); - EVENT_FD_NOT_READABLE(web->conn->event.fde); - EVENT_FD_WRITEABLE(web->conn->event.fde); - web->output.output_pending = true; -} - -/* - map a unix error code to a http error -*/ -void http_error_unix(struct websrv_context *web, const char *info) -{ - int code = 500; - switch (errno) { - case ENOENT: - case EISDIR: - code = 404; - break; - case EACCES: - code = 403; - break; - } - info = talloc_asprintf(web, "%s

%s

\n", info, strerror(errno)); - http_error(web, code, info); -} - - -/* - a simple file request -*/ -static void http_simple_request(struct websrv_context *web) -{ - const char *url = web->input.url; - const char *path; - struct stat st; - - path = http_local_path(web, url, lp_swat_directory(web->task->lp_ctx)); - if (path == NULL) goto invalid; - - /* looks ok */ - web->output.fd = open(path, O_RDONLY); - if (web->output.fd == -1) { - DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno))); - http_error_unix(web, path); - return; - } - - if (fstat(web->output.fd, &st) != 0 || !S_ISREG(st.st_mode)) { - close(web->output.fd); - goto invalid; - } - - return; - -invalid: - http_error(web, 400, "Malformed URL"); -} - -/* - setup the standard ESP arrays -*/ -static void http_setup_arrays(struct web_server_data *wdata, struct esp_state *esp) -{ - struct websrv_context *web = esp->web; - struct EspRequest *req = esp->req; - struct socket_address *socket_address = socket_get_my_addr(web->conn->socket, esp); - struct socket_address *peer_address = socket_get_peer_addr(web->conn->socket, esp); - char *p; - -#define SETVAR(type, name, value) do { \ - const char *v = value; \ - if (v) espSetStringVar(req, type, name, v); \ -} while (0) - - SETVAR(ESP_REQUEST_OBJ, "CONTENT_LENGTH", - talloc_asprintf(esp, "%u", web->input.content_length)); - SETVAR(ESP_REQUEST_OBJ, "QUERY_STRING", web->input.query_string); - SETVAR(ESP_REQUEST_OBJ, "POST_DATA", - talloc_strndup(esp, - web->input.partial.data, - web->input.partial.length)); - SETVAR(ESP_REQUEST_OBJ, "REQUEST_METHOD", web->input.post_request?"POST":"GET"); - SETVAR(ESP_REQUEST_OBJ, "REQUEST_URI", web->input.url); - p = strrchr(web->input.url, '/'); - SETVAR(ESP_REQUEST_OBJ, "SCRIPT_NAME", p+1); - SETVAR(ESP_REQUEST_OBJ, "SCRIPT_FILENAME", web->input.url); - if (peer_address) { - struct MprVar mpv = mprObject("socket_address"); - mprSetPtrChild(&mpv, "socket_address", peer_address); - espSetVar(req, ESP_REQUEST_OBJ, "REMOTE_SOCKET_ADDRESS", mpv); - SETVAR(ESP_REQUEST_OBJ, "REMOTE_ADDR", peer_address->addr); - } - p = socket_get_peer_name(web->conn->socket, esp); - SETVAR(ESP_REQUEST_OBJ, "REMOTE_HOST", p); - SETVAR(ESP_REQUEST_OBJ, "REMOTE_USER", ""); - SETVAR(ESP_REQUEST_OBJ, "CONTENT_TYPE", web->input.content_type); - if (web->session) { - SETVAR(ESP_REQUEST_OBJ, "SESSION_ID", web->session->id); - } - SETVAR(ESP_REQUEST_OBJ, "COOKIE_SUPPORT", web->input.cookie?"true":"false"); - - SETVAR(ESP_HEADERS_OBJ, "HTTP_REFERER", web->input.referer); - SETVAR(ESP_HEADERS_OBJ, "HOST", web->input.host); - SETVAR(ESP_HEADERS_OBJ, "ACCEPT_ENCODING", web->input.accept_encoding); - SETVAR(ESP_HEADERS_OBJ, "ACCEPT_LANGUAGE", web->input.accept_language); - SETVAR(ESP_HEADERS_OBJ, "ACCEPT_CHARSET", web->input.accept_charset); - SETVAR(ESP_HEADERS_OBJ, "COOKIE", web->input.cookie); - SETVAR(ESP_HEADERS_OBJ, "USER_AGENT", web->input.user_agent); - - if (socket_address) { - SETVAR(ESP_SERVER_OBJ, "SERVER_ADDR", socket_address->addr); - SETVAR(ESP_SERVER_OBJ, "SERVER_NAME", socket_address->addr); - SETVAR(ESP_SERVER_OBJ, "SERVER_HOST", socket_address->addr); - SETVAR(ESP_SERVER_OBJ, "SERVER_PORT", - talloc_asprintf(esp, "%u", socket_address->port)); - } - - SETVAR(ESP_SERVER_OBJ, "DOCUMENT_ROOT", lp_swat_directory(esp->web->task->lp_ctx)); - SETVAR(ESP_SERVER_OBJ, "SERVER_PROTOCOL", tls_enabled(web->conn->socket)?"https":"http"); - SETVAR(ESP_SERVER_OBJ, "SERVER_SOFTWARE", "SAMBA"); - SETVAR(ESP_SERVER_OBJ, "GATEWAY_INTERFACE", "CGI/1.1"); - SETVAR(ESP_SERVER_OBJ, "TLS_SUPPORT", tls_support(wdata->tls_params)?"true":"false"); -} - -#if HAVE_SETJMP_H -/* the esp scripting lirary generates exceptions when - it hits a major error. We need to catch these and - report a internal server error via http -*/ -static jmp_buf ejs_exception_buf; -static const char *exception_reason; - -static void web_server_ejs_exception(const char *reason) -{ - Ejs *ep = ejsPtr(0); - if (ep) { - ejsSetErrorMsg(0, "%s", reason); - exception_reason = ep->error; - } else { - exception_reason = reason; - } - DEBUG(0,("%s", exception_reason)); - longjmp(ejs_exception_buf, -1); -} -#else -static void web_server_ejs_exception(const char *reason) -{ - DEBUG(0,("%s", reason)); - smb_panic(reason); -} -#endif - -/* - process a esp request -*/ -static void esp_request(struct esp_state *esp, const char *url) -{ - struct websrv_context *web = esp->web; - int size; - int res; - char *emsg = NULL, *buf; - - if (http_readFile(web, &buf, &size, url, lp_swat_directory(esp->web->task->lp_ctx)) != 0) { - http_error_unix(web, url); - return; - } - -#if HAVE_SETJMP_H - if (setjmp(ejs_exception_buf) != 0) { - http_error(web, 500, exception_reason); - return; - } -#endif - - res = espProcessRequest(esp->req, url, buf, &emsg); - if (res != 0 && emsg) { - http_writeBlock(web, "

", 5);
-		http_writeBlock(web, emsg, strlen(emsg));
-		http_writeBlock(web, "
", 6); - } - talloc_free(buf); -} - -/* - perform pre-authentication on every page if /scripting/preauth.esp - exists. If this script generates any non-whitepace output at all, - then we don't run the requested URL. - - note that the preauth is run even for static pages such as images -*/ -static bool http_preauth(struct esp_state *esp) -{ - const char *path = http_local_path(esp->web, - HTTP_PREAUTH_URI, - lp_swat_directory(esp->web->task->lp_ctx)); - int i; - if (path == NULL) { - http_error(esp->web, 500, "Internal server error"); - return false; - } - if (!file_exist(path)) { - /* if the preath script is not installed then allow access */ - return true; - } - esp_request(esp, HTTP_PREAUTH_URI); - for (i=0;iweb->output.content.length;i++) { - if (!isspace(esp->web->output.content.data[i])) { - /* if the preauth has generated content, then force it - to be html, so that we can show the login page for - failed access to images */ - http_setHeader(esp->web, "Content-Type: text/html", 0); - return false; - } - } - data_blob_free(&esp->web->output.content); - return true; -} - - -/* - handling of + and % escapes in http variables -*/ -static const char *http_unescape(TALLOC_CTX *mem_ctx, const char *p) -{ - char *s0 = talloc_strdup(mem_ctx, p); - char *s = s0; - if (s == NULL) return NULL; - - while (*s) { - unsigned v; - if (*s == '+') *s = ' '; - if (*s == '%' && sscanf(s+1, "%02x", &v) == 1) { - *s = (char)v; - memmove(s+1, s+3, strlen(s+3)+1); - } - s++; - } - - return s0; -} - -/* - set a form or GET variable -*/ -static void esp_putvar(struct esp_state *esp, const char *var, const char *value) -{ - if (strcasecmp(var, SAMBA_SESSION_KEY) == 0) { - /* special case support for browsers without cookie - support */ - esp->web->input.session_key = talloc_strdup(esp, value); - } else { - mprSetPropertyValue(&esp->variables[ESP_FORM_OBJ], - http_unescape(esp, var), - mprCreateStringVar(http_unescape(esp, value), 0)); - } -} - - -/* - parse the variables in a POST style request -*/ -static NTSTATUS http_parse_post(struct esp_state *esp) -{ - DATA_BLOB b = esp->web->input.partial; - - while (b.length) { - char *p, *line; - size_t len; - - p = memchr(b.data, '&', b.length); - if (p == NULL) { - len = b.length; - } else { - len = p - (char *)b.data; - } - line = talloc_strndup(esp, (char *)b.data, len); - NT_STATUS_HAVE_NO_MEMORY(line); - - p = strchr(line,'='); - if (p) { - *p = 0; - esp_putvar(esp, line, p+1); - } - talloc_free(line); - b.length -= len; - b.data += len; - if (b.length > 0) { - b.length--; - b.data++; - } - } - - return NT_STATUS_OK; -} - -/* - parse the variables in a GET style request -*/ -static NTSTATUS http_parse_get(struct esp_state *esp) -{ - struct websrv_context *web = esp->web; - char *p, *s, *tok; - char *pp; - - p = strchr(web->input.url, '?'); - web->input.query_string = p+1; - *p = 0; - - s = talloc_strdup(esp, esp->web->input.query_string); - NT_STATUS_HAVE_NO_MEMORY(s); - - for (tok=strtok_r(s,"&;", &pp);tok;tok=strtok_r(NULL,"&;", &pp)) { - p = strchr(tok,'='); - if (p) { - *p = 0; - esp_putvar(esp, tok, p+1); - } - } - return NT_STATUS_OK; -} - -/* - called when a session times out -*/ -static void session_timeout(struct event_context *ev, struct timed_event *te, - struct timeval t, void *private) -{ - struct session_data *s = talloc_get_type(private, struct session_data); - talloc_free(s); -} - -/* - destroy a session - */ -static int session_destructor(struct session_data *s) -{ - DLIST_REMOVE(s->edata->sessions, s); - return 0; -} - -/* - setup the session for this request -*/ -static void http_setup_session(struct esp_data *edata, struct esp_state *esp) -{ - const char *session_key = SAMBA_SESSION_KEY; - char *p; - const char *cookie = esp->web->input.cookie; - const char *key = NULL; - struct session_data *s; - bool generated_key = false; - - /* look for our session key */ - if (cookie && (p = strstr(cookie, session_key)) && - p[strlen(session_key)] == '=') { - p += strlen(session_key)+1; - key = talloc_strndup(esp, p, strcspn(p, ";")); - } - - if (key == NULL && esp->web->input.session_key) { - key = esp->web->input.session_key; - } else if (key == NULL) { - key = generate_random_str_list(esp, 16, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - generated_key = true; - } - - /* try to find this session in the existing session list */ - for (s=edata->sessions;s;s=s->next) { - if (strcmp(key, s->id) == 0) { - break; - } - } - - if (s == NULL) { - /* create a new session */ - s = talloc_zero(edata, struct session_data); - s->id = talloc_steal(s, key); - s->data = NULL; - s->te = NULL; - s->edata = edata; - s->lifetime = lp_parm_int(esp->web->task->lp_ctx, NULL, "web", "sessiontimeout", 900); - DLIST_ADD(edata->sessions, s); - talloc_set_destructor(s, session_destructor); - if (!generated_key) { - mprSetPropertyValue(&esp->variables[ESP_REQUEST_OBJ], - "SESSION_EXPIRED", mprCreateStringVar("true", 0)); - } - } - - http_setCookie(esp->web, session_key, key, s->lifetime, "/", 0); - - if (s->data) { - mprCopyVar(&esp->variables[ESP_SESSION_OBJ], s->data, MPR_DEEP_COPY); - } - - esp->web->session = s; -} - - -/* callbacks for esp processing */ -static const struct Esp esp_control = { - .maxScriptSize = 60000, - .writeBlock = http_writeBlock, - .setHeader = http_setHeader, - .redirect = http_redirect, - .setResponseCode = http_setResponseCode, - .readFile = http_readFileFromSwatDir, - .mapToStorage = http_mapToStorage, - .setCookie = http_setCookie, - .createSession = http_createSession, - .destroySession = http_destroySession, - .getSessionId = http_getSessionId -}; - -/* - process a complete http request -*/ -void esp_process_http_input(struct web_server_data *wdata, struct websrv_context *web) -{ - NTSTATUS status; - struct esp_state *esp = NULL; - struct esp_data *edata = talloc_get_type(wdata->private, struct esp_data); - struct smbcalls_context *smbcalls_ctx; - char *p; - void *save_mpr_ctx = mprMemCtx(); - void *ejs_save = ejs_save_state(); - int i; - const char *file_type = NULL; - enum page_type { - page_type_simple, - page_type_esp - }; - enum page_type page_type; - const struct { - const char *extension; - const char *mime_type; - enum page_type page_type; - } mime_types[] = { - {"gif", "image/gif"}, - {"png", "image/png"}, - {"jpg", "image/jpeg"}, - {"txt", "text/plain"}, - {"ico", "image/x-icon"}, - {"css", "text/css"}, - {"esp", "text/html", true} - }; - - /* - * give the smbcalls a chance to find the event context - * and messaging context - */ - smbcalls_ctx = talloc(web, struct smbcalls_context); - if (smbcalls_ctx == NULL) goto internal_error; - smbcalls_ctx->event_ctx = web->conn->event.ctx; - smbcalls_ctx->msg_ctx = web->conn->msg_ctx; - - esp = talloc_zero(smbcalls_ctx, struct esp_state); - if (esp == NULL) goto internal_error; - - esp->web = web; - - mprSetCtx(esp); - - if (espOpen(&esp_control) != 0) goto internal_error; - - for (i=0;ivariables);i++) { - esp->variables[i] = mprCreateUndefinedVar(); - } - esp->variables[ESP_HEADERS_OBJ] = mprCreateObjVar("headers", ESP_HASH_SIZE); - esp->variables[ESP_FORM_OBJ] = mprCreateObjVar("form", ESP_HASH_SIZE); - esp->variables[ESP_APPLICATION_OBJ] = mprCreateObjVar("application", ESP_HASH_SIZE); - esp->variables[ESP_COOKIES_OBJ] = mprCreateObjVar("cookies", ESP_HASH_SIZE); - esp->variables[ESP_FILES_OBJ] = mprCreateObjVar("files", ESP_HASH_SIZE); - esp->variables[ESP_REQUEST_OBJ] = mprCreateObjVar("request", ESP_HASH_SIZE); - esp->variables[ESP_SERVER_OBJ] = mprCreateObjVar("server", ESP_HASH_SIZE); - esp->variables[ESP_SESSION_OBJ] = mprCreateObjVar("session", ESP_HASH_SIZE); - - if (edata->application_data) { - mprCopyVar(&esp->variables[ESP_APPLICATION_OBJ], - edata->application_data, MPR_DEEP_COPY); - } - - smb_setup_ejs_functions(web_server_ejs_exception); - - if (web->input.url == NULL) { - http_error(web, 400, "You must specify a GET or POST request"); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - } - - /* parse any form or get variables */ - if (web->input.post_request) { - status = http_parse_post(esp); - if (!NT_STATUS_IS_OK(status)) { - http_error(web, 400, "Malformed POST data"); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - } - } - if (strchr(web->input.url, '?')) { - status = http_parse_get(esp); - if (!NT_STATUS_IS_OK(status)) { - http_error(web, 400, "Malformed GET data"); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - } - } - - http_setup_session(edata, esp); - - esp->req = espCreateRequest(web, web->input.url, esp->variables); - if (esp->req == NULL) goto internal_error; - - p = strrchr(web->input.url, '.'); - if (p == NULL) { - page_type = page_type_esp; - file_type = "text/html"; - } - for (i=0;p && iinput.url); - } - break; - } - - if (web->conn == NULL) { - /* the connection has been terminated above us, probably - via a timeout */ - goto internal_error; - } - - if (!web->output.output_pending) { - http_output_headers(web); - EVENT_FD_WRITEABLE(web->conn->event.fde); - web->output.output_pending = true; - } - - /* copy any application data to long term storage in edata */ - talloc_free(edata->application_data); - edata->application_data = talloc_zero(edata, struct MprVar); - mprSetCtx(edata->application_data); - mprCopyVar(edata->application_data, &esp->variables[ESP_APPLICATION_OBJ], - MPR_DEEP_COPY); - mprSetCtx(esp); - - /* copy any session data */ - if (web->session) { - talloc_free(web->session->data); - web->session->data = talloc_zero(web->session, struct MprVar); - if (esp->variables[ESP_SESSION_OBJ].properties == NULL || - esp->variables[ESP_SESSION_OBJ].properties[0].numItems == 0) { - talloc_free(web->session); - web->session = NULL; - } else { - mprSetCtx(web->session->data); - mprCopyVar(web->session->data, &esp->variables[ESP_SESSION_OBJ], - MPR_DEEP_COPY); - /* setup the timeout for the session data */ - mprSetCtx(esp); - talloc_free(web->session->te); - web->session->te = event_add_timed(web->conn->event.ctx, web->session, - timeval_current_ofs(web->session->lifetime, 0), - session_timeout, web->session); - } - } - - talloc_free(esp); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - -internal_error: - mprSetCtx(esp); - talloc_free(esp); - if (web->conn != NULL) { - http_error(web, 500, "Internal server error"); - } - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); -} - - -/* - parse one line of header input -*/ -NTSTATUS http_parse_header(struct websrv_context *web, const char *line) -{ - if (line[0] == 0) { - web->input.end_of_headers = true; - } else if (strncasecmp(line,"GET ", 4)==0) { - web->input.url = talloc_strndup(web, &line[4], strcspn(&line[4], " \t")); - } else if (strncasecmp(line,"POST ", 5)==0) { - web->input.post_request = true; - web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t")); - } else if (strchr(line, ':') == NULL) { - http_error(web, 400, "This server only accepts GET and POST requests"); - return NT_STATUS_INVALID_PARAMETER; - } else if (strncasecmp(line,"Content-Length: ", 16)==0) { - web->input.content_length = strtoul(&line[16], NULL, 10); - } else { -#define PULL_HEADER(v, s) do { \ - if (strncmp(line, s, strlen(s)) == 0) { \ - web->input.v = talloc_strdup(web, &line[strlen(s)]); \ - return NT_STATUS_OK; \ - } \ -} while (0) - PULL_HEADER(content_type, "Content-Type: "); - PULL_HEADER(user_agent, "User-Agent: "); - PULL_HEADER(referer, "Referer: "); - PULL_HEADER(host, "Host: "); - PULL_HEADER(accept_encoding, "Accept-Encoding: "); - PULL_HEADER(accept_language, "Accept-Language: "); - PULL_HEADER(accept_charset, "Accept-Charset: "); - PULL_HEADER(cookie, "Cookie: "); - } - - /* ignore all other headers for now */ - return NT_STATUS_OK; -} - - -/* - setup the esp processor - called at task initialisation -*/ -struct esp_data *http_setup_esp(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx) -{ - struct esp_data *edata; - - edata = talloc_zero(mem_ctx, struct esp_data); - if (edata == NULL) - return NULL; - - return edata; -} diff --git a/source4/web_server/web_server.c b/source4/web_server/web_server.c index 6d8b2a2758..20924ff0dc 100644 --- a/source4/web_server/web_server.c +++ b/source4/web_server/web_server.c @@ -4,6 +4,7 @@ web server startup Copyright (C) Andrew Tridgell 2005 + Copyright (C) Jelmer Vernooij 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 @@ -29,6 +30,7 @@ #include "system/network.h" #include "lib/socket/netif.h" #include "lib/tls/tls.h" +#include "lib/util/dlinklist.h" #include "param/param.h" /* don't allow connections to hang around forever */ @@ -61,6 +63,62 @@ static void websrv_timeout(struct event_context *event_context, stream_terminate_connection(conn, "websrv_timeout: timed out"); } +/* + setup for a raw http level error +*/ +void http_error(struct websrv_context *web, int code, const char *info) +{ + char *s; + s = talloc_asprintf(web,"Error %u

Error %u

%s

\r\n\r\n", + code, code, info); + if (s == NULL) { + stream_terminate_connection(web->conn, "http_error: out of memory"); + return; + } + /* FIXME: + http_writeBlock(web, s, strlen(s)); + http_setResponseCode(web, code); + http_output_headers(web); */ + EVENT_FD_NOT_READABLE(web->conn->event.fde); + EVENT_FD_WRITEABLE(web->conn->event.fde); + web->output.output_pending = true; +} + + +/* + parse one line of header input +*/ +NTSTATUS http_parse_header(struct websrv_context *web, const char *line) +{ + if (line[0] == 0) { + web->input.end_of_headers = true; + } else if (strncasecmp(line,"GET ", 4)==0) { + web->input.url = talloc_strndup(web, &line[4], strcspn(&line[4], " \t")); + } else if (strncasecmp(line,"POST ", 5)==0) { + web->input.post_request = true; + web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t")); + } else if (strchr(line, ':') == NULL) { + http_error(web, 400, "This server only accepts GET and POST requests"); + return NT_STATUS_INVALID_PARAMETER; + } else if (strncasecmp(line, "Content-Length: ", 16)==0) { + web->input.content_length = strtoul(&line[16], NULL, 10); + } else { + struct http_header *hdr = talloc_zero(web, struct http_header); + char *colon = strchr(line, ':'); + if (colon == NULL) { + http_error(web, 500, "invalidly formatted header"); + return NT_STATUS_INVALID_PARAMETER; + } + + hdr->name = talloc_strndup(hdr, line, colon-line); + hdr->value = talloc_strdup(hdr, colon+1); + DLIST_ADD(web->input.headers, hdr); + } + + /* ignore all other headers for now */ + return NT_STATUS_OK; +} + /* called when a web connection becomes readable */ @@ -199,7 +257,7 @@ static void websrv_accept(struct stream_connection *conn) web = talloc_zero(conn, struct websrv_context); if (web == NULL) goto failed; - web->http_process_input = esp_process_http_input; + web->http_process_input = wsgi_process_http_input; web->task = task; web->conn = conn; conn->private = web; @@ -290,9 +348,6 @@ static void websrv_task_init(struct task_server *task) wdata->tls_params = tls_initialise(wdata, task->lp_ctx); if (wdata->tls_params == NULL) goto failed; - wdata->private = http_setup_esp(task, task->lp_ctx); - if (wdata->private == NULL) goto failed; - return; failed: diff --git a/source4/web_server/web_server.h b/source4/web_server/web_server.h index 0ce68bdd17..7375a2e9ca 100644 --- a/source4/web_server/web_server.h +++ b/source4/web_server/web_server.h @@ -24,6 +24,12 @@ struct web_server_data { void *private; }; +struct http_header { + char *name; + char *value; + struct http_header *prev, *next; +}; + /* context of one open web connection */ @@ -40,16 +46,8 @@ struct websrv_context { char *url; unsigned content_length; bool post_request; + struct http_header *headers; const char *content_type; - const char *query_string; - const char *user_agent; - const char *referer; - const char *host; - const char *accept_encoding; - const char *accept_language; - const char *accept_charset; - const char *cookie; - const char *session_key; } input; struct { bool output_pending; @@ -57,7 +55,7 @@ struct websrv_context { int fd; unsigned nsent; int response_code; - const char **headers; + struct http_header *headers; } output; struct session_data *session; }; diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 32b1f0dbc2..3391065dae 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -32,7 +32,7 @@ static PyObject *start_response(PyObject *self, PyObject *args, PyObject *kwargs "status", "response_header", "exc_info", NULL }; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *)"sOO:start_response", (char **)kwnames, &status, &response_header, &exc_info)) { + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sOO:start_response", discard_const_p(char *, kwnames), &status, &response_header, &exc_info)) { return NULL; } @@ -57,7 +57,7 @@ static PyObject *py_error_write(PyObject *self, PyObject *args, PyObject *kwargs const char *kwnames[] = { "str", NULL }; char *str = NULL; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *)"s:write", (char **)kwnames, &str)) { + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s:write", discard_const_p(char *, kwnames), &str)) { return NULL; } @@ -71,7 +71,7 @@ static PyObject *py_error_writelines(PyObject *self, PyObject *args, PyObject *k const char *kwnames[] = { "seq", NULL }; PyObject *seq = NULL, *item; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *)"O:writelines", (char **)kwnames, &seq)) { + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:writelines", discard_const_p(char *, kwnames), &seq)) { return NULL; } @@ -141,14 +141,14 @@ PyTypeObject input_Stream_Type = { static PyObject *Py_InputHttpStream(void *foo) { - PyObject *ret = PyObject_New(input_Stream_Object, &input_Stream_Type); - return ret; + input_Stream_Object *ret = PyObject_New(input_Stream_Object, &input_Stream_Type); + return (PyObject *)ret; } static PyObject *Py_ErrorHttpStream(void) { - PyObject *ret = PyObject_New(error_Stream_Object, &error_Stream_Type); - return ret; + error_Stream_Object *ret = PyObject_New(error_Stream_Object, &error_Stream_Type); + return (PyObject *)ret; } static PyObject *create_environ(void) -- cgit From 7e5f345cfe2f553bca65deccb4b47f19f9208a5b Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sun, 21 Sep 2008 18:09:55 +0200 Subject: Fix the build -- appweb is no more --- source3/samba4.m4 | 1 - 1 file changed, 1 deletion(-) diff --git a/source3/samba4.m4 b/source3/samba4.m4 index c02d3d4b3b..728fd2d45d 100644 --- a/source3/samba4.m4 +++ b/source3/samba4.m4 @@ -95,7 +95,6 @@ m4_include(ntvfs/unixuid/config.m4) m4_include(auth/config.m4) m4_include(kdc/config.m4) m4_include(ntvfs/sysdep/config.m4) -m4_include(lib/appweb/config.m4) m4_include(nsswitch/config.m4) dnl Samba 4 files -- cgit From 4141e70da97d924969b48fcd198e5996d615e75d Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 18:45:09 +0200 Subject: Properly call WSGI request handler when requests come in. --- source4/web_server/swat/__init__.py | 3 +- source4/web_server/web_server.c | 42 +++----- source4/web_server/web_server.h | 13 +-- source4/web_server/wsgi.c | 204 +++++++++++++++++++++++++++++++----- 4 files changed, 198 insertions(+), 64 deletions(-) diff --git a/source4/web_server/swat/__init__.py b/source4/web_server/swat/__init__.py index e0d85dbe2c..580097186c 100644 --- a/source4/web_server/swat/__init__.py +++ b/source4/web_server/swat/__init__.py @@ -1,4 +1,5 @@ #!/usr/bin/python +# -*- coding: utf-8 -*- # Unix SMB/CIFS implementation. # Copyright © Jelmer Vernooij 2008 @@ -19,7 +20,7 @@ # along with this program. If not, see . # -def SWAT(environ, start_response): +def __call__(environ, start_response): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) diff --git a/source4/web_server/web_server.c b/source4/web_server/web_server.c index 20924ff0dc..1a3c48a03d 100644 --- a/source4/web_server/web_server.c +++ b/source4/web_server/web_server.c @@ -41,9 +41,6 @@ */ static int websrv_destructor(struct websrv_context *web) { - if (web->output.fd != -1) { - close(web->output.fd); - } return 0; } @@ -84,6 +81,11 @@ void http_error(struct websrv_context *web, int code, const char *info) web->output.output_pending = true; } +void websrv_output_headers(struct websrv_context *web, const char *status, struct http_header *headers) +{ + /* FIXME */ +} + /* parse one line of header input @@ -124,6 +126,7 @@ NTSTATUS http_parse_header(struct websrv_context *web, const char *line) */ static void websrv_recv(struct stream_connection *conn, uint16_t flags) { + struct web_server_data *wdata; struct websrv_context *web = talloc_get_type(conn->private, struct websrv_context); NTSTATUS status; @@ -181,7 +184,9 @@ static void websrv_recv(struct stream_connection *conn, uint16_t flags) destroy the stack variables being used by that rendering process when we handle the timeout. */ if (!talloc_reference(web->task, web)) goto failed; - web->http_process_input(web); + wdata = talloc_get_type(web->task->private, struct web_server_data); + if (wdata == NULL) goto failed; + wdata->http_process_input(wdata, web); talloc_unlink(web->task, web); } return; @@ -191,6 +196,7 @@ failed: } + /* called when a web connection becomes writable */ @@ -217,29 +223,7 @@ static void websrv_send(struct stream_connection *conn, uint16_t flags) web->output.nsent += nsent; - /* possibly read some more raw data from a file */ - if (web->output.content.length == web->output.nsent && - web->output.fd != -1) { - uint8_t buf[2048]; - ssize_t nread; - - data_blob_free(&web->output.content); - web->output.nsent = 0; - - nread = read(web->output.fd, buf, sizeof(buf)); - if (nread == -1 && errno == EINTR) { - return; - } - if (nread <= 0) { - close(web->output.fd); - web->output.fd = -1; - nread = 0; - } - web->output.content = data_blob_talloc(web, buf, nread); - } - - if (web->output.content.length == web->output.nsent && - web->output.fd == -1) { + if (web->output.content.length == web->output.nsent) { stream_terminate_connection(web->conn, "websrv_send: finished sending"); } } @@ -257,11 +241,9 @@ static void websrv_accept(struct stream_connection *conn) web = talloc_zero(conn, struct websrv_context); if (web == NULL) goto failed; - web->http_process_input = wsgi_process_http_input; web->task = task; web->conn = conn; conn->private = web; - web->output.fd = -1; talloc_set_destructor(web, websrv_destructor); event_add_timed(conn->event.ctx, web, @@ -348,6 +330,8 @@ static void websrv_task_init(struct task_server *task) wdata->tls_params = tls_initialise(wdata, task->lp_ctx); if (wdata->tls_params == NULL) goto failed; + if (!wsgi_initialize(wdata)) goto failed; + return; failed: diff --git a/source4/web_server/web_server.h b/source4/web_server/web_server.h index 7375a2e9ca..0cc299f332 100644 --- a/source4/web_server/web_server.h +++ b/source4/web_server/web_server.h @@ -19,8 +19,12 @@ #include "smbd/process_model.h" +struct websrv_context; + struct web_server_data { struct tls_params *tls_params; + void (*http_process_input)(struct web_server_data *wdata, + struct websrv_context *web); void *private; }; @@ -36,8 +40,7 @@ struct http_header { struct websrv_context { struct task_server *task; struct stream_connection *conn; - void (*http_process_input)(struct websrv_context *web); - struct { + struct websrv_request_input { bool tls_detect; bool tls_first_char; uint8_t first_byte; @@ -49,13 +52,11 @@ struct websrv_context { struct http_header *headers; const char *content_type; } input; - struct { + struct websrv_request_output { bool output_pending; DATA_BLOB content; - int fd; + bool headers_sent; unsigned nsent; - int response_code; - struct http_header *headers; } output; struct session_data *session; }; diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 3391065dae..0709e0ba39 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -22,26 +22,90 @@ #include "includes.h" #include "web_server/web_server.h" +#include "lib/util/dlinklist.h" +#include "lib/util/data_blob.h" #include +typedef struct { + PyObject_HEAD + struct websrv_context *web; +} web_request_Object; + static PyObject *start_response(PyObject *self, PyObject *args, PyObject *kwargs) { - PyObject *response_header, *exc_info; + PyObject *response_header, *exc_info = NULL; char *status; + int i; const char *kwnames[] = { "status", "response_header", "exc_info", NULL }; + web_request_Object *py_web = (web_request_Object *)self; + struct websrv_context *web = py_web->web; + struct http_header *headers = NULL; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sOO:start_response", discard_const_p(char *, kwnames), &status, &response_header, &exc_info)) { + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|O:start_response", discard_const_p(char *, kwnames), &status, &response_header, &exc_info)) { return NULL; } - /* FIXME: response_header, exc_info */ + /* FIXME: exc_info */ - /* FIXME: Wrap stdout */ - return NULL; + if (!PyList_Check(response_header)) { + PyErr_SetString(PyExc_TypeError, "response_header should be list"); + return NULL; + } + + for (i = 0; i < PyList_Size(response_header); i++) { + struct http_header *hdr = talloc_zero(web, struct http_header); + PyObject *item = PyList_GetItem(response_header, i); + PyObject *py_name, *py_value; + + if (!PyTuple_Check(item)) { + PyErr_SetString(PyExc_TypeError, "Expected tuple"); + return NULL; + } + + if (PyTuple_Size(item) != 2) { + PyErr_SetString(PyExc_TypeError, "header tuple has invalid size, expected 2"); + return NULL; + } + + py_name = PyTuple_GetItem(item, 0); + + if (!PyString_Check(py_name)) { + PyErr_SetString(PyExc_TypeError, "header name should be string"); + return NULL; + } + + py_value = PyTuple_GetItem(item, 1); + if (!PyString_Check(py_value)) { + PyErr_SetString(PyExc_TypeError, "header value should be string"); + return NULL; + } + + hdr->name = talloc_strdup(hdr, PyString_AsString(py_name)); + hdr->value = talloc_strdup(hdr, PyString_AsString(py_value)); + DLIST_ADD(headers, hdr); + } + + websrv_output_headers(web, status, headers); + + return Py_None; } +static PyMethodDef web_request_methods[] = { + { "start_response", (PyCFunction)start_response, METH_VARARGS|METH_KEYWORDS, NULL }, + { NULL } +}; + + +PyTypeObject web_request_Type = { + PyObject_HEAD_INIT(NULL) 0, + .tp_name = "wsgi.Request", + .tp_methods = web_request_methods, + .tp_basicsize = sizeof(web_request_Object), + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, +}; + typedef struct { PyObject_HEAD } error_Stream_Object; @@ -85,9 +149,9 @@ static PyObject *py_error_writelines(PyObject *self, PyObject *args, PyObject *k } static PyMethodDef error_Stream_methods[] = { - { "flush", (PyCFunction)py_error_flush, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, - { "write", (PyCFunction)py_error_write, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, - { "writelines", (PyCFunction)py_error_writelines, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "flush", (PyCFunction)py_error_flush, METH_VARARGS|METH_KEYWORDS, NULL }, + { "write", (PyCFunction)py_error_write, METH_VARARGS|METH_KEYWORDS, NULL }, + { "writelines", (PyCFunction)py_error_writelines, METH_VARARGS|METH_KEYWORDS, NULL }, { NULL, NULL, 0, NULL } }; @@ -105,29 +169,33 @@ typedef struct { static PyObject *py_input_read(PyObject *self, PyObject *args, PyObject *kwargs) { + /* FIXME */ return NULL; } static PyObject *py_input_readline(PyObject *self, PyObject *args, PyObject *kwargs) { + /* FIXME */ return NULL; } static PyObject *py_input_readlines(PyObject *self, PyObject *args, PyObject *kwargs) { + /* FIXME */ return NULL; } static PyObject *py_input___iter__(PyObject *self, PyObject *args, PyObject *kwargs) { + /* FIXME */ return NULL; } static PyMethodDef input_Stream_methods[] = { - { "read", (PyCFunction)py_input_read, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, - { "readline", (PyCFunction)py_input_readline, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, - { "readlines", (PyCFunction)py_input_readlines, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, - { "__iter__", (PyCFunction)py_input___iter__, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "read", (PyCFunction)py_input_read, METH_VARARGS|METH_KEYWORDS, NULL }, + { "readline", (PyCFunction)py_input_readline, METH_VARARGS|METH_KEYWORDS, NULL }, + { "readlines", (PyCFunction)py_input_readlines, METH_VARARGS|METH_KEYWORDS, NULL }, + { "__iter__", (PyCFunction)py_input___iter__, METH_VARARGS|METH_KEYWORDS, NULL }, { NULL, NULL, 0, NULL } }; @@ -151,20 +219,17 @@ static PyObject *Py_ErrorHttpStream(void) return (PyObject *)ret; } -static PyObject *create_environ(void) +static PyObject *create_environ(bool tls, int content_length, const char *content_type, struct http_header *headers, const char *request_method) { - PyObject *env, *osmodule, *osenviron; + PyObject *env; PyObject *inputstream, *errorstream; - - osmodule = PyImport_ImportModule("os"); - if (osmodule == NULL) + PyObject *py_scheme; + struct http_header *hdr; + + env = PyDict_New(); + if (env == NULL) { return NULL; - - osenviron = PyObject_CallMethod(osmodule, "environ", NULL); - - env = PyDict_Copy(osenviron); - - Py_DECREF(env); + } inputstream = Py_InputHttpStream(NULL); if (inputstream == NULL) { @@ -185,16 +250,99 @@ static PyObject *create_environ(void) PyDict_SetItemString(env, "wsgi.multithread", Py_False); PyDict_SetItemString(env, "wsgi.multiprocess", Py_True); PyDict_SetItemString(env, "wsgi.run_once", Py_False); + PyDict_SetItemString(env, "SERVER_PROTOCOL", PyString_FromString("HTTP/1.0")); + if (content_type != NULL) { + PyDict_SetItemString(env, "CONTENT_TYPE", PyString_FromString(content_type)); + } + if (content_length > 0) { + PyDict_SetItemString(env, "CONTENT_LENGTH", PyLong_FromLong(content_length)); + } + PyDict_SetItemString(env, "REQUEST_METHOD", PyString_FromString(request_method)); + + /* FIXME: SCRIPT_NAME */ + /* FIXME: PATH_INFO */ + /* FIXME: QUERY_STRING */ + /* FIXME: SERVER_NAME, SERVER_PORT */ + + for (hdr = headers; hdr; hdr = hdr->next) { + char *name; + asprintf(&name, "HTTP_%s", hdr->name); + PyDict_SetItemString(env, name, PyString_FromString(hdr->value)); + free(name); + } - /* FIXME: - PyDict_SetItemString(env, "wsgi.url_scheme", "http"); - PyDict_SetItemString(env, "wsgi.url_scheme", "https"); - */ + if (tls) { + py_scheme = PyString_FromString("https"); + } else { + py_scheme = PyString_FromString("http"); + } + PyDict_SetItemString(env, "wsgi.url_scheme", py_scheme); return env; } -void wsgi_process_http_input(struct websrv_context *web) +static void wsgi_process_http_input(struct web_server_data *wdata, + struct websrv_context *web) +{ + PyObject *py_environ, *result, *item, *iter; + PyObject *request_handler = wdata->private; + + web_request_Object *py_web = PyObject_New(web_request_Object, &web_request_Type); + py_web->web = web; + + py_environ = create_environ(false /* FIXME: Figure out whether we're using tls */, + web->input.content_length, + web->input.content_type, + web->input.headers, + web->input.post_request?"POST":"GET"); + if (py_environ == NULL) { + DEBUG(0, ("Unable to create WSGI environment object\n")); + return; + } + + result = PyObject_CallMethod(request_handler, discard_const_p(char, "__call__"), discard_const_p(char, "OO"), + py_environ, PyObject_GetAttrString((PyObject *)py_web, "start_response")); + + if (result == NULL) { + DEBUG(0, ("error while running WSGI code\n")); + return; + } + + iter = PyObject_GetIter(result); + Py_DECREF(result); + + /* Now, iter over all the data returned */ + + while ((item = PyIter_Next(iter))) { + data_blob_append(web, &web->output.content, + PyString_AsString(item), PyString_Size(item)); + Py_DECREF(item); + } + + Py_DECREF(iter); +} + +bool wsgi_initialize(struct web_server_data *wdata) { + PyObject *py_swat; + Py_Initialize(); + + if (PyType_Ready(&web_request_Type) < 0) + return false; + + if (PyType_Ready(&input_Stream_Type) < 0) + return false; + + if (PyType_Ready(&error_Stream_Type) < 0) + return false; + + wdata->http_process_input = wsgi_process_http_input; + py_swat = PyImport_Import(PyString_FromString("swat")); + if (py_swat == NULL) { + DEBUG(0, ("Unable to find SWAT\n")); + return false; + } + wdata->private = py_swat; + return true; } -- cgit From 1ed040d8e22a63079c72126bbc896fa3c32c7f0f Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 19:03:12 +0200 Subject: First GET request works. SWAT now displays a Hello world message. --- source4/web_server/web_server.c | 44 +++++++++++++++++++++++++++++------------ source4/web_server/wsgi.c | 3 +-- 2 files changed, 32 insertions(+), 15 deletions(-) diff --git a/source4/web_server/web_server.c b/source4/web_server/web_server.c index 1a3c48a03d..1ed37f657b 100644 --- a/source4/web_server/web_server.c +++ b/source4/web_server/web_server.c @@ -63,27 +63,45 @@ static void websrv_timeout(struct event_context *event_context, /* setup for a raw http level error */ -void http_error(struct websrv_context *web, int code, const char *info) +void http_error(struct websrv_context *web, const char *status, const char *info) { char *s; - s = talloc_asprintf(web,"Error %u

Error %u

%s

\r\n\r\n", - code, code, info); + s = talloc_asprintf(web,"Error %s

Error %s

%s

\r\n\r\n", + status, status, info); if (s == NULL) { stream_terminate_connection(web->conn, "http_error: out of memory"); return; } - /* FIXME: - http_writeBlock(web, s, strlen(s)); - http_setResponseCode(web, code); - http_output_headers(web); */ - EVENT_FD_NOT_READABLE(web->conn->event.fde); - EVENT_FD_WRITEABLE(web->conn->event.fde); - web->output.output_pending = true; + websrv_output_headers(web, status, NULL); + websrv_output(web, s, strlen(s)); } void websrv_output_headers(struct websrv_context *web, const char *status, struct http_header *headers) { - /* FIXME */ + char *s; + DATA_BLOB b; + struct http_header *hdr; + + s = talloc_asprintf(web, "HTTP/1.0 %s\r\n", status); + if (s == NULL) return; + for (hdr = headers; hdr; hdr = hdr->next) { + s = talloc_asprintf_append_buffer(s, "%s: %s\r\n", hdr->name, hdr->value); + } + + s = talloc_asprintf_append_buffer(s, "\r\n"); + + b = web->output.content; + web->output.content = data_blob_string_const(s); + websrv_output(web, b.data, b.length); + data_blob_free(&b); +} + +void websrv_output(struct websrv_context *web, void *data, size_t length) +{ + data_blob_append(web, &web->output.content, data, length); + EVENT_FD_NOT_READABLE(web->conn->event.fde); + EVENT_FD_WRITEABLE(web->conn->event.fde); + web->output.output_pending = true; } @@ -100,7 +118,7 @@ NTSTATUS http_parse_header(struct websrv_context *web, const char *line) web->input.post_request = true; web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t")); } else if (strchr(line, ':') == NULL) { - http_error(web, 400, "This server only accepts GET and POST requests"); + http_error(web, "400 Bad request", "This server only accepts GET and POST requests"); return NT_STATUS_INVALID_PARAMETER; } else if (strncasecmp(line, "Content-Length: ", 16)==0) { web->input.content_length = strtoul(&line[16], NULL, 10); @@ -108,7 +126,7 @@ NTSTATUS http_parse_header(struct websrv_context *web, const char *line) struct http_header *hdr = talloc_zero(web, struct http_header); char *colon = strchr(line, ':'); if (colon == NULL) { - http_error(web, 500, "invalidly formatted header"); + http_error(web, "500 Internal Server Error", "invalidly formatted header"); return NT_STATUS_INVALID_PARAMETER; } diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 0709e0ba39..3d5d0b4bf0 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -314,8 +314,7 @@ static void wsgi_process_http_input(struct web_server_data *wdata, /* Now, iter over all the data returned */ while ((item = PyIter_Next(iter))) { - data_blob_append(web, &web->output.content, - PyString_AsString(item), PyString_Size(item)); + websrv_output(web, PyString_AsString(item), PyString_Size(item)); Py_DECREF(item); } -- cgit From ef8d9f8a756936578dc770a0ec275e57aa3ee51b Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 20:00:44 +0200 Subject: Make standard SWAT script print received headers. --- source4/web_server/swat/__init__.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/source4/web_server/swat/__init__.py b/source4/web_server/swat/__init__.py index 580097186c..8229d15a3c 100644 --- a/source4/web_server/swat/__init__.py +++ b/source4/web_server/swat/__init__.py @@ -22,7 +22,13 @@ def __call__(environ, start_response): status = '200 OK' - response_headers = [('Content-type','text/plain')] + response_headers = [('Content-type','text/html')] start_response(status, response_headers) - return ['Hello world!\n'] + yield '\n' + + for key, value in environ.items(): + if isinstance(value, str): + yield '\t\n' % (key, value) + + yield '
%s%s
\n' -- cgit From f3d513b378fcc094255264de0c73f96fac461b68 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 20:01:00 +0200 Subject: Support POST requests again, provide more variables in environment. --- source4/web_server/web_server.h | 1 - source4/web_server/wsgi.c | 106 ++++++++++++++++++++++++++++------------ 2 files changed, 75 insertions(+), 32 deletions(-) diff --git a/source4/web_server/web_server.h b/source4/web_server/web_server.h index 0cc299f332..f91c766494 100644 --- a/source4/web_server/web_server.h +++ b/source4/web_server/web_server.h @@ -50,7 +50,6 @@ struct websrv_context { unsigned content_length; bool post_request; struct http_header *headers; - const char *content_type; } input; struct websrv_request_output { bool output_pending; diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 3d5d0b4bf0..66697868e0 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -24,6 +24,7 @@ #include "web_server/web_server.h" #include "lib/util/dlinklist.h" #include "lib/util/data_blob.h" +#include "lib/tls/tls.h" #include typedef struct { @@ -165,37 +166,71 @@ PyTypeObject error_Stream_Type = { typedef struct { PyObject_HEAD + struct websrv_context *web; + size_t offset; } input_Stream_Object; -static PyObject *py_input_read(PyObject *self, PyObject *args, PyObject *kwargs) +static PyObject *py_input_read(PyObject *_self, PyObject *args, PyObject *kwargs) { - /* FIXME */ - return NULL; + const char *kwnames[] = { "size", NULL }; + PyObject *ret; + input_Stream_Object *self = (input_Stream_Object *)_self; + int size = -1; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", discard_const_p(char *, kwnames), &size)) + return NULL; + + /* Don't read beyond buffer boundaries */ + if (size == -1) + size = self->web->input.partial.length-self->offset; + else + size = MIN(size, self->web->input.partial.length-self->offset); + + ret = PyString_FromStringAndSize((char *)self->web->input.partial.data+self->offset, size); + self->offset += size; + + return ret; } -static PyObject *py_input_readline(PyObject *self, PyObject *args, PyObject *kwargs) +static PyObject *py_input_readline(PyObject *_self) { + input_Stream_Object *self = (input_Stream_Object *)_self; /* FIXME */ + PyErr_SetString(PyExc_NotImplementedError, + "readline() not yet implemented"); return NULL; } -static PyObject *py_input_readlines(PyObject *self, PyObject *args, PyObject *kwargs) +static PyObject *py_input_readlines(PyObject *_self, PyObject *args, PyObject *kwargs) { + const char *kwnames[] = { "hint", NULL }; + PyObject *ret; + int hint; + input_Stream_Object *self = (input_Stream_Object *)_self; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", discard_const_p(char *, kwnames), &hint)) + return NULL; + /* FIXME */ + PyErr_SetString(PyExc_NotImplementedError, + "readlines() not yet implemented"); return NULL; } -static PyObject *py_input___iter__(PyObject *self, PyObject *args, PyObject *kwargs) +static PyObject *py_input___iter__(PyObject *_self) { + input_Stream_Object *self = (input_Stream_Object *)_self; /* FIXME */ + PyErr_SetString(PyExc_NotImplementedError, + "__iter__() not yet implemented"); return NULL; } static PyMethodDef input_Stream_methods[] = { { "read", (PyCFunction)py_input_read, METH_VARARGS|METH_KEYWORDS, NULL }, - { "readline", (PyCFunction)py_input_readline, METH_VARARGS|METH_KEYWORDS, NULL }, + { "readline", (PyCFunction)py_input_readline, METH_NOARGS, NULL }, { "readlines", (PyCFunction)py_input_readlines, METH_VARARGS|METH_KEYWORDS, NULL }, - { "__iter__", (PyCFunction)py_input___iter__, METH_VARARGS|METH_KEYWORDS, NULL }, + { "__iter__", (PyCFunction)py_input___iter__, METH_NOARGS, NULL }, { NULL, NULL, 0, NULL } }; @@ -207,9 +242,11 @@ PyTypeObject input_Stream_Type = { .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, }; -static PyObject *Py_InputHttpStream(void *foo) +static PyObject *Py_InputHttpStream(struct websrv_context *web) { input_Stream_Object *ret = PyObject_New(input_Stream_Object, &input_Stream_Type); + ret->web = web; + ret->offset = 0; return (PyObject *)ret; } @@ -219,24 +256,19 @@ static PyObject *Py_ErrorHttpStream(void) return (PyObject *)ret; } -static PyObject *create_environ(bool tls, int content_length, const char *content_type, struct http_header *headers, const char *request_method) +static PyObject *create_environ(bool tls, int content_length, struct http_header *headers, const char *request_method, const char *servername, int serverport, PyObject *inputstream, const char *request_string) { PyObject *env; - PyObject *inputstream, *errorstream; + PyObject *errorstream; PyObject *py_scheme; struct http_header *hdr; + char *questionmark; env = PyDict_New(); if (env == NULL) { return NULL; } - inputstream = Py_InputHttpStream(NULL); - if (inputstream == NULL) { - Py_DECREF(env); - return NULL; - } - errorstream = Py_ErrorHttpStream(); if (errorstream == NULL) { Py_DECREF(env); @@ -251,24 +283,30 @@ static PyObject *create_environ(bool tls, int content_length, const char *conten PyDict_SetItemString(env, "wsgi.multiprocess", Py_True); PyDict_SetItemString(env, "wsgi.run_once", Py_False); PyDict_SetItemString(env, "SERVER_PROTOCOL", PyString_FromString("HTTP/1.0")); - if (content_type != NULL) { - PyDict_SetItemString(env, "CONTENT_TYPE", PyString_FromString(content_type)); - } if (content_length > 0) { PyDict_SetItemString(env, "CONTENT_LENGTH", PyLong_FromLong(content_length)); } PyDict_SetItemString(env, "REQUEST_METHOD", PyString_FromString(request_method)); - /* FIXME: SCRIPT_NAME */ - /* FIXME: PATH_INFO */ - /* FIXME: QUERY_STRING */ - /* FIXME: SERVER_NAME, SERVER_PORT */ - + questionmark = strchr(request_string, '?'); + if (questionmark == NULL) { + PyDict_SetItemString(env, "SCRIPT_NAME", PyString_FromString(request_string)); + } else { + PyDict_SetItemString(env, "QUERY_STRING", PyString_FromString(questionmark+1)); + PyDict_SetItemString(env, "SCRIPT_NAME", PyString_FromStringAndSize(request_string, questionmark-request_string)); + } + + PyDict_SetItemString(env, "SERVER_NAME", PyString_FromString(servername)); + PyDict_SetItemString(env, "SERVER_PORT", PyInt_FromLong(serverport)); for (hdr = headers; hdr; hdr = hdr->next) { char *name; - asprintf(&name, "HTTP_%s", hdr->name); - PyDict_SetItemString(env, name, PyString_FromString(hdr->value)); - free(name); + if (!strcasecmp(hdr->name, "Content-Type")) { + PyDict_SetItemString(env, "CONTENT_TYPE", PyString_FromString(hdr->value)); + } else { + asprintf(&name, "HTTP_%s", hdr->name); + PyDict_SetItemString(env, name, PyString_FromString(hdr->value)); + free(name); + } } if (tls) { @@ -286,15 +324,21 @@ static void wsgi_process_http_input(struct web_server_data *wdata, { PyObject *py_environ, *result, *item, *iter; PyObject *request_handler = wdata->private; + struct socket_address *socket_address; web_request_Object *py_web = PyObject_New(web_request_Object, &web_request_Type); py_web->web = web; - py_environ = create_environ(false /* FIXME: Figure out whether we're using tls */, + socket_address = socket_get_my_addr(web->conn->socket, web); + py_environ = create_environ(tls_enabled(web->conn->socket), web->input.content_length, - web->input.content_type, web->input.headers, - web->input.post_request?"POST":"GET"); + web->input.post_request?"POST":"GET", + socket_address->addr, + socket_address->port, + Py_InputHttpStream(web), + web->input.url + ); if (py_environ == NULL) { DEBUG(0, ("Unable to create WSGI environment object\n")); return; -- cgit From bbfce1b43d183cdccbe6f9a189098091f9d4a251 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 20:06:18 +0200 Subject: Allow SWAT to be run outside of smbd. --- source4/web_server/swat/__init__.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/source4/web_server/swat/__init__.py b/source4/web_server/swat/__init__.py index 8229d15a3c..d434bb260b 100644 --- a/source4/web_server/swat/__init__.py +++ b/source4/web_server/swat/__init__.py @@ -32,3 +32,8 @@ def __call__(environ, start_response): yield '\n' +if __name__ == '__main__': + from wsgiref import simple_server + httpd = simple_server.make_server('localhost', 8090, __call__) + print "Serving HTTP on port 8090..." + httpd.serve_forever() -- cgit From 0e9008be35a5b334bd65e6417193d4b8f27bdc36 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 21:26:40 +0200 Subject: Rename smbd -> samba. --- source4/build/smb_build/summary.pm | 2 +- source4/cldap_server/config.mk | 2 +- source4/cluster/ctdb/example/cluster_start.sh | 8 +- source4/dsdb/config.mk | 2 +- source4/dynconfig/config.mk | 2 +- source4/kdc/config.mk | 2 +- source4/ldap_server/config.mk | 2 +- source4/nbt_server/config.mk | 2 +- source4/ntp_signd/config.mk | 2 +- source4/rpc_server/config.mk | 2 +- source4/selftest/config.mk | 12 +- source4/selftest/selftest.pl | 4 +- source4/selftest/target/Samba4.pm | 26 ++-- source4/selftest/test_win.sh | 2 +- source4/smb_server/config.mk | 2 +- source4/smbd/config.mk | 10 +- source4/smbd/samba.8.xml | 178 ++++++++++++++++++++++++++ source4/smbd/server.c | 2 +- source4/smbd/smbd.8.xml | 177 ------------------------- source4/web_server/config.mk | 2 +- source4/winbind/config.mk | 2 +- source4/wrepl_server/config.mk | 2 +- 22 files changed, 221 insertions(+), 224 deletions(-) create mode 100644 source4/smbd/samba.8.xml delete mode 100644 source4/smbd/smbd.8.xml diff --git a/source4/build/smb_build/summary.pm b/source4/build/smb_build/summary.pm index 4ea1ad525e..f6c1c50550 100644 --- a/source4/build/smb_build/summary.pm +++ b/source4/build/smb_build/summary.pm @@ -46,7 +46,7 @@ sub show($$) print "Summary:\n\n"; showitem($output, "SSL in SWAT and LDAP", ["GNUTLS"]); - showitem($output, "threads in smbd (see --with-pthread)", ["PTHREAD"]); + showitem($output, "threads in server (see --with-pthread)", ["PTHREAD"]); showitem($output, "intelligent command line editing", ["READLINE"]); showitem($output, "changing process titles (see --with-setproctitle)", ["SETPROCTITLE"]); showitem($output, "using extended attributes", ["XATTR"]); diff --git a/source4/cldap_server/config.mk b/source4/cldap_server/config.mk index 137a44d0f7..baf2620f32 100644 --- a/source4/cldap_server/config.mk +++ b/source4/cldap_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM CLDAPD [MODULE::CLDAPD] INIT_FUNCTION = server_service_cldapd_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = \ LIBCLI_CLDAP LIBNETIF process_model # End SUBSYSTEM CLDAPD diff --git a/source4/cluster/ctdb/example/cluster_start.sh b/source4/cluster/ctdb/example/cluster_start.sh index 575d031c95..825eadb483 100755 --- a/source4/cluster/ctdb/example/cluster_start.sh +++ b/source4/cluster/ctdb/example/cluster_start.sh @@ -1,12 +1,12 @@ #!/bin/sh -killall smbd +killall samba sleep 1 -killall -9 smbd +killall -9 samba killall -9 valgrind type=$1 -xterm -e $type bin/smbd -s /home/tridge/samba/samba4.svn/prefix/etc/smb.conf.node1 -M single -i & -xterm -e $type bin/smbd -s /home/tridge/samba/samba4.svn/prefix/etc/smb.conf.node2 -M single -i & +xterm -e $type bin/samba -s /home/tridge/samba/samba4.svn/prefix/etc/smb.conf.node1 -M single -i & +xterm -e $type bin/samba -s /home/tridge/samba/samba4.svn/prefix/etc/smb.conf.node2 -M single -i & diff --git a/source4/dsdb/config.mk b/source4/dsdb/config.mk index 63e8a77ce4..8bc8b6e000 100644 --- a/source4/dsdb/config.mk +++ b/source4/dsdb/config.mk @@ -46,7 +46,7 @@ $(eval $(call proto_header_template,$(dsdbsrcdir)/schema/proto.h,$(SAMDB_SCHEMA_ # Start SUBSYSTEM DREPL_SRV [MODULE::DREPL_SRV] INIT_FUNCTION = server_service_drepl_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = \ SAMDB \ process_model diff --git a/source4/dynconfig/config.mk b/source4/dynconfig/config.mk index b10018384f..78deb04f65 100644 --- a/source4/dynconfig/config.mk +++ b/source4/dynconfig/config.mk @@ -3,7 +3,7 @@ DYNCONFIG_OBJ_FILES = $(dynconfigsrcdir)/dynconfig.o # set these to where to find various files -# These can be overridden by command line switches (see smbd(8)) +# These can be overridden by command line switches (see samba(8)) # or in smb.conf (see smb.conf(5)) CONFIGFILE = $(sysconfdir)/smb.conf PKGCONFIGDIR = $(libdir)/pkgconfig diff --git a/source4/kdc/config.mk b/source4/kdc/config.mk index 2c96e22cb3..b3e5bfdb92 100644 --- a/source4/kdc/config.mk +++ b/source4/kdc/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM KDC [MODULE::KDC] INIT_FUNCTION = server_service_kdc_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = \ HEIMDAL_KDC HDB_LDB # End SUBSYSTEM KDC diff --git a/source4/ldap_server/config.mk b/source4/ldap_server/config.mk index 65f5b17f9a..4c35117a72 100644 --- a/source4/ldap_server/config.mk +++ b/source4/ldap_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM LDAP [MODULE::LDAP] INIT_FUNCTION = server_service_ldap_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = CREDENTIALS \ LIBCLI_LDAP SAMDB \ process_model \ diff --git a/source4/nbt_server/config.mk b/source4/nbt_server/config.mk index 1121bfc690..951949a43f 100644 --- a/source4/nbt_server/config.mk +++ b/source4/nbt_server/config.mk @@ -70,7 +70,7 @@ $(eval $(call proto_header_template,$(nbt_serversrcdir)/nbt_server_proto.h,$(NBT [MODULE::service_nbtd] INIT_FUNCTION = server_service_nbtd_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = NBT_SERVER process_model service_nbtd_OBJ_FILES = \ diff --git a/source4/ntp_signd/config.mk b/source4/ntp_signd/config.mk index 96e0de5583..3b52a200ce 100644 --- a/source4/ntp_signd/config.mk +++ b/source4/ntp_signd/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM NTP_signd [MODULE::NTP_SIGND] INIT_FUNCTION = server_service_ntp_signd_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = \ SAMDB NDR_NTP_SIGND # End SUBSYSTEM NTP_SIGND diff --git a/source4/rpc_server/config.mk b/source4/rpc_server/config.mk index 6b1813544e..fb697d0c0f 100644 --- a/source4/rpc_server/config.mk +++ b/source4/rpc_server/config.mk @@ -206,7 +206,7 @@ PUBLIC_HEADERS += $(rpc_serversrcdir)/dcerpc_server.h [MODULE::DCESRV] INIT_FUNCTION = server_service_rpc_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = dcerpc_server DCESRV_OBJ_FILES = $(rpc_serversrcdir)/service_rpc.o diff --git a/source4/selftest/config.mk b/source4/selftest/config.mk index 5503a42cdd..2fcb71eb7a 100644 --- a/source4/selftest/config.mk +++ b/source4/selftest/config.mk @@ -52,30 +52,30 @@ testenv:: everything valgrindtest:: valgrindtest-all valgrindtest-quick:: all - SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ VALGRIND="valgrind -q --num-callers=30 --log-file=${selftest_prefix}/valgrind.log" \ $(SELFTEST) $(SELFTEST_QUICK_OPTS) --immediate --socket-wrapper $(TESTS) valgrindtest-all:: everything - SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ VALGRIND="valgrind -q --num-callers=30 --log-file=${selftest_prefix}/valgrind.log" \ $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --immediate --socket-wrapper $(TESTS) valgrindtest-env:: everything - SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ VALGRIND="valgrind -q --num-callers=30 --log-file=${selftest_prefix}/valgrind.log" \ $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --socket-wrapper --testenv gdbtest:: gdbtest-all gdbtest-quick:: all - SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ $(SELFTEST) $(SELFTEST_QUICK_OPTS) --immediate --socket-wrapper $(TESTS) gdbtest-all:: everything - SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --immediate --socket-wrapper $(TESTS) gdbtest-env:: everything - SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --socket-wrapper --testenv diff --git a/source4/selftest/selftest.pl b/source4/selftest/selftest.pl index 51a354c7a4..92aa67e8d3 100755 --- a/source4/selftest/selftest.pl +++ b/source4/selftest/selftest.pl @@ -303,7 +303,7 @@ Target Specific: --expected-failures=FILE specify list of tests that is guaranteed to fail Samba4 Specific: - --ldap=openldap|fedora-ds back smbd onto specified ldap server + --ldap=openldap|fedora-ds back samba onto specified ldap server Samba3 Specific: --bindir=PATH path to binaries @@ -809,7 +809,7 @@ if ($opt_testenv) { Welcome to the Samba4 Test environment '$testenv_name' This matches the client environment used in make test -smbd is pid `cat \$PIDDIR/smbd.pid` +server is pid `cat \$PIDDIR/samba.pid` Some useful environment variables: TORTURE_OPTIONS=\$TORTURE_OPTIONS diff --git a/source4/selftest/target/Samba4.pm b/source4/selftest/target/Samba4.pm index 992e251c35..9364008ee2 100644 --- a/source4/selftest/target/Samba4.pm +++ b/source4/selftest/target/Samba4.pm @@ -116,20 +116,20 @@ sub check_or_start($$$) if (defined($ENV{SMBD_OPTIONS})) { $optarg.= " $ENV{SMBD_OPTIONS}"; } - my $ret = system("$valgrind $self->{bindir}/smbd $optarg $env_vars->{CONFIGURATION} -M single -i --leak-report-full"); + my $ret = system("$valgrind $self->{bindir}/samba $optarg $env_vars->{CONFIGURATION} -M single -i --leak-report-full"); if ($? == -1) { - print "Unable to start smbd: $ret: $!\n"; + print "Unable to start samba: $ret: $!\n"; exit 1; } unlink($env_vars->{SMBD_TEST_FIFO}); my $exit = $? >> 8; if ( $ret == 0 ) { - print "smbd exits with status $exit\n"; + print "samba exits with status $exit\n"; } elsif ( $ret & 127 ) { - print "smbd got signal ".($ret & 127)." and exits with $exit!\n"; + print "samba got signal ".($ret & 127)." and exits with $exit!\n"; } else { $ret = $? >> 8; - print "smbd failed with status $exit!\n"; + print "samba failed with status $exit!\n"; } exit $exit; } @@ -498,7 +498,7 @@ sub provision($$$$$$) { my ($self, $prefix, $server_role, $netbiosname, $netbiosalias, $swiface, $password) = @_; - my $smbd_loglevel = 1; + my $server_loglevel = 1; my $username = "administrator"; my $domain = "SAMBADOMAIN"; my $realm = "SAMBA.EXAMPLE.COM"; @@ -571,7 +571,7 @@ sub provision($$$$$$) ldb:nosync = true #We don't want to pass our self-tests if the PAC code is wrong gensec:require_pac = true - log level = $smbd_loglevel + log level = $server_loglevel [tmp] path = $tmpdir @@ -606,7 +606,7 @@ sub provision($$$$$$) cifs:server = $netbiosname cifs:share = tmp #There is no username specified here, instead the client is expected -#to log in with kerberos, and smbd will used delegated credentials. +#to log in with kerberos, and the serverwill use delegated credentials. [simple] path = $tmpdir @@ -828,8 +828,8 @@ sub provision_dc($$) $self->add_wins_config("$prefix/private") or die("Unable to add wins configuration"); - $ret->{SMBD_TEST_FIFO} = "$prefix/smbd_test.fifo"; - $ret->{SMBD_TEST_LOG} = "$prefix/smbd_test.log"; + $ret->{SMBD_TEST_FIFO} = "$prefix/server_test.fifo"; + $ret->{SMBD_TEST_LOG} = "$prefix/server_test.log"; $ret->{SMBD_TEST_LOG_POS} = 0; return $ret; } @@ -841,8 +841,8 @@ sub teardown_env($$) close(DATA); - if (-f "$envvars->{PIDDIR}/smbd.pid" ) { - open(IN, "<$envvars->{PIDDIR}/smbd.pid") or die("unable to open smbd pid file"); + if (-f "$envvars->{PIDDIR}/samba.pid" ) { + open(IN, "<$envvars->{PIDDIR}/samba.pid") or die("unable to open server pid file"); $pid = ; close(IN); @@ -858,7 +858,7 @@ sub teardown_env($$) # If it is still around, kill it if ($count > 20) { - print "smbd process $pid took more than $count seconds to exit, killing\n"; + print "server process $pid took more than $count seconds to exit, killing\n"; kill 9, $pid; } } diff --git a/source4/selftest/test_win.sh b/source4/selftest/test_win.sh index bc40620af5..17c09e6b26 100755 --- a/source4/selftest/test_win.sh +++ b/source4/selftest/test_win.sh @@ -32,7 +32,7 @@ name="NET against Windows 2003" testit "$name" smb $WINTEST_DIR/wintest_net.sh $SMBTORTURE_REMOTE_HOST \ $SMBTORTURE_USERNAME $SMBTORTURE_PASSWORD $SMBTORTURE_WORKGROUP -name="Windows 2003 against smbd" +name="Windows 2003 against samba" testit "$name" smb $WINTEST_DIR/wintest_client.sh $SMBTORTURE_REMOTE_HOST dc_tests="RPC-DRSUAPI ncacn_np ncacn_ip_tcp" diff --git a/source4/smb_server/config.mk b/source4/smb_server/config.mk index e11968a100..52c000839d 100644 --- a/source4/smb_server/config.mk +++ b/source4/smb_server/config.mk @@ -2,7 +2,7 @@ # [MODULE::SERVICE_SMB] INIT_FUNCTION = server_service_smb_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = SMB_SERVER SERVICE_SMB_OBJ_FILES = $(smb_serversrcdir)/smb_server.o diff --git a/source4/smbd/config.mk b/source4/smbd/config.mk index e60f444456..b5babd4d69 100644 --- a/source4/smbd/config.mk +++ b/source4/smbd/config.mk @@ -17,9 +17,7 @@ PIDFILE_OBJ_FILES = $(smbdsrcdir)/pidfile.o $(eval $(call proto_header_template,$(smbdsrcdir)/pidfile.h,$(PIDFILE_OBJ_FILES:.o=.c))) -################################# -# Start BINARY smbd -[BINARY::smbd] +[BINARY::samba] INSTALLDIR = SBINDIR PRIVATE_DEPENDENCIES = \ process_model \ @@ -36,8 +34,6 @@ PRIVATE_DEPENDENCIES = \ share \ CLUSTER -smbd_OBJ_FILES = $(smbdsrcdir)/server.o +samba_OBJ_FILES = $(smbdsrcdir)/server.o -MANPAGES += $(smbdsrcdir)/smbd.8 -# End BINARY smbd -################################# +MANPAGES += $(smbdsrcdir)/samba.8 diff --git a/source4/smbd/samba.8.xml b/source4/smbd/samba.8.xml new file mode 100644 index 0000000000..e1ec8cabd5 --- /dev/null +++ b/source4/smbd/samba.8.xml @@ -0,0 +1,178 @@ + + + + + + samba + 8 + + + + + samba + server to provide filesharing- and directory services to clients + + + + + samba + -i + -M model + + + + + DESCRIPTION + This program is part of the samba + 7 suite. + + samba is the server daemon that + provides filesharing and directory services to Windows clients. + The server provides filespace and directory services to + clients using the SMB (or CIFS) protocol and other + related protocols such as DCE/RPC, LDAP and Kerberos. + + + + Clients supported include MSCLIENT 3.0 for DOS, Windows for + Workgroups, Windows 95/98/ME, Windows NT, Windows 2000/XP/2003, + OS/2, DAVE for Macintosh, and cifsfs for Linux. + + An extensive description of the services that the + server can provide is given in the man page for the + configuration file controlling the attributes of those + services (see smb.conf + 5. This man page will not describe the + services, but will concentrate on the administrative aspects + of running the server. + + Please note that there are significant security + implications to running this server, and the smb.conf + 5 manual page should be regarded as mandatory reading before + proceeding with installation. + + As of Samba 4, there is a single daemon that incorporates the + functionality of both smbd and nmbd that are present in older versions + of Samba. + + + + + OPTIONS + + + + -i + If this parameter is specified it causes the + server to run "interactively", not as a daemon, even if the + server is executed on the command line of a shell. Setting this + parameter negates the implicit deamon mode when run from the + command line. samba also logs to standard + output, as if the -S parameter had been + given. + + + + + -M model + This parameter can be used to specify the + "process model" samba should use. This determines + how concurrent clients are handled. Available process + models include single (everything in + a single process), standard (similar + behaviour to that of Samba 3), thread + (single process, different threads. + + + + + + + FILES + + + + /etc/rc + or whatever initialization script your + system uses). + + If running the server as a daemon at startup, + this file will need to contain an appropriate startup + sequence for the server. + + + + /etc/services + If running the server via the + meta-daemon inetd, this file + must contain a mapping of service name (e.g., netbios-ssn) + to service port (e.g., 139) and protocol type (e.g., tcp). + + + + + /usr/local/samba/lib/smb.conf + This is the default location of the smb.conf + 5 server configuration file. Other common places that systems + install this file are /usr/samba/lib/smb.conf + and /etc/samba/smb.conf. + + This file describes all the services the server + is to make available to clients. See smb.conf + 5 for more information. + + + + + + + VERSION + + This man page is correct for version 4 of + the Samba suite. + + + + DIAGNOSTICS + + Most diagnostics issued by the server are logged + in a specified log file. The log file name is specified + at compile time, but may be overridden on the command line. + + The number and nature of diagnostics available depends + on the debug level used by the server. If you have problems, set + the debug level to 3 and peruse the log files. + + Most messages are reasonably self-explanatory. Unfortunately, + at the time this man page was created, there are too many diagnostics + available in the source code to warrant describing each and every + diagnostic. At this stage your best bet is still to grep the + source code and inspect the conditions that gave rise to the + diagnostics you are seeing. + + + + SEE ALSO + hosts_access + 5 + smb.conf + 5, smbclient + 1, testparm + 1, and the + Internet RFC's rfc1001.txt, rfc1002.txt. + In addition the CIFS (formerly SMB) specification is available + as a link from the Web page + http://samba.org/cifs/. + + + + AUTHOR + + 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. + + + + diff --git a/source4/smbd/server.c b/source4/smbd/server.c index 5bd5568913..c6332e4834 100644 --- a/source4/smbd/server.c +++ b/source4/smbd/server.c @@ -199,7 +199,7 @@ static int binary_smbd_main(const char *binary_name, int argc, const char *argv[ extern NTSTATUS server_service_drepl_init(void); extern NTSTATUS server_service_rpc_init(void); extern NTSTATUS server_service_ntp_signd_init(void); - init_module_fn static_init[] = { STATIC_smbd_MODULES }; + init_module_fn static_init[] = { STATIC_samba_MODULES }; init_module_fn *shared_init; struct event_context *event_ctx; uint16_t stdin_event_flags; diff --git a/source4/smbd/smbd.8.xml b/source4/smbd/smbd.8.xml deleted file mode 100644 index a02c2ce80a..0000000000 --- a/source4/smbd/smbd.8.xml +++ /dev/null @@ -1,177 +0,0 @@ - - - - - - smbd - 8 - - - - - smbd - server to provide filesharing- and directory services to clients - - - - - smbd - -i - -M model - - - - - DESCRIPTION - This program is part of the samba - 7 suite. - - smbd is the server daemon that - provides filesharing and directory services to Windows clients. - The server provides filespace and directory services to - clients using the SMB (or CIFS) protocol and other - related protocols such as DCE/RPC, LDAP and Kerberos. - - - - Clients supported include MSCLIENT 3.0 for DOS, Windows for - Workgroups, Windows 95/98/ME, Windows NT, Windows 2000/XP/2003, - OS/2, DAVE for Macintosh, and cifsfs for Linux. - - An extensive description of the services that the - server can provide is given in the man page for the - configuration file controlling the attributes of those - services (see smb.conf - 5. This man page will not describe the - services, but will concentrate on the administrative aspects - of running the server. - - Please note that there are significant security - implications to running this server, and the smb.conf - 5 manual page should be regarded as mandatory reading before - proceeding with installation. - - As of Samba 4, smbd also incorporates all the functionality of - nmbd. - - - - - OPTIONS - - - - -i - If this parameter is specified it causes the - server to run "interactively", not as a daemon, even if the - server is executed on the command line of a shell. Setting this - parameter negates the implicit deamon mode when run from the - command line. smbd also logs to standard - output, as if the -S parameter had been - given. - - - - - -M model - This parameter can be used to specify the - "process model" smbd should use. This determines - how concurrent clients are handled. Available process - models include single (everything in - a single process), standard (similar - behaviour to that of Samba 3), thread - (single process, different threads. - - - - - - - FILES - - - - /etc/rc - or whatever initialization script your - system uses). - - If running the server as a daemon at startup, - this file will need to contain an appropriate startup - sequence for the server. - - - - /etc/services - If running the server via the - meta-daemon inetd, this file - must contain a mapping of service name (e.g., netbios-ssn) - to service port (e.g., 139) and protocol type (e.g., tcp). - - - - - /usr/local/samba/lib/smb.conf - This is the default location of the smb.conf - 5 server configuration file. Other common places that systems - install this file are /usr/samba/lib/smb.conf - and /etc/samba/smb.conf. - - This file describes all the services the server - is to make available to clients. See smb.conf - 5 for more information. - - - - - - - VERSION - - This man page is correct for version 4 of - the Samba suite. - - - - DIAGNOSTICS - - Most diagnostics issued by the server are logged - in a specified log file. The log file name is specified - at compile time, but may be overridden on the command line. - - The number and nature of diagnostics available depends - on the debug level used by the server. If you have problems, set - the debug level to 3 and peruse the log files. - - Most messages are reasonably self-explanatory. Unfortunately, - at the time this man page was created, there are too many diagnostics - available in the source code to warrant describing each and every - diagnostic. At this stage your best bet is still to grep the - source code and inspect the conditions that gave rise to the - diagnostics you are seeing. - - - - SEE ALSO - hosts_access - 5 - smb.conf - 5, smbclient - 1, testparm - 1, and the - Internet RFC's rfc1001.txt, rfc1002.txt. - In addition the CIFS (formerly SMB) specification is available - as a link from the Web page - http://samba.org/cifs/. - - - - AUTHOR - - 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. - - - - diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index af3ac5f544..e034590111 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM WEB [MODULE::WEB] INIT_FUNCTION = server_service_web_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = LIBTLS smbcalls process_model LIBPYTHON # End SUBSYSTEM WEB ####################### diff --git a/source4/winbind/config.mk b/source4/winbind/config.mk index 1837c52891..f719f00853 100644 --- a/source4/winbind/config.mk +++ b/source4/winbind/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM WINBIND [MODULE::WINBIND] INIT_FUNCTION = server_service_winbind_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = \ WB_HELPER \ IDMAP \ diff --git a/source4/wrepl_server/config.mk b/source4/wrepl_server/config.mk index 235a897503..c7b5c3e1df 100644 --- a/source4/wrepl_server/config.mk +++ b/source4/wrepl_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM WREPL_SRV [MODULE::WREPL_SRV] INIT_FUNCTION = server_service_wrepl_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = \ LIBCLI_WREPL WINSDB process_model # End SUBSYSTEM WREPL_SRV -- cgit From 236eb0694bda3d82198e51de11bd4bc045832f75 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 21:29:13 +0200 Subject: Use absolute paths for wbinfo rather than relying on it being in PATH. --- source4/nsswitch/tests/test_wbinfo.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source4/nsswitch/tests/test_wbinfo.sh b/source4/nsswitch/tests/test_wbinfo.sh index dfd633b656..a67fac9394 100755 --- a/source4/nsswitch/tests/test_wbinfo.sh +++ b/source4/nsswitch/tests/test_wbinfo.sh @@ -62,7 +62,7 @@ admin_sid=`$wbinfo -n "$DOMAIN/$USERNAME" | cut -d " " -f1` echo "$DOMAIN/$USERNAME resolved to $admin_sid" testit "wbinfo -s $admin_sid against $TARGET" $wbinfo -s $admin_sid || failed=`expr $failed + 1` -admin_name=`wbinfo -s $admin_sid | cut -d " " -f1| tr a-z A-Z` +admin_name=`$wbinfo -s $admin_sid | cut -d " " -f1| tr a-z A-Z` echo "$admin_sid resolved to $admin_name" tested_name=`echo $DOMAIN/$USERNAME | tr a-z A-Z` @@ -100,7 +100,7 @@ else echo "success: wbinfo -U check for sane mapping" fi -admin_uid=`wbinfo -U $admin_sid` +admin_uid=`$wbinfo -U $admin_sid` testit "wbinfo -G against $TARGET" $wbinfo -G 30000 || failed=`expr $failed + 1` @@ -149,7 +149,7 @@ testit "wbinfo --all-domains against $TARGET" $wbinfo --all-domains || failed=`e testit "wbinfo --own-domain against $TARGET" $wbinfo --own-domain || failed=`expr $failed + 1` echo "test: wbinfo --own-domain against $TARGET check output" -own_domain=`wbinfo --own-domain` +own_domain=`$wbinfo --own-domain` if test x$own_domain = x$DOMAIN; then echo "success: wbinfo --own-domain against $TARGET check output" else -- cgit From 05ea5e23cf4e70de0bd658b1c5c0ead133967091 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 21:32:40 +0200 Subject: Revert "Rename smbd -> samba." This reverts commit 0e9008be35a5b334bd65e6417193d4b8f27bdc36. --- source4/build/smb_build/summary.pm | 2 +- source4/cldap_server/config.mk | 2 +- source4/cluster/ctdb/example/cluster_start.sh | 8 +- source4/dsdb/config.mk | 2 +- source4/dynconfig/config.mk | 2 +- source4/kdc/config.mk | 2 +- source4/ldap_server/config.mk | 2 +- source4/nbt_server/config.mk | 2 +- source4/ntp_signd/config.mk | 2 +- source4/rpc_server/config.mk | 2 +- source4/selftest/config.mk | 12 +- source4/selftest/selftest.pl | 4 +- source4/selftest/target/Samba4.pm | 26 ++-- source4/selftest/test_win.sh | 2 +- source4/smb_server/config.mk | 2 +- source4/smbd/config.mk | 10 +- source4/smbd/samba.8.xml | 178 -------------------------- source4/smbd/server.c | 2 +- source4/smbd/smbd.8.xml | 177 +++++++++++++++++++++++++ source4/web_server/config.mk | 2 +- source4/winbind/config.mk | 2 +- source4/wrepl_server/config.mk | 2 +- 22 files changed, 224 insertions(+), 221 deletions(-) delete mode 100644 source4/smbd/samba.8.xml create mode 100644 source4/smbd/smbd.8.xml diff --git a/source4/build/smb_build/summary.pm b/source4/build/smb_build/summary.pm index f6c1c50550..4ea1ad525e 100644 --- a/source4/build/smb_build/summary.pm +++ b/source4/build/smb_build/summary.pm @@ -46,7 +46,7 @@ sub show($$) print "Summary:\n\n"; showitem($output, "SSL in SWAT and LDAP", ["GNUTLS"]); - showitem($output, "threads in server (see --with-pthread)", ["PTHREAD"]); + showitem($output, "threads in smbd (see --with-pthread)", ["PTHREAD"]); showitem($output, "intelligent command line editing", ["READLINE"]); showitem($output, "changing process titles (see --with-setproctitle)", ["SETPROCTITLE"]); showitem($output, "using extended attributes", ["XATTR"]); diff --git a/source4/cldap_server/config.mk b/source4/cldap_server/config.mk index baf2620f32..137a44d0f7 100644 --- a/source4/cldap_server/config.mk +++ b/source4/cldap_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM CLDAPD [MODULE::CLDAPD] INIT_FUNCTION = server_service_cldapd_init -SUBSYSTEM = samba +SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = \ LIBCLI_CLDAP LIBNETIF process_model # End SUBSYSTEM CLDAPD diff --git a/source4/cluster/ctdb/example/cluster_start.sh b/source4/cluster/ctdb/example/cluster_start.sh index 825eadb483..575d031c95 100755 --- a/source4/cluster/ctdb/example/cluster_start.sh +++ b/source4/cluster/ctdb/example/cluster_start.sh @@ -1,12 +1,12 @@ #!/bin/sh -killall samba +killall smbd sleep 1 -killall -9 samba +killall -9 smbd killall -9 valgrind type=$1 -xterm -e $type bin/samba -s /home/tridge/samba/samba4.svn/prefix/etc/smb.conf.node1 -M single -i & -xterm -e $type bin/samba -s /home/tridge/samba/samba4.svn/prefix/etc/smb.conf.node2 -M single -i & +xterm -e $type bin/smbd -s /home/tridge/samba/samba4.svn/prefix/etc/smb.conf.node1 -M single -i & +xterm -e $type bin/smbd -s /home/tridge/samba/samba4.svn/prefix/etc/smb.conf.node2 -M single -i & diff --git a/source4/dsdb/config.mk b/source4/dsdb/config.mk index 8bc8b6e000..63e8a77ce4 100644 --- a/source4/dsdb/config.mk +++ b/source4/dsdb/config.mk @@ -46,7 +46,7 @@ $(eval $(call proto_header_template,$(dsdbsrcdir)/schema/proto.h,$(SAMDB_SCHEMA_ # Start SUBSYSTEM DREPL_SRV [MODULE::DREPL_SRV] INIT_FUNCTION = server_service_drepl_init -SUBSYSTEM = samba +SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = \ SAMDB \ process_model diff --git a/source4/dynconfig/config.mk b/source4/dynconfig/config.mk index 78deb04f65..b10018384f 100644 --- a/source4/dynconfig/config.mk +++ b/source4/dynconfig/config.mk @@ -3,7 +3,7 @@ DYNCONFIG_OBJ_FILES = $(dynconfigsrcdir)/dynconfig.o # set these to where to find various files -# These can be overridden by command line switches (see samba(8)) +# These can be overridden by command line switches (see smbd(8)) # or in smb.conf (see smb.conf(5)) CONFIGFILE = $(sysconfdir)/smb.conf PKGCONFIGDIR = $(libdir)/pkgconfig diff --git a/source4/kdc/config.mk b/source4/kdc/config.mk index b3e5bfdb92..2c96e22cb3 100644 --- a/source4/kdc/config.mk +++ b/source4/kdc/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM KDC [MODULE::KDC] INIT_FUNCTION = server_service_kdc_init -SUBSYSTEM = samba +SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = \ HEIMDAL_KDC HDB_LDB # End SUBSYSTEM KDC diff --git a/source4/ldap_server/config.mk b/source4/ldap_server/config.mk index 4c35117a72..65f5b17f9a 100644 --- a/source4/ldap_server/config.mk +++ b/source4/ldap_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM LDAP [MODULE::LDAP] INIT_FUNCTION = server_service_ldap_init -SUBSYSTEM = samba +SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = CREDENTIALS \ LIBCLI_LDAP SAMDB \ process_model \ diff --git a/source4/nbt_server/config.mk b/source4/nbt_server/config.mk index 951949a43f..1121bfc690 100644 --- a/source4/nbt_server/config.mk +++ b/source4/nbt_server/config.mk @@ -70,7 +70,7 @@ $(eval $(call proto_header_template,$(nbt_serversrcdir)/nbt_server_proto.h,$(NBT [MODULE::service_nbtd] INIT_FUNCTION = server_service_nbtd_init -SUBSYSTEM = samba +SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = NBT_SERVER process_model service_nbtd_OBJ_FILES = \ diff --git a/source4/ntp_signd/config.mk b/source4/ntp_signd/config.mk index 3b52a200ce..96e0de5583 100644 --- a/source4/ntp_signd/config.mk +++ b/source4/ntp_signd/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM NTP_signd [MODULE::NTP_SIGND] INIT_FUNCTION = server_service_ntp_signd_init -SUBSYSTEM = samba +SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = \ SAMDB NDR_NTP_SIGND # End SUBSYSTEM NTP_SIGND diff --git a/source4/rpc_server/config.mk b/source4/rpc_server/config.mk index fb697d0c0f..6b1813544e 100644 --- a/source4/rpc_server/config.mk +++ b/source4/rpc_server/config.mk @@ -206,7 +206,7 @@ PUBLIC_HEADERS += $(rpc_serversrcdir)/dcerpc_server.h [MODULE::DCESRV] INIT_FUNCTION = server_service_rpc_init -SUBSYSTEM = samba +SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = dcerpc_server DCESRV_OBJ_FILES = $(rpc_serversrcdir)/service_rpc.o diff --git a/source4/selftest/config.mk b/source4/selftest/config.mk index 2fcb71eb7a..5503a42cdd 100644 --- a/source4/selftest/config.mk +++ b/source4/selftest/config.mk @@ -52,30 +52,30 @@ testenv:: everything valgrindtest:: valgrindtest-all valgrindtest-quick:: all - SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ VALGRIND="valgrind -q --num-callers=30 --log-file=${selftest_prefix}/valgrind.log" \ $(SELFTEST) $(SELFTEST_QUICK_OPTS) --immediate --socket-wrapper $(TESTS) valgrindtest-all:: everything - SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ VALGRIND="valgrind -q --num-callers=30 --log-file=${selftest_prefix}/valgrind.log" \ $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --immediate --socket-wrapper $(TESTS) valgrindtest-env:: everything - SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ VALGRIND="valgrind -q --num-callers=30 --log-file=${selftest_prefix}/valgrind.log" \ $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --socket-wrapper --testenv gdbtest:: gdbtest-all gdbtest-quick:: all - SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ $(SELFTEST) $(SELFTEST_QUICK_OPTS) --immediate --socket-wrapper $(TESTS) gdbtest-all:: everything - SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --immediate --socket-wrapper $(TESTS) gdbtest-env:: everything - SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --socket-wrapper --testenv diff --git a/source4/selftest/selftest.pl b/source4/selftest/selftest.pl index 92aa67e8d3..51a354c7a4 100755 --- a/source4/selftest/selftest.pl +++ b/source4/selftest/selftest.pl @@ -303,7 +303,7 @@ Target Specific: --expected-failures=FILE specify list of tests that is guaranteed to fail Samba4 Specific: - --ldap=openldap|fedora-ds back samba onto specified ldap server + --ldap=openldap|fedora-ds back smbd onto specified ldap server Samba3 Specific: --bindir=PATH path to binaries @@ -809,7 +809,7 @@ if ($opt_testenv) { Welcome to the Samba4 Test environment '$testenv_name' This matches the client environment used in make test -server is pid `cat \$PIDDIR/samba.pid` +smbd is pid `cat \$PIDDIR/smbd.pid` Some useful environment variables: TORTURE_OPTIONS=\$TORTURE_OPTIONS diff --git a/source4/selftest/target/Samba4.pm b/source4/selftest/target/Samba4.pm index 9364008ee2..992e251c35 100644 --- a/source4/selftest/target/Samba4.pm +++ b/source4/selftest/target/Samba4.pm @@ -116,20 +116,20 @@ sub check_or_start($$$) if (defined($ENV{SMBD_OPTIONS})) { $optarg.= " $ENV{SMBD_OPTIONS}"; } - my $ret = system("$valgrind $self->{bindir}/samba $optarg $env_vars->{CONFIGURATION} -M single -i --leak-report-full"); + my $ret = system("$valgrind $self->{bindir}/smbd $optarg $env_vars->{CONFIGURATION} -M single -i --leak-report-full"); if ($? == -1) { - print "Unable to start samba: $ret: $!\n"; + print "Unable to start smbd: $ret: $!\n"; exit 1; } unlink($env_vars->{SMBD_TEST_FIFO}); my $exit = $? >> 8; if ( $ret == 0 ) { - print "samba exits with status $exit\n"; + print "smbd exits with status $exit\n"; } elsif ( $ret & 127 ) { - print "samba got signal ".($ret & 127)." and exits with $exit!\n"; + print "smbd got signal ".($ret & 127)." and exits with $exit!\n"; } else { $ret = $? >> 8; - print "samba failed with status $exit!\n"; + print "smbd failed with status $exit!\n"; } exit $exit; } @@ -498,7 +498,7 @@ sub provision($$$$$$) { my ($self, $prefix, $server_role, $netbiosname, $netbiosalias, $swiface, $password) = @_; - my $server_loglevel = 1; + my $smbd_loglevel = 1; my $username = "administrator"; my $domain = "SAMBADOMAIN"; my $realm = "SAMBA.EXAMPLE.COM"; @@ -571,7 +571,7 @@ sub provision($$$$$$) ldb:nosync = true #We don't want to pass our self-tests if the PAC code is wrong gensec:require_pac = true - log level = $server_loglevel + log level = $smbd_loglevel [tmp] path = $tmpdir @@ -606,7 +606,7 @@ sub provision($$$$$$) cifs:server = $netbiosname cifs:share = tmp #There is no username specified here, instead the client is expected -#to log in with kerberos, and the serverwill use delegated credentials. +#to log in with kerberos, and smbd will used delegated credentials. [simple] path = $tmpdir @@ -828,8 +828,8 @@ sub provision_dc($$) $self->add_wins_config("$prefix/private") or die("Unable to add wins configuration"); - $ret->{SMBD_TEST_FIFO} = "$prefix/server_test.fifo"; - $ret->{SMBD_TEST_LOG} = "$prefix/server_test.log"; + $ret->{SMBD_TEST_FIFO} = "$prefix/smbd_test.fifo"; + $ret->{SMBD_TEST_LOG} = "$prefix/smbd_test.log"; $ret->{SMBD_TEST_LOG_POS} = 0; return $ret; } @@ -841,8 +841,8 @@ sub teardown_env($$) close(DATA); - if (-f "$envvars->{PIDDIR}/samba.pid" ) { - open(IN, "<$envvars->{PIDDIR}/samba.pid") or die("unable to open server pid file"); + if (-f "$envvars->{PIDDIR}/smbd.pid" ) { + open(IN, "<$envvars->{PIDDIR}/smbd.pid") or die("unable to open smbd pid file"); $pid = ; close(IN); @@ -858,7 +858,7 @@ sub teardown_env($$) # If it is still around, kill it if ($count > 20) { - print "server process $pid took more than $count seconds to exit, killing\n"; + print "smbd process $pid took more than $count seconds to exit, killing\n"; kill 9, $pid; } } diff --git a/source4/selftest/test_win.sh b/source4/selftest/test_win.sh index 17c09e6b26..bc40620af5 100755 --- a/source4/selftest/test_win.sh +++ b/source4/selftest/test_win.sh @@ -32,7 +32,7 @@ name="NET against Windows 2003" testit "$name" smb $WINTEST_DIR/wintest_net.sh $SMBTORTURE_REMOTE_HOST \ $SMBTORTURE_USERNAME $SMBTORTURE_PASSWORD $SMBTORTURE_WORKGROUP -name="Windows 2003 against samba" +name="Windows 2003 against smbd" testit "$name" smb $WINTEST_DIR/wintest_client.sh $SMBTORTURE_REMOTE_HOST dc_tests="RPC-DRSUAPI ncacn_np ncacn_ip_tcp" diff --git a/source4/smb_server/config.mk b/source4/smb_server/config.mk index 52c000839d..e11968a100 100644 --- a/source4/smb_server/config.mk +++ b/source4/smb_server/config.mk @@ -2,7 +2,7 @@ # [MODULE::SERVICE_SMB] INIT_FUNCTION = server_service_smb_init -SUBSYSTEM = samba +SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = SMB_SERVER SERVICE_SMB_OBJ_FILES = $(smb_serversrcdir)/smb_server.o diff --git a/source4/smbd/config.mk b/source4/smbd/config.mk index b5babd4d69..e60f444456 100644 --- a/source4/smbd/config.mk +++ b/source4/smbd/config.mk @@ -17,7 +17,9 @@ PIDFILE_OBJ_FILES = $(smbdsrcdir)/pidfile.o $(eval $(call proto_header_template,$(smbdsrcdir)/pidfile.h,$(PIDFILE_OBJ_FILES:.o=.c))) -[BINARY::samba] +################################# +# Start BINARY smbd +[BINARY::smbd] INSTALLDIR = SBINDIR PRIVATE_DEPENDENCIES = \ process_model \ @@ -34,6 +36,8 @@ PRIVATE_DEPENDENCIES = \ share \ CLUSTER -samba_OBJ_FILES = $(smbdsrcdir)/server.o +smbd_OBJ_FILES = $(smbdsrcdir)/server.o -MANPAGES += $(smbdsrcdir)/samba.8 +MANPAGES += $(smbdsrcdir)/smbd.8 +# End BINARY smbd +################################# diff --git a/source4/smbd/samba.8.xml b/source4/smbd/samba.8.xml deleted file mode 100644 index e1ec8cabd5..0000000000 --- a/source4/smbd/samba.8.xml +++ /dev/null @@ -1,178 +0,0 @@ - - - - - - samba - 8 - - - - - samba - server to provide filesharing- and directory services to clients - - - - - samba - -i - -M model - - - - - DESCRIPTION - This program is part of the samba - 7 suite. - - samba is the server daemon that - provides filesharing and directory services to Windows clients. - The server provides filespace and directory services to - clients using the SMB (or CIFS) protocol and other - related protocols such as DCE/RPC, LDAP and Kerberos. - - - - Clients supported include MSCLIENT 3.0 for DOS, Windows for - Workgroups, Windows 95/98/ME, Windows NT, Windows 2000/XP/2003, - OS/2, DAVE for Macintosh, and cifsfs for Linux. - - An extensive description of the services that the - server can provide is given in the man page for the - configuration file controlling the attributes of those - services (see smb.conf - 5. This man page will not describe the - services, but will concentrate on the administrative aspects - of running the server. - - Please note that there are significant security - implications to running this server, and the smb.conf - 5 manual page should be regarded as mandatory reading before - proceeding with installation. - - As of Samba 4, there is a single daemon that incorporates the - functionality of both smbd and nmbd that are present in older versions - of Samba. - - - - - OPTIONS - - - - -i - If this parameter is specified it causes the - server to run "interactively", not as a daemon, even if the - server is executed on the command line of a shell. Setting this - parameter negates the implicit deamon mode when run from the - command line. samba also logs to standard - output, as if the -S parameter had been - given. - - - - - -M model - This parameter can be used to specify the - "process model" samba should use. This determines - how concurrent clients are handled. Available process - models include single (everything in - a single process), standard (similar - behaviour to that of Samba 3), thread - (single process, different threads. - - - - - - - FILES - - - - /etc/rc - or whatever initialization script your - system uses). - - If running the server as a daemon at startup, - this file will need to contain an appropriate startup - sequence for the server. - - - - /etc/services - If running the server via the - meta-daemon inetd, this file - must contain a mapping of service name (e.g., netbios-ssn) - to service port (e.g., 139) and protocol type (e.g., tcp). - - - - - /usr/local/samba/lib/smb.conf - This is the default location of the smb.conf - 5 server configuration file. Other common places that systems - install this file are /usr/samba/lib/smb.conf - and /etc/samba/smb.conf. - - This file describes all the services the server - is to make available to clients. See smb.conf - 5 for more information. - - - - - - - VERSION - - This man page is correct for version 4 of - the Samba suite. - - - - DIAGNOSTICS - - Most diagnostics issued by the server are logged - in a specified log file. The log file name is specified - at compile time, but may be overridden on the command line. - - The number and nature of diagnostics available depends - on the debug level used by the server. If you have problems, set - the debug level to 3 and peruse the log files. - - Most messages are reasonably self-explanatory. Unfortunately, - at the time this man page was created, there are too many diagnostics - available in the source code to warrant describing each and every - diagnostic. At this stage your best bet is still to grep the - source code and inspect the conditions that gave rise to the - diagnostics you are seeing. - - - - SEE ALSO - hosts_access - 5 - smb.conf - 5, smbclient - 1, testparm - 1, and the - Internet RFC's rfc1001.txt, rfc1002.txt. - In addition the CIFS (formerly SMB) specification is available - as a link from the Web page - http://samba.org/cifs/. - - - - AUTHOR - - 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. - - - - diff --git a/source4/smbd/server.c b/source4/smbd/server.c index c6332e4834..5bd5568913 100644 --- a/source4/smbd/server.c +++ b/source4/smbd/server.c @@ -199,7 +199,7 @@ static int binary_smbd_main(const char *binary_name, int argc, const char *argv[ extern NTSTATUS server_service_drepl_init(void); extern NTSTATUS server_service_rpc_init(void); extern NTSTATUS server_service_ntp_signd_init(void); - init_module_fn static_init[] = { STATIC_samba_MODULES }; + init_module_fn static_init[] = { STATIC_smbd_MODULES }; init_module_fn *shared_init; struct event_context *event_ctx; uint16_t stdin_event_flags; diff --git a/source4/smbd/smbd.8.xml b/source4/smbd/smbd.8.xml new file mode 100644 index 0000000000..a02c2ce80a --- /dev/null +++ b/source4/smbd/smbd.8.xml @@ -0,0 +1,177 @@ + + + + + + smbd + 8 + + + + + smbd + server to provide filesharing- and directory services to clients + + + + + smbd + -i + -M model + + + + + DESCRIPTION + This program is part of the samba + 7 suite. + + smbd is the server daemon that + provides filesharing and directory services to Windows clients. + The server provides filespace and directory services to + clients using the SMB (or CIFS) protocol and other + related protocols such as DCE/RPC, LDAP and Kerberos. + + + + Clients supported include MSCLIENT 3.0 for DOS, Windows for + Workgroups, Windows 95/98/ME, Windows NT, Windows 2000/XP/2003, + OS/2, DAVE for Macintosh, and cifsfs for Linux. + + An extensive description of the services that the + server can provide is given in the man page for the + configuration file controlling the attributes of those + services (see smb.conf + 5. This man page will not describe the + services, but will concentrate on the administrative aspects + of running the server. + + Please note that there are significant security + implications to running this server, and the smb.conf + 5 manual page should be regarded as mandatory reading before + proceeding with installation. + + As of Samba 4, smbd also incorporates all the functionality of + nmbd. + + + + + OPTIONS + + + + -i + If this parameter is specified it causes the + server to run "interactively", not as a daemon, even if the + server is executed on the command line of a shell. Setting this + parameter negates the implicit deamon mode when run from the + command line. smbd also logs to standard + output, as if the -S parameter had been + given. + + + + + -M model + This parameter can be used to specify the + "process model" smbd should use. This determines + how concurrent clients are handled. Available process + models include single (everything in + a single process), standard (similar + behaviour to that of Samba 3), thread + (single process, different threads. + + + + + + + FILES + + + + /etc/rc + or whatever initialization script your + system uses). + + If running the server as a daemon at startup, + this file will need to contain an appropriate startup + sequence for the server. + + + + /etc/services + If running the server via the + meta-daemon inetd, this file + must contain a mapping of service name (e.g., netbios-ssn) + to service port (e.g., 139) and protocol type (e.g., tcp). + + + + + /usr/local/samba/lib/smb.conf + This is the default location of the smb.conf + 5 server configuration file. Other common places that systems + install this file are /usr/samba/lib/smb.conf + and /etc/samba/smb.conf. + + This file describes all the services the server + is to make available to clients. See smb.conf + 5 for more information. + + + + + + + VERSION + + This man page is correct for version 4 of + the Samba suite. + + + + DIAGNOSTICS + + Most diagnostics issued by the server are logged + in a specified log file. The log file name is specified + at compile time, but may be overridden on the command line. + + The number and nature of diagnostics available depends + on the debug level used by the server. If you have problems, set + the debug level to 3 and peruse the log files. + + Most messages are reasonably self-explanatory. Unfortunately, + at the time this man page was created, there are too many diagnostics + available in the source code to warrant describing each and every + diagnostic. At this stage your best bet is still to grep the + source code and inspect the conditions that gave rise to the + diagnostics you are seeing. + + + + SEE ALSO + hosts_access + 5 + smb.conf + 5, smbclient + 1, testparm + 1, and the + Internet RFC's rfc1001.txt, rfc1002.txt. + In addition the CIFS (formerly SMB) specification is available + as a link from the Web page + http://samba.org/cifs/. + + + + AUTHOR + + 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. + + + + diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index e034590111..af3ac5f544 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM WEB [MODULE::WEB] INIT_FUNCTION = server_service_web_init -SUBSYSTEM = samba +SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = LIBTLS smbcalls process_model LIBPYTHON # End SUBSYSTEM WEB ####################### diff --git a/source4/winbind/config.mk b/source4/winbind/config.mk index f719f00853..1837c52891 100644 --- a/source4/winbind/config.mk +++ b/source4/winbind/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM WINBIND [MODULE::WINBIND] INIT_FUNCTION = server_service_winbind_init -SUBSYSTEM = samba +SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = \ WB_HELPER \ IDMAP \ diff --git a/source4/wrepl_server/config.mk b/source4/wrepl_server/config.mk index c7b5c3e1df..235a897503 100644 --- a/source4/wrepl_server/config.mk +++ b/source4/wrepl_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM WREPL_SRV [MODULE::WREPL_SRV] INIT_FUNCTION = server_service_wrepl_init -SUBSYSTEM = samba +SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = \ LIBCLI_WREPL WINSDB process_model # End SUBSYSTEM WREPL_SRV -- cgit From beee9debeab72ce172575be6a93f1fb712bb6026 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 22:26:44 +0200 Subject: Print status (one character per test) when not running selftest with --immediate. --- source4/selftest/output/plain.pm | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/source4/selftest/output/plain.pm b/source4/selftest/output/plain.pm index 4bec4e0fdc..bad6505e93 100644 --- a/source4/selftest/output/plain.pm +++ b/source4/selftest/output/plain.pm @@ -48,10 +48,7 @@ sub start_testsuite($$) if ($self->{immediate}) { print "$out\n"; } else { - require Term::ReadKey; - my ($wchar, $hchar, $wpixels, $hpixels) = Term::ReadKey::GetTerminalSize(); - foreach (1..$wchar) { $out.= " "; } - print "\r".substr($out, 0, $wchar); + print "$out: "; } } @@ -94,6 +91,13 @@ sub end_testsuite($$$$$) $out .= $self->{test_output}->{$name}; } + if (not $self->{immediate}) { + if (not $unexpected) { + $out .= " ok\n"; + } else { + $out .= " " . uc($result) . "\n"; + } + } print $out; } @@ -120,6 +124,10 @@ sub end_test($$$$$) unless ($unexpected) { $self->{test_output}->{$self->{NAME}} = ""; + if ($result eq "failure") { print "f"; } + elsif ($result eq "skip") { print "s"; } + elsif ($result eq "success") { print "."; } + else { print "?($result)"; } return; } @@ -133,6 +141,13 @@ sub end_test($$$$$) print $self->{test_output}->{$self->{NAME}}; $self->{test_output}->{$self->{NAME}} = ""; } + + if (not $self->{immediate}) { + if ($result eq "error") { print "E"; } + elsif ($result eq "failure") { print "F"; } + elsif ($result eq "success") { print "S"; } + else { print "?"; } + } } sub summary($) -- cgit From 2331c96d28fe713d37b421924e610eef80cc8d91 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sat, 20 Sep 2008 17:02:00 +0200 Subject: build: rebuild only changed IDL files. Let"s see how this works now. Guenther --- source3/script/build_idl.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/script/build_idl.sh b/source3/script/build_idl.sh index 8ff5dcd949..2027fd3937 100755 --- a/source3/script/build_idl.sh +++ b/source3/script/build_idl.sh @@ -19,7 +19,7 @@ for f in ${IDL_FILES}; do basename=`basename $f .idl` ndr="librpc/gen_ndr/ndr_$basename.c" - if [ -f $ndr ] && false; then + if [ -f $ndr ]; then if [ "x`find librpc/idl/$f -newer $ndr -print`" = "xlibrpc/idl/$f" ]; then list="$list librpc/idl/$f" fi -- cgit From 1f9624175ab35fe5c4012e931a165d422bf26fdb Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sat, 20 Sep 2008 17:00:30 +0200 Subject: netlogon: add init_netr_CryptPassword. Guenther --- source3/include/proto.h | 3 +++ source3/rpc_client/init_netlogon.c | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/source3/include/proto.h b/source3/include/proto.h index 2901911c70..bec5f10f3c 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -7427,6 +7427,9 @@ void init_netr_PasswordInfo(struct netr_PasswordInfo *r, const char *workstation, struct samr_Password lmpassword, struct samr_Password ntpassword); +void init_netr_CryptPassword(const char *pwd, + unsigned char session_key[16], + struct netr_CryptPassword *pwd_buf); /* The following definitions come from rpc_client/init_samr.c */ diff --git a/source3/rpc_client/init_netlogon.c b/source3/rpc_client/init_netlogon.c index 61841953fc..e4c39e739e 100644 --- a/source3/rpc_client/init_netlogon.c +++ b/source3/rpc_client/init_netlogon.c @@ -391,3 +391,20 @@ void init_netr_PasswordInfo(struct netr_PasswordInfo *r, r->lmpassword = lmpassword; r->ntpassword = ntpassword; } + +/************************************************************************* + inits a netr_CryptPassword structure + *************************************************************************/ + +void init_netr_CryptPassword(const char *pwd, + unsigned char session_key[16], + struct netr_CryptPassword *pwd_buf) +{ + struct samr_CryptPassword password_buf; + + encode_pw_buffer(password_buf.data, pwd, STR_UNICODE); + + SamOEMhash(password_buf.data, session_key, 516); + memcpy(pwd_buf->data, password_buf.data, 512); + pwd_buf->length = IVAL(password_buf.data, 512); +} -- cgit From ca56c02d4bdfa26f5eda16c5621dcac67d7458ef Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sat, 20 Sep 2008 17:01:20 +0200 Subject: netlogon: use init_netr_CryptPassword in "just_change_the_password" Guenther --- source3/libsmb/trusts_util.c | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/source3/libsmb/trusts_util.c b/source3/libsmb/trusts_util.c index 08a49930b4..9265c60665 100644 --- a/source3/libsmb/trusts_util.c +++ b/source3/libsmb/trusts_util.c @@ -57,24 +57,21 @@ static NTSTATUS just_change_the_password(struct rpc_pipe_client *cli, TALLOC_CTX struct netr_Authenticator clnt_creds, srv_cred; struct netr_CryptPassword new_password; - struct samr_CryptPassword password_buf; netlogon_creds_client_step(cli->dc, &clnt_creds); - encode_pw_buffer(password_buf.data, new_trust_pwd_cleartext, STR_UNICODE); - - SamOEMhash(password_buf.data, cli->dc->sess_key, 516); - memcpy(new_password.data, password_buf.data, 512); - new_password.length = IVAL(password_buf.data, 512); + init_netr_CryptPassword(new_trust_pwd_cleartext, + cli->dc->sess_key, + &new_password); result = rpccli_netr_ServerPasswordSet2(cli, mem_ctx, - cli->dc->remote_machine, - cli->dc->mach_acct, - sec_channel_type, - global_myname(), - &clnt_creds, - &srv_cred, - &new_password); + cli->dc->remote_machine, + cli->dc->mach_acct, + sec_channel_type, + global_myname(), + &clnt_creds, + &srv_cred, + &new_password); /* Always check returned credentials. */ if (!netlogon_creds_client_check(cli->dc, &srv_cred.cred)) { -- cgit From 6f9a83505fced805f5a4d4827ddf7300eda6aaa0 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sat, 20 Sep 2008 18:20:29 +0200 Subject: netlogon: refactor just_change_the_password a bit. Guenther --- source3/libsmb/trusts_util.c | 38 ++++++++++++++++---------------------- 1 file changed, 16 insertions(+), 22 deletions(-) diff --git a/source3/libsmb/trusts_util.c b/source3/libsmb/trusts_util.c index 9265c60665..7897d51717 100644 --- a/source3/libsmb/trusts_util.c +++ b/source3/libsmb/trusts_util.c @@ -37,6 +37,7 @@ static NTSTATUS just_change_the_password(struct rpc_pipe_client *cli, TALLOC_CTX { NTSTATUS result; uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS; + struct netr_Authenticator clnt_creds, srv_cred; result = rpccli_netlogon_setup_creds(cli, cli->desthost, /* server name */ @@ -53,13 +54,12 @@ static NTSTATUS just_change_the_password(struct rpc_pipe_client *cli, TALLOC_CTX return result; } + netlogon_creds_client_step(cli->dc, &clnt_creds); + if (neg_flags & NETLOGON_NEG_PASSWORD_SET2) { - struct netr_Authenticator clnt_creds, srv_cred; struct netr_CryptPassword new_password; - netlogon_creds_client_step(cli->dc, &clnt_creds); - init_netr_CryptPassword(new_trust_pwd_cleartext, cli->dc->sess_key, &new_password); @@ -72,21 +72,15 @@ static NTSTATUS just_change_the_password(struct rpc_pipe_client *cli, TALLOC_CTX &clnt_creds, &srv_cred, &new_password); - - /* Always check returned credentials. */ - if (!netlogon_creds_client_check(cli->dc, &srv_cred.cred)) { - DEBUG(0,("rpccli_netr_ServerPasswordSet2: " - "credentials chain check failed\n")); - return NT_STATUS_ACCESS_DENIED; + if (!NT_STATUS_IS_OK(result)) { + DEBUG(0,("rpccli_netr_ServerPasswordSet2 failed: %s\n", + nt_errstr(result))); + return result; } - } else { - struct netr_Authenticator clnt_creds, srv_cred; struct samr_Password new_password; - netlogon_creds_client_step(cli->dc, &clnt_creds); - cred_hash3(new_password.hash, new_trust_passwd_hash, cli->dc->sess_key, 1); @@ -99,19 +93,19 @@ static NTSTATUS just_change_the_password(struct rpc_pipe_client *cli, TALLOC_CTX &clnt_creds, &srv_cred, &new_password); - - /* Always check returned credentials. */ - if (!netlogon_creds_client_check(cli->dc, &srv_cred.cred)) { - DEBUG(0,("rpccli_netr_ServerPasswordSet: " - "credentials chain check failed\n")); - return NT_STATUS_ACCESS_DENIED; + if (!NT_STATUS_IS_OK(result)) { + DEBUG(0,("rpccli_netr_ServerPasswordSet failed: %s\n", + nt_errstr(result))); + return result; } } - if (!NT_STATUS_IS_OK(result)) { - DEBUG(0,("just_change_the_password: unable to change password (%s)!\n", - nt_errstr(result))); + /* Always check returned credentials. */ + if (!netlogon_creds_client_check(cli->dc, &srv_cred.cred)) { + DEBUG(0,("credentials chain check failed\n")); + return NT_STATUS_ACCESS_DENIED; } + return result; } -- cgit From e194ded26e716fad510191f85e67ff1d775bdcb8 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sun, 21 Sep 2008 18:57:26 +0200 Subject: netlogon: move password change code out to rpccli_netlogon_set_trust_password. Guenther --- source3/include/proto.h | 6 +++ source3/libsmb/trusts_util.c | 99 ++------------------------------------- source3/rpc_client/cli_netlogon.c | 91 +++++++++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 94 deletions(-) diff --git a/source3/include/proto.h b/source3/include/proto.h index bec5f10f3c..194548c082 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -7049,6 +7049,12 @@ NTSTATUS rpccli_netlogon_sam_network_logon_ex(struct rpc_pipe_client *cli, DATA_BLOB lm_response, DATA_BLOB nt_response, struct netr_SamInfo3 **info3); +NTSTATUS rpccli_netlogon_set_trust_password(struct rpc_pipe_client *cli, + TALLOC_CTX *mem_ctx, + const unsigned char orig_trust_passwd_hash[16], + const char *new_trust_pwd_cleartext, + const unsigned char new_trust_passwd_hash[16], + uint32_t sec_channel_type); /* The following definitions come from rpc_client/cli_pipe.c */ diff --git a/source3/libsmb/trusts_util.c b/source3/libsmb/trusts_util.c index 7897d51717..2f336f14e6 100644 --- a/source3/libsmb/trusts_util.c +++ b/source3/libsmb/trusts_util.c @@ -20,95 +20,6 @@ #include "includes.h" -/********************************************************* - Change the domain password on the PDC. - - Just changes the password betwen the two values specified. - - Caller must have the cli connected to the netlogon pipe - already. -**********************************************************/ - -static NTSTATUS just_change_the_password(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, - const unsigned char orig_trust_passwd_hash[16], - const char *new_trust_pwd_cleartext, - const unsigned char new_trust_passwd_hash[16], - uint32 sec_channel_type) -{ - NTSTATUS result; - uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS; - struct netr_Authenticator clnt_creds, srv_cred; - - result = rpccli_netlogon_setup_creds(cli, - cli->desthost, /* server name */ - lp_workgroup(), /* domain */ - global_myname(), /* client name */ - global_myname(), /* machine account name */ - orig_trust_passwd_hash, - sec_channel_type, - &neg_flags); - - if (!NT_STATUS_IS_OK(result)) { - DEBUG(3,("just_change_the_password: unable to setup creds (%s)!\n", - nt_errstr(result))); - return result; - } - - netlogon_creds_client_step(cli->dc, &clnt_creds); - - if (neg_flags & NETLOGON_NEG_PASSWORD_SET2) { - - struct netr_CryptPassword new_password; - - init_netr_CryptPassword(new_trust_pwd_cleartext, - cli->dc->sess_key, - &new_password); - - result = rpccli_netr_ServerPasswordSet2(cli, mem_ctx, - cli->dc->remote_machine, - cli->dc->mach_acct, - sec_channel_type, - global_myname(), - &clnt_creds, - &srv_cred, - &new_password); - if (!NT_STATUS_IS_OK(result)) { - DEBUG(0,("rpccli_netr_ServerPasswordSet2 failed: %s\n", - nt_errstr(result))); - return result; - } - } else { - - struct samr_Password new_password; - - cred_hash3(new_password.hash, - new_trust_passwd_hash, - cli->dc->sess_key, 1); - - result = rpccli_netr_ServerPasswordSet(cli, mem_ctx, - cli->dc->remote_machine, - cli->dc->mach_acct, - sec_channel_type, - global_myname(), - &clnt_creds, - &srv_cred, - &new_password); - if (!NT_STATUS_IS_OK(result)) { - DEBUG(0,("rpccli_netr_ServerPasswordSet failed: %s\n", - nt_errstr(result))); - return result; - } - } - - /* Always check returned credentials. */ - if (!netlogon_creds_client_check(cli->dc, &srv_cred.cred)) { - DEBUG(0,("credentials chain check failed\n")); - return NT_STATUS_ACCESS_DENIED; - } - - return result; -} - /********************************************************* Change the domain password on the PDC. Store the password ourselves, but use the supplied password @@ -135,11 +46,11 @@ NTSTATUS trust_pw_change_and_store_it(struct rpc_pipe_client *cli, TALLOC_CTX *m E_md4hash(new_trust_passwd, new_trust_passwd_hash); - nt_status = just_change_the_password(cli, mem_ctx, - orig_trust_passwd_hash, - new_trust_passwd, - new_trust_passwd_hash, - sec_channel_type); + nt_status = rpccli_netlogon_set_trust_password(cli, mem_ctx, + orig_trust_passwd_hash, + new_trust_passwd, + new_trust_passwd_hash, + sec_channel_type); if (NT_STATUS_IS_OK(nt_status)) { DEBUG(3,("%s : trust_pw_change_and_store_it: Changed password.\n", diff --git a/source3/rpc_client/cli_netlogon.c b/source3/rpc_client/cli_netlogon.c index df87ed13d1..23618efd9f 100644 --- a/source3/rpc_client/cli_netlogon.c +++ b/source3/rpc_client/cli_netlogon.c @@ -538,3 +538,94 @@ NTSTATUS rpccli_netlogon_sam_network_logon_ex(struct rpc_pipe_client *cli, return result; } + +/********************************************************* + Change the domain password on the PDC. + + Just changes the password betwen the two values specified. + + Caller must have the cli connected to the netlogon pipe + already. +**********************************************************/ + +NTSTATUS rpccli_netlogon_set_trust_password(struct rpc_pipe_client *cli, + TALLOC_CTX *mem_ctx, + const unsigned char orig_trust_passwd_hash[16], + const char *new_trust_pwd_cleartext, + const unsigned char new_trust_passwd_hash[16], + uint32_t sec_channel_type) +{ + NTSTATUS result; + uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS; + struct netr_Authenticator clnt_creds, srv_cred; + + result = rpccli_netlogon_setup_creds(cli, + cli->desthost, /* server name */ + lp_workgroup(), /* domain */ + global_myname(), /* client name */ + global_myname(), /* machine account name */ + orig_trust_passwd_hash, + sec_channel_type, + &neg_flags); + + if (!NT_STATUS_IS_OK(result)) { + DEBUG(3,("rpccli_netlogon_set_trust_password: unable to setup creds (%s)!\n", + nt_errstr(result))); + return result; + } + + netlogon_creds_client_step(cli->dc, &clnt_creds); + + if (neg_flags & NETLOGON_NEG_PASSWORD_SET2) { + + struct netr_CryptPassword new_password; + + init_netr_CryptPassword(new_trust_pwd_cleartext, + cli->dc->sess_key, + &new_password); + + result = rpccli_netr_ServerPasswordSet2(cli, mem_ctx, + cli->dc->remote_machine, + cli->dc->mach_acct, + sec_channel_type, + global_myname(), + &clnt_creds, + &srv_cred, + &new_password); + if (!NT_STATUS_IS_OK(result)) { + DEBUG(0,("rpccli_netr_ServerPasswordSet2 failed: %s\n", + nt_errstr(result))); + return result; + } + } else { + + struct samr_Password new_password; + + cred_hash3(new_password.hash, + new_trust_passwd_hash, + cli->dc->sess_key, 1); + + result = rpccli_netr_ServerPasswordSet(cli, mem_ctx, + cli->dc->remote_machine, + cli->dc->mach_acct, + sec_channel_type, + global_myname(), + &clnt_creds, + &srv_cred, + &new_password); + if (!NT_STATUS_IS_OK(result)) { + DEBUG(0,("rpccli_netr_ServerPasswordSet failed: %s\n", + nt_errstr(result))); + return result; + } + } + + /* Always check returned credentials. */ + if (!netlogon_creds_client_check(cli->dc, &srv_cred.cred)) { + DEBUG(0,("credentials chain check failed\n")); + return NT_STATUS_ACCESS_DENIED; + } + + return result; +} + -- cgit From 73aebd7d070099d4d6d6da98817f42937bc7fd03 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sun, 21 Sep 2008 20:39:17 +0200 Subject: Attempt to fix bug 5778 Jeff, Steve, please check! --- source3/client/mount.cifs.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/source3/client/mount.cifs.c b/source3/client/mount.cifs.c index 3b56e5f861..b7a76c6102 100644 --- a/source3/client/mount.cifs.c +++ b/source3/client/mount.cifs.c @@ -56,6 +56,10 @@ #endif /* _SAMBA_BUILD_ */ #endif /* MOUNT_CIFS_VENDOR_SUFFIX */ +#ifdef _SAMBA_BUILD_ +#include "include/config.h" +#endif + #ifndef MS_MOVE #define MS_MOVE 8192 #endif @@ -94,6 +98,8 @@ char * prefixpath = NULL; /* like strncpy but does not 0 fill the buffer and always null * terminates. bufsize is the size of the destination buffer */ + +#ifndef HAVE_STRLCPY static size_t strlcpy(char *d, const char *s, size_t bufsize) { size_t len = strlen(s); @@ -104,10 +110,13 @@ static size_t strlcpy(char *d, const char *s, size_t bufsize) d[len] = 0; return ret; } +#endif /* like strncat but does not 0 fill the buffer and always null * terminates. bufsize is the length of the buffer, which should * be one more than the maximum resulting string length */ + +#ifndef HAVE_STRLCAT static size_t strlcat(char *d, const char *s, size_t bufsize) { size_t len1 = strlen(d); @@ -126,6 +135,7 @@ static size_t strlcat(char *d, const char *s, size_t bufsize) } return ret; } +#endif /* BB finish BB -- cgit From afa850910ff7845b2c8b19fdcf6fbb703e42d2db Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 23:09:56 +0200 Subject: Avoid printing characters when in immediate mode. --- source4/selftest/output/plain.pm | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/source4/selftest/output/plain.pm b/source4/selftest/output/plain.pm index bad6505e93..4e1e290534 100644 --- a/source4/selftest/output/plain.pm +++ b/source4/selftest/output/plain.pm @@ -124,10 +124,12 @@ sub end_test($$$$$) unless ($unexpected) { $self->{test_output}->{$self->{NAME}} = ""; - if ($result eq "failure") { print "f"; } - elsif ($result eq "skip") { print "s"; } - elsif ($result eq "success") { print "."; } - else { print "?($result)"; } + if (not $self->{immediate}) { + if ($result eq "failure") { print "f"; } + elsif ($result eq "skip") { print "s"; } + elsif ($result eq "success") { print "."; } + else { print "?($result)"; } + } return; } -- cgit From faa4ac2a52cee89be66a11604dd65871b3b70a6b Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Fri, 12 Sep 2008 16:41:49 +0200 Subject: Registry tool "regtree": Handle the default attribute in the right way This commit introduces the default attribute in "regtree" --- source4/lib/registry/tools/regtree.c | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/source4/lib/registry/tools/regtree.c b/source4/lib/registry/tools/regtree.c index 19e4a010b4..fef9c7ee49 100644 --- a/source4/lib/registry/tools/regtree.c +++ b/source4/lib/registry/tools/regtree.c @@ -40,8 +40,8 @@ static void print_tree(int level, struct registry_key *p, struct registry_key *subkey; const char *valuename; const char *keyname; - uint32_t value_type; - DATA_BLOB value_data; + uint32_t valuetype; + DATA_BLOB valuedata; struct security_descriptor *sec_desc; WERROR error; int i; @@ -73,18 +73,24 @@ static void print_tree(int level, struct registry_key *p, if (!novals) { mem_ctx = talloc_init("print_tree"); - for(i = 0; W_ERROR_IS_OK(error = reg_key_get_value_by_index(mem_ctx, - p, - i, - &valuename, - &value_type, - &value_data)); i++) { + /* default value */ + if (W_ERROR_IS_OK(reg_key_get_value_by_index(mem_ctx, p, 0, + &valuename, &valuetype, &valuedata))) { int j; - char *desc; for(j = 0; j < level+1; j++) putchar(' '); - desc = reg_val_description(mem_ctx, lp_iconv_convenience(cmdline_lp_ctx), valuename, - value_type, value_data); - printf("%s\n", desc); + printf("%s\n", reg_val_description(mem_ctx, + lp_iconv_convenience(cmdline_lp_ctx), + "(Default)", valuetype, valuedata)); + } + /* other values */ + for(i = 1; W_ERROR_IS_OK(error = reg_key_get_value_by_index( + mem_ctx, p, i, &valuename, &valuetype, &valuedata)); + i++) { + int j; + for(j = 0; j < level+1; j++) putchar(' '); + printf("%s\n", reg_val_description(mem_ctx, + lp_iconv_convenience(cmdline_lp_ctx), valuename, + valuetype, valuedata)); } talloc_free(mem_ctx); -- cgit From 965a12f5b8bb862bab9eb46fba6e95f3906bae7d Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Fri, 12 Sep 2008 16:57:22 +0200 Subject: Registry tool "regtree": Removing an error message The error message "Error occurred while fetching values" doesn't seem very useful, so remove it. --- source4/lib/registry/tools/regtree.c | 5 ----- 1 file changed, 5 deletions(-) diff --git a/source4/lib/registry/tools/regtree.c b/source4/lib/registry/tools/regtree.c index fef9c7ee49..17a9163adc 100644 --- a/source4/lib/registry/tools/regtree.c +++ b/source4/lib/registry/tools/regtree.c @@ -93,11 +93,6 @@ static void print_tree(int level, struct registry_key *p, valuetype, valuedata)); } talloc_free(mem_ctx); - - if(!W_ERROR_EQUAL(error, WERR_NO_MORE_ITEMS)) { - DEBUG(0, ("Error occured while fetching values for '%s': %s\n", - name, win_errstr(error))); - } } mem_ctx = talloc_init("sec_desc"); -- cgit From a2d8ccad734b850a8e368408328c32b4f15e2525 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Fri, 12 Sep 2008 17:02:30 +0200 Subject: Registry tool "regshell": Handle the default attribute in the right way This commit introduces the default attribute in "regshell" --- source4/lib/registry/tools/regshell.c | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/source4/lib/registry/tools/regshell.c b/source4/lib/registry/tools/regshell.c index 98f7f02c38..fb7a08e38f 100644 --- a/source4/lib/registry/tools/regshell.c +++ b/source4/lib/registry/tools/regshell.c @@ -207,8 +207,8 @@ static WERROR cmd_ls(struct regshell_context *ctx, int argc, char **argv) { int i; WERROR error; - uint32_t data_type; - DATA_BLOB data; + uint32_t valuetype; + DATA_BLOB valuedata; const char *name = NULL; for (i = 0; W_ERROR_IS_OK(error = reg_key_get_subkey_by_index(ctx, @@ -221,19 +221,21 @@ static WERROR cmd_ls(struct regshell_context *ctx, int argc, char **argv) } if (!W_ERROR_EQUAL(error, WERR_NO_MORE_ITEMS)) { - DEBUG(0, ("Error occured while browsing thru keys: %s\n", - win_errstr(error))); + fprintf(stderr, "Error occured while browsing thru keys: %s\n", + win_errstr(error)); + return error; } - for (i = 0; W_ERROR_IS_OK(error = reg_key_get_value_by_index(ctx, - ctx->current, - i, - &name, - &data_type, - &data)); i++) { - printf("V \"%s\" %s %s\n", name, str_regtype(data_type), - reg_val_data_string(ctx, lp_iconv_convenience(cmdline_lp_ctx), data_type, data)); - } + /* default value */ + if (W_ERROR_IS_OK(reg_key_get_value_by_index(ctx, ctx->current, 0, + &name, &valuetype, &valuedata))) + printf("V \"(Default)\" %s %s\n", str_regtype(valuetype), + reg_val_data_string(ctx, lp_iconv_convenience(cmdline_lp_ctx), valuetype, valuedata)); + /* other values */ + for (i = 1; W_ERROR_IS_OK(error = reg_key_get_value_by_index(ctx, + ctx->current, i, &name, &valuetype, &valuedata)); i++) + printf("V \"%s\" %s %s\n", name, str_regtype(valuetype), + reg_val_data_string(ctx, lp_iconv_convenience(cmdline_lp_ctx), valuetype, valuedata)); return WERR_OK; } -- cgit From 5bf62260505d1e8dfddcb3acef69ef0217841a3f Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Fri, 12 Sep 2008 20:26:13 +0200 Subject: Registry client: Various cleanups and charset conversions This patch contains various changes to the "rpc.c" file to clean it up and introduces the right string charset conversions (UNIX <-> UTF16). --- source4/lib/registry/rpc.c | 191 +++++++++++++++++++++++++++++---------------- 1 file changed, 125 insertions(+), 66 deletions(-) diff --git a/source4/lib/registry/rpc.c b/source4/lib/registry/rpc.c index 18b7607713..3fdba02852 100644 --- a/source4/lib/registry/rpc.c +++ b/source4/lib/registry/rpc.c @@ -19,6 +19,7 @@ #include "includes.h" #include "registry.h" #include "librpc/gen_ndr/ndr_winreg_c.h" +#include "param/param.h" struct rpc_key { struct registry_key key; @@ -43,26 +44,82 @@ static struct registry_operations reg_backend_rpc; * This is the RPC backend for the registry library. */ -static void init_winreg_String(struct winreg_String *name, const char *s) +/* + * Converts a SAMBA (UNIX) string into a WINREG (UTF16) string + */ +static void chars_to_winreg_String(TALLOC_CTX *mem_ctx, struct winreg_String + *winregStr, const char *str) { - name->name = s; + winregStr->name = NULL; + winregStr->name_len = 0; + if (str != NULL) + winregStr->name_len = convert_string_talloc(mem_ctx, + lp_iconv_convenience(global_loadparm), CH_UNIX, + CH_UTF16, (void *) str, strlen(str), + (void **) &winregStr->name); + winregStr->name_size = winregStr->name_len; } +/* + * Converts a WINREG (UTF16) string into a SAMBA (UNIX) string + */ +static void winreg_String_to_chars(TALLOC_CTX *mem_ctx, const char **str, + struct winreg_String *winregStr) +{ + *str = NULL; + if (winregStr->name != NULL) + convert_string_talloc(mem_ctx, + lp_iconv_convenience(global_loadparm), CH_UTF16, + CH_UNIX, (void *) winregStr->name, winregStr->name_len, + (void **) str); +} + +/* + * Converts a SAMBA (UNIX) string into a WINREG (UTF16) string buffer + */ +static void chars_to_winreg_StringBuf(TALLOC_CTX *mem_ctx, struct winreg_StringBuf + *winregStrBuf, const char *str, uint16_t size) +{ + winregStrBuf->name = NULL; + winregStrBuf->length = 0; + if (str != NULL) + winregStrBuf->length = convert_string_talloc(mem_ctx, + lp_iconv_convenience(global_loadparm), CH_UNIX, + CH_UTF16, (void *) str, strlen(str), + (void **) &winregStrBuf->name); + winregStrBuf->size = size; +} + +/* + * Converts a WINREG (UTF16) string buffer into a SAMBA (UNIX) string + */ +static void winreg_StringBuf_to_chars(TALLOC_CTX *mem_ctx, const char **str, + struct winreg_StringBuf *winregStrBuf) +{ + *str = NULL; + if (winregStrBuf->name != NULL) + convert_string_talloc(mem_ctx, + lp_iconv_convenience(global_loadparm), CH_UTF16, + CH_UNIX, (void *) winregStrBuf->name, + winregStrBuf->length, (void **) str); +} #define openhive(u) static WERROR open_ ## u(struct dcerpc_pipe *p, TALLOC_CTX *mem_ctx, struct policy_handle *hnd) \ { \ struct winreg_Open ## u r; \ NTSTATUS status; \ - \ +\ + ZERO_STRUCT(r); \ r.in.system_name = NULL; \ r.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; \ r.out.handle = hnd;\ - \ +\ status = dcerpc_winreg_Open ## u(p, mem_ctx, &r); \ - if (NT_STATUS_IS_ERR(status)) {\ - DEBUG(0,("Error executing open\n"));\ - return ntstatus_to_werror(status);\ - }\ +\ + if (!NT_STATUS_IS_OK(status)) { \ + DEBUG(1, ("OpenHive failed - %s\n", nt_errstr(status))); \ + return ntstatus_to_werror(status); \ + } \ \ return r.out.result;\ } @@ -133,9 +190,9 @@ static WERROR rpc_key_put_rpc_data(TALLOC_CTX *mem_ctx, struct registry_key *k) /* Then, open the handle using the hive */ - memset(&r, 0, sizeof(struct winreg_OpenKey)); + ZERO_STRUCT(r); r.in.handle = &(((struct rpc_key_data *)k->hive->root->backend_data)->pol); - init_winreg_String(&r.in.keyname, k->path); + chars_to_winreg_String(mem_ctx, &r.in.keyname, k->path); r.in.unknown = 0x00000000; r.in.access_mask = 0x02000000; r.out.handle = &mykeydata->pol; @@ -166,14 +223,15 @@ static WERROR rpc_open_key(TALLOC_CTX *mem_ctx, struct registry_key *h, /* Then, open the handle using the hive */ ZERO_STRUCT(r); r.in.parent_handle = &parentkeydata->pol; - init_winreg_String(&r.in.keyname, name); + chars_to_winreg_String(mem_ctx, &r.in.keyname, name); r.in.unknown = 0x00000000; r.in.access_mask = 0x02000000; r.out.handle = &mykeydata->pol; status = dcerpc_winreg_OpenKey(mykeydata->pipe, mem_ctx, &r); - if (NT_STATUS_IS_ERR(status)) { - DEBUG(0,("Error executing openkey: %s\n", nt_errstr(status))); + + if (!NT_STATUS_IS_OK(status)) { + DEBUG(1, ("OpenKey failed - %s\n", nt_errstr(status))); return ntstatus_to_werror(status); } @@ -188,47 +246,45 @@ static WERROR rpc_get_value_by_index(TALLOC_CTX *mem_ctx, DATA_BLOB *data) { struct rpc_key *mykeydata = talloc_get_type(parent, struct rpc_key); - WERROR error; struct winreg_EnumValue r; - uint32_t in_type = 0; - NTSTATUS status; struct winreg_StringBuf name; - uint32_t zero = 0; - - ZERO_STRUCT(r); + uint8_t value; + uint32_t zero = 0, zero2 = 0; + WERROR error; + NTSTATUS status; if (mykeydata->num_values == -1) { error = rpc_query_key(parent); if(!W_ERROR_IS_OK(error)) return error; } - name.length = 0; - name.size = mykeydata->max_valnamelen * 2; - name.name = NULL; + chars_to_winreg_StringBuf(mem_ctx, &name, "", 1024); + ZERO_STRUCT(r); r.in.handle = &mykeydata->pol; r.in.enum_index = n; r.in.name = &name; - r.in.type = &in_type; - r.in.value = talloc_zero_array(mem_ctx, uint8_t, 0); - r.in.length = &zero; + r.in.type = type; + r.in.value = &value; r.in.size = &mykeydata->max_valdatalen; + r.in.length = &zero; r.out.name = &name; r.out.type = type; + r.out.value = &value; + r.out.size = &zero2; + r.out.length = &zero; status = dcerpc_winreg_EnumValue(mykeydata->pipe, mem_ctx, &r); - if(NT_STATUS_IS_ERR(status)) { - DEBUG(0, ("Error in EnumValue: %s\n", nt_errstr(status))); - return WERR_GENERAL_FAILURE; - } - if(NT_STATUS_IS_OK(status) && - W_ERROR_IS_OK(r.out.result) && r.out.length) { - *value_name = talloc_strdup(mem_ctx, r.out.name->name); - *data = data_blob_talloc(mem_ctx, r.out.value, *r.out.length); - return WERR_OK; + if (!NT_STATUS_IS_OK(status)) { + DEBUG(1, ("EnumValue failed - %s\n", nt_errstr(status))); + return ntstatus_to_werror(status); } + winreg_StringBuf_to_chars(mem_ctx, value_name, r.out.name); + *type = *(r.out.type); + *data = data_blob_talloc(mem_ctx, r.out.value, *r.out.length); + return r.out.result; } @@ -241,34 +297,33 @@ static WERROR rpc_get_subkey_by_index(TALLOC_CTX *mem_ctx, { struct winreg_EnumKey r; struct rpc_key *mykeydata = talloc_get_type(parent, struct rpc_key); - NTSTATUS status; struct winreg_StringBuf namebuf, classbuf; NTTIME change_time = 0; + NTSTATUS status; - ZERO_STRUCT(r); - - namebuf.length = 0; - namebuf.size = 1024; - namebuf.name = NULL; - classbuf.length = 0; - classbuf.size = 0; - classbuf.name = NULL; + chars_to_winreg_StringBuf(mem_ctx, &namebuf, "", 1024); + chars_to_winreg_StringBuf(mem_ctx, &classbuf, NULL, 0); + ZERO_STRUCT(r); r.in.handle = &mykeydata->pol; r.in.enum_index = n; r.in.name = &namebuf; r.in.keyclass = &classbuf; r.in.last_changed_time = &change_time; - r.out.name = &namebuf; + r.out.keyclass = &classbuf; + r.out.last_changed_time = &change_time; status = dcerpc_winreg_EnumKey(mykeydata->pipe, mem_ctx, &r); - if (NT_STATUS_IS_OK(status) && W_ERROR_IS_OK(r.out.result)) { - *name = talloc_strdup(mem_ctx, r.out.name->name); - if (keyclass != NULL) - *keyclass = talloc_strdup(mem_ctx, r.out.keyclass->name); + + if (!NT_STATUS_IS_OK(status)) { + DEBUG(1, ("EnumKey failed - %s\n", nt_errstr(status))); + return ntstatus_to_werror(status); } + winreg_StringBuf_to_chars(mem_ctx, name, r.out.name); + winreg_StringBuf_to_chars(mem_ctx, keyclass, r.out.keyclass); + return r.out.result; } @@ -278,19 +333,22 @@ static WERROR rpc_add_key(TALLOC_CTX *mem_ctx, struct security_descriptor *sec, struct registry_key **key) { - NTSTATUS status; struct winreg_CreateKey r; struct rpc_key *parentkd = talloc_get_type(parent, struct rpc_key); struct rpc_key *rpck = talloc(mem_ctx, struct rpc_key); + + NTSTATUS status; - init_winreg_String(&r.in.name, name); - init_winreg_String(&r.in.keyclass, NULL); - + ZERO_STRUCT(r); r.in.handle = &parentkd->pol; - r.out.new_handle = &rpck->pol; + chars_to_winreg_String(mem_ctx, &r.in.name, name); + chars_to_winreg_String(mem_ctx, &r.in.keyclass, NULL); r.in.options = 0; r.in.access_mask = SEC_STD_ALL; r.in.secdesc = NULL; + r.in.action_taken = NULL; + r.out.new_handle = &rpck->pol; + r.out.action_taken = NULL; status = dcerpc_winreg_CreateKey(parentkd->pipe, mem_ctx, &r); @@ -300,26 +358,25 @@ static WERROR rpc_add_key(TALLOC_CTX *mem_ctx, return ntstatus_to_werror(status); } - if (W_ERROR_IS_OK(r.out.result)) { - rpck->pipe = talloc_reference(rpck, parentkd->pipe); - *key = (struct registry_key *)rpck; - } + rpck->pipe = talloc_reference(rpck, parentkd->pipe); + *key = (struct registry_key *)rpck; return r.out.result; } static WERROR rpc_query_key(const struct registry_key *k) { - NTSTATUS status; struct winreg_QueryInfoKey r; struct rpc_key *mykeydata = talloc_get_type(k, struct rpc_key); TALLOC_CTX *mem_ctx = talloc_init("query_key"); uint32_t max_subkeysize; uint32_t secdescsize; NTTIME last_changed_time; + NTSTATUS status; - ZERO_STRUCT(r.out); - + ZERO_STRUCT(r); + r.in.handle = &mykeydata->pol; + chars_to_winreg_String(mem_ctx, r.in.classname, NULL); r.out.num_subkeys = &mykeydata->num_subkeys; r.out.max_subkeylen = &mykeydata->max_subkeynamelen; r.out.max_valnamelen = &mykeydata->max_valnamelen; @@ -330,10 +387,9 @@ static WERROR rpc_query_key(const struct registry_key *k) r.out.last_changed_time = &last_changed_time; r.out.classname = r.in.classname = talloc_zero(mem_ctx, struct winreg_String); - init_winreg_String(r.in.classname, NULL); - r.in.handle = &mykeydata->pol; status = dcerpc_winreg_QueryInfoKey(mykeydata->pipe, mem_ctx, &r); + talloc_free(mem_ctx); if (!NT_STATUS_IS_OK(status)) { @@ -341,9 +397,6 @@ static WERROR rpc_query_key(const struct registry_key *k) return ntstatus_to_werror(status); } - if (W_ERROR_IS_OK(r.out.result)) { - } - return r.out.result; } @@ -354,13 +407,19 @@ static WERROR rpc_del_key(struct registry_key *parent, const char *name) struct winreg_DeleteKey r; TALLOC_CTX *mem_ctx = talloc_init("del_key"); + ZERO_STRUCT(r); r.in.handle = &mykeydata->pol; - init_winreg_String(&r.in.key, name); + chars_to_winreg_String(mem_ctx, &r.in.key, name); status = dcerpc_winreg_DeleteKey(mykeydata->pipe, mem_ctx, &r); talloc_free(mem_ctx); + if (!NT_STATUS_IS_OK(status)) { + DEBUG(1, ("DeleteKey failed - %s\n", nt_errstr(status))); + return ntstatus_to_werror(status); + } + return r.out.result; } -- cgit From 92e1574d3ddb0edf3173e18c6e0dfc4974bedcf5 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Sat, 13 Sep 2008 12:26:03 +0200 Subject: Registry tools "regshell" and "regtree": Small fixup's I fixed up my fault regarding the handling of the default value (if it doesn't exist it hasn't the index number zero and you get immediately the subvalues). Then I corrected an error in regshell to find the right registry context. --- source4/lib/registry/tools/regshell.c | 13 ++++--------- source4/lib/registry/tools/regtree.c | 15 ++------------- 2 files changed, 6 insertions(+), 22 deletions(-) diff --git a/source4/lib/registry/tools/regshell.c b/source4/lib/registry/tools/regshell.c index fb7a08e38f..208b19fba8 100644 --- a/source4/lib/registry/tools/regshell.c +++ b/source4/lib/registry/tools/regshell.c @@ -226,13 +226,7 @@ static WERROR cmd_ls(struct regshell_context *ctx, int argc, char **argv) return error; } - /* default value */ - if (W_ERROR_IS_OK(reg_key_get_value_by_index(ctx, ctx->current, 0, - &name, &valuetype, &valuedata))) - printf("V \"(Default)\" %s %s\n", str_regtype(valuetype), - reg_val_data_string(ctx, lp_iconv_convenience(cmdline_lp_ctx), valuetype, valuedata)); - /* other values */ - for (i = 1; W_ERROR_IS_OK(error = reg_key_get_value_by_index(ctx, + for (i = 0; W_ERROR_IS_OK(error = reg_key_get_value_by_index(ctx, ctx->current, i, &name, &valuetype, &valuedata)); i++) printf("V \"%s\" %s %s\n", name, str_regtype(valuetype), reg_val_data_string(ctx, lp_iconv_convenience(cmdline_lp_ctx), valuetype, valuedata)); @@ -440,7 +434,7 @@ static char **reg_complete_key(const char *text, int start, int end) len = strlen(text); for(i = 0; j < MAX_COMPLETIONS-1; i++) { status = reg_key_get_subkey_by_index(mem_ctx, base, i, - &subkeyname, NULL, NULL); + &subkeyname, NULL, NULL); if(W_ERROR_IS_OK(status)) { if(!strncmp(text, subkeyname, len)) { matches[j] = strdup(subkeyname); @@ -538,7 +532,8 @@ int main(int argc, char **argv) if (ctx->current == NULL) { int i; - for (i = 0; reg_predefined_keys[i].handle; i++) { + for (i = 0; (reg_predefined_keys[i].handle != 0) && + (ctx->current == NULL); i++) { WERROR err; err = reg_get_predefined_key(ctx->registry, reg_predefined_keys[i].handle, diff --git a/source4/lib/registry/tools/regtree.c b/source4/lib/registry/tools/regtree.c index 17a9163adc..2175f9c9d3 100644 --- a/source4/lib/registry/tools/regtree.c +++ b/source4/lib/registry/tools/regtree.c @@ -38,8 +38,7 @@ static void print_tree(int level, struct registry_key *p, bool fullpath, bool novals) { struct registry_key *subkey; - const char *valuename; - const char *keyname; + const char *valuename, *keyname; uint32_t valuetype; DATA_BLOB valuedata; struct security_descriptor *sec_desc; @@ -73,17 +72,7 @@ static void print_tree(int level, struct registry_key *p, if (!novals) { mem_ctx = talloc_init("print_tree"); - /* default value */ - if (W_ERROR_IS_OK(reg_key_get_value_by_index(mem_ctx, p, 0, - &valuename, &valuetype, &valuedata))) { - int j; - for(j = 0; j < level+1; j++) putchar(' '); - printf("%s\n", reg_val_description(mem_ctx, - lp_iconv_convenience(cmdline_lp_ctx), - "(Default)", valuetype, valuedata)); - } - /* other values */ - for(i = 1; W_ERROR_IS_OK(error = reg_key_get_value_by_index( + for(i = 0; W_ERROR_IS_OK(error = reg_key_get_value_by_index( mem_ctx, p, i, &valuename, &valuetype, &valuedata)); i++) { int j; -- cgit From c1fef1fabf03e9c2f412b03d9f8cd314a5d34760 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Sat, 13 Sep 2008 12:30:47 +0200 Subject: Registry client library: Various fixup's and corrections I reverted the change with the string conversions because they aren't needed and included many fixup's and improvements in the code. We should be able now to connect to a Windows WINREG server without a problem. --- source4/lib/registry/rpc.c | 127 +++++++++++++++++++++++---------------------- 1 file changed, 64 insertions(+), 63 deletions(-) diff --git a/source4/lib/registry/rpc.c b/source4/lib/registry/rpc.c index 3fdba02852..2792bd556b 100644 --- a/source4/lib/registry/rpc.c +++ b/source4/lib/registry/rpc.c @@ -2,6 +2,7 @@ Samba Unix/Linux SMB implementation RPC backend for the registry library Copyright (C) 2003-2007 Jelmer Vernooij, jelmer@samba.org + Copyright (C) 2008 Matthias Dieter Wallnöfer, mwallnoefer@yahoo.de 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 @@ -19,18 +20,21 @@ #include "includes.h" #include "registry.h" #include "librpc/gen_ndr/ndr_winreg_c.h" -#include "param/param.h" struct rpc_key { struct registry_key key; struct policy_handle pol; struct dcerpc_pipe *pipe; - uint32_t num_values; + const char* classname; uint32_t num_subkeys; + uint32_t max_subkeylen; + uint32_t max_subkeysize; + uint32_t num_values; uint32_t max_valnamelen; - uint32_t max_valdatalen; - uint32_t max_subkeynamelen; + uint32_t max_valbufsize; + uint32_t secdescsize; + NTTIME last_changed_time; }; struct rpc_registry_context { @@ -45,63 +49,55 @@ static struct registry_operations reg_backend_rpc; */ /* - * Converts a SAMBA (UNIX) string into a WINREG (UTF16) string + * Converts a SAMBA string into a WINREG string */ static void chars_to_winreg_String(TALLOC_CTX *mem_ctx, struct winreg_String *winregStr, const char *str) { winregStr->name = NULL; winregStr->name_len = 0; - if (str != NULL) - winregStr->name_len = convert_string_talloc(mem_ctx, - lp_iconv_convenience(global_loadparm), CH_UNIX, - CH_UTF16, (void *) str, strlen(str), - (void **) &winregStr->name); + if (str != NULL) { + winregStr->name = talloc_strdup(mem_ctx, str); + winregStr->name_len = strlen(str); + } winregStr->name_size = winregStr->name_len; } /* - * Converts a WINREG (UTF16) string into a SAMBA (UNIX) string + * Converts a WINREG string into a SAMBA string */ static void winreg_String_to_chars(TALLOC_CTX *mem_ctx, const char **str, struct winreg_String *winregStr) { *str = NULL; if (winregStr->name != NULL) - convert_string_talloc(mem_ctx, - lp_iconv_convenience(global_loadparm), CH_UTF16, - CH_UNIX, (void *) winregStr->name, winregStr->name_len, - (void **) str); + *str = talloc_strdup(mem_ctx, winregStr->name); } /* - * Converts a SAMBA (UNIX) string into a WINREG (UTF16) string buffer + * Converts a SAMBA string into a WINREG string buffer */ static void chars_to_winreg_StringBuf(TALLOC_CTX *mem_ctx, struct winreg_StringBuf *winregStrBuf, const char *str, uint16_t size) { winregStrBuf->name = NULL; winregStrBuf->length = 0; - if (str != NULL) - winregStrBuf->length = convert_string_talloc(mem_ctx, - lp_iconv_convenience(global_loadparm), CH_UNIX, - CH_UTF16, (void *) str, strlen(str), - (void **) &winregStrBuf->name); + if (str != NULL) { + winregStrBuf->name = talloc_strdup(mem_ctx, str); + winregStrBuf->length = strlen(str); + } winregStrBuf->size = size; } /* - * Converts a WINREG (UTF16) string buffer into a SAMBA (UNIX) string + * Converts a WINREG string buffer into a SAMBA string */ static void winreg_StringBuf_to_chars(TALLOC_CTX *mem_ctx, const char **str, struct winreg_StringBuf *winregStrBuf) { *str = NULL; if (winregStrBuf->name != NULL) - convert_string_talloc(mem_ctx, - lp_iconv_convenience(global_loadparm), CH_UTF16, - CH_UNIX, (void *) winregStrBuf->name, - winregStrBuf->length, (void **) str); + *str = talloc_strdup(mem_ctx, winregStrBuf->name); } #define openhive(u) static WERROR open_ ## u(struct dcerpc_pipe *p, TALLOC_CTX *mem_ctx, struct policy_handle *hnd) \ @@ -147,7 +143,7 @@ static struct { { 0, NULL } }; -static WERROR rpc_query_key(const struct registry_key *k); +static WERROR rpc_query_key(TALLOC_CTX *mem_ctx, const struct registry_key *k); static WERROR rpc_get_predefined_key(struct registry_context *ctx, uint32_t hkey_type, @@ -254,11 +250,11 @@ static WERROR rpc_get_value_by_index(TALLOC_CTX *mem_ctx, NTSTATUS status; if (mykeydata->num_values == -1) { - error = rpc_query_key(parent); + error = rpc_query_key(mem_ctx, parent); if(!W_ERROR_IS_OK(error)) return error; } - chars_to_winreg_StringBuf(mem_ctx, &name, "", 1024); + chars_to_winreg_StringBuf(mem_ctx, &name, "", mykeydata->max_valbufsize); ZERO_STRUCT(r); r.in.handle = &mykeydata->pol; @@ -266,7 +262,7 @@ static WERROR rpc_get_value_by_index(TALLOC_CTX *mem_ctx, r.in.name = &name; r.in.type = type; r.in.value = &value; - r.in.size = &mykeydata->max_valdatalen; + r.in.size = &mykeydata->max_valbufsize; r.in.length = &zero; r.out.name = &name; r.out.type = type; @@ -301,7 +297,7 @@ static WERROR rpc_get_subkey_by_index(TALLOC_CTX *mem_ctx, NTTIME change_time = 0; NTSTATUS status; - chars_to_winreg_StringBuf(mem_ctx, &namebuf, "", 1024); + chars_to_winreg_StringBuf(mem_ctx, &namebuf, " ", 1024); chars_to_winreg_StringBuf(mem_ctx, &classbuf, NULL, 0); ZERO_STRUCT(r); @@ -321,8 +317,12 @@ static WERROR rpc_get_subkey_by_index(TALLOC_CTX *mem_ctx, return ntstatus_to_werror(status); } - winreg_StringBuf_to_chars(mem_ctx, name, r.out.name); - winreg_StringBuf_to_chars(mem_ctx, keyclass, r.out.keyclass); + if (name != NULL) + winreg_StringBuf_to_chars(mem_ctx, name, r.out.name); + if (keyclass != NULL) + winreg_StringBuf_to_chars(mem_ctx, keyclass, r.out.keyclass); + if (last_changed_time != NULL) + *last_changed_time = *(r.out.last_changed_time); return r.out.result; } @@ -364,39 +364,37 @@ static WERROR rpc_add_key(TALLOC_CTX *mem_ctx, return r.out.result; } -static WERROR rpc_query_key(const struct registry_key *k) +static WERROR rpc_query_key(TALLOC_CTX *mem_ctx, const struct registry_key *k) { struct winreg_QueryInfoKey r; struct rpc_key *mykeydata = talloc_get_type(k, struct rpc_key); - TALLOC_CTX *mem_ctx = talloc_init("query_key"); - uint32_t max_subkeysize; - uint32_t secdescsize; - NTTIME last_changed_time; + struct winreg_String classname; NTSTATUS status; + chars_to_winreg_String(mem_ctx, &classname, NULL); + ZERO_STRUCT(r); r.in.handle = &mykeydata->pol; - chars_to_winreg_String(mem_ctx, r.in.classname, NULL); + r.in.classname = &classname; + r.out.classname = &classname; r.out.num_subkeys = &mykeydata->num_subkeys; - r.out.max_subkeylen = &mykeydata->max_subkeynamelen; - r.out.max_valnamelen = &mykeydata->max_valnamelen; - r.out.max_valbufsize = &mykeydata->max_valdatalen; - r.out.max_subkeysize = &max_subkeysize; + r.out.max_subkeylen = &mykeydata->max_subkeylen; + r.out.max_subkeysize = &mykeydata->max_subkeysize; r.out.num_values = &mykeydata->num_values; - r.out.secdescsize = &secdescsize; - r.out.last_changed_time = &last_changed_time; - - r.out.classname = r.in.classname = talloc_zero(mem_ctx, struct winreg_String); + r.out.max_valnamelen = &mykeydata->max_valnamelen; + r.out.max_valbufsize = &mykeydata->max_valbufsize; + r.out.secdescsize = &mykeydata->secdescsize; + r.out.last_changed_time = &mykeydata->last_changed_time; status = dcerpc_winreg_QueryInfoKey(mykeydata->pipe, mem_ctx, &r); - talloc_free(mem_ctx); - if (!NT_STATUS_IS_OK(status)) { DEBUG(1, ("QueryInfoKey failed - %s\n", nt_errstr(status))); return ntstatus_to_werror(status); } + winreg_String_to_chars(mem_ctx, &mykeydata->classname, r.out.classname); + return r.out.result; } @@ -425,10 +423,10 @@ static WERROR rpc_del_key(struct registry_key *parent, const char *name) static WERROR rpc_get_info(TALLOC_CTX *mem_ctx, const struct registry_key *key, const char **classname, - uint32_t *numsubkeys, - uint32_t *numvalue, + uint32_t *num_subkeys, + uint32_t *num_values, NTTIME *last_changed_time, - uint32_t *max_subkeynamelen, + uint32_t *max_subkeylen, uint32_t *max_valnamelen, uint32_t *max_valbufsize) { @@ -436,27 +434,30 @@ static WERROR rpc_get_info(TALLOC_CTX *mem_ctx, const struct registry_key *key, WERROR error; if (mykeydata->num_values == -1) { - error = rpc_query_key(key); + error = rpc_query_key(mem_ctx, key); if(!W_ERROR_IS_OK(error)) return error; } - /* FIXME: *classname = talloc_strdup(mem_ctx, mykeydata->classname); */ - /* FIXME: *last_changed_time = mykeydata->last_changed_time */ + if (classname != NULL) + *classname = mykeydata->classname; + + if (num_subkeys != NULL) + *num_subkeys = mykeydata->num_subkeys; - if (numvalue != NULL) - *numvalue = mykeydata->num_values; + if (num_values != NULL) + *num_values = mykeydata->num_values; - if (numsubkeys != NULL) - *numsubkeys = mykeydata->num_subkeys; + if (last_changed_time != NULL) + *last_changed_time = mykeydata->last_changed_time; + + if (max_subkeylen != NULL) + *max_subkeylen = mykeydata->max_subkeylen; if (max_valnamelen != NULL) *max_valnamelen = mykeydata->max_valnamelen; if (max_valbufsize != NULL) - *max_valbufsize = mykeydata->max_valdatalen; - - if (max_subkeynamelen != NULL) - *max_subkeynamelen = mykeydata->max_subkeynamelen; + *max_valbufsize = mykeydata->max_valbufsize; return WERR_OK; } -- cgit From 1e178ffc03456064bfd2ec330b9b6b6217c8561d Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Sat, 13 Sep 2008 14:26:08 +0200 Subject: Registry client library: Fix some buffer problems This buffer maximum values are used in Windows (2000), so I take them also for SAMBA 4. --- source4/lib/registry/rpc.c | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/source4/lib/registry/rpc.c b/source4/lib/registry/rpc.c index 2792bd556b..7469bb60d8 100644 --- a/source4/lib/registry/rpc.c +++ b/source4/lib/registry/rpc.c @@ -21,6 +21,9 @@ #include "registry.h" #include "librpc/gen_ndr/ndr_winreg_c.h" +#define MAX_NAMESIZE 512 +#define MAX_VALSIZE 32768 + struct rpc_key { struct registry_key key; struct policy_handle pol; @@ -245,7 +248,8 @@ static WERROR rpc_get_value_by_index(TALLOC_CTX *mem_ctx, struct winreg_EnumValue r; struct winreg_StringBuf name; uint8_t value; - uint32_t zero = 0, zero2 = 0; + uint32_t val_size = MAX_VALSIZE; + uint32_t zero = 0; WERROR error; NTSTATUS status; @@ -254,7 +258,7 @@ static WERROR rpc_get_value_by_index(TALLOC_CTX *mem_ctx, if(!W_ERROR_IS_OK(error)) return error; } - chars_to_winreg_StringBuf(mem_ctx, &name, "", mykeydata->max_valbufsize); + chars_to_winreg_StringBuf(mem_ctx, &name, "", MAX_NAMESIZE); ZERO_STRUCT(r); r.in.handle = &mykeydata->pol; @@ -262,12 +266,12 @@ static WERROR rpc_get_value_by_index(TALLOC_CTX *mem_ctx, r.in.name = &name; r.in.type = type; r.in.value = &value; - r.in.size = &mykeydata->max_valbufsize; + r.in.size = &val_size; r.in.length = &zero; r.out.name = &name; r.out.type = type; r.out.value = &value; - r.out.size = &zero2; + r.out.size = &val_size; r.out.length = &zero; status = dcerpc_winreg_EnumValue(mykeydata->pipe, mem_ctx, &r); @@ -297,7 +301,7 @@ static WERROR rpc_get_subkey_by_index(TALLOC_CTX *mem_ctx, NTTIME change_time = 0; NTSTATUS status; - chars_to_winreg_StringBuf(mem_ctx, &namebuf, " ", 1024); + chars_to_winreg_StringBuf(mem_ctx, &namebuf, " ", MAX_NAMESIZE); chars_to_winreg_StringBuf(mem_ctx, &classbuf, NULL, 0); ZERO_STRUCT(r); -- cgit From 04f29b84a4bf2378d326b86a983792095231922e Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Sat, 13 Sep 2008 15:02:56 +0200 Subject: Registry client library: Fixes the creation of new keys Giving the right permissions --- source4/lib/registry/rpc.c | 2 +- source4/lib/registry/tools/regshell.c | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/source4/lib/registry/rpc.c b/source4/lib/registry/rpc.c index 7469bb60d8..69da90128e 100644 --- a/source4/lib/registry/rpc.c +++ b/source4/lib/registry/rpc.c @@ -348,7 +348,7 @@ static WERROR rpc_add_key(TALLOC_CTX *mem_ctx, chars_to_winreg_String(mem_ctx, &r.in.name, name); chars_to_winreg_String(mem_ctx, &r.in.keyclass, NULL); r.in.options = 0; - r.in.access_mask = SEC_STD_ALL; + r.in.access_mask = 0x02000000; r.in.secdesc = NULL; r.in.action_taken = NULL; r.out.new_handle = &rpck->pol; diff --git a/source4/lib/registry/tools/regshell.c b/source4/lib/registry/tools/regshell.c index 208b19fba8..5c308bfbda 100644 --- a/source4/lib/registry/tools/regshell.c +++ b/source4/lib/registry/tools/regshell.c @@ -246,7 +246,8 @@ static WERROR cmd_mkkey(struct regshell_context *ctx, int argc, char **argv) error = reg_key_add_name(ctx, ctx->current, argv[1], 0, NULL, &tmp); if (!W_ERROR_IS_OK(error)) { - fprintf(stderr, "Error adding new subkey '%s'\n", argv[1]); + fprintf(stderr, "Error adding new subkey '%s': %s\n", argv[1], + win_errstr(error)); return error; } -- cgit From db829f04adc27764a4a53ae94bc24c64e143e024 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Sun, 14 Sep 2008 03:29:07 +0200 Subject: Registry tool "regdiff": Add the event context for remote connections Adds the event context for remote connections to make the tool working again. --- source4/lib/registry/tools/regdiff.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/lib/registry/tools/regdiff.c b/source4/lib/registry/tools/regdiff.c index 240c582340..fcf7c26237 100644 --- a/source4/lib/registry/tools/regdiff.c +++ b/source4/lib/registry/tools/regdiff.c @@ -46,7 +46,7 @@ static struct registry_context *open_backend(poptContext pc, break; case REG_REMOTE: error = reg_open_remote(&ctx, NULL, cmdline_credentials, lp_ctx, - remote_host, NULL); + remote_host, ev_ctx); break; case REG_NULL: error = reg_open_local(NULL, &ctx); -- cgit From 9b70485207735a8d4c1395963944e5a19a791f53 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Mon, 15 Sep 2008 13:04:40 +0200 Subject: Registry client library: Use "talloc_zero" to avoid uninitialized values --- source4/lib/registry/rpc.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/source4/lib/registry/rpc.c b/source4/lib/registry/rpc.c index 69da90128e..83c6dc762c 100644 --- a/source4/lib/registry/rpc.c +++ b/source4/lib/registry/rpc.c @@ -183,7 +183,7 @@ static WERROR rpc_key_put_rpc_data(TALLOC_CTX *mem_ctx, struct registry_key *k) struct winreg_OpenKey r; struct rpc_key_data *mykeydata; - k->backend_data = mykeydata = talloc(mem_ctx, struct rpc_key_data); + k->backend_data = mykeydata = talloc_zero(mem_ctx, struct rpc_key_data); mykeydata->num_values = -1; mykeydata->num_subkeys = -1; @@ -211,8 +211,7 @@ static WERROR rpc_open_key(TALLOC_CTX *mem_ctx, struct registry_key *h, struct winreg_OpenKey r; NTSTATUS status; - mykeydata = talloc(mem_ctx, struct rpc_key); - + mykeydata = talloc_zero(mem_ctx, struct rpc_key); mykeydata->key.context = parentkeydata->key.context; mykeydata->pipe = talloc_reference(mykeydata, parentkeydata->pipe); mykeydata->num_values = -1; -- cgit From f25f0dd74489bfea39170a9277afbf96deb8f389 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Mon, 15 Sep 2008 18:59:17 +0200 Subject: Registry client: Implement the "winreg_QueryValue" call This is needed for the registry patchfile library --- source4/lib/registry/rpc.c | 48 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/source4/lib/registry/rpc.c b/source4/lib/registry/rpc.c index 83c6dc762c..b5918dc4db 100644 --- a/source4/lib/registry/rpc.c +++ b/source4/lib/registry/rpc.c @@ -287,6 +287,53 @@ static WERROR rpc_get_value_by_index(TALLOC_CTX *mem_ctx, return r.out.result; } +static WERROR rpc_get_value_by_name(TALLOC_CTX *mem_ctx, + const struct registry_key *parent, + const char *value_name, + uint32_t *type, + DATA_BLOB *data) +{ + struct rpc_key *mykeydata = talloc_get_type(parent, struct rpc_key); + struct winreg_QueryValue r; + struct winreg_String name; + uint8_t value; + uint32_t val_size = MAX_VALSIZE; + uint32_t zero = 0; + WERROR error; + NTSTATUS status; + + if (mykeydata->num_values == -1) { + error = rpc_query_key(mem_ctx, parent); + if(!W_ERROR_IS_OK(error)) return error; + } + + chars_to_winreg_String(mem_ctx, &name, value_name); + + ZERO_STRUCT(r); + r.in.handle = &mykeydata->pol; + r.in.value_name = name; + r.in.type = type; + r.in.data = &value; + r.in.size = &val_size; + r.in.length = &zero; + r.out.type = type; + r.out.data = &value; + r.out.size = &val_size; + r.out.length = &zero; + + status = dcerpc_winreg_QueryValue(mykeydata->pipe, mem_ctx, &r); + + if (!NT_STATUS_IS_OK(status)) { + DEBUG(1, ("QueryValue failed - %s\n", nt_errstr(status))); + return ntstatus_to_werror(status); + } + + *type = *(r.out.type); + *data = data_blob_talloc(mem_ctx, r.out.data, *r.out.length); + + return r.out.result; +} + static WERROR rpc_get_subkey_by_index(TALLOC_CTX *mem_ctx, const struct registry_key *parent, uint32_t n, @@ -471,6 +518,7 @@ static struct registry_operations reg_backend_rpc = { .get_predefined_key = rpc_get_predefined_key, .enum_key = rpc_get_subkey_by_index, .enum_value = rpc_get_value_by_index, + .get_value = rpc_get_value_by_name, .create_key = rpc_add_key, .delete_key = rpc_del_key, .get_key_info = rpc_get_info, -- cgit From 03e582cc866a957af792a7c128716622f1a1dc83 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Mon, 15 Sep 2008 19:00:07 +0200 Subject: Registry client: Fixup the "patchfile" library Rework and enhance the "patchfile" library (used in "regdiff") --- source4/lib/registry/patchfile.c | 104 +++++++++++++++++++++++++-------------- 1 file changed, 66 insertions(+), 38 deletions(-) diff --git a/source4/lib/registry/patchfile.c b/source4/lib/registry/patchfile.c index 0ede3106f0..d49d46250d 100644 --- a/source4/lib/registry/patchfile.c +++ b/source4/lib/registry/patchfile.c @@ -4,6 +4,7 @@ Copyright (C) Jelmer Vernooij 2004-2007 Copyright (C) Wilco Baan Hofman 2006 + Copyright (C) Matthias Dieter Wallnöfer 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 @@ -58,8 +59,9 @@ WERROR reg_generate_diff_key(struct registry_key *oldkey, &old_num_subkeys, &old_num_values, NULL, NULL, NULL, NULL); if (!W_ERROR_IS_OK(error)) { - DEBUG(0, ("Error occured while getting key info: %s\n", + DEBUG(0, ("Error occurred while getting key info: %s\n", win_errstr(error))); + talloc_free(mem_ctx); return error; } } else { @@ -70,11 +72,10 @@ WERROR reg_generate_diff_key(struct registry_key *oldkey, /* Subkeys that were deleted */ for (i = 0; i < old_num_subkeys; i++) { error1 = reg_key_get_subkey_by_index(mem_ctx, oldkey, i, - &keyname1, - NULL, NULL); + &keyname1, NULL, NULL); if (!W_ERROR_IS_OK(error1)) { - DEBUG(0, ("Error occured while getting subkey by index: %s\n", - win_errstr(error2))); + DEBUG(0, ("Error occurred while getting subkey by index: %s\n", + win_errstr(error1))); continue; } @@ -98,6 +99,17 @@ WERROR reg_generate_diff_key(struct registry_key *oldkey, /* newkey didn't have such a subkey, add del diff */ tmppath = talloc_asprintf(mem_ctx, "%s\\%s", path, keyname1); callbacks->del_key(callback_data, tmppath); + + /* perform here also the recursive invocation */ + error1 = reg_open_key(mem_ctx, oldkey, keyname1, &t1); + if (!W_ERROR_IS_OK(error1)) { + DEBUG(0, ("Error occured while getting subkey by name: %s\n", + win_errstr(error1))); + talloc_free(mem_ctx); + return error1; + } + reg_generate_diff_key(t1, t2, tmppath, callbacks, callback_data); + talloc_free(tmppath); } @@ -106,8 +118,9 @@ WERROR reg_generate_diff_key(struct registry_key *oldkey, &new_num_subkeys, &new_num_values, NULL, NULL, NULL, NULL); if (!W_ERROR_IS_OK(error)) { - DEBUG(0, ("Error occured while getting key info: %s\n", + DEBUG(0, ("Error occurred while getting key info: %s\n", win_errstr(error))); + talloc_free(mem_ctx); return error; } } else { @@ -117,11 +130,10 @@ WERROR reg_generate_diff_key(struct registry_key *oldkey, /* Subkeys that were added */ for(i = 0; i < new_num_subkeys; i++) { - error1 = reg_key_get_subkey_by_index(mem_ctx, newkey, - i, &keyname1, - NULL, NULL); + error1 = reg_key_get_subkey_by_index(mem_ctx, newkey, i, + &keyname1, NULL, NULL); if (!W_ERROR_IS_OK(error1)) { - DEBUG(0, ("Error occured while getting subkey by index: %s\n", + DEBUG(0, ("Error occurred while getting subkey by index: %s\n", win_errstr(error1))); talloc_free(mem_ctx); return error1; @@ -133,12 +145,12 @@ WERROR reg_generate_diff_key(struct registry_key *oldkey, if (W_ERROR_IS_OK(error2)) continue; } else { + error2 = WERR_BADFILE; t1 = NULL; - error2 = WERR_BADFILE; } if (!W_ERROR_EQUAL(error2, WERR_BADFILE)) { - DEBUG(0, ("Error occured while getting subkey by name: %s\n", + DEBUG(0, ("Error occurred while getting subkey by name: %s\n", win_errstr(error2))); talloc_free(mem_ctx); return error2; @@ -148,15 +160,20 @@ WERROR reg_generate_diff_key(struct registry_key *oldkey, tmppath = talloc_asprintf(mem_ctx, "%s\\%s", path, keyname1); callbacks->add_key(callback_data, tmppath); - W_ERROR_NOT_OK_RETURN( - reg_open_key(mem_ctx, newkey, keyname1, &t2)); + /* perform here also the recursive invocation */ + error1 = reg_open_key(mem_ctx, newkey, keyname1, &t2); + if (!W_ERROR_IS_OK(error1)) { + DEBUG(0, ("Error occured while getting subkey by name: %s\n", + win_errstr(error1))); + talloc_free(mem_ctx); + return error1; + } + reg_generate_diff_key(t1, t2, tmppath, callbacks, callback_data); - reg_generate_diff_key(t1, t2, tmppath, - callbacks, callback_data); talloc_free(tmppath); } - /* Values that were changed */ + /* Values that were added or changed */ for(i = 0; i < new_num_values; i++) { const char *name; uint32_t type1, type2; @@ -165,7 +182,7 @@ WERROR reg_generate_diff_key(struct registry_key *oldkey, error1 = reg_key_get_value_by_index(mem_ctx, newkey, i, &name, &type1, &contents1); if (!W_ERROR_IS_OK(error1)) { - DEBUG(0, ("Unable to get key by index: %s\n", + DEBUG(0, ("Unable to get value by index: %s\n", win_errstr(error1))); talloc_free(mem_ctx); return error1; @@ -178,16 +195,17 @@ WERROR reg_generate_diff_key(struct registry_key *oldkey, } else error2 = WERR_BADFILE; - if(!W_ERROR_IS_OK(error2) && - !W_ERROR_EQUAL(error2, WERR_BADFILE)) { - DEBUG(0, ("Error occured while getting value by name: %s\n", + if (!W_ERROR_IS_OK(error2) + && !W_ERROR_EQUAL(error2, WERR_BADFILE)) { + DEBUG(0, ("Error occurred while getting value by name: %s\n", win_errstr(error2))); talloc_free(mem_ctx); return error2; } - if (W_ERROR_IS_OK(error2) && - data_blob_cmp(&contents1, &contents2) == 0) + if (W_ERROR_IS_OK(error2) + && (data_blob_cmp(&contents1, &contents2) == 0) + && (type1 == type2)) continue; callbacks->set_value(callback_data, path, name, @@ -197,24 +215,31 @@ WERROR reg_generate_diff_key(struct registry_key *oldkey, /* Values that were deleted */ for (i = 0; i < old_num_values; i++) { const char *name; + uint32_t type; + DATA_BLOB contents; + error1 = reg_key_get_value_by_index(mem_ctx, oldkey, i, &name, - NULL, NULL); + &type, &contents); if (!W_ERROR_IS_OK(error1)) { - DEBUG(0, ("Error ocurred getting value by index: %s\n", + DEBUG(0, ("Unable to get value by index: %s\n", win_errstr(error1))); talloc_free(mem_ctx); return error1; } - error2 = reg_key_get_value_by_name(mem_ctx, newkey, name, NULL, - NULL); + if (newkey != NULL) + error2 = reg_key_get_value_by_name(mem_ctx, newkey, + name, &type, &contents); + else + error2 = WERR_BADFILE; if (W_ERROR_IS_OK(error2)) continue; if (!W_ERROR_EQUAL(error2, WERR_BADFILE)) { - DEBUG(0, ("Error occured while getting value by name: %s\n", + DEBUG(0, ("Error occurred while getting value by name: %s\n", win_errstr(error2))); + talloc_free(mem_ctx); return error2; } @@ -236,27 +261,30 @@ _PUBLIC_ WERROR reg_generate_diff(struct registry_context *ctx1, int i; WERROR error; - for(i = HKEY_FIRST; i <= HKEY_LAST; i++) { + for (i = 0; reg_predefined_keys[i].name; i++) { struct registry_key *r1 = NULL, *r2 = NULL; - error = reg_get_predefined_key(ctx1, i, &r1); + + error = reg_get_predefined_key(ctx1, + reg_predefined_keys[i].handle, &r1); if (!W_ERROR_IS_OK(error) && !W_ERROR_EQUAL(error, WERR_BADFILE)) { DEBUG(0, ("Unable to open hive %s for backend 1\n", - reg_get_predef_name(i))); + reg_predefined_keys[i].name)); + continue; } - error = reg_get_predefined_key(ctx2, i, &r2); + error = reg_get_predefined_key(ctx2, + reg_predefined_keys[i].handle, &r2); if (!W_ERROR_IS_OK(error) && !W_ERROR_EQUAL(error, WERR_BADFILE)) { DEBUG(0, ("Unable to open hive %s for backend 2\n", - reg_get_predef_name(i))); - } - - if (r1 == NULL && r2 == NULL) + reg_predefined_keys[i].name)); continue; + } - error = reg_generate_diff_key(r1, r2, reg_get_predef_name(i), - callbacks, callback_data); + error = reg_generate_diff_key(r1, r2, + reg_predefined_keys[i].name, callbacks, + callback_data); if (!W_ERROR_IS_OK(error)) { DEBUG(0, ("Unable to determine diff: %s\n", win_errstr(error))); -- cgit From 9038f2a0fd87075cf2125b1444e2669125bc72ea Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Mon, 15 Sep 2008 21:09:32 +0200 Subject: Torture suite: Fixes the tests to not segfault again SAMBA 4 registry server --- source4/torture/rpc/samba3rpc.c | 13 +++++++++++++ source4/torture/rpc/winreg.c | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/source4/torture/rpc/samba3rpc.c b/source4/torture/rpc/samba3rpc.c index 17342f9b86..7017233cab 100644 --- a/source4/torture/rpc/samba3rpc.c +++ b/source4/torture/rpc/samba3rpc.c @@ -2897,6 +2897,7 @@ static NTSTATUS enumvalues(struct dcerpc_pipe *p, struct policy_handle *handle, r.in.handle = handle; r.in.enum_index = enum_index; name.name = ""; + name.length = 0; name.size = 1024; r.in.name = r.out.name = &name; size = 1024; @@ -2927,6 +2928,7 @@ static NTSTATUS enumkeys(struct dcerpc_pipe *p, struct policy_handle *handle, } class.name = ""; + class.length = 0; class.size = 1024; r.in.handle = handle; @@ -2947,6 +2949,7 @@ static NTSTATUS enumkeys(struct dcerpc_pipe *p, struct policy_handle *handle, } name.name = NULL; + name.length = 0; name.size = 1024; status = dcerpc_winreg_EnumKey(p, tmp_ctx, &r); @@ -2963,6 +2966,8 @@ static NTSTATUS enumkeys(struct dcerpc_pipe *p, struct policy_handle *handle, o.in.parent_handle = handle; o.in.keyname.name = r.out.name->name; + o.in.keyname.name_len = strlen(o.in.keyname.name); + o.in.keyname.name_size = 1024; o.in.unknown = 0; o.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; o.out.handle = &key_handle; @@ -3215,6 +3220,8 @@ static NTSTATUS torture_samba3_createshare(struct smbcli_state *cli, goto fail; } c.in.keyclass.name = ""; + c.in.keyclass.name_len = 0; + c.in.keyclass.name_size = 1024; c.in.options = 0; c.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; c.in.secdesc = NULL; @@ -3272,6 +3279,8 @@ static NTSTATUS torture_samba3_deleteshare(struct torture_context *torture, status = NT_STATUS_NO_MEMORY; goto fail; } + d.in.key.name_len = strlen(d.in.key.name); + d.in.key.name_size = 1024; status = dcerpc_winreg_DeleteKey(p, p, &d); if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(d.out.result)) { d_printf("(%s) OpenKey failed: %s, %s\n", __location__, @@ -3312,6 +3321,8 @@ static NTSTATUS torture_samba3_setconfig(struct smbcli_state *cli, status = NT_STATUS_NO_MEMORY; goto done; } + o.in.keyname.name_len = strlen(o.in.keyname.name); + o.in.keyname.name_size = 1024; o.in.unknown = 0; o.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; o.out.handle = &key_handle; @@ -3331,6 +3342,8 @@ static NTSTATUS torture_samba3_setconfig(struct smbcli_state *cli, s.in.handle = &key_handle; s.in.name.name = parameter; + s.in.name.name_len = strlen(s.in.name.name); + s.in.name.name_size = 1024; s.in.type = type; s.in.data = val.data; s.in.size = val.length; diff --git a/source4/torture/rpc/winreg.c b/source4/torture/rpc/winreg.c index 8b602ef652..eb439bd5f6 100644 --- a/source4/torture/rpc/winreg.c +++ b/source4/torture/rpc/winreg.c @@ -80,6 +80,7 @@ static bool test_NotifyChangeKeyValue(struct dcerpc_pipe *p, { struct winreg_NotifyChangeKeyValue r; + ZERO_STRUCT(r); r.in.handle = handle; r.in.watch_subtree = true; r.in.notify_filter = 0; @@ -109,6 +110,7 @@ static bool test_CreateKey(struct dcerpc_pipe *p, struct torture_context *tctx, struct policy_handle newhandle; enum winreg_CreateAction action_taken = 0; + ZERO_STRUCT(r); r.in.handle = handle; r.out.new_handle = &newhandle; init_winreg_String(&r.in.name, name); @@ -163,6 +165,7 @@ static bool test_CreateKey_sd(struct dcerpc_pipe *p, secbuf.length = sdblob.length-10; secbuf.inherit = 0; + ZERO_STRUCT(r); r.in.handle = handle; r.out.new_handle = newhandle; init_winreg_String(&r.in.name, name); @@ -317,6 +320,7 @@ static bool test_CloseKey(struct dcerpc_pipe *p, struct torture_context *tctx, { struct winreg_CloseKey r; + ZERO_STRUCT(r); r.in.handle = r.out.handle = handle; torture_assert_ntstatus_ok(tctx, dcerpc_winreg_CloseKey(p, tctx, &r), @@ -332,6 +336,7 @@ static bool test_FlushKey(struct dcerpc_pipe *p, struct torture_context *tctx, { struct winreg_FlushKey r; + ZERO_STRUCT(r); r.in.handle = handle; torture_assert_ntstatus_ok(tctx, dcerpc_winreg_FlushKey(p, tctx, &r), @@ -351,6 +356,7 @@ static bool _test_OpenKey(struct dcerpc_pipe *p, struct torture_context *tctx, { struct winreg_OpenKey r; + ZERO_STRUCT(r); r.in.parent_handle = hive_handle; init_winreg_String(&r.in.keyname, keyname); r.in.unknown = 0x00000000; @@ -384,6 +390,7 @@ static bool test_Cleanup(struct dcerpc_pipe *p, struct torture_context *tctx, { struct winreg_DeleteKey r; + ZERO_STRUCT(r); r.in.handle = handle; init_winreg_String(&r.in.key, key); @@ -1433,8 +1440,10 @@ static bool test_EnumKey(struct dcerpc_pipe *p, struct torture_context *tctx, NTTIME t = 0; class.name = ""; + class.length = 0; class.size = 1024; + ZERO_STRUCT(r); r.in.handle = handle; r.in.enum_index = 0; r.in.name = &name; @@ -1444,6 +1453,7 @@ static bool test_EnumKey(struct dcerpc_pipe *p, struct torture_context *tctx, do { name.name = NULL; + name.length = 0; name.size = 1024; status = dcerpc_winreg_EnumKey(p, tctx, &r); @@ -1486,6 +1496,7 @@ static bool test_QueryMultipleValues(struct dcerpc_pipe *p, NTSTATUS status; uint32_t bufsize=0; + ZERO_STRUCT(r); r.in.key_handle = handle; r.in.values = r.out.values = talloc_array(tctx, struct QueryMultipleValue, 1); r.in.values[0].name = talloc(tctx, struct winreg_String); @@ -1527,6 +1538,7 @@ static bool test_QueryValue(struct dcerpc_pipe *p, uint32_t offered = 0xfff; uint32_t zero = 0; + ZERO_STRUCT(r); r.in.handle = handle; r.in.data = NULL; r.in.value_name.name = valuename; @@ -1556,8 +1568,10 @@ static bool test_EnumValue(struct dcerpc_pipe *p, struct torture_context *tctx, struct winreg_StringBuf name; name.name = ""; + name.length = 0; name.size = 1024; + ZERO_STRUCT(r); r.in.handle = handle; r.in.enum_index = 0; r.in.name = &name; @@ -1594,6 +1608,7 @@ static bool test_AbortSystemShutdown(struct dcerpc_pipe *p, struct winreg_AbortSystemShutdown r; uint16_t server = 0x0; + ZERO_STRUCT(r); r.in.server = &server; torture_assert_ntstatus_ok(tctx, @@ -1612,6 +1627,7 @@ static bool test_InitiateSystemShutdown(struct torture_context *tctx, struct winreg_InitiateSystemShutdown r; uint16_t hostname = 0x0; + ZERO_STRUCT(r); r.in.hostname = &hostname; r.in.message = talloc(tctx, struct lsa_StringLarge); init_lsa_StringLarge(r.in.message, "spottyfood"); @@ -1636,6 +1652,7 @@ static bool test_InitiateSystemShutdownEx(struct torture_context *tctx, struct winreg_InitiateSystemShutdownEx r; uint16_t hostname = 0x0; + ZERO_STRUCT(r); r.in.hostname = &hostname; r.in.message = talloc(tctx, struct lsa_StringLarge); init_lsa_StringLarge(r.in.message, "spottyfood"); @@ -1694,6 +1711,7 @@ static bool test_Open_Security(struct torture_context *tctx, winreg_open_fn open_fn = userdata; + ZERO_STRUCT(r); r.in.system_name = 0; r.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; r.out.handle = &handle; @@ -1767,6 +1785,7 @@ static bool test_Open(struct torture_context *tctx, struct dcerpc_pipe *p, winreg_open_fn open_fn = userdata; + ZERO_STRUCT(r); r.in.system_name = 0; r.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; r.out.handle = &handle; -- cgit From 5c3e76eddd89d9af18bf2a00e7ee6021ab90b234 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Fri, 19 Sep 2008 12:57:26 +0200 Subject: Revert "Registry tool "regtree": Removing an error message" This reverts commit f37a57fa366e2b0d77f9c1bd232d42a0f2cceb52. --- source4/lib/registry/tools/regtree.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/source4/lib/registry/tools/regtree.c b/source4/lib/registry/tools/regtree.c index 2175f9c9d3..6d55a3eb84 100644 --- a/source4/lib/registry/tools/regtree.c +++ b/source4/lib/registry/tools/regtree.c @@ -82,6 +82,11 @@ static void print_tree(int level, struct registry_key *p, valuetype, valuedata)); } talloc_free(mem_ctx); + + if(!W_ERROR_EQUAL(error, WERR_NO_MORE_ITEMS)) { + DEBUG(0, ("Error occured while fetching values for '%s': %s\n", + name, win_errstr(error))); + } } mem_ctx = talloc_init("sec_desc"); -- cgit From 4c7203367fb487de616a137d74ad70c67e8781c9 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Fri, 19 Sep 2008 14:35:35 +0200 Subject: Registry client library: Remove two elementar conversion functions --- source4/lib/registry/rpc.c | 30 ++++-------------------------- 1 file changed, 4 insertions(+), 26 deletions(-) diff --git a/source4/lib/registry/rpc.c b/source4/lib/registry/rpc.c index b5918dc4db..caf5318693 100644 --- a/source4/lib/registry/rpc.c +++ b/source4/lib/registry/rpc.c @@ -66,17 +66,6 @@ static void chars_to_winreg_String(TALLOC_CTX *mem_ctx, struct winreg_String winregStr->name_size = winregStr->name_len; } -/* - * Converts a WINREG string into a SAMBA string - */ -static void winreg_String_to_chars(TALLOC_CTX *mem_ctx, const char **str, - struct winreg_String *winregStr) -{ - *str = NULL; - if (winregStr->name != NULL) - *str = talloc_strdup(mem_ctx, winregStr->name); -} - /* * Converts a SAMBA string into a WINREG string buffer */ @@ -92,17 +81,6 @@ static void chars_to_winreg_StringBuf(TALLOC_CTX *mem_ctx, struct winreg_StringB winregStrBuf->size = size; } -/* - * Converts a WINREG string buffer into a SAMBA string - */ -static void winreg_StringBuf_to_chars(TALLOC_CTX *mem_ctx, const char **str, - struct winreg_StringBuf *winregStrBuf) -{ - *str = NULL; - if (winregStrBuf->name != NULL) - *str = talloc_strdup(mem_ctx, winregStrBuf->name); -} - #define openhive(u) static WERROR open_ ## u(struct dcerpc_pipe *p, TALLOC_CTX *mem_ctx, struct policy_handle *hnd) \ { \ struct winreg_Open ## u r; \ @@ -280,7 +258,7 @@ static WERROR rpc_get_value_by_index(TALLOC_CTX *mem_ctx, return ntstatus_to_werror(status); } - winreg_StringBuf_to_chars(mem_ctx, value_name, r.out.name); + *value_name = talloc_strdup(mem_ctx, r.out.name->name); *type = *(r.out.type); *data = data_blob_talloc(mem_ctx, r.out.value, *r.out.length); @@ -368,9 +346,9 @@ static WERROR rpc_get_subkey_by_index(TALLOC_CTX *mem_ctx, } if (name != NULL) - winreg_StringBuf_to_chars(mem_ctx, name, r.out.name); + *name = talloc_strdup(mem_ctx, r.out.name->name); if (keyclass != NULL) - winreg_StringBuf_to_chars(mem_ctx, keyclass, r.out.keyclass); + *keyclass = talloc_strdup(mem_ctx, r.out.keyclass->name); if (last_changed_time != NULL) *last_changed_time = *(r.out.last_changed_time); @@ -443,7 +421,7 @@ static WERROR rpc_query_key(TALLOC_CTX *mem_ctx, const struct registry_key *k) return ntstatus_to_werror(status); } - winreg_String_to_chars(mem_ctx, &mykeydata->classname, r.out.classname); + mykeydata->classname = talloc_strdup(mem_ctx, r.out.classname->name); return r.out.result; } -- cgit From 08953e44db2d3369c51324bb21474830cd24dd4b Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Fri, 19 Sep 2008 15:53:02 +0200 Subject: Registry client: Remove all conversion helper functions --- source4/lib/registry/rpc.c | 61 +++++++++++++--------------------------------- 1 file changed, 17 insertions(+), 44 deletions(-) diff --git a/source4/lib/registry/rpc.c b/source4/lib/registry/rpc.c index caf5318693..6429a390db 100644 --- a/source4/lib/registry/rpc.c +++ b/source4/lib/registry/rpc.c @@ -51,36 +51,6 @@ static struct registry_operations reg_backend_rpc; * This is the RPC backend for the registry library. */ -/* - * Converts a SAMBA string into a WINREG string - */ -static void chars_to_winreg_String(TALLOC_CTX *mem_ctx, struct winreg_String - *winregStr, const char *str) -{ - winregStr->name = NULL; - winregStr->name_len = 0; - if (str != NULL) { - winregStr->name = talloc_strdup(mem_ctx, str); - winregStr->name_len = strlen(str); - } - winregStr->name_size = winregStr->name_len; -} - -/* - * Converts a SAMBA string into a WINREG string buffer - */ -static void chars_to_winreg_StringBuf(TALLOC_CTX *mem_ctx, struct winreg_StringBuf - *winregStrBuf, const char *str, uint16_t size) -{ - winregStrBuf->name = NULL; - winregStrBuf->length = 0; - if (str != NULL) { - winregStrBuf->name = talloc_strdup(mem_ctx, str); - winregStrBuf->length = strlen(str); - } - winregStrBuf->size = size; -} - #define openhive(u) static WERROR open_ ## u(struct dcerpc_pipe *p, TALLOC_CTX *mem_ctx, struct policy_handle *hnd) \ { \ struct winreg_Open ## u r; \ @@ -169,7 +139,7 @@ static WERROR rpc_key_put_rpc_data(TALLOC_CTX *mem_ctx, struct registry_key *k) ZERO_STRUCT(r); r.in.handle = &(((struct rpc_key_data *)k->hive->root->backend_data)->pol); - chars_to_winreg_String(mem_ctx, &r.in.keyname, k->path); + r.in.keyname.name = k->path; r.in.unknown = 0x00000000; r.in.access_mask = 0x02000000; r.out.handle = &mykeydata->pol; @@ -199,7 +169,7 @@ static WERROR rpc_open_key(TALLOC_CTX *mem_ctx, struct registry_key *h, /* Then, open the handle using the hive */ ZERO_STRUCT(r); r.in.parent_handle = &parentkeydata->pol; - chars_to_winreg_String(mem_ctx, &r.in.keyname, name); + r.in.keyname.name = name; r.in.unknown = 0x00000000; r.in.access_mask = 0x02000000; r.out.handle = &mykeydata->pol; @@ -235,7 +205,8 @@ static WERROR rpc_get_value_by_index(TALLOC_CTX *mem_ctx, if(!W_ERROR_IS_OK(error)) return error; } - chars_to_winreg_StringBuf(mem_ctx, &name, "", MAX_NAMESIZE); + name.name = ""; + name.size = MAX_NAMESIZE; ZERO_STRUCT(r); r.in.handle = &mykeydata->pol; @@ -258,7 +229,7 @@ static WERROR rpc_get_value_by_index(TALLOC_CTX *mem_ctx, return ntstatus_to_werror(status); } - *value_name = talloc_strdup(mem_ctx, r.out.name->name); + *value_name = talloc_reference(mem_ctx, r.out.name->name); *type = *(r.out.type); *data = data_blob_talloc(mem_ctx, r.out.value, *r.out.length); @@ -285,7 +256,7 @@ static WERROR rpc_get_value_by_name(TALLOC_CTX *mem_ctx, if(!W_ERROR_IS_OK(error)) return error; } - chars_to_winreg_String(mem_ctx, &name, value_name); + name.name = value_name; ZERO_STRUCT(r); r.in.handle = &mykeydata->pol; @@ -325,8 +296,10 @@ static WERROR rpc_get_subkey_by_index(TALLOC_CTX *mem_ctx, NTTIME change_time = 0; NTSTATUS status; - chars_to_winreg_StringBuf(mem_ctx, &namebuf, " ", MAX_NAMESIZE); - chars_to_winreg_StringBuf(mem_ctx, &classbuf, NULL, 0); + namebuf.name = ""; + namebuf.size = MAX_NAMESIZE; + classbuf.name = NULL; + classbuf.size = 0; ZERO_STRUCT(r); r.in.handle = &mykeydata->pol; @@ -346,9 +319,9 @@ static WERROR rpc_get_subkey_by_index(TALLOC_CTX *mem_ctx, } if (name != NULL) - *name = talloc_strdup(mem_ctx, r.out.name->name); + *name = talloc_reference(mem_ctx, r.out.name->name); if (keyclass != NULL) - *keyclass = talloc_strdup(mem_ctx, r.out.keyclass->name); + *keyclass = talloc_reference(mem_ctx, r.out.keyclass->name); if (last_changed_time != NULL) *last_changed_time = *(r.out.last_changed_time); @@ -369,8 +342,8 @@ static WERROR rpc_add_key(TALLOC_CTX *mem_ctx, ZERO_STRUCT(r); r.in.handle = &parentkd->pol; - chars_to_winreg_String(mem_ctx, &r.in.name, name); - chars_to_winreg_String(mem_ctx, &r.in.keyclass, NULL); + r.in.name.name = name; + r.in.keyclass.name = NULL; r.in.options = 0; r.in.access_mask = 0x02000000; r.in.secdesc = NULL; @@ -399,7 +372,7 @@ static WERROR rpc_query_key(TALLOC_CTX *mem_ctx, const struct registry_key *k) struct winreg_String classname; NTSTATUS status; - chars_to_winreg_String(mem_ctx, &classname, NULL); + classname.name = NULL; ZERO_STRUCT(r); r.in.handle = &mykeydata->pol; @@ -421,7 +394,7 @@ static WERROR rpc_query_key(TALLOC_CTX *mem_ctx, const struct registry_key *k) return ntstatus_to_werror(status); } - mykeydata->classname = talloc_strdup(mem_ctx, r.out.classname->name); + mykeydata->classname = talloc_reference(mem_ctx, r.out.classname->name); return r.out.result; } @@ -435,7 +408,7 @@ static WERROR rpc_del_key(struct registry_key *parent, const char *name) ZERO_STRUCT(r); r.in.handle = &mykeydata->pol; - chars_to_winreg_String(mem_ctx, &r.in.key, name); + r.in.key.name = name; status = dcerpc_winreg_DeleteKey(mykeydata->pipe, mem_ctx, &r); -- cgit From 89b23974d3efa3d8a1e97cf49c2f949d3fa52ffa Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Fri, 19 Sep 2008 16:03:20 +0200 Subject: Torture suite: Revert some changes because they aren't necessary This reverts some changes made by me because they aren't necessary. The "ZERO_STRUCT"'s remain in. --- source4/torture/rpc/samba3rpc.c | 13 ------------- source4/torture/rpc/winreg.c | 3 --- 2 files changed, 16 deletions(-) diff --git a/source4/torture/rpc/samba3rpc.c b/source4/torture/rpc/samba3rpc.c index 7017233cab..17342f9b86 100644 --- a/source4/torture/rpc/samba3rpc.c +++ b/source4/torture/rpc/samba3rpc.c @@ -2897,7 +2897,6 @@ static NTSTATUS enumvalues(struct dcerpc_pipe *p, struct policy_handle *handle, r.in.handle = handle; r.in.enum_index = enum_index; name.name = ""; - name.length = 0; name.size = 1024; r.in.name = r.out.name = &name; size = 1024; @@ -2928,7 +2927,6 @@ static NTSTATUS enumkeys(struct dcerpc_pipe *p, struct policy_handle *handle, } class.name = ""; - class.length = 0; class.size = 1024; r.in.handle = handle; @@ -2949,7 +2947,6 @@ static NTSTATUS enumkeys(struct dcerpc_pipe *p, struct policy_handle *handle, } name.name = NULL; - name.length = 0; name.size = 1024; status = dcerpc_winreg_EnumKey(p, tmp_ctx, &r); @@ -2966,8 +2963,6 @@ static NTSTATUS enumkeys(struct dcerpc_pipe *p, struct policy_handle *handle, o.in.parent_handle = handle; o.in.keyname.name = r.out.name->name; - o.in.keyname.name_len = strlen(o.in.keyname.name); - o.in.keyname.name_size = 1024; o.in.unknown = 0; o.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; o.out.handle = &key_handle; @@ -3220,8 +3215,6 @@ static NTSTATUS torture_samba3_createshare(struct smbcli_state *cli, goto fail; } c.in.keyclass.name = ""; - c.in.keyclass.name_len = 0; - c.in.keyclass.name_size = 1024; c.in.options = 0; c.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; c.in.secdesc = NULL; @@ -3279,8 +3272,6 @@ static NTSTATUS torture_samba3_deleteshare(struct torture_context *torture, status = NT_STATUS_NO_MEMORY; goto fail; } - d.in.key.name_len = strlen(d.in.key.name); - d.in.key.name_size = 1024; status = dcerpc_winreg_DeleteKey(p, p, &d); if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(d.out.result)) { d_printf("(%s) OpenKey failed: %s, %s\n", __location__, @@ -3321,8 +3312,6 @@ static NTSTATUS torture_samba3_setconfig(struct smbcli_state *cli, status = NT_STATUS_NO_MEMORY; goto done; } - o.in.keyname.name_len = strlen(o.in.keyname.name); - o.in.keyname.name_size = 1024; o.in.unknown = 0; o.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; o.out.handle = &key_handle; @@ -3342,8 +3331,6 @@ static NTSTATUS torture_samba3_setconfig(struct smbcli_state *cli, s.in.handle = &key_handle; s.in.name.name = parameter; - s.in.name.name_len = strlen(s.in.name.name); - s.in.name.name_size = 1024; s.in.type = type; s.in.data = val.data; s.in.size = val.length; diff --git a/source4/torture/rpc/winreg.c b/source4/torture/rpc/winreg.c index eb439bd5f6..898813f807 100644 --- a/source4/torture/rpc/winreg.c +++ b/source4/torture/rpc/winreg.c @@ -1440,7 +1440,6 @@ static bool test_EnumKey(struct dcerpc_pipe *p, struct torture_context *tctx, NTTIME t = 0; class.name = ""; - class.length = 0; class.size = 1024; ZERO_STRUCT(r); @@ -1453,7 +1452,6 @@ static bool test_EnumKey(struct dcerpc_pipe *p, struct torture_context *tctx, do { name.name = NULL; - name.length = 0; name.size = 1024; status = dcerpc_winreg_EnumKey(p, tctx, &r); @@ -1568,7 +1566,6 @@ static bool test_EnumValue(struct dcerpc_pipe *p, struct torture_context *tctx, struct winreg_StringBuf name; name.name = ""; - name.length = 0; name.size = 1024; ZERO_STRUCT(r); -- cgit From bc794246df473b2e1a12694671afd51da14af5ad Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 23:57:59 +0200 Subject: Fix merged build. --- source3/samba4.mk | 5 ++--- source4/Makefile | 1 + source4/lib/com/config.mk | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/source3/samba4.mk b/source3/samba4.mk index 294eef8b8f..2646b12a0d 100644 --- a/source3/samba4.mk +++ b/source3/samba4.mk @@ -7,7 +7,7 @@ PARTLINK = $(PROG_LD) -r MDLD = $(SHLD) MDLD_FLAGS = $(LDSHFLAGS) -samba4srcdir = $(call abspath,$(srcdir)/../source4) +samba4srcdir = $(srcdir)/../source4 # Flags used for the samba 4 files # $(srcdir)/include is required for config.h @@ -83,7 +83,6 @@ libcmdlinesrcdir := $(samba4srcdir)/lib/cmdline poptsrcdir := $(samba4srcdir)/../lib/popt socketwrappersrcdir := $(samba4srcdir)/../lib/socket_wrapper nsswrappersrcdir := $(samba4srcdir)/../lib/nss_wrapper -appwebsrcdir := $(samba4srcdir)/lib/appweb libstreamsrcdir := $(samba4srcdir)/lib/stream libutilsrcdir := $(samba4srcdir)/lib/util libtdrsrcdir := $(samba4srcdir)/lib/tdr @@ -108,7 +107,6 @@ ntvfssrcdir := $(samba4srcdir)/ntvfs ntptrsrcdir := $(samba4srcdir)/ntptr clientsrcdir := $(samba4srcdir)/client libclisrcdir := $(samba4srcdir)/libcli -ejsscriptsrcdir := $(samba4srcdir)/scripting/ejs pyscriptsrcdir := $(samba4srcdir)/scripting/python kdcsrcdir := $(samba4srcdir)/kdc smbreadlinesrcdir := $(samba4srcdir)/lib/smbreadline @@ -116,6 +114,7 @@ ntp_signdsrcdir := $(samba4srcdir)/ntp_signd tdbsrcdir := $(samba4srcdir)/../lib/tdb ldbsrcdir := $(samba4srcdir)/lib/ldb tallocsrcdir := $(samba4srcdir)/../lib/talloc +comsrcdir := $(samba4srcdir)/lib/com override ASN1C = bin/asn1_compile4 override ET_COMPILER = bin/compile_et4 include samba4-data.mk diff --git a/source4/Makefile b/source4/Makefile index bc470742c6..2a267c3e7b 100644 --- a/source4/Makefile +++ b/source4/Makefile @@ -102,6 +102,7 @@ kdcsrcdir := kdc ntp_signdsrcdir := ntp_signd wmisrcdir := lib/wmi tallocsrcdir := ../lib/talloc +comsrcdir := $(srcdir)/lib/com include data.mk diff --git a/source4/lib/com/config.mk b/source4/lib/com/config.mk index c5c5a35003..73836ef5f8 100644 --- a/source4/lib/com/config.mk +++ b/source4/lib/com/config.mk @@ -1,22 +1,22 @@ [SUBSYSTEM::COM] PRIVATE_DEPENDENCIES = LIBSAMBA-UTIL LIBSAMBA-HOSTCONFIG LIBEVENTS LIBNDR -COM_OBJ_FILES = $(addprefix lib/com/, tables.o rot.o main.o) +COM_OBJ_FILES = $(addprefix $(comsrcdir)/, tables.o rot.o main.o) [SUBSYSTEM::DCOM] PUBLIC_DEPENDENCIES = COM DCOM_PROXY_DCOM RPC_NDR_REMACT \ RPC_NDR_OXIDRESOLVER -DCOM_OBJ_FILES = $(addprefix lib/com/dcom/, main.o tables.o) +DCOM_OBJ_FILES = $(addprefix $(comsrcdir)/dcom/, main.o tables.o) [MODULE::com_simple] SUBSYSTEM = COM INIT_FUNCTION = com_simple_init -com_simple_OBJ_FILES = lib/com/classes/simple.o +com_simple_OBJ_FILES = $(comsrcdir)/classes/simple.o [PYTHON::pycom] LIBRARY_REALNAME = samba/com.$(SHLIBEXT) PRIVATE_DEPENDENCIES = COM -pycom_OBJ_FILES = lib/com/pycom.o +pycom_OBJ_FILES = $(comsrcdir)/pycom.o -- cgit From 05525071e0af67b970c0d348a621bc276542f092 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Sun, 21 Sep 2008 23:59:58 +0200 Subject: libreplace: move main() out of testsuite.c metze --- lib/replace/Makefile.in | 2 +- lib/replace/test/main.c | 37 +++++++++++++++++++++++++++++++++++++ lib/replace/test/testsuite.c | 11 ----------- 3 files changed, 38 insertions(+), 12 deletions(-) create mode 100644 lib/replace/test/main.c diff --git a/lib/replace/Makefile.in b/lib/replace/Makefile.in index c889a0e457..65f8125efd 100644 --- a/lib/replace/Makefile.in +++ b/lib/replace/Makefile.in @@ -47,7 +47,7 @@ test: all installcheck: install test -TEST_OBJS = test/testsuite.o test/os2_delete.o test/strptime.o test/getifaddrs.o +TEST_OBJS = test/main.o test/testsuite.o test/os2_delete.o test/strptime.o test/getifaddrs.o testsuite: libreplace.a $(TEST_OBJS) $(CC) -o testsuite $(TEST_OBJS) -L. -lreplace $(LDFLAGS) $(LIBS) diff --git a/lib/replace/test/main.c b/lib/replace/test/main.c new file mode 100644 index 0000000000..9bd12840a5 --- /dev/null +++ b/lib/replace/test/main.c @@ -0,0 +1,37 @@ +/* + Unix SMB/CIFS implementation. + + libreplace tests + + Copyright (C) Jelmer Vernooij 2006 + + ** NOTE! The following LGPL license applies to the talloc + ** library. This does NOT imply that all of Samba is released + ** under the LGPL + + 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, see . +*/ + +#include "replace.h" + +struct torture_context; +bool torture_local_replace(struct torture_context *ctx); + +int main(void) +{ + bool ret = torture_local_replace(NULL); + if (ret) + return 0; + return -1; +} diff --git a/lib/replace/test/testsuite.c b/lib/replace/test/testsuite.c index dcb05fbbf4..7929f11add 100644 --- a/lib/replace/test/testsuite.c +++ b/lib/replace/test/testsuite.c @@ -1068,14 +1068,3 @@ bool torture_local_replace(struct torture_context *ctx) return ret; } - -#if _SAMBA_BUILD_>3 -#else -int main(void) -{ - bool ret = torture_local_replace(NULL); - if (ret) - return 0; - return -1; -} -#endif -- cgit From 2c7cbb6b1d54c0463fd788002190ee673179f7c1 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Sun, 21 Sep 2008 23:46:10 +0200 Subject: s3: link libreplace/test/main.c into replacetort metze --- source3/Makefile.in | 1 + 1 file changed, 1 insertion(+) diff --git a/source3/Makefile.in b/source3/Makefile.in index 2300e4a20c..2ae7e15bf4 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -953,6 +953,7 @@ REPLACETORT_OBJ = @libreplacedir@/test/testsuite.o \ @libreplacedir@/test/getifaddrs.o \ @libreplacedir@/test/os2_delete.o \ @libreplacedir@/test/strptime.o \ + @libreplacedir@/test/main.o \ $(LIBREPLACE_OBJ) NDRDUMP_OBJ = librpc/tools/ndrdump.o \ -- cgit From 2019a98e4603ad5e201c9ed297baafc3373c1fba Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Mon, 22 Sep 2008 00:20:39 +0200 Subject: lib/talloc: move main() out of testsuite.c metze --- lib/talloc/talloc.mk | 6 +++--- lib/talloc/testsuite.c | 10 ---------- lib/talloc/testsuite_main.c | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 13 deletions(-) create mode 100644 lib/talloc/testsuite_main.c diff --git a/lib/talloc/talloc.mk b/lib/talloc/talloc.mk index 23331b6365..f183cd57ef 100644 --- a/lib/talloc/talloc.mk +++ b/lib/talloc/talloc.mk @@ -5,8 +5,8 @@ TALLOC_SONAME = libtalloc.$(SHLIBEXT).1 all:: libtalloc.a $(TALLOC_SOLIB) testsuite -testsuite:: $(LIBOBJ) testsuite.o - $(CC) $(CFLAGS) -o testsuite testsuite.o $(LIBOBJ) $(LIBS) +testsuite:: $(LIBOBJ) testsuite.o testsuite_main.o + $(CC) $(CFLAGS) -o testsuite testsuite.o testsuite_main.o $(LIBOBJ) $(LIBS) libtalloc.a: $(LIBOBJ) ar -rv $@ $(LIBOBJ) @@ -28,7 +28,7 @@ install:: all doc:: talloc.3 talloc.3.html clean:: - rm -f *~ $(LIBOBJ) $(TALLOC_SOLIB) libtalloc.a testsuite testsuite.o *.gc?? talloc.3 talloc.3.html + rm -f *~ $(LIBOBJ) $(TALLOC_SOLIB) libtalloc.a testsuite testsuite.o testsuite_main.o *.gc?? talloc.3 talloc.3.html test:: testsuite ./testsuite diff --git a/lib/talloc/testsuite.c b/lib/talloc/testsuite.c index 3f06eee566..3d490ddf49 100644 --- a/lib/talloc/testsuite.c +++ b/lib/talloc/testsuite.c @@ -1140,13 +1140,3 @@ bool torture_local_talloc(struct torture_context *tctx) return ret; } - -#if _SAMBA_BUILD_ < 4 -int main(void) -{ - bool ret = torture_local_talloc(NULL); - if (!ret) - return -1; - return 0; -} -#endif diff --git a/lib/talloc/testsuite_main.c b/lib/talloc/testsuite_main.c new file mode 100644 index 0000000000..1b51333278 --- /dev/null +++ b/lib/talloc/testsuite_main.c @@ -0,0 +1,37 @@ +/* + Unix SMB/CIFS implementation. + + local testing of talloc routines. + + Copyright (C) Andrew Tridgell 2004 + + ** NOTE! The following LGPL license applies to the talloc + ** library. This does NOT imply that all of Samba is released + ** under the LGPL + + 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, see . +*/ + +#include "replace.h" + +struct torture_context; +bool torture_local_talloc(struct torture_context *tctx); + +int main(void) +{ + bool ret = torture_local_talloc(NULL); + if (!ret) + return -1; + return 0; +} -- cgit From b7e2c74cef708dfaf7a22de8d68382b9a5f2cf57 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Mon, 22 Sep 2008 00:21:26 +0200 Subject: s3: link @tallocdir@/testsuite_main.o into talloctort metze --- source3/Makefile.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source3/Makefile.in b/source3/Makefile.in index 2ae7e15bf4..8304981a1f 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -946,8 +946,8 @@ SHARESEC_OBJ = $(SHARESEC_OBJ0) $(PARAM_OBJ) $(LIB_NONSMBD_OBJ) \ $(LIBSAMBA_OBJ) \ $(POPT_LIB_OBJ) -TALLOCTORT_OBJ = @tallocdir@/testsuite.o $(PARAM_OBJ) $(LIB_NONSMBD_OBJ) \ - $(LIBSAMBA_OBJ) +TALLOCTORT_OBJ = @tallocdir@/testsuite.o @tallocdir@/testsuite_main.o \ + $(PARAM_OBJ) $(LIB_NONSMBD_OBJ) $(LIBSAMBA_OBJ) REPLACETORT_OBJ = @libreplacedir@/test/testsuite.o \ @libreplacedir@/test/getifaddrs.o \ -- cgit From bee2b6c3a3890949bd87e1e4b8c6de010c808f4d Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Mon, 22 Sep 2008 03:57:31 +0200 Subject: process incoming connections and fork a samba3 in inetd mode --- source4/smb_server/config.mk | 8 ++ source4/smb_server/smb_samba3.c | 174 ++++++++++++++++++++++++++++++++++++++++ source4/smbd/server.c | 1 + 3 files changed, 183 insertions(+) create mode 100644 source4/smb_server/smb_samba3.c diff --git a/source4/smb_server/config.mk b/source4/smb_server/config.mk index e11968a100..d1ec6d49e8 100644 --- a/source4/smb_server/config.mk +++ b/source4/smb_server/config.mk @@ -9,6 +9,14 @@ SERVICE_SMB_OBJ_FILES = $(smb_serversrcdir)/smb_server.o $(eval $(call proto_header_template,$(smb_serversrcdir)/service_smb_proto.h,$(SERVICE_SMB_OBJ_FILES:.o=.c))) +# samba3 SMB server subsystem +# +[MODULE::SERVICE_SAMBA3_SMB] +INIT_FUNCTION = server_service_samba3_smb_init +SUBSYSTEM = smbd + +SERVICE_SAMBA3_SMB_OBJ_FILES = $(smb_serversrcdir)/smb_samba3.o + ####################### # Start SUBSYSTEM SMB [SUBSYSTEM::SMB_SERVER] diff --git a/source4/smb_server/smb_samba3.c b/source4/smb_server/smb_samba3.c new file mode 100644 index 0000000000..7b3229892f --- /dev/null +++ b/source4/smb_server/smb_samba3.c @@ -0,0 +1,174 @@ +/* + Unix SMB/CIFS implementation. + + process incoming connections and fork a samba3 in inetd mode + + 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 . +*/ + +#include "includes.h" +#include "smbd/service_task.h" +#include "smbd/service_stream.h" +#include "smbd/service.h" +#include "lib/messaging/irpc.h" +#include "lib/stream/packet.h" +#include "lib/socket/socket.h" +#include "libcli/smb2/smb2.h" +#include "smb_server/smb2/smb2_server.h" +#include "system/network.h" +#include "lib/socket/netif.h" +#include "param/share.h" +#include "dsdb/samdb/samdb.h" +#include "param/param.h" +#include "dynconfig/dynconfig.h" +#include "smbd/process_model.h" + +/* + initialise a server_context from a open socket and register a event handler + for reading from that socket +*/ +static void samba3_smb_accept(struct stream_connection *conn) +{ + int i; + int fd = socket_get_fd(conn->socket); + const char *prog; + char *argv[2]; + char *reason; + + close(0); + close(1); + dup2(fd, 0); + dup2(fd, 1); + for (i=2;i<256;i++) { + close(i); + } + + prog = lp_parm_string(conn->lp_ctx, NULL, "samba3", "smbd"); + + if (prog == NULL) { + argv[0] = talloc_asprintf(conn, "%s/%s", dyn_BINDIR, "smbd3"); + } + else { + argv[0] = talloc_strdup(conn, prog); + } + + if (argv[0] == NULL) { + stream_terminate_connection(conn, "out of memory"); + return; + } + argv[1] = NULL; + + execve(argv[0], argv, environ); + + /* + * Should never get here + */ + reason = talloc_asprintf(conn, "Could not execute %s", argv[0]); + if (reason == NULL) { + stream_terminate_connection(conn, "out of memory"); + return; + } + stream_terminate_connection(conn, reason); + talloc_free(reason); +} + +static const struct stream_server_ops samba3_smb_stream_ops = { + .name = "samba3", + .accept_connection = samba3_smb_accept, +}; + +/* + setup a listening socket on all the SMB ports for a particular address +*/ +static NTSTATUS samba3_add_socket(struct event_context *event_context, + struct loadparm_context *lp_ctx, + const struct model_ops *model_ops, + const char *address) +{ + const char **ports = lp_smb_ports(lp_ctx); + int i; + NTSTATUS status; + + for (i=0;ports[i];i++) { + uint16_t port = atoi(ports[i]); + if (port == 0) continue; + status = stream_setup_socket(event_context, lp_ctx, + model_ops, &samba3_smb_stream_ops, + "ip", address, &port, + lp_socket_options(lp_ctx), + NULL); + NT_STATUS_NOT_OK_RETURN(status); + } + + return NT_STATUS_OK; +} + + +/* + open the smb server sockets +*/ +static void samba3_smb_task_init(struct task_server *task) +{ + NTSTATUS status; + const struct model_ops *model_ops; + + model_ops = process_model_startup(task->event_ctx, "standard"); + + if (model_ops == NULL) { + goto failed; + } + + task_server_set_title(task, "task[samba3_smb]"); + + if (lp_interfaces(task->lp_ctx) + && lp_bind_interfaces_only(task->lp_ctx)) { + int num_interfaces; + int i; + struct interface *ifaces; + + load_interfaces(task, lp_interfaces(task->lp_ctx), &ifaces); + + num_interfaces = iface_count(ifaces); + + /* We have been given an interfaces line, and been + told to only bind to those interfaces. Create a + socket per interface and bind to only these. + */ + for(i = 0; i < num_interfaces; i++) { + const char *address = iface_n_ip(ifaces, i); + status = samba3_add_socket(task->event_ctx, + task->lp_ctx, + model_ops, address); + if (!NT_STATUS_IS_OK(status)) goto failed; + } + } else { + /* Just bind to lp_socket_address() (usually 0.0.0.0) */ + status = samba3_add_socket(task->event_ctx, task->lp_ctx, + model_ops, + lp_socket_address(task->lp_ctx)); + if (!NT_STATUS_IS_OK(status)) goto failed; + } + + return; +failed: + task_server_terminate(task, "Failed to startup samba3 smb task"); +} + +/* called at smbd startup - register ourselves as a server service */ +NTSTATUS server_service_samba3_smb_init(void) +{ + return register_server_service("samba3_smb", samba3_smb_task_init); +} diff --git a/source4/smbd/server.c b/source4/smbd/server.c index 5bd5568913..cf25693fbe 100644 --- a/source4/smbd/server.c +++ b/source4/smbd/server.c @@ -199,6 +199,7 @@ static int binary_smbd_main(const char *binary_name, int argc, const char *argv[ extern NTSTATUS server_service_drepl_init(void); extern NTSTATUS server_service_rpc_init(void); extern NTSTATUS server_service_ntp_signd_init(void); + extern NTSTATUS server_service_samba3_smb_init(void); init_module_fn static_init[] = { STATIC_smbd_MODULES }; init_module_fn *shared_init; struct event_context *event_ctx; -- cgit From a99a176707cade1e6cc12c46a6ca689ef9ea1f16 Mon Sep 17 00:00:00 2001 From: Karolin Seeger Date: Mon, 22 Sep 2008 08:53:40 -0700 Subject: create-tarball: Remove trailing/leading whitespaces. Karolin --- release-scripts/create-tarball | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/release-scripts/create-tarball b/release-scripts/create-tarball index 3463f012a5..1ce88941ba 100755 --- a/release-scripts/create-tarball +++ b/release-scripts/create-tarball @@ -38,7 +38,7 @@ function printUsage } ## -## Parse the command line options +## Parse the command line options ## function parseOptions @@ -115,7 +115,7 @@ function buildDocs rsync -av "${OPT_DOCSDIR}"/ docs/ exitOnError $? "Failed top copy docs from ${OPT_DOCSDIR}" - + return 0 fi @@ -163,11 +163,11 @@ function createReleaseTag ## ## Main driver ## -function main +function main { parseOptions "$@" exitOnError $? "Failed to parse options" - + cd $TOPDIR git-checkout ${OPT_BRANCH} -- cgit From cb4d7b48e51fe5bcf538e7b98b5a2392e51cb0b0 Mon Sep 17 00:00:00 2001 From: Karolin Seeger Date: Mon, 22 Sep 2008 08:55:01 -0700 Subject: create-tarball: Don't remove /*. These strings do appear several times. Extend the grep pattern to get the right string only. This avoids the removal of /*! Karolin --- release-scripts/create-tarball | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/release-scripts/create-tarball b/release-scripts/create-tarball index 1ce88941ba..deff6d344c 100755 --- a/release-scripts/create-tarball +++ b/release-scripts/create-tarball @@ -178,8 +178,8 @@ function main exitOnError 1 "Failed to find ${VER_H}!" fi - version=`grep SAMBA_VERSION_OFFICIAL_STRING $VER_H | awk '{print $3}'` - vendor_version=`grep SAMBA_VERSION_VENDOR_SUFFIX $VER_H | awk '{print $3}'` + version=`grep "define SAMBA_VERSION_OFFICIAL_STRING" $VER_H | awk '{print $3}'` + vendor_version=`grep "define SAMBA_VERSION_VENDOR_SUFFIX" $VER_H | awk '{print $3}'` if [ -n "$vendor_version" ]; then version="$version-$vendor_version" fi -- cgit From 31dc3629475a07dcc9900929ce943c274db36250 Mon Sep 17 00:00:00 2001 From: Karolin Seeger Date: Mon, 22 Sep 2008 08:57:59 -0700 Subject: create-tarball: Adapt script to changed directory structure. Karolin --- release-scripts/create-tarball | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/release-scripts/create-tarball b/release-scripts/create-tarball index deff6d344c..04728d835d 100755 --- a/release-scripts/create-tarball +++ b/release-scripts/create-tarball @@ -7,7 +7,7 @@ OPT_TAG="" OPT_KEYID="" TOPDIR="`dirname $0`/.." -VER_H="${TOPDIR}/source/include/version.h" +VER_H="${TOPDIR}/source3/include/version.h" function exitOnError { @@ -173,7 +173,7 @@ function main git-checkout ${OPT_BRANCH} exitOnError $? "Invalid branch name \"${OPT_BRANCH}\"" - (cd source && ./script/mkversion.sh) + (cd source3 && ./script/mkversion.sh) if [ ! -f $VER_H ]; then exitOnError 1 "Failed to find ${VER_H}!" fi @@ -198,7 +198,7 @@ function main buildDocs exitOnError $? "Failed to build documentation" - ( cd source && ./autogen.sh ) + ( cd source3 && ./autogen.sh ) cd .. tar cf samba-${version}.tar --exclude=.git* --exclude=CVS --exclude=.svn samba-${version} -- cgit From 1d92b2211cc507dd62526f564ec7f75a07110e00 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Mon, 22 Sep 2008 18:15:24 +0200 Subject: s4: allways initialize the process model before it's used metze --- source4/kdc/kdc.c | 2 +- source4/ldap_server/ldap_server.c | 2 +- source4/ntp_signd/ntp_signd.c | 2 +- source4/smbd/process_model.c | 4 +++- source4/smbd/process_model.h | 1 - source4/web_server/web_server.c | 2 +- source4/winbind/wb_server.c | 2 +- source4/wrepl_server/wrepl_in_connection.c | 4 ++-- 8 files changed, 10 insertions(+), 9 deletions(-) diff --git a/source4/kdc/kdc.c b/source4/kdc/kdc.c index b7009b030f..307c39a43c 100644 --- a/source4/kdc/kdc.c +++ b/source4/kdc/kdc.c @@ -484,7 +484,7 @@ static NTSTATUS kdc_add_socket(struct kdc_server *kdc, const char *address, /* within the kdc task we want to be a single process, so ask for the single process model ops and pass these to the stream_setup_socket() call. */ - model_ops = process_model_byname("single"); + model_ops = process_model_startup(kdc->task->event_ctx, "single"); if (!model_ops) { DEBUG(0,("Can't find 'single' process model_ops\n")); talloc_free(kdc_socket); diff --git a/source4/ldap_server/ldap_server.c b/source4/ldap_server/ldap_server.c index 39a55f4420..57a63a8516 100644 --- a/source4/ldap_server/ldap_server.c +++ b/source4/ldap_server/ldap_server.c @@ -529,7 +529,7 @@ static void ldapsrv_task_init(struct task_server *task) task_server_set_title(task, "task[ldapsrv]"); /* run the ldap server as a single process */ - model_ops = process_model_byname("single"); + model_ops = process_model_startup(task->event_ctx, "single"); if (!model_ops) goto failed; ldap_service = talloc_zero(task, struct ldapsrv_service); diff --git a/source4/ntp_signd/ntp_signd.c b/source4/ntp_signd/ntp_signd.c index 546743e4e6..8bcf258e5e 100644 --- a/source4/ntp_signd/ntp_signd.c +++ b/source4/ntp_signd/ntp_signd.c @@ -349,7 +349,7 @@ static void ntp_signd_task_init(struct task_server *task) /* within the ntp_signd task we want to be a single process, so ask for the single process model ops and pass these to the stream_setup_socket() call. */ - model_ops = process_model_byname("single"); + model_ops = process_model_startup(task->event_ctx, "single"); if (!model_ops) { DEBUG(0,("Can't find 'single' process model_ops\n")); return; diff --git a/source4/smbd/process_model.c b/source4/smbd/process_model.c index 704e6cc7a2..d99d517d9f 100644 --- a/source4/smbd/process_model.c +++ b/source4/smbd/process_model.c @@ -22,6 +22,8 @@ #include "smbd/process_model.h" #include "param/param.h" +static const struct model_ops *process_model_byname(const char *name); + /* setup the events for the chosen process model */ @@ -99,7 +101,7 @@ _PUBLIC_ NTSTATUS process_model_init(struct loadparm_context *lp_ctx) /* return the operations structure for a named backend of the specified type */ -_PUBLIC_ const struct model_ops *process_model_byname(const char *name) +static const struct model_ops *process_model_byname(const char *name) { int i; diff --git a/source4/smbd/process_model.h b/source4/smbd/process_model.h index b545212091..a9b33a4725 100644 --- a/source4/smbd/process_model.h +++ b/source4/smbd/process_model.h @@ -78,7 +78,6 @@ struct process_model_critical_sizes { extern const struct model_ops single_ops; const struct model_ops *process_model_startup(struct event_context *ev, const char *model); -const struct model_ops *process_model_byname(const char *name); NTSTATUS register_process_model(const void *_ops); NTSTATUS process_model_init(struct loadparm_context *lp_ctx); diff --git a/source4/web_server/web_server.c b/source4/web_server/web_server.c index 1ed37f657b..d741992770 100644 --- a/source4/web_server/web_server.c +++ b/source4/web_server/web_server.c @@ -307,7 +307,7 @@ static void websrv_task_init(struct task_server *task) task_server_set_title(task, "task[websrv]"); /* run the web server as a single process */ - model_ops = process_model_byname("single"); + model_ops = process_model_startup(task->event_ctx, "single"); if (!model_ops) goto failed; if (lp_interfaces(task->lp_ctx) && lp_bind_interfaces_only(task->lp_ctx)) { diff --git a/source4/winbind/wb_server.c b/source4/winbind/wb_server.c index d56a82ea18..638fac00a1 100644 --- a/source4/winbind/wb_server.c +++ b/source4/winbind/wb_server.c @@ -122,7 +122,7 @@ static void winbind_task_init(struct task_server *task) /* within the winbind task we want to be a single process, so ask for the single process model ops and pass these to the stream_setup_socket() call. */ - model_ops = process_model_byname("single"); + model_ops = process_model_startup(task->event_ctx, "single"); if (!model_ops) { task_server_terminate(task, "Can't find 'single' process model_ops"); diff --git a/source4/wrepl_server/wrepl_in_connection.c b/source4/wrepl_server/wrepl_in_connection.c index 25227481b8..ecc265e590 100644 --- a/source4/wrepl_server/wrepl_in_connection.c +++ b/source4/wrepl_server/wrepl_in_connection.c @@ -218,7 +218,7 @@ NTSTATUS wreplsrv_in_connection_merge(struct wreplsrv_partner *partner, /* within the wrepl task we want to be a single process, so ask for the single process model ops and pass these to the stream_setup_socket() call. */ - model_ops = process_model_byname("single"); + model_ops = process_model_startup(service->task->event_ctx, "single"); if (!model_ops) { DEBUG(0,("Can't find 'single' process model_ops")); return NT_STATUS_INTERNAL_ERROR; @@ -273,7 +273,7 @@ NTSTATUS wreplsrv_setup_sockets(struct wreplsrv_service *service, struct loadpar /* within the wrepl task we want to be a single process, so ask for the single process model ops and pass these to the stream_setup_socket() call. */ - model_ops = process_model_byname("single"); + model_ops = process_model_startup(task->event_ctx, "single"); if (!model_ops) { DEBUG(0,("Can't find 'single' process model_ops")); return NT_STATUS_INTERNAL_ERROR; -- cgit From ba58d17e6981dcf6775c1706ff21afa6c5849ede Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Mon, 22 Sep 2008 19:31:44 +0200 Subject: netapi: fix case statement in example NetUserSetModals code. Guenther --- source3/lib/netapi/examples/user/user_modalsset.c | 1 + 1 file changed, 1 insertion(+) diff --git a/source3/lib/netapi/examples/user/user_modalsset.c b/source3/lib/netapi/examples/user/user_modalsset.c index 57e1ef70ea..c6958a9012 100644 --- a/source3/lib/netapi/examples/user/user_modalsset.c +++ b/source3/lib/netapi/examples/user/user_modalsset.c @@ -95,6 +95,7 @@ int main(int argc, const char **argv) case 1: case 2: case 3: + break; case 1001: u1001.usrmod1001_min_passwd_len = 0; buffer = (uint8_t *)&u1001; -- cgit From b47953ea105a04a3d62259f1cbf5aea2f7910173 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Fri, 12 Sep 2008 17:24:37 +0200 Subject: netapi: add NetFile testsuite. Guenther --- source3/lib/netapi/tests/Makefile.in | 2 +- source3/lib/netapi/tests/common.h | 2 + source3/lib/netapi/tests/netapitest.c | 5 ++ source3/lib/netapi/tests/netfile.c | 143 ++++++++++++++++++++++++++++++++++ 4 files changed, 151 insertions(+), 1 deletion(-) create mode 100644 source3/lib/netapi/tests/netfile.c diff --git a/source3/lib/netapi/tests/Makefile.in b/source3/lib/netapi/tests/Makefile.in index 0145753212..659f82c9d8 100644 --- a/source3/lib/netapi/tests/Makefile.in +++ b/source3/lib/netapi/tests/Makefile.in @@ -44,7 +44,7 @@ bin/.dummy: CMDLINE_OBJ = common.o NETAPIBUFFER_OBJ = netapibuffer.o -NETAPITEST_OBJ = netapitest.o netlocalgroup.o netuser.o netgroup.o netdisplay.o netshare.o $(CMDLINE_OBJ) +NETAPITEST_OBJ = netapitest.o netlocalgroup.o netuser.o netgroup.o netdisplay.o netshare.o netfile.o $(CMDLINE_OBJ) bin/netapitest@EXEEXT@: $(BINARY_PREREQS) $(NETAPITEST_OBJ) @echo Linking $@ diff --git a/source3/lib/netapi/tests/common.h b/source3/lib/netapi/tests/common.h index 5a320321ba..9320840909 100644 --- a/source3/lib/netapi/tests/common.h +++ b/source3/lib/netapi/tests/common.h @@ -41,6 +41,8 @@ NET_API_STATUS netapitest_display(struct libnetapi_ctx *ctx, const char *hostname); NET_API_STATUS netapitest_share(struct libnetapi_ctx *ctx, const char *hostname); +NET_API_STATUS netapitest_file(struct libnetapi_ctx *ctx, + const char *hostname); #ifndef ARRAY_SIZE #define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0])) diff --git a/source3/lib/netapi/tests/netapitest.c b/source3/lib/netapi/tests/netapitest.c index 87144020f5..4a38f721d8 100644 --- a/source3/lib/netapi/tests/netapitest.c +++ b/source3/lib/netapi/tests/netapitest.c @@ -84,6 +84,11 @@ int main(int argc, const char **argv) goto out; } + status = netapitest_file(ctx, hostname); + if (status) { + goto out; + } + out: if (status != 0) { printf("testsuite failed with: %s\n", diff --git a/source3/lib/netapi/tests/netfile.c b/source3/lib/netapi/tests/netfile.c new file mode 100644 index 0000000000..36ee8288ee --- /dev/null +++ b/source3/lib/netapi/tests/netfile.c @@ -0,0 +1,143 @@ +/* + * Unix SMB/CIFS implementation. + * NetFile testsuite + * 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 . + */ + +#include +#include +#include +#include +#include + +#include + +#include "common.h" + +static NET_API_STATUS test_netfileenum(const char *hostname, + uint32_t level) +{ + NET_API_STATUS status; + uint32_t entries_read = 0; + uint32_t total_entries = 0; + uint32_t resume_handle = 0; + uint8_t *buffer = NULL; + int i; + + struct FILE_INFO_2 *i2; + struct FILE_INFO_3 *i3; + + printf("testing NetFileEnum level %d\n", level); + + do { + status = NetFileEnum(hostname, + NULL, + NULL, + level, + &buffer, + (uint32_t)-1, + &entries_read, + &total_entries, + &resume_handle); + if (status == 0 || status == ERROR_MORE_DATA) { + switch (level) { + case 2: + i2 = (struct FILE_INFO_2 *)buffer; + break; + case 3: + i3 = (struct FILE_INFO_3 *)buffer; + break; + default: + return -1; + } + + for (i=0; i Date: Tue, 16 Sep 2008 16:04:31 +0200 Subject: netapi: add more fields to USER_INFO_X. Guenther --- source3/librpc/idl/libnetapi.idl | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source3/librpc/idl/libnetapi.idl b/source3/librpc/idl/libnetapi.idl index 039dcf4152..f2f4a16c12 100644 --- a/source3/librpc/idl/libnetapi.idl +++ b/source3/librpc/idl/libnetapi.idl @@ -517,7 +517,9 @@ interface libnetapi uint32 usriX_code_page; string usriX_profile; string usriX_home_dir_drive; + uint32 usriX_user_id; uint32 usriX_primary_group_id; + uint32 usriX_password_expired; } USER_INFO_X; [nopush,nopull] NET_API_STATUS NetUserAdd( -- cgit From 92ebd6afc9a1979d5a08af1f7964032763d8fc5b Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 16 Sep 2008 16:04:43 +0200 Subject: re-run make idl. Guenther --- source3/librpc/gen_ndr/libnetapi.h | 2 ++ source3/librpc/gen_ndr/ndr_libnetapi.c | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/source3/librpc/gen_ndr/libnetapi.h b/source3/librpc/gen_ndr/libnetapi.h index 98da9e12ea..ae7acbf572 100644 --- a/source3/librpc/gen_ndr/libnetapi.h +++ b/source3/librpc/gen_ndr/libnetapi.h @@ -413,7 +413,9 @@ struct USER_INFO_X { uint32_t usriX_code_page; const char * usriX_profile; const char * usriX_home_dir_drive; + uint32_t usriX_user_id; uint32_t usriX_primary_group_id; + uint32_t usriX_password_expired; }; struct GROUP_USERS_INFO_0 { diff --git a/source3/librpc/gen_ndr/ndr_libnetapi.c b/source3/librpc/gen_ndr/ndr_libnetapi.c index a5266827b6..d7bf63e62f 100644 --- a/source3/librpc/gen_ndr/ndr_libnetapi.c +++ b/source3/librpc/gen_ndr/ndr_libnetapi.c @@ -1895,7 +1895,9 @@ _PUBLIC_ enum ndr_err_code ndr_push_USER_INFO_X(struct ndr_push *ndr, int ndr_fl NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->usriX_code_page)); NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->usriX_profile)); NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->usriX_home_dir_drive)); + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->usriX_user_id)); NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->usriX_primary_group_id)); + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->usriX_password_expired)); } if (ndr_flags & NDR_BUFFERS) { if (r->usriX_logon_hours) { @@ -1942,7 +1944,9 @@ _PUBLIC_ enum ndr_err_code ndr_pull_USER_INFO_X(struct ndr_pull *ndr, int ndr_fl NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->usriX_code_page)); NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->usriX_profile)); NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->usriX_home_dir_drive)); + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->usriX_user_id)); NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->usriX_primary_group_id)); + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->usriX_password_expired)); } if (ndr_flags & NDR_BUFFERS) { if (r->usriX_logon_hours) { @@ -1990,7 +1994,9 @@ _PUBLIC_ void ndr_print_USER_INFO_X(struct ndr_print *ndr, const char *name, con ndr_print_uint32(ndr, "usriX_code_page", r->usriX_code_page); ndr_print_string(ndr, "usriX_profile", r->usriX_profile); ndr_print_string(ndr, "usriX_home_dir_drive", r->usriX_home_dir_drive); + ndr_print_uint32(ndr, "usriX_user_id", r->usriX_user_id); ndr_print_uint32(ndr, "usriX_primary_group_id", r->usriX_primary_group_id); + ndr_print_uint32(ndr, "usriX_password_expired", r->usriX_password_expired); ndr->depth--; } -- cgit From cebd9a9013a76073c3035b74175d228116fc7e48 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Mon, 22 Sep 2008 14:23:22 -0700 Subject: This torture test and skipping of the server-side check was bogus. The IDL is declared to force the MessageType to 3 on output, so we instead checked the same thing 255 times... Andrew Bartlett --- source4/kdc/kdc.c | 4 +--- source4/torture/rpc/remote_pac.c | 49 ---------------------------------------- 2 files changed, 1 insertion(+), 52 deletions(-) diff --git a/source4/kdc/kdc.c b/source4/kdc/kdc.c index 307c39a43c..030eb23c10 100644 --- a/source4/kdc/kdc.c +++ b/source4/kdc/kdc.c @@ -584,13 +584,11 @@ static NTSTATUS kdc_check_generic_kerberos(struct irpc_message *msg, return NT_STATUS_INVALID_PARAMETER; } -#if 0 - /* Windows does not check this */ if (pac_validate.MessageType != 3) { /* We don't implement any other message types - such as certificate validation - yet */ return NT_STATUS_INVALID_PARAMETER; } -#endif + if (pac_validate.ChecksumAndSignature.length != (pac_validate.ChecksumLength + pac_validate.SignatureLength) || pac_validate.ChecksumAndSignature.length < pac_validate.ChecksumLength || pac_validate.ChecksumAndSignature.length < pac_validate.SignatureLength ) { diff --git a/source4/torture/rpc/remote_pac.c b/source4/torture/rpc/remote_pac.c index 6419e40014..b32881cc69 100644 --- a/source4/torture/rpc/remote_pac.c +++ b/source4/torture/rpc/remote_pac.c @@ -137,7 +137,6 @@ static bool test_PACVerify(struct torture_context *tctx, status = gensec_session_info(gensec_server_context, &session_info); torture_assert_ntstatus_ok(tctx, status, "gensec_session_info failed"); - pac_wrapped_struct.MessageType = 0x3; pac_wrapped_struct.ChecksumLength = session_info->server_info->pac_srv_sig.signature.length; pac_wrapped_struct.SignatureType = session_info->server_info->pac_kdc_sig.type; pac_wrapped_struct.SignatureLength = session_info->server_info->pac_kdc_sig.signature.length; @@ -207,51 +206,6 @@ static bool test_PACVerify(struct torture_context *tctx, torture_assert(tctx, creds_client_check(creds, &r.out.return_authenticator->cred), "Credential chaining failed"); - /* This will break message type, check that however we still get NT_STATUS_OK */ - for (i=0; i < 256; i++) { - pac_wrapped_struct.MessageType = i; - pac_wrapped_struct.ChecksumLength = session_info->server_info->pac_srv_sig.signature.length; - pac_wrapped_struct.SignatureType = session_info->server_info->pac_kdc_sig.type; - pac_wrapped_struct.SignatureLength = session_info->server_info->pac_kdc_sig.signature.length; - pac_wrapped_struct.ChecksumAndSignature = payload - = data_blob_talloc(tmp_ctx, NULL, - pac_wrapped_struct.ChecksumLength - + pac_wrapped_struct.SignatureLength); - memcpy(&payload.data[0], - session_info->server_info->pac_srv_sig.signature.data, - pac_wrapped_struct.ChecksumLength); - memcpy(&payload.data[pac_wrapped_struct.ChecksumLength], - session_info->server_info->pac_kdc_sig.signature.data, - pac_wrapped_struct.SignatureLength); - - ndr_err = ndr_push_struct_blob(&pac_wrapped, tmp_ctx, lp_iconv_convenience(tctx->lp_ctx), &pac_wrapped_struct, - (ndr_push_flags_fn_t)ndr_push_PAC_Validate); - torture_assert(tctx, NDR_ERR_CODE_IS_SUCCESS(ndr_err), "ndr_push_struct_blob of PACValidate structure failed"); - - torture_assert(tctx, (creds->negotiate_flags & NETLOGON_NEG_ARCFOUR), "not willing to even try a PACValidate without RC4 encryption"); - creds_arcfour_crypt(creds, pac_wrapped.data, pac_wrapped.length); - - generic.length = pac_wrapped.length; - generic.data = pac_wrapped.data; - - ZERO_STRUCT(auth2); - creds_client_authenticator(creds, &auth); - r.in.credential = &auth; - r.in.return_authenticator = &auth2; - r.in.logon_level = NetlogonGenericInformation; - r.in.logon.generic = &generic; - r.in.server_name = talloc_asprintf(tctx, "\\\\%s", dcerpc_server_name(p)); - r.in.computer_name = cli_credentials_get_workstation(credentials); - r.in.validation_level = NetlogonValidationGenericInfo2; - - status = dcerpc_netr_LogonSamLogon(p, tctx, &r); - - torture_assert_ntstatus_ok(tctx, status, "LogonSamLogon failed"); - - torture_assert(tctx, creds_client_check(creds, &r.out.return_authenticator->cred), - "Credential chaining failed"); - } - /* This will break the parsing nicely (even in the crypto wrapping), check we get INVALID_PARAMETER */ generic.length--; @@ -272,7 +226,6 @@ static bool test_PACVerify(struct torture_context *tctx, torture_assert(tctx, creds_client_check(creds, &r.out.return_authenticator->cred), "Credential chaining failed"); - pac_wrapped_struct.MessageType = 0x3; pac_wrapped_struct.ChecksumLength = session_info->server_info->pac_srv_sig.signature.length; pac_wrapped_struct.SignatureType = session_info->server_info->pac_kdc_sig.type; @@ -318,8 +271,6 @@ static bool test_PACVerify(struct torture_context *tctx, torture_assert(tctx, creds_client_check(creds, &r.out.return_authenticator->cred), "Credential chaining failed"); - - pac_wrapped_struct.MessageType = 0x3; pac_wrapped_struct.ChecksumLength = session_info->server_info->pac_srv_sig.signature.length; pac_wrapped_struct.SignatureType = session_info->server_info->pac_kdc_sig.type; pac_wrapped_struct.SignatureLength = session_info->server_info->pac_kdc_sig.signature.length; -- cgit From 7831169af5a909b614c8e34ef505f3565b4e2a0a Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Mon, 22 Sep 2008 15:37:16 -0700 Subject: Test re-setting the challenge after an auth3 in RPC-NETLOGON --- source4/torture/rpc/netlogon.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source4/torture/rpc/netlogon.c b/source4/torture/rpc/netlogon.c index 5ec2c29a20..2522062696 100644 --- a/source4/torture/rpc/netlogon.c +++ b/source4/torture/rpc/netlogon.c @@ -250,6 +250,10 @@ static bool test_SetupCredentials3(struct dcerpc_pipe *p, struct torture_context torture_assert(tctx, creds_client_check(creds, &credentials3), "Credential chaining failed"); torture_comment(tctx, "negotiate_flags=0x%08x\n", negotiate_flags); + + /* Prove that requesting a challenge again won't break it */ + status = dcerpc_netr_ServerReqChallenge(p, tctx, &r); + torture_assert_ntstatus_ok(tctx, status, "ServerReqChallenge"); *creds_out = creds; return true; -- cgit From 7d5fb989ac9942a6f3394853f6930d34ef6adf7b Mon Sep 17 00:00:00 2001 From: "Gerald (Jerry) Carter" Date: Fri, 19 Sep 2008 12:27:15 -0500 Subject: idmap_adex: Add new idmap plugin for support RFC2307 enabled AD forests. The adex idmap/nss_info plugin is an adapation of the Likewise Enterprise plugin with support for OU based cells removed (since the Windows pieces to manage the cells are not available). This plugin supports * The RFC2307 schema for users and groups. * Connections to trusted domains * Global catalog searches * Cross forest trusts * User and group aliases Prerequiste: Add the following attributes to the Partial Attribute Set in global catalog: * uidNumber * uid * gidNumber A basic config using the current trunk code would look like [global] idmap backend = adex idmap uid = 10000 - 19999 idmap gid = 20000 - 29999 idmap config US:backend = adex idmap config US:range = 20000 - 29999 winbind nss info = adex winbind normalize names = yes winbind refresh tickets = yes template homedir = /home/%D/%U template shell = /bin/bash --- source3/Makefile.in | 12 + source3/configure.in | 1 + source3/winbindd/idmap_adex/cell_util.c | 292 ++++++ source3/winbindd/idmap_adex/domain_util.c | 278 ++++++ source3/winbindd/idmap_adex/gc_util.c | 848 +++++++++++++++++ source3/winbindd/idmap_adex/idmap_adex.c | 460 +++++++++ source3/winbindd/idmap_adex/idmap_adex.h | 257 ++++++ source3/winbindd/idmap_adex/likewise_cell.c | 425 +++++++++ source3/winbindd/idmap_adex/provider_unified.c | 1180 ++++++++++++++++++++++++ 9 files changed, 3753 insertions(+) create mode 100644 source3/winbindd/idmap_adex/cell_util.c create mode 100644 source3/winbindd/idmap_adex/domain_util.c create mode 100644 source3/winbindd/idmap_adex/gc_util.c create mode 100644 source3/winbindd/idmap_adex/idmap_adex.c create mode 100644 source3/winbindd/idmap_adex/idmap_adex.h create mode 100644 source3/winbindd/idmap_adex/likewise_cell.c create mode 100644 source3/winbindd/idmap_adex/provider_unified.c diff --git a/source3/Makefile.in b/source3/Makefile.in index 8304981a1f..1ce0ce9067 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -985,6 +985,14 @@ IDMAP_HASH_OBJ = \ winbindd/idmap_hash/idmap_hash.o \ winbindd/idmap_hash/mapfile.o +IDMAP_ADEX_OBJ = \ + winbindd/idmap_adex/idmap_adex.o \ + winbindd/idmap_adex/cell_util.o \ + winbindd/idmap_adex/likewise_cell.o \ + winbindd/idmap_adex/provider_unified.o \ + winbindd/idmap_adex/gc_util.o \ + winbindd/idmap_adex/domain_util.o + WINBINDD_OBJ1 = \ winbindd/winbindd.o \ winbindd/winbindd_user.o \ @@ -2218,6 +2226,10 @@ bin/hash.@SHLIBEXT@: $(BINARY_PREREQS) $(IDMAP_HASH_OBJ) @echo "Building plugin $@" @$(SHLD_MODULE) $(IDMAP_HASH_OBJ) +bin/adex.@SHLIBEXT@: $(BINARY_PREREQS) $(IDMAP_ADEX_OBJ) + @echo "Building plugin $@" + @$(SHLD_MODULE) $(IDMAP_ADEX_OBJ) + bin/tdb2.@SHLIBEXT@: $(BINARY_PREREQS) winbindd/idmap_tdb2.o @echo "Building plugin $@" @$(SHLD_MODULE) winbindd/idmap_tdb2.o diff --git a/source3/configure.in b/source3/configure.in index 640afc47fb..d1000d9a52 100644 --- a/source3/configure.in +++ b/source3/configure.in @@ -6058,6 +6058,7 @@ SMB_MODULE(idmap_nss, winbindd/idmap_nss.o, "bin/nss.$SHLIBEXT", IDMAP) SMB_MODULE(idmap_rid, winbindd/idmap_rid.o, "bin/rid.$SHLIBEXT", IDMAP) SMB_MODULE(idmap_ad, winbindd/idmap_ad.o, "bin/ad.$SHLIBEXT", IDMAP) SMB_MODULE(idmap_hash, \$(IDMAP_HASH_OBJ), "bin/hash.$SHLIBEXT", IDMAP) +SMB_MODULE(idmap_adex, \$(IDMAP_ADEX_OBJ), "bin/adex.$SHLIBEXT", IDMAP) SMB_SUBSYSTEM(IDMAP, winbindd/idmap.o) SMB_MODULE(nss_info_template, winbindd/nss_info_template.o, "bin/template.$SHLIBEXT", NSS_INFO) diff --git a/source3/winbindd/idmap_adex/cell_util.c b/source3/winbindd/idmap_adex/cell_util.c new file mode 100644 index 0000000000..f5c08a0454 --- /dev/null +++ b/source3/winbindd/idmap_adex/cell_util.c @@ -0,0 +1,292 @@ +/* + * idmap_adex: Support for AD Forests + * + * Copyright (C) Gerald (Jerry) Carter 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 + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include "includes.h" +#include "idmap_adex.h" + +#undef DBGC_CLASS +#define DBGC_CLASS DBGC_IDMAP + +/********************************************************************** +**********************************************************************/ + + char *find_attr_string(char **list, size_t num_lines, const char *substr) +{ + int i; + int cmplen = strlen(substr); + + for (i = 0; i < num_lines; i++) { + /* make sure to avoid substring matches like uid + and uidNumber */ + if ((StrnCaseCmp(list[i], substr, cmplen) == 0) && + (list[i][cmplen] == '=')) { + /* Don't return an empty string */ + if (list[i][cmplen + 1] != '\0') + return &(list[i][cmplen + 1]); + + return NULL; + } + } + + return NULL; +} + +/********************************************************************** +**********************************************************************/ + + bool is_object_class(char **list, size_t num_lines, const char *substr) +{ + int i; + + for (i = 0; i < num_lines; i++) { + if (strequal(list[i], substr)) { + return true; + } + } + + return false; +} + +/********************************************************************** + Find out about the cell (e.g. use2307Attrs, etc...) +**********************************************************************/ + + NTSTATUS cell_lookup_settings(struct likewise_cell * cell) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + + /* Parameter check */ + + if (!cell) { + nt_status = NT_STATUS_INVALID_PARAMETER; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* Only supporting Forest-wide, schema based searches */ + + cell_set_flags(cell, LWCELL_FLAG_USE_RFC2307_ATTRS); + cell_set_flags(cell, LWCELL_FLAG_SEARCH_FOREST); + + cell->provider = &ccp_unified; + + nt_status = NT_STATUS_OK; + +done: + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(1,("LWI: Failed to obtain cell settings (%s)\n", + nt_errstr(nt_status))); + } + + return nt_status; +} + + +static NTSTATUS cell_lookup_forest(struct likewise_cell *c) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + struct gc_info *gc = NULL; + + if (!c) { + return NT_STATUS_INVALID_PARAMETER; + } + + if ((gc = TALLOC_ZERO_P(NULL, struct gc_info)) == NULL) { + nt_status = NT_STATUS_NO_MEMORY; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* Query the rootDSE for the forest root naming conect first. + Check that the a GC server for the forest has not already + been added */ + + nt_status = gc_find_forest_root(gc, cell_dns_domain(c)); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + c->forest_name = talloc_strdup(c, gc->forest_name); + BAIL_ON_PTR_ERROR(c->forest_name, nt_status); + +done: + if (gc) { + talloc_free(gc); + } + + return nt_status; +} + +/********************************************************************** +**********************************************************************/ + + NTSTATUS cell_locate_membership(ADS_STRUCT * ads) +{ + ADS_STATUS status; + char *domain_dn = ads_build_dn(lp_realm()); + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + DOM_SID sid; + struct likewise_cell *cell = NULL; + + /* In the Likewise plugin, I had to support the concept of cells + based on the machine's membership in an OU. However, now I'll + just assume our membership in the forest cell */ + + DEBUG(2, ("locate_cell_membership: Located membership " + "in cell \"%s\"\n", domain_dn)); + + if ((cell = cell_new()) == NULL) { + nt_status = NT_STATUS_NO_MEMORY; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + status = ads_domain_sid(ads, &sid); + if (!ADS_ERR_OK(status)) { + DEBUG(3,("locate_cell_membership: Failed to find " + "domain SID for %s\n", domain_dn)); + } + + /* save the SID and search base for our domain */ + + cell_set_dns_domain(cell, lp_realm()); + cell_set_connection(cell, ads); + cell_set_dn(cell, domain_dn); + cell_set_domain_sid(cell, &sid); + + /* Now save our forest root */ + + cell_lookup_forest(cell); + + /* Add the cell to the list */ + + if (!cell_list_add(cell)) { + nt_status = NT_STATUS_INSUFFICIENT_RESOURCES; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* Done! */ + nt_status = NT_STATUS_OK; + +done: + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(0,("LWI: Failed to locate cell membership (%s)\n", + nt_errstr(nt_status))); + } + + SAFE_FREE(domain_dn); + + return nt_status; +} + +/********************************************************************* + ********************************************************************/ + + int min_id_value(void) +{ + int id_val; + + id_val = lp_parm_int(-1, "lwidentity", "min_id_value", MIN_ID_VALUE); + + /* Still don't let it go below 50 */ + + return MAX(50, id_val); +} + +/******************************************************************** + *******************************************************************/ + + char *cell_dn_to_dns(const char *dn) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + char *domain = NULL; + char *dns_name = NULL; + const char *tmp_dn; + char *buffer = NULL; + TALLOC_CTX *frame = talloc_stackframe(); + + if (!dn || !*dn) { + goto done; + } + + tmp_dn = talloc_strdup(frame, dn); + BAIL_ON_PTR_ERROR(tmp_dn, nt_status); + + while (next_token_talloc(frame, &tmp_dn, &buffer, ",")) { + + /* skip everything up the where DC=... begins */ + if (StrnCaseCmp(buffer, "DC=", 3) != 0) + continue; + + if (!domain) { + domain = talloc_strdup(frame, &buffer[3]); + } else { + domain = talloc_asprintf_append(domain, ".%s", + &buffer[3]); + } + BAIL_ON_PTR_ERROR(domain, nt_status); + } + + dns_name = SMB_STRDUP(domain); + BAIL_ON_PTR_ERROR(dns_name, nt_status); + + nt_status = NT_STATUS_OK; + +done: + PRINT_NTSTATUS_ERROR(nt_status, "cell_dn_to_dns", 1); + + talloc_destroy(frame); + + return dns_name; +} + +/********************************************************************* + ********************************************************************/ + + NTSTATUS get_sid_type(ADS_STRUCT *ads, + LDAPMessage *msg, + enum lsa_SidType *type) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + uint32_t atype; + + if (!ads_pull_uint32(ads, msg, "sAMAccountType", &atype)) { + nt_status = NT_STATUS_INVALID_USER_BUFFER; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + switch (atype &0xF0000000) { + case ATYPE_SECURITY_GLOBAL_GROUP: + *type = SID_NAME_DOM_GRP; + break; + case ATYPE_SECURITY_LOCAL_GROUP: + *type = SID_NAME_ALIAS; + break; + case ATYPE_NORMAL_ACCOUNT: + case ATYPE_WORKSTATION_TRUST: + case ATYPE_INTERDOMAIN_TRUST: + *type = SID_NAME_USER; + break; + default: + *type = SID_NAME_USE_NONE; + nt_status = NT_STATUS_INVALID_ACCOUNT_NAME; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + nt_status = NT_STATUS_OK; + +done: + return nt_status; +} diff --git a/source3/winbindd/idmap_adex/domain_util.c b/source3/winbindd/idmap_adex/domain_util.c new file mode 100644 index 0000000000..ab31ccef7a --- /dev/null +++ b/source3/winbindd/idmap_adex/domain_util.c @@ -0,0 +1,278 @@ +/* + * idmap_adex: Domain search interface + * + * Copyright (C) Gerald (Jerry) Carter 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 + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include "includes.h" +#include "idmap_adex.h" + +#undef DBGC_CLASS +#define DBGC_CLASS DBGC_IDMAP + +struct dc_info { + struct dc_info *prev, *next; + char *dns_name; + struct likewise_cell *domain_cell; +}; + +static struct dc_info *_dc_server_list = NULL; + + +/********************************************************************** + *********************************************************************/ + +static struct dc_info *dc_list_head(void) +{ + return _dc_server_list; +} + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS dc_add_domain(const char *domain) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + struct dc_info *dc = NULL; + + /* Check for duplicates */ + + dc = dc_list_head(); + while (dc) { + if (strequal (dc->dns_name, domain)) + break; + dc = dc->next; + } + + if (dc) { + DEBUG(10,("dc_add_domain: %s already in list\n", domain)); + return NT_STATUS_OK; + } + + dc = TALLOC_ZERO_P(NULL, struct dc_info); + BAIL_ON_PTR_ERROR(dc, nt_status); + + dc->dns_name = talloc_strdup(dc, domain); + BAIL_ON_PTR_ERROR(dc->dns_name, nt_status); + + DLIST_ADD_END(_dc_server_list, dc, struct dc_info*); + + nt_status = NT_STATUS_OK; + +done: + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_destroy(dc); + DEBUG(0,("LWI: Failed to add new DC connection for %s (%s)\n", + domain, nt_errstr(nt_status))); + } + + return nt_status; +} + +/********************************************************************** + *********************************************************************/ + +static void dc_server_list_destroy(void) +{ + struct dc_info *dc = dc_list_head(); + + while (dc) { + struct dc_info *p = dc->next; + + cell_destroy(dc->domain_cell); + talloc_destroy(dc); + + dc = p; + } + + return; +} + + +/********************************************************************** + *********************************************************************/ + + NTSTATUS domain_init_list(void) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + struct winbindd_tdc_domain *domains = NULL; + size_t num_domains = 0; + int i; + + if (_dc_server_list != NULL) { + dc_server_list_destroy(); + } + + /* Add our domain */ + + nt_status = dc_add_domain(lp_realm()); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + if (!wcache_tdc_fetch_list(&domains, &num_domains)) { + nt_status = NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* Add all domains with an incoming trust path */ + + for (i=0; idomain_cell, search_base, + scope, expr, attrs, msg); + nt_status = ads_ntstatus(status); + + return nt_status; +} + +/********************************************************************** + *********************************************************************/ + +static struct dc_info *dc_find_domain(const char *dns_domain) +{ + struct dc_info *dc = dc_list_head(); + + if (!dc) + return NULL; + + while (dc) { + if (strequal(dc->dns_name, dns_domain)) { + return dc; + } + + dc = dc->next; + } + + return NULL; +} + +/********************************************************************** + *********************************************************************/ + + NTSTATUS dc_search_domains(struct likewise_cell **cell, + LDAPMessage **msg, + const char *dn, + const DOM_SID *sid) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + TALLOC_CTX *frame = talloc_stackframe(); + char *dns_domain; + const char *attrs[] = { "*", NULL }; + struct dc_info *dc = NULL; + const char *base = NULL; + + if (!dn || !*dn) { + nt_status = NT_STATUS_INVALID_PARAMETER; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + dns_domain = cell_dn_to_dns(dn); + BAIL_ON_PTR_ERROR(dns_domain, nt_status); + + if ((dc = dc_find_domain(dns_domain)) == NULL) { + nt_status = NT_STATUS_TRUSTED_DOMAIN_FAILURE; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* Reparse the cell settings for the domain if necessary */ + + if (!dc->domain_cell) { + char *base_dn; + + base_dn = ads_build_dn(dc->dns_name); + BAIL_ON_PTR_ERROR(base_dn, nt_status); + + nt_status = cell_connect_dn(&dc->domain_cell, base_dn); + SAFE_FREE(base_dn); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + nt_status = cell_lookup_settings(dc->domain_cell); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + /* By definition this is already part of a larger + forest-wide search scope */ + + cell_set_flags(dc->domain_cell, LWCELL_FLAG_SEARCH_FOREST); + } + + /* Check whether we are operating in non-schema or RFC2307 + mode */ + + if (cell_flags(dc->domain_cell) & LWCELL_FLAG_USE_RFC2307_ATTRS) { + nt_status = dc_do_search(dc, dn, LDAP_SCOPE_BASE, + "(objectclass=*)", attrs, msg); + } else { + const char *sid_str = NULL; + char *filter = NULL; + + sid_str = sid_string_talloc(frame, sid); + BAIL_ON_PTR_ERROR(sid_str, nt_status); + + filter = talloc_asprintf(frame, "(keywords=backLink=%s)", + sid_str); + BAIL_ON_PTR_ERROR(filter, nt_status); + + base = cell_search_base(dc->domain_cell); + BAIL_ON_PTR_ERROR(base, nt_status); + + nt_status = dc_do_search(dc, base, LDAP_SCOPE_SUBTREE, + filter, attrs, msg); + } + BAIL_ON_NTSTATUS_ERROR(nt_status); + + *cell = dc->domain_cell; + +done: + talloc_destroy(CONST_DISCARD(char*, base)); + talloc_destroy(frame); + + return nt_status; +} diff --git a/source3/winbindd/idmap_adex/gc_util.c b/source3/winbindd/idmap_adex/gc_util.c new file mode 100644 index 0000000000..87dd3c058d --- /dev/null +++ b/source3/winbindd/idmap_adex/gc_util.c @@ -0,0 +1,848 @@ +/* + * idmap_adex: Global Catalog search interface + * + * Copyright (C) Gerald (Jerry) Carter 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 + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include "includes.h" +#include "idmap_adex.h" + +#undef DBGC_CLASS +#define DBGC_CLASS DBGC_IDMAP + +static struct gc_info *_gc_server_list = NULL; + + +/********************************************************************** + *********************************************************************/ + +static struct gc_info *gc_list_head(void) +{ + return _gc_server_list; +} + +/********************************************************************** + Checks if either of the domains is a subdomain of the other + *********************************************************************/ + +static bool is_subdomain(const char* a, const char *b) +{ + char *s; + TALLOC_CTX *frame = talloc_stackframe(); + char *x, *y; + bool ret = false; + + /* Trivial cases */ + + if (!a && !b) + return true; + + if (!a || !b) + return false; + + /* Normalize the case */ + + x = talloc_strdup(frame, a); + y = talloc_strdup(frame, b); + if (!x || !y) { + ret = false; + goto done; + } + + strupper_m(x); + strupper_m(y); + + /* Exact match */ + + if (strcmp(x, y) == 0) { + ret = true; + goto done; + } + + /* Check for trailing substrings */ + + s = strstr_m(x, y); + if (s && (strlen(s) == strlen(y))) { + ret = true; + goto done; + } + + s = strstr_m(y, x); + if (s && (strlen(s) == strlen(x))) { + ret = true; + goto done; + } + +done: + talloc_destroy(frame); + + return ret; +} + +/********************************************************************** + *********************************************************************/ + + NTSTATUS gc_find_forest_root(struct gc_info *gc, const char *domain) +{ + ADS_STRUCT *ads = NULL; + ADS_STATUS ads_status; + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + struct nbt_cldap_netlogon_5 cldap_reply; + TALLOC_CTX *frame = talloc_stackframe(); + + if (!gc || !domain) { + return NT_STATUS_INVALID_PARAMETER; + } + + ZERO_STRUCT(cldap_reply); + + ads = ads_init(domain, NULL, NULL); + BAIL_ON_PTR_ERROR(ads, nt_status); + + ads->auth.flags = ADS_AUTH_NO_BIND; + ads_status = ads_connect(ads); + if (!ADS_ERR_OK(ads_status)) { + DEBUG(4, ("find_forest_root: ads_connect(%s) failed! (%s)\n", + domain, ads_errstr(ads_status))); + } + nt_status = ads_ntstatus(ads_status); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + if (!ads_cldap_netlogon_5(frame, + ads->config.ldap_server_name, + ads->config.realm, + &cldap_reply)) + { + DEBUG(4,("find_forest_root: Failed to get a CLDAP reply from %s!\n", + ads->server.ldap_server)); + nt_status = NT_STATUS_IO_TIMEOUT; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + gc->forest_name = talloc_strdup(gc, cldap_reply.forest); + BAIL_ON_PTR_ERROR(gc->forest_name, nt_status); + +done: + if (ads) { + ads_destroy(&ads); + } + + return nt_status; +} + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS gc_add_forest(const char *domain) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + struct gc_info *gc = NULL; + struct gc_info *find_gc = NULL; + char *dn; + ADS_STRUCT *ads = NULL; + struct likewise_cell *primary_cell = NULL; + + primary_cell = cell_list_head(); + if (!primary_cell) { + nt_status = NT_STATUS_INVALID_SERVER_STATE; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* Check for duplicates based on domain name first as this + requires no connection */ + + find_gc = gc_list_head(); + while (find_gc) { + if (strequal (find_gc->forest_name, domain)) + break; + find_gc = find_gc->next; + } + + if (find_gc) { + DEBUG(10,("gc_add_forest: %s already in list\n", find_gc->forest_name)); + return NT_STATUS_OK; + } + + if ((gc = TALLOC_ZERO_P(NULL, struct gc_info)) == NULL) { + nt_status = NT_STATUS_NO_MEMORY; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* Query the rootDSE for the forest root naming conect first. + Check that the a GC server for the forest has not already + been added */ + + nt_status = gc_find_forest_root(gc, domain); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + find_gc = gc_list_head(); + while (find_gc) { + if (strequal (find_gc->forest_name, gc->forest_name)) + break; + find_gc = find_gc->next; + } + + if (find_gc) { + DEBUG(10,("gc_add_forest: Forest %s already in list\n", + find_gc->forest_name)); + return NT_STATUS_OK; + } + + /* Not found, so add it here. Make sure we connect to + a DC in _this_ domain and not the forest root. */ + + dn = ads_build_dn(gc->forest_name); + BAIL_ON_PTR_ERROR(dn, nt_status); + + gc->search_base = talloc_strdup(gc, dn); + SAFE_FREE(dn); + BAIL_ON_PTR_ERROR(gc->search_base, nt_status); + +#if 0 + /* Can't use cell_connect_dn() here as there is no way to + specifiy the LWCELL_FLAG_GC_CELL flag setting for cell_connect() */ + + nt_status = cell_connect_dn(&gc->forest_cell, gc->search_base); + BAIL_ON_NTSTATUS_ERROR(nt_status); +#else + + gc->forest_cell = cell_new(); + BAIL_ON_PTR_ERROR(gc->forest_cell, nt_status); + + /* Set the DNS domain, dn, etc ... and add it to the list */ + + cell_set_dns_domain(gc->forest_cell, gc->forest_name); + cell_set_dn(gc->forest_cell, gc->search_base); + cell_set_flags(gc->forest_cell, LWCELL_FLAG_GC_CELL); +#endif + + /* It is possible to belong to a non-forest cell and a + non-provisioned forest (at our domain levele). In that + case, we should just inherit the flags from our primary + cell since the GC searches will match our own schema + model. */ + + if (strequal(primary_cell->forest_name, gc->forest_name) + || is_subdomain(primary_cell->dns_domain, gc->forest_name)) + { + cell_set_flags(gc->forest_cell, cell_flags(primary_cell)); + } else { + /* outside of our domain */ + + nt_status = cell_connect(gc->forest_cell); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + nt_status = cell_lookup_settings(gc->forest_cell); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + /* Drop the connection now that we have the settings */ + + ads = cell_connection(gc->forest_cell); + ads_destroy(&ads); + cell_set_connection(gc->forest_cell, NULL); + } + + DLIST_ADD_END(_gc_server_list, gc, struct gc_info*); + + DEBUG(10,("gc_add_forest: Added %s to Global Catalog list of servers\n", + gc->forest_name)); + + nt_status = NT_STATUS_OK; + +done: + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_destroy(gc); + DEBUG(3,("LWI: Failed to add new GC connection for %s (%s)\n", + domain, nt_errstr(nt_status))); + } + + return nt_status; +} + +/********************************************************************** + *********************************************************************/ + +static void gc_server_list_destroy(void) +{ + struct gc_info *gc = gc_list_head(); + + while (gc) { + struct gc_info *p = gc->next; + + cell_destroy(gc->forest_cell); + talloc_destroy(gc); + + gc = p; + } + + _gc_server_list = NULL; + + return; +} + +/********************************************************************** + Setup the initial list of forests and initial the forest cell + settings for each. FIXME!!! + *********************************************************************/ + + NTSTATUS gc_init_list(void) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + struct winbindd_tdc_domain *domains = NULL; + size_t num_domains = 0; + int i; + + if (_gc_server_list != NULL) { + gc_server_list_destroy(); + } + + if (!wcache_tdc_fetch_list(&domains, &num_domains)) { + nt_status = NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* Find our forest first. Have to try all domains here starting + with our own. gc_add_forest() filters duplicates */ + + nt_status = gc_add_forest(lp_realm()); + WARN_ON_NTSTATUS_ERROR(nt_status); + + for (i=0; iforest_cell, "", + LDAP_SCOPE_SUBTREE, filter, attrs, &m); + nt_status = ads_ntstatus(ads_status); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + *msg = m; + +done: + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(2,("LWI: Forest wide search %s failed (%s)\n", + filter, nt_errstr(nt_status))); + } + + return nt_status; +} + +/********************************************************************** + Search all forests via GC and return the results in an array of + ADS_STRUCT/LDAPMessage pairs. + *********************************************************************/ + + NTSTATUS gc_search_all_forests(const char *filter, + ADS_STRUCT ***ads_list, + LDAPMessage ***msg_list, + int *num_resp, uint32_t flags) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + struct gc_info *gc = NULL; + uint32_t test_flags = ADEX_GC_SEARCH_CHECK_UNIQUE; + + *ads_list = NULL; + *msg_list = NULL; + *num_resp = 0; + + if ((gc = gc_search_start()) == NULL) { + nt_status = NT_STATUS_INVALID_DOMAIN_STATE; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + while (gc) { + LDAPMessage *m = NULL; + + nt_status = gc_search_forest(gc, &m, filter); + if (!NT_STATUS_IS_OK(nt_status)) { + gc = gc->next; + continue; + } + + nt_status = add_ads_result_to_array(cell_connection(gc->forest_cell), + m, ads_list, msg_list, + num_resp); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + /* If there can only be one match, then we are done */ + + if ((*num_resp > 0) && ((flags & test_flags) == test_flags)) { + break; + } + + gc = gc->next; + } + + if (*num_resp == 0) { + nt_status = NT_STATUS_OBJECT_NAME_NOT_FOUND; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + nt_status = NT_STATUS_OK; + +done: + return nt_status; +} + +/********************************************************************** + Search all forests via GC and return the results in an array of + ADS_STRUCT/LDAPMessage pairs. + *********************************************************************/ + + NTSTATUS gc_search_all_forests_unique(const char *filter, + ADS_STRUCT **ads, + LDAPMessage **msg) +{ + ADS_STRUCT **ads_list = NULL; + LDAPMessage **msg_list = NULL; + int num_resp; + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + + nt_status = gc_search_all_forests(filter, &ads_list, + &msg_list, &num_resp, + ADEX_GC_SEARCH_CHECK_UNIQUE); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + nt_status = check_result_unique(ads_list[0], msg_list[0]); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + *ads = ads_list[0]; + *msg = msg_list[0]; + +done: + /* Be care that we don't free the msg result being returned */ + + if (!NT_STATUS_IS_OK(nt_status)) { + free_result_array(ads_list, msg_list, num_resp); + } else { + talloc_destroy(ads_list); + talloc_destroy(msg_list); + } + + return nt_status; +} + +/********************************************************************* + ********************************************************************/ + + NTSTATUS gc_name_to_sid(const char *domain, + const char *name, + DOM_SID *sid, + enum lsa_SidType *sid_type) +{ + TALLOC_CTX *frame = talloc_stackframe(); + char *p, *name_user; + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + char *name_filter; + ADS_STRUCT *ads = NULL; + LDAPMessage *msg = NULL; + LDAPMessage *e = NULL; + char *dn = NULL; + char *dns_domain = NULL; + ADS_STRUCT **ads_list = NULL; + LDAPMessage **msg_list = NULL; + int num_resp = 0; + int i; + + /* Strip the "DOMAIN\" prefix if necessary and search for + a matching sAMAccountName in the forest */ + + if ((p = strchr_m( name, '\\' )) == NULL) + name_user = talloc_strdup( frame, name ); + else + name_user = talloc_strdup( frame, p+1 ); + BAIL_ON_PTR_ERROR(name_user, nt_status); + + name_filter = talloc_asprintf(frame, "(sAMAccountName=%s)", name_user); + BAIL_ON_PTR_ERROR(name_filter, nt_status); + + nt_status = gc_search_all_forests(name_filter, &ads_list, + &msg_list, &num_resp, 0); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + /* Assume failure until we know otherwise*/ + + nt_status = NT_STATUS_OBJECT_NAME_NOT_FOUND; + + /* Match the domain name from the DN */ + + for (i=0; idomain_name)) { + if (!ads_pull_sid(ads, e, "objectSid", sid)) { + nt_status = NT_STATUS_INVALID_SID; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + talloc_destroy(domain_rec); + + nt_status = get_sid_type(ads, msg, sid_type); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + /* We're done! */ + nt_status = NT_STATUS_OK; + break; + } + + /* once more around thew merry-go-round */ + + talloc_destroy(domain_rec); + e = ads_next_entry(ads, e); + } + } + +done: + free_result_array(ads_list, msg_list, num_resp); + talloc_destroy(frame); + + return nt_status; +} + +/******************************************************************** + Pull an attribute string value + *******************************************************************/ + +static NTSTATUS get_object_account_name(ADS_STRUCT *ads, + LDAPMessage *msg, + char **name) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + char *sam_name = NULL; + struct winbindd_tdc_domain *domain_rec = NULL; + char *dns_domain = NULL; + char *dn = NULL; + TALLOC_CTX *frame = talloc_stackframe(); + int len; + + /* Check parameters */ + + if (!ads || !msg || !name) { + nt_status = NT_STATUS_INVALID_PARAMETER; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* get the name and domain */ + + dn = ads_get_dn(ads, msg); + BAIL_ON_PTR_ERROR(dn, nt_status); + + DEBUG(10,("get_object_account_name: dn = \"%s\"\n", dn)); + + dns_domain = cell_dn_to_dns(dn); + SAFE_FREE(dn); + BAIL_ON_PTR_ERROR(dns_domain, nt_status); + + domain_rec = wcache_tdc_fetch_domain(frame, dns_domain); + SAFE_FREE(dns_domain); + + if (!domain_rec) { + nt_status = NT_STATUS_TRUSTED_DOMAIN_FAILURE; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + sam_name = ads_pull_string(ads, frame, msg, "sAMAccountName"); + BAIL_ON_PTR_ERROR(sam_name, nt_status); + + len = asprintf(name, "%s\\%s", domain_rec->domain_name, sam_name); + if (len == -1) { + *name = NULL; + BAIL_ON_PTR_ERROR((*name), nt_status); + } + + nt_status = NT_STATUS_OK; + +done: + talloc_destroy(frame); + + return nt_status; +} + +/********************************************************************* + ********************************************************************/ + + NTSTATUS gc_sid_to_name(const DOM_SID *sid, + char **name, + enum lsa_SidType *sid_type) +{ + TALLOC_CTX *frame = talloc_stackframe(); + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + char *filter; + ADS_STRUCT *ads = NULL; + LDAPMessage *msg = NULL; + char *sid_string; + + *name = NULL; + + sid_string = sid_binstring(sid); + BAIL_ON_PTR_ERROR(sid_string, nt_status); + + filter = talloc_asprintf(frame, "(objectSid=%s)", sid_string); + SAFE_FREE(sid_string); + BAIL_ON_PTR_ERROR(filter, nt_status); + + nt_status = gc_search_all_forests_unique(filter, &ads, &msg); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + nt_status = get_object_account_name(ads, msg, name); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + nt_status = get_sid_type(ads, msg, sid_type); + BAIL_ON_NTSTATUS_ERROR(nt_status); + +done: + ads_msgfree(ads, msg); + talloc_destroy(frame); + + return nt_status; +} + +/********************************************************************** + *********************************************************************/ + + NTSTATUS add_ads_result_to_array(ADS_STRUCT *ads, + LDAPMessage *msg, + ADS_STRUCT ***ads_list, + LDAPMessage ***msg_list, + int *size) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + ADS_STRUCT **ads_tmp = NULL; + LDAPMessage **msg_tmp = NULL; + int count = *size; + + if (!ads || !msg) { + nt_status = NT_STATUS_INVALID_PARAMETER; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + +#if 0 + /* Don't add a response with no entries */ + + if (ads_count_replies(ads, msg) == 0) { + return NT_STATUS_OK; + } +#endif + + if (count == 0) { + ads_tmp = TALLOC_ARRAY(NULL, ADS_STRUCT*, 1); + BAIL_ON_PTR_ERROR(ads_tmp, nt_status); + + msg_tmp = TALLOC_ARRAY(NULL, LDAPMessage*, 1); + BAIL_ON_PTR_ERROR(msg_tmp, nt_status); + } else { + ads_tmp = TALLOC_REALLOC_ARRAY(*ads_list, *ads_list, ADS_STRUCT*, + count+1); + BAIL_ON_PTR_ERROR(ads_tmp, nt_status); + + msg_tmp = TALLOC_REALLOC_ARRAY(*msg_list, *msg_list, LDAPMessage*, + count+1); + BAIL_ON_PTR_ERROR(msg_tmp, nt_status); + } + + ads_tmp[count] = ads; + msg_tmp[count] = msg; + count++; + + *ads_list = ads_tmp; + *msg_list = msg_tmp; + *size = count; + + nt_status = NT_STATUS_OK; + +done: + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_destroy(ads_tmp); + talloc_destroy(msg_tmp); + } + + return nt_status; +} + +/********************************************************************** + Frees search results. Do not free the ads_list as these are + references back to the GC search structures. + *********************************************************************/ + + void free_result_array(ADS_STRUCT **ads_list, + LDAPMessage **msg_list, + int num_resp) +{ + int i; + + for (i=0; i 1) { + nt_status = NT_STATUS_DUPLICATE_NAME; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + nt_status = NT_STATUS_OK; + +done: + return nt_status; +} diff --git a/source3/winbindd/idmap_adex/idmap_adex.c b/source3/winbindd/idmap_adex/idmap_adex.c new file mode 100644 index 0000000000..23ab843e95 --- /dev/null +++ b/source3/winbindd/idmap_adex/idmap_adex.c @@ -0,0 +1,460 @@ +/* + * idmap_adex: Support for D Forests + * + * Copyright (C) Gerald (Jerry) Carter 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 + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include "includes.h" +#include "idmap_adex.h" + +#undef DBGC_CLASS +#define DBGC_CLASS DBGC_IDMAP + +#define WINBIND_CCACHE_NAME "MEMORY:winbind_ccache" + +NTSTATUS init_module(void); + +/* + * IdMap backend + */ + +/******************************************************************** + Basic init function responsible for determining our current mode + (standalone or using Centeris Cells). This must return success or + it will be dropped from the idmap backend list. + *******************************************************************/ + +static NTSTATUS _idmap_adex_init(struct idmap_domain *dom, + const char *params) +{ + ADS_STRUCT *ads = NULL; + ADS_STATUS status; + static NTSTATUS init_status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND; + DOM_SID domain_sid; + fstring dcname; + struct sockaddr_storage ip; + struct likewise_cell *lwcell; + + if (NT_STATUS_IS_OK(init_status)) + return NT_STATUS_OK; + + /* Silently fail if we are not a member server in security = ads */ + + if ((lp_server_role() != ROLE_DOMAIN_MEMBER) || + (lp_security() != SEC_ADS)) { + init_status = NT_STATUS_INVALID_SERVER_STATE; + BAIL_ON_NTSTATUS_ERROR(init_status); + } + + /* fetch our domain SID first */ + + if (!secrets_fetch_domain_sid(lp_workgroup(), &domain_sid)) { + init_status = NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + BAIL_ON_NTSTATUS_ERROR(init_status); + } + + /* reuse the same ticket cache as winbindd */ + + setenv("KRB5CCNAME", WINBIND_CCACHE_NAME, 1); + + /* Establish a connection to a DC */ + + if ((ads = ads_init(lp_realm(), lp_workgroup(), NULL)) == NULL) { + init_status = NT_STATUS_NO_MEMORY; + BAIL_ON_NTSTATUS_ERROR(init_status); + } + + ads->auth.password = + secrets_fetch_machine_password(lp_workgroup(), NULL, NULL); + ads->auth.realm = SMB_STRDUP(lp_realm()); + + /* get the DC name here to setup the server affinity cache and + local krb5.conf */ + + get_dc_name(lp_workgroup(), lp_realm(), dcname, &ip); + + status = ads_connect(ads); + if (!ADS_ERR_OK(status)) { + DEBUG(0, ("_idmap_adex_init: ads_connect() failed! (%s)\n", + ads_errstr(status))); + } + init_status = ads_ntstatus(status); + BAIL_ON_NTSTATUS_ERROR(init_status); + + + /* Find out cell membership */ + + init_status = cell_locate_membership(ads); + if (!NT_STATUS_IS_OK(init_status)) { + DEBUG(0,("LWI: Fail to locate cell membership (%s).", + nt_errstr(init_status))); + goto done; + } + + /* Fill in the cell information */ + + lwcell = cell_list_head(); + + init_status = cell_lookup_settings(lwcell); + BAIL_ON_NTSTATUS_ERROR(init_status); + + /* Miscellaneous setup. E.g. set up the list of GC + servers and domain list for our forest (does not actually + connect). */ + + init_status = gc_init_list(); + BAIL_ON_NTSTATUS_ERROR(init_status); + + init_status = domain_init_list(); + BAIL_ON_NTSTATUS_ERROR(init_status); + +done: + if (!NT_STATUS_IS_OK(init_status)) { + DEBUG(1,("Likewise initialization failed (%s)\n", + nt_errstr(init_status))); + } + + /* cleanup */ + + if (!NT_STATUS_IS_OK(init_status)) { + cell_list_destroy(); + + /* init_status stores the failure reason but we need to + return success or else idmap_init() will drop us from the + backend list */ + return NT_STATUS_OK; + } + + init_status = NT_STATUS_OK; + + return init_status; +} + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS _idmap_adex_get_sid_from_id(struct + idmap_domain + *dom, struct + id_map + **ids) +{ + int i; + bool one_mapped = false; + bool all_mapped = true; + NTSTATUS nt_status; + struct likewise_cell *cell; + + nt_status = _idmap_adex_init(dom, NULL); + if (!NT_STATUS_IS_OK(nt_status)) + return nt_status; + + if ((cell = cell_list_head()) == NULL) { + return NT_STATUS_INVALID_SERVER_STATE; + } + + /* have to work through these one by one */ + for (i = 0; ids[i]; i++) { + NTSTATUS status; + status = cell->provider->get_sid_from_id(ids[i]->sid, + ids[i]->xid.id, + ids[i]->xid.type); + /* Fail if we cannot find any DC */ + if (NT_STATUS_EQUAL + (status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) { + return status; + } + + if (!NT_STATUS_IS_OK(status)) { + ids[i]->status = ID_UNMAPPED; + all_mapped = false; + continue; + } + + ids[i]->status = ID_MAPPED; + one_mapped = true; + } + + return NT_STATUS_OK; +} + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS _idmap_adex_get_id_from_sid(struct + idmap_domain + *dom, struct + id_map + **ids) +{ + int i; + bool one_mapped = false; + bool all_mapped = true; + NTSTATUS nt_status; + struct likewise_cell *cell; + + nt_status = _idmap_adex_init(dom, NULL); + if (!NT_STATUS_IS_OK(nt_status)) + return nt_status; + + if ((cell = cell_list_head()) == NULL) { + return NT_STATUS_INVALID_SERVER_STATE; + } + + /* have to work through these one by one */ + for (i = 0; ids[i]; i++) { + NTSTATUS status; + status = cell->provider->get_id_from_sid(&ids[i]->xid.id, + &ids[i]->xid. + type, ids[i]->sid); + /* Fail if we cannot find any DC */ + if (NT_STATUS_EQUAL + (status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) { + return status; + } + + if (!NT_STATUS_IS_OK(status)) { + ids[i]->status = ID_UNMAPPED; + all_mapped = false; + continue; + } + + ids[i]->status = ID_MAPPED; + one_mapped = true; + } + + return NT_STATUS_OK; +} + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS _idmap_adex_set_mapping(struct + idmap_domain + *dom, const struct + id_map *map) +{ + DEBUG(0, ("_idmap_adex_set_mapping: not implemented\n")); + return NT_STATUS_NOT_IMPLEMENTED; +} + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS _idmap_adex_remove_mapping(struct + idmap_domain + *dom, const + struct + id_map + *map) +{ + DEBUG(0, ("_idmap_adex_remove_mapping: not implemented\n")); + return NT_STATUS_NOT_IMPLEMENTED; +} + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS _idmap_adex_dump(struct idmap_domain + *dom, struct id_map **maps, int *num_map) +{ + return NT_STATUS_NOT_IMPLEMENTED; +} + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS _idmap_adex_close(struct idmap_domain + *dom) +{ + /* FIXME! need to do cleanup here */ + + return NT_STATUS_OK; +} + +/* + * IdMap NSS plugin + */ + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS _nss_adex_init(struct nss_domain_entry + *e) +{ + return _idmap_adex_init(NULL, NULL); +} + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS _nss_adex_get_info(struct + nss_domain_entry *e, + const DOM_SID * sid, + TALLOC_CTX * ctx, + ADS_STRUCT * ads, + LDAPMessage * msg, + char **homedir, + char **shell, char **gecos, gid_t * p_gid) +{ + NTSTATUS nt_status; + struct likewise_cell *cell; + + nt_status = _idmap_adex_init(NULL, NULL); + if (!NT_STATUS_IS_OK(nt_status)) + return nt_status; + + if ((cell = cell_list_head()) == NULL) { + return NT_STATUS_INVALID_SERVER_STATE; + } + + return cell->provider->get_nss_info(sid, ctx, homedir, + shell, gecos, p_gid); +} + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS _nss_adex_map_to_alias(TALLOC_CTX * mem_ctx, const char + *domain, const char + *name, char **alias) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + struct likewise_cell *cell = NULL; + + nt_status = _idmap_adex_init(NULL, NULL); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + if ((cell = cell_list_head()) == NULL) { + nt_status = NT_STATUS_INVALID_SERVER_STATE; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + nt_status = cell->provider->map_to_alias(mem_ctx, domain, + name, alias); + + /* go ahead and allow the cache mgr to mark this in + negative cache */ + + if (!NT_STATUS_IS_OK(nt_status)) + nt_status = NT_STATUS_NONE_MAPPED; + +done: + return nt_status; +} + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS _nss_adex_map_from_alias(TALLOC_CTX * mem_ctx, const char + *domain, const char + *alias, char **name) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + struct likewise_cell *cell = NULL; + + nt_status = _idmap_adex_init(NULL, NULL); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + if ((cell = cell_list_head()) == NULL) { + nt_status = NT_STATUS_INVALID_SERVER_STATE; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + + nt_status = cell->provider->map_from_alias(mem_ctx, domain, + alias, name); + + /* go ahead and allow the cache mgr to mark this in + negative cache */ + + if (!NT_STATUS_IS_OK(nt_status)) + nt_status = NT_STATUS_NONE_MAPPED; + +done: + return nt_status; +} + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS _nss_adex_close(void) +{ + return NT_STATUS_NOT_IMPLEMENTED; +} + +/********************************************************************** + *********************************************************************/ + +static struct idmap_methods adex_idmap_methods = { + + .init = _idmap_adex_init, + .unixids_to_sids = _idmap_adex_get_sid_from_id, + .sids_to_unixids = _idmap_adex_get_id_from_sid, + .set_mapping = _idmap_adex_set_mapping, + .remove_mapping = _idmap_adex_remove_mapping, + .dump_data = _idmap_adex_dump, + .close_fn = _idmap_adex_close +}; +static struct nss_info_methods adex_nss_methods = { + .init = _nss_adex_init, + .get_nss_info = _nss_adex_get_info, + .map_to_alias = _nss_adex_map_to_alias, + .map_from_alias = _nss_adex_map_from_alias, + .close_fn = _nss_adex_close +}; + +/********************************************************************** + Register with the idmap and idmap_nss subsystems. We have to protect + against the idmap and nss_info interfaces being in a half-registered + state. + **********************************************************************/ +NTSTATUS idmap_adex_init(void) +{ + static NTSTATUS idmap_status = NT_STATUS_UNSUCCESSFUL; + static NTSTATUS nss_status = NT_STATUS_UNSUCCESSFUL; + if (!NT_STATUS_IS_OK(idmap_status)) { + idmap_status = + smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, + "adex", &adex_idmap_methods); + if (!NT_STATUS_IS_OK(idmap_status)) { + DEBUG(0, + ("idmap_centeris_init: Failed to register the adex" + "idmap plugin.\n")); + return idmap_status; + } + } + + if (!NT_STATUS_IS_OK(nss_status)) { + nss_status = + smb_register_idmap_nss(SMB_NSS_INFO_INTERFACE_VERSION, + "adex", &adex_nss_methods); + if (!NT_STATUS_IS_OK(nss_status)) { + DEBUG(0, + ("idmap_adex_init: Failed to register the adex" + "nss plugin.\n")); + return nss_status; + } + } + + return NT_STATUS_OK; +} + +NTSTATUS nss_info_adex_init(void) +{ + return idmap_adex_init(); +} diff --git a/source3/winbindd/idmap_adex/idmap_adex.h b/source3/winbindd/idmap_adex/idmap_adex.h new file mode 100644 index 0000000000..f91bba8d07 --- /dev/null +++ b/source3/winbindd/idmap_adex/idmap_adex.h @@ -0,0 +1,257 @@ +/* + * idmap_centeris: Support for Local IDs and Centeris Cell Structure + * + * Copyright (C) Gerald (Jerry) Carter 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 + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#ifndef _IDMAP_ADEX_H +#define _IDMAP_ADEX_H + +#include "winbindd/winbindd.h" + +#define ADEX_CELL_RDN "$LikewiseIdentityCell" + +#define ADEX_OC_USER "centerisLikewiseUser" +#define ADEX_OC_GROUP "centerisLikewiseGroup" + +#define AD_USER "User" +#define AD_GROUP "Group" + +#define ADEX_OC_POSIX_USER "posixAccount" +#define ADEX_OC_POSIX_GROUP "posixGroup" + +#define ADEX_ATTR_UIDNUM "uidNumber" +#define ADEX_ATTR_GIDNUM "gidNUmber" +#define ADEX_ATTR_HOMEDIR "unixHomeDirectory" +#define ADEX_ATTR_USERPW "unixUserPassword" +#define ADEX_ATTR_GROUPALIAS "groupAlias" /* Not part of RFC2307 */ +#define ADEX_ATTR_SHELL "loginShell" +#define ADEX_ATTR_GECOS "gecos" +#define ADEX_ATTR_UID "uid" +#define ADEX_ATTR_DISPLAYNAME "displayName" + +#define MIN_ID_VALUE 100 + +#define BAIL_ON_NTSTATUS_ERROR(x) \ + do { \ + if (!NT_STATUS_IS_OK(x)) { \ + DEBUG(10,("Failed! (%s)\n", nt_errstr(x))); \ + goto done; \ + } \ + } \ + while (0); \ + +#define WARN_ON_NTSTATUS_ERROR(x) \ + do { \ + if (!NT_STATUS_IS_OK(x)) { \ + DEBUG(10,("Failure ignored! (%s)\n", nt_errstr(x))); \ + } \ + } \ + while (0); \ + +#define BAIL_ON_ADS_ERROR(x) \ + do { \ + if (!ADS_ERR_OK(x)) { \ + goto done; \ + } \ + } \ + while (0); + +#define BAIL_ON_PTR_ERROR(p, x) \ + do { \ + if ((p) == NULL ) { \ + DEBUG(10,("NULL pointer!\n")); \ + x = NT_STATUS_NO_MEMORY; \ + goto done; \ + } \ + } while (0); + +#define PRINT_NTSTATUS_ERROR(x, hdr, level) \ + do { \ + if (!NT_STATUS_IS_OK(x)) { \ + DEBUG(level,("LWI ("hdr"): %s\n", nt_errstr(x))); \ + } \ + } while(0); +/* + * Cell Provider API + */ + +struct cell_provider_api { + NTSTATUS(*get_sid_from_id) (DOM_SID * sid, + uint32_t id, enum id_type type); + NTSTATUS(*get_id_from_sid) (uint32_t * id, + enum id_type * type, const DOM_SID * sid); + NTSTATUS(*get_nss_info) (const DOM_SID * sid, + TALLOC_CTX * ctx, + char **homedir, + char **shell, char **gecos, gid_t * p_gid); + NTSTATUS(*map_to_alias) (TALLOC_CTX * mem_ctx, + const char *domain, + const char *name, char **alias); + NTSTATUS(*map_from_alias) (TALLOC_CTX * mem_ctx, + const char *domain, + const char *alias, char **name); +}; + +/* registered providers */ + +extern struct cell_provider_api ccp_unified; +extern struct cell_provider_api ccp_local; + +#define LWCELL_FLAG_USE_RFC2307_ATTRS 0x00000001 +#define LWCELL_FLAG_SEARCH_FOREST 0x00000002 +#define LWCELL_FLAG_GC_CELL 0x00000004 +#define LWCELL_FLAG_LOCAL_MODE 0x00000008 + +struct likewise_cell { + struct likewise_cell *prev, *next; + ADS_STRUCT *conn; + struct likewise_cell *gc_search_cell; + DOM_SID domain_sid; + char *dns_domain; + char *forest_name; + char *dn; + struct GUID *links; /* only held by owning cell */ + size_t num_links; + uint32_t flags; + struct cell_provider_api *provider; +}; + +/* Search flags used for Global Catalog API */ + +#define ADEX_GC_SEARCH_CHECK_UNIQUE 0x00000001 + +struct gc_info { + struct gc_info *prev, *next; + char *forest_name; + char *search_base; + struct likewise_cell *forest_cell; +}; + +/* Available functions outside of idmap_lwidentity.c */ + +/* cell_util.c */ + +char *find_attr_string(char **list, size_t num_lines, const char *substr); +bool is_object_class(char **list, size_t num_lines, const char *substr); +int min_id_value(void); +char *cell_dn_to_dns(const char *dn); +NTSTATUS get_sid_type(ADS_STRUCT *ads, + LDAPMessage *msg, + enum lsa_SidType *type); + +NTSTATUS cell_locate_membership(ADS_STRUCT * ads); +NTSTATUS cell_lookup_settings(struct likewise_cell * cell); +NTSTATUS cell_follow_links(struct likewise_cell *cell); +NTSTATUS cell_set_local_provider(void); + +/* likewise_cell.c */ + +struct likewise_cell *cell_new(void); +struct likewise_cell *cell_list_head(void); + +bool cell_list_add(struct likewise_cell *cell); +bool cell_list_remove(struct likewise_cell * cell); + +void cell_list_destroy(); +void cell_destroy(struct likewise_cell *c); +void cell_set_forest_searches(struct likewise_cell *c, + bool search); +void cell_set_dns_domain(struct likewise_cell *c, + const char *dns_domain); +void cell_set_connection(struct likewise_cell *c, + ADS_STRUCT *ads); +void cell_set_dn(struct likewise_cell *c, + const char *dn); +void cell_set_domain_sid(struct likewise_cell *c, + DOM_SID *sid); +void cell_set_flags(struct likewise_cell *c, uint32_t flags); +void cell_clear_flags(struct likewise_cell *c, uint32_t flags); + +const char* cell_search_base(struct likewise_cell *c); +const char *cell_dns_domain(struct likewise_cell *c); +ADS_STRUCT *cell_connection(struct likewise_cell *c); +bool cell_search_forest(struct likewise_cell *c); +ADS_STATUS cell_do_search(struct likewise_cell *c, + const char *search_base, + int scope, + const char *expr, + const char **attrs, + LDAPMessage ** msg); +uint32_t cell_flags(struct likewise_cell *c); + +NTSTATUS cell_connect_dn(struct likewise_cell **c, + const char *dn); +NTSTATUS cell_connect(struct likewise_cell *c); + + +/* gc_util.c */ + +NTSTATUS gc_init_list(void); + +NTSTATUS gc_find_forest_root(struct gc_info *gc, + const char *domain); + +struct gc_info *gc_search_start(void); + +NTSTATUS gc_search_forest(struct gc_info *gc, + LDAPMessage **msg, + const char *filter); + +NTSTATUS gc_search_all_forests(const char *filter, + ADS_STRUCT ***ads_list, + LDAPMessage ***msg_list, + int *num_resp, uint32_t flags); + +NTSTATUS gc_search_all_forests_unique(const char *filter, + ADS_STRUCT **ads, + LDAPMessage **msg); + +NTSTATUS gc_name_to_sid(const char *domain, + const char *name, + DOM_SID *sid, + enum lsa_SidType *sid_type); + +NTSTATUS gc_sid_to_name(const DOM_SID *sid, + char **name, + enum lsa_SidType *sid_type); + +NTSTATUS add_ads_result_to_array(ADS_STRUCT *ads, + LDAPMessage *msg, + ADS_STRUCT ***ads_list, + LDAPMessage ***msg_list, + int *size); + +void free_result_array(ADS_STRUCT **ads_list, + LDAPMessage **msg_list, + int num_resp); + +NTSTATUS check_result_unique(ADS_STRUCT *ads, + LDAPMessage *msg); + + +/* domain_util.c */ + +NTSTATUS domain_init_list(void); + +NTSTATUS dc_search_domains(struct likewise_cell **cell, + LDAPMessage **msg, + const char *dn, + const DOM_SID *user_sid); + + +#endif /* _IDMAP_ADEX_H */ diff --git a/source3/winbindd/idmap_adex/likewise_cell.c b/source3/winbindd/idmap_adex/likewise_cell.c new file mode 100644 index 0000000000..77eeee406b --- /dev/null +++ b/source3/winbindd/idmap_adex/likewise_cell.c @@ -0,0 +1,425 @@ +/* + * idmap_adex: Support for AD Forests + * + * Copyright (C) Gerald (Jerry) Carter 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 + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include "includes.h" +#include "idmap_adex.h" + +#undef DBGC_CLASS +#define DBGC_CLASS DBGC_IDMAP + +static struct likewise_cell *_lw_cell_list = NULL; + +/********************************************************************** + Return the current HEAD of the list + *********************************************************************/ + + struct likewise_cell *cell_list_head(void) +{ + return _lw_cell_list; +} + + +/********************************************************************** + *********************************************************************/ + + void cell_destroy(struct likewise_cell *c) +{ + if (!c) + return; + + if (c->conn) + ads_destroy(&c->conn); + + talloc_destroy(c); +} + +/********************************************************************** + Free all cell entries and reset the list head to NULL + *********************************************************************/ + + void cell_list_destroy(void) +{ + struct likewise_cell *p = _lw_cell_list; + + while (p) { + struct likewise_cell *q = p->next; + + cell_destroy(p); + + p = q; + } + + _lw_cell_list = NULL; + + return; +} + +/********************************************************************** + Add a new cell structure to the list + *********************************************************************/ + + struct likewise_cell* cell_new(void) +{ + struct likewise_cell *c; + + /* Each cell struct is a TALLOC_CTX* */ + + c = TALLOC_ZERO_P(NULL, struct likewise_cell); + if (!c) { + DEBUG(0,("cell_new: memory allocation failure!\n")); + return NULL; + } + + return c; +} + +/********************************************************************** + Add a new cell structure to the list + *********************************************************************/ + + bool cell_list_add(struct likewise_cell * cell) +{ + if (!cell) { + return false; + } + + /* Always add to the end */ + + DLIST_ADD_END(_lw_cell_list, cell, struct likewise_cell *); + + return true; +} + +/********************************************************************** + Add a new cell structure to the list + *********************************************************************/ + + bool cell_list_remove(struct likewise_cell * cell) +{ + if (!cell) { + return false; + } + + /* Remove and drop the cell structure */ + + DLIST_REMOVE(_lw_cell_list, cell); + talloc_destroy(cell); + + return true; +} + +/********************************************************************** + Set the containing DNS domain for a cell + *********************************************************************/ + + void cell_set_dns_domain(struct likewise_cell *c, const char *dns_domain) +{ + c->dns_domain = talloc_strdup(c, dns_domain); +} + +/********************************************************************** + Set ADS connection for a cell + *********************************************************************/ + + void cell_set_connection(struct likewise_cell *c, ADS_STRUCT *ads) +{ + c->conn = ads; +} + +/********************************************************************** + *********************************************************************/ + + void cell_set_flags(struct likewise_cell *c, uint32_t flags) +{ + c->flags |= flags; +} + +/********************************************************************** + *********************************************************************/ + + void cell_clear_flags(struct likewise_cell *c, uint32_t flags) +{ + c->flags &= ~flags; +} + +/********************************************************************** + Set the Cell's DN + *********************************************************************/ + + void cell_set_dn(struct likewise_cell *c, const char *dn) +{ + if ( c->dn) { + talloc_free(c->dn); + c->dn = NULL; + } + + c->dn = talloc_strdup(c, dn); +} + +/********************************************************************** + *********************************************************************/ + + void cell_set_domain_sid(struct likewise_cell *c, DOM_SID *sid) +{ + sid_copy(&c->domain_sid, sid); +} + +/* + * Query Routines + */ + +/********************************************************************** + *********************************************************************/ + + const char* cell_search_base(struct likewise_cell *c) +{ + if (!c) + return NULL; + + return talloc_asprintf(c, "cn=%s,%s", ADEX_CELL_RDN, c->dn); +} + +/********************************************************************** + *********************************************************************/ + + bool cell_search_forest(struct likewise_cell *c) +{ + uint32_t test_flags = LWCELL_FLAG_SEARCH_FOREST; + + return ((c->flags & test_flags) == test_flags); +} + +/********************************************************************** + *********************************************************************/ + + uint32_t cell_flags(struct likewise_cell *c) +{ + if (!c) + return 0; + + return c->flags; +} + +/********************************************************************** + *********************************************************************/ + + const char *cell_dns_domain(struct likewise_cell *c) +{ + if (!c) + return NULL; + + return c->dns_domain; +} + +/********************************************************************** + *********************************************************************/ + + ADS_STRUCT *cell_connection(struct likewise_cell *c) +{ + if (!c) + return NULL; + + return c->conn; +} + +/* + * Connection functions + */ + +/******************************************************************** + *******************************************************************/ + + NTSTATUS cell_connect(struct likewise_cell *c) +{ + ADS_STRUCT *ads = NULL; + ADS_STATUS ads_status; + fstring dc_name; + struct sockaddr_storage dcip; + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + + /* have to at least have the AD domain name */ + + if (!c->dns_domain) { + nt_status = NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* clear out any old information */ + + if (c->conn) { + ads_destroy(&c->conn); + c->conn = NULL; + } + + /* now setup the new connection */ + + ads = ads_init(c->dns_domain, NULL, NULL); + BAIL_ON_PTR_ERROR(ads, nt_status); + + ads->auth.password = + secrets_fetch_machine_password(lp_workgroup(), NULL, NULL); + ads->auth.realm = SMB_STRDUP(lp_realm()); + + /* Make the connection. We should already have an initial + TGT using the machine creds */ + + if (cell_flags(c) & LWCELL_FLAG_GC_CELL) { + ads_status = ads_connect_gc(ads); + } else { + /* Set up server affinity for normal cells and the client + site name cache */ + + if (!get_dc_name("", c->dns_domain, dc_name, &dcip)) { + nt_status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + ads_status = ads_connect(ads); + } + + + c->conn = ads; + + nt_status = ads_ntstatus(ads_status); + +done: + if (!NT_STATUS_IS_OK(nt_status)) { + ads_destroy(&ads); + c->conn = NULL; + } + + return nt_status; +} + +/******************************************************************** + *******************************************************************/ + + NTSTATUS cell_connect_dn(struct likewise_cell **c, const char *dn) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + struct likewise_cell *new_cell = NULL; + char *dns_domain = NULL; + + if (*c || !dn) { + nt_status = NT_STATUS_INVALID_PARAMETER; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + if ((new_cell = cell_new()) == NULL) { + nt_status = NT_STATUS_NO_MEMORY; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* Set the DNS domain, dn, etc ... and add it to the list */ + + dns_domain = cell_dn_to_dns(dn); + cell_set_dns_domain(new_cell, dns_domain); + SAFE_FREE(dns_domain); + + cell_set_dn(new_cell, dn); + + nt_status = cell_connect(new_cell); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + *c = new_cell; + +done: + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(1,("LWI: Failled to connect to cell \"%s\" (%s)\n", + dn ? dn : "NULL", nt_errstr(nt_status))); + talloc_destroy(new_cell); + } + + return nt_status; +} + + +/******************************************************************** + *******************************************************************/ + +#define MAX_SEARCH_COUNT 2 + + ADS_STATUS cell_do_search(struct likewise_cell *c, + const char *search_base, + int scope, + const char *expr, + const char **attrs, + LDAPMessage ** msg) +{ + int search_count = 0; + ADS_STATUS status; + NTSTATUS nt_status; + + /* check for a NULL connection */ + + if (!c->conn) { + nt_status = cell_connect(c); + if (!NT_STATUS_IS_OK(nt_status)) { + status = ADS_ERROR_NT(nt_status); + return status; + } + } + + DEBUG(10, ("cell_do_search: Base = %s, Filter = %s, Scope = %d, GC = %s\n", + search_base, expr, scope, + c->conn->server.gc ? "yes" : "no")); + + /* we try multiple times in case the ADS_STRUCT is bad + and we need to reconnect */ + + while (search_count < MAX_SEARCH_COUNT) { + *msg = NULL; + status = ads_do_search(c->conn, search_base, + scope, expr, attrs, msg); + if (ADS_ERR_OK(status)) { + return status; + } + + + DEBUG(5, ("cell_do_search: search[%d] failed (%s)\n", + search_count, ads_errstr(status))); + + search_count++; + + /* Houston, we have a problem */ + + if (status.error_type == ENUM_ADS_ERROR_LDAP) { + switch (status.err.rc) { + case LDAP_TIMELIMIT_EXCEEDED: + case LDAP_TIMEOUT: + case -1: /* we get this error if we cannot contact + the LDAP server */ + nt_status = cell_connect(c); + if (!NT_STATUS_IS_OK(nt_status)) { + status = ADS_ERROR_NT(nt_status); + return status; + } + break; + default: + /* we're all done here */ + return status; + } + } + } + + DEBUG(5, ("cell_do_search: exceeded maximum search count!\n")); + + return ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL); +} diff --git a/source3/winbindd/idmap_adex/provider_unified.c b/source3/winbindd/idmap_adex/provider_unified.c new file mode 100644 index 0000000000..f18534797e --- /dev/null +++ b/source3/winbindd/idmap_adex/provider_unified.c @@ -0,0 +1,1180 @@ +/* + * idmap_adex + * + * Provider for RFC2307 and SFU AD Forests + * + * Copyright (C) Gerald (Jerry) Carter 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 + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include "includes.h" +#include "idmap_adex.h" + +#undef DBGC_CLASS +#define DBGC_CLASS DBGC_IDMAP + +/* Information needed by the LDAP search filters */ + +enum filterType { SidFilter, IdFilter, AliasFilter }; + +struct lwcell_filter +{ + enum filterType ftype; + bool use2307; + union { + DOM_SID sid; + struct { + uint32_t id; + enum id_type type; + } id; + fstring alias; + } filter; +}; + +/******************************************************************** + *******************************************************************/ + +static char* build_id_filter(uint32_t id, + enum id_type type, + uint32_t search_flags) +{ + char *filter = NULL; + char *oc_filter, *attr_filter; + NTSTATUS nt_status; + TALLOC_CTX *frame = talloc_stackframe(); + bool use2307 = ((search_flags & LWCELL_FLAG_USE_RFC2307_ATTRS) + == LWCELL_FLAG_USE_RFC2307_ATTRS); + bool use_gc = ((search_flags & LWCELL_FLAG_SEARCH_FOREST) + == LWCELL_FLAG_SEARCH_FOREST); + const char *oc; + + /* Construct search filter for objectclass and attributes */ + + switch (type) { + case ID_TYPE_UID: + oc = ADEX_OC_USER; + if (use2307) { + oc = ADEX_OC_POSIX_USER; + if (use_gc) { + oc = AD_USER; + } + } + oc_filter = talloc_asprintf(frame, "objectclass=%s", oc); + attr_filter = talloc_asprintf(frame, "%s=%u", + ADEX_ATTR_UIDNUM, id); + break; + + case ID_TYPE_GID: + oc = ADEX_OC_GROUP; + if (use2307) { + oc = ADEX_OC_POSIX_GROUP; + if (use_gc) { + oc = AD_GROUP; + } + } + oc_filter = talloc_asprintf(frame, "objectclass=%s", oc); + attr_filter = talloc_asprintf(frame, "%s=%u", + ADEX_ATTR_GIDNUM, id); + break; + default: + return NULL; + } + + BAIL_ON_PTR_ERROR(oc_filter, nt_status); + BAIL_ON_PTR_ERROR(attr_filter, nt_status); + + /* Use "keywords=%s" for non-schema cells */ + + if (use2307) { + filter = talloc_asprintf(frame, "(&(%s)(%s))", + oc_filter, attr_filter); + } else { + filter = talloc_asprintf(frame, "(&(keywords=%s)(keywords=%s))", + oc_filter, attr_filter); + } + + talloc_destroy(oc_filter); + talloc_destroy(attr_filter); + +done: + /* Don't destroy the stackframe CTX since we are returning + memory from it */ + + return filter; +} + +/******************************************************************** + *******************************************************************/ + +static char* build_alias_filter(const char *alias, uint32_t search_flags) +{ + char *filter = NULL; + char *user_attr_filter, *group_attr_filter; + NTSTATUS nt_status; + TALLOC_CTX *frame = talloc_stackframe(); + bool use2307 = ((search_flags & LWCELL_FLAG_USE_RFC2307_ATTRS) + == LWCELL_FLAG_USE_RFC2307_ATTRS); + bool search_forest = ((search_flags & LWCELL_FLAG_SEARCH_FOREST) + == LWCELL_FLAG_SEARCH_FOREST); + + /* Construct search filter for objectclass and attributes */ + + user_attr_filter = talloc_asprintf(frame, "%s=%s", + ADEX_ATTR_UID, alias); + group_attr_filter = talloc_asprintf(frame, "%s=%s", + ADEX_ATTR_DISPLAYNAME, alias); + BAIL_ON_PTR_ERROR(user_attr_filter, nt_status); + BAIL_ON_PTR_ERROR(group_attr_filter, nt_status); + + /* Use "keywords=%s" for non-schema cells */ + + if (use2307) { + filter = talloc_asprintf(frame, + "(|(&(%s)(objectclass=%s))(&(%s)(objectclass=%s)))", + user_attr_filter, + search_forest ? AD_USER : ADEX_OC_POSIX_USER, + group_attr_filter, + search_forest ? AD_GROUP : ADEX_OC_POSIX_GROUP); + } else { + filter = talloc_asprintf(frame, + "(|(keywords=%s)(keywords=%s))", + user_attr_filter, + group_attr_filter); + } + + talloc_destroy(user_attr_filter); + talloc_destroy(group_attr_filter); + +done: + /* Don't destroy the stackframe CTX since we are returning + memory from it */ + + return filter; +} + + +/******************************************************************** + *******************************************************************/ + +static NTSTATUS search_cell(struct likewise_cell *c, + LDAPMessage **msg, + const struct lwcell_filter *fdata) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + TALLOC_CTX* frame = talloc_stackframe(); + char *filter = NULL; + const char *base = NULL; + ADS_STATUS ads_status = ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL); + const char *attrs[] = { "*", NULL }; + int count; + char *sid_str; + + /* get the filter and other search parameters */ + + switch (fdata->ftype) { + case SidFilter: + sid_str = sid_string_talloc(frame, &fdata->filter.sid); + BAIL_ON_PTR_ERROR(sid_str, nt_status); + + filter = talloc_asprintf(frame, "(keywords=backLink=%s)", + sid_str); + break; + case IdFilter: + filter = build_id_filter(fdata->filter.id.id, + fdata->filter.id.type, + cell_flags(c)); + break; + case AliasFilter: + filter = build_alias_filter(fdata->filter.alias, + cell_flags(c)); + break; + default: + nt_status = NT_STATUS_INVALID_PARAMETER; + break; + } + BAIL_ON_PTR_ERROR(filter, nt_status); + + base = cell_search_base(c); + BAIL_ON_PTR_ERROR(base, nt_status); + + ads_status = cell_do_search(c, base, LDAP_SCOPE_SUBTREE, + filter, attrs, msg); + + nt_status = ads_ntstatus(ads_status); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + /* Now check that we got only one reply */ + + count = ads_count_replies(c->conn, *msg); + if (count < 1) { + nt_status = NT_STATUS_OBJECT_NAME_NOT_FOUND; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + if ( count > 1) { + nt_status = NT_STATUS_DUPLICATE_NAME; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + +done: + PRINT_NTSTATUS_ERROR(nt_status, "search_cell", 4); + + talloc_destroy(CONST_DISCARD(char*, base)); + talloc_destroy(frame); + + return nt_status; +} + +/******************************************************************** + *******************************************************************/ + +static NTSTATUS search_domain(struct likewise_cell **cell, + LDAPMessage **msg, + const char *dn, + const DOM_SID *sid) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + TALLOC_CTX* frame = talloc_stackframe(); + int count; + + nt_status = dc_search_domains(cell, msg, dn, sid); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + /* Now check that we got only one reply */ + + count = ads_count_replies(cell_connection(*cell), *msg); + if (count < 1) { + nt_status = NT_STATUS_OBJECT_NAME_NOT_FOUND; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + if ( count > 1) { + nt_status = NT_STATUS_DUPLICATE_NAME; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + +done: + PRINT_NTSTATUS_ERROR(nt_status, "search_domain", 4); + talloc_destroy(frame); + + return nt_status; +} + + +/******************************************************************** + Check that a DN is within the forest scope. + *******************************************************************/ + +static bool check_forest_scope(const char *dn) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + TALLOC_CTX *frame = talloc_stackframe(); + char *p = NULL; + char *q = NULL; + char *dns_domain = NULL; + struct winbindd_tdc_domain *domain; + + /* If the DN does *not* contain "$LikewiseIdentityCell", + assume this is a schema mode forest and it is in the + forest scope by definition. */ + + if ((p = strstr_m(dn, ADEX_CELL_RDN)) == NULL) { + nt_status = NT_STATUS_OK; + goto done; + } + + /* If this is a non-schema forest, then make sure that the DN + is in the form "...,cn=$LikewiseIdentityCell,DC=..." */ + + if ((q = strchr_m(p, ',')) == NULL) { + nt_status = NT_STATUS_OBJECT_NAME_INVALID; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + q++; + if (StrnCaseCmp(q, "dc=", 3) != 0) { + nt_status = NT_STATUS_OBJECT_PATH_NOT_FOUND; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + + dns_domain = cell_dn_to_dns(q); + BAIL_ON_PTR_ERROR(dns_domain, nt_status); + + domain = wcache_tdc_fetch_domain(frame, dns_domain); + if (!domain) { + nt_status = NT_STATUS_TRUSTED_DOMAIN_FAILURE; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + nt_status = NT_STATUS_OK; + +done: + talloc_destroy(frame); + SAFE_FREE(dns_domain); + + return NT_STATUS_IS_OK(nt_status); +} + + + +/******************************************************************** + Check that only one result was returned within the forest cell + scope. + *******************************************************************/ + +static NTSTATUS check_result_unique_scoped(ADS_STRUCT **ads_list, + LDAPMessage **msg_list, + int num_resp, + char **dn, + DOM_SID *user_sid) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + int i; + ADS_STRUCT *ads = NULL; + LDAPMessage *msg = NULL; + int count = 0; + char *entry_dn = NULL; + TALLOC_CTX *frame = talloc_stackframe(); + + if (!dn || !user_sid) { + nt_status = NT_STATUS_INVALID_PARAMETER; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + *dn = NULL; + + if (!ads_list || !msg_list || (num_resp == 0)) { + nt_status = NT_STATUS_NO_SUCH_FILE; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* Loop over all msgs */ + + for (i=0; i 1) { + nt_status = NT_STATUS_DUPLICATE_NAME; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + ads = ads_list[i]; + msg = e; + *dn = SMB_STRDUP(entry_dn); + BAIL_ON_PTR_ERROR((*dn), nt_status); + } + + e = ads_next_entry(ads_list[i], e); + SAFE_FREE(entry_dn); + } + } + + if (!ads || !msg) { + nt_status = NT_STATUS_OBJECT_NAME_NOT_FOUND; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* If we made is through the loop, then grab the user_sid and + run home to base */ + + /* + Try and get the SID from either objectSid or keywords. + We cannot use pull_sid() here since we want to try + both methods and not only one or the other (and we + have no full likewise_cell struct. + + Fail if both are unavailable + */ + + if (!ads_pull_sid(ads, msg, "objectSid", user_sid)) { + char **keywords; + char *s; + size_t num_lines = 0; + + keywords = ads_pull_strings(ads, frame, msg, "keywords", + &num_lines); + BAIL_ON_PTR_ERROR(keywords, nt_status); + + s = find_attr_string(keywords, num_lines, "backLink"); + if (!s) { + nt_status = NT_STATUS_INTERNAL_DB_CORRUPTION; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + if (!string_to_sid(user_sid, s)) { + nt_status = NT_STATUS_INVALID_SID; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + } + + nt_status = NT_STATUS_OK; + +done: + if (!NT_STATUS_IS_OK(nt_status)) { + SAFE_FREE(*dn); + } + + talloc_destroy(frame); + SAFE_FREE(entry_dn); + + return nt_status; +} + +/******************************************************************** + Search all forests. Each forest can have it's own forest-cell + settings so we have to generate the filter for each search. + We don't use gc_search_all_forests() since we may have a different + schema model in each forest and need to construct the search + filter for each GC search. + *******************************************************************/ + +static NTSTATUS search_forest(struct likewise_cell *forest_cell, + LDAPMessage **msg, + const struct lwcell_filter *fdata) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + TALLOC_CTX *frame = talloc_stackframe(); + char *filter = NULL; + char *dn = NULL; + struct gc_info *gc = NULL; + ADS_STRUCT **ads_list = NULL; + LDAPMessage **msg_list = NULL; + int num_resp = 0; + LDAPMessage *m; + DOM_SID user_sid; + struct likewise_cell *domain_cell = NULL; + + if ((gc = gc_search_start()) == NULL) { + nt_status = NT_STATUS_INVALID_DOMAIN_STATE; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + while (gc) { + char *sid_binstr = NULL; + uint32_t flags = LWCELL_FLAG_SEARCH_FOREST; + + m = NULL; + + flags |= cell_flags(gc->forest_cell); + + switch (fdata->ftype) { + case SidFilter: + sid_binstr = sid_binstring(&fdata->filter.sid); + BAIL_ON_PTR_ERROR(sid_binstr, nt_status); + + filter = talloc_asprintf(frame, "(objectSid=%s)", sid_binstr); + SAFE_FREE(sid_binstr); + break; + case IdFilter: + filter = build_id_filter(fdata->filter.id.id, + fdata->filter.id.type, flags); + break; + case AliasFilter: + filter = build_alias_filter(fdata->filter.alias, flags); + break; + } + + /* First find the sparse object in GC */ + nt_status = gc_search_forest(gc, &m, filter); + if (!NT_STATUS_IS_OK(nt_status)) { + gc = gc->next; + continue; + } + + nt_status = add_ads_result_to_array(cell_connection(gc->forest_cell), + m, &ads_list, &msg_list, + &num_resp); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + gc = gc->next; + } + + /* Uniqueness check across forests */ + + nt_status = check_result_unique_scoped(ads_list, msg_list, num_resp, + &dn, &user_sid); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + nt_status = search_domain(&domain_cell, &m, dn, &user_sid); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + /* Save the connection and results in the return parameters */ + + forest_cell->gc_search_cell = domain_cell; + *msg = m; + +done: + PRINT_NTSTATUS_ERROR(nt_status, "search_forest", 4); + + SAFE_FREE(dn); + + free_result_array(ads_list, msg_list, num_resp); + talloc_destroy(frame); + + return nt_status; +} + +/******************************************************************** + *******************************************************************/ + +static NTSTATUS search_cell_list(struct likewise_cell **c, + LDAPMessage **m, + const struct lwcell_filter *fdata) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + struct likewise_cell *cell = NULL; + LDAPMessage *msg = NULL; + struct likewise_cell *result_cell = NULL; + + if ((cell = cell_list_head()) == NULL) { + nt_status = NT_STATUS_INVALID_SERVER_STATE; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + while (cell) { + /* Clear any previous GC search results */ + + cell->gc_search_cell = NULL; + + if (cell_search_forest(cell)) { + nt_status = search_forest(cell, &msg, fdata); + } else { + nt_status = search_cell(cell, &msg, fdata); + } + + /* Always point to the search result cell. + In forests this might be for another domain + which means the schema model may be different */ + + result_cell = cell->gc_search_cell ? + cell->gc_search_cell : cell; + + /* Check if we are done */ + + if (NT_STATUS_IS_OK(nt_status)) { + break; + } + + /* No luck. Free memory and hit the next cell. + Forest searches always set the gc_search_cell + so give preference to that connection if possible. */ + + ads_msgfree(cell_connection(result_cell), msg); + msg = NULL; + + cell = cell->next; + } + + /* This might be assigning NULL but that is ok as long as we + give back the proper error code */ + + *c = result_cell; + *m = msg; + +done: + PRINT_NTSTATUS_ERROR(nt_status, "search_cell_list", 3); + + return nt_status; +} + +/******************************************************************** + Pull the SID from an object which is always stored in the keywords + attribute as "backLink=S-1-5-21-..." + *******************************************************************/ + +static NTSTATUS pull_sid(struct likewise_cell *c, + LDAPMessage *msg, + DOM_SID *sid) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + TALLOC_CTX *frame = talloc_stackframe(); + ADS_STRUCT *ads = NULL; + + ads = cell_connection(c); + + /* + We have two ways of getting the sid: + (a) from the objectSID in case of a GC search, + (b) from backLink in the case of a cell search. + Pull the keywords attributes and grab the backLink. + */ + + if (!ads_pull_sid(ads, msg, "objectSid", sid)) { + char **keywords; + char *s; + size_t num_lines = 0; + + keywords = ads_pull_strings(ads, frame, msg, + "keywords", &num_lines); + BAIL_ON_PTR_ERROR(keywords, nt_status); + + s = find_attr_string(keywords, num_lines, "backLink"); + if (!s) { + nt_status = NT_STATUS_INTERNAL_DB_CORRUPTION; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + if (!string_to_sid(sid, s)) { + nt_status = NT_STATUS_INVALID_SID; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + } + + nt_status = NT_STATUS_OK; + +done: + talloc_destroy(frame); + + return nt_status; +} + +/******************************************************************** + *******************************************************************/ + +static NTSTATUS get_object_type(struct likewise_cell *c, + LDAPMessage *msg, + enum id_type *type) +{ + TALLOC_CTX *ctx = talloc_stackframe(); + char **oc_list = NULL; + NTSTATUS nt_status = NT_STATUS_OK; + size_t list_size = 0; + char *s = NULL; + ADS_STRUCT *ads = NULL; + + ads = cell_connection(c); + + /* Deal with RFC 2307 support first */ + + if (cell_flags(c) & LWCELL_FLAG_USE_RFC2307_ATTRS) { + oc_list = ads_pull_strings(ads, ctx, msg, + "objectClass", &list_size); + if (!oc_list) { + nt_status = NT_STATUS_INTERNAL_DB_CORRUPTION; + goto done; + } + + /* Check for posix classes and AD classes */ + + if (is_object_class(oc_list, list_size, ADEX_OC_POSIX_USER) + || is_object_class(oc_list, list_size, AD_USER)) { + *type = ID_TYPE_UID; + } else if (is_object_class(oc_list, list_size, ADEX_OC_POSIX_GROUP) + || is_object_class(oc_list, list_size, AD_GROUP)) { + *type = ID_TYPE_GID; + } else { + *type = ID_TYPE_NOT_SPECIFIED; + nt_status = NT_STATUS_INVALID_PARAMETER; + } + } else { + /* Default to non-schema mode */ + + oc_list = ads_pull_strings(ads, ctx, msg, + "keywords", &list_size); + if (!oc_list) { + nt_status = NT_STATUS_INTERNAL_DB_CORRUPTION; + goto done; + } + + s = find_attr_string(oc_list, list_size, "objectClass"); + if (!s) { + nt_status = NT_STATUS_INTERNAL_DB_CORRUPTION; + goto done; + } + + if (strequal(s, ADEX_OC_USER)) { + *type = ID_TYPE_UID; + } else if (strequal(s, ADEX_OC_GROUP)) { + *type = ID_TYPE_GID; + } else { + *type = ID_TYPE_NOT_SPECIFIED; + nt_status = NT_STATUS_INVALID_PARAMETER; + } + } + + nt_status = NT_STATUS_OK; + +done: + talloc_destroy(ctx); + + return nt_status; +} + +/******************************************************************** + Pull an attribute uint32_t value + *******************************************************************/ + +static NTSTATUS get_object_uint32(struct likewise_cell *c, + LDAPMessage *msg, + const char *attrib, + uint32_t *x) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + char **keywords = NULL; + size_t list_size = 0; + TALLOC_CTX *frame = talloc_stackframe(); + ADS_STRUCT *ads = NULL; + + ads = cell_connection(c); + + /* Deal with RFC2307 schema */ + + if (cell_flags(c) & LWCELL_FLAG_USE_RFC2307_ATTRS) { + if (!ads_pull_uint32(ads, msg, attrib, x)) { + nt_status = NT_STATUS_OBJECT_NAME_NOT_FOUND; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + } else { + /* Non-schema mode */ + char *s = NULL; + uint32_t num; + + keywords = ads_pull_strings(ads, frame, msg, "keywords", + &list_size); + BAIL_ON_PTR_ERROR(keywords, nt_status); + + s = find_attr_string(keywords, list_size, attrib); + if (!s) { + nt_status = NT_STATUS_OBJECT_NAME_NOT_FOUND; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + num = strtoll(s, NULL, 10); + if (errno == ERANGE) { + nt_status = NT_STATUS_OBJECT_NAME_NOT_FOUND; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + *x = num; + } + + nt_status = NT_STATUS_OK; + +done: + talloc_destroy(frame); + + return nt_status; +} + +/******************************************************************** + *******************************************************************/ + +static NTSTATUS get_object_id(struct likewise_cell *c, + LDAPMessage *msg, + enum id_type type, + uint32_t *id) +{ + NTSTATUS nt_status = NT_STATUS_OK; + const char *id_attr; + + /* Figure out which attribute we need to pull */ + + switch (type) { + case ID_TYPE_UID: + id_attr = ADEX_ATTR_UIDNUM; + break; + case ID_TYPE_GID: + id_attr = ADEX_ATTR_GIDNUM; + break; + default: + nt_status = NT_STATUS_INVALID_PARAMETER; + BAIL_ON_NTSTATUS_ERROR(nt_status); + break; + } + + nt_status = get_object_uint32(c, msg, id_attr, id); + BAIL_ON_NTSTATUS_ERROR(nt_status); + +done: + return nt_status; +} + +/******************************************************************** + Pull the uid/gid and type from an object. This differs depending on + the cell flags. + *******************************************************************/ + +static NTSTATUS pull_id(struct likewise_cell *c, + LDAPMessage *msg, + uint32_t *id, + enum id_type *type) +{ + NTSTATUS nt_status; + + nt_status = get_object_type(c, msg, type); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + nt_status = get_object_id(c, msg, *type, id); + BAIL_ON_NTSTATUS_ERROR(nt_status); + +done: + return nt_status; +} + +/******************************************************************** + Pull an attribute string value + *******************************************************************/ + +static NTSTATUS get_object_string(struct likewise_cell *c, + LDAPMessage *msg, + TALLOC_CTX *ctx, + const char *attrib, + char **string) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + char **keywords = NULL; + size_t list_size = 0; + TALLOC_CTX *frame = talloc_stackframe(); + ADS_STRUCT *ads = NULL; + + *string = NULL; + + ads = cell_connection(c); + + /* Deal with RFC2307 schema */ + + if (cell_flags(c) & LWCELL_FLAG_USE_RFC2307_ATTRS) { + *string = ads_pull_string(ads, ctx, msg, attrib); + } else { + /* Non-schema mode */ + + char *s = NULL; + + keywords = ads_pull_strings(ads, frame, msg, + "keywords", &list_size); + if (!keywords) { + nt_status = NT_STATUS_NO_MEMORY; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + s = find_attr_string(keywords, list_size, attrib); + if (s) { + *string = talloc_strdup(ctx, s); + } + } + + if (!*string) { + nt_status = NT_STATUS_OBJECT_NAME_NOT_FOUND; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + nt_status = NT_STATUS_OK; + +done: + talloc_destroy(frame); + + return nt_status; +} + +/******************************************************************** + Pull the struct passwd fields for a user + *******************************************************************/ + +static NTSTATUS pull_nss_info(struct likewise_cell *c, + LDAPMessage *msg, + TALLOC_CTX *ctx, + char **homedir, + char **shell, + char **gecos, + gid_t *p_gid) +{ + NTSTATUS nt_status; + + nt_status = get_object_string(c, msg, ctx, ADEX_ATTR_HOMEDIR, homedir); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + nt_status = get_object_string(c, msg, ctx, ADEX_ATTR_SHELL, shell); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + nt_status = get_object_string(c, msg, ctx, ADEX_ATTR_GECOS, gecos); + /* Gecos is often not set so ignore failures */ + + nt_status = get_object_uint32(c, msg, ADEX_ATTR_GIDNUM, p_gid); + BAIL_ON_NTSTATUS_ERROR(nt_status); + +done: + return nt_status; +} + +/******************************************************************** + Pull the struct passwd fields for a user + *******************************************************************/ + +static NTSTATUS pull_alias(struct likewise_cell *c, + LDAPMessage *msg, + TALLOC_CTX *ctx, + char **alias) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + enum id_type type; + const char *attr = NULL; + + /* Figure out if this is a user or a group */ + + nt_status = get_object_type(c, msg, &type); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + switch (type) { + case ID_TYPE_UID: + attr = ADEX_ATTR_UID; + break; + case ID_TYPE_GID: + /* What is the group attr for RFC2307 Forests? */ + attr = ADEX_ATTR_DISPLAYNAME; + break; + default: + nt_status = NT_STATUS_INVALID_PARAMETER; + BAIL_ON_NTSTATUS_ERROR(nt_status); + break; + } + + nt_status = get_object_string(c, msg, ctx, attr, alias); + BAIL_ON_NTSTATUS_ERROR(nt_status); + +done: + return nt_status; +} + +/******************************************************************** + *******************************************************************/ + +static NTSTATUS _ccp_get_sid_from_id(DOM_SID * sid, + uint32_t id, enum id_type type) +{ + struct likewise_cell *cell = NULL; + LDAPMessage *msg = NULL; + NTSTATUS nt_status; + struct lwcell_filter filter; + + filter.ftype = IdFilter; + filter.filter.id.id = id; + filter.filter.id.type = type; + + nt_status = search_cell_list(&cell, &msg, &filter); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + nt_status = pull_sid(cell, msg, sid); + BAIL_ON_NTSTATUS_ERROR(nt_status); + +done: + ads_msgfree(cell->conn, msg); + + return nt_status; +} + +/******************************************************************** + *******************************************************************/ + +static NTSTATUS _ccp_get_id_from_sid(uint32_t * id, + enum id_type *type, + const DOM_SID * sid) +{ + struct likewise_cell *cell = NULL; + LDAPMessage *msg = NULL; + NTSTATUS nt_status; + struct lwcell_filter filter; + + filter.ftype = SidFilter; + sid_copy(&filter.filter.sid, sid); + + nt_status = search_cell_list(&cell, &msg, &filter); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + nt_status = pull_id(cell, msg, id, type); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + if (*id < min_id_value()) { + nt_status = NT_STATUS_INVALID_PARAMETER; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + +done: + ads_msgfree(cell->conn, msg); + + return nt_status; +} + +/******************************************************************** + *******************************************************************/ + +static NTSTATUS _ccp_nss_get_info(const DOM_SID * sid, + TALLOC_CTX * ctx, + char **homedir, + char **shell, + char **gecos, gid_t * p_gid) +{ + struct likewise_cell *cell = NULL; + LDAPMessage *msg = NULL; + NTSTATUS nt_status; + struct lwcell_filter filter; + enum id_type type; + + filter.ftype = SidFilter; + sid_copy(&filter.filter.sid, sid); + + nt_status = search_cell_list(&cell, &msg, &filter); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + nt_status = get_object_type(cell, msg, &type); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + if (type != ID_TYPE_UID) { + nt_status = NT_STATUS_NO_SUCH_USER; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + nt_status = pull_nss_info(cell, msg, ctx, homedir, shell, gecos, + (uint32_t*) p_gid); + BAIL_ON_NTSTATUS_ERROR(nt_status); + +done: + ads_msgfree(cell->conn, msg); + + return nt_status; +} + +/********************************************************************** + *********************************************************************/ + +static NTSTATUS _ccp_map_to_alias(TALLOC_CTX *ctx, + const char *domain, + const char *name, char **alias) +{ + TALLOC_CTX *frame = talloc_stackframe(); + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + DOM_SID sid; + struct likewise_cell *cell = NULL; + LDAPMessage *msg = NULL; + struct lwcell_filter filter; + enum lsa_SidType sid_type; + + /* Convert the name to a SID */ + + nt_status = gc_name_to_sid(domain, name, &sid, &sid_type); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + /* Find the user/group */ + + filter.ftype = SidFilter; + sid_copy(&filter.filter.sid, &sid); + + nt_status = search_cell_list(&cell, &msg, &filter); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + /* Pull the alias and return */ + + nt_status = pull_alias(cell, msg, ctx, alias); + BAIL_ON_NTSTATUS_ERROR(nt_status); + +done: + PRINT_NTSTATUS_ERROR(nt_status, "map_to_alias", 3); + + talloc_destroy(frame); + ads_msgfree(cell_connection(cell), msg); + + return nt_status; +} + +/********************************************************************** + Map from an alias name to the canonical, qualified name. + Ensure that the alias is only pull from the closest in which + the user or gorup is enabled in + *********************************************************************/ + +static NTSTATUS _ccp_map_from_alias(TALLOC_CTX *mem_ctx, + const char *domain, + const char *alias, char **name) +{ + TALLOC_CTX *frame = talloc_stackframe(); + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + DOM_SID sid; + struct likewise_cell *cell_alias = NULL; + LDAPMessage *msg_alias = NULL; + struct likewise_cell *cell_sid = NULL; + LDAPMessage *msg_sid = NULL; + struct lwcell_filter filter; + char *canonical_name = NULL; + enum lsa_SidType type; + + /* Find the user/group */ + + filter.ftype = AliasFilter; + fstrcpy(filter.filter.alias, alias); + + nt_status = search_cell_list(&cell_alias, &msg_alias, &filter); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + nt_status = pull_sid(cell_alias, msg_alias, &sid); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + /* Now search again for the SID according to the cell list. + Verify that the cell of both search results is the same + so that we only match an alias from the closest cell + in which a user/group has been instantied. */ + + filter.ftype = SidFilter; + sid_copy(&filter.filter.sid, &sid); + + nt_status = search_cell_list(&cell_sid, &msg_sid, &filter); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + if (cell_alias != cell_sid) { + nt_status = NT_STATUS_OBJECT_PATH_NOT_FOUND; + BAIL_ON_NTSTATUS_ERROR(nt_status); + } + + /* Finally do the GC sid/name conversion */ + + nt_status = gc_sid_to_name(&sid, &canonical_name, &type); + BAIL_ON_NTSTATUS_ERROR(nt_status); + + *name = talloc_strdup(mem_ctx, canonical_name); + BAIL_ON_PTR_ERROR((*name), nt_status); + + nt_status = NT_STATUS_OK; + +done: + PRINT_NTSTATUS_ERROR(nt_status, "map_from_alias", 3); + + ads_msgfree(cell_connection(cell_alias), msg_alias); + ads_msgfree(cell_connection(cell_sid), msg_sid); + + SAFE_FREE(canonical_name); + + talloc_destroy(frame); + + return nt_status; +} + +/******************************************************************** + *******************************************************************/ + +struct cell_provider_api ccp_unified = { + .get_sid_from_id = _ccp_get_sid_from_id, + .get_id_from_sid = _ccp_get_id_from_sid, + .get_nss_info = _ccp_nss_get_info, + .map_to_alias = _ccp_map_to_alias, + .map_from_alias = _ccp_map_from_alias +}; -- cgit From 3b5060fdbaee5ffdfcb304179772d5e89dc8cff0 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Mon, 22 Sep 2008 16:32:04 -0700 Subject: Explain why we use signing for DCs, but not file servers --- source4/smb_server/smb/signing.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/source4/smb_server/smb/signing.c b/source4/smb_server/smb/signing.c index ee4531c8f6..21dc99b165 100644 --- a/source4/smb_server/smb/signing.c +++ b/source4/smb_server/smb/signing.c @@ -118,10 +118,19 @@ bool smbsrv_init_signing(struct smbsrv_connection *smb_conn) smb_conn->signing.mandatory_signing = true; break; case SMB_SIGNING_AUTO: + /* If we are a domain controller, SMB signing is + * really important, as it can prevent a number of + * attacks on communications between us and the + * clients */ + if (lp_server_role(smb_conn->lp_ctx) == ROLE_DOMAIN_CONTROLLER) { smb_conn->signing.allow_smb_signing = true; smb_conn->signing.mandatory_signing = true; } else { + /* However, it really sucks (no sendfile, CPU + * overhead) performance-wise when used on a + * file server, so disable it by default (auto + * is the default) on non-DCs */ smb_conn->signing.allow_smb_signing = false; } break; -- cgit From 6660ac5d0ab882e1fd70a72af96b1b1e815b4b14 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Tue, 23 Sep 2008 01:24:56 +0200 Subject: Fix make pch in the merged build --- source3/configure.in | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source3/configure.in b/source3/configure.in index d1000d9a52..f23f6b55be 100644 --- a/source3/configure.in +++ b/source3/configure.in @@ -6272,8 +6272,10 @@ fi SMBD_LIBS="$samba_dmapi_libs" AC_SUBST(SMBD_LIBS) +CFLAGS="${CFLAGS} \$(FLAGS)" + if test x$MERGED_BUILD != x1; then - CFLAGS="${CFLAGS} \$(FLAGS) -D_SAMBA_BUILD_=3" + CFLAGS="${CFLAGS} -D_SAMBA_BUILD_=3" fi AC_OUTPUT(Makefile -- cgit From aaa45c832596d8f1b75f09f1de8fbee7483f6977 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Mon, 22 Sep 2008 17:24:57 -0700 Subject: Remove unused variable --- source4/torture/rpc/remote_pac.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/source4/torture/rpc/remote_pac.c b/source4/torture/rpc/remote_pac.c index b32881cc69..25368d239a 100644 --- a/source4/torture/rpc/remote_pac.c +++ b/source4/torture/rpc/remote_pac.c @@ -68,8 +68,6 @@ static bool test_PACVerify(struct torture_context *tctx, TALLOC_CTX *tmp_ctx = talloc_new(tctx); - int i; - torture_assert(tctx, tmp_ctx != NULL, "talloc_new() failed"); if (!test_SetupCredentials2(p, tctx, NETLOGON_NEG_AUTH2_ADS_FLAGS, -- cgit From c39d1b829b02d275ea1052afec58ab40f22267a3 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Mon, 22 Sep 2008 17:50:43 -0700 Subject: Remove unused parameter from decode_pw_buffer and fail on invalid UTF-16 input The input checking is important, as otherwise we could set the wrong password. Andrew Bartlett --- source4/libcli/auth/smbencrypt.c | 14 +++++++++----- source4/rpc_server/netlogon/dcerpc_netlogon.c | 3 +-- source4/rpc_server/samr/samr_password.c | 10 ++++------ 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/source4/libcli/auth/smbencrypt.c b/source4/libcli/auth/smbencrypt.c index 7de9627302..b50f003b91 100644 --- a/source4/libcli/auth/smbencrypt.c +++ b/source4/libcli/auth/smbencrypt.c @@ -497,10 +497,10 @@ bool encode_pw_buffer(uint8_t buffer[516], const char *password, int string_flag returned password including termination. ************************************************************/ bool decode_pw_buffer(uint8_t in_buffer[516], char *new_pwrd, - int new_pwrd_size, uint32_t *new_pw_len, - int string_flags) + int new_pwrd_size, int string_flags) { int byte_len=0; + ssize_t converted_pw_len; /* the incoming buffer can be any alignment. */ string_flags |= STR_NOALIGN; @@ -526,13 +526,17 @@ bool decode_pw_buffer(uint8_t in_buffer[516], char *new_pwrd, } /* decode into the return buffer. Buffer length supplied */ - *new_pw_len = pull_string(lp_iconv_convenience(global_loadparm), new_pwrd, &in_buffer[512 - byte_len], new_pwrd_size, + converted_pw_len = pull_string(lp_iconv_convenience(global_loadparm), new_pwrd, &in_buffer[512 - byte_len], new_pwrd_size, byte_len, string_flags); + if (converted_pw_len == -1) { + return false; + } + #ifdef DEBUG_PASSWORD DEBUG(100,("decode_pw_buffer: new_pwrd: ")); - dump_data(100, (const uint8_t *)new_pwrd, *new_pw_len); - DEBUG(100,("multibyte len:%d\n", *new_pw_len)); + dump_data(100, (const uint8_t *)new_pwrd, converted_pw_len); + DEBUG(100,("multibyte len:%d\n", converted_pw_len)); DEBUG(100,("original char len:%d\n", byte_len/2)); #endif diff --git a/source4/rpc_server/netlogon/dcerpc_netlogon.c b/source4/rpc_server/netlogon/dcerpc_netlogon.c index 6f4287f9d8..cceb2a62ac 100644 --- a/source4/rpc_server/netlogon/dcerpc_netlogon.c +++ b/source4/rpc_server/netlogon/dcerpc_netlogon.c @@ -337,7 +337,6 @@ static NTSTATUS dcesrv_netr_ServerPasswordSet2(struct dcesrv_call_state *dce_cal struct ldb_context *sam_ctx; NTSTATUS nt_status; char new_pass[512]; - uint32_t new_pass_len; bool ret; struct samr_CryptPassword password_buf; @@ -358,7 +357,7 @@ static NTSTATUS dcesrv_netr_ServerPasswordSet2(struct dcesrv_call_state *dce_cal creds_arcfour_crypt(creds, password_buf.data, 516); ret = decode_pw_buffer(password_buf.data, new_pass, sizeof(new_pass), - &new_pass_len, STR_UNICODE); + STR_UNICODE); if (!ret) { DEBUG(3,("netr_ServerPasswordSet2: failed to decode password buffer\n")); return NT_STATUS_ACCESS_DENIED; diff --git a/source4/rpc_server/samr/samr_password.c b/source4/rpc_server/samr/samr_password.c index b78a9ceaa7..5b8e92583b 100644 --- a/source4/rpc_server/samr/samr_password.c +++ b/source4/rpc_server/samr/samr_password.c @@ -243,7 +243,7 @@ NTSTATUS dcesrv_samr_OemChangePasswordUser2(struct dcesrv_call_state *dce_call, data_blob_free(&lm_pwd_blob); if (!decode_pw_buffer(pwbuf->data, new_pass, sizeof(new_pass), - &new_pass_len, STR_ASCII)) { + STR_ASCII)) { ldb_transaction_cancel(sam_ctx); DEBUG(3,("samr: failed to decode password buffer\n")); return NT_STATUS_WRONG_PASSWORD; @@ -321,7 +321,6 @@ NTSTATUS dcesrv_samr_ChangePasswordUser3(struct dcesrv_call_state *dce_call, { NTSTATUS status; char new_pass[512]; - uint32_t new_pass_len; struct ldb_context *sam_ctx = NULL; struct ldb_dn *user_dn; int ret; @@ -386,7 +385,7 @@ NTSTATUS dcesrv_samr_ChangePasswordUser3(struct dcesrv_call_state *dce_call, data_blob_free(&nt_pwd_blob); if (!decode_pw_buffer(r->in.nt_password->data, new_pass, sizeof(new_pass), - &new_pass_len, STR_UNICODE)) { + STR_UNICODE)) { DEBUG(3,("samr: failed to decode password buffer\n")); status = NT_STATUS_WRONG_PASSWORD; goto failed; @@ -519,7 +518,6 @@ NTSTATUS samr_set_password(struct dcesrv_call_state *dce_call, { NTSTATUS nt_status; char new_pass[512]; - uint32_t new_pass_len; DATA_BLOB session_key = data_blob(NULL, 0); nt_status = dcesrv_fetch_session_key(dce_call->conn, &session_key); @@ -530,7 +528,7 @@ NTSTATUS samr_set_password(struct dcesrv_call_state *dce_call, arcfour_crypt_blob(pwbuf->data, 516, &session_key); if (!decode_pw_buffer(pwbuf->data, new_pass, sizeof(new_pass), - &new_pass_len, STR_UNICODE)) { + STR_UNICODE)) { DEBUG(3,("samr: failed to decode password buffer\n")); return NT_STATUS_WRONG_PASSWORD; } @@ -583,7 +581,7 @@ NTSTATUS samr_set_password_ex(struct dcesrv_call_state *dce_call, arcfour_crypt_blob(pwbuf->data, 516, &co_session_key); if (!decode_pw_buffer(pwbuf->data, new_pass, sizeof(new_pass), - &new_pass_len, STR_UNICODE)) { + STR_UNICODE)) { DEBUG(3,("samr: failed to decode password buffer\n")); return NT_STATUS_WRONG_PASSWORD; } -- cgit From f4e212323fb7ba2bd226194287602210aa9590ec Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 23 Sep 2008 12:09:56 +1000 Subject: added some debug code --- source4/ntvfs/ntvfs_generic.c | 2 ++ source4/ntvfs/posix/pvfs_open.c | 2 ++ source4/ntvfs/posix/pvfs_xattr.c | 2 +- 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/source4/ntvfs/ntvfs_generic.c b/source4/ntvfs/ntvfs_generic.c index c34bb7125e..554d5c5aef 100644 --- a/source4/ntvfs/ntvfs_generic.c +++ b/source4/ntvfs/ntvfs_generic.c @@ -533,6 +533,8 @@ NTSTATUS ntvfs_map_open(struct ntvfs_module_context *ntvfs, /* we need to check these bits before we check the private mask */ if (io2->generic.in.create_options & SMB2_CREATE_OPTIONS_NOT_SUPPORTED_MASK) { + DEBUG(2,(__location__ " create_options 0x%x not supported\n", + io2->generic.in.create_options)); status = NT_STATUS_NOT_SUPPORTED; break; } diff --git a/source4/ntvfs/posix/pvfs_open.c b/source4/ntvfs/posix/pvfs_open.c index c127885a68..8dbc674241 100644 --- a/source4/ntvfs/posix/pvfs_open.c +++ b/source4/ntvfs/posix/pvfs_open.c @@ -1216,6 +1216,8 @@ NTSTATUS pvfs_open(struct ntvfs_module_context *ntvfs, create_options &= ~create_options_must_ignore_mask; if (create_options & NTCREATEX_OPTIONS_NOT_SUPPORTED_MASK) { + DEBUG(2,(__location__ " create_options 0x%x not supported\n", + create_options)); return NT_STATUS_NOT_SUPPORTED; } diff --git a/source4/ntvfs/posix/pvfs_xattr.c b/source4/ntvfs/posix/pvfs_xattr.c index 3cbbcbe92f..7a2945cd05 100644 --- a/source4/ntvfs/posix/pvfs_xattr.c +++ b/source4/ntvfs/posix/pvfs_xattr.c @@ -50,7 +50,7 @@ static NTSTATUS pull_xattr_blob(struct pvfs_state *pvfs, if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_SUPPORTED)|| NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)|| NT_STATUS_EQUAL(status, NT_STATUS_INVALID_SYSTEM_SERVICE)) { - DEBUG(5,("pvfs_xattr: xattr not supported in filesystem: %s\n", nt_errstr(status))); + DEBUG(2,("pvfs_xattr: xattr not supported in filesystem: %s\n", nt_errstr(status))); pvfs->flags &= ~PVFS_FLAG_XATTR_ENABLE; status = NT_STATUS_NOT_FOUND; } -- cgit From 2b6e139206e5f436dd51437599d0228d8db77a78 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 23 Sep 2008 15:16:46 +1000 Subject: fixed readonly handling in deltree --- source4/libcli/clideltree.c | 17 ++++++++++++++++- source4/libcli/smb2/util.c | 6 ++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/source4/libcli/clideltree.c b/source4/libcli/clideltree.c index 2c306e501e..d59a03f194 100644 --- a/source4/libcli/clideltree.c +++ b/source4/libcli/clideltree.c @@ -84,6 +84,7 @@ int smbcli_deltree(struct smbcli_tree *tree, const char *dname) { char *mask; struct delete_state dstate; + NTSTATUS status; dstate.tree = tree; dstate.total_deleted = 0; @@ -98,6 +99,13 @@ int smbcli_deltree(struct smbcli_tree *tree, const char *dname) NT_STATUS_EQUAL(smbcli_nt_error(tree), NT_STATUS_NO_SUCH_FILE)) { return 0; } + if (NT_STATUS_EQUAL(status, NT_STATUS_CANNOT_DELETE)) { + /* it could be read-only */ + status = smbcli_setatr(tree, dname, FILE_ATTRIBUTE_NORMAL, 0); + if (NT_STATUS_IS_OK(smbcli_unlink(tree, dname))) { + return 1; + } + } asprintf(&mask, "%s\\*", dname); smbcli_unlink(dstate.tree, mask); @@ -105,7 +113,14 @@ int smbcli_deltree(struct smbcli_tree *tree, const char *dname) FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM, delete_fn, &dstate); free(mask); - if (NT_STATUS_IS_ERR(smbcli_rmdir(dstate.tree, dname))) { + + status = smbcli_rmdir(dstate.tree, dname); + if (NT_STATUS_EQUAL(status, NT_STATUS_CANNOT_DELETE)) { + /* it could be read-only */ + status = smbcli_setatr(dstate.tree, dname, FILE_ATTRIBUTE_NORMAL, 0); + status = smbcli_rmdir(dstate.tree, dname); + } + if (NT_STATUS_IS_ERR(status)) { DEBUG(2,("Failed to delete %s - %s\n", dname, smbcli_errstr(dstate.tree))); return -1; diff --git a/source4/libcli/smb2/util.c b/source4/libcli/smb2/util.c index 311cea94a0..b149b3d6ce 100644 --- a/source4/libcli/smb2/util.c +++ b/source4/libcli/smb2/util.c @@ -197,6 +197,12 @@ int smb2_deltree(struct smb2_tree *tree, const char *dname) smb2_util_close(tree, create_parm.out.file.handle); status = smb2_util_rmdir(tree, dname); + if (NT_STATUS_EQUAL(status, NT_STATUS_CANNOT_DELETE)) { + /* it could be read-only */ + status = smb2_util_setatr(tree, dname, FILE_ATTRIBUTE_NORMAL); + status = smb2_util_rmdir(tree, dname); + } + if (NT_STATUS_IS_ERR(status)) { DEBUG(2,("Failed to delete %s - %s\n", dname, nt_errstr(status))); -- cgit From e3a562b1cd63cbd92c231a3e18b9164f42111e95 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 23 Sep 2008 15:20:24 +1000 Subject: fixed a memory error in change notify handling in gentest --- source4/torture/gentest.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/source4/torture/gentest.c b/source4/torture/gentest.c index af5a95e751..1bb7c4debd 100644 --- a/source4/torture/gentest.c +++ b/source4/torture/gentest.c @@ -2907,12 +2907,11 @@ static int run_test(struct event_context *ev, struct loadparm_context *lp_ctx) current_op.opnum = op; current_op.name = gen_ops[which_op].name; current_op.status = NT_STATUS_OK; + talloc_free(current_op.mem_ctx); current_op.mem_ctx = talloc_named(NULL, 0, "%s", current_op.name); ret = gen_ops[which_op].handler(instance); - talloc_free(current_op.mem_ctx); - gen_ops[which_op].count++; if (NT_STATUS_IS_OK(current_op.status)) { gen_ops[which_op].success_count++; -- cgit From 219aa1b4fd2a8b93d5b2e67f26abc7f59fb2e0f2 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 23 Sep 2008 16:45:10 +1000 Subject: added FULL_EA_INFORMATION setea call --- source4/libcli/raw/interfaces.h | 9 +++++++++ source4/libcli/raw/rawsetfileinfo.c | 12 +++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/source4/libcli/raw/interfaces.h b/source4/libcli/raw/interfaces.h index 537041c137..20ed441435 100644 --- a/source4/libcli/raw/interfaces.h +++ b/source4/libcli/raw/interfaces.h @@ -1112,6 +1112,15 @@ union smb_setfileinfo { struct security_descriptor *sd; } in; } set_secdesc; + + /* RAW_SFILEINFO_FULL_EA_INFORMATION */ + struct { + enum smb_setfileinfo_level level; + struct { + union smb_handle_or_path file; + struct smb_ea_list eas; + } in; + } full_ea_information; }; diff --git a/source4/libcli/raw/rawsetfileinfo.c b/source4/libcli/raw/rawsetfileinfo.c index 5a4706778a..f7dfb933f1 100644 --- a/source4/libcli/raw/rawsetfileinfo.c +++ b/source4/libcli/raw/rawsetfileinfo.c @@ -37,7 +37,7 @@ bool smb_raw_setfileinfo_passthru(TALLOC_CTX *mem_ctx, #define NEED_BLOB(n) do { \ *blob = data_blob_talloc(mem_ctx, NULL, n); \ - if (blob->data == NULL) return false; \ + if (blob->data == NULL && n != 0) return false; \ } while (0) switch (level) { @@ -109,6 +109,16 @@ bool smb_raw_setfileinfo_passthru(TALLOC_CTX *mem_ctx, return true; } + case RAW_SFILEINFO_FULL_EA_INFORMATION: + printf("num_eas=%d\n", parms->full_ea_information.in.eas.num_eas); + NEED_BLOB(ea_list_size_chained( + parms->full_ea_information.in.eas.num_eas, + parms->full_ea_information.in.eas.eas, 4)); + ea_put_list_chained(blob->data, + parms->full_ea_information.in.eas.num_eas, + parms->full_ea_information.in.eas.eas, 4); + return true; + /* Unhandled levels */ case RAW_SFILEINFO_PIPE_INFORMATION: case RAW_SFILEINFO_VALID_DATA_INFORMATION: -- cgit From 9cf29abee296ea2fcdf712687a6ce2cf9fd9d74c Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 23 Sep 2008 16:45:55 +1000 Subject: test setinfo FULL_EA_INFORMATION in gentest --- source4/torture/gentest.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/source4/torture/gentest.c b/source4/torture/gentest.c index 1bb7c4debd..176fc035e7 100644 --- a/source4/torture/gentest.c +++ b/source4/torture/gentest.c @@ -2166,6 +2166,9 @@ static void gen_setfileinfo(int instance, union smb_setfileinfo *info) case RAW_SFILEINFO_MODE_INFORMATION: info->mode_information.in.mode = gen_bits_mask(0xFFFFFFFF); break; + case RAW_SFILEINFO_FULL_EA_INFORMATION: + info->full_ea_information.in.eas = gen_ea_list(); + break; case RAW_SFILEINFO_GENERIC: case RAW_SFILEINFO_SEC_DESC: case RAW_SFILEINFO_UNIX_BASIC: @@ -2222,7 +2225,8 @@ static void gen_setfileinfo(int instance, union smb_setfileinfo *info) do { i = gen_int_range(0, num_levels-1); } while (ignore_pattern(levels[i].name)); - + + ZERO_STRUCTP(info); info->generic.level = levels[i].level; switch (info->generic.level) { @@ -2279,6 +2283,9 @@ static void gen_setfileinfo(int instance, union smb_setfileinfo *info) case RAW_SFILEINFO_MODE_INFORMATION: info->mode_information.in.mode = gen_bits_mask(0xFFFFFFFF); break; + case RAW_SFILEINFO_FULL_EA_INFORMATION: + info->full_ea_information.in.eas = gen_ea_list(); + break; case RAW_SFILEINFO_GENERIC: case RAW_SFILEINFO_SEC_DESC: -- cgit From b60d612cdeb7dad7c1e2496c5b1e19abb58da50f Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 08:32:42 +0200 Subject: s4: add talloc_strdup_upper. Guenther --- source4/lib/charset/util_unistr.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/source4/lib/charset/util_unistr.c b/source4/lib/charset/util_unistr.c index 09ec7b0471..a8ff88423a 100644 --- a/source4/lib/charset/util_unistr.c +++ b/source4/lib/charset/util_unistr.c @@ -570,7 +570,13 @@ _PUBLIC_ char *strupper_talloc(TALLOC_CTX *ctx, const char *src) return strupper_talloc_n(ctx, src, src?strlen(src):0); } - +/** + talloc_strdup() a unix string to upper case. +**/ +_PUBLIC_ char *talloc_strdup_upper(TALLOC_CTX *ctx, const char *src) +{ + return strupper_talloc(ctx, src); +} /** Convert a string to lower case. -- cgit From 9216153827f0000cc82cb51adcba722181c94999 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Mon, 22 Sep 2008 22:22:04 +0200 Subject: s4-nbt: remove unrequired include. Guenther --- source4/libcli/nbt/nbtname.c | 1 - 1 file changed, 1 deletion(-) diff --git a/source4/libcli/nbt/nbtname.c b/source4/libcli/nbt/nbtname.c index 97ae2e9d72..67bb4486e5 100644 --- a/source4/libcli/nbt/nbtname.c +++ b/source4/libcli/nbt/nbtname.c @@ -27,7 +27,6 @@ #include "librpc/gen_ndr/ndr_nbt.h" #include "librpc/gen_ndr/ndr_misc.h" #include "system/locale.h" -#include "param/param.h" /* don't allow an unlimited number of name components */ #define MAX_COMPONENTS 10 -- cgit From f093ddbc111ccdfe0995d40d24bed94a3d62deb6 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 02:41:44 +0200 Subject: s3-charset: add smb_iconv_convenience. Guenther --- source3/include/charset.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source3/include/charset.h b/source3/include/charset.h index 4d04b5a1a6..1c2a5fb5f0 100644 --- a/source3/include/charset.h +++ b/source3/include/charset.h @@ -18,6 +18,8 @@ along with this program. If not, see . */ +struct smb_iconv_convenience; + /* this defines the charset types used in samba */ typedef enum {CH_UTF16LE=0, CH_UTF16=0, CH_UNIX=1, CH_DISPLAY=2, CH_DOS=3, CH_UTF8=4, CH_UTF16BE=5} charset_t; -- cgit From 9421ecac33b79dcb56b685c2b17d32cff7524331 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 08:31:34 +0200 Subject: s3-nbt: fix nbt.idl in order to use shared nbt helper. Guenther --- source3/librpc/idl/nbt.idl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source3/librpc/idl/nbt.idl b/source3/librpc/idl/nbt.idl index 654f53c52f..99bffc8755 100644 --- a/source3/librpc/idl/nbt.idl +++ b/source3/librpc/idl/nbt.idl @@ -73,11 +73,11 @@ interface nbt nbt_name_type type; } nbt_name; - typedef [enum16bit] enum { + typedef [public,enum16bit] enum { NBT_QCLASS_IP = 0x01 } nbt_qclass; - typedef [enum16bit] enum { + typedef [public,enum16bit] enum { NBT_QTYPE_ADDRESS = 0x0001, NBT_QTYPE_NAMESERVICE = 0x0002, NBT_QTYPE_NULL = 0x000A, @@ -160,7 +160,7 @@ interface nbt uint8 data[length]; } nbt_rdata_data; - typedef [nodiscriminant] union { + typedef [nodiscriminant,public] union { [case(NBT_QTYPE_NETBIOS)] nbt_rdata_netbios netbios; [case(NBT_QTYPE_STATUS)] nbt_rdata_status status; [default] nbt_rdata_data data; -- cgit From c8858058e93aa5c44df5fd64f2844a34e240a0e9 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 08:58:37 +0200 Subject: s3: re-run make idl. Guenther --- source3/librpc/gen_ndr/nbt.h | 2 +- source3/librpc/gen_ndr/ndr_nbt.c | 12 ++++++------ source3/librpc/gen_ndr/ndr_nbt.h | 6 ++++++ 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/source3/librpc/gen_ndr/nbt.h b/source3/librpc/gen_ndr/nbt.h index 62ad524a91..0943ee1a4d 100644 --- a/source3/librpc/gen_ndr/nbt.h +++ b/source3/librpc/gen_ndr/nbt.h @@ -221,7 +221,7 @@ union nbt_rdata { struct nbt_rdata_netbios netbios;/* [case(NBT_QTYPE_NETBIOS)] */ struct nbt_rdata_status status;/* [case(NBT_QTYPE_STATUS)] */ struct nbt_rdata_data data;/* [default] */ -}/* [nodiscriminant] */; +}/* [nodiscriminant,public] */; struct nbt_res_rec { struct nbt_name name; diff --git a/source3/librpc/gen_ndr/ndr_nbt.c b/source3/librpc/gen_ndr/ndr_nbt.c index 75667183a8..01cccd6742 100644 --- a/source3/librpc/gen_ndr/ndr_nbt.c +++ b/source3/librpc/gen_ndr/ndr_nbt.c @@ -77,13 +77,13 @@ _PUBLIC_ void ndr_print_nbt_name(struct ndr_print *ndr, const char *name, const ndr->depth--; } -static enum ndr_err_code ndr_push_nbt_qclass(struct ndr_push *ndr, int ndr_flags, enum nbt_qclass r) +_PUBLIC_ enum ndr_err_code ndr_push_nbt_qclass(struct ndr_push *ndr, int ndr_flags, enum nbt_qclass r) { NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r)); return NDR_ERR_SUCCESS; } -static enum ndr_err_code ndr_pull_nbt_qclass(struct ndr_pull *ndr, int ndr_flags, enum nbt_qclass *r) +_PUBLIC_ enum ndr_err_code ndr_pull_nbt_qclass(struct ndr_pull *ndr, int ndr_flags, enum nbt_qclass *r) { uint16_t v; NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &v)); @@ -101,13 +101,13 @@ _PUBLIC_ void ndr_print_nbt_qclass(struct ndr_print *ndr, const char *name, enum ndr_print_enum(ndr, name, "ENUM", val, r); } -static enum ndr_err_code ndr_push_nbt_qtype(struct ndr_push *ndr, int ndr_flags, enum nbt_qtype r) +_PUBLIC_ enum ndr_err_code ndr_push_nbt_qtype(struct ndr_push *ndr, int ndr_flags, enum nbt_qtype r) { NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r)); return NDR_ERR_SUCCESS; } -static enum ndr_err_code ndr_pull_nbt_qtype(struct ndr_pull *ndr, int ndr_flags, enum nbt_qtype *r) +_PUBLIC_ enum ndr_err_code ndr_pull_nbt_qtype(struct ndr_pull *ndr, int ndr_flags, enum nbt_qtype *r) { uint16_t v; NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &v)); @@ -496,7 +496,7 @@ _PUBLIC_ void ndr_print_nbt_rdata_data(struct ndr_print *ndr, const char *name, ndr->depth--; } -static enum ndr_err_code ndr_push_nbt_rdata(struct ndr_push *ndr, int ndr_flags, const union nbt_rdata *r) +_PUBLIC_ enum ndr_err_code ndr_push_nbt_rdata(struct ndr_push *ndr, int ndr_flags, const union nbt_rdata *r) { if (ndr_flags & NDR_SCALARS) { int level = ndr_push_get_switch_value(ndr, r); @@ -532,7 +532,7 @@ static enum ndr_err_code ndr_push_nbt_rdata(struct ndr_push *ndr, int ndr_flags, return NDR_ERR_SUCCESS; } -static enum ndr_err_code ndr_pull_nbt_rdata(struct ndr_pull *ndr, int ndr_flags, union nbt_rdata *r) +_PUBLIC_ enum ndr_err_code ndr_pull_nbt_rdata(struct ndr_pull *ndr, int ndr_flags, union nbt_rdata *r) { int level; level = ndr_pull_get_switch_value(ndr, r); diff --git a/source3/librpc/gen_ndr/ndr_nbt.h b/source3/librpc/gen_ndr/ndr_nbt.h index 6e9702d5d5..f6f3e3c899 100644 --- a/source3/librpc/gen_ndr/ndr_nbt.h +++ b/source3/librpc/gen_ndr/ndr_nbt.h @@ -13,7 +13,11 @@ void ndr_print_nbt_name_type(struct ndr_print *ndr, const char *name, enum nbt_n enum ndr_err_code ndr_push_nbt_name(struct ndr_push *ndr, int ndr_flags, const struct nbt_name *r); enum ndr_err_code ndr_pull_nbt_name(struct ndr_pull *ndr, int ndr_flags, struct nbt_name *r); void ndr_print_nbt_name(struct ndr_print *ndr, const char *name, const struct nbt_name *r); +enum ndr_err_code ndr_push_nbt_qclass(struct ndr_push *ndr, int ndr_flags, enum nbt_qclass r); +enum ndr_err_code ndr_pull_nbt_qclass(struct ndr_pull *ndr, int ndr_flags, enum nbt_qclass *r); void ndr_print_nbt_qclass(struct ndr_print *ndr, const char *name, enum nbt_qclass r); +enum ndr_err_code ndr_push_nbt_qtype(struct ndr_push *ndr, int ndr_flags, enum nbt_qtype r); +enum ndr_err_code ndr_pull_nbt_qtype(struct ndr_pull *ndr, int ndr_flags, enum nbt_qtype *r); void ndr_print_nbt_qtype(struct ndr_print *ndr, const char *name, enum nbt_qtype r); void ndr_print_nbt_name_question(struct ndr_print *ndr, const char *name, const struct nbt_name_question *r); void ndr_print_nb_flags(struct ndr_print *ndr, const char *name, uint16_t r); @@ -23,6 +27,8 @@ void ndr_print_nbt_statistics(struct ndr_print *ndr, const char *name, const str void ndr_print_nbt_status_name(struct ndr_print *ndr, const char *name, const struct nbt_status_name *r); void ndr_print_nbt_rdata_status(struct ndr_print *ndr, const char *name, const struct nbt_rdata_status *r); void ndr_print_nbt_rdata_data(struct ndr_print *ndr, const char *name, const struct nbt_rdata_data *r); +enum ndr_err_code ndr_push_nbt_rdata(struct ndr_push *ndr, int ndr_flags, const union nbt_rdata *r); +enum ndr_err_code ndr_pull_nbt_rdata(struct ndr_pull *ndr, int ndr_flags, union nbt_rdata *r); void ndr_print_nbt_rdata(struct ndr_print *ndr, const char *name, const union nbt_rdata *r); void ndr_print_nbt_res_rec(struct ndr_print *ndr, const char *name, const struct nbt_res_rec *r); enum ndr_err_code ndr_push_nbt_name_packet(struct ndr_push *ndr, int ndr_flags, const struct nbt_name_packet *r); -- cgit From c48186f507219e8732f02bdc2f835a7d8d02541c Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 08:09:37 +0200 Subject: s3: use samba4 prototype for ndr_push/pull_struct_blob. Guenther --- source3/include/proto.h | 6 ++---- source3/libads/authdata.c | 14 +++++++------- source3/libads/cldap.c | 2 +- source3/librpc/ndr/ndr.c | 14 ++++++++++---- source3/libsmb/dsgetdcname.c | 4 ++-- source3/libsmb/samlogon_cache.c | 4 ++-- source3/smbd/notify_internal.c | 8 ++++---- source3/winbindd/winbindd_pam.c | 2 +- 8 files changed, 29 insertions(+), 25 deletions(-) diff --git a/source3/include/proto.h b/source3/include/proto.h index 194548c082..ddd3a573f2 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -3960,16 +3960,14 @@ _PUBLIC_ enum ndr_err_code ndr_print_set_switch_value(struct ndr_print *ndr, con _PUBLIC_ uint32_t ndr_push_get_switch_value(struct ndr_push *ndr, const void *p); _PUBLIC_ uint32_t ndr_pull_get_switch_value(struct ndr_pull *ndr, const void *p); _PUBLIC_ uint32_t ndr_print_get_switch_value(struct ndr_print *ndr, const void *p); -_PUBLIC_ enum ndr_err_code ndr_pull_struct_blob(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, void *p, - ndr_pull_flags_fn_t fn); +_PUBLIC_ enum ndr_err_code ndr_pull_struct_blob(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, struct smb_iconv_convenience *iconv_convenience, void *p, ndr_pull_flags_fn_t fn); _PUBLIC_ enum ndr_err_code ndr_pull_struct_blob_all(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, void *p, ndr_pull_flags_fn_t fn); _PUBLIC_ enum ndr_err_code ndr_pull_union_blob(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, void *p, uint32_t level, ndr_pull_flags_fn_t fn); _PUBLIC_ enum ndr_err_code ndr_pull_union_blob_all(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, void *p, uint32_t level, ndr_pull_flags_fn_t fn); -_PUBLIC_ enum ndr_err_code ndr_push_struct_blob(DATA_BLOB *blob, TALLOC_CTX *mem_ctx, const void *p, - ndr_push_flags_fn_t fn); +_PUBLIC_ enum ndr_err_code ndr_push_struct_blob(DATA_BLOB *blob, TALLOC_CTX *mem_ctx, struct smb_iconv_convenience *iconv_convenience, const void *p, ndr_push_flags_fn_t fn); _PUBLIC_ enum ndr_err_code ndr_push_union_blob(DATA_BLOB *blob, TALLOC_CTX *mem_ctx, void *p, uint32_t level, ndr_push_flags_fn_t fn); _PUBLIC_ size_t ndr_size_struct(const void *p, int flags, ndr_push_flags_fn_t push); diff --git a/source3/libads/authdata.c b/source3/libads/authdata.c index 0bde3e6984..40f051c851 100644 --- a/source3/libads/authdata.c +++ b/source3/libads/authdata.c @@ -108,7 +108,7 @@ static krb5_error_code check_pac_checksum(TALLOC_CTX *mem_ctx, } ndr_err = ndr_pull_struct_blob(pac_data_blob, pac_data, - pac_data, + NULL, pac_data, (ndr_pull_flags_fn_t)ndr_pull_PAC_DATA); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { status = ndr_map_error2ntstatus(ndr_err); @@ -124,7 +124,7 @@ static krb5_error_code check_pac_checksum(TALLOC_CTX *mem_ctx, } ndr_err = ndr_pull_struct_blob(pac_data_blob, pac_data_raw, - pac_data_raw, + NULL, pac_data_raw, (ndr_pull_flags_fn_t)ndr_pull_PAC_DATA_RAW); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { status = ndr_map_error2ntstatus(ndr_err); @@ -205,7 +205,7 @@ static krb5_error_code check_pac_checksum(TALLOC_CTX *mem_ctx, /* We find the data blobs above, now we parse them to get at the exact portion we should zero */ ndr_err = ndr_pull_struct_blob(kdc_sig_blob, kdc_sig_wipe, - kdc_sig_wipe, + NULL, kdc_sig_wipe, (ndr_pull_flags_fn_t)ndr_pull_PAC_SIGNATURE_DATA); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { status = ndr_map_error2ntstatus(ndr_err); @@ -215,7 +215,7 @@ static krb5_error_code check_pac_checksum(TALLOC_CTX *mem_ctx, } ndr_err = ndr_pull_struct_blob(srv_sig_blob, srv_sig_wipe, - srv_sig_wipe, + NULL, srv_sig_wipe, (ndr_pull_flags_fn_t)ndr_pull_PAC_SIGNATURE_DATA); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { status = ndr_map_error2ntstatus(ndr_err); @@ -230,7 +230,7 @@ static krb5_error_code check_pac_checksum(TALLOC_CTX *mem_ctx, /* and reencode, back into the same place it came from */ ndr_err = ndr_push_struct_blob(kdc_sig_blob, pac_data_raw, - kdc_sig_wipe, + NULL, kdc_sig_wipe, (ndr_push_flags_fn_t)ndr_push_PAC_SIGNATURE_DATA); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { status = ndr_map_error2ntstatus(ndr_err); @@ -239,7 +239,7 @@ static krb5_error_code check_pac_checksum(TALLOC_CTX *mem_ctx, return status; } ndr_err = ndr_push_struct_blob(srv_sig_blob, pac_data_raw, - srv_sig_wipe, + NULL, srv_sig_wipe, (ndr_push_flags_fn_t)ndr_push_PAC_SIGNATURE_DATA); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { status = ndr_map_error2ntstatus(ndr_err); @@ -250,7 +250,7 @@ static krb5_error_code check_pac_checksum(TALLOC_CTX *mem_ctx, /* push out the whole structure, but now with zero'ed signatures */ ndr_err = ndr_push_struct_blob(&modified_pac_blob, pac_data_raw, - pac_data_raw, + NULL, pac_data_raw, (ndr_push_flags_fn_t)ndr_push_PAC_DATA_RAW); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { status = ndr_map_error2ntstatus(ndr_err); diff --git a/source3/libads/cldap.c b/source3/libads/cldap.c index 11565065af..73b28b523a 100644 --- a/source3/libads/cldap.c +++ b/source3/libads/cldap.c @@ -294,7 +294,7 @@ bool pull_mailslot_cldap_reply(TALLOC_CTX *mem_ctx, uint32_t nt_version_query = ((*nt_version) & 0x0000001f); uint16_t command = 0; - ndr_err = ndr_pull_struct_blob(blob, mem_ctx, &command, + ndr_err = ndr_pull_struct_blob(blob, mem_ctx, NULL, &command, (ndr_pull_flags_fn_t)ndr_pull_uint16); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { return false; diff --git a/source3/librpc/ndr/ndr.c b/source3/librpc/ndr/ndr.c index d94d12e146..624024c94d 100644 --- a/source3/librpc/ndr/ndr.c +++ b/source3/librpc/ndr/ndr.c @@ -803,8 +803,11 @@ _PUBLIC_ uint32_t ndr_print_get_switch_value(struct ndr_print *ndr, const void * /* pull a struct from a blob using NDR */ -_PUBLIC_ enum ndr_err_code ndr_pull_struct_blob(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, void *p, - ndr_pull_flags_fn_t fn) +_PUBLIC_ enum ndr_err_code ndr_pull_struct_blob(const DATA_BLOB *blob, + TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + void *p, + ndr_pull_flags_fn_t fn) { struct ndr_pull *ndr; ndr = ndr_pull_init_blob(blob, mem_ctx); @@ -868,8 +871,11 @@ _PUBLIC_ enum ndr_err_code ndr_pull_union_blob_all(const DATA_BLOB *blob, TALLOC /* push a struct to a blob using NDR */ -_PUBLIC_ enum ndr_err_code ndr_push_struct_blob(DATA_BLOB *blob, TALLOC_CTX *mem_ctx, const void *p, - ndr_push_flags_fn_t fn) +_PUBLIC_ enum ndr_err_code ndr_push_struct_blob(DATA_BLOB *blob, + TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + const void *p, + ndr_push_flags_fn_t fn) { struct ndr_push *ndr; ndr = ndr_push_init_ctx(mem_ctx); diff --git a/source3/libsmb/dsgetdcname.c b/source3/libsmb/dsgetdcname.c index 2a445cbd5a..e822635546 100644 --- a/source3/libsmb/dsgetdcname.c +++ b/source3/libsmb/dsgetdcname.c @@ -331,7 +331,7 @@ static NTSTATUS store_cldap_reply(TALLOC_CTX *mem_ctx, return status; } - ndr_err = ndr_push_struct_blob(&blob, mem_ctx, &logon29, + ndr_err = ndr_push_struct_blob(&blob, mem_ctx, NULL, &logon29, (ndr_push_flags_fn_t)ndr_push_nbt_cldap_netlogon_29); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { return ndr_map_error2ntstatus(ndr_err); @@ -508,7 +508,7 @@ static NTSTATUS dsgetdcname_cache_fetch(TALLOC_CTX *mem_ctx, return NT_STATUS_NO_MEMORY; } - ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &r, + ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, NULL, &r, (ndr_pull_flags_fn_t)ndr_pull_nbt_cldap_netlogon_29); data_blob_free(&blob); diff --git a/source3/libsmb/samlogon_cache.c b/source3/libsmb/samlogon_cache.c index 4abe5bb6de..af4986fa9d 100644 --- a/source3/libsmb/samlogon_cache.c +++ b/source3/libsmb/samlogon_cache.c @@ -141,7 +141,7 @@ bool netsamlogon_cache_store(const char *username, struct netr_SamInfo3 *info3) NDR_PRINT_DEBUG(netsamlogoncache_entry, &r); } - ndr_err = ndr_push_struct_blob(&blob, mem_ctx, &r, + ndr_err = ndr_push_struct_blob(&blob, mem_ctx, NULL, &r, (ndr_push_flags_fn_t)ndr_push_netsamlogoncache_entry); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { DEBUG(0,("netsamlogon_cache_store: failed to push entry to cache\n")); @@ -197,7 +197,7 @@ struct netr_SamInfo3 *netsamlogon_cache_get(TALLOC_CTX *mem_ctx, const DOM_SID * blob = data_blob_const(data.dptr, data.dsize); - ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &r, + ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, NULL, &r, (ndr_pull_flags_fn_t)ndr_pull_netsamlogoncache_entry); if (DEBUGLEVEL >= 10) { diff --git a/source3/smbd/notify_internal.c b/source3/smbd/notify_internal.c index 84b8e1098e..06da717799 100644 --- a/source3/smbd/notify_internal.c +++ b/source3/smbd/notify_internal.c @@ -166,7 +166,7 @@ static NTSTATUS notify_load(struct notify_context *notify, struct db_record *rec status = NT_STATUS_OK; if (blob.length > 0) { enum ndr_err_code ndr_err; - ndr_err = ndr_pull_struct_blob(&blob, notify->array, notify->array, + ndr_err = ndr_pull_struct_blob(&blob, notify->array, NULL, notify->array, (ndr_pull_flags_fn_t)ndr_pull_notify_array); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { status = ndr_map_error2ntstatus(ndr_err); @@ -220,7 +220,7 @@ static NTSTATUS notify_save(struct notify_context *notify, struct db_record *rec tmp_ctx = talloc_new(notify); NT_STATUS_HAVE_NO_MEMORY(tmp_ctx); - ndr_err = ndr_push_struct_blob(&blob, tmp_ctx, notify->array, + ndr_err = ndr_push_struct_blob(&blob, tmp_ctx, NULL, notify->array, (ndr_push_flags_fn_t)ndr_push_notify_array); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { talloc_free(tmp_ctx); @@ -258,7 +258,7 @@ static void notify_handler(struct messaging_context *msg_ctx, void *private_data return; } - ndr_err = ndr_pull_struct_blob(data, tmp_ctx, &ev, + ndr_err = ndr_pull_struct_blob(data, tmp_ctx, NULL, &ev, (ndr_pull_flags_fn_t)ndr_pull_notify_event); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { talloc_free(tmp_ctx); @@ -561,7 +561,7 @@ static NTSTATUS notify_send(struct notify_context *notify, struct notify_entry * tmp_ctx = talloc_new(notify); - ndr_err = ndr_push_struct_blob(&data, tmp_ctx, &ev, + ndr_err = ndr_push_struct_blob(&data, tmp_ctx, NULL, &ev, (ndr_push_flags_fn_t)ndr_push_notify_event); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { talloc_free(tmp_ctx); diff --git a/source3/winbindd/winbindd_pam.c b/source3/winbindd/winbindd_pam.c index d9104ca600..9ff3899661 100644 --- a/source3/winbindd/winbindd_pam.c +++ b/source3/winbindd/winbindd_pam.c @@ -127,7 +127,7 @@ static NTSTATUS append_info3_as_ndr(TALLOC_CTX *mem_ctx, DATA_BLOB blob; enum ndr_err_code ndr_err; - ndr_err = ndr_push_struct_blob(&blob, mem_ctx, info3, + ndr_err = ndr_push_struct_blob(&blob, mem_ctx, NULL, info3, (ndr_push_flags_fn_t)ndr_push_netr_SamInfo3); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { DEBUG(0,("append_info3_as_ndr: failed to append\n")); -- cgit From 13a3971438fb12d60aa0eaf88d22019a5e4f67cd Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 09:02:16 +0200 Subject: s4-nbt: use private_data instead of private. Guenther --- source4/libcli/composite/composite.c | 2 +- source4/libcli/finddcs.c | 2 +- source4/libcli/nbt/libnbt.h | 8 ++++---- source4/libcli/nbt/namerefresh.c | 8 ++++---- source4/libcli/nbt/nameregister.c | 14 +++++++------- source4/libcli/nbt/nbtsocket.c | 2 +- source4/libcli/resolve/nbtlist.c | 4 ++-- source4/nbt_server/defense.c | 2 +- source4/nbt_server/interfaces.c | 2 +- source4/nbt_server/nodestatus.c | 2 +- source4/nbt_server/packet.c | 14 +++++++------- source4/nbt_server/query.c | 2 +- source4/nbt_server/register.c | 4 ++-- source4/nbt_server/wins/wins_dns_proxy.c | 2 +- source4/nbt_server/wins/winsserver.c | 16 ++++++++-------- source4/nbt_server/wins/winswack.c | 8 ++++---- source4/torture/nbt/query.c | 4 ++-- source4/torture/nbt/winsbench.c | 12 ++++++------ source4/torture/nbt/winsreplication.c | 6 +++--- 19 files changed, 57 insertions(+), 57 deletions(-) diff --git a/source4/libcli/composite/composite.c b/source4/libcli/composite/composite.c index 3e3f224f47..91a842706f 100644 --- a/source4/libcli/composite/composite.c +++ b/source4/libcli/composite/composite.c @@ -214,5 +214,5 @@ _PUBLIC_ void composite_continue_nbt(struct composite_context *ctx, { if (composite_nomem(new_req, ctx)) return; new_req->async.fn = continuation; - new_req->async.private = private_data; + new_req->async.private_data = private_data; } diff --git a/source4/libcli/finddcs.c b/source4/libcli/finddcs.c index 56f931ce19..f12f1ac805 100644 --- a/source4/libcli/finddcs.c +++ b/source4/libcli/finddcs.c @@ -217,7 +217,7 @@ static void fallback_node_status(struct finddcs_state *state) static void fallback_node_status_replied(struct nbt_name_request *name_req) { int i; - struct finddcs_state *state = talloc_get_type(name_req->async.private, struct finddcs_state); + struct finddcs_state *state = talloc_get_type(name_req->async.private_data, struct finddcs_state); state->ctx->status = nbt_name_status_recv(name_req, state, &state->node_status); if (!composite_is_ok(state->ctx)) return; diff --git a/source4/libcli/nbt/libnbt.h b/source4/libcli/nbt/libnbt.h index 0b01365510..ff4fe65ac8 100644 --- a/source4/libcli/nbt/libnbt.h +++ b/source4/libcli/nbt/libnbt.h @@ -83,7 +83,7 @@ struct nbt_name_request { /* information on what to do on completion */ struct { void (*fn)(struct nbt_name_request *); - void *private; + void *private_data; } async; }; @@ -113,14 +113,14 @@ struct nbt_name_socket { struct { void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, struct socket_address *); - void *private; + void *private_data; } incoming; /* what to do with unexpected replies */ struct { void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, struct socket_address *); - void *private; + void *private_data; } unexpected; }; @@ -323,7 +323,7 @@ NTSTATUS nbt_name_refresh_recv(struct nbt_name_request *req, NTSTATUS nbt_set_incoming_handler(struct nbt_name_socket *nbtsock, void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, struct socket_address *), - void *private); + void *private_data); NTSTATUS nbt_name_reply_send(struct nbt_name_socket *nbtsock, struct socket_address *dest, struct nbt_name_packet *request); diff --git a/source4/libcli/nbt/namerefresh.c b/source4/libcli/nbt/namerefresh.c index b372e4a3f3..b939c97740 100644 --- a/source4/libcli/nbt/namerefresh.c +++ b/source4/libcli/nbt/namerefresh.c @@ -159,7 +159,7 @@ struct refresh_wins_state { */ static void name_refresh_wins_handler(struct nbt_name_request *req) { - struct composite_context *c = talloc_get_type(req->async.private, + struct composite_context *c = talloc_get_type(req->async.private_data, struct composite_context); struct refresh_wins_state *state = talloc_get_type(c->private_data, struct refresh_wins_state); @@ -184,7 +184,7 @@ static void name_refresh_wins_handler(struct nbt_name_request *req) c->status = NT_STATUS_NO_MEMORY; } else { state->req->async.fn = name_refresh_wins_handler; - state->req->async.private = c; + state->req->async.private_data = c; } } else if (!NT_STATUS_IS_OK(status)) { c->state = COMPOSITE_STATE_ERROR; @@ -200,7 +200,7 @@ static void name_refresh_wins_handler(struct nbt_name_request *req) c->status = NT_STATUS_NO_MEMORY; } else { state->req->async.fn = name_refresh_wins_handler; - state->req->async.private = c; + state->req->async.private_data = c; } } else { c->state = COMPOSITE_STATE_DONE; @@ -259,7 +259,7 @@ _PUBLIC_ struct composite_context *nbt_name_refresh_wins_send(struct nbt_name_so if (state->req == NULL) goto failed; state->req->async.fn = name_refresh_wins_handler; - state->req->async.private = c; + state->req->async.private_data = c; c->private_data = state; c->state = COMPOSITE_STATE_IN_PROGRESS; diff --git a/source4/libcli/nbt/nameregister.c b/source4/libcli/nbt/nameregister.c index 9c5ae43d40..c50f9b3b3a 100644 --- a/source4/libcli/nbt/nameregister.c +++ b/source4/libcli/nbt/nameregister.c @@ -161,7 +161,7 @@ struct register_bcast_state { */ static void name_register_bcast_handler(struct nbt_name_request *req) { - struct composite_context *c = talloc_get_type(req->async.private, struct composite_context); + struct composite_context *c = talloc_get_type(req->async.private_data, struct composite_context); struct register_bcast_state *state = talloc_get_type(c->private_data, struct register_bcast_state); NTSTATUS status; @@ -183,7 +183,7 @@ static void name_register_bcast_handler(struct nbt_name_request *req) c->status = NT_STATUS_NO_MEMORY; } else { state->req->async.fn = name_register_bcast_handler; - state->req->async.private = c; + state->req->async.private_data = c; } } else if (!NT_STATUS_IS_OK(status)) { c->state = COMPOSITE_STATE_ERROR; @@ -241,7 +241,7 @@ _PUBLIC_ struct composite_context *nbt_name_register_bcast_send(struct nbt_name_ if (state->req == NULL) goto failed; state->req->async.fn = name_register_bcast_handler; - state->req->async.private = c; + state->req->async.private_data = c; c->private_data = state; c->state = COMPOSITE_STATE_IN_PROGRESS; @@ -297,7 +297,7 @@ struct register_wins_state { */ static void name_register_wins_handler(struct nbt_name_request *req) { - struct composite_context *c = talloc_get_type(req->async.private, + struct composite_context *c = talloc_get_type(req->async.private_data, struct composite_context); struct register_wins_state *state = talloc_get_type(c->private_data, struct register_wins_state); @@ -322,7 +322,7 @@ static void name_register_wins_handler(struct nbt_name_request *req) c->status = NT_STATUS_NO_MEMORY; } else { state->req->async.fn = name_register_wins_handler; - state->req->async.private = c; + state->req->async.private_data = c; } } else if (!NT_STATUS_IS_OK(status)) { c->state = COMPOSITE_STATE_ERROR; @@ -338,7 +338,7 @@ static void name_register_wins_handler(struct nbt_name_request *req) c->status = NT_STATUS_NO_MEMORY; } else { state->req->async.fn = name_register_wins_handler; - state->req->async.private = c; + state->req->async.private_data = c; } } else { c->state = COMPOSITE_STATE_DONE; @@ -399,7 +399,7 @@ _PUBLIC_ struct composite_context *nbt_name_register_wins_send(struct nbt_name_s if (state->req == NULL) goto failed; state->req->async.fn = name_register_wins_handler; - state->req->async.private = c; + state->req->async.private_data = c; c->private_data = state; c->state = COMPOSITE_STATE_IN_PROGRESS; diff --git a/source4/libcli/nbt/nbtsocket.c b/source4/libcli/nbt/nbtsocket.c index 5d4611e2d9..49f175b8a3 100644 --- a/source4/libcli/nbt/nbtsocket.c +++ b/source4/libcli/nbt/nbtsocket.c @@ -488,7 +488,7 @@ _PUBLIC_ NTSTATUS nbt_set_incoming_handler(struct nbt_name_socket *nbtsock, void *private) { nbtsock->incoming.handler = handler; - nbtsock->incoming.private = private; + nbtsock->incoming.private_data = private; EVENT_FD_READABLE(nbtsock->fde); return NT_STATUS_OK; } diff --git a/source4/libcli/resolve/nbtlist.c b/source4/libcli/resolve/nbtlist.c index 8f085c5404..0cc2ee6726 100644 --- a/source4/libcli/resolve/nbtlist.c +++ b/source4/libcli/resolve/nbtlist.c @@ -46,7 +46,7 @@ struct nbtlist_state { */ static void nbtlist_handler(struct nbt_name_request *req) { - struct composite_context *c = talloc_get_type(req->async.private, + struct composite_context *c = talloc_get_type(req->async.private_data, struct composite_context); struct nbtlist_state *state = talloc_get_type(c->private_data, struct nbtlist_state); struct nbt_name_query *q; @@ -169,7 +169,7 @@ struct composite_context *resolve_name_nbtlist_send(TALLOC_CTX *mem_ctx, if (composite_nomem(state->queries[i], c)) return c; state->queries[i]->async.fn = nbtlist_handler; - state->queries[i]->async.private = c; + state->queries[i]->async.private_data = c; } return c; diff --git a/source4/nbt_server/defense.c b/source4/nbt_server/defense.c index 2d7a126f5b..08eebe0c55 100644 --- a/source4/nbt_server/defense.c +++ b/source4/nbt_server/defense.c @@ -38,7 +38,7 @@ void nbtd_request_defense(struct nbt_name_socket *nbtsock, { struct nbtd_iface_name *iname; struct nbt_name *name; - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); /* diff --git a/source4/nbt_server/interfaces.c b/source4/nbt_server/interfaces.c index e59475051b..76bc145903 100644 --- a/source4/nbt_server/interfaces.c +++ b/source4/nbt_server/interfaces.c @@ -38,7 +38,7 @@ static void nbtd_request_handler(struct nbt_name_socket *nbtsock, struct nbt_name_packet *packet, struct socket_address *src) { - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct nbtd_server *nbtsrv = iface->nbtsrv; diff --git a/source4/nbt_server/nodestatus.c b/source4/nbt_server/nodestatus.c index a7bf67ad51..a5f1426f37 100644 --- a/source4/nbt_server/nodestatus.c +++ b/source4/nbt_server/nodestatus.c @@ -104,7 +104,7 @@ void nbtd_query_status(struct nbt_name_socket *nbtsock, { struct nbt_name *name; struct nbtd_iface_name *iname; - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); NBTD_ASSERT_PACKET(packet, src, packet->qdcount == 1); diff --git a/source4/nbt_server/packet.c b/source4/nbt_server/packet.c index 07a309b633..ff4e94fef9 100644 --- a/source4/nbt_server/packet.c +++ b/source4/nbt_server/packet.c @@ -47,7 +47,7 @@ bool nbtd_self_packet_and_bcast(struct nbt_name_socket *nbtsock, struct nbt_name_packet *packet, const struct socket_address *src) { - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); /* if its not a broadcast then its not considered a self packet */ @@ -74,7 +74,7 @@ bool nbtd_self_packet(struct nbt_name_socket *nbtsock, struct nbt_name_packet *packet, const struct socket_address *src) { - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct nbtd_server *nbtsrv = iface->nbtsrv; @@ -106,7 +106,7 @@ void nbtd_name_query_reply(struct nbt_name_socket *nbtsock, { struct nbt_name_packet *packet; size_t num_addresses = str_list_length(addresses); - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct nbtd_server *nbtsrv = iface->nbtsrv; int i; @@ -168,7 +168,7 @@ void nbtd_negative_name_query_reply(struct nbt_name_socket *nbtsock, { struct nbt_name_packet *packet; struct nbt_name *name = &request_packet->questions[0].name; - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct nbtd_server *nbtsrv = iface->nbtsrv; @@ -212,7 +212,7 @@ void nbtd_name_registration_reply(struct nbt_name_socket *nbtsock, { struct nbt_name_packet *packet; struct nbt_name *name = &request_packet->questions[0].name; - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct nbtd_server *nbtsrv = iface->nbtsrv; @@ -260,7 +260,7 @@ void nbtd_name_release_reply(struct nbt_name_socket *nbtsock, { struct nbt_name_packet *packet; struct nbt_name *name = &request_packet->questions[0].name; - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct nbtd_server *nbtsrv = iface->nbtsrv; @@ -306,7 +306,7 @@ void nbtd_wack_reply(struct nbt_name_socket *nbtsock, { struct nbt_name_packet *packet; struct nbt_name *name = &request_packet->questions[0].name; - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct nbtd_server *nbtsrv = iface->nbtsrv; diff --git a/source4/nbt_server/query.c b/source4/nbt_server/query.c index dfd742db5a..a8809e84a2 100644 --- a/source4/nbt_server/query.c +++ b/source4/nbt_server/query.c @@ -38,7 +38,7 @@ void nbtd_request_query(struct nbt_name_socket *nbtsock, { struct nbtd_iface_name *iname; struct nbt_name *name; - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); /* see if its a node status query */ diff --git a/source4/nbt_server/register.c b/source4/nbt_server/register.c index a17d503190..ebdb4dc0f8 100644 --- a/source4/nbt_server/register.c +++ b/source4/nbt_server/register.c @@ -38,7 +38,7 @@ static void nbtd_start_refresh_timer(struct nbtd_iface_name *iname); */ static void refresh_completion_handler(struct nbt_name_request *req) { - struct nbtd_iface_name *iname = talloc_get_type(req->async.private, + struct nbtd_iface_name *iname = talloc_get_type(req->async.private_data, struct nbtd_iface_name); NTSTATUS status; struct nbt_name_refresh io; @@ -108,7 +108,7 @@ static void name_refresh_handler(struct event_context *ev, struct timed_event *t if (req == NULL) return; req->async.fn = refresh_completion_handler; - req->async.private = iname; + req->async.private_data = iname; } diff --git a/source4/nbt_server/wins/wins_dns_proxy.c b/source4/nbt_server/wins/wins_dns_proxy.c index 3322ad55fd..cd605907a8 100644 --- a/source4/nbt_server/wins/wins_dns_proxy.c +++ b/source4/nbt_server/wins/wins_dns_proxy.c @@ -68,7 +68,7 @@ void nbtd_wins_dns_proxy_query(struct nbt_name_socket *nbtsock, struct socket_address *src) { struct nbt_name *name = &packet->questions[0].name; - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct wins_dns_proxy_state *s; struct composite_context *creq; diff --git a/source4/nbt_server/wins/winsserver.c b/source4/nbt_server/wins/winsserver.c index f8901ce09d..399530b4cf 100644 --- a/source4/nbt_server/wins/winsserver.c +++ b/source4/nbt_server/wins/winsserver.c @@ -68,7 +68,7 @@ static uint8_t wins_register_new(struct nbt_name_socket *nbtsock, const struct socket_address *src, enum wrepl_name_type type) { - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct wins_server *winssrv = iface->nbtsrv->winssrv; struct nbt_name *name = &packet->questions[0].name; @@ -119,7 +119,7 @@ static uint8_t wins_update_ttl(struct nbt_name_socket *nbtsock, struct winsdb_addr *winsdb_addr, const struct socket_address *src) { - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct wins_server *winssrv = iface->nbtsrv->winssrv; uint32_t ttl = wins_server_ttl(winssrv, packet->additional[0].ttl); @@ -158,7 +158,7 @@ static uint8_t wins_sgroup_merge(struct nbt_name_socket *nbtsock, const char *address, const struct socket_address *src) { - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct wins_server *winssrv = iface->nbtsrv->winssrv; uint32_t ttl = wins_server_ttl(winssrv, packet->additional[0].ttl); @@ -357,7 +357,7 @@ static void wins_register_wack(struct nbt_name_socket *nbtsock, struct socket_address *src, enum wrepl_name_type new_type) { - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct wins_server *winssrv = iface->nbtsrv->winssrv; struct wack_state *s; @@ -415,7 +415,7 @@ static void nbtd_winsserver_register(struct nbt_name_socket *nbtsock, struct socket_address *src) { NTSTATUS status; - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct wins_server *winssrv = iface->nbtsrv->winssrv; struct nbt_name *name = &packet->questions[0].name; @@ -671,7 +671,7 @@ static void nbtd_winsserver_query(struct loadparm_context *lp_ctx, struct socket_address *src) { NTSTATUS status; - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct wins_server *winssrv = iface->nbtsrv->winssrv; struct nbt_name *name = &packet->questions[0].name; @@ -813,7 +813,7 @@ static void nbtd_winsserver_release(struct nbt_name_socket *nbtsock, struct socket_address *src) { NTSTATUS status; - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct wins_server *winssrv = iface->nbtsrv->winssrv; struct nbt_name *name = &packet->questions[0].name; @@ -928,7 +928,7 @@ void nbtd_winsserver_request(struct nbt_name_socket *nbtsock, struct nbt_name_packet *packet, struct socket_address *src) { - struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private, + struct nbtd_interface *iface = talloc_get_type(nbtsock->incoming.private_data, struct nbtd_interface); struct wins_server *winssrv = iface->nbtsrv->winssrv; if ((packet->operation & NBT_FLAG_BROADCAST) || winssrv == NULL) { diff --git a/source4/nbt_server/wins/winswack.c b/source4/nbt_server/wins/winswack.c index 43d2747ae7..7e0c73a810 100644 --- a/source4/nbt_server/wins/winswack.c +++ b/source4/nbt_server/wins/winswack.c @@ -37,7 +37,7 @@ struct wins_challenge_state { static void wins_challenge_handler(struct nbt_name_request *req) { - struct composite_context *ctx = talloc_get_type(req->async.private, struct composite_context); + struct composite_context *ctx = talloc_get_type(req->async.private_data, struct composite_context); struct wins_challenge_state *state = talloc_get_type(ctx->private_data, struct wins_challenge_state); ctx->status = nbt_name_query_recv(req, state, &state->query); @@ -123,7 +123,7 @@ struct composite_context *wins_challenge_send(TALLOC_CTX *mem_ctx, struct wins_c if (req == NULL) goto failed; req->async.fn = wins_challenge_handler; - req->async.private = result; + req->async.private_data = result; return result; failed: @@ -151,7 +151,7 @@ struct wins_release_demand_state { static void wins_release_demand_handler(struct nbt_name_request *req) { - struct composite_context *ctx = talloc_get_type(req->async.private, struct composite_context); + struct composite_context *ctx = talloc_get_type(req->async.private_data, struct composite_context); struct wins_release_demand_state *state = talloc_get_type(ctx->private_data, struct wins_release_demand_state); ctx->status = nbt_name_release_recv(req, state, &state->release); @@ -240,7 +240,7 @@ static struct composite_context *wins_release_demand_send(TALLOC_CTX *mem_ctx, s if (req == NULL) goto failed; req->async.fn = wins_release_demand_handler; - req->async.private = result; + req->async.private_data = result; return result; failed: diff --git a/source4/torture/nbt/query.c b/source4/torture/nbt/query.c index 80027a1b68..b1b703a3c2 100644 --- a/source4/torture/nbt/query.c +++ b/source4/torture/nbt/query.c @@ -33,7 +33,7 @@ struct result_struct { static void increment_handler(struct nbt_name_request *req) { - struct result_struct *v = talloc_get_type(req->async.private, struct result_struct); + struct result_struct *v = talloc_get_type(req->async.private_data, struct result_struct); if (req->state != NBT_REQUEST_DONE) { v->num_fail++; } else { @@ -76,7 +76,7 @@ static bool bench_namequery(struct torture_context *tctx) req = nbt_name_query_send(nbtsock, &io); torture_assert(tctx, req != NULL, "Failed to setup request!"); req->async.fn = increment_handler; - req->async.private = result; + req->async.private_data = result; num_sent++; if (num_sent % 1000 == 0) { if (torture_setting_bool(tctx, "progress", true)) { diff --git a/source4/torture/nbt/winsbench.c b/source4/torture/nbt/winsbench.c index a0d90fb653..bea3d4f9cf 100644 --- a/source4/torture/nbt/winsbench.c +++ b/source4/torture/nbt/winsbench.c @@ -56,7 +56,7 @@ static struct nbt_name generate_name(TALLOC_CTX *tctx, int idx) static void register_handler(struct nbt_name_request *req) { - struct idx_state *istate = talloc_get_type(req->async.private, struct idx_state); + struct idx_state *istate = talloc_get_type(req->async.private_data, struct idx_state); struct wins_state *state = istate->state; struct nbt_name_register io; NTSTATUS status; @@ -100,7 +100,7 @@ static void generate_register(struct nbt_name_socket *nbtsock, struct wins_state req = nbt_name_register_send(nbtsock, &io); req->async.fn = register_handler; - req->async.private = istate; + req->async.private_data = istate; talloc_free(tmp_ctx); } @@ -108,7 +108,7 @@ static void generate_register(struct nbt_name_socket *nbtsock, struct wins_state static void release_handler(struct nbt_name_request *req) { - struct idx_state *istate = talloc_get_type(req->async.private, struct idx_state); + struct idx_state *istate = talloc_get_type(req->async.private_data, struct idx_state); struct wins_state *state = istate->state; struct nbt_name_release io; NTSTATUS status; @@ -150,7 +150,7 @@ static void generate_release(struct nbt_name_socket *nbtsock, struct wins_state req = nbt_name_release_send(nbtsock, &io); req->async.fn = release_handler; - req->async.private = istate; + req->async.private_data = istate; talloc_free(tmp_ctx); } @@ -158,7 +158,7 @@ static void generate_release(struct nbt_name_socket *nbtsock, struct wins_state static void query_handler(struct nbt_name_request *req) { - struct idx_state *istate = talloc_get_type(req->async.private, struct idx_state); + struct idx_state *istate = talloc_get_type(req->async.private_data, struct idx_state); struct wins_state *state = istate->state; struct nbt_name_query io; NTSTATUS status; @@ -197,7 +197,7 @@ static void generate_query(struct nbt_name_socket *nbtsock, struct wins_state *s req = nbt_name_query_send(nbtsock, &io); req->async.fn = query_handler; - req->async.private = istate; + req->async.private_data = istate; talloc_free(tmp_ctx); } diff --git a/source4/torture/nbt/winsreplication.c b/source4/torture/nbt/winsreplication.c index 6b600bd7cd..b688f1fbfe 100644 --- a/source4/torture/nbt/winsreplication.c +++ b/source4/torture/nbt/winsreplication.c @@ -9457,7 +9457,7 @@ static void test_conflict_owned_active_vs_replica_handler_query(struct nbt_name_ struct nbt_name *name; struct nbt_name_packet *rep_packet; struct test_conflict_owned_active_vs_replica_struct *rec = - (struct test_conflict_owned_active_vs_replica_struct *)nbtsock->incoming.private; + (struct test_conflict_owned_active_vs_replica_struct *)nbtsock->incoming.private_data; _NBT_ASSERT(req_packet->qdcount, 1); _NBT_ASSERT(req_packet->questions[0].question_type, NBT_QTYPE_NETBIOS); @@ -9556,7 +9556,7 @@ static void test_conflict_owned_active_vs_replica_handler_release( struct nbt_name *name; struct nbt_name_packet *rep_packet; struct test_conflict_owned_active_vs_replica_struct *rec = - (struct test_conflict_owned_active_vs_replica_struct *)nbtsock->incoming.private; + (struct test_conflict_owned_active_vs_replica_struct *)nbtsock->incoming.private_data; _NBT_ASSERT(req_packet->qdcount, 1); _NBT_ASSERT(req_packet->questions[0].question_type, NBT_QTYPE_NETBIOS); @@ -9610,7 +9610,7 @@ static void test_conflict_owned_active_vs_replica_handler(struct nbt_name_socket struct socket_address *src) { struct test_conflict_owned_active_vs_replica_struct *rec = - (struct test_conflict_owned_active_vs_replica_struct *)nbtsock->incoming.private; + (struct test_conflict_owned_active_vs_replica_struct *)nbtsock->incoming.private_data; rec->defend.ret = false; -- cgit From be8b72dd5541182e24f522026bafbaef044a47e3 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 09:34:03 +0200 Subject: s4-nbt: merge some fixes from samba3 nbt helper. Guenther --- source4/libcli/nbt/libnbt.h | 6 +++--- source4/libcli/nbt/nbtname.c | 42 +++++++++++++++++++++--------------------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/source4/libcli/nbt/libnbt.h b/source4/libcli/nbt/libnbt.h index ff4fe65ac8..8529ec362b 100644 --- a/source4/libcli/nbt/libnbt.h +++ b/source4/libcli/nbt/libnbt.h @@ -329,9 +329,9 @@ NTSTATUS nbt_name_reply_send(struct nbt_name_socket *nbtsock, struct nbt_name_packet *request); -NDR_SCALAR_PROTO(wrepl_nbt_name, const struct nbt_name *) -NDR_SCALAR_PROTO(nbt_string, const char *) -NDR_BUFFER_PROTO(nbt_name, struct nbt_name) +NDR_SCALAR_PROTO(wrepl_nbt_name, const struct nbt_name *); +NDR_SCALAR_PROTO(nbt_string, const char *); +NDR_BUFFER_PROTO(nbt_name, struct nbt_name); NTSTATUS nbt_rcode_to_ntstatus(uint8_t rcode); struct composite_context; diff --git a/source4/libcli/nbt/nbtname.c b/source4/libcli/nbt/nbtname.c index 67bb4486e5..338cb21089 100644 --- a/source4/libcli/nbt/nbtname.c +++ b/source4/libcli/nbt/nbtname.c @@ -1,20 +1,20 @@ -/* +/* Unix SMB/CIFS implementation. manipulate nbt name structures Copyright (C) Andrew Tridgell 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 . */ @@ -111,7 +111,7 @@ _PUBLIC_ enum ndr_err_code ndr_pull_nbt_string(struct ndr_pull *ndr, int ndr_fla /* break up name into a list of components */ for (num_components=0;num_componentsnbt_string_list, s, &offset, (comparison_fn_t)strcmp, false); if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { uint8_t b[2]; - + if (offset > 0x3FFF) { return ndr_push_error(ndr, NDR_ERR_STRING, "offset for nbt string label pointer %u[%08X] > 0x00003FFF", @@ -218,7 +218,7 @@ static bool decompress_name(char *name, enum nbt_name_type *type) c2 < 'A' || c2 > 'P') { return false; } - name[i] = ((c1-'A')<<4) | (c2-'A'); + name[i] = ((c1-'A')<<4) | (c2-'A'); } name[i] = 0; if (i == 16) { @@ -233,7 +233,7 @@ static bool decompress_name(char *name, enum nbt_name_type *type) for (;i>0 && name[i-1]==' ';i--) { name[i-1] = 0; } - + return true; } @@ -241,7 +241,7 @@ static bool decompress_name(char *name, enum nbt_name_type *type) /* compress a name component */ -static uint8_t *compress_name(TALLOC_CTX *mem_ctx, +static uint8_t *compress_name(TALLOC_CTX *mem_ctx, const uint8_t *name, enum nbt_name_type type) { uint8_t *cname; @@ -355,7 +355,7 @@ _PUBLIC_ enum ndr_err_code ndr_push_nbt_name(struct ndr_push *ndr, int ndr_flags } else { fullname = cname; } - + ndr_err = ndr_push_nbt_string(ndr, ndr_flags, (const char *)fullname); return ndr_err; @@ -421,7 +421,7 @@ _PUBLIC_ void nbt_choose_called_name(TALLOC_CTX *mem_ctx, n->scope = NULL; n->type = type; - if (is_ipaddress(name) || name == NULL) { + if ((name == NULL) || is_ipaddress(name)) { n->name = "*SMBSERVER"; return; } @@ -433,11 +433,11 @@ _PUBLIC_ void nbt_choose_called_name(TALLOC_CTX *mem_ctx, return; } s = talloc_strndup(mem_ctx, name, PTR_DIFF(p, name)); - n->name = strupper_talloc(mem_ctx, s); + n->name = talloc_strdup_upper(mem_ctx, s); return; } - n->name = strupper_talloc(mem_ctx, name); + n->name = talloc_strdup_upper(mem_ctx, name); } @@ -482,14 +482,14 @@ _PUBLIC_ char *nbt_name_string(TALLOC_CTX *mem_ctx, const struct nbt_name *name) { TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx); char *ret; - if (name->scope) { + if (name->scope) { ret = talloc_asprintf(mem_ctx, "%s<%02x>-%s", nbt_hex_encode(tmp_ctx, name->name), - name->type, + name->type, nbt_hex_encode(tmp_ctx, name->scope)); } else { - ret = talloc_asprintf(mem_ctx, "%s<%02x>", - nbt_hex_encode(tmp_ctx, name->name), + ret = talloc_asprintf(mem_ctx, "%s<%02x>", + nbt_hex_encode(tmp_ctx, name->name), name->type); } talloc_free(tmp_ctx); @@ -517,7 +517,7 @@ _PUBLIC_ enum ndr_err_code ndr_pull_wrepl_nbt_name(struct ndr_pull *ndr, int ndr NDR_PULL_ALLOC_N(ndr, namebuf, namebuf_len); NDR_CHECK(ndr_pull_array_uint8(ndr, NDR_SCALARS, namebuf, namebuf_len)); - NDR_PULL_ALLOC(ndr, r); + NDR_PULL_ALLOC(ndr, r); /* oh wow, what a nasty bug in windows ... */ if (namebuf[0] == 0x1b && namebuf_len >= 16) { @@ -564,7 +564,7 @@ _PUBLIC_ enum ndr_err_code ndr_push_wrepl_nbt_name(struct ndr_push *ndr, int ndr { uint8_t *namebuf; uint32_t namebuf_len; - uint32_t name_len; + uint32_t _name_len; uint32_t scope_len = 0; if (r == NULL) { @@ -576,8 +576,8 @@ _PUBLIC_ enum ndr_err_code ndr_push_wrepl_nbt_name(struct ndr_push *ndr, int ndr return NDR_ERR_SUCCESS; } - name_len = strlen(r->name); - if (name_len > 15) { + _name_len = strlen(r->name); + if (_name_len > 15) { return ndr_push_error(ndr, NDR_ERR_STRING, "wrepl_nbt_name longer as 15 chars: %s", r->name); -- cgit From 6f33f3e4c26564602d5d13c7459938955b56a16e Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 06:58:17 +0200 Subject: s4-nbt: move libcli/nbt up one level. Guenther --- libcli/nbt/libnbt.h | 351 +++++++++++++++++++++ libcli/nbt/namequery.c | 235 ++++++++++++++ libcli/nbt/namerefresh.c | 302 ++++++++++++++++++ libcli/nbt/nameregister.c | 442 ++++++++++++++++++++++++++ libcli/nbt/namerelease.c | 135 ++++++++ libcli/nbt/nbtname.c | 648 ++++++++++++++++++++++++++++++++++++++ libcli/nbt/nbtsocket.c | 521 ++++++++++++++++++++++++++++++ libcli/nbt/pynbt.c | 408 ++++++++++++++++++++++++ source4/libcli/nbt/libnbt.h | 351 --------------------- source4/libcli/nbt/namequery.c | 235 -------------- source4/libcli/nbt/namerefresh.c | 302 ------------------ source4/libcli/nbt/nameregister.c | 442 -------------------------- source4/libcli/nbt/namerelease.c | 135 -------- source4/libcli/nbt/nbtname.c | 648 -------------------------------------- source4/libcli/nbt/nbtsocket.c | 521 ------------------------------ source4/libcli/nbt/pynbt.c | 408 ------------------------ 16 files changed, 3042 insertions(+), 3042 deletions(-) create mode 100644 libcli/nbt/libnbt.h create mode 100644 libcli/nbt/namequery.c create mode 100644 libcli/nbt/namerefresh.c create mode 100644 libcli/nbt/nameregister.c create mode 100644 libcli/nbt/namerelease.c create mode 100644 libcli/nbt/nbtname.c create mode 100644 libcli/nbt/nbtsocket.c create mode 100644 libcli/nbt/pynbt.c delete mode 100644 source4/libcli/nbt/libnbt.h delete mode 100644 source4/libcli/nbt/namequery.c delete mode 100644 source4/libcli/nbt/namerefresh.c delete mode 100644 source4/libcli/nbt/nameregister.c delete mode 100644 source4/libcli/nbt/namerelease.c delete mode 100644 source4/libcli/nbt/nbtname.c delete mode 100644 source4/libcli/nbt/nbtsocket.c delete mode 100644 source4/libcli/nbt/pynbt.c diff --git a/libcli/nbt/libnbt.h b/libcli/nbt/libnbt.h new file mode 100644 index 0000000000..4ef4e9d60d --- /dev/null +++ b/libcli/nbt/libnbt.h @@ -0,0 +1,351 @@ +/* + Unix SMB/CIFS implementation. + + a raw async NBT library + + Copyright (C) Andrew Tridgell 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 . +*/ + +#ifndef __LIBNBT_H__ +#define __LIBNBT_H__ + +#include "librpc/gen_ndr/nbt.h" +#include "librpc/ndr/libndr.h" + +/* + possible states for pending requests +*/ +enum nbt_request_state {NBT_REQUEST_SEND, + NBT_REQUEST_WAIT, + NBT_REQUEST_DONE, + NBT_REQUEST_TIMEOUT, + NBT_REQUEST_ERROR}; + +/* + a nbt name request +*/ +struct nbt_name_request { + struct nbt_name_request *next, *prev; + + enum nbt_request_state state; + + NTSTATUS status; + + /* the socket this was on */ + struct nbt_name_socket *nbtsock; + + /* where to send the request */ + struct socket_address *dest; + + /* timeout between retries */ + int timeout; + + /* how many retries to send on timeout */ + int num_retries; + + /* whether we have received a WACK */ + bool received_wack; + + /* the timeout event */ + struct timed_event *te; + + /* the name transaction id */ + uint16_t name_trn_id; + + /* is it a reply? */ + bool is_reply; + + /* the encoded request */ + DATA_BLOB encoded; + + /* shall we allow multiple replies? */ + bool allow_multiple_replies; + + unsigned int num_replies; + struct nbt_name_reply { + struct nbt_name_packet *packet; + struct socket_address *dest; + } *replies; + + /* information on what to do on completion */ + struct { + void (*fn)(struct nbt_name_request *); + void *private_data; + } async; +}; + + + +/* + context structure for operations on name queries +*/ +struct nbt_name_socket { + struct socket_context *sock; + struct event_context *event_ctx; + struct smb_iconv_convenience *iconv_convenience; + + /* a queue of requests pending to be sent */ + struct nbt_name_request *send_queue; + + /* the fd event */ + struct fd_event *fde; + + /* mapping from name_trn_id to pending event */ + struct idr_context *idr; + + /* how many requests are waiting for a reply */ + uint16_t num_pending; + + /* what to do with incoming request packets */ + struct { + void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, + struct socket_address *); + void *private_data; + } incoming; + + /* what to do with unexpected replies */ + struct { + void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, + struct socket_address *); + void *private_data; + } unexpected; +}; + + +/* a simple name query */ +struct nbt_name_query { + struct { + struct nbt_name name; + const char *dest_addr; + uint16_t dest_port; + bool broadcast; + bool wins_lookup; + int timeout; /* in seconds */ + int retries; + } in; + struct { + const char *reply_from; + struct nbt_name name; + int16_t num_addrs; + const char **reply_addrs; + } out; +}; + +/* a simple name status query */ +struct nbt_name_status { + struct { + struct nbt_name name; + const char *dest_addr; + uint16_t dest_port; + int timeout; /* in seconds */ + int retries; + } in; + struct { + const char *reply_from; + struct nbt_name name; + struct nbt_rdata_status status; + } out; +}; + +/* a name registration request */ +struct nbt_name_register { + struct { + struct nbt_name name; + const char *dest_addr; + uint16_t dest_port; + const char *address; + uint16_t nb_flags; + bool register_demand; + bool broadcast; + bool multi_homed; + uint32_t ttl; + int timeout; /* in seconds */ + int retries; + } in; + struct { + const char *reply_from; + struct nbt_name name; + const char *reply_addr; + uint8_t rcode; + } out; +}; + +/* a send 3 times then demand name broadcast name registration */ +struct nbt_name_register_bcast { + struct { + struct nbt_name name; + const char *dest_addr; + uint16_t dest_port; + const char *address; + uint16_t nb_flags; + uint32_t ttl; + } in; +}; + + +/* wins name register with multiple wins servers to try and multiple + addresses to register */ +struct nbt_name_register_wins { + struct { + struct nbt_name name; + const char **wins_servers; + uint16_t wins_port; + const char **addresses; + uint16_t nb_flags; + uint32_t ttl; + } in; + struct { + const char *wins_server; + uint8_t rcode; + } out; +}; + + + +/* a name refresh request */ +struct nbt_name_refresh { + struct { + struct nbt_name name; + const char *dest_addr; + uint16_t dest_port; + const char *address; + uint16_t nb_flags; + bool broadcast; + uint32_t ttl; + int timeout; /* in seconds */ + int retries; + } in; + struct { + const char *reply_from; + struct nbt_name name; + const char *reply_addr; + uint8_t rcode; + } out; +}; + +/* wins name refresh with multiple wins servers to try and multiple + addresses to register */ +struct nbt_name_refresh_wins { + struct { + struct nbt_name name; + const char **wins_servers; + uint16_t wins_port; + const char **addresses; + uint16_t nb_flags; + uint32_t ttl; + } in; + struct { + const char *wins_server; + uint8_t rcode; + } out; +}; + + +/* a name release request */ +struct nbt_name_release { + struct { + struct nbt_name name; + const char *dest_addr; + uint16_t dest_port; + const char *address; + uint16_t nb_flags; + bool broadcast; + int timeout; /* in seconds */ + int retries; + } in; + struct { + const char *reply_from; + struct nbt_name name; + const char *reply_addr; + uint8_t rcode; + } out; +}; + +struct nbt_name_socket *nbt_name_socket_init(TALLOC_CTX *mem_ctx, + struct event_context *event_ctx, + struct smb_iconv_convenience *iconv_convenience); +struct nbt_name_request *nbt_name_query_send(struct nbt_name_socket *nbtsock, + struct nbt_name_query *io); +NTSTATUS nbt_name_query_recv(struct nbt_name_request *req, + TALLOC_CTX *mem_ctx, struct nbt_name_query *io); +NTSTATUS nbt_name_query(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, struct nbt_name_query *io); +struct nbt_name_request *nbt_name_status_send(struct nbt_name_socket *nbtsock, + struct nbt_name_status *io); +NTSTATUS nbt_name_status_recv(struct nbt_name_request *req, + TALLOC_CTX *mem_ctx, struct nbt_name_status *io); +NTSTATUS nbt_name_status(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, struct nbt_name_status *io); + +NTSTATUS nbt_name_dup(TALLOC_CTX *mem_ctx, struct nbt_name *name, struct nbt_name *newname); +NTSTATUS nbt_name_to_blob(TALLOC_CTX *mem_ctx, struct smb_iconv_convenience *iconv_convenience, DATA_BLOB *blob, struct nbt_name *name); +NTSTATUS nbt_name_from_blob(TALLOC_CTX *mem_ctx, const DATA_BLOB *blob, struct nbt_name *name); +void nbt_choose_called_name(TALLOC_CTX *mem_ctx, struct nbt_name *n, const char *name, int type); +char *nbt_name_string(TALLOC_CTX *mem_ctx, const struct nbt_name *name); +NTSTATUS nbt_name_register(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, struct nbt_name_register *io); +NTSTATUS nbt_name_refresh(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, struct nbt_name_refresh *io); +NTSTATUS nbt_name_release(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, struct nbt_name_release *io); +NTSTATUS nbt_name_register_wins(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, + struct nbt_name_register_wins *io); +NTSTATUS nbt_name_refresh_wins(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, + struct nbt_name_refresh_wins *io); +NTSTATUS nbt_name_register_recv(struct nbt_name_request *req, + TALLOC_CTX *mem_ctx, struct nbt_name_register *io); +struct nbt_name_request *nbt_name_register_send(struct nbt_name_socket *nbtsock, + struct nbt_name_register *io); +NTSTATUS nbt_name_release_recv(struct nbt_name_request *req, + TALLOC_CTX *mem_ctx, struct nbt_name_release *io); + +struct nbt_name_request *nbt_name_release_send(struct nbt_name_socket *nbtsock, + struct nbt_name_release *io); + +NTSTATUS nbt_name_refresh_recv(struct nbt_name_request *req, + TALLOC_CTX *mem_ctx, struct nbt_name_refresh *io); + +NTSTATUS nbt_set_incoming_handler(struct nbt_name_socket *nbtsock, + void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, + struct socket_address *), + void *private_data); +NTSTATUS nbt_name_reply_send(struct nbt_name_socket *nbtsock, + struct socket_address *dest, + struct nbt_name_packet *request); + + +NDR_SCALAR_PROTO(wrepl_nbt_name, const struct nbt_name *); +NDR_SCALAR_PROTO(nbt_string, const char *); +NDR_BUFFER_PROTO(nbt_name, struct nbt_name); +NTSTATUS nbt_rcode_to_ntstatus(uint8_t rcode); + +struct composite_context; +struct composite_context *nbt_name_register_bcast_send(struct nbt_name_socket *nbtsock, + struct nbt_name_register_bcast *io); +NTSTATUS nbt_name_register_bcast_recv(struct composite_context *c); +struct composite_context *nbt_name_register_wins_send(struct nbt_name_socket *nbtsock, + struct nbt_name_register_wins *io); +NTSTATUS nbt_name_refresh_wins_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, + struct nbt_name_refresh_wins *io); +struct composite_context *nbt_name_refresh_wins_send(struct nbt_name_socket *nbtsock, + struct nbt_name_refresh_wins *io); +NTSTATUS nbt_name_register_wins_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, + struct nbt_name_register_wins *io); + + +#endif /* __LIBNBT_H__ */ diff --git a/libcli/nbt/namequery.c b/libcli/nbt/namequery.c new file mode 100644 index 0000000000..ed3d8a2492 --- /dev/null +++ b/libcli/nbt/namequery.c @@ -0,0 +1,235 @@ +/* + Unix SMB/CIFS implementation. + + make nbt name query requests + + Copyright (C) Andrew Tridgell 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 . +*/ + +#include "includes.h" +#include "../libcli/nbt/libnbt.h" +#include "../libcli/nbt/nbt_proto.h" +#include "lib/socket/socket.h" +#include "param/param.h" + +/** + send a nbt name query +*/ +_PUBLIC_ struct nbt_name_request *nbt_name_query_send(struct nbt_name_socket *nbtsock, + struct nbt_name_query *io) +{ + struct nbt_name_request *req; + struct nbt_name_packet *packet; + struct socket_address *dest; + + packet = talloc_zero(nbtsock, struct nbt_name_packet); + if (packet == NULL) return NULL; + + packet->qdcount = 1; + packet->operation = NBT_OPCODE_QUERY; + if (io->in.broadcast) { + packet->operation |= NBT_FLAG_BROADCAST; + } + if (io->in.wins_lookup) { + packet->operation |= NBT_FLAG_RECURSION_DESIRED; + } + + packet->questions = talloc_array(packet, struct nbt_name_question, 1); + if (packet->questions == NULL) goto failed; + + packet->questions[0].name = io->in.name; + packet->questions[0].question_type = NBT_QTYPE_NETBIOS; + packet->questions[0].question_class = NBT_QCLASS_IP; + + dest = socket_address_from_strings(packet, nbtsock->sock->backend_name, + io->in.dest_addr, io->in.dest_port); + if (dest == NULL) goto failed; + req = nbt_name_request_send(nbtsock, dest, packet, + io->in.timeout, io->in.retries, false); + if (req == NULL) goto failed; + + talloc_free(packet); + return req; + +failed: + talloc_free(packet); + return NULL; +} + +/** + wait for a name query reply +*/ +_PUBLIC_ NTSTATUS nbt_name_query_recv(struct nbt_name_request *req, + TALLOC_CTX *mem_ctx, struct nbt_name_query *io) +{ + NTSTATUS status; + struct nbt_name_packet *packet; + int i; + + status = nbt_name_request_recv(req); + if (!NT_STATUS_IS_OK(status) || + req->num_replies == 0) { + talloc_free(req); + return status; + } + + packet = req->replies[0].packet; + io->out.reply_from = talloc_steal(mem_ctx, req->replies[0].dest->addr); + + if ((packet->operation & NBT_RCODE) != 0) { + status = nbt_rcode_to_ntstatus(packet->operation & NBT_RCODE); + talloc_free(req); + return status; + } + + if (packet->ancount != 1 || + packet->answers[0].rr_type != NBT_QTYPE_NETBIOS || + packet->answers[0].rr_class != NBT_QCLASS_IP) { + talloc_free(req); + return status; + } + + io->out.name = packet->answers[0].name; + io->out.num_addrs = packet->answers[0].rdata.netbios.length / 6; + io->out.reply_addrs = talloc_array(mem_ctx, const char *, io->out.num_addrs+1); + if (io->out.reply_addrs == NULL) { + talloc_free(req); + return NT_STATUS_NO_MEMORY; + } + + for (i=0;iout.num_addrs;i++) { + io->out.reply_addrs[i] = talloc_steal(io->out.reply_addrs, + packet->answers[0].rdata.netbios.addresses[i].ipaddr); + } + io->out.reply_addrs[i] = NULL; + + talloc_steal(mem_ctx, io->out.name.name); + talloc_steal(mem_ctx, io->out.name.scope); + + talloc_free(req); + + return NT_STATUS_OK; +} + +/** + wait for a name query reply +*/ +_PUBLIC_ NTSTATUS nbt_name_query(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, struct nbt_name_query *io) +{ + struct nbt_name_request *req = nbt_name_query_send(nbtsock, io); + return nbt_name_query_recv(req, mem_ctx, io); +} + + +/** + send a nbt name status +*/ +_PUBLIC_ struct nbt_name_request *nbt_name_status_send(struct nbt_name_socket *nbtsock, + struct nbt_name_status *io) +{ + struct nbt_name_request *req; + struct nbt_name_packet *packet; + struct socket_address *dest; + + packet = talloc_zero(nbtsock, struct nbt_name_packet); + if (packet == NULL) return NULL; + + packet->qdcount = 1; + packet->operation = NBT_OPCODE_QUERY; + + packet->questions = talloc_array(packet, struct nbt_name_question, 1); + if (packet->questions == NULL) goto failed; + + packet->questions[0].name = io->in.name; + packet->questions[0].question_type = NBT_QTYPE_STATUS; + packet->questions[0].question_class = NBT_QCLASS_IP; + + dest = socket_address_from_strings(packet, nbtsock->sock->backend_name, + io->in.dest_addr, io->in.dest_port); + if (dest == NULL) goto failed; + req = nbt_name_request_send(nbtsock, dest, packet, + io->in.timeout, io->in.retries, false); + if (req == NULL) goto failed; + + talloc_free(packet); + return req; + +failed: + talloc_free(packet); + return NULL; +} + +/** + wait for a name status reply +*/ +_PUBLIC_ NTSTATUS nbt_name_status_recv(struct nbt_name_request *req, + TALLOC_CTX *mem_ctx, struct nbt_name_status *io) +{ + NTSTATUS status; + struct nbt_name_packet *packet; + int i; + + status = nbt_name_request_recv(req); + if (!NT_STATUS_IS_OK(status) || + req->num_replies == 0) { + talloc_free(req); + return status; + } + + packet = req->replies[0].packet; + io->out.reply_from = talloc_steal(mem_ctx, req->replies[0].dest->addr); + + if ((packet->operation & NBT_RCODE) != 0) { + status = nbt_rcode_to_ntstatus(packet->operation & NBT_RCODE); + talloc_free(req); + return status; + } + + if (packet->ancount != 1 || + packet->answers[0].rr_type != NBT_QTYPE_STATUS || + packet->answers[0].rr_class != NBT_QCLASS_IP) { + talloc_free(req); + return NT_STATUS_INVALID_NETWORK_RESPONSE; + } + + io->out.name = packet->answers[0].name; + talloc_steal(mem_ctx, io->out.name.name); + talloc_steal(mem_ctx, io->out.name.scope); + + io->out.status = packet->answers[0].rdata.status; + talloc_steal(mem_ctx, io->out.status.names); + for (i=0;iout.status.num_names;i++) { + talloc_steal(io->out.status.names, io->out.status.names[i].name); + } + + + talloc_free(req); + + return NT_STATUS_OK; +} + +/** + wait for a name status reply +*/ +_PUBLIC_ NTSTATUS nbt_name_status(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, struct nbt_name_status *io) +{ + struct nbt_name_request *req = nbt_name_status_send(nbtsock, io); + return nbt_name_status_recv(req, mem_ctx, io); +} + + diff --git a/libcli/nbt/namerefresh.c b/libcli/nbt/namerefresh.c new file mode 100644 index 0000000000..37bf0fc8f1 --- /dev/null +++ b/libcli/nbt/namerefresh.c @@ -0,0 +1,302 @@ +/* + Unix SMB/CIFS implementation. + + send out a name refresh request + + Copyright (C) Andrew Tridgell 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 . +*/ + +#include "includes.h" +#include "../libcli/nbt/libnbt.h" +#include "../libcli/nbt/nbt_proto.h" +#include "libcli/composite/composite.h" +#include "lib/socket/socket.h" +#include "param/param.h" + +/* + send a nbt name refresh request +*/ +struct nbt_name_request *nbt_name_refresh_send(struct nbt_name_socket *nbtsock, + struct nbt_name_refresh *io) +{ + struct nbt_name_request *req; + struct nbt_name_packet *packet; + struct socket_address *dest; + + packet = talloc_zero(nbtsock, struct nbt_name_packet); + if (packet == NULL) return NULL; + + packet->qdcount = 1; + packet->arcount = 1; + packet->operation = NBT_OPCODE_REFRESH; + if (io->in.broadcast) { + packet->operation |= NBT_FLAG_BROADCAST; + } + + packet->questions = talloc_array(packet, struct nbt_name_question, 1); + if (packet->questions == NULL) goto failed; + + packet->questions[0].name = io->in.name; + packet->questions[0].question_type = NBT_QTYPE_NETBIOS; + packet->questions[0].question_class = NBT_QCLASS_IP; + + packet->additional = talloc_array(packet, struct nbt_res_rec, 1); + if (packet->additional == NULL) goto failed; + + packet->additional[0].name = io->in.name; + packet->additional[0].rr_type = NBT_QTYPE_NETBIOS; + packet->additional[0].rr_class = NBT_QCLASS_IP; + packet->additional[0].ttl = io->in.ttl; + packet->additional[0].rdata.netbios.length = 6; + packet->additional[0].rdata.netbios.addresses = talloc_array(packet->additional, + struct nbt_rdata_address, 1); + if (packet->additional[0].rdata.netbios.addresses == NULL) goto failed; + packet->additional[0].rdata.netbios.addresses[0].nb_flags = io->in.nb_flags; + packet->additional[0].rdata.netbios.addresses[0].ipaddr = + talloc_strdup(packet->additional, io->in.address); + + dest = socket_address_from_strings(nbtsock, + nbtsock->sock->backend_name, + io->in.dest_addr, io->in.dest_port); + if (dest == NULL) goto failed; + req = nbt_name_request_send(nbtsock, dest, packet, + io->in.timeout, io->in.retries, false); + if (req == NULL) goto failed; + + talloc_free(packet); + return req; + +failed: + talloc_free(packet); + return NULL; +} + +/* + wait for a refresh reply +*/ +_PUBLIC_ NTSTATUS nbt_name_refresh_recv(struct nbt_name_request *req, + TALLOC_CTX *mem_ctx, struct nbt_name_refresh *io) +{ + NTSTATUS status; + struct nbt_name_packet *packet; + + status = nbt_name_request_recv(req); + if (!NT_STATUS_IS_OK(status) || + req->num_replies == 0) { + talloc_free(req); + return status; + } + + packet = req->replies[0].packet; + io->out.reply_from = talloc_steal(mem_ctx, req->replies[0].dest->addr); + + if (packet->ancount != 1 || + packet->answers[0].rr_type != NBT_QTYPE_NETBIOS || + packet->answers[0].rr_class != NBT_QCLASS_IP) { + talloc_free(req); + return NT_STATUS_INVALID_NETWORK_RESPONSE; + } + + io->out.rcode = packet->operation & NBT_RCODE; + io->out.name = packet->answers[0].name; + if (packet->answers[0].rdata.netbios.length < 6) { + talloc_free(req); + return NT_STATUS_INVALID_NETWORK_RESPONSE; + } + io->out.reply_addr = talloc_steal(mem_ctx, + packet->answers[0].rdata.netbios.addresses[0].ipaddr); + talloc_steal(mem_ctx, io->out.name.name); + talloc_steal(mem_ctx, io->out.name.scope); + + talloc_free(req); + + return NT_STATUS_OK; +} + +/* + synchronous name refresh request +*/ +_PUBLIC_ NTSTATUS nbt_name_refresh(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, struct nbt_name_refresh *io) +{ + struct nbt_name_request *req = nbt_name_refresh_send(nbtsock, io); + return nbt_name_refresh_recv(req, mem_ctx, io); +} + + + +/** + a wins name refresh with multiple WINS servers and multiple + addresses to refresh. Try each WINS server in turn, until we get a + reply for each address +*/ +struct refresh_wins_state { + struct nbt_name_socket *nbtsock; + struct nbt_name_refresh *io; + const char **wins_servers; + uint16_t wins_port; + const char **addresses; + int address_idx; + struct nbt_name_request *req; +}; + + +/** + state handler for WINS multi-homed multi-server name refresh +*/ +static void name_refresh_wins_handler(struct nbt_name_request *req) +{ + struct composite_context *c = talloc_get_type(req->async.private_data, + struct composite_context); + struct refresh_wins_state *state = talloc_get_type(c->private_data, + struct refresh_wins_state); + NTSTATUS status; + + status = nbt_name_refresh_recv(state->req, state, state->io); + if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) { + /* the refresh timed out - try the next WINS server */ + state->wins_servers++; + state->address_idx = 0; + if (state->wins_servers[0] == NULL) { + c->state = COMPOSITE_STATE_ERROR; + c->status = status; + goto done; + } + state->io->in.dest_addr = state->wins_servers[0]; + state->io->in.dest_port = state->wins_port; + state->io->in.address = state->addresses[0]; + state->req = nbt_name_refresh_send(state->nbtsock, state->io); + if (state->req == NULL) { + c->state = COMPOSITE_STATE_ERROR; + c->status = NT_STATUS_NO_MEMORY; + } else { + state->req->async.fn = name_refresh_wins_handler; + state->req->async.private_data = c; + } + } else if (!NT_STATUS_IS_OK(status)) { + c->state = COMPOSITE_STATE_ERROR; + c->status = status; + } else { + if (state->io->out.rcode == 0 && + state->addresses[state->address_idx+1] != NULL) { + /* refresh our next address */ + state->io->in.address = state->addresses[++(state->address_idx)]; + state->req = nbt_name_refresh_send(state->nbtsock, state->io); + if (state->req == NULL) { + c->state = COMPOSITE_STATE_ERROR; + c->status = NT_STATUS_NO_MEMORY; + } else { + state->req->async.fn = name_refresh_wins_handler; + state->req->async.private_data = c; + } + } else { + c->state = COMPOSITE_STATE_DONE; + c->status = NT_STATUS_OK; + } + } + +done: + if (c->state >= COMPOSITE_STATE_DONE && + c->async.fn) { + c->async.fn(c); + } +} + +/** + the async send call for a multi-server WINS refresh +*/ +_PUBLIC_ struct composite_context *nbt_name_refresh_wins_send(struct nbt_name_socket *nbtsock, + struct nbt_name_refresh_wins *io) +{ + struct composite_context *c; + struct refresh_wins_state *state; + + c = talloc_zero(nbtsock, struct composite_context); + if (c == NULL) goto failed; + + state = talloc(c, struct refresh_wins_state); + if (state == NULL) goto failed; + + state->io = talloc(state, struct nbt_name_refresh); + if (state->io == NULL) goto failed; + + state->wins_port = io->in.wins_port; + state->wins_servers = str_list_copy(state, io->in.wins_servers); + if (state->wins_servers == NULL || + state->wins_servers[0] == NULL) goto failed; + + state->addresses = str_list_copy(state, io->in.addresses); + if (state->addresses == NULL || + state->addresses[0] == NULL) goto failed; + + state->io->in.name = io->in.name; + state->io->in.dest_addr = state->wins_servers[0]; + state->io->in.dest_port = state->wins_port; + state->io->in.address = io->in.addresses[0]; + state->io->in.nb_flags = io->in.nb_flags; + state->io->in.broadcast = false; + state->io->in.ttl = io->in.ttl; + state->io->in.timeout = 2; + state->io->in.retries = 2; + + state->nbtsock = nbtsock; + state->address_idx = 0; + + state->req = nbt_name_refresh_send(nbtsock, state->io); + if (state->req == NULL) goto failed; + + state->req->async.fn = name_refresh_wins_handler; + state->req->async.private_data = c; + + c->private_data = state; + c->state = COMPOSITE_STATE_IN_PROGRESS; + c->event_ctx = nbtsock->event_ctx; + + return c; + +failed: + talloc_free(c); + return NULL; +} + +/* + multi-homed WINS name refresh - recv side +*/ +_PUBLIC_ NTSTATUS nbt_name_refresh_wins_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, + struct nbt_name_refresh_wins *io) +{ + NTSTATUS status; + status = composite_wait(c); + if (NT_STATUS_IS_OK(status)) { + struct refresh_wins_state *state = + talloc_get_type(c->private_data, struct refresh_wins_state); + io->out.wins_server = talloc_steal(mem_ctx, state->wins_servers[0]); + io->out.rcode = state->io->out.rcode; + } + talloc_free(c); + return status; +} + +/* + multi-homed WINS refresh - sync interface +*/ +_PUBLIC_ NTSTATUS nbt_name_refresh_wins(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, + struct nbt_name_refresh_wins *io) +{ + struct composite_context *c = nbt_name_refresh_wins_send(nbtsock, io); + return nbt_name_refresh_wins_recv(c, mem_ctx, io); +} diff --git a/libcli/nbt/nameregister.c b/libcli/nbt/nameregister.c new file mode 100644 index 0000000000..d4728a8e02 --- /dev/null +++ b/libcli/nbt/nameregister.c @@ -0,0 +1,442 @@ +/* + Unix SMB/CIFS implementation. + + send out a name registration request + + Copyright (C) Andrew Tridgell 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 . +*/ + +#include "includes.h" +#include "../libcli/nbt/libnbt.h" +#include "../libcli/nbt/nbt_proto.h" +#include "libcli/composite/composite.h" +#include "lib/socket/socket.h" +#include "librpc/gen_ndr/ndr_nbt.h" +#include "param/param.h" + +/* + send a nbt name registration request +*/ +struct nbt_name_request *nbt_name_register_send(struct nbt_name_socket *nbtsock, + struct nbt_name_register *io) +{ + struct nbt_name_request *req; + struct nbt_name_packet *packet; + struct socket_address *dest; + + packet = talloc_zero(nbtsock, struct nbt_name_packet); + if (packet == NULL) return NULL; + + packet->qdcount = 1; + packet->arcount = 1; + if (io->in.multi_homed) { + packet->operation = NBT_OPCODE_MULTI_HOME_REG; + } else { + packet->operation = NBT_OPCODE_REGISTER; + } + if (io->in.broadcast) { + packet->operation |= NBT_FLAG_BROADCAST; + } + if (io->in.register_demand) { + packet->operation |= NBT_FLAG_RECURSION_DESIRED; + } + + packet->questions = talloc_array(packet, struct nbt_name_question, 1); + if (packet->questions == NULL) goto failed; + + packet->questions[0].name = io->in.name; + packet->questions[0].question_type = NBT_QTYPE_NETBIOS; + packet->questions[0].question_class = NBT_QCLASS_IP; + + packet->additional = talloc_array(packet, struct nbt_res_rec, 1); + if (packet->additional == NULL) goto failed; + + packet->additional[0].name = io->in.name; + packet->additional[0].rr_type = NBT_QTYPE_NETBIOS; + packet->additional[0].rr_class = NBT_QCLASS_IP; + packet->additional[0].ttl = io->in.ttl; + packet->additional[0].rdata.netbios.length = 6; + packet->additional[0].rdata.netbios.addresses = talloc_array(packet->additional, + struct nbt_rdata_address, 1); + if (packet->additional[0].rdata.netbios.addresses == NULL) goto failed; + packet->additional[0].rdata.netbios.addresses[0].nb_flags = io->in.nb_flags; + packet->additional[0].rdata.netbios.addresses[0].ipaddr = + talloc_strdup(packet->additional, io->in.address); + if (packet->additional[0].rdata.netbios.addresses[0].ipaddr == NULL) goto failed; + + dest = socket_address_from_strings(packet, nbtsock->sock->backend_name, + io->in.dest_addr, io->in.dest_port); + if (dest == NULL) goto failed; + req = nbt_name_request_send(nbtsock, dest, packet, + io->in.timeout, io->in.retries, false); + if (req == NULL) goto failed; + + talloc_free(packet); + return req; + +failed: + talloc_free(packet); + return NULL; +} + +/* + wait for a registration reply +*/ +_PUBLIC_ NTSTATUS nbt_name_register_recv(struct nbt_name_request *req, + TALLOC_CTX *mem_ctx, struct nbt_name_register *io) +{ + NTSTATUS status; + struct nbt_name_packet *packet; + + status = nbt_name_request_recv(req); + if (!NT_STATUS_IS_OK(status) || + req->num_replies == 0) { + talloc_free(req); + return status; + } + + packet = req->replies[0].packet; + io->out.reply_from = talloc_steal(mem_ctx, req->replies[0].dest->addr); + + if (packet->ancount != 1 || + packet->answers[0].rr_type != NBT_QTYPE_NETBIOS || + packet->answers[0].rr_class != NBT_QCLASS_IP) { + talloc_free(req); + return NT_STATUS_INVALID_NETWORK_RESPONSE; + } + + io->out.rcode = packet->operation & NBT_RCODE; + io->out.name = packet->answers[0].name; + if (packet->answers[0].rdata.netbios.length < 6) { + talloc_free(req); + return NT_STATUS_INVALID_NETWORK_RESPONSE; + } + io->out.reply_addr = talloc_steal(mem_ctx, + packet->answers[0].rdata.netbios.addresses[0].ipaddr); + talloc_steal(mem_ctx, io->out.name.name); + talloc_steal(mem_ctx, io->out.name.scope); + + talloc_free(req); + + return NT_STATUS_OK; +} + +/* + synchronous name registration request +*/ +_PUBLIC_ NTSTATUS nbt_name_register(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, struct nbt_name_register *io) +{ + struct nbt_name_request *req = nbt_name_register_send(nbtsock, io); + return nbt_name_register_recv(req, mem_ctx, io); +} + + +/* + a 4 step broadcast registration. 3 lots of name registration requests, followed by + a name registration demand +*/ +struct register_bcast_state { + struct nbt_name_socket *nbtsock; + struct nbt_name_register *io; + struct nbt_name_request *req; +}; + + +/* + state handler for 4 stage name registration +*/ +static void name_register_bcast_handler(struct nbt_name_request *req) +{ + struct composite_context *c = talloc_get_type(req->async.private_data, struct composite_context); + struct register_bcast_state *state = talloc_get_type(c->private_data, struct register_bcast_state); + NTSTATUS status; + + status = nbt_name_register_recv(state->req, state, state->io); + if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) { + if (state->io->in.register_demand == true) { + /* all done */ + c->state = COMPOSITE_STATE_DONE; + c->status = NT_STATUS_OK; + goto done; + } + + /* the registration timed out - good, send the demand */ + state->io->in.register_demand = true; + state->io->in.retries = 0; + state->req = nbt_name_register_send(state->nbtsock, state->io); + if (state->req == NULL) { + c->state = COMPOSITE_STATE_ERROR; + c->status = NT_STATUS_NO_MEMORY; + } else { + state->req->async.fn = name_register_bcast_handler; + state->req->async.private_data = c; + } + } else if (!NT_STATUS_IS_OK(status)) { + c->state = COMPOSITE_STATE_ERROR; + c->status = status; + } else { + c->state = COMPOSITE_STATE_ERROR; + c->status = NT_STATUS_CONFLICTING_ADDRESSES; + DEBUG(3,("Name registration conflict from %s for %s with ip %s - rcode %d\n", + state->io->out.reply_from, + nbt_name_string(state, &state->io->out.name), + state->io->out.reply_addr, + state->io->out.rcode)); + } + +done: + if (c->state >= COMPOSITE_STATE_DONE && + c->async.fn) { + c->async.fn(c); + } +} + +/* + the async send call for a 4 stage name registration +*/ +_PUBLIC_ struct composite_context *nbt_name_register_bcast_send(struct nbt_name_socket *nbtsock, + struct nbt_name_register_bcast *io) +{ + struct composite_context *c; + struct register_bcast_state *state; + + c = talloc_zero(nbtsock, struct composite_context); + if (c == NULL) goto failed; + + state = talloc(c, struct register_bcast_state); + if (state == NULL) goto failed; + + state->io = talloc(state, struct nbt_name_register); + if (state->io == NULL) goto failed; + + state->io->in.name = io->in.name; + state->io->in.dest_addr = io->in.dest_addr; + state->io->in.dest_port = io->in.dest_port; + state->io->in.address = io->in.address; + state->io->in.nb_flags = io->in.nb_flags; + state->io->in.register_demand = false; + state->io->in.broadcast = true; + state->io->in.multi_homed = false; + state->io->in.ttl = io->in.ttl; + state->io->in.timeout = 1; + state->io->in.retries = 2; + + state->nbtsock = nbtsock; + + state->req = nbt_name_register_send(nbtsock, state->io); + if (state->req == NULL) goto failed; + + state->req->async.fn = name_register_bcast_handler; + state->req->async.private_data = c; + + c->private_data = state; + c->state = COMPOSITE_STATE_IN_PROGRESS; + c->event_ctx = nbtsock->event_ctx; + + return c; + +failed: + talloc_free(c); + return NULL; +} + +/* + broadcast 4 part name register - recv +*/ +_PUBLIC_ NTSTATUS nbt_name_register_bcast_recv(struct composite_context *c) +{ + NTSTATUS status; + status = composite_wait(c); + talloc_free(c); + return status; +} + +/* + broadcast 4 part name register - sync interface +*/ +NTSTATUS nbt_name_register_bcast(struct nbt_name_socket *nbtsock, + struct nbt_name_register_bcast *io) +{ + struct composite_context *c = nbt_name_register_bcast_send(nbtsock, io); + return nbt_name_register_bcast_recv(c); +} + + +/* + a wins name register with multiple WINS servers and multiple + addresses to register. Try each WINS server in turn, until we get a + reply for each address +*/ +struct register_wins_state { + struct nbt_name_socket *nbtsock; + struct nbt_name_register *io; + const char **wins_servers; + uint16_t wins_port; + const char **addresses; + int address_idx; + struct nbt_name_request *req; +}; + + +/* + state handler for WINS multi-homed multi-server name register +*/ +static void name_register_wins_handler(struct nbt_name_request *req) +{ + struct composite_context *c = talloc_get_type(req->async.private_data, + struct composite_context); + struct register_wins_state *state = talloc_get_type(c->private_data, + struct register_wins_state); + NTSTATUS status; + + status = nbt_name_register_recv(state->req, state, state->io); + if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) { + /* the register timed out - try the next WINS server */ + state->wins_servers++; + state->address_idx = 0; + if (state->wins_servers[0] == NULL) { + c->state = COMPOSITE_STATE_ERROR; + c->status = status; + goto done; + } + state->io->in.dest_addr = state->wins_servers[0]; + state->io->in.dest_port = state->wins_port; + state->io->in.address = state->addresses[0]; + state->req = nbt_name_register_send(state->nbtsock, state->io); + if (state->req == NULL) { + c->state = COMPOSITE_STATE_ERROR; + c->status = NT_STATUS_NO_MEMORY; + } else { + state->req->async.fn = name_register_wins_handler; + state->req->async.private_data = c; + } + } else if (!NT_STATUS_IS_OK(status)) { + c->state = COMPOSITE_STATE_ERROR; + c->status = status; + } else { + if (state->io->out.rcode == 0 && + state->addresses[state->address_idx+1] != NULL) { + /* register our next address */ + state->io->in.address = state->addresses[++(state->address_idx)]; + state->req = nbt_name_register_send(state->nbtsock, state->io); + if (state->req == NULL) { + c->state = COMPOSITE_STATE_ERROR; + c->status = NT_STATUS_NO_MEMORY; + } else { + state->req->async.fn = name_register_wins_handler; + state->req->async.private_data = c; + } + } else { + c->state = COMPOSITE_STATE_DONE; + c->status = NT_STATUS_OK; + } + } + +done: + if (c->state >= COMPOSITE_STATE_DONE && + c->async.fn) { + c->async.fn(c); + } +} + +/* + the async send call for a multi-server WINS register +*/ +_PUBLIC_ struct composite_context *nbt_name_register_wins_send(struct nbt_name_socket *nbtsock, + struct nbt_name_register_wins *io) +{ + struct composite_context *c; + struct register_wins_state *state; + + c = talloc_zero(nbtsock, struct composite_context); + if (c == NULL) goto failed; + + state = talloc(c, struct register_wins_state); + if (state == NULL) goto failed; + + state->io = talloc(state, struct nbt_name_register); + if (state->io == NULL) goto failed; + + state->wins_port = io->in.wins_port; + state->wins_servers = str_list_copy(state, io->in.wins_servers); + if (state->wins_servers == NULL || + state->wins_servers[0] == NULL) goto failed; + + state->addresses = str_list_copy(state, io->in.addresses); + if (state->addresses == NULL || + state->addresses[0] == NULL) goto failed; + + state->io->in.name = io->in.name; + state->io->in.dest_addr = state->wins_servers[0]; + state->io->in.dest_port = state->wins_port; + state->io->in.address = io->in.addresses[0]; + state->io->in.nb_flags = io->in.nb_flags; + state->io->in.broadcast = false; + state->io->in.register_demand = false; + state->io->in.multi_homed = (io->in.nb_flags & NBT_NM_GROUP)?false:true; + state->io->in.ttl = io->in.ttl; + state->io->in.timeout = 3; + state->io->in.retries = 2; + + state->nbtsock = nbtsock; + state->address_idx = 0; + + state->req = nbt_name_register_send(nbtsock, state->io); + if (state->req == NULL) goto failed; + + state->req->async.fn = name_register_wins_handler; + state->req->async.private_data = c; + + c->private_data = state; + c->state = COMPOSITE_STATE_IN_PROGRESS; + c->event_ctx = nbtsock->event_ctx; + + return c; + +failed: + talloc_free(c); + return NULL; +} + +/* + multi-homed WINS name register - recv side +*/ +_PUBLIC_ NTSTATUS nbt_name_register_wins_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, + struct nbt_name_register_wins *io) +{ + NTSTATUS status; + status = composite_wait(c); + if (NT_STATUS_IS_OK(status)) { + struct register_wins_state *state = + talloc_get_type(c->private_data, struct register_wins_state); + io->out.wins_server = talloc_steal(mem_ctx, state->wins_servers[0]); + io->out.rcode = state->io->out.rcode; + } + talloc_free(c); + return status; +} + +/* + multi-homed WINS register - sync interface +*/ +_PUBLIC_ NTSTATUS nbt_name_register_wins(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, + struct nbt_name_register_wins *io) +{ + struct composite_context *c = nbt_name_register_wins_send(nbtsock, io); + return nbt_name_register_wins_recv(c, mem_ctx, io); +} diff --git a/libcli/nbt/namerelease.c b/libcli/nbt/namerelease.c new file mode 100644 index 0000000000..e57a2f396e --- /dev/null +++ b/libcli/nbt/namerelease.c @@ -0,0 +1,135 @@ +/* + Unix SMB/CIFS implementation. + + send out a name release request + + Copyright (C) Andrew Tridgell 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 . +*/ + +#include "includes.h" +#include "../libcli/nbt/libnbt.h" +#include "../libcli/nbt/nbt_proto.h" +#include "lib/socket/socket.h" +#include "param/param.h" + +/* + send a nbt name release request +*/ +_PUBLIC_ struct nbt_name_request *nbt_name_release_send(struct nbt_name_socket *nbtsock, + struct nbt_name_release *io) +{ + struct nbt_name_request *req; + struct nbt_name_packet *packet; + struct socket_address *dest; + + packet = talloc_zero(nbtsock, struct nbt_name_packet); + if (packet == NULL) return NULL; + + packet->qdcount = 1; + packet->arcount = 1; + packet->operation = NBT_OPCODE_RELEASE; + if (io->in.broadcast) { + packet->operation |= NBT_FLAG_BROADCAST; + } + + packet->questions = talloc_array(packet, struct nbt_name_question, 1); + if (packet->questions == NULL) goto failed; + + packet->questions[0].name = io->in.name; + packet->questions[0].question_type = NBT_QTYPE_NETBIOS; + packet->questions[0].question_class = NBT_QCLASS_IP; + + packet->additional = talloc_array(packet, struct nbt_res_rec, 1); + if (packet->additional == NULL) goto failed; + + packet->additional[0].name = io->in.name; + packet->additional[0].rr_type = NBT_QTYPE_NETBIOS; + packet->additional[0].rr_class = NBT_QCLASS_IP; + packet->additional[0].ttl = 0; + packet->additional[0].rdata.netbios.length = 6; + packet->additional[0].rdata.netbios.addresses = talloc_array(packet->additional, + struct nbt_rdata_address, 1); + if (packet->additional[0].rdata.netbios.addresses == NULL) goto failed; + packet->additional[0].rdata.netbios.addresses[0].nb_flags = io->in.nb_flags; + packet->additional[0].rdata.netbios.addresses[0].ipaddr = + talloc_strdup(packet->additional, io->in.address); + + dest = socket_address_from_strings(packet, nbtsock->sock->backend_name, + io->in.dest_addr, io->in.dest_port); + if (dest == NULL) goto failed; + req = nbt_name_request_send(nbtsock, dest, packet, + io->in.timeout, io->in.retries, false); + if (req == NULL) goto failed; + + talloc_free(packet); + return req; + +failed: + talloc_free(packet); + return NULL; +} + +/* + wait for a release reply +*/ +_PUBLIC_ NTSTATUS nbt_name_release_recv(struct nbt_name_request *req, + TALLOC_CTX *mem_ctx, struct nbt_name_release *io) +{ + NTSTATUS status; + struct nbt_name_packet *packet; + + status = nbt_name_request_recv(req); + if (!NT_STATUS_IS_OK(status) || + req->num_replies == 0) { + talloc_free(req); + return status; + } + + packet = req->replies[0].packet; + io->out.reply_from = talloc_steal(mem_ctx, req->replies[0].dest->addr); + + if (packet->ancount != 1 || + packet->answers[0].rr_type != NBT_QTYPE_NETBIOS || + packet->answers[0].rr_class != NBT_QCLASS_IP) { + talloc_free(req); + return NT_STATUS_INVALID_NETWORK_RESPONSE; + } + + io->out.rcode = packet->operation & NBT_RCODE; + io->out.name = packet->answers[0].name; + if (packet->answers[0].rdata.netbios.length < 6) { + talloc_free(req); + return NT_STATUS_INVALID_NETWORK_RESPONSE; + } + io->out.reply_addr = talloc_steal(mem_ctx, + packet->answers[0].rdata.netbios.addresses[0].ipaddr); + talloc_steal(mem_ctx, io->out.name.name); + talloc_steal(mem_ctx, io->out.name.scope); + + talloc_free(req); + + return NT_STATUS_OK; +} + +/* + synchronous name release request +*/ +_PUBLIC_ NTSTATUS nbt_name_release(struct nbt_name_socket *nbtsock, + TALLOC_CTX *mem_ctx, struct nbt_name_release *io) +{ + struct nbt_name_request *req = nbt_name_release_send(nbtsock, io); + return nbt_name_release_recv(req, mem_ctx, io); +} diff --git a/libcli/nbt/nbtname.c b/libcli/nbt/nbtname.c new file mode 100644 index 0000000000..338cb21089 --- /dev/null +++ b/libcli/nbt/nbtname.c @@ -0,0 +1,648 @@ +/* + Unix SMB/CIFS implementation. + + manipulate nbt name structures + + Copyright (C) Andrew Tridgell 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 . +*/ + +/* + see rfc1002 for the detailed format of compressed names +*/ + +#include "includes.h" +#include "librpc/gen_ndr/ndr_nbt.h" +#include "librpc/gen_ndr/ndr_misc.h" +#include "system/locale.h" + +/* don't allow an unlimited number of name components */ +#define MAX_COMPONENTS 10 + +/** + print a nbt string +*/ +_PUBLIC_ void ndr_print_nbt_string(struct ndr_print *ndr, const char *name, const char *s) +{ + ndr_print_string(ndr, name, s); +} + +/* + pull one component of a nbt_string +*/ +static enum ndr_err_code ndr_pull_component(struct ndr_pull *ndr, + uint8_t **component, + uint32_t *offset, + uint32_t *max_offset) +{ + uint8_t len; + uint_t loops = 0; + while (loops < 5) { + if (*offset >= ndr->data_size) { + return ndr_pull_error(ndr, NDR_ERR_STRING, + "BAD NBT NAME component"); + } + len = ndr->data[*offset]; + if (len == 0) { + *offset += 1; + *max_offset = MAX(*max_offset, *offset); + *component = NULL; + return NDR_ERR_SUCCESS; + } + if ((len & 0xC0) == 0xC0) { + /* its a label pointer */ + if (1 + *offset >= ndr->data_size) { + return ndr_pull_error(ndr, NDR_ERR_STRING, + "BAD NBT NAME component"); + } + *max_offset = MAX(*max_offset, *offset + 2); + *offset = ((len&0x3F)<<8) | ndr->data[1 + *offset]; + *max_offset = MAX(*max_offset, *offset); + loops++; + continue; + } + if ((len & 0xC0) != 0) { + /* its a reserved length field */ + return ndr_pull_error(ndr, NDR_ERR_STRING, + "BAD NBT NAME component"); + } + if (*offset + len + 2 > ndr->data_size) { + return ndr_pull_error(ndr, NDR_ERR_STRING, + "BAD NBT NAME component"); + } + *component = (uint8_t*)talloc_strndup(ndr, (const char *)&ndr->data[1 + *offset], len); + NDR_ERR_HAVE_NO_MEMORY(*component); + *offset += len + 1; + *max_offset = MAX(*max_offset, *offset); + return NDR_ERR_SUCCESS; + } + + /* too many pointers */ + return ndr_pull_error(ndr, NDR_ERR_STRING, "BAD NBT NAME component"); +} + +/** + pull a nbt_string from the wire +*/ +_PUBLIC_ enum ndr_err_code ndr_pull_nbt_string(struct ndr_pull *ndr, int ndr_flags, const char **s) +{ + uint32_t offset = ndr->offset; + uint32_t max_offset = offset; + unsigned num_components; + char *name; + + if (!(ndr_flags & NDR_SCALARS)) { + return NDR_ERR_SUCCESS; + } + + name = NULL; + + /* break up name into a list of components */ + for (num_components=0;num_componentsoffset = max_offset; + + return NDR_ERR_SUCCESS; +} + +/** + push a nbt string to the wire +*/ +_PUBLIC_ enum ndr_err_code ndr_push_nbt_string(struct ndr_push *ndr, int ndr_flags, const char *s) +{ + if (!(ndr_flags & NDR_SCALARS)) { + return NDR_ERR_SUCCESS; + } + + while (s && *s) { + enum ndr_err_code ndr_err; + char *compname; + size_t complen; + uint32_t offset; + + /* see if we have pushed the remaing string allready, + * if so we use a label pointer to this string + */ + ndr_err = ndr_token_retrieve_cmp_fn(&ndr->nbt_string_list, s, &offset, (comparison_fn_t)strcmp, false); + if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + uint8_t b[2]; + + if (offset > 0x3FFF) { + return ndr_push_error(ndr, NDR_ERR_STRING, + "offset for nbt string label pointer %u[%08X] > 0x00003FFF", + offset, offset); + } + + b[0] = 0xC0 | (offset>>8); + b[1] = (offset & 0xFF); + + return ndr_push_bytes(ndr, b, 2); + } + + complen = strcspn(s, "."); + + /* we need to make sure the length fits into 6 bytes */ + if (complen >= 0x3F) { + return ndr_push_error(ndr, NDR_ERR_STRING, + "component length %u[%08X] > 0x00003F", + (unsigned)complen, (unsigned)complen); + } + + compname = talloc_asprintf(ndr, "%c%*.*s", + (unsigned char)complen, + (unsigned char)complen, + (unsigned char)complen, s); + NDR_ERR_HAVE_NO_MEMORY(compname); + + /* remember the current componemt + the rest of the string + * so it can be reused later + */ + NDR_CHECK(ndr_token_store(ndr, &ndr->nbt_string_list, s, ndr->offset)); + + /* push just this component into the blob */ + NDR_CHECK(ndr_push_bytes(ndr, (const uint8_t *)compname, complen+1)); + talloc_free(compname); + + s += complen; + if (*s == '.') s++; + } + + /* if we reach the end of the string and have pushed the last component + * without using a label pointer, we need to terminate the string + */ + return ndr_push_bytes(ndr, (const uint8_t *)"", 1); +} + + +/* + decompress a 'compressed' name component + */ +static bool decompress_name(char *name, enum nbt_name_type *type) +{ + int i; + for (i=0;name[2*i];i++) { + uint8_t c1 = name[2*i]; + uint8_t c2 = name[1+(2*i)]; + if (c1 < 'A' || c1 > 'P' || + c2 < 'A' || c2 > 'P') { + return false; + } + name[i] = ((c1-'A')<<4) | (c2-'A'); + } + name[i] = 0; + if (i == 16) { + *type = (enum nbt_name_type)(name[15]); + name[15] = 0; + i--; + } else { + *type = NBT_NAME_CLIENT; + } + + /* trim trailing spaces */ + for (;i>0 && name[i-1]==' ';i--) { + name[i-1] = 0; + } + + return true; +} + + +/* + compress a name component + */ +static uint8_t *compress_name(TALLOC_CTX *mem_ctx, + const uint8_t *name, enum nbt_name_type type) +{ + uint8_t *cname; + int i; + uint8_t pad_char; + + if (strlen((const char *)name) > 15) { + return NULL; + } + + cname = talloc_array(mem_ctx, uint8_t, 33); + if (cname == NULL) return NULL; + + for (i=0;name[i];i++) { + cname[2*i] = 'A' + (name[i]>>4); + cname[1+2*i] = 'A' + (name[i]&0xF); + } + if (strcmp((const char *)name, "*") == 0) { + pad_char = 0; + } else { + pad_char = ' '; + } + for (;i<15;i++) { + cname[2*i] = 'A' + (pad_char>>4); + cname[1+2*i] = 'A' + (pad_char&0xF); + } + + pad_char = type; + cname[2*i] = 'A' + (pad_char>>4); + cname[1+2*i] = 'A' + (pad_char&0xF); + + cname[32] = 0; + return cname; +} + + +/** + pull a nbt name from the wire +*/ +_PUBLIC_ enum ndr_err_code ndr_pull_nbt_name(struct ndr_pull *ndr, int ndr_flags, struct nbt_name *r) +{ + uint8_t *scope; + char *cname; + const char *s; + bool ok; + + if (!(ndr_flags & NDR_SCALARS)) { + return NDR_ERR_SUCCESS; + } + + NDR_CHECK(ndr_pull_nbt_string(ndr, ndr_flags, &s)); + + scope = (uint8_t *)strchr(s, '.'); + if (scope) { + *scope = 0; + r->scope = talloc_strdup(ndr->current_mem_ctx, (const char *)&scope[1]); + NDR_ERR_HAVE_NO_MEMORY(r->scope); + } else { + r->scope = NULL; + } + + cname = discard_const_p(char, s); + + /* the first component is limited to 16 bytes in the DOS charset, + which is 32 in the 'compressed' form */ + if (strlen(cname) > 32) { + return ndr_pull_error(ndr, NDR_ERR_STRING, + "NBT NAME cname > 32"); + } + + /* decompress the first component */ + ok = decompress_name(cname, &r->type); + if (!ok) { + return ndr_pull_error(ndr, NDR_ERR_STRING, + "NBT NAME failed to decompress"); + } + + r->name = talloc_strdup(ndr->current_mem_ctx, cname); + NDR_ERR_HAVE_NO_MEMORY(r->name); + + talloc_free(cname); + + return NDR_ERR_SUCCESS; +} + +/** + push a nbt name to the wire +*/ +_PUBLIC_ enum ndr_err_code ndr_push_nbt_name(struct ndr_push *ndr, int ndr_flags, const struct nbt_name *r) +{ + uint8_t *cname, *fullname; + enum ndr_err_code ndr_err; + + if (!(ndr_flags & NDR_SCALARS)) { + return NDR_ERR_SUCCESS; + } + + if (strlen(r->name) > 15) { + return ndr_push_error(ndr, NDR_ERR_STRING, + "nbt_name longer as 15 chars: %s", + r->name); + } + + cname = compress_name(ndr, (const uint8_t *)r->name, r->type); + NDR_ERR_HAVE_NO_MEMORY(cname); + + if (r->scope) { + fullname = (uint8_t *)talloc_asprintf(ndr, "%s.%s", cname, r->scope); + NDR_ERR_HAVE_NO_MEMORY(fullname); + talloc_free(cname); + } else { + fullname = cname; + } + + ndr_err = ndr_push_nbt_string(ndr, ndr_flags, (const char *)fullname); + + return ndr_err; +} + + +/** + copy a nbt name structure +*/ +_PUBLIC_ NTSTATUS nbt_name_dup(TALLOC_CTX *mem_ctx, struct nbt_name *name, struct nbt_name *newname) +{ + *newname = *name; + newname->name = talloc_strdup(mem_ctx, newname->name); + NT_STATUS_HAVE_NO_MEMORY(newname->name); + newname->scope = talloc_strdup(mem_ctx, newname->scope); + if (name->scope) { + NT_STATUS_HAVE_NO_MEMORY(newname->scope); + } + return NT_STATUS_OK; +} + +/** + push a nbt name into a blob +*/ +_PUBLIC_ NTSTATUS nbt_name_to_blob(TALLOC_CTX *mem_ctx, struct smb_iconv_convenience *iconv_convenience, DATA_BLOB *blob, struct nbt_name *name) +{ + enum ndr_err_code ndr_err; + + ndr_err = ndr_push_struct_blob(blob, mem_ctx, iconv_convenience, name, (ndr_push_flags_fn_t)ndr_push_nbt_name); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + return ndr_map_error2ntstatus(ndr_err); + } + + return NT_STATUS_OK; +} + +/** + pull a nbt name from a blob +*/ +_PUBLIC_ NTSTATUS nbt_name_from_blob(TALLOC_CTX *mem_ctx, const DATA_BLOB *blob, struct nbt_name *name) +{ + enum ndr_err_code ndr_err; + + ndr_err = ndr_pull_struct_blob(blob, mem_ctx, NULL, name, + (ndr_pull_flags_fn_t)ndr_pull_nbt_name); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + return ndr_map_error2ntstatus(ndr_err); + } + + return NT_STATUS_OK; +} + + +/** + choose a name to use when calling a server in a NBT session request. + we use heuristics to see if the name we have been given is a IP + address, or a too-long name. If it is then use *SMBSERVER, or a + truncated name +*/ +_PUBLIC_ void nbt_choose_called_name(TALLOC_CTX *mem_ctx, + struct nbt_name *n, const char *name, int type) +{ + n->scope = NULL; + n->type = type; + + if ((name == NULL) || is_ipaddress(name)) { + n->name = "*SMBSERVER"; + return; + } + if (strlen(name) > 15) { + const char *p = strchr(name, '.'); + char *s; + if (p - name > 15) { + n->name = "*SMBSERVER"; + return; + } + s = talloc_strndup(mem_ctx, name, PTR_DIFF(p, name)); + n->name = talloc_strdup_upper(mem_ctx, s); + return; + } + + n->name = talloc_strdup_upper(mem_ctx, name); +} + + +/* + escape a string into a form containing only a small set of characters, + the rest is hex encoded. This is similar to URL encoding +*/ +static const char *nbt_hex_encode(TALLOC_CTX *mem_ctx, const char *s) +{ + int i, len; + char *ret; + const char *valid_chars = "_-.$@ "; +#define NBT_CHAR_ALLOW(c) (isalnum((unsigned char)c) || strchr(valid_chars, c)) + + for (len=i=0;s[i];i++,len++) { + if (!NBT_CHAR_ALLOW(s[i])) { + len += 2; + } + } + + ret = talloc_array(mem_ctx, char, len+1); + if (ret == NULL) return NULL; + + for (len=i=0;s[i];i++) { + if (NBT_CHAR_ALLOW(s[i])) { + ret[len++] = s[i]; + } else { + snprintf(&ret[len], 4, "%%%02x", (unsigned char)s[i]); + len += 3; + } + } + ret[len] = 0; + + return ret; +} + + +/** + form a string for a NBT name +*/ +_PUBLIC_ char *nbt_name_string(TALLOC_CTX *mem_ctx, const struct nbt_name *name) +{ + TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx); + char *ret; + if (name->scope) { + ret = talloc_asprintf(mem_ctx, "%s<%02x>-%s", + nbt_hex_encode(tmp_ctx, name->name), + name->type, + nbt_hex_encode(tmp_ctx, name->scope)); + } else { + ret = talloc_asprintf(mem_ctx, "%s<%02x>", + nbt_hex_encode(tmp_ctx, name->name), + name->type); + } + talloc_free(tmp_ctx); + return ret; +} + +/** + pull a nbt name, WINS Replication uses another on wire format for nbt name +*/ +_PUBLIC_ enum ndr_err_code ndr_pull_wrepl_nbt_name(struct ndr_pull *ndr, int ndr_flags, const struct nbt_name **_r) +{ + struct nbt_name *r; + uint8_t *namebuf; + uint32_t namebuf_len; + + if (!(ndr_flags & NDR_SCALARS)) { + return NDR_ERR_SUCCESS; + } + + NDR_CHECK(ndr_pull_align(ndr, 4)); + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &namebuf_len)); + if (namebuf_len < 1 || namebuf_len > 255) { + return ndr_pull_error(ndr, NDR_ERR_ALLOC, "value out of range"); + } + NDR_PULL_ALLOC_N(ndr, namebuf, namebuf_len); + NDR_CHECK(ndr_pull_array_uint8(ndr, NDR_SCALARS, namebuf, namebuf_len)); + + NDR_PULL_ALLOC(ndr, r); + + /* oh wow, what a nasty bug in windows ... */ + if (namebuf[0] == 0x1b && namebuf_len >= 16) { + namebuf[0] = namebuf[15]; + namebuf[15] = 0x1b; + } + + if (namebuf_len < 17) { + r->type = 0x00; + + r->name = talloc_strndup(r, (char *)namebuf, namebuf_len); + if (!r->name) return ndr_pull_error(ndr, NDR_ERR_ALLOC, "out of memory"); + + r->scope= NULL; + + talloc_free(namebuf); + *_r = r; + return NDR_ERR_SUCCESS; + } + + r->type = namebuf[15]; + + namebuf[15] = '\0'; + trim_string((char *)namebuf, NULL, " "); + r->name = talloc_strdup(r, (char *)namebuf); + if (!r->name) return ndr_pull_error(ndr, NDR_ERR_ALLOC, "out of memory"); + + if (namebuf_len > 18) { + r->scope = talloc_strndup(r, (char *)(namebuf+17), namebuf_len-17); + if (!r->scope) return ndr_pull_error(ndr, NDR_ERR_ALLOC, "out of memory"); + } else { + r->scope = NULL; + } + + talloc_free(namebuf); + *_r = r; + return NDR_ERR_SUCCESS; +} + +/** + push a nbt name, WINS Replication uses another on wire format for nbt name +*/ +_PUBLIC_ enum ndr_err_code ndr_push_wrepl_nbt_name(struct ndr_push *ndr, int ndr_flags, const struct nbt_name *r) +{ + uint8_t *namebuf; + uint32_t namebuf_len; + uint32_t _name_len; + uint32_t scope_len = 0; + + if (r == NULL) { + return ndr_push_error(ndr, NDR_ERR_INVALID_POINTER, + "wrepl_nbt_name NULL pointer"); + } + + if (!(ndr_flags & NDR_SCALARS)) { + return NDR_ERR_SUCCESS; + } + + _name_len = strlen(r->name); + if (_name_len > 15) { + return ndr_push_error(ndr, NDR_ERR_STRING, + "wrepl_nbt_name longer as 15 chars: %s", + r->name); + } + + if (r->scope) { + scope_len = strlen(r->scope); + } + if (scope_len > 238) { + return ndr_push_error(ndr, NDR_ERR_STRING, + "wrepl_nbt_name scope longer as 238 chars: %s", + r->scope); + } + + namebuf = (uint8_t *)talloc_asprintf(ndr, "%-15s%c%s", + r->name, 'X', + (r->scope?r->scope:"")); + if (!namebuf) return ndr_push_error(ndr, NDR_ERR_ALLOC, "out of memory"); + + namebuf_len = strlen((char *)namebuf) + 1; + + /* + * we need to set the type here, and use a place-holder in the talloc_asprintf() + * as the type can be 0x00, and then the namebuf_len = strlen(namebuf); would give wrong results + */ + namebuf[15] = r->type; + + /* oh wow, what a nasty bug in windows ... */ + if (r->type == 0x1b) { + namebuf[15] = namebuf[0]; + namebuf[0] = 0x1b; + } + + NDR_CHECK(ndr_push_align(ndr, 4)); + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, namebuf_len)); + NDR_CHECK(ndr_push_array_uint8(ndr, NDR_SCALARS, namebuf, namebuf_len)); + + talloc_free(namebuf); + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ void ndr_print_wrepl_nbt_name(struct ndr_print *ndr, const char *name, const struct nbt_name *r) +{ + char *s = nbt_name_string(ndr, r); + ndr_print_string(ndr, name, s); + talloc_free(s); +} + +_PUBLIC_ enum ndr_err_code ndr_push_nbt_res_rec(struct ndr_push *ndr, int ndr_flags, const struct nbt_res_rec *r) +{ + { + uint32_t _flags_save_STRUCT = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_PRINT_ARRAY_HEX); + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_push_align(ndr, 4)); + NDR_CHECK(ndr_push_nbt_name(ndr, NDR_SCALARS, &r->name)); + NDR_CHECK(ndr_push_nbt_qtype(ndr, NDR_SCALARS, r->rr_type)); + NDR_CHECK(ndr_push_nbt_qclass(ndr, NDR_SCALARS, r->rr_class)); + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->ttl)); + NDR_CHECK(ndr_push_set_switch_value(ndr, &r->rdata, ((((r->rr_type) == NBT_QTYPE_NETBIOS) && ((r->rdata).data.length == 2))?0:r->rr_type))); + NDR_CHECK(ndr_push_nbt_rdata(ndr, NDR_SCALARS, &r->rdata)); + } + if (ndr_flags & NDR_BUFFERS) { + } + ndr->flags = _flags_save_STRUCT; + } + return NDR_ERR_SUCCESS; +} diff --git a/libcli/nbt/nbtsocket.c b/libcli/nbt/nbtsocket.c new file mode 100644 index 0000000000..57531d2e7b --- /dev/null +++ b/libcli/nbt/nbtsocket.c @@ -0,0 +1,521 @@ +/* + Unix SMB/CIFS implementation. + + low level socket handling for nbt requests + + Copyright (C) Andrew Tridgell 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 . +*/ + +#include "includes.h" +#include "lib/events/events.h" +#include "lib/util/dlinklist.h" +#include "../libcli/nbt/libnbt.h" +#include "lib/socket/socket.h" +#include "librpc/gen_ndr/ndr_nbt.h" +#include "param/param.h" + +#define NBT_MAX_REPLIES 1000 + +/* + destroy a pending request +*/ +static int nbt_name_request_destructor(struct nbt_name_request *req) +{ + if (req->state == NBT_REQUEST_SEND) { + DLIST_REMOVE(req->nbtsock->send_queue, req); + } + if (req->state == NBT_REQUEST_WAIT) { + req->nbtsock->num_pending--; + } + if (req->name_trn_id != 0 && !req->is_reply) { + idr_remove(req->nbtsock->idr, req->name_trn_id); + req->name_trn_id = 0; + } + if (req->te) { + talloc_free(req->te); + req->te = NULL; + } + if (req->nbtsock->send_queue == NULL) { + EVENT_FD_NOT_WRITEABLE(req->nbtsock->fde); + } + if (req->nbtsock->num_pending == 0 && + req->nbtsock->incoming.handler == NULL) { + EVENT_FD_NOT_READABLE(req->nbtsock->fde); + } + return 0; +} + + +/* + handle send events on a nbt name socket +*/ +static void nbt_name_socket_send(struct nbt_name_socket *nbtsock) +{ + struct nbt_name_request *req = nbtsock->send_queue; + TALLOC_CTX *tmp_ctx = talloc_new(nbtsock); + NTSTATUS status; + + while ((req = nbtsock->send_queue)) { + size_t len; + + len = req->encoded.length; + status = socket_sendto(nbtsock->sock, &req->encoded, &len, + req->dest); + if (NT_STATUS_IS_ERR(status)) goto failed; + + if (!NT_STATUS_IS_OK(status)) { + talloc_free(tmp_ctx); + return; + } + + DLIST_REMOVE(nbtsock->send_queue, req); + req->state = NBT_REQUEST_WAIT; + if (req->is_reply) { + talloc_free(req); + } else { + EVENT_FD_READABLE(nbtsock->fde); + nbtsock->num_pending++; + } + } + + EVENT_FD_NOT_WRITEABLE(nbtsock->fde); + talloc_free(tmp_ctx); + return; + +failed: + DLIST_REMOVE(nbtsock->send_queue, req); + nbt_name_request_destructor(req); + req->status = status; + req->state = NBT_REQUEST_ERROR; + talloc_free(tmp_ctx); + if (req->async.fn) { + req->async.fn(req); + } else if (req->is_reply) { + talloc_free(req); + } + return; +} + + +/* + handle a request timeout +*/ +static void nbt_name_socket_timeout(struct event_context *ev, struct timed_event *te, + struct timeval t, void *private) +{ + struct nbt_name_request *req = talloc_get_type(private, + struct nbt_name_request); + + if (req->num_retries != 0) { + req->num_retries--; + req->te = event_add_timed(req->nbtsock->event_ctx, req, + timeval_add(&t, req->timeout, 0), + nbt_name_socket_timeout, req); + if (req->state != NBT_REQUEST_SEND) { + req->state = NBT_REQUEST_SEND; + DLIST_ADD_END(req->nbtsock->send_queue, req, + struct nbt_name_request *); + } + EVENT_FD_WRITEABLE(req->nbtsock->fde); + return; + } + + nbt_name_request_destructor(req); + if (req->num_replies == 0) { + req->state = NBT_REQUEST_TIMEOUT; + req->status = NT_STATUS_IO_TIMEOUT; + } else { + req->state = NBT_REQUEST_DONE; + req->status = NT_STATUS_OK; + } + if (req->async.fn) { + req->async.fn(req); + } else if (req->is_reply) { + talloc_free(req); + } +} + + + +/** + handle recv events on a nbt name socket +*/ +static void nbt_name_socket_recv(struct nbt_name_socket *nbtsock) +{ + TALLOC_CTX *tmp_ctx = talloc_new(nbtsock); + NTSTATUS status; + enum ndr_err_code ndr_err; + struct socket_address *src; + DATA_BLOB blob; + size_t nread, dsize; + struct nbt_name_packet *packet; + struct nbt_name_request *req; + + status = socket_pending(nbtsock->sock, &dsize); + if (!NT_STATUS_IS_OK(status)) { + talloc_free(tmp_ctx); + return; + } + + blob = data_blob_talloc(tmp_ctx, NULL, dsize); + if (blob.data == NULL) { + talloc_free(tmp_ctx); + return; + } + + status = socket_recvfrom(nbtsock->sock, blob.data, blob.length, &nread, + tmp_ctx, &src); + if (!NT_STATUS_IS_OK(status)) { + talloc_free(tmp_ctx); + return; + } + + packet = talloc(tmp_ctx, struct nbt_name_packet); + if (packet == NULL) { + talloc_free(tmp_ctx); + return; + } + + /* parse the request */ + ndr_err = ndr_pull_struct_blob(&blob, packet, nbtsock->iconv_convenience, packet, + (ndr_pull_flags_fn_t)ndr_pull_nbt_name_packet); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + status = ndr_map_error2ntstatus(ndr_err); + DEBUG(2,("Failed to parse incoming NBT name packet - %s\n", + nt_errstr(status))); + talloc_free(tmp_ctx); + return; + } + + if (DEBUGLVL(10)) { + DEBUG(10,("Received nbt packet of length %d from %s:%d\n", + (int)blob.length, src->addr, src->port)); + NDR_PRINT_DEBUG(nbt_name_packet, packet); + } + + /* if its not a reply then pass it off to the incoming request + handler, if any */ + if (!(packet->operation & NBT_FLAG_REPLY)) { + if (nbtsock->incoming.handler) { + nbtsock->incoming.handler(nbtsock, packet, src); + } + talloc_free(tmp_ctx); + return; + } + + /* find the matching request */ + req = (struct nbt_name_request *)idr_find(nbtsock->idr, + packet->name_trn_id); + if (req == NULL) { + if (nbtsock->unexpected.handler) { + nbtsock->unexpected.handler(nbtsock, packet, src); + } else { + DEBUG(10,("Failed to match request for incoming name packet id 0x%04x on %p\n", + packet->name_trn_id, nbtsock)); + } + talloc_free(tmp_ctx); + return; + } + + /* if this is a WACK response, this we need to go back to waiting, + but perhaps increase the timeout */ + if ((packet->operation & NBT_OPCODE) == NBT_OPCODE_WACK) { + if (req->received_wack || packet->ancount < 1) { + nbt_name_request_destructor(req); + req->status = NT_STATUS_INVALID_NETWORK_RESPONSE; + req->state = NBT_REQUEST_ERROR; + goto done; + } + talloc_free(req->te); + /* we know we won't need any more retries - the server + has received our request */ + req->num_retries = 0; + req->received_wack = true; + /* although there can be a timeout in the packet, w2k3 screws it up, + so better to set it ourselves */ + req->timeout = lp_parm_int(global_loadparm, NULL, "nbt", "wack_timeout", 30); + req->te = event_add_timed(req->nbtsock->event_ctx, req, + timeval_current_ofs(req->timeout, 0), + nbt_name_socket_timeout, req); + talloc_free(tmp_ctx); + return; + } + + + req->replies = talloc_realloc(req, req->replies, struct nbt_name_reply, req->num_replies+1); + if (req->replies == NULL) { + nbt_name_request_destructor(req); + req->state = NBT_REQUEST_ERROR; + req->status = NT_STATUS_NO_MEMORY; + goto done; + } + + talloc_steal(req, src); + req->replies[req->num_replies].dest = src; + talloc_steal(req, packet); + req->replies[req->num_replies].packet = packet; + req->num_replies++; + + /* if we don't want multiple replies then we are done */ + if (req->allow_multiple_replies && + req->num_replies < NBT_MAX_REPLIES) { + talloc_free(tmp_ctx); + return; + } + + nbt_name_request_destructor(req); + req->state = NBT_REQUEST_DONE; + req->status = NT_STATUS_OK; + +done: + talloc_free(tmp_ctx); + if (req->async.fn) { + req->async.fn(req); + } +} + +/* + handle fd events on a nbt_name_socket +*/ +static void nbt_name_socket_handler(struct event_context *ev, struct fd_event *fde, + uint16_t flags, void *private) +{ + struct nbt_name_socket *nbtsock = talloc_get_type(private, + struct nbt_name_socket); + if (flags & EVENT_FD_WRITE) { + nbt_name_socket_send(nbtsock); + } + if (flags & EVENT_FD_READ) { + nbt_name_socket_recv(nbtsock); + } +} + + +/* + initialise a nbt_name_socket. The event_ctx is optional, if provided + then operations will use that event context +*/ +_PUBLIC_ struct nbt_name_socket *nbt_name_socket_init(TALLOC_CTX *mem_ctx, + struct event_context *event_ctx, + struct smb_iconv_convenience *iconv_convenience) +{ + struct nbt_name_socket *nbtsock; + NTSTATUS status; + + nbtsock = talloc(mem_ctx, struct nbt_name_socket); + if (nbtsock == NULL) goto failed; + + nbtsock->event_ctx = talloc_reference(nbtsock, event_ctx); + if (nbtsock->event_ctx == NULL) goto failed; + + status = socket_create("ip", SOCKET_TYPE_DGRAM, &nbtsock->sock, 0); + if (!NT_STATUS_IS_OK(status)) goto failed; + + socket_set_option(nbtsock->sock, "SO_BROADCAST", "1"); + + talloc_steal(nbtsock, nbtsock->sock); + + nbtsock->idr = idr_init(nbtsock); + if (nbtsock->idr == NULL) goto failed; + + nbtsock->send_queue = NULL; + nbtsock->num_pending = 0; + nbtsock->incoming.handler = NULL; + nbtsock->unexpected.handler = NULL; + nbtsock->iconv_convenience = iconv_convenience; + + nbtsock->fde = event_add_fd(nbtsock->event_ctx, nbtsock, + socket_get_fd(nbtsock->sock), 0, + nbt_name_socket_handler, nbtsock); + + return nbtsock; + +failed: + talloc_free(nbtsock); + return NULL; +} + +/* + send off a nbt name request +*/ +struct nbt_name_request *nbt_name_request_send(struct nbt_name_socket *nbtsock, + struct socket_address *dest, + struct nbt_name_packet *request, + int timeout, int retries, + bool allow_multiple_replies) +{ + struct nbt_name_request *req; + int id; + enum ndr_err_code ndr_err; + + req = talloc_zero(nbtsock, struct nbt_name_request); + if (req == NULL) goto failed; + + req->nbtsock = nbtsock; + req->allow_multiple_replies = allow_multiple_replies; + req->state = NBT_REQUEST_SEND; + req->is_reply = false; + req->timeout = timeout; + req->num_retries = retries; + req->dest = dest; + if (talloc_reference(req, dest) == NULL) goto failed; + + /* we select a random transaction id unless the user supplied one */ + if (request->name_trn_id == 0) { + id = idr_get_new_random(req->nbtsock->idr, req, UINT16_MAX); + } else { + if (idr_find(req->nbtsock->idr, request->name_trn_id)) goto failed; + id = idr_get_new_above(req->nbtsock->idr, req, request->name_trn_id, + UINT16_MAX); + } + if (id == -1) goto failed; + + request->name_trn_id = id; + req->name_trn_id = id; + + req->te = event_add_timed(nbtsock->event_ctx, req, + timeval_current_ofs(req->timeout, 0), + nbt_name_socket_timeout, req); + + talloc_set_destructor(req, nbt_name_request_destructor); + + ndr_err = ndr_push_struct_blob(&req->encoded, req, + req->nbtsock->iconv_convenience, + request, + (ndr_push_flags_fn_t)ndr_push_nbt_name_packet); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) goto failed; + + DLIST_ADD_END(nbtsock->send_queue, req, struct nbt_name_request *); + + if (DEBUGLVL(10)) { + DEBUG(10,("Queueing nbt packet to %s:%d\n", + req->dest->addr, req->dest->port)); + NDR_PRINT_DEBUG(nbt_name_packet, request); + } + + EVENT_FD_WRITEABLE(nbtsock->fde); + + return req; + +failed: + talloc_free(req); + return NULL; +} + + +/* + send off a nbt name reply +*/ +_PUBLIC_ NTSTATUS nbt_name_reply_send(struct nbt_name_socket *nbtsock, + struct socket_address *dest, + struct nbt_name_packet *request) +{ + struct nbt_name_request *req; + enum ndr_err_code ndr_err; + + req = talloc_zero(nbtsock, struct nbt_name_request); + NT_STATUS_HAVE_NO_MEMORY(req); + + req->nbtsock = nbtsock; + req->dest = dest; + if (talloc_reference(req, dest) == NULL) goto failed; + req->state = NBT_REQUEST_SEND; + req->is_reply = true; + + talloc_set_destructor(req, nbt_name_request_destructor); + + if (DEBUGLVL(10)) { + NDR_PRINT_DEBUG(nbt_name_packet, request); + } + + ndr_err = ndr_push_struct_blob(&req->encoded, req, + req->nbtsock->iconv_convenience, + request, + (ndr_push_flags_fn_t)ndr_push_nbt_name_packet); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + talloc_free(req); + return ndr_map_error2ntstatus(ndr_err); + } + + DLIST_ADD_END(nbtsock->send_queue, req, struct nbt_name_request *); + + EVENT_FD_WRITEABLE(nbtsock->fde); + + return NT_STATUS_OK; + +failed: + talloc_free(req); + return NT_STATUS_NO_MEMORY; +} + +/* + wait for a nbt request to complete +*/ +NTSTATUS nbt_name_request_recv(struct nbt_name_request *req) +{ + if (!req) return NT_STATUS_NO_MEMORY; + + while (req->state < NBT_REQUEST_DONE) { + if (event_loop_once(req->nbtsock->event_ctx) != 0) { + req->state = NBT_REQUEST_ERROR; + req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR; + break; + } + } + return req->status; +} + + +/* + setup a handler for incoming requests +*/ +_PUBLIC_ NTSTATUS nbt_set_incoming_handler(struct nbt_name_socket *nbtsock, + void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, + struct socket_address *), + void *private) +{ + nbtsock->incoming.handler = handler; + nbtsock->incoming.private_data = private; + EVENT_FD_READABLE(nbtsock->fde); + return NT_STATUS_OK; +} + + +/* + turn a NBT rcode into a NTSTATUS +*/ +_PUBLIC_ NTSTATUS nbt_rcode_to_ntstatus(uint8_t rcode) +{ + int i; + struct { + enum nbt_rcode rcode; + NTSTATUS status; + } map[] = { + { NBT_RCODE_FMT, NT_STATUS_INVALID_PARAMETER }, + { NBT_RCODE_SVR, NT_STATUS_SERVER_DISABLED }, + { NBT_RCODE_NAM, NT_STATUS_OBJECT_NAME_NOT_FOUND }, + { NBT_RCODE_IMP, NT_STATUS_NOT_SUPPORTED }, + { NBT_RCODE_RFS, NT_STATUS_ACCESS_DENIED }, + { NBT_RCODE_ACT, NT_STATUS_ADDRESS_ALREADY_EXISTS }, + { NBT_RCODE_CFT, NT_STATUS_CONFLICTING_ADDRESSES } + }; + for (i=0;i 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 . +*/ + +#include "includes.h" +#include +#include "libcli/util/pyerrors.h" +#include "../libcli/nbt/libnbt.h" +#include "lib/events/events.h" +#include "param/param.h" + +PyAPI_DATA(PyTypeObject) nbt_node_Type; + +typedef struct { + PyObject_HEAD + TALLOC_CTX *mem_ctx; + struct nbt_name_socket *socket; +} nbt_node_Object; + +static void py_nbt_node_dealloc(PyObject *obj) +{ + talloc_free(((nbt_node_Object *)obj)->mem_ctx); + PyObject_Del(obj); +} + +static PyObject *py_nbt_node_init(PyTypeObject *self, PyObject *args, PyObject *kwargs) +{ + struct event_context *ev; + nbt_node_Object *ret = PyObject_New(nbt_node_Object, &nbt_node_Type); + + ret->mem_ctx = talloc_new(NULL); + if (ret->mem_ctx == NULL) + return NULL; + + ev = s4_event_context_init(ret->mem_ctx); + ret->socket = nbt_name_socket_init(ret->mem_ctx, ev, lp_iconv_convenience(global_loadparm)); + return (PyObject *)ret; +} + +static bool PyObject_AsDestinationTuple(PyObject *obj, const char **dest_addr, uint16_t *dest_port) +{ + if (PyString_Check(obj)) { + *dest_addr = PyString_AsString(obj); + *dest_port = NBT_NAME_SERVICE_PORT; + return true; + } + + if (PyTuple_Check(obj)) { + if (PyTuple_Size(obj) < 1) { + PyErr_SetString(PyExc_TypeError, "Destination tuple size invalid"); + return false; + } + + if (!PyString_Check(PyTuple_GetItem(obj, 0))) { + PyErr_SetString(PyExc_TypeError, "Destination tuple first element not string"); + return false; + } + + *dest_addr = PyString_AsString(obj); + + if (PyTuple_Size(obj) == 1) { + *dest_port = NBT_NAME_SERVICE_PORT; + return true; + } else if (PyInt_Check(PyTuple_GetItem(obj, 1))) { + *dest_port = PyInt_AsLong(PyTuple_GetItem(obj, 1)); + return true; + } else { + PyErr_SetString(PyExc_TypeError, "Destination tuple second element not a port"); + return false; + } + } + + PyErr_SetString(PyExc_TypeError, "Destination tuple second element not a port"); + return false; +} + +static bool PyObject_AsNBTName(PyObject *obj, struct nbt_name_socket *socket, struct nbt_name *name) +{ + if (PyTuple_Check(obj)) { + if (PyTuple_Size(obj) == 2) { + name->name = PyString_AsString(PyTuple_GetItem(obj, 0)); + name->type = PyInt_AsLong(PyTuple_GetItem(obj, 1)); + name->scope = NULL; + return true; + } else if (PyTuple_Size(obj) == 3) { + name->name = PyString_AsString(PyTuple_GetItem(obj, 0)); + name->scope = PyString_AsString(PyTuple_GetItem(obj, 1)); + name->type = PyInt_AsLong(PyTuple_GetItem(obj, 2)); + return true; + } else { + PyErr_SetString(PyExc_TypeError, "Invalid tuple size"); + return false; + } + } + + if (PyString_Check(obj)) { + /* FIXME: Parse string to be able to interpret things like RHONWYN<02> ? */ + name->name = PyString_AsString(obj); + name->scope = NULL; + name->type = 0; + return true; + } + + PyErr_SetString(PyExc_TypeError, "Invalid type for object"); + return false; +} + +static PyObject *PyObject_FromNBTName(struct nbt_name_socket *socket, struct smb_iconv_convenience *ic, + struct nbt_name *name) +{ + if (name->scope) { + return Py_BuildValue("(ssi)", name->name, name->scope, name->type); + } else { + return Py_BuildValue("(si)", name->name, name->type); + } +} + +static PyObject *py_nbt_name_query(PyObject *self, PyObject *args, PyObject *kwargs) +{ + nbt_node_Object *node = (nbt_node_Object *)self; + PyObject *ret, *reply_addrs, *py_dest, *py_name; + struct nbt_name_query io; + NTSTATUS status; + int i; + + const char *kwnames[] = { "name", "dest", "broadcast", "wins", "timeout", + "retries", NULL }; + io.in.broadcast = true; + io.in.wins_lookup = false; + io.in.timeout = 0; + io.in.retries = 3; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|bbii:query_name", + discard_const_p(char *, kwnames), + &py_name, &py_dest, + &io.in.broadcast, &io.in.wins_lookup, + &io.in.timeout, &io.in.retries)) { + return NULL; + } + + if (!PyObject_AsDestinationTuple(py_dest, &io.in.dest_addr, &io.in.dest_port)) + return NULL; + + if (!PyObject_AsNBTName(py_name, node->socket, &io.in.name)) + return NULL; + + status = nbt_name_query(node->socket, NULL, &io); + + if (NT_STATUS_IS_ERR(status)) { + PyErr_SetNTSTATUS(status); + return NULL; + } + + ret = PyTuple_New(3); + if (ret == NULL) + return NULL; + PyTuple_SetItem(ret, 0, PyString_FromString(io.out.reply_from)); + + py_name = PyObject_FromNBTName(node->socket, lp_iconv_convenience(global_loadparm), &io.out.name); + if (py_name == NULL) + return NULL; + + PyTuple_SetItem(ret, 1, py_name); + + reply_addrs = PyList_New(io.out.num_addrs); + if (reply_addrs == NULL) { + Py_DECREF(ret); + return NULL; + } + + for (i = 0; i < io.out.num_addrs; i++) { + PyList_SetItem(reply_addrs, i, PyString_FromString(io.out.reply_addrs[i])); + } + + PyTuple_SetItem(ret, 2, reply_addrs); + return ret; +} + +static PyObject *py_nbt_name_status(PyObject *self, PyObject *args, PyObject *kwargs) +{ + nbt_node_Object *node = (nbt_node_Object *)self; + PyObject *ret, *py_dest, *py_name, *py_names; + struct nbt_name_status io; + int i; + NTSTATUS status; + + const char *kwnames[] = { "name", "dest", "timeout", "retries", NULL }; + + io.in.timeout = 0; + io.in.retries = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|ii:name_status", + discard_const_p(char *, kwnames), + &py_name, &py_dest, + &io.in.timeout, &io.in.retries)) { + return NULL; + } + + if (!PyObject_AsDestinationTuple(py_dest, &io.in.dest_addr, &io.in.dest_port)) + return NULL; + + if (!PyObject_AsNBTName(py_name, node->socket, &io.in.name)) + return NULL; + + status = nbt_name_status(node->socket, NULL, &io); + + if (NT_STATUS_IS_ERR(status)) { + PyErr_SetNTSTATUS(status); + return NULL; + } + + ret = PyTuple_New(3); + if (ret == NULL) + return NULL; + PyTuple_SetItem(ret, 0, PyString_FromString(io.out.reply_from)); + + py_name = PyObject_FromNBTName(node->socket, lp_iconv_convenience(global_loadparm), &io.out.name); + if (py_name == NULL) + return NULL; + + PyTuple_SetItem(ret, 1, py_name); + + py_names = PyList_New(io.out.status.num_names); + + for (i = 0; i < io.out.status.num_names; i++) { + PyList_SetItem(py_names, i, Py_BuildValue("(sii)", + io.out.status.names[i].name, + io.out.status.names[i].nb_flags, + io.out.status.names[i].type)); + } + + PyTuple_SetItem(ret, 2, py_names); + + return ret; +} + +static PyObject *py_nbt_name_register(PyObject *self, PyObject *args, PyObject *kwargs) +{ + nbt_node_Object *node = (nbt_node_Object *)self; + PyObject *ret, *py_dest, *py_name; + struct nbt_name_register io; + NTSTATUS status; + + const char *kwnames[] = { "name", "address", "dest", "register_demand", "broadcast", + "multi_homed", "ttl", "timeout", "retries", NULL }; + + io.in.broadcast = true; + io.in.multi_homed = true; + io.in.register_demand = true; + io.in.timeout = 0; + io.in.retries = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OsO|bbbiii:query_name", + discard_const_p(char *, kwnames), + &py_name, &io.in.address, &py_dest, + &io.in.register_demand, + &io.in.broadcast, &io.in.multi_homed, + &io.in.ttl, &io.in.timeout, &io.in.retries)) { + return NULL; + } + + if (!PyObject_AsDestinationTuple(py_dest, &io.in.dest_addr, &io.in.dest_port)) + return NULL; + + if (!PyObject_AsNBTName(py_name, node->socket, &io.in.name)) + return NULL; + + status = nbt_name_register(node->socket, NULL, &io); + + if (NT_STATUS_IS_ERR(status)) { + PyErr_SetNTSTATUS(status); + return NULL; + } + + ret = PyTuple_New(3); + if (ret == NULL) + return NULL; + PyTuple_SetItem(ret, 0, PyString_FromString(io.out.reply_from)); + + py_name = PyObject_FromNBTName(node->socket, lp_iconv_convenience(global_loadparm), &io.out.name); + if (py_name == NULL) + return NULL; + + PyTuple_SetItem(ret, 1, py_name); + + PyTuple_SetItem(ret, 2, PyString_FromString(io.out.reply_addr)); + + PyTuple_SetItem(ret, 3, PyInt_FromLong(io.out.rcode)); + + return ret; +} + +static PyObject *py_nbt_name_refresh(PyObject *self, PyObject *args, PyObject *kwargs) +{ + nbt_node_Object *node = (nbt_node_Object *)self; + PyObject *ret, *py_dest, *py_name; + struct nbt_name_refresh io; + NTSTATUS status; + + const char *kwnames[] = { "name", "address", "dest", "nb_flags", "broadcast", + "ttl", "timeout", "retries", NULL }; + + io.in.broadcast = true; + io.in.nb_flags = 0; + io.in.timeout = 0; + io.in.retries = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OsO|ibiii:query_name", + discard_const_p(char *, kwnames), + &py_name, &io.in.address, &py_dest, + &io.in.nb_flags, + &io.in.broadcast, + &io.in.ttl, &io.in.timeout, &io.in.retries)) { + return NULL; + } + + if (!PyObject_AsDestinationTuple(py_dest, &io.in.dest_addr, &io.in.dest_port)) + return NULL; + + if (!PyObject_AsNBTName(py_name, node->socket, &io.in.name)) + return NULL; + + status = nbt_name_refresh(node->socket, NULL, &io); + + if (NT_STATUS_IS_ERR(status)) { + PyErr_SetNTSTATUS(status); + return NULL; + } + + ret = PyTuple_New(3); + if (ret == NULL) + return NULL; + PyTuple_SetItem(ret, 0, PyString_FromString(io.out.reply_from)); + + py_name = PyObject_FromNBTName(node->socket, lp_iconv_convenience(global_loadparm), &io.out.name); + if (py_name == NULL) + return NULL; + + PyTuple_SetItem(ret, 1, py_name); + + PyTuple_SetItem(ret, 2, PyString_FromString(io.out.reply_addr)); + + PyTuple_SetItem(ret, 3, PyInt_FromLong(io.out.rcode)); + + return ret; +} + +static PyObject *py_nbt_name_release(PyObject *self, PyObject *args, PyObject *kwargs) +{ + return Py_None; /* FIXME */ +} + +static PyMethodDef py_nbt_methods[] = { + { "query_name", (PyCFunction)py_nbt_name_query, METH_VARARGS|METH_KEYWORDS, + "S.query_name(name, dest, broadcast=True, wins=False, timeout=0, retries=3) -> (reply_from, name, reply_addr)\n" + "Query for a NetBIOS name" }, + { "register_name", (PyCFunction)py_nbt_name_register, METH_VARARGS|METH_KEYWORDS, + "S.register_name(name, address, dest, register_demand=True, broadcast=True, multi_homed=True, ttl=0, timeout=0, retries=0) -> (reply_from, name, reply_addr, rcode)\n" + "Register a new name" }, + { "release_name", (PyCFunction)py_nbt_name_release, METH_VARARGS|METH_KEYWORDS, "S.release_name(name, address, dest, nb_flags=0, broadcast=true, timeout=0, retries=3) -> (reply_from, name, reply_addr, rcode)\n" + "release a previously registered name" }, + { "refresh_name", (PyCFunction)py_nbt_name_refresh, METH_VARARGS|METH_KEYWORDS, "S.refresh_name(name, address, dest, nb_flags=0, broadcast=True, ttl=0, timeout=0, retries=0) -> (reply_from, name, reply_addr, rcode)\n" + "release a previously registered name" }, + { "name_status", (PyCFunction)py_nbt_name_status, METH_VARARGS|METH_KEYWORDS, + "S.name_status(name, dest, timeout=0, retries=0) -> (reply_from, name, status)\n" + "Find the status of a name" }, + + { NULL } +}; + +PyTypeObject nbt_node_Type = { + PyObject_HEAD_INIT(NULL) 0, + .tp_name = "netbios.Node", + .tp_basicsize = sizeof(nbt_node_Object), + .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, + .tp_new = py_nbt_node_init, + .tp_dealloc = py_nbt_node_dealloc, + .tp_methods = py_nbt_methods, + .tp_doc = "Node()\n" + "Create a new NetBIOS node\n" +}; + +void initnetbios(void) +{ + PyObject *mod; + if (PyType_Ready(&nbt_node_Type) < 0) + return; + + mod = Py_InitModule3("netbios", NULL, "NetBIOS over TCP/IP support"); + + Py_INCREF((PyObject *)&nbt_node_Type); + PyModule_AddObject(mod, "Node", (PyObject *)&nbt_node_Type); +} diff --git a/source4/libcli/nbt/libnbt.h b/source4/libcli/nbt/libnbt.h deleted file mode 100644 index 8529ec362b..0000000000 --- a/source4/libcli/nbt/libnbt.h +++ /dev/null @@ -1,351 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - a raw async NBT library - - Copyright (C) Andrew Tridgell 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 . -*/ - -#ifndef __LIBNBT_H__ -#define __LIBNBT_H__ - -#include "librpc/gen_ndr/nbt.h" -#include "librpc/ndr/libndr.h" - -/* - possible states for pending requests -*/ -enum nbt_request_state {NBT_REQUEST_SEND, - NBT_REQUEST_WAIT, - NBT_REQUEST_DONE, - NBT_REQUEST_TIMEOUT, - NBT_REQUEST_ERROR}; - -/* - a nbt name request -*/ -struct nbt_name_request { - struct nbt_name_request *next, *prev; - - enum nbt_request_state state; - - NTSTATUS status; - - /* the socket this was on */ - struct nbt_name_socket *nbtsock; - - /* where to send the request */ - struct socket_address *dest; - - /* timeout between retries */ - int timeout; - - /* how many retries to send on timeout */ - int num_retries; - - /* whether we have received a WACK */ - bool received_wack; - - /* the timeout event */ - struct timed_event *te; - - /* the name transaction id */ - uint16_t name_trn_id; - - /* is it a reply? */ - bool is_reply; - - /* the encoded request */ - DATA_BLOB encoded; - - /* shall we allow multiple replies? */ - bool allow_multiple_replies; - - unsigned int num_replies; - struct nbt_name_reply { - struct nbt_name_packet *packet; - struct socket_address *dest; - } *replies; - - /* information on what to do on completion */ - struct { - void (*fn)(struct nbt_name_request *); - void *private_data; - } async; -}; - - - -/* - context structure for operations on name queries -*/ -struct nbt_name_socket { - struct socket_context *sock; - struct event_context *event_ctx; - struct smb_iconv_convenience *iconv_convenience; - - /* a queue of requests pending to be sent */ - struct nbt_name_request *send_queue; - - /* the fd event */ - struct fd_event *fde; - - /* mapping from name_trn_id to pending event */ - struct idr_context *idr; - - /* how many requests are waiting for a reply */ - uint16_t num_pending; - - /* what to do with incoming request packets */ - struct { - void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, - struct socket_address *); - void *private_data; - } incoming; - - /* what to do with unexpected replies */ - struct { - void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, - struct socket_address *); - void *private_data; - } unexpected; -}; - - -/* a simple name query */ -struct nbt_name_query { - struct { - struct nbt_name name; - const char *dest_addr; - uint16_t dest_port; - bool broadcast; - bool wins_lookup; - int timeout; /* in seconds */ - int retries; - } in; - struct { - const char *reply_from; - struct nbt_name name; - int16_t num_addrs; - const char **reply_addrs; - } out; -}; - -/* a simple name status query */ -struct nbt_name_status { - struct { - struct nbt_name name; - const char *dest_addr; - uint16_t dest_port; - int timeout; /* in seconds */ - int retries; - } in; - struct { - const char *reply_from; - struct nbt_name name; - struct nbt_rdata_status status; - } out; -}; - -/* a name registration request */ -struct nbt_name_register { - struct { - struct nbt_name name; - const char *dest_addr; - uint16_t dest_port; - const char *address; - uint16_t nb_flags; - bool register_demand; - bool broadcast; - bool multi_homed; - uint32_t ttl; - int timeout; /* in seconds */ - int retries; - } in; - struct { - const char *reply_from; - struct nbt_name name; - const char *reply_addr; - uint8_t rcode; - } out; -}; - -/* a send 3 times then demand name broadcast name registration */ -struct nbt_name_register_bcast { - struct { - struct nbt_name name; - const char *dest_addr; - uint16_t dest_port; - const char *address; - uint16_t nb_flags; - uint32_t ttl; - } in; -}; - - -/* wins name register with multiple wins servers to try and multiple - addresses to register */ -struct nbt_name_register_wins { - struct { - struct nbt_name name; - const char **wins_servers; - uint16_t wins_port; - const char **addresses; - uint16_t nb_flags; - uint32_t ttl; - } in; - struct { - const char *wins_server; - uint8_t rcode; - } out; -}; - - - -/* a name refresh request */ -struct nbt_name_refresh { - struct { - struct nbt_name name; - const char *dest_addr; - uint16_t dest_port; - const char *address; - uint16_t nb_flags; - bool broadcast; - uint32_t ttl; - int timeout; /* in seconds */ - int retries; - } in; - struct { - const char *reply_from; - struct nbt_name name; - const char *reply_addr; - uint8_t rcode; - } out; -}; - -/* wins name refresh with multiple wins servers to try and multiple - addresses to register */ -struct nbt_name_refresh_wins { - struct { - struct nbt_name name; - const char **wins_servers; - uint16_t wins_port; - const char **addresses; - uint16_t nb_flags; - uint32_t ttl; - } in; - struct { - const char *wins_server; - uint8_t rcode; - } out; -}; - - -/* a name release request */ -struct nbt_name_release { - struct { - struct nbt_name name; - const char *dest_addr; - uint16_t dest_port; - const char *address; - uint16_t nb_flags; - bool broadcast; - int timeout; /* in seconds */ - int retries; - } in; - struct { - const char *reply_from; - struct nbt_name name; - const char *reply_addr; - uint8_t rcode; - } out; -}; - -struct nbt_name_socket *nbt_name_socket_init(TALLOC_CTX *mem_ctx, - struct event_context *event_ctx, - struct smb_iconv_convenience *iconv_convenience); -struct nbt_name_request *nbt_name_query_send(struct nbt_name_socket *nbtsock, - struct nbt_name_query *io); -NTSTATUS nbt_name_query_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_query *io); -NTSTATUS nbt_name_query(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_query *io); -struct nbt_name_request *nbt_name_status_send(struct nbt_name_socket *nbtsock, - struct nbt_name_status *io); -NTSTATUS nbt_name_status_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_status *io); -NTSTATUS nbt_name_status(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_status *io); - -NTSTATUS nbt_name_dup(TALLOC_CTX *mem_ctx, struct nbt_name *name, struct nbt_name *newname); -NTSTATUS nbt_name_to_blob(TALLOC_CTX *mem_ctx, struct smb_iconv_convenience *iconv_convenience, DATA_BLOB *blob, struct nbt_name *name); -NTSTATUS nbt_name_from_blob(TALLOC_CTX *mem_ctx, const DATA_BLOB *blob, struct nbt_name *name); -void nbt_choose_called_name(TALLOC_CTX *mem_ctx, struct nbt_name *n, const char *name, int type); -char *nbt_name_string(TALLOC_CTX *mem_ctx, const struct nbt_name *name); -NTSTATUS nbt_name_register(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_register *io); -NTSTATUS nbt_name_refresh(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_refresh *io); -NTSTATUS nbt_name_release(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_release *io); -NTSTATUS nbt_name_register_wins(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, - struct nbt_name_register_wins *io); -NTSTATUS nbt_name_refresh_wins(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, - struct nbt_name_refresh_wins *io); -NTSTATUS nbt_name_register_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_register *io); -struct nbt_name_request *nbt_name_register_send(struct nbt_name_socket *nbtsock, - struct nbt_name_register *io); -NTSTATUS nbt_name_release_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_release *io); - -struct nbt_name_request *nbt_name_release_send(struct nbt_name_socket *nbtsock, - struct nbt_name_release *io); - -NTSTATUS nbt_name_refresh_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_refresh *io); - -NTSTATUS nbt_set_incoming_handler(struct nbt_name_socket *nbtsock, - void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, - struct socket_address *), - void *private_data); -NTSTATUS nbt_name_reply_send(struct nbt_name_socket *nbtsock, - struct socket_address *dest, - struct nbt_name_packet *request); - - -NDR_SCALAR_PROTO(wrepl_nbt_name, const struct nbt_name *); -NDR_SCALAR_PROTO(nbt_string, const char *); -NDR_BUFFER_PROTO(nbt_name, struct nbt_name); -NTSTATUS nbt_rcode_to_ntstatus(uint8_t rcode); - -struct composite_context; -struct composite_context *nbt_name_register_bcast_send(struct nbt_name_socket *nbtsock, - struct nbt_name_register_bcast *io); -NTSTATUS nbt_name_register_bcast_recv(struct composite_context *c); -struct composite_context *nbt_name_register_wins_send(struct nbt_name_socket *nbtsock, - struct nbt_name_register_wins *io); -NTSTATUS nbt_name_refresh_wins_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, - struct nbt_name_refresh_wins *io); -struct composite_context *nbt_name_refresh_wins_send(struct nbt_name_socket *nbtsock, - struct nbt_name_refresh_wins *io); -NTSTATUS nbt_name_register_wins_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, - struct nbt_name_register_wins *io); - - -#endif /* __LIBNBT_H__ */ diff --git a/source4/libcli/nbt/namequery.c b/source4/libcli/nbt/namequery.c deleted file mode 100644 index 2e1bcd818b..0000000000 --- a/source4/libcli/nbt/namequery.c +++ /dev/null @@ -1,235 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - make nbt name query requests - - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "includes.h" -#include "libcli/nbt/libnbt.h" -#include "libcli/nbt/nbt_proto.h" -#include "lib/socket/socket.h" -#include "param/param.h" - -/** - send a nbt name query -*/ -_PUBLIC_ struct nbt_name_request *nbt_name_query_send(struct nbt_name_socket *nbtsock, - struct nbt_name_query *io) -{ - struct nbt_name_request *req; - struct nbt_name_packet *packet; - struct socket_address *dest; - - packet = talloc_zero(nbtsock, struct nbt_name_packet); - if (packet == NULL) return NULL; - - packet->qdcount = 1; - packet->operation = NBT_OPCODE_QUERY; - if (io->in.broadcast) { - packet->operation |= NBT_FLAG_BROADCAST; - } - if (io->in.wins_lookup) { - packet->operation |= NBT_FLAG_RECURSION_DESIRED; - } - - packet->questions = talloc_array(packet, struct nbt_name_question, 1); - if (packet->questions == NULL) goto failed; - - packet->questions[0].name = io->in.name; - packet->questions[0].question_type = NBT_QTYPE_NETBIOS; - packet->questions[0].question_class = NBT_QCLASS_IP; - - dest = socket_address_from_strings(packet, nbtsock->sock->backend_name, - io->in.dest_addr, io->in.dest_port); - if (dest == NULL) goto failed; - req = nbt_name_request_send(nbtsock, dest, packet, - io->in.timeout, io->in.retries, false); - if (req == NULL) goto failed; - - talloc_free(packet); - return req; - -failed: - talloc_free(packet); - return NULL; -} - -/** - wait for a name query reply -*/ -_PUBLIC_ NTSTATUS nbt_name_query_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_query *io) -{ - NTSTATUS status; - struct nbt_name_packet *packet; - int i; - - status = nbt_name_request_recv(req); - if (!NT_STATUS_IS_OK(status) || - req->num_replies == 0) { - talloc_free(req); - return status; - } - - packet = req->replies[0].packet; - io->out.reply_from = talloc_steal(mem_ctx, req->replies[0].dest->addr); - - if ((packet->operation & NBT_RCODE) != 0) { - status = nbt_rcode_to_ntstatus(packet->operation & NBT_RCODE); - talloc_free(req); - return status; - } - - if (packet->ancount != 1 || - packet->answers[0].rr_type != NBT_QTYPE_NETBIOS || - packet->answers[0].rr_class != NBT_QCLASS_IP) { - talloc_free(req); - return status; - } - - io->out.name = packet->answers[0].name; - io->out.num_addrs = packet->answers[0].rdata.netbios.length / 6; - io->out.reply_addrs = talloc_array(mem_ctx, const char *, io->out.num_addrs+1); - if (io->out.reply_addrs == NULL) { - talloc_free(req); - return NT_STATUS_NO_MEMORY; - } - - for (i=0;iout.num_addrs;i++) { - io->out.reply_addrs[i] = talloc_steal(io->out.reply_addrs, - packet->answers[0].rdata.netbios.addresses[i].ipaddr); - } - io->out.reply_addrs[i] = NULL; - - talloc_steal(mem_ctx, io->out.name.name); - talloc_steal(mem_ctx, io->out.name.scope); - - talloc_free(req); - - return NT_STATUS_OK; -} - -/** - wait for a name query reply -*/ -_PUBLIC_ NTSTATUS nbt_name_query(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_query *io) -{ - struct nbt_name_request *req = nbt_name_query_send(nbtsock, io); - return nbt_name_query_recv(req, mem_ctx, io); -} - - -/** - send a nbt name status -*/ -_PUBLIC_ struct nbt_name_request *nbt_name_status_send(struct nbt_name_socket *nbtsock, - struct nbt_name_status *io) -{ - struct nbt_name_request *req; - struct nbt_name_packet *packet; - struct socket_address *dest; - - packet = talloc_zero(nbtsock, struct nbt_name_packet); - if (packet == NULL) return NULL; - - packet->qdcount = 1; - packet->operation = NBT_OPCODE_QUERY; - - packet->questions = talloc_array(packet, struct nbt_name_question, 1); - if (packet->questions == NULL) goto failed; - - packet->questions[0].name = io->in.name; - packet->questions[0].question_type = NBT_QTYPE_STATUS; - packet->questions[0].question_class = NBT_QCLASS_IP; - - dest = socket_address_from_strings(packet, nbtsock->sock->backend_name, - io->in.dest_addr, io->in.dest_port); - if (dest == NULL) goto failed; - req = nbt_name_request_send(nbtsock, dest, packet, - io->in.timeout, io->in.retries, false); - if (req == NULL) goto failed; - - talloc_free(packet); - return req; - -failed: - talloc_free(packet); - return NULL; -} - -/** - wait for a name status reply -*/ -_PUBLIC_ NTSTATUS nbt_name_status_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_status *io) -{ - NTSTATUS status; - struct nbt_name_packet *packet; - int i; - - status = nbt_name_request_recv(req); - if (!NT_STATUS_IS_OK(status) || - req->num_replies == 0) { - talloc_free(req); - return status; - } - - packet = req->replies[0].packet; - io->out.reply_from = talloc_steal(mem_ctx, req->replies[0].dest->addr); - - if ((packet->operation & NBT_RCODE) != 0) { - status = nbt_rcode_to_ntstatus(packet->operation & NBT_RCODE); - talloc_free(req); - return status; - } - - if (packet->ancount != 1 || - packet->answers[0].rr_type != NBT_QTYPE_STATUS || - packet->answers[0].rr_class != NBT_QCLASS_IP) { - talloc_free(req); - return NT_STATUS_INVALID_NETWORK_RESPONSE; - } - - io->out.name = packet->answers[0].name; - talloc_steal(mem_ctx, io->out.name.name); - talloc_steal(mem_ctx, io->out.name.scope); - - io->out.status = packet->answers[0].rdata.status; - talloc_steal(mem_ctx, io->out.status.names); - for (i=0;iout.status.num_names;i++) { - talloc_steal(io->out.status.names, io->out.status.names[i].name); - } - - - talloc_free(req); - - return NT_STATUS_OK; -} - -/** - wait for a name status reply -*/ -_PUBLIC_ NTSTATUS nbt_name_status(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_status *io) -{ - struct nbt_name_request *req = nbt_name_status_send(nbtsock, io); - return nbt_name_status_recv(req, mem_ctx, io); -} - - diff --git a/source4/libcli/nbt/namerefresh.c b/source4/libcli/nbt/namerefresh.c deleted file mode 100644 index b939c97740..0000000000 --- a/source4/libcli/nbt/namerefresh.c +++ /dev/null @@ -1,302 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - send out a name refresh request - - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "includes.h" -#include "libcli/nbt/libnbt.h" -#include "libcli/nbt/nbt_proto.h" -#include "libcli/composite/composite.h" -#include "lib/socket/socket.h" -#include "param/param.h" - -/* - send a nbt name refresh request -*/ -struct nbt_name_request *nbt_name_refresh_send(struct nbt_name_socket *nbtsock, - struct nbt_name_refresh *io) -{ - struct nbt_name_request *req; - struct nbt_name_packet *packet; - struct socket_address *dest; - - packet = talloc_zero(nbtsock, struct nbt_name_packet); - if (packet == NULL) return NULL; - - packet->qdcount = 1; - packet->arcount = 1; - packet->operation = NBT_OPCODE_REFRESH; - if (io->in.broadcast) { - packet->operation |= NBT_FLAG_BROADCAST; - } - - packet->questions = talloc_array(packet, struct nbt_name_question, 1); - if (packet->questions == NULL) goto failed; - - packet->questions[0].name = io->in.name; - packet->questions[0].question_type = NBT_QTYPE_NETBIOS; - packet->questions[0].question_class = NBT_QCLASS_IP; - - packet->additional = talloc_array(packet, struct nbt_res_rec, 1); - if (packet->additional == NULL) goto failed; - - packet->additional[0].name = io->in.name; - packet->additional[0].rr_type = NBT_QTYPE_NETBIOS; - packet->additional[0].rr_class = NBT_QCLASS_IP; - packet->additional[0].ttl = io->in.ttl; - packet->additional[0].rdata.netbios.length = 6; - packet->additional[0].rdata.netbios.addresses = talloc_array(packet->additional, - struct nbt_rdata_address, 1); - if (packet->additional[0].rdata.netbios.addresses == NULL) goto failed; - packet->additional[0].rdata.netbios.addresses[0].nb_flags = io->in.nb_flags; - packet->additional[0].rdata.netbios.addresses[0].ipaddr = - talloc_strdup(packet->additional, io->in.address); - - dest = socket_address_from_strings(nbtsock, - nbtsock->sock->backend_name, - io->in.dest_addr, io->in.dest_port); - if (dest == NULL) goto failed; - req = nbt_name_request_send(nbtsock, dest, packet, - io->in.timeout, io->in.retries, false); - if (req == NULL) goto failed; - - talloc_free(packet); - return req; - -failed: - talloc_free(packet); - return NULL; -} - -/* - wait for a refresh reply -*/ -_PUBLIC_ NTSTATUS nbt_name_refresh_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_refresh *io) -{ - NTSTATUS status; - struct nbt_name_packet *packet; - - status = nbt_name_request_recv(req); - if (!NT_STATUS_IS_OK(status) || - req->num_replies == 0) { - talloc_free(req); - return status; - } - - packet = req->replies[0].packet; - io->out.reply_from = talloc_steal(mem_ctx, req->replies[0].dest->addr); - - if (packet->ancount != 1 || - packet->answers[0].rr_type != NBT_QTYPE_NETBIOS || - packet->answers[0].rr_class != NBT_QCLASS_IP) { - talloc_free(req); - return NT_STATUS_INVALID_NETWORK_RESPONSE; - } - - io->out.rcode = packet->operation & NBT_RCODE; - io->out.name = packet->answers[0].name; - if (packet->answers[0].rdata.netbios.length < 6) { - talloc_free(req); - return NT_STATUS_INVALID_NETWORK_RESPONSE; - } - io->out.reply_addr = talloc_steal(mem_ctx, - packet->answers[0].rdata.netbios.addresses[0].ipaddr); - talloc_steal(mem_ctx, io->out.name.name); - talloc_steal(mem_ctx, io->out.name.scope); - - talloc_free(req); - - return NT_STATUS_OK; -} - -/* - synchronous name refresh request -*/ -_PUBLIC_ NTSTATUS nbt_name_refresh(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_refresh *io) -{ - struct nbt_name_request *req = nbt_name_refresh_send(nbtsock, io); - return nbt_name_refresh_recv(req, mem_ctx, io); -} - - - -/** - a wins name refresh with multiple WINS servers and multiple - addresses to refresh. Try each WINS server in turn, until we get a - reply for each address -*/ -struct refresh_wins_state { - struct nbt_name_socket *nbtsock; - struct nbt_name_refresh *io; - const char **wins_servers; - uint16_t wins_port; - const char **addresses; - int address_idx; - struct nbt_name_request *req; -}; - - -/** - state handler for WINS multi-homed multi-server name refresh -*/ -static void name_refresh_wins_handler(struct nbt_name_request *req) -{ - struct composite_context *c = talloc_get_type(req->async.private_data, - struct composite_context); - struct refresh_wins_state *state = talloc_get_type(c->private_data, - struct refresh_wins_state); - NTSTATUS status; - - status = nbt_name_refresh_recv(state->req, state, state->io); - if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) { - /* the refresh timed out - try the next WINS server */ - state->wins_servers++; - state->address_idx = 0; - if (state->wins_servers[0] == NULL) { - c->state = COMPOSITE_STATE_ERROR; - c->status = status; - goto done; - } - state->io->in.dest_addr = state->wins_servers[0]; - state->io->in.dest_port = state->wins_port; - state->io->in.address = state->addresses[0]; - state->req = nbt_name_refresh_send(state->nbtsock, state->io); - if (state->req == NULL) { - c->state = COMPOSITE_STATE_ERROR; - c->status = NT_STATUS_NO_MEMORY; - } else { - state->req->async.fn = name_refresh_wins_handler; - state->req->async.private_data = c; - } - } else if (!NT_STATUS_IS_OK(status)) { - c->state = COMPOSITE_STATE_ERROR; - c->status = status; - } else { - if (state->io->out.rcode == 0 && - state->addresses[state->address_idx+1] != NULL) { - /* refresh our next address */ - state->io->in.address = state->addresses[++(state->address_idx)]; - state->req = nbt_name_refresh_send(state->nbtsock, state->io); - if (state->req == NULL) { - c->state = COMPOSITE_STATE_ERROR; - c->status = NT_STATUS_NO_MEMORY; - } else { - state->req->async.fn = name_refresh_wins_handler; - state->req->async.private_data = c; - } - } else { - c->state = COMPOSITE_STATE_DONE; - c->status = NT_STATUS_OK; - } - } - -done: - if (c->state >= COMPOSITE_STATE_DONE && - c->async.fn) { - c->async.fn(c); - } -} - -/** - the async send call for a multi-server WINS refresh -*/ -_PUBLIC_ struct composite_context *nbt_name_refresh_wins_send(struct nbt_name_socket *nbtsock, - struct nbt_name_refresh_wins *io) -{ - struct composite_context *c; - struct refresh_wins_state *state; - - c = talloc_zero(nbtsock, struct composite_context); - if (c == NULL) goto failed; - - state = talloc(c, struct refresh_wins_state); - if (state == NULL) goto failed; - - state->io = talloc(state, struct nbt_name_refresh); - if (state->io == NULL) goto failed; - - state->wins_port = io->in.wins_port; - state->wins_servers = str_list_copy(state, io->in.wins_servers); - if (state->wins_servers == NULL || - state->wins_servers[0] == NULL) goto failed; - - state->addresses = str_list_copy(state, io->in.addresses); - if (state->addresses == NULL || - state->addresses[0] == NULL) goto failed; - - state->io->in.name = io->in.name; - state->io->in.dest_addr = state->wins_servers[0]; - state->io->in.dest_port = state->wins_port; - state->io->in.address = io->in.addresses[0]; - state->io->in.nb_flags = io->in.nb_flags; - state->io->in.broadcast = false; - state->io->in.ttl = io->in.ttl; - state->io->in.timeout = 2; - state->io->in.retries = 2; - - state->nbtsock = nbtsock; - state->address_idx = 0; - - state->req = nbt_name_refresh_send(nbtsock, state->io); - if (state->req == NULL) goto failed; - - state->req->async.fn = name_refresh_wins_handler; - state->req->async.private_data = c; - - c->private_data = state; - c->state = COMPOSITE_STATE_IN_PROGRESS; - c->event_ctx = nbtsock->event_ctx; - - return c; - -failed: - talloc_free(c); - return NULL; -} - -/* - multi-homed WINS name refresh - recv side -*/ -_PUBLIC_ NTSTATUS nbt_name_refresh_wins_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, - struct nbt_name_refresh_wins *io) -{ - NTSTATUS status; - status = composite_wait(c); - if (NT_STATUS_IS_OK(status)) { - struct refresh_wins_state *state = - talloc_get_type(c->private_data, struct refresh_wins_state); - io->out.wins_server = talloc_steal(mem_ctx, state->wins_servers[0]); - io->out.rcode = state->io->out.rcode; - } - talloc_free(c); - return status; -} - -/* - multi-homed WINS refresh - sync interface -*/ -_PUBLIC_ NTSTATUS nbt_name_refresh_wins(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, - struct nbt_name_refresh_wins *io) -{ - struct composite_context *c = nbt_name_refresh_wins_send(nbtsock, io); - return nbt_name_refresh_wins_recv(c, mem_ctx, io); -} diff --git a/source4/libcli/nbt/nameregister.c b/source4/libcli/nbt/nameregister.c deleted file mode 100644 index c50f9b3b3a..0000000000 --- a/source4/libcli/nbt/nameregister.c +++ /dev/null @@ -1,442 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - send out a name registration request - - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "includes.h" -#include "libcli/nbt/libnbt.h" -#include "libcli/nbt/nbt_proto.h" -#include "libcli/composite/composite.h" -#include "lib/socket/socket.h" -#include "librpc/gen_ndr/ndr_nbt.h" -#include "param/param.h" - -/* - send a nbt name registration request -*/ -struct nbt_name_request *nbt_name_register_send(struct nbt_name_socket *nbtsock, - struct nbt_name_register *io) -{ - struct nbt_name_request *req; - struct nbt_name_packet *packet; - struct socket_address *dest; - - packet = talloc_zero(nbtsock, struct nbt_name_packet); - if (packet == NULL) return NULL; - - packet->qdcount = 1; - packet->arcount = 1; - if (io->in.multi_homed) { - packet->operation = NBT_OPCODE_MULTI_HOME_REG; - } else { - packet->operation = NBT_OPCODE_REGISTER; - } - if (io->in.broadcast) { - packet->operation |= NBT_FLAG_BROADCAST; - } - if (io->in.register_demand) { - packet->operation |= NBT_FLAG_RECURSION_DESIRED; - } - - packet->questions = talloc_array(packet, struct nbt_name_question, 1); - if (packet->questions == NULL) goto failed; - - packet->questions[0].name = io->in.name; - packet->questions[0].question_type = NBT_QTYPE_NETBIOS; - packet->questions[0].question_class = NBT_QCLASS_IP; - - packet->additional = talloc_array(packet, struct nbt_res_rec, 1); - if (packet->additional == NULL) goto failed; - - packet->additional[0].name = io->in.name; - packet->additional[0].rr_type = NBT_QTYPE_NETBIOS; - packet->additional[0].rr_class = NBT_QCLASS_IP; - packet->additional[0].ttl = io->in.ttl; - packet->additional[0].rdata.netbios.length = 6; - packet->additional[0].rdata.netbios.addresses = talloc_array(packet->additional, - struct nbt_rdata_address, 1); - if (packet->additional[0].rdata.netbios.addresses == NULL) goto failed; - packet->additional[0].rdata.netbios.addresses[0].nb_flags = io->in.nb_flags; - packet->additional[0].rdata.netbios.addresses[0].ipaddr = - talloc_strdup(packet->additional, io->in.address); - if (packet->additional[0].rdata.netbios.addresses[0].ipaddr == NULL) goto failed; - - dest = socket_address_from_strings(packet, nbtsock->sock->backend_name, - io->in.dest_addr, io->in.dest_port); - if (dest == NULL) goto failed; - req = nbt_name_request_send(nbtsock, dest, packet, - io->in.timeout, io->in.retries, false); - if (req == NULL) goto failed; - - talloc_free(packet); - return req; - -failed: - talloc_free(packet); - return NULL; -} - -/* - wait for a registration reply -*/ -_PUBLIC_ NTSTATUS nbt_name_register_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_register *io) -{ - NTSTATUS status; - struct nbt_name_packet *packet; - - status = nbt_name_request_recv(req); - if (!NT_STATUS_IS_OK(status) || - req->num_replies == 0) { - talloc_free(req); - return status; - } - - packet = req->replies[0].packet; - io->out.reply_from = talloc_steal(mem_ctx, req->replies[0].dest->addr); - - if (packet->ancount != 1 || - packet->answers[0].rr_type != NBT_QTYPE_NETBIOS || - packet->answers[0].rr_class != NBT_QCLASS_IP) { - talloc_free(req); - return NT_STATUS_INVALID_NETWORK_RESPONSE; - } - - io->out.rcode = packet->operation & NBT_RCODE; - io->out.name = packet->answers[0].name; - if (packet->answers[0].rdata.netbios.length < 6) { - talloc_free(req); - return NT_STATUS_INVALID_NETWORK_RESPONSE; - } - io->out.reply_addr = talloc_steal(mem_ctx, - packet->answers[0].rdata.netbios.addresses[0].ipaddr); - talloc_steal(mem_ctx, io->out.name.name); - talloc_steal(mem_ctx, io->out.name.scope); - - talloc_free(req); - - return NT_STATUS_OK; -} - -/* - synchronous name registration request -*/ -_PUBLIC_ NTSTATUS nbt_name_register(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_register *io) -{ - struct nbt_name_request *req = nbt_name_register_send(nbtsock, io); - return nbt_name_register_recv(req, mem_ctx, io); -} - - -/* - a 4 step broadcast registration. 3 lots of name registration requests, followed by - a name registration demand -*/ -struct register_bcast_state { - struct nbt_name_socket *nbtsock; - struct nbt_name_register *io; - struct nbt_name_request *req; -}; - - -/* - state handler for 4 stage name registration -*/ -static void name_register_bcast_handler(struct nbt_name_request *req) -{ - struct composite_context *c = talloc_get_type(req->async.private_data, struct composite_context); - struct register_bcast_state *state = talloc_get_type(c->private_data, struct register_bcast_state); - NTSTATUS status; - - status = nbt_name_register_recv(state->req, state, state->io); - if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) { - if (state->io->in.register_demand == true) { - /* all done */ - c->state = COMPOSITE_STATE_DONE; - c->status = NT_STATUS_OK; - goto done; - } - - /* the registration timed out - good, send the demand */ - state->io->in.register_demand = true; - state->io->in.retries = 0; - state->req = nbt_name_register_send(state->nbtsock, state->io); - if (state->req == NULL) { - c->state = COMPOSITE_STATE_ERROR; - c->status = NT_STATUS_NO_MEMORY; - } else { - state->req->async.fn = name_register_bcast_handler; - state->req->async.private_data = c; - } - } else if (!NT_STATUS_IS_OK(status)) { - c->state = COMPOSITE_STATE_ERROR; - c->status = status; - } else { - c->state = COMPOSITE_STATE_ERROR; - c->status = NT_STATUS_CONFLICTING_ADDRESSES; - DEBUG(3,("Name registration conflict from %s for %s with ip %s - rcode %d\n", - state->io->out.reply_from, - nbt_name_string(state, &state->io->out.name), - state->io->out.reply_addr, - state->io->out.rcode)); - } - -done: - if (c->state >= COMPOSITE_STATE_DONE && - c->async.fn) { - c->async.fn(c); - } -} - -/* - the async send call for a 4 stage name registration -*/ -_PUBLIC_ struct composite_context *nbt_name_register_bcast_send(struct nbt_name_socket *nbtsock, - struct nbt_name_register_bcast *io) -{ - struct composite_context *c; - struct register_bcast_state *state; - - c = talloc_zero(nbtsock, struct composite_context); - if (c == NULL) goto failed; - - state = talloc(c, struct register_bcast_state); - if (state == NULL) goto failed; - - state->io = talloc(state, struct nbt_name_register); - if (state->io == NULL) goto failed; - - state->io->in.name = io->in.name; - state->io->in.dest_addr = io->in.dest_addr; - state->io->in.dest_port = io->in.dest_port; - state->io->in.address = io->in.address; - state->io->in.nb_flags = io->in.nb_flags; - state->io->in.register_demand = false; - state->io->in.broadcast = true; - state->io->in.multi_homed = false; - state->io->in.ttl = io->in.ttl; - state->io->in.timeout = 1; - state->io->in.retries = 2; - - state->nbtsock = nbtsock; - - state->req = nbt_name_register_send(nbtsock, state->io); - if (state->req == NULL) goto failed; - - state->req->async.fn = name_register_bcast_handler; - state->req->async.private_data = c; - - c->private_data = state; - c->state = COMPOSITE_STATE_IN_PROGRESS; - c->event_ctx = nbtsock->event_ctx; - - return c; - -failed: - talloc_free(c); - return NULL; -} - -/* - broadcast 4 part name register - recv -*/ -_PUBLIC_ NTSTATUS nbt_name_register_bcast_recv(struct composite_context *c) -{ - NTSTATUS status; - status = composite_wait(c); - talloc_free(c); - return status; -} - -/* - broadcast 4 part name register - sync interface -*/ -NTSTATUS nbt_name_register_bcast(struct nbt_name_socket *nbtsock, - struct nbt_name_register_bcast *io) -{ - struct composite_context *c = nbt_name_register_bcast_send(nbtsock, io); - return nbt_name_register_bcast_recv(c); -} - - -/* - a wins name register with multiple WINS servers and multiple - addresses to register. Try each WINS server in turn, until we get a - reply for each address -*/ -struct register_wins_state { - struct nbt_name_socket *nbtsock; - struct nbt_name_register *io; - const char **wins_servers; - uint16_t wins_port; - const char **addresses; - int address_idx; - struct nbt_name_request *req; -}; - - -/* - state handler for WINS multi-homed multi-server name register -*/ -static void name_register_wins_handler(struct nbt_name_request *req) -{ - struct composite_context *c = talloc_get_type(req->async.private_data, - struct composite_context); - struct register_wins_state *state = talloc_get_type(c->private_data, - struct register_wins_state); - NTSTATUS status; - - status = nbt_name_register_recv(state->req, state, state->io); - if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) { - /* the register timed out - try the next WINS server */ - state->wins_servers++; - state->address_idx = 0; - if (state->wins_servers[0] == NULL) { - c->state = COMPOSITE_STATE_ERROR; - c->status = status; - goto done; - } - state->io->in.dest_addr = state->wins_servers[0]; - state->io->in.dest_port = state->wins_port; - state->io->in.address = state->addresses[0]; - state->req = nbt_name_register_send(state->nbtsock, state->io); - if (state->req == NULL) { - c->state = COMPOSITE_STATE_ERROR; - c->status = NT_STATUS_NO_MEMORY; - } else { - state->req->async.fn = name_register_wins_handler; - state->req->async.private_data = c; - } - } else if (!NT_STATUS_IS_OK(status)) { - c->state = COMPOSITE_STATE_ERROR; - c->status = status; - } else { - if (state->io->out.rcode == 0 && - state->addresses[state->address_idx+1] != NULL) { - /* register our next address */ - state->io->in.address = state->addresses[++(state->address_idx)]; - state->req = nbt_name_register_send(state->nbtsock, state->io); - if (state->req == NULL) { - c->state = COMPOSITE_STATE_ERROR; - c->status = NT_STATUS_NO_MEMORY; - } else { - state->req->async.fn = name_register_wins_handler; - state->req->async.private_data = c; - } - } else { - c->state = COMPOSITE_STATE_DONE; - c->status = NT_STATUS_OK; - } - } - -done: - if (c->state >= COMPOSITE_STATE_DONE && - c->async.fn) { - c->async.fn(c); - } -} - -/* - the async send call for a multi-server WINS register -*/ -_PUBLIC_ struct composite_context *nbt_name_register_wins_send(struct nbt_name_socket *nbtsock, - struct nbt_name_register_wins *io) -{ - struct composite_context *c; - struct register_wins_state *state; - - c = talloc_zero(nbtsock, struct composite_context); - if (c == NULL) goto failed; - - state = talloc(c, struct register_wins_state); - if (state == NULL) goto failed; - - state->io = talloc(state, struct nbt_name_register); - if (state->io == NULL) goto failed; - - state->wins_port = io->in.wins_port; - state->wins_servers = str_list_copy(state, io->in.wins_servers); - if (state->wins_servers == NULL || - state->wins_servers[0] == NULL) goto failed; - - state->addresses = str_list_copy(state, io->in.addresses); - if (state->addresses == NULL || - state->addresses[0] == NULL) goto failed; - - state->io->in.name = io->in.name; - state->io->in.dest_addr = state->wins_servers[0]; - state->io->in.dest_port = state->wins_port; - state->io->in.address = io->in.addresses[0]; - state->io->in.nb_flags = io->in.nb_flags; - state->io->in.broadcast = false; - state->io->in.register_demand = false; - state->io->in.multi_homed = (io->in.nb_flags & NBT_NM_GROUP)?false:true; - state->io->in.ttl = io->in.ttl; - state->io->in.timeout = 3; - state->io->in.retries = 2; - - state->nbtsock = nbtsock; - state->address_idx = 0; - - state->req = nbt_name_register_send(nbtsock, state->io); - if (state->req == NULL) goto failed; - - state->req->async.fn = name_register_wins_handler; - state->req->async.private_data = c; - - c->private_data = state; - c->state = COMPOSITE_STATE_IN_PROGRESS; - c->event_ctx = nbtsock->event_ctx; - - return c; - -failed: - talloc_free(c); - return NULL; -} - -/* - multi-homed WINS name register - recv side -*/ -_PUBLIC_ NTSTATUS nbt_name_register_wins_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, - struct nbt_name_register_wins *io) -{ - NTSTATUS status; - status = composite_wait(c); - if (NT_STATUS_IS_OK(status)) { - struct register_wins_state *state = - talloc_get_type(c->private_data, struct register_wins_state); - io->out.wins_server = talloc_steal(mem_ctx, state->wins_servers[0]); - io->out.rcode = state->io->out.rcode; - } - talloc_free(c); - return status; -} - -/* - multi-homed WINS register - sync interface -*/ -_PUBLIC_ NTSTATUS nbt_name_register_wins(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, - struct nbt_name_register_wins *io) -{ - struct composite_context *c = nbt_name_register_wins_send(nbtsock, io); - return nbt_name_register_wins_recv(c, mem_ctx, io); -} diff --git a/source4/libcli/nbt/namerelease.c b/source4/libcli/nbt/namerelease.c deleted file mode 100644 index ba3af41752..0000000000 --- a/source4/libcli/nbt/namerelease.c +++ /dev/null @@ -1,135 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - send out a name release request - - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "includes.h" -#include "libcli/nbt/libnbt.h" -#include "libcli/nbt/nbt_proto.h" -#include "lib/socket/socket.h" -#include "param/param.h" - -/* - send a nbt name release request -*/ -_PUBLIC_ struct nbt_name_request *nbt_name_release_send(struct nbt_name_socket *nbtsock, - struct nbt_name_release *io) -{ - struct nbt_name_request *req; - struct nbt_name_packet *packet; - struct socket_address *dest; - - packet = talloc_zero(nbtsock, struct nbt_name_packet); - if (packet == NULL) return NULL; - - packet->qdcount = 1; - packet->arcount = 1; - packet->operation = NBT_OPCODE_RELEASE; - if (io->in.broadcast) { - packet->operation |= NBT_FLAG_BROADCAST; - } - - packet->questions = talloc_array(packet, struct nbt_name_question, 1); - if (packet->questions == NULL) goto failed; - - packet->questions[0].name = io->in.name; - packet->questions[0].question_type = NBT_QTYPE_NETBIOS; - packet->questions[0].question_class = NBT_QCLASS_IP; - - packet->additional = talloc_array(packet, struct nbt_res_rec, 1); - if (packet->additional == NULL) goto failed; - - packet->additional[0].name = io->in.name; - packet->additional[0].rr_type = NBT_QTYPE_NETBIOS; - packet->additional[0].rr_class = NBT_QCLASS_IP; - packet->additional[0].ttl = 0; - packet->additional[0].rdata.netbios.length = 6; - packet->additional[0].rdata.netbios.addresses = talloc_array(packet->additional, - struct nbt_rdata_address, 1); - if (packet->additional[0].rdata.netbios.addresses == NULL) goto failed; - packet->additional[0].rdata.netbios.addresses[0].nb_flags = io->in.nb_flags; - packet->additional[0].rdata.netbios.addresses[0].ipaddr = - talloc_strdup(packet->additional, io->in.address); - - dest = socket_address_from_strings(packet, nbtsock->sock->backend_name, - io->in.dest_addr, io->in.dest_port); - if (dest == NULL) goto failed; - req = nbt_name_request_send(nbtsock, dest, packet, - io->in.timeout, io->in.retries, false); - if (req == NULL) goto failed; - - talloc_free(packet); - return req; - -failed: - talloc_free(packet); - return NULL; -} - -/* - wait for a release reply -*/ -_PUBLIC_ NTSTATUS nbt_name_release_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_release *io) -{ - NTSTATUS status; - struct nbt_name_packet *packet; - - status = nbt_name_request_recv(req); - if (!NT_STATUS_IS_OK(status) || - req->num_replies == 0) { - talloc_free(req); - return status; - } - - packet = req->replies[0].packet; - io->out.reply_from = talloc_steal(mem_ctx, req->replies[0].dest->addr); - - if (packet->ancount != 1 || - packet->answers[0].rr_type != NBT_QTYPE_NETBIOS || - packet->answers[0].rr_class != NBT_QCLASS_IP) { - talloc_free(req); - return NT_STATUS_INVALID_NETWORK_RESPONSE; - } - - io->out.rcode = packet->operation & NBT_RCODE; - io->out.name = packet->answers[0].name; - if (packet->answers[0].rdata.netbios.length < 6) { - talloc_free(req); - return NT_STATUS_INVALID_NETWORK_RESPONSE; - } - io->out.reply_addr = talloc_steal(mem_ctx, - packet->answers[0].rdata.netbios.addresses[0].ipaddr); - talloc_steal(mem_ctx, io->out.name.name); - talloc_steal(mem_ctx, io->out.name.scope); - - talloc_free(req); - - return NT_STATUS_OK; -} - -/* - synchronous name release request -*/ -_PUBLIC_ NTSTATUS nbt_name_release(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_release *io) -{ - struct nbt_name_request *req = nbt_name_release_send(nbtsock, io); - return nbt_name_release_recv(req, mem_ctx, io); -} diff --git a/source4/libcli/nbt/nbtname.c b/source4/libcli/nbt/nbtname.c deleted file mode 100644 index 338cb21089..0000000000 --- a/source4/libcli/nbt/nbtname.c +++ /dev/null @@ -1,648 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - manipulate nbt name structures - - Copyright (C) Andrew Tridgell 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 . -*/ - -/* - see rfc1002 for the detailed format of compressed names -*/ - -#include "includes.h" -#include "librpc/gen_ndr/ndr_nbt.h" -#include "librpc/gen_ndr/ndr_misc.h" -#include "system/locale.h" - -/* don't allow an unlimited number of name components */ -#define MAX_COMPONENTS 10 - -/** - print a nbt string -*/ -_PUBLIC_ void ndr_print_nbt_string(struct ndr_print *ndr, const char *name, const char *s) -{ - ndr_print_string(ndr, name, s); -} - -/* - pull one component of a nbt_string -*/ -static enum ndr_err_code ndr_pull_component(struct ndr_pull *ndr, - uint8_t **component, - uint32_t *offset, - uint32_t *max_offset) -{ - uint8_t len; - uint_t loops = 0; - while (loops < 5) { - if (*offset >= ndr->data_size) { - return ndr_pull_error(ndr, NDR_ERR_STRING, - "BAD NBT NAME component"); - } - len = ndr->data[*offset]; - if (len == 0) { - *offset += 1; - *max_offset = MAX(*max_offset, *offset); - *component = NULL; - return NDR_ERR_SUCCESS; - } - if ((len & 0xC0) == 0xC0) { - /* its a label pointer */ - if (1 + *offset >= ndr->data_size) { - return ndr_pull_error(ndr, NDR_ERR_STRING, - "BAD NBT NAME component"); - } - *max_offset = MAX(*max_offset, *offset + 2); - *offset = ((len&0x3F)<<8) | ndr->data[1 + *offset]; - *max_offset = MAX(*max_offset, *offset); - loops++; - continue; - } - if ((len & 0xC0) != 0) { - /* its a reserved length field */ - return ndr_pull_error(ndr, NDR_ERR_STRING, - "BAD NBT NAME component"); - } - if (*offset + len + 2 > ndr->data_size) { - return ndr_pull_error(ndr, NDR_ERR_STRING, - "BAD NBT NAME component"); - } - *component = (uint8_t*)talloc_strndup(ndr, (const char *)&ndr->data[1 + *offset], len); - NDR_ERR_HAVE_NO_MEMORY(*component); - *offset += len + 1; - *max_offset = MAX(*max_offset, *offset); - return NDR_ERR_SUCCESS; - } - - /* too many pointers */ - return ndr_pull_error(ndr, NDR_ERR_STRING, "BAD NBT NAME component"); -} - -/** - pull a nbt_string from the wire -*/ -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_string(struct ndr_pull *ndr, int ndr_flags, const char **s) -{ - uint32_t offset = ndr->offset; - uint32_t max_offset = offset; - unsigned num_components; - char *name; - - if (!(ndr_flags & NDR_SCALARS)) { - return NDR_ERR_SUCCESS; - } - - name = NULL; - - /* break up name into a list of components */ - for (num_components=0;num_componentsoffset = max_offset; - - return NDR_ERR_SUCCESS; -} - -/** - push a nbt string to the wire -*/ -_PUBLIC_ enum ndr_err_code ndr_push_nbt_string(struct ndr_push *ndr, int ndr_flags, const char *s) -{ - if (!(ndr_flags & NDR_SCALARS)) { - return NDR_ERR_SUCCESS; - } - - while (s && *s) { - enum ndr_err_code ndr_err; - char *compname; - size_t complen; - uint32_t offset; - - /* see if we have pushed the remaing string allready, - * if so we use a label pointer to this string - */ - ndr_err = ndr_token_retrieve_cmp_fn(&ndr->nbt_string_list, s, &offset, (comparison_fn_t)strcmp, false); - if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - uint8_t b[2]; - - if (offset > 0x3FFF) { - return ndr_push_error(ndr, NDR_ERR_STRING, - "offset for nbt string label pointer %u[%08X] > 0x00003FFF", - offset, offset); - } - - b[0] = 0xC0 | (offset>>8); - b[1] = (offset & 0xFF); - - return ndr_push_bytes(ndr, b, 2); - } - - complen = strcspn(s, "."); - - /* we need to make sure the length fits into 6 bytes */ - if (complen >= 0x3F) { - return ndr_push_error(ndr, NDR_ERR_STRING, - "component length %u[%08X] > 0x00003F", - (unsigned)complen, (unsigned)complen); - } - - compname = talloc_asprintf(ndr, "%c%*.*s", - (unsigned char)complen, - (unsigned char)complen, - (unsigned char)complen, s); - NDR_ERR_HAVE_NO_MEMORY(compname); - - /* remember the current componemt + the rest of the string - * so it can be reused later - */ - NDR_CHECK(ndr_token_store(ndr, &ndr->nbt_string_list, s, ndr->offset)); - - /* push just this component into the blob */ - NDR_CHECK(ndr_push_bytes(ndr, (const uint8_t *)compname, complen+1)); - talloc_free(compname); - - s += complen; - if (*s == '.') s++; - } - - /* if we reach the end of the string and have pushed the last component - * without using a label pointer, we need to terminate the string - */ - return ndr_push_bytes(ndr, (const uint8_t *)"", 1); -} - - -/* - decompress a 'compressed' name component - */ -static bool decompress_name(char *name, enum nbt_name_type *type) -{ - int i; - for (i=0;name[2*i];i++) { - uint8_t c1 = name[2*i]; - uint8_t c2 = name[1+(2*i)]; - if (c1 < 'A' || c1 > 'P' || - c2 < 'A' || c2 > 'P') { - return false; - } - name[i] = ((c1-'A')<<4) | (c2-'A'); - } - name[i] = 0; - if (i == 16) { - *type = (enum nbt_name_type)(name[15]); - name[15] = 0; - i--; - } else { - *type = NBT_NAME_CLIENT; - } - - /* trim trailing spaces */ - for (;i>0 && name[i-1]==' ';i--) { - name[i-1] = 0; - } - - return true; -} - - -/* - compress a name component - */ -static uint8_t *compress_name(TALLOC_CTX *mem_ctx, - const uint8_t *name, enum nbt_name_type type) -{ - uint8_t *cname; - int i; - uint8_t pad_char; - - if (strlen((const char *)name) > 15) { - return NULL; - } - - cname = talloc_array(mem_ctx, uint8_t, 33); - if (cname == NULL) return NULL; - - for (i=0;name[i];i++) { - cname[2*i] = 'A' + (name[i]>>4); - cname[1+2*i] = 'A' + (name[i]&0xF); - } - if (strcmp((const char *)name, "*") == 0) { - pad_char = 0; - } else { - pad_char = ' '; - } - for (;i<15;i++) { - cname[2*i] = 'A' + (pad_char>>4); - cname[1+2*i] = 'A' + (pad_char&0xF); - } - - pad_char = type; - cname[2*i] = 'A' + (pad_char>>4); - cname[1+2*i] = 'A' + (pad_char&0xF); - - cname[32] = 0; - return cname; -} - - -/** - pull a nbt name from the wire -*/ -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_name(struct ndr_pull *ndr, int ndr_flags, struct nbt_name *r) -{ - uint8_t *scope; - char *cname; - const char *s; - bool ok; - - if (!(ndr_flags & NDR_SCALARS)) { - return NDR_ERR_SUCCESS; - } - - NDR_CHECK(ndr_pull_nbt_string(ndr, ndr_flags, &s)); - - scope = (uint8_t *)strchr(s, '.'); - if (scope) { - *scope = 0; - r->scope = talloc_strdup(ndr->current_mem_ctx, (const char *)&scope[1]); - NDR_ERR_HAVE_NO_MEMORY(r->scope); - } else { - r->scope = NULL; - } - - cname = discard_const_p(char, s); - - /* the first component is limited to 16 bytes in the DOS charset, - which is 32 in the 'compressed' form */ - if (strlen(cname) > 32) { - return ndr_pull_error(ndr, NDR_ERR_STRING, - "NBT NAME cname > 32"); - } - - /* decompress the first component */ - ok = decompress_name(cname, &r->type); - if (!ok) { - return ndr_pull_error(ndr, NDR_ERR_STRING, - "NBT NAME failed to decompress"); - } - - r->name = talloc_strdup(ndr->current_mem_ctx, cname); - NDR_ERR_HAVE_NO_MEMORY(r->name); - - talloc_free(cname); - - return NDR_ERR_SUCCESS; -} - -/** - push a nbt name to the wire -*/ -_PUBLIC_ enum ndr_err_code ndr_push_nbt_name(struct ndr_push *ndr, int ndr_flags, const struct nbt_name *r) -{ - uint8_t *cname, *fullname; - enum ndr_err_code ndr_err; - - if (!(ndr_flags & NDR_SCALARS)) { - return NDR_ERR_SUCCESS; - } - - if (strlen(r->name) > 15) { - return ndr_push_error(ndr, NDR_ERR_STRING, - "nbt_name longer as 15 chars: %s", - r->name); - } - - cname = compress_name(ndr, (const uint8_t *)r->name, r->type); - NDR_ERR_HAVE_NO_MEMORY(cname); - - if (r->scope) { - fullname = (uint8_t *)talloc_asprintf(ndr, "%s.%s", cname, r->scope); - NDR_ERR_HAVE_NO_MEMORY(fullname); - talloc_free(cname); - } else { - fullname = cname; - } - - ndr_err = ndr_push_nbt_string(ndr, ndr_flags, (const char *)fullname); - - return ndr_err; -} - - -/** - copy a nbt name structure -*/ -_PUBLIC_ NTSTATUS nbt_name_dup(TALLOC_CTX *mem_ctx, struct nbt_name *name, struct nbt_name *newname) -{ - *newname = *name; - newname->name = talloc_strdup(mem_ctx, newname->name); - NT_STATUS_HAVE_NO_MEMORY(newname->name); - newname->scope = talloc_strdup(mem_ctx, newname->scope); - if (name->scope) { - NT_STATUS_HAVE_NO_MEMORY(newname->scope); - } - return NT_STATUS_OK; -} - -/** - push a nbt name into a blob -*/ -_PUBLIC_ NTSTATUS nbt_name_to_blob(TALLOC_CTX *mem_ctx, struct smb_iconv_convenience *iconv_convenience, DATA_BLOB *blob, struct nbt_name *name) -{ - enum ndr_err_code ndr_err; - - ndr_err = ndr_push_struct_blob(blob, mem_ctx, iconv_convenience, name, (ndr_push_flags_fn_t)ndr_push_nbt_name); - if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - return ndr_map_error2ntstatus(ndr_err); - } - - return NT_STATUS_OK; -} - -/** - pull a nbt name from a blob -*/ -_PUBLIC_ NTSTATUS nbt_name_from_blob(TALLOC_CTX *mem_ctx, const DATA_BLOB *blob, struct nbt_name *name) -{ - enum ndr_err_code ndr_err; - - ndr_err = ndr_pull_struct_blob(blob, mem_ctx, NULL, name, - (ndr_pull_flags_fn_t)ndr_pull_nbt_name); - if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - return ndr_map_error2ntstatus(ndr_err); - } - - return NT_STATUS_OK; -} - - -/** - choose a name to use when calling a server in a NBT session request. - we use heuristics to see if the name we have been given is a IP - address, or a too-long name. If it is then use *SMBSERVER, or a - truncated name -*/ -_PUBLIC_ void nbt_choose_called_name(TALLOC_CTX *mem_ctx, - struct nbt_name *n, const char *name, int type) -{ - n->scope = NULL; - n->type = type; - - if ((name == NULL) || is_ipaddress(name)) { - n->name = "*SMBSERVER"; - return; - } - if (strlen(name) > 15) { - const char *p = strchr(name, '.'); - char *s; - if (p - name > 15) { - n->name = "*SMBSERVER"; - return; - } - s = talloc_strndup(mem_ctx, name, PTR_DIFF(p, name)); - n->name = talloc_strdup_upper(mem_ctx, s); - return; - } - - n->name = talloc_strdup_upper(mem_ctx, name); -} - - -/* - escape a string into a form containing only a small set of characters, - the rest is hex encoded. This is similar to URL encoding -*/ -static const char *nbt_hex_encode(TALLOC_CTX *mem_ctx, const char *s) -{ - int i, len; - char *ret; - const char *valid_chars = "_-.$@ "; -#define NBT_CHAR_ALLOW(c) (isalnum((unsigned char)c) || strchr(valid_chars, c)) - - for (len=i=0;s[i];i++,len++) { - if (!NBT_CHAR_ALLOW(s[i])) { - len += 2; - } - } - - ret = talloc_array(mem_ctx, char, len+1); - if (ret == NULL) return NULL; - - for (len=i=0;s[i];i++) { - if (NBT_CHAR_ALLOW(s[i])) { - ret[len++] = s[i]; - } else { - snprintf(&ret[len], 4, "%%%02x", (unsigned char)s[i]); - len += 3; - } - } - ret[len] = 0; - - return ret; -} - - -/** - form a string for a NBT name -*/ -_PUBLIC_ char *nbt_name_string(TALLOC_CTX *mem_ctx, const struct nbt_name *name) -{ - TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx); - char *ret; - if (name->scope) { - ret = talloc_asprintf(mem_ctx, "%s<%02x>-%s", - nbt_hex_encode(tmp_ctx, name->name), - name->type, - nbt_hex_encode(tmp_ctx, name->scope)); - } else { - ret = talloc_asprintf(mem_ctx, "%s<%02x>", - nbt_hex_encode(tmp_ctx, name->name), - name->type); - } - talloc_free(tmp_ctx); - return ret; -} - -/** - pull a nbt name, WINS Replication uses another on wire format for nbt name -*/ -_PUBLIC_ enum ndr_err_code ndr_pull_wrepl_nbt_name(struct ndr_pull *ndr, int ndr_flags, const struct nbt_name **_r) -{ - struct nbt_name *r; - uint8_t *namebuf; - uint32_t namebuf_len; - - if (!(ndr_flags & NDR_SCALARS)) { - return NDR_ERR_SUCCESS; - } - - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &namebuf_len)); - if (namebuf_len < 1 || namebuf_len > 255) { - return ndr_pull_error(ndr, NDR_ERR_ALLOC, "value out of range"); - } - NDR_PULL_ALLOC_N(ndr, namebuf, namebuf_len); - NDR_CHECK(ndr_pull_array_uint8(ndr, NDR_SCALARS, namebuf, namebuf_len)); - - NDR_PULL_ALLOC(ndr, r); - - /* oh wow, what a nasty bug in windows ... */ - if (namebuf[0] == 0x1b && namebuf_len >= 16) { - namebuf[0] = namebuf[15]; - namebuf[15] = 0x1b; - } - - if (namebuf_len < 17) { - r->type = 0x00; - - r->name = talloc_strndup(r, (char *)namebuf, namebuf_len); - if (!r->name) return ndr_pull_error(ndr, NDR_ERR_ALLOC, "out of memory"); - - r->scope= NULL; - - talloc_free(namebuf); - *_r = r; - return NDR_ERR_SUCCESS; - } - - r->type = namebuf[15]; - - namebuf[15] = '\0'; - trim_string((char *)namebuf, NULL, " "); - r->name = talloc_strdup(r, (char *)namebuf); - if (!r->name) return ndr_pull_error(ndr, NDR_ERR_ALLOC, "out of memory"); - - if (namebuf_len > 18) { - r->scope = talloc_strndup(r, (char *)(namebuf+17), namebuf_len-17); - if (!r->scope) return ndr_pull_error(ndr, NDR_ERR_ALLOC, "out of memory"); - } else { - r->scope = NULL; - } - - talloc_free(namebuf); - *_r = r; - return NDR_ERR_SUCCESS; -} - -/** - push a nbt name, WINS Replication uses another on wire format for nbt name -*/ -_PUBLIC_ enum ndr_err_code ndr_push_wrepl_nbt_name(struct ndr_push *ndr, int ndr_flags, const struct nbt_name *r) -{ - uint8_t *namebuf; - uint32_t namebuf_len; - uint32_t _name_len; - uint32_t scope_len = 0; - - if (r == NULL) { - return ndr_push_error(ndr, NDR_ERR_INVALID_POINTER, - "wrepl_nbt_name NULL pointer"); - } - - if (!(ndr_flags & NDR_SCALARS)) { - return NDR_ERR_SUCCESS; - } - - _name_len = strlen(r->name); - if (_name_len > 15) { - return ndr_push_error(ndr, NDR_ERR_STRING, - "wrepl_nbt_name longer as 15 chars: %s", - r->name); - } - - if (r->scope) { - scope_len = strlen(r->scope); - } - if (scope_len > 238) { - return ndr_push_error(ndr, NDR_ERR_STRING, - "wrepl_nbt_name scope longer as 238 chars: %s", - r->scope); - } - - namebuf = (uint8_t *)talloc_asprintf(ndr, "%-15s%c%s", - r->name, 'X', - (r->scope?r->scope:"")); - if (!namebuf) return ndr_push_error(ndr, NDR_ERR_ALLOC, "out of memory"); - - namebuf_len = strlen((char *)namebuf) + 1; - - /* - * we need to set the type here, and use a place-holder in the talloc_asprintf() - * as the type can be 0x00, and then the namebuf_len = strlen(namebuf); would give wrong results - */ - namebuf[15] = r->type; - - /* oh wow, what a nasty bug in windows ... */ - if (r->type == 0x1b) { - namebuf[15] = namebuf[0]; - namebuf[0] = 0x1b; - } - - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, namebuf_len)); - NDR_CHECK(ndr_push_array_uint8(ndr, NDR_SCALARS, namebuf, namebuf_len)); - - talloc_free(namebuf); - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_wrepl_nbt_name(struct ndr_print *ndr, const char *name, const struct nbt_name *r) -{ - char *s = nbt_name_string(ndr, r); - ndr_print_string(ndr, name, s); - talloc_free(s); -} - -_PUBLIC_ enum ndr_err_code ndr_push_nbt_res_rec(struct ndr_push *ndr, int ndr_flags, const struct nbt_res_rec *r) -{ - { - uint32_t _flags_save_STRUCT = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_PRINT_ARRAY_HEX); - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_nbt_name(ndr, NDR_SCALARS, &r->name)); - NDR_CHECK(ndr_push_nbt_qtype(ndr, NDR_SCALARS, r->rr_type)); - NDR_CHECK(ndr_push_nbt_qclass(ndr, NDR_SCALARS, r->rr_class)); - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->ttl)); - NDR_CHECK(ndr_push_set_switch_value(ndr, &r->rdata, ((((r->rr_type) == NBT_QTYPE_NETBIOS) && ((r->rdata).data.length == 2))?0:r->rr_type))); - NDR_CHECK(ndr_push_nbt_rdata(ndr, NDR_SCALARS, &r->rdata)); - } - if (ndr_flags & NDR_BUFFERS) { - } - ndr->flags = _flags_save_STRUCT; - } - return NDR_ERR_SUCCESS; -} diff --git a/source4/libcli/nbt/nbtsocket.c b/source4/libcli/nbt/nbtsocket.c deleted file mode 100644 index 49f175b8a3..0000000000 --- a/source4/libcli/nbt/nbtsocket.c +++ /dev/null @@ -1,521 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - low level socket handling for nbt requests - - Copyright (C) Andrew Tridgell 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 . -*/ - -#include "includes.h" -#include "lib/events/events.h" -#include "lib/util/dlinklist.h" -#include "libcli/nbt/libnbt.h" -#include "lib/socket/socket.h" -#include "librpc/gen_ndr/ndr_nbt.h" -#include "param/param.h" - -#define NBT_MAX_REPLIES 1000 - -/* - destroy a pending request -*/ -static int nbt_name_request_destructor(struct nbt_name_request *req) -{ - if (req->state == NBT_REQUEST_SEND) { - DLIST_REMOVE(req->nbtsock->send_queue, req); - } - if (req->state == NBT_REQUEST_WAIT) { - req->nbtsock->num_pending--; - } - if (req->name_trn_id != 0 && !req->is_reply) { - idr_remove(req->nbtsock->idr, req->name_trn_id); - req->name_trn_id = 0; - } - if (req->te) { - talloc_free(req->te); - req->te = NULL; - } - if (req->nbtsock->send_queue == NULL) { - EVENT_FD_NOT_WRITEABLE(req->nbtsock->fde); - } - if (req->nbtsock->num_pending == 0 && - req->nbtsock->incoming.handler == NULL) { - EVENT_FD_NOT_READABLE(req->nbtsock->fde); - } - return 0; -} - - -/* - handle send events on a nbt name socket -*/ -static void nbt_name_socket_send(struct nbt_name_socket *nbtsock) -{ - struct nbt_name_request *req = nbtsock->send_queue; - TALLOC_CTX *tmp_ctx = talloc_new(nbtsock); - NTSTATUS status; - - while ((req = nbtsock->send_queue)) { - size_t len; - - len = req->encoded.length; - status = socket_sendto(nbtsock->sock, &req->encoded, &len, - req->dest); - if (NT_STATUS_IS_ERR(status)) goto failed; - - if (!NT_STATUS_IS_OK(status)) { - talloc_free(tmp_ctx); - return; - } - - DLIST_REMOVE(nbtsock->send_queue, req); - req->state = NBT_REQUEST_WAIT; - if (req->is_reply) { - talloc_free(req); - } else { - EVENT_FD_READABLE(nbtsock->fde); - nbtsock->num_pending++; - } - } - - EVENT_FD_NOT_WRITEABLE(nbtsock->fde); - talloc_free(tmp_ctx); - return; - -failed: - DLIST_REMOVE(nbtsock->send_queue, req); - nbt_name_request_destructor(req); - req->status = status; - req->state = NBT_REQUEST_ERROR; - talloc_free(tmp_ctx); - if (req->async.fn) { - req->async.fn(req); - } else if (req->is_reply) { - talloc_free(req); - } - return; -} - - -/* - handle a request timeout -*/ -static void nbt_name_socket_timeout(struct event_context *ev, struct timed_event *te, - struct timeval t, void *private) -{ - struct nbt_name_request *req = talloc_get_type(private, - struct nbt_name_request); - - if (req->num_retries != 0) { - req->num_retries--; - req->te = event_add_timed(req->nbtsock->event_ctx, req, - timeval_add(&t, req->timeout, 0), - nbt_name_socket_timeout, req); - if (req->state != NBT_REQUEST_SEND) { - req->state = NBT_REQUEST_SEND; - DLIST_ADD_END(req->nbtsock->send_queue, req, - struct nbt_name_request *); - } - EVENT_FD_WRITEABLE(req->nbtsock->fde); - return; - } - - nbt_name_request_destructor(req); - if (req->num_replies == 0) { - req->state = NBT_REQUEST_TIMEOUT; - req->status = NT_STATUS_IO_TIMEOUT; - } else { - req->state = NBT_REQUEST_DONE; - req->status = NT_STATUS_OK; - } - if (req->async.fn) { - req->async.fn(req); - } else if (req->is_reply) { - talloc_free(req); - } -} - - - -/** - handle recv events on a nbt name socket -*/ -static void nbt_name_socket_recv(struct nbt_name_socket *nbtsock) -{ - TALLOC_CTX *tmp_ctx = talloc_new(nbtsock); - NTSTATUS status; - enum ndr_err_code ndr_err; - struct socket_address *src; - DATA_BLOB blob; - size_t nread, dsize; - struct nbt_name_packet *packet; - struct nbt_name_request *req; - - status = socket_pending(nbtsock->sock, &dsize); - if (!NT_STATUS_IS_OK(status)) { - talloc_free(tmp_ctx); - return; - } - - blob = data_blob_talloc(tmp_ctx, NULL, dsize); - if (blob.data == NULL) { - talloc_free(tmp_ctx); - return; - } - - status = socket_recvfrom(nbtsock->sock, blob.data, blob.length, &nread, - tmp_ctx, &src); - if (!NT_STATUS_IS_OK(status)) { - talloc_free(tmp_ctx); - return; - } - - packet = talloc(tmp_ctx, struct nbt_name_packet); - if (packet == NULL) { - talloc_free(tmp_ctx); - return; - } - - /* parse the request */ - ndr_err = ndr_pull_struct_blob(&blob, packet, nbtsock->iconv_convenience, packet, - (ndr_pull_flags_fn_t)ndr_pull_nbt_name_packet); - if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - status = ndr_map_error2ntstatus(ndr_err); - DEBUG(2,("Failed to parse incoming NBT name packet - %s\n", - nt_errstr(status))); - talloc_free(tmp_ctx); - return; - } - - if (DEBUGLVL(10)) { - DEBUG(10,("Received nbt packet of length %d from %s:%d\n", - (int)blob.length, src->addr, src->port)); - NDR_PRINT_DEBUG(nbt_name_packet, packet); - } - - /* if its not a reply then pass it off to the incoming request - handler, if any */ - if (!(packet->operation & NBT_FLAG_REPLY)) { - if (nbtsock->incoming.handler) { - nbtsock->incoming.handler(nbtsock, packet, src); - } - talloc_free(tmp_ctx); - return; - } - - /* find the matching request */ - req = (struct nbt_name_request *)idr_find(nbtsock->idr, - packet->name_trn_id); - if (req == NULL) { - if (nbtsock->unexpected.handler) { - nbtsock->unexpected.handler(nbtsock, packet, src); - } else { - DEBUG(10,("Failed to match request for incoming name packet id 0x%04x on %p\n", - packet->name_trn_id, nbtsock)); - } - talloc_free(tmp_ctx); - return; - } - - /* if this is a WACK response, this we need to go back to waiting, - but perhaps increase the timeout */ - if ((packet->operation & NBT_OPCODE) == NBT_OPCODE_WACK) { - if (req->received_wack || packet->ancount < 1) { - nbt_name_request_destructor(req); - req->status = NT_STATUS_INVALID_NETWORK_RESPONSE; - req->state = NBT_REQUEST_ERROR; - goto done; - } - talloc_free(req->te); - /* we know we won't need any more retries - the server - has received our request */ - req->num_retries = 0; - req->received_wack = true; - /* although there can be a timeout in the packet, w2k3 screws it up, - so better to set it ourselves */ - req->timeout = lp_parm_int(global_loadparm, NULL, "nbt", "wack_timeout", 30); - req->te = event_add_timed(req->nbtsock->event_ctx, req, - timeval_current_ofs(req->timeout, 0), - nbt_name_socket_timeout, req); - talloc_free(tmp_ctx); - return; - } - - - req->replies = talloc_realloc(req, req->replies, struct nbt_name_reply, req->num_replies+1); - if (req->replies == NULL) { - nbt_name_request_destructor(req); - req->state = NBT_REQUEST_ERROR; - req->status = NT_STATUS_NO_MEMORY; - goto done; - } - - talloc_steal(req, src); - req->replies[req->num_replies].dest = src; - talloc_steal(req, packet); - req->replies[req->num_replies].packet = packet; - req->num_replies++; - - /* if we don't want multiple replies then we are done */ - if (req->allow_multiple_replies && - req->num_replies < NBT_MAX_REPLIES) { - talloc_free(tmp_ctx); - return; - } - - nbt_name_request_destructor(req); - req->state = NBT_REQUEST_DONE; - req->status = NT_STATUS_OK; - -done: - talloc_free(tmp_ctx); - if (req->async.fn) { - req->async.fn(req); - } -} - -/* - handle fd events on a nbt_name_socket -*/ -static void nbt_name_socket_handler(struct event_context *ev, struct fd_event *fde, - uint16_t flags, void *private) -{ - struct nbt_name_socket *nbtsock = talloc_get_type(private, - struct nbt_name_socket); - if (flags & EVENT_FD_WRITE) { - nbt_name_socket_send(nbtsock); - } - if (flags & EVENT_FD_READ) { - nbt_name_socket_recv(nbtsock); - } -} - - -/* - initialise a nbt_name_socket. The event_ctx is optional, if provided - then operations will use that event context -*/ -_PUBLIC_ struct nbt_name_socket *nbt_name_socket_init(TALLOC_CTX *mem_ctx, - struct event_context *event_ctx, - struct smb_iconv_convenience *iconv_convenience) -{ - struct nbt_name_socket *nbtsock; - NTSTATUS status; - - nbtsock = talloc(mem_ctx, struct nbt_name_socket); - if (nbtsock == NULL) goto failed; - - nbtsock->event_ctx = talloc_reference(nbtsock, event_ctx); - if (nbtsock->event_ctx == NULL) goto failed; - - status = socket_create("ip", SOCKET_TYPE_DGRAM, &nbtsock->sock, 0); - if (!NT_STATUS_IS_OK(status)) goto failed; - - socket_set_option(nbtsock->sock, "SO_BROADCAST", "1"); - - talloc_steal(nbtsock, nbtsock->sock); - - nbtsock->idr = idr_init(nbtsock); - if (nbtsock->idr == NULL) goto failed; - - nbtsock->send_queue = NULL; - nbtsock->num_pending = 0; - nbtsock->incoming.handler = NULL; - nbtsock->unexpected.handler = NULL; - nbtsock->iconv_convenience = iconv_convenience; - - nbtsock->fde = event_add_fd(nbtsock->event_ctx, nbtsock, - socket_get_fd(nbtsock->sock), 0, - nbt_name_socket_handler, nbtsock); - - return nbtsock; - -failed: - talloc_free(nbtsock); - return NULL; -} - -/* - send off a nbt name request -*/ -struct nbt_name_request *nbt_name_request_send(struct nbt_name_socket *nbtsock, - struct socket_address *dest, - struct nbt_name_packet *request, - int timeout, int retries, - bool allow_multiple_replies) -{ - struct nbt_name_request *req; - int id; - enum ndr_err_code ndr_err; - - req = talloc_zero(nbtsock, struct nbt_name_request); - if (req == NULL) goto failed; - - req->nbtsock = nbtsock; - req->allow_multiple_replies = allow_multiple_replies; - req->state = NBT_REQUEST_SEND; - req->is_reply = false; - req->timeout = timeout; - req->num_retries = retries; - req->dest = dest; - if (talloc_reference(req, dest) == NULL) goto failed; - - /* we select a random transaction id unless the user supplied one */ - if (request->name_trn_id == 0) { - id = idr_get_new_random(req->nbtsock->idr, req, UINT16_MAX); - } else { - if (idr_find(req->nbtsock->idr, request->name_trn_id)) goto failed; - id = idr_get_new_above(req->nbtsock->idr, req, request->name_trn_id, - UINT16_MAX); - } - if (id == -1) goto failed; - - request->name_trn_id = id; - req->name_trn_id = id; - - req->te = event_add_timed(nbtsock->event_ctx, req, - timeval_current_ofs(req->timeout, 0), - nbt_name_socket_timeout, req); - - talloc_set_destructor(req, nbt_name_request_destructor); - - ndr_err = ndr_push_struct_blob(&req->encoded, req, - req->nbtsock->iconv_convenience, - request, - (ndr_push_flags_fn_t)ndr_push_nbt_name_packet); - if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) goto failed; - - DLIST_ADD_END(nbtsock->send_queue, req, struct nbt_name_request *); - - if (DEBUGLVL(10)) { - DEBUG(10,("Queueing nbt packet to %s:%d\n", - req->dest->addr, req->dest->port)); - NDR_PRINT_DEBUG(nbt_name_packet, request); - } - - EVENT_FD_WRITEABLE(nbtsock->fde); - - return req; - -failed: - talloc_free(req); - return NULL; -} - - -/* - send off a nbt name reply -*/ -_PUBLIC_ NTSTATUS nbt_name_reply_send(struct nbt_name_socket *nbtsock, - struct socket_address *dest, - struct nbt_name_packet *request) -{ - struct nbt_name_request *req; - enum ndr_err_code ndr_err; - - req = talloc_zero(nbtsock, struct nbt_name_request); - NT_STATUS_HAVE_NO_MEMORY(req); - - req->nbtsock = nbtsock; - req->dest = dest; - if (talloc_reference(req, dest) == NULL) goto failed; - req->state = NBT_REQUEST_SEND; - req->is_reply = true; - - talloc_set_destructor(req, nbt_name_request_destructor); - - if (DEBUGLVL(10)) { - NDR_PRINT_DEBUG(nbt_name_packet, request); - } - - ndr_err = ndr_push_struct_blob(&req->encoded, req, - req->nbtsock->iconv_convenience, - request, - (ndr_push_flags_fn_t)ndr_push_nbt_name_packet); - if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - talloc_free(req); - return ndr_map_error2ntstatus(ndr_err); - } - - DLIST_ADD_END(nbtsock->send_queue, req, struct nbt_name_request *); - - EVENT_FD_WRITEABLE(nbtsock->fde); - - return NT_STATUS_OK; - -failed: - talloc_free(req); - return NT_STATUS_NO_MEMORY; -} - -/* - wait for a nbt request to complete -*/ -NTSTATUS nbt_name_request_recv(struct nbt_name_request *req) -{ - if (!req) return NT_STATUS_NO_MEMORY; - - while (req->state < NBT_REQUEST_DONE) { - if (event_loop_once(req->nbtsock->event_ctx) != 0) { - req->state = NBT_REQUEST_ERROR; - req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR; - break; - } - } - return req->status; -} - - -/* - setup a handler for incoming requests -*/ -_PUBLIC_ NTSTATUS nbt_set_incoming_handler(struct nbt_name_socket *nbtsock, - void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, - struct socket_address *), - void *private) -{ - nbtsock->incoming.handler = handler; - nbtsock->incoming.private_data = private; - EVENT_FD_READABLE(nbtsock->fde); - return NT_STATUS_OK; -} - - -/* - turn a NBT rcode into a NTSTATUS -*/ -_PUBLIC_ NTSTATUS nbt_rcode_to_ntstatus(uint8_t rcode) -{ - int i; - struct { - enum nbt_rcode rcode; - NTSTATUS status; - } map[] = { - { NBT_RCODE_FMT, NT_STATUS_INVALID_PARAMETER }, - { NBT_RCODE_SVR, NT_STATUS_SERVER_DISABLED }, - { NBT_RCODE_NAM, NT_STATUS_OBJECT_NAME_NOT_FOUND }, - { NBT_RCODE_IMP, NT_STATUS_NOT_SUPPORTED }, - { NBT_RCODE_RFS, NT_STATUS_ACCESS_DENIED }, - { NBT_RCODE_ACT, NT_STATUS_ADDRESS_ALREADY_EXISTS }, - { NBT_RCODE_CFT, NT_STATUS_CONFLICTING_ADDRESSES } - }; - for (i=0;i 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 . -*/ - -#include "includes.h" -#include -#include "libcli/util/pyerrors.h" -#include "libcli/nbt/libnbt.h" -#include "lib/events/events.h" -#include "param/param.h" - -PyAPI_DATA(PyTypeObject) nbt_node_Type; - -typedef struct { - PyObject_HEAD - TALLOC_CTX *mem_ctx; - struct nbt_name_socket *socket; -} nbt_node_Object; - -static void py_nbt_node_dealloc(PyObject *obj) -{ - talloc_free(((nbt_node_Object *)obj)->mem_ctx); - PyObject_Del(obj); -} - -static PyObject *py_nbt_node_init(PyTypeObject *self, PyObject *args, PyObject *kwargs) -{ - struct event_context *ev; - nbt_node_Object *ret = PyObject_New(nbt_node_Object, &nbt_node_Type); - - ret->mem_ctx = talloc_new(NULL); - if (ret->mem_ctx == NULL) - return NULL; - - ev = s4_event_context_init(ret->mem_ctx); - ret->socket = nbt_name_socket_init(ret->mem_ctx, ev, lp_iconv_convenience(global_loadparm)); - return (PyObject *)ret; -} - -static bool PyObject_AsDestinationTuple(PyObject *obj, const char **dest_addr, uint16_t *dest_port) -{ - if (PyString_Check(obj)) { - *dest_addr = PyString_AsString(obj); - *dest_port = NBT_NAME_SERVICE_PORT; - return true; - } - - if (PyTuple_Check(obj)) { - if (PyTuple_Size(obj) < 1) { - PyErr_SetString(PyExc_TypeError, "Destination tuple size invalid"); - return false; - } - - if (!PyString_Check(PyTuple_GetItem(obj, 0))) { - PyErr_SetString(PyExc_TypeError, "Destination tuple first element not string"); - return false; - } - - *dest_addr = PyString_AsString(obj); - - if (PyTuple_Size(obj) == 1) { - *dest_port = NBT_NAME_SERVICE_PORT; - return true; - } else if (PyInt_Check(PyTuple_GetItem(obj, 1))) { - *dest_port = PyInt_AsLong(PyTuple_GetItem(obj, 1)); - return true; - } else { - PyErr_SetString(PyExc_TypeError, "Destination tuple second element not a port"); - return false; - } - } - - PyErr_SetString(PyExc_TypeError, "Destination tuple second element not a port"); - return false; -} - -static bool PyObject_AsNBTName(PyObject *obj, struct nbt_name_socket *socket, struct nbt_name *name) -{ - if (PyTuple_Check(obj)) { - if (PyTuple_Size(obj) == 2) { - name->name = PyString_AsString(PyTuple_GetItem(obj, 0)); - name->type = PyInt_AsLong(PyTuple_GetItem(obj, 1)); - name->scope = NULL; - return true; - } else if (PyTuple_Size(obj) == 3) { - name->name = PyString_AsString(PyTuple_GetItem(obj, 0)); - name->scope = PyString_AsString(PyTuple_GetItem(obj, 1)); - name->type = PyInt_AsLong(PyTuple_GetItem(obj, 2)); - return true; - } else { - PyErr_SetString(PyExc_TypeError, "Invalid tuple size"); - return false; - } - } - - if (PyString_Check(obj)) { - /* FIXME: Parse string to be able to interpret things like RHONWYN<02> ? */ - name->name = PyString_AsString(obj); - name->scope = NULL; - name->type = 0; - return true; - } - - PyErr_SetString(PyExc_TypeError, "Invalid type for object"); - return false; -} - -static PyObject *PyObject_FromNBTName(struct nbt_name_socket *socket, struct smb_iconv_convenience *ic, - struct nbt_name *name) -{ - if (name->scope) { - return Py_BuildValue("(ssi)", name->name, name->scope, name->type); - } else { - return Py_BuildValue("(si)", name->name, name->type); - } -} - -static PyObject *py_nbt_name_query(PyObject *self, PyObject *args, PyObject *kwargs) -{ - nbt_node_Object *node = (nbt_node_Object *)self; - PyObject *ret, *reply_addrs, *py_dest, *py_name; - struct nbt_name_query io; - NTSTATUS status; - int i; - - const char *kwnames[] = { "name", "dest", "broadcast", "wins", "timeout", - "retries", NULL }; - io.in.broadcast = true; - io.in.wins_lookup = false; - io.in.timeout = 0; - io.in.retries = 3; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|bbii:query_name", - discard_const_p(char *, kwnames), - &py_name, &py_dest, - &io.in.broadcast, &io.in.wins_lookup, - &io.in.timeout, &io.in.retries)) { - return NULL; - } - - if (!PyObject_AsDestinationTuple(py_dest, &io.in.dest_addr, &io.in.dest_port)) - return NULL; - - if (!PyObject_AsNBTName(py_name, node->socket, &io.in.name)) - return NULL; - - status = nbt_name_query(node->socket, NULL, &io); - - if (NT_STATUS_IS_ERR(status)) { - PyErr_SetNTSTATUS(status); - return NULL; - } - - ret = PyTuple_New(3); - if (ret == NULL) - return NULL; - PyTuple_SetItem(ret, 0, PyString_FromString(io.out.reply_from)); - - py_name = PyObject_FromNBTName(node->socket, lp_iconv_convenience(global_loadparm), &io.out.name); - if (py_name == NULL) - return NULL; - - PyTuple_SetItem(ret, 1, py_name); - - reply_addrs = PyList_New(io.out.num_addrs); - if (reply_addrs == NULL) { - Py_DECREF(ret); - return NULL; - } - - for (i = 0; i < io.out.num_addrs; i++) { - PyList_SetItem(reply_addrs, i, PyString_FromString(io.out.reply_addrs[i])); - } - - PyTuple_SetItem(ret, 2, reply_addrs); - return ret; -} - -static PyObject *py_nbt_name_status(PyObject *self, PyObject *args, PyObject *kwargs) -{ - nbt_node_Object *node = (nbt_node_Object *)self; - PyObject *ret, *py_dest, *py_name, *py_names; - struct nbt_name_status io; - int i; - NTSTATUS status; - - const char *kwnames[] = { "name", "dest", "timeout", "retries", NULL }; - - io.in.timeout = 0; - io.in.retries = 0; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|ii:name_status", - discard_const_p(char *, kwnames), - &py_name, &py_dest, - &io.in.timeout, &io.in.retries)) { - return NULL; - } - - if (!PyObject_AsDestinationTuple(py_dest, &io.in.dest_addr, &io.in.dest_port)) - return NULL; - - if (!PyObject_AsNBTName(py_name, node->socket, &io.in.name)) - return NULL; - - status = nbt_name_status(node->socket, NULL, &io); - - if (NT_STATUS_IS_ERR(status)) { - PyErr_SetNTSTATUS(status); - return NULL; - } - - ret = PyTuple_New(3); - if (ret == NULL) - return NULL; - PyTuple_SetItem(ret, 0, PyString_FromString(io.out.reply_from)); - - py_name = PyObject_FromNBTName(node->socket, lp_iconv_convenience(global_loadparm), &io.out.name); - if (py_name == NULL) - return NULL; - - PyTuple_SetItem(ret, 1, py_name); - - py_names = PyList_New(io.out.status.num_names); - - for (i = 0; i < io.out.status.num_names; i++) { - PyList_SetItem(py_names, i, Py_BuildValue("(sii)", - io.out.status.names[i].name, - io.out.status.names[i].nb_flags, - io.out.status.names[i].type)); - } - - PyTuple_SetItem(ret, 2, py_names); - - return ret; -} - -static PyObject *py_nbt_name_register(PyObject *self, PyObject *args, PyObject *kwargs) -{ - nbt_node_Object *node = (nbt_node_Object *)self; - PyObject *ret, *py_dest, *py_name; - struct nbt_name_register io; - NTSTATUS status; - - const char *kwnames[] = { "name", "address", "dest", "register_demand", "broadcast", - "multi_homed", "ttl", "timeout", "retries", NULL }; - - io.in.broadcast = true; - io.in.multi_homed = true; - io.in.register_demand = true; - io.in.timeout = 0; - io.in.retries = 0; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OsO|bbbiii:query_name", - discard_const_p(char *, kwnames), - &py_name, &io.in.address, &py_dest, - &io.in.register_demand, - &io.in.broadcast, &io.in.multi_homed, - &io.in.ttl, &io.in.timeout, &io.in.retries)) { - return NULL; - } - - if (!PyObject_AsDestinationTuple(py_dest, &io.in.dest_addr, &io.in.dest_port)) - return NULL; - - if (!PyObject_AsNBTName(py_name, node->socket, &io.in.name)) - return NULL; - - status = nbt_name_register(node->socket, NULL, &io); - - if (NT_STATUS_IS_ERR(status)) { - PyErr_SetNTSTATUS(status); - return NULL; - } - - ret = PyTuple_New(3); - if (ret == NULL) - return NULL; - PyTuple_SetItem(ret, 0, PyString_FromString(io.out.reply_from)); - - py_name = PyObject_FromNBTName(node->socket, lp_iconv_convenience(global_loadparm), &io.out.name); - if (py_name == NULL) - return NULL; - - PyTuple_SetItem(ret, 1, py_name); - - PyTuple_SetItem(ret, 2, PyString_FromString(io.out.reply_addr)); - - PyTuple_SetItem(ret, 3, PyInt_FromLong(io.out.rcode)); - - return ret; -} - -static PyObject *py_nbt_name_refresh(PyObject *self, PyObject *args, PyObject *kwargs) -{ - nbt_node_Object *node = (nbt_node_Object *)self; - PyObject *ret, *py_dest, *py_name; - struct nbt_name_refresh io; - NTSTATUS status; - - const char *kwnames[] = { "name", "address", "dest", "nb_flags", "broadcast", - "ttl", "timeout", "retries", NULL }; - - io.in.broadcast = true; - io.in.nb_flags = 0; - io.in.timeout = 0; - io.in.retries = 0; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OsO|ibiii:query_name", - discard_const_p(char *, kwnames), - &py_name, &io.in.address, &py_dest, - &io.in.nb_flags, - &io.in.broadcast, - &io.in.ttl, &io.in.timeout, &io.in.retries)) { - return NULL; - } - - if (!PyObject_AsDestinationTuple(py_dest, &io.in.dest_addr, &io.in.dest_port)) - return NULL; - - if (!PyObject_AsNBTName(py_name, node->socket, &io.in.name)) - return NULL; - - status = nbt_name_refresh(node->socket, NULL, &io); - - if (NT_STATUS_IS_ERR(status)) { - PyErr_SetNTSTATUS(status); - return NULL; - } - - ret = PyTuple_New(3); - if (ret == NULL) - return NULL; - PyTuple_SetItem(ret, 0, PyString_FromString(io.out.reply_from)); - - py_name = PyObject_FromNBTName(node->socket, lp_iconv_convenience(global_loadparm), &io.out.name); - if (py_name == NULL) - return NULL; - - PyTuple_SetItem(ret, 1, py_name); - - PyTuple_SetItem(ret, 2, PyString_FromString(io.out.reply_addr)); - - PyTuple_SetItem(ret, 3, PyInt_FromLong(io.out.rcode)); - - return ret; -} - -static PyObject *py_nbt_name_release(PyObject *self, PyObject *args, PyObject *kwargs) -{ - return Py_None; /* FIXME */ -} - -static PyMethodDef py_nbt_methods[] = { - { "query_name", (PyCFunction)py_nbt_name_query, METH_VARARGS|METH_KEYWORDS, - "S.query_name(name, dest, broadcast=True, wins=False, timeout=0, retries=3) -> (reply_from, name, reply_addr)\n" - "Query for a NetBIOS name" }, - { "register_name", (PyCFunction)py_nbt_name_register, METH_VARARGS|METH_KEYWORDS, - "S.register_name(name, address, dest, register_demand=True, broadcast=True, multi_homed=True, ttl=0, timeout=0, retries=0) -> (reply_from, name, reply_addr, rcode)\n" - "Register a new name" }, - { "release_name", (PyCFunction)py_nbt_name_release, METH_VARARGS|METH_KEYWORDS, "S.release_name(name, address, dest, nb_flags=0, broadcast=true, timeout=0, retries=3) -> (reply_from, name, reply_addr, rcode)\n" - "release a previously registered name" }, - { "refresh_name", (PyCFunction)py_nbt_name_refresh, METH_VARARGS|METH_KEYWORDS, "S.refresh_name(name, address, dest, nb_flags=0, broadcast=True, ttl=0, timeout=0, retries=0) -> (reply_from, name, reply_addr, rcode)\n" - "release a previously registered name" }, - { "name_status", (PyCFunction)py_nbt_name_status, METH_VARARGS|METH_KEYWORDS, - "S.name_status(name, dest, timeout=0, retries=0) -> (reply_from, name, status)\n" - "Find the status of a name" }, - - { NULL } -}; - -PyTypeObject nbt_node_Type = { - PyObject_HEAD_INIT(NULL) 0, - .tp_name = "netbios.Node", - .tp_basicsize = sizeof(nbt_node_Object), - .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, - .tp_new = py_nbt_node_init, - .tp_dealloc = py_nbt_node_dealloc, - .tp_methods = py_nbt_methods, - .tp_doc = "Node()\n" - "Create a new NetBIOS node\n" -}; - -void initnetbios(void) -{ - PyObject *mod; - if (PyType_Ready(&nbt_node_Type) < 0) - return; - - mod = Py_InitModule3("netbios", NULL, "NetBIOS over TCP/IP support"); - - Py_INCREF((PyObject *)&nbt_node_Type); - PyModule_AddObject(mod, "Node", (PyObject *)&nbt_node_Type); -} -- cgit From a1a92688ba0a811400b4d12920988c62fa0efdf4 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 08:06:33 +0200 Subject: s4-nbt: use ../libcli/nbt Guenther --- source4/libcli/composite/composite.c | 2 +- source4/libcli/config.mk | 10 +++++----- source4/libcli/raw/clitransport.c | 2 +- source4/libcli/resolve/nbtlist.c | 2 +- source4/libcli/resolve/resolve.h | 2 +- source4/libcli/resolve/wins.c | 2 +- source4/librpc/idl/nbt.idl | 2 +- source4/nbt_server/nbt_server.h | 2 +- source4/torture/nbt/nbt.c | 2 +- source4/utils/nmblookup.c | 2 +- 10 files changed, 14 insertions(+), 14 deletions(-) diff --git a/source4/libcli/composite/composite.c b/source4/libcli/composite/composite.c index 91a842706f..104397fa48 100644 --- a/source4/libcli/composite/composite.c +++ b/source4/libcli/composite/composite.c @@ -28,7 +28,7 @@ #include "libcli/composite/composite.h" #include "lib/messaging/irpc.h" #include "librpc/rpc/dcerpc.h" -#include "libcli/nbt/libnbt.h" +#include "../libcli/nbt/libnbt.h" /* create a new composite_context structure diff --git a/source4/libcli/config.mk b/source4/libcli/config.mk index 262a2cfa22..cee51439ab 100644 --- a/source4/libcli/config.mk +++ b/source4/libcli/config.mk @@ -40,22 +40,22 @@ $(eval $(call proto_header_template,$(libclisrcdir)/smb_composite/proto.h,$(LIBC [SUBSYSTEM::NDR_NBT_BUF] -NDR_NBT_BUF_OBJ_FILES = $(libclisrcdir)/nbt/nbtname.o +NDR_NBT_BUF_OBJ_FILES = ../$(libclisrcdir)/nbt/nbtname.o -$(eval $(call proto_header_template,$(libclisrcdir)/nbt/nbtname.h,$(NDR_NBT_BUF_OBJ_FILES:.o=.c))) +$(eval $(call proto_header_template,../$(libclisrcdir)/nbt/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 $(libclisrcdir)/nbt/, \ +LIBCLI_NBT_OBJ_FILES = $(addprefix ../$(libclisrcdir)/nbt/, \ nbtsocket.o \ namequery.o \ nameregister.o \ namerefresh.o \ namerelease.o) -$(eval $(call proto_header_template,$(libclisrcdir)/nbt/nbt_proto.h,$(LIBCLI_NBT_OBJ_FILES:.o=.c))) +$(eval $(call proto_header_template,../$(libclisrcdir)/nbt/nbt_proto.h,$(LIBCLI_NBT_OBJ_FILES:.o=.c))) [SUBSYSTEM::LIBCLI_NDR_NETLOGON] PUBLIC_DEPENDENCIES = LIBNDR \ @@ -85,7 +85,7 @@ $(eval $(call proto_header_template,$(libclisrcdir)/drsblobs_proto.h,$(LIBCLI_DR LIBRARY_REALNAME = samba/netbios.$(SHLIBEXT) PUBLIC_DEPENDENCIES = LIBCLI_NBT DYNCONFIG LIBSAMBA-HOSTCONFIG -python_netbios_OBJ_FILES = $(libclisrcdir)/nbt/pynbt.o +python_netbios_OBJ_FILES = ../$(libclisrcdir)/nbt/pynbt.o $(python_libcli_nbt_OBJ_FILES): CFLAGS+=$(CFLAG_NO_UNUSED_MACROS) $(CFLAG_NO_CAST_QUAL) diff --git a/source4/libcli/raw/clitransport.c b/source4/libcli/raw/clitransport.c index e95ae3271e..f8ef343e3a 100644 --- a/source4/libcli/raw/clitransport.c +++ b/source4/libcli/raw/clitransport.c @@ -28,7 +28,7 @@ #include "lib/stream/packet.h" #include "librpc/gen_ndr/ndr_nbt.h" #include "param/param.h" -#include "libcli/nbt/libnbt.h" +#include "../libcli/nbt/libnbt.h" /* diff --git a/source4/libcli/resolve/nbtlist.c b/source4/libcli/resolve/nbtlist.c index 0cc2ee6726..7dafd130f8 100644 --- a/source4/libcli/resolve/nbtlist.c +++ b/source4/libcli/resolve/nbtlist.c @@ -28,7 +28,7 @@ #include "system/network.h" #include "lib/socket/netif.h" #include "librpc/gen_ndr/ndr_nbt.h" -#include "libcli/nbt/libnbt.h" +#include "../libcli/nbt/libnbt.h" #include "param/param.h" struct nbtlist_state { diff --git a/source4/libcli/resolve/resolve.h b/source4/libcli/resolve/resolve.h index 79b91dc836..22de146c99 100644 --- a/source4/libcli/resolve/resolve.h +++ b/source4/libcli/resolve/resolve.h @@ -22,7 +22,7 @@ #ifndef __RESOLVE_H__ #define __RESOLVE_H__ -#include "libcli/nbt/libnbt.h" +#include "../libcli/nbt/libnbt.h" typedef struct composite_context *(*resolve_name_send_fn)(TALLOC_CTX *mem_ctx, struct event_context *, void *privdata, struct nbt_name *); typedef NTSTATUS (*resolve_name_recv_fn)(struct composite_context *, TALLOC_CTX *, const char **); #include "libcli/resolve/proto.h" diff --git a/source4/libcli/resolve/wins.c b/source4/libcli/resolve/wins.c index 3ec180f332..ebce9b98bd 100644 --- a/source4/libcli/resolve/wins.c +++ b/source4/libcli/resolve/wins.c @@ -20,7 +20,7 @@ */ #include "includes.h" -#include "libcli/nbt/libnbt.h" +#include "../libcli/nbt/libnbt.h" #include "libcli/resolve/resolve.h" #include "param/param.h" #include "lib/socket/netif.h" diff --git a/source4/librpc/idl/nbt.idl b/source4/librpc/idl/nbt.idl index 63be489e0d..fad3a39e30 100644 --- a/source4/librpc/idl/nbt.idl +++ b/source4/librpc/idl/nbt.idl @@ -10,7 +10,7 @@ import "misc.idl", "security.idl", "svcctl.idl", "samr.idl"; [ - helper("libcli/netlogon.h", "libcli/nbt/libnbt.h") + helper("libcli/netlogon.h", "../libcli/nbt/libnbt.h") ] interface nbt { diff --git a/source4/nbt_server/nbt_server.h b/source4/nbt_server/nbt_server.h index 688b6a7a7d..00d8f31b2b 100644 --- a/source4/nbt_server/nbt_server.h +++ b/source4/nbt_server/nbt_server.h @@ -19,7 +19,7 @@ along with this program. If not, see . */ -#include "libcli/nbt/libnbt.h" +#include "../libcli/nbt/libnbt.h" #include "libcli/wrepl/winsrepl.h" #include "libcli/dgram/libdgram.h" #include "librpc/gen_ndr/irpc.h" diff --git a/source4/torture/nbt/nbt.c b/source4/torture/nbt/nbt.c index 7d35fc856a..aee0c54358 100644 --- a/source4/torture/nbt/nbt.c +++ b/source4/torture/nbt/nbt.c @@ -18,7 +18,7 @@ */ #include "includes.h" -#include "libcli/nbt/libnbt.h" +#include "../libcli/nbt/libnbt.h" #include "torture/torture.h" #include "torture/nbt/proto.h" #include "torture/smbtorture.h" diff --git a/source4/utils/nmblookup.c b/source4/utils/nmblookup.c index a74ab5a42e..0d98cb99de 100644 --- a/source4/utils/nmblookup.c +++ b/source4/utils/nmblookup.c @@ -29,7 +29,7 @@ #include "system/locale.h" #include "lib/socket/netif.h" #include "librpc/gen_ndr/nbt.h" -#include "libcli/nbt/libnbt.h" +#include "../libcli/nbt/libnbt.h" #include "param/param.h" /* command line options */ -- cgit From 83c042583b8a18fbb41e1fa8402ac91490941cff Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 08:59:19 +0200 Subject: s3-nbt: refer to ../libcli/nbt in nbt.idl. Guenther --- source3/librpc/idl/nbt.idl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/librpc/idl/nbt.idl b/source3/librpc/idl/nbt.idl index 99bffc8755..da1eb2ef3f 100644 --- a/source3/librpc/idl/nbt.idl +++ b/source3/librpc/idl/nbt.idl @@ -10,7 +10,7 @@ import "misc.idl", "security.idl", "svcctl.idl", "samr.idl"; [ -helper("libcli/nbt/libnbt.h") +helper("../libcli/nbt/libnbt.h") ] interface nbt { -- cgit From 9f8813e4d4f4963e6ec15e1886e03421c782f638 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 08:59:40 +0200 Subject: s3: re-run make idl. Guenther --- source3/librpc/gen_ndr/ndr_nbt.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/librpc/gen_ndr/ndr_nbt.h b/source3/librpc/gen_ndr/ndr_nbt.h index f6f3e3c899..f70d1ba8df 100644 --- a/source3/librpc/gen_ndr/ndr_nbt.h +++ b/source3/librpc/gen_ndr/ndr_nbt.h @@ -6,7 +6,7 @@ #ifndef _HEADER_NDR_nbt #define _HEADER_NDR_nbt -#include "libcli/nbt/libnbt.h" +#include "../libcli/nbt/libnbt.h" #define NDR_NBT_CALL_COUNT (0) void ndr_print_nbt_operation(struct ndr_print *ndr, const char *name, uint16_t r); void ndr_print_nbt_name_type(struct ndr_print *ndr, const char *name, enum nbt_name_type r); -- cgit From 7f5aef542ae07e5b53a2372c41b6da4e1123459b Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 08:34:22 +0200 Subject: s3-nbt: use ../libcli/nbt helper. Guenther --- source3/Makefile.in | 2 +- source3/include/proto.h | 17 ----------------- 2 files changed, 1 insertion(+), 18 deletions(-) diff --git a/source3/Makefile.in b/source3/Makefile.in index 1ce0ce9067..94d8d50da8 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -376,7 +376,7 @@ LIBADS_SERVER_OBJ = libads/kerberos_verify.o libads/authdata.o \ SECRETS_OBJ = passdb/secrets.o passdb/machine_sid.o -LIBNBT_OBJ = libcli/nbt/nbtname.o \ +LIBNBT_OBJ = ../libcli/nbt/nbtname.o \ librpc/gen_ndr/ndr_nbt.o \ librpc/gen_ndr/ndr_svcctl.o diff --git a/source3/include/proto.h b/source3/include/proto.h index ddd3a573f2..a2772384c5 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -2204,23 +2204,6 @@ ADS_STATUS ads_change_trust_account_password(ADS_STRUCT *ads, char *host_princip ADS_STATUS ads_guess_service_principal(ADS_STRUCT *ads, char **returned_principal); -/* The following definitions come from libcli/nbt/nbtname.c */ - -_PUBLIC_ void ndr_print_nbt_string(struct ndr_print *ndr, const char *name, const char *s); -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_string(struct ndr_pull *ndr, int ndr_flags, const char **s); -_PUBLIC_ enum ndr_err_code ndr_push_nbt_string(struct ndr_push *ndr, int ndr_flags, const char *s); -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_name(struct ndr_pull *ndr, int ndr_flags, struct nbt_name *r); -_PUBLIC_ enum ndr_err_code ndr_push_nbt_name(struct ndr_push *ndr, int ndr_flags, const struct nbt_name *r); -_PUBLIC_ NTSTATUS nbt_name_dup(TALLOC_CTX *mem_ctx, struct nbt_name *name, struct nbt_name *newname); -_PUBLIC_ NTSTATUS nbt_name_to_blob(TALLOC_CTX *mem_ctx, DATA_BLOB *blob, struct nbt_name *name); -_PUBLIC_ NTSTATUS nbt_name_from_blob(TALLOC_CTX *mem_ctx, const DATA_BLOB *blob, struct nbt_name *name); -_PUBLIC_ void nbt_choose_called_name(TALLOC_CTX *mem_ctx, - struct nbt_name *n, const char *name, int type); -_PUBLIC_ char *nbt_name_string(TALLOC_CTX *mem_ctx, const struct nbt_name *name); -_PUBLIC_ enum ndr_err_code ndr_pull_wrepl_nbt_name(struct ndr_pull *ndr, int ndr_flags, const struct nbt_name **_r); -_PUBLIC_ enum ndr_err_code ndr_push_wrepl_nbt_name(struct ndr_push *ndr, int ndr_flags, const struct nbt_name *r); -_PUBLIC_ void ndr_print_wrepl_nbt_name(struct ndr_print *ndr, const char *name, const struct nbt_name *r); - /* The following definitions come from libgpo/gpext/gpext.c */ struct gp_extension *get_gp_extension_list(void); -- cgit From fd3ba988dca5014a9a2d5636506265c084e5db97 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 09:49:56 +0200 Subject: s3-nbt: fix remaining callers of ndr_push/pull_struct_blob. Guenther --- source3/lib/messages_local.c | 4 ++-- source3/lib/secdesc.c | 4 ++-- source3/libnet/libnet_dssync_keytab.c | 6 +++--- source3/libnet/libnet_samsync.c | 4 ++-- source3/libsmb/clidgram.c | 2 +- source3/modules/vfs_acl_xattr.c | 4 ++-- source3/modules/vfs_xattr_tdb.c | 4 ++-- source3/utils/net_rpc_registry.c | 2 +- 8 files changed, 15 insertions(+), 15 deletions(-) diff --git a/source3/lib/messages_local.c b/source3/lib/messages_local.c index f436afc2ff..9f7f88f783 100644 --- a/source3/lib/messages_local.c +++ b/source3/lib/messages_local.c @@ -160,7 +160,7 @@ static NTSTATUS messaging_tdb_fetch(TDB_CONTEXT *msg_tdb, blob = data_blob_const(data.dptr, data.dsize); ndr_err = ndr_pull_struct_blob( - &blob, result, result, + &blob, result, NULL, result, (ndr_pull_flags_fn_t)ndr_pull_messaging_array); SAFE_FREE(data.dptr); @@ -203,7 +203,7 @@ static NTSTATUS messaging_tdb_store(TDB_CONTEXT *msg_tdb, } ndr_err = ndr_push_struct_blob( - &blob, mem_ctx, array, + &blob, mem_ctx, NULL, array, (ndr_push_flags_fn_t)ndr_push_messaging_array); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { diff --git a/source3/lib/secdesc.c b/source3/lib/secdesc.c index 44ae23271e..4965200bc1 100644 --- a/source3/lib/secdesc.c +++ b/source3/lib/secdesc.c @@ -249,7 +249,7 @@ NTSTATUS marshall_sec_desc(TALLOC_CTX *mem_ctx, enum ndr_err_code ndr_err; ndr_err = ndr_push_struct_blob( - &blob, mem_ctx, secdesc, + &blob, mem_ctx, NULL, secdesc, (ndr_push_flags_fn_t)ndr_push_security_descriptor); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { @@ -285,7 +285,7 @@ NTSTATUS unmarshall_sec_desc(TALLOC_CTX *mem_ctx, uint8 *data, size_t len, blob = data_blob_const(data, len); ndr_err = ndr_pull_struct_blob( - &blob, result, result, + &blob, result, NULL, result, (ndr_pull_flags_fn_t)ndr_pull_security_descriptor); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { diff --git a/source3/libnet/libnet_dssync_keytab.c b/source3/libnet/libnet_dssync_keytab.c index 6ba2c3aa41..e762ecbe49 100644 --- a/source3/libnet/libnet_dssync_keytab.c +++ b/source3/libnet/libnet_dssync_keytab.c @@ -86,7 +86,7 @@ static NTSTATUS keytab_startup(struct dssync_context *ctx, TALLOC_CTX *mem_ctx, old_utdv = talloc(mem_ctx, struct replUpToDateVectorBlob); ndr_err = ndr_pull_struct_blob(&entry->password, old_utdv, - old_utdv, + NULL, old_utdv, (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { NTSTATUS status = ndr_map_error2ntstatus(ndr_err); @@ -124,7 +124,7 @@ static NTSTATUS keytab_finish(struct dssync_context *ctx, TALLOC_CTX *mem_ctx, NDR_PRINT_DEBUG(replUpToDateVectorBlob, new_utdv); } - ndr_err = ndr_push_struct_blob(&blob, mem_ctx, new_utdv, + ndr_err = ndr_push_struct_blob(&blob, mem_ctx, NULL, new_utdv, (ndr_push_flags_fn_t)ndr_push_replUpToDateVectorBlob); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { status = ndr_map_error2ntstatus(ndr_err); @@ -236,7 +236,7 @@ static NTSTATUS parse_supplemental_credentials(TALLOC_CTX *mem_ctx, status = NT_STATUS_NO_MEMORY; goto done; } - ndr_err = ndr_pull_struct_blob(&scpk_blob, mem_ctx, pkb, + ndr_err = ndr_pull_struct_blob(&scpk_blob, mem_ctx, NULL, pkb, (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { status = ndr_map_error2ntstatus(ndr_err); diff --git a/source3/libnet/libnet_samsync.c b/source3/libnet/libnet_samsync.c index daf27ffb51..64dcf6de51 100644 --- a/source3/libnet/libnet_samsync.c +++ b/source3/libnet/libnet_samsync.c @@ -65,7 +65,7 @@ static NTSTATUS fix_user(TALLOC_CTX *mem_ctx, user->user_private_info.SensitiveData = data.data; user->user_private_info.DataLength = data.length; - ndr_err = ndr_pull_struct_blob(&data, mem_ctx, &keys, + ndr_err = ndr_pull_struct_blob(&data, mem_ctx, NULL, &keys, (ndr_pull_flags_fn_t)ndr_pull_netr_USER_KEYS); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { dump_data(10, data.data, data.length); @@ -397,7 +397,7 @@ NTSTATUS pull_netr_AcctLockStr(TALLOC_CTX *mem_ctx, blob = data_blob_const(r->array, r->length); - ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, str, + ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, NULL, str, (ndr_pull_flags_fn_t)ndr_pull_netr_AcctLockStr); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { diff --git a/source3/libsmb/clidgram.c b/source3/libsmb/clidgram.c index 8b35a69def..8ee3507a04 100644 --- a/source3/libsmb/clidgram.c +++ b/source3/libsmb/clidgram.c @@ -181,7 +181,7 @@ bool send_getdc_request(TALLOC_CTX *mem_ctx, NDR_PRINT_DEBUG(nbt_ntlogon_packet, &packet); } - ndr_err = ndr_push_struct_blob(&blob, mem_ctx, &packet, + ndr_err = ndr_push_struct_blob(&blob, mem_ctx, NULL, &packet, (ndr_push_flags_fn_t)ndr_push_nbt_ntlogon_packet); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { return false; diff --git a/source3/modules/vfs_acl_xattr.c b/source3/modules/vfs_acl_xattr.c index fd59310755..a2f3477b76 100644 --- a/source3/modules/vfs_acl_xattr.c +++ b/source3/modules/vfs_acl_xattr.c @@ -38,7 +38,7 @@ static NTSTATUS parse_acl_blob(const DATA_BLOB *pblob, size_t sd_size; struct timespec ts; - ndr_err = ndr_pull_struct_blob(pblob, ctx, &xacl, + ndr_err = ndr_pull_struct_blob(pblob, ctx, NULL, &xacl, (ndr_pull_flags_fn_t)ndr_pull_xattr_NTACL); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { @@ -245,7 +245,7 @@ static NTSTATUS create_acl_blob(SEC_DESC *psd, DATA_BLOB *pblob) unix_timespec_to_nt_time(&xacl.info.sd_ts->last_changed, curr); ndr_err = ndr_push_struct_blob( - pblob, ctx, &xacl, + pblob, ctx, NULL, &xacl, (ndr_push_flags_fn_t)ndr_push_xattr_NTACL); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { diff --git a/source3/modules/vfs_xattr_tdb.c b/source3/modules/vfs_xattr_tdb.c index 7b5e510747..c707a1828f 100644 --- a/source3/modules/vfs_xattr_tdb.c +++ b/source3/modules/vfs_xattr_tdb.c @@ -48,7 +48,7 @@ static NTSTATUS xattr_tdb_pull_attrs(TALLOC_CTX *mem_ctx, blob = data_blob_const(data->dptr, data->dsize); ndr_err = ndr_pull_struct_blob( - &blob, result, result, + &blob, result, NULL, result, (ndr_pull_flags_fn_t)ndr_pull_tdb_xattrs); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { @@ -74,7 +74,7 @@ static NTSTATUS xattr_tdb_push_attrs(TALLOC_CTX *mem_ctx, enum ndr_err_code ndr_err; ndr_err = ndr_push_struct_blob( - &blob, mem_ctx, attribs, + &blob, mem_ctx, NULL, attribs, (ndr_push_flags_fn_t)ndr_push_tdb_xattrs); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { diff --git a/source3/utils/net_rpc_registry.c b/source3/utils/net_rpc_registry.c index 124af00b57..005e3ca556 100644 --- a/source3/utils/net_rpc_registry.c +++ b/source3/utils/net_rpc_registry.c @@ -1186,7 +1186,7 @@ static NTSTATUS rpc_registry_getsd_internal(struct net_context *c, blob.data = sd->data; blob.length = sd->size; - ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &sec_desc, + ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, NULL, &sec_desc, (ndr_pull_flags_fn_t)ndr_pull_security_descriptor); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { status = ndr_map_error2ntstatus(ndr_err); -- cgit From 6c8c5d7113fda1a0d6a843f2564e84e2a3daf4c2 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Mon, 22 Sep 2008 10:34:57 +0200 Subject: [s3]winbind_util: fix an implicit cast compile warning. Michael --- source3/winbindd/winbindd_util.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/winbindd/winbindd_util.c b/source3/winbindd/winbindd_util.c index e7b6576317..b296465ed5 100644 --- a/source3/winbindd/winbindd_util.c +++ b/source3/winbindd/winbindd_util.c @@ -1160,7 +1160,7 @@ void parse_add_domuser(void *buf, char *domuser, int *len) } } - safe_strcpy(buf, user, *len); + safe_strcpy((char *)buf, user, *len); } /* Ensure an incoming username from NSS is fully qualified. Replace the -- cgit From f0dccdca6a9da4440406f9cccd76805cad87d7e6 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Mon, 22 Sep 2008 14:51:51 +0200 Subject: [s3]winbindd: fix a comment typo Michael --- source3/winbindd/winbindd_async.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/winbindd/winbindd_async.c b/source3/winbindd/winbindd_async.c index 1481aed8e1..7500bcbe5b 100644 --- a/source3/winbindd/winbindd_async.c +++ b/source3/winbindd/winbindd_async.c @@ -366,7 +366,7 @@ static void lookupname_recv(TALLOC_CTX *mem_ctx, bool success, /******************************************************************** The lookup name call first contacts a DC in its own domain - and fallbacks to contact a DC in the forest in our domain doesn't + and fallbacks to contact a DC if the forest in our domain doesn't know the name. ********************************************************************/ -- cgit From e401ce6de79e696d8dda7b56568b1565d2e21f62 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Mon, 22 Sep 2008 10:36:32 +0200 Subject: [s3]winbindd_util: add prototype for fill_domain_username_talloc(). A talloc version of fill_domain_username(). Michael --- source3/winbindd/winbindd_proto.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source3/winbindd/winbindd_proto.h b/source3/winbindd/winbindd_proto.h index 4774bc8106..3836c46e36 100644 --- a/source3/winbindd/winbindd_proto.h +++ b/source3/winbindd/winbindd_proto.h @@ -569,6 +569,10 @@ bool parse_domain_user_talloc(TALLOC_CTX *mem_ctx, const char *domuser, void parse_add_domuser(void *buf, char *domuser, int *len); bool canonicalize_username(fstring username_inout, fstring domain, fstring user); void fill_domain_username(fstring name, const char *domain, const char *user, bool can_assume); +char *fill_domain_username_talloc(TALLOC_CTX *ctx, + const char *domain, + const char *user, + bool can_assume); const char *get_winbind_pipe_dir(void) ; char *get_winbind_priv_pipe_dir(void) ; int open_winbindd_socket(void); -- cgit From 1b9c2ccb1f1ba4d67ee0d82f4ff89b0abd62cbe2 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Mon, 22 Sep 2008 10:37:11 +0200 Subject: [s3]winbindd_util: add fill_domain_username_talloc(). A talloc version of fill_domain_username(). Michael --- source3/winbindd/winbindd_util.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/source3/winbindd/winbindd_util.c b/source3/winbindd/winbindd_util.c index b296465ed5..5b5ca41a74 100644 --- a/source3/winbindd/winbindd_util.c +++ b/source3/winbindd/winbindd_util.c @@ -1213,6 +1213,33 @@ void fill_domain_username(fstring name, const char *domain, const char *user, bo } } +/** + * talloc version of fill_domain_username() + * return NULL on talloc failure. + */ +char *fill_domain_username_talloc(TALLOC_CTX *mem_ctx, + const char *domain, + const char *user, + bool can_assume) +{ + char *tmp_user, *name; + + tmp_user = talloc_strdup(mem_ctx, user); + strlower_m(tmp_user); + + if (can_assume && assume_domain(domain)) { + name = tmp_user; + } else { + name = talloc_asprintf(mem_ctx, "%s%c%s", + domain, + *lp_winbind_separator(), + tmp_user); + TALLOC_FREE(tmp_user); + } + + return name; +} + /* * Winbindd socket accessor functions */ -- cgit From 1f8a7739ace7715b20c9b8c72732ab1ff689b552 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Sun, 21 Sep 2008 01:20:32 +0200 Subject: [s3]winbindd_rpc: add domain prefix to username in lookup_groupmem(). This makes the output of "getent group" of a domain group show the domain prefix with "security = domain". Michael --- source3/winbindd/winbindd_rpc.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/source3/winbindd/winbindd_rpc.c b/source3/winbindd/winbindd_rpc.c index df80ad8029..9fbea8e45b 100644 --- a/source3/winbindd/winbindd_rpc.c +++ b/source3/winbindd/winbindd_rpc.c @@ -854,7 +854,10 @@ static NTSTATUS lookup_groupmem(struct winbindd_domain *domain, } for (r=0; rname, + tmp_names.names[r].string, + true); (*name_types)[i+r] = tmp_types.ids[r]; } -- cgit From 49145bfefae54672c5d4cccdbb9dd33e1cd89b88 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Mon, 22 Sep 2008 10:39:37 +0200 Subject: [s3]winbindd_ads: honour "winbind use default domain" in lookup_groupmem(). This fixes the output of "getent group" when "winbind use default domain = yes" with security = ads. Michael --- source3/winbindd/winbindd_ads.c | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/source3/winbindd/winbindd_ads.c b/source3/winbindd/winbindd_ads.c index 894e7866b3..1febddf110 100644 --- a/source3/winbindd/winbindd_ads.c +++ b/source3/winbindd/winbindd_ads.c @@ -1023,10 +1023,11 @@ static NTSTATUS lookup_groupmem(struct winbindd_domain *domain, DEBUG(10,("ads: lookup_groupmem: got sid %s from " "cache\n", sid_string_dbg(&sid))); sid_copy(&(*sid_mem)[*num_names], &sid); - (*names)[*num_names] = talloc_asprintf(*names, "%s%c%s", - domain_name, - *lp_winbind_separator(), - name ); + (*names)[*num_names] = fill_domain_username_talloc( + *names, + domain_name, + name, + true); (*name_types)[*num_names] = name_type; (*num_names)++; @@ -1071,11 +1072,12 @@ static NTSTATUS lookup_groupmem(struct winbindd_domain *domain, { sid_copy(&(*sid_mem)[*num_names], &sid_mem_nocache[i]); - (*names)[*num_names] = talloc_asprintf( *names, - "%s%c%s", - domains_nocache[i], - *lp_winbind_separator(), - names_nocache[i] ); + (*names)[*num_names] = + fill_domain_username_talloc( + *names, + domains_nocache[i], + names_nocache[i], + true); (*name_types)[*num_names] = name_types_nocache[i]; (*num_names)++; } -- cgit From 4205fab500927a4248fda622e1c338b7e791617f Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Sun, 21 Sep 2008 02:06:44 +0200 Subject: [s3]winbindd_group: sanely handle NULL domain in add_member(). Michael --- source3/winbindd/winbindd_group.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/source3/winbindd/winbindd_group.c b/source3/winbindd/winbindd_group.c index 088f946877..b2bba09537 100644 --- a/source3/winbindd/winbindd_group.c +++ b/source3/winbindd/winbindd_group.c @@ -35,7 +35,11 @@ static void add_member(const char *domain, const char *user, { fstring name; - fill_domain_username(name, domain, user, True); + if (domain != NULL) { + fill_domain_username(name, domain, user, True); + } else { + fstrcpy(name, user); + } safe_strcat(name, ",", sizeof(name)-1); string_append(pp_members, name); *p_num_members += 1; -- cgit From 4432967532897cc90ce7d7b11fab6f6f88f8bfc0 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Sun, 21 Sep 2008 02:07:43 +0200 Subject: [s3]winbindd_group: don't list the domain twice when expanding internal aliases Before this, "getent group builtin\\administrators" expanded domain group members in the form DOMAIN\domain\user. Michael --- source3/winbindd/winbindd_group.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/winbindd/winbindd_group.c b/source3/winbindd/winbindd_group.c index b2bba09537..f2b6fbefb5 100644 --- a/source3/winbindd/winbindd_group.c +++ b/source3/winbindd/winbindd_group.c @@ -140,7 +140,7 @@ static void add_expanded_sid(const DOM_SID *sid, continue; } - add_member(domain->name, names[i], pp_members, p_num_members); + add_member(NULL, names[i], pp_members, p_num_members); } done: -- cgit From 05e0966d85e7b6c61c88edb4633d0dda40959f01 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 10:04:17 +0200 Subject: s3-nbt: remove old samba3 libcli/nbt copy. Guenther --- source3/libcli/nbt/libnbt.h | 353 ------------------------ source3/libcli/nbt/nbtname.c | 626 ------------------------------------------- 2 files changed, 979 deletions(-) delete mode 100644 source3/libcli/nbt/libnbt.h delete mode 100644 source3/libcli/nbt/nbtname.c diff --git a/source3/libcli/nbt/libnbt.h b/source3/libcli/nbt/libnbt.h deleted file mode 100644 index d37a17c192..0000000000 --- a/source3/libcli/nbt/libnbt.h +++ /dev/null @@ -1,353 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - a raw async NBT library - - Copyright (C) Andrew Tridgell 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 . -*/ - -#ifndef __LIBNBT_H__ -#define __LIBNBT_H__ - -#include "librpc/gen_ndr/nbt.h" -#include "librpc/ndr/libndr.h" - -/* - possible states for pending requests -*/ -enum nbt_request_state {NBT_REQUEST_SEND, - NBT_REQUEST_WAIT, - NBT_REQUEST_DONE, - NBT_REQUEST_TIMEOUT, - NBT_REQUEST_ERROR}; - -/* - a nbt name request -*/ -struct nbt_name_request { - struct nbt_name_request *next, *prev; - - enum nbt_request_state state; - - NTSTATUS status; - - /* the socket this was on */ - struct nbt_name_socket *nbtsock; - - /* where to send the request */ - struct socket_address *dest; - - /* timeout between retries */ - int timeout; - - /* how many retries to send on timeout */ - int num_retries; - - /* whether we have received a WACK */ - bool received_wack; - - /* the timeout event */ - struct timed_event *te; - - /* the name transaction id */ - uint16_t name_trn_id; - - /* is it a reply? */ - bool is_reply; - - /* the encoded request */ - DATA_BLOB encoded; - - /* shall we allow multiple replies? */ - bool allow_multiple_replies; - - unsigned int num_replies; - struct nbt_name_reply { - struct nbt_name_packet *packet; - struct socket_address *dest; - } *replies; - - /* information on what to do on completion */ - struct { - void (*fn)(struct nbt_name_request *); - void *_private; - } async; -}; - - - -/* - context structure for operations on name queries -*/ -struct nbt_name_socket { - struct socket_context *sock; - struct event_context *event_ctx; -/* - struct smb_iconv_convenience *iconv_convenience; -*/ - /* a queue of requests pending to be sent */ - struct nbt_name_request *send_queue; - - /* the fd event */ - struct fd_event *fde; - - /* mapping from name_trn_id to pending event */ - struct idr_context *idr; - - /* how many requests are waiting for a reply */ - uint16_t num_pending; - - /* what to do with incoming request packets */ - struct { - void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, - struct socket_address *); - void *_private; - } incoming; - - /* what to do with unexpected replies */ - struct { - void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, - struct socket_address *); - void *_private; - } unexpected; -}; - - -/* a simple name query */ -struct nbt_name_query { - struct { - struct nbt_name name; - const char *dest_addr; - uint16_t dest_port; - bool broadcast; - bool wins_lookup; - int timeout; /* in seconds */ - int retries; - } in; - struct { - const char *reply_from; - struct nbt_name name; - int16_t num_addrs; - const char **reply_addrs; - } out; -}; - -/* a simple name status query */ -struct nbt_name_status { - struct { - struct nbt_name name; - const char *dest_addr; - uint16_t dest_port; - int timeout; /* in seconds */ - int retries; - } in; - struct { - const char *reply_from; - struct nbt_name name; - struct nbt_rdata_status status; - } out; -}; - -/* a name registration request */ -struct nbt_name_register { - struct { - struct nbt_name name; - const char *dest_addr; - uint16_t dest_port; - const char *address; - uint16_t nb_flags; - bool register_demand; - bool broadcast; - bool multi_homed; - uint32_t ttl; - int timeout; /* in seconds */ - int retries; - } in; - struct { - const char *reply_from; - struct nbt_name name; - const char *reply_addr; - uint8_t rcode; - } out; -}; - -/* a send 3 times then demand name broadcast name registration */ -struct nbt_name_register_bcast { - struct { - struct nbt_name name; - const char *dest_addr; - uint16_t dest_port; - const char *address; - uint16_t nb_flags; - uint32_t ttl; - } in; -}; - - -/* wins name register with multiple wins servers to try and multiple - addresses to register */ -struct nbt_name_register_wins { - struct { - struct nbt_name name; - const char **wins_servers; - uint16_t wins_port; - const char **addresses; - uint16_t nb_flags; - uint32_t ttl; - } in; - struct { - const char *wins_server; - uint8_t rcode; - } out; -}; - - - -/* a name refresh request */ -struct nbt_name_refresh { - struct { - struct nbt_name name; - const char *dest_addr; - uint16_t dest_port; - const char *address; - uint16_t nb_flags; - bool broadcast; - uint32_t ttl; - int timeout; /* in seconds */ - int retries; - } in; - struct { - const char *reply_from; - struct nbt_name name; - const char *reply_addr; - uint8_t rcode; - } out; -}; - -/* wins name refresh with multiple wins servers to try and multiple - addresses to register */ -struct nbt_name_refresh_wins { - struct { - struct nbt_name name; - const char **wins_servers; - uint16_t wins_port; - const char **addresses; - uint16_t nb_flags; - uint32_t ttl; - } in; - struct { - const char *wins_server; - uint8_t rcode; - } out; -}; - - -/* a name release request */ -struct nbt_name_release { - struct { - struct nbt_name name; - const char *dest_addr; - uint16_t dest_port; - const char *address; - uint16_t nb_flags; - bool broadcast; - int timeout; /* in seconds */ - int retries; - } in; - struct { - const char *reply_from; - struct nbt_name name; - const char *reply_addr; - uint8_t rcode; - } out; -}; - -struct nbt_name_socket *nbt_name_socket_init(TALLOC_CTX *mem_ctx, - struct event_context *event_ctx); - /*, - struct smb_iconv_convenience *iconv_convenience);*/ -struct nbt_name_request *nbt_name_query_send(struct nbt_name_socket *nbtsock, - struct nbt_name_query *io); -NTSTATUS nbt_name_query_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_query *io); -NTSTATUS nbt_name_query(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_query *io); -struct nbt_name_request *nbt_name_status_send(struct nbt_name_socket *nbtsock, - struct nbt_name_status *io); -NTSTATUS nbt_name_status_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_status *io); -NTSTATUS nbt_name_status(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_status *io); - -NTSTATUS nbt_name_dup(TALLOC_CTX *mem_ctx, struct nbt_name *name, struct nbt_name *newname); -NTSTATUS nbt_name_to_blob(TALLOC_CTX *mem_ctx, DATA_BLOB *blob, struct nbt_name *name); -NTSTATUS nbt_name_from_blob(TALLOC_CTX *mem_ctx, const DATA_BLOB *blob, struct nbt_name *name); -void nbt_choose_called_name(TALLOC_CTX *mem_ctx, struct nbt_name *n, const char *name, int type); -char *nbt_name_string(TALLOC_CTX *mem_ctx, const struct nbt_name *name); -NTSTATUS nbt_name_register(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_register *io); -NTSTATUS nbt_name_refresh(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_refresh *io); -NTSTATUS nbt_name_release(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, struct nbt_name_release *io); -NTSTATUS nbt_name_register_wins(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, - struct nbt_name_register_wins *io); -NTSTATUS nbt_name_refresh_wins(struct nbt_name_socket *nbtsock, - TALLOC_CTX *mem_ctx, - struct nbt_name_refresh_wins *io); -NTSTATUS nbt_name_register_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_register *io); -struct nbt_name_request *nbt_name_register_send(struct nbt_name_socket *nbtsock, - struct nbt_name_register *io); -NTSTATUS nbt_name_release_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_release *io); - -struct nbt_name_request *nbt_name_release_send(struct nbt_name_socket *nbtsock, - struct nbt_name_release *io); - -NTSTATUS nbt_name_refresh_recv(struct nbt_name_request *req, - TALLOC_CTX *mem_ctx, struct nbt_name_refresh *io); - -NTSTATUS nbt_set_incoming_handler(struct nbt_name_socket *nbtsock, - void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, - struct socket_address *), - void *_private); -NTSTATUS nbt_name_reply_send(struct nbt_name_socket *nbtsock, - struct socket_address *dest, - struct nbt_name_packet *request); - - -NDR_SCALAR_PROTO(wrepl_nbt_name, const struct nbt_name *); -NDR_SCALAR_PROTO(nbt_string, const char *); -NDR_BUFFER_PROTO(nbt_name, struct nbt_name); -NTSTATUS nbt_rcode_to_ntstatus(uint8_t rcode); - -struct composite_context; -struct composite_context *nbt_name_register_bcast_send(struct nbt_name_socket *nbtsock, - struct nbt_name_register_bcast *io); -NTSTATUS nbt_name_register_bcast_recv(struct composite_context *c); -struct composite_context *nbt_name_register_wins_send(struct nbt_name_socket *nbtsock, - struct nbt_name_register_wins *io); -NTSTATUS nbt_name_refresh_wins_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, - struct nbt_name_refresh_wins *io); -struct composite_context *nbt_name_refresh_wins_send(struct nbt_name_socket *nbtsock, - struct nbt_name_refresh_wins *io); -NTSTATUS nbt_name_register_wins_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, - struct nbt_name_register_wins *io); - - -#endif /* __LIBNBT_H__ */ diff --git a/source3/libcli/nbt/nbtname.c b/source3/libcli/nbt/nbtname.c deleted file mode 100644 index fbb9550655..0000000000 --- a/source3/libcli/nbt/nbtname.c +++ /dev/null @@ -1,626 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - manipulate nbt name structures - - Copyright (C) Andrew Tridgell 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 . -*/ - -/* - see rfc1002 for the detailed format of compressed names -*/ - -#include "includes.h" -#include "librpc/gen_ndr/ndr_nbt.h" -#include "librpc/gen_ndr/ndr_misc.h" - -/* don't allow an unlimited number of name components */ -#define MAX_COMPONENTS 10 - -/** - print a nbt string -*/ -_PUBLIC_ void ndr_print_nbt_string(struct ndr_print *ndr, const char *name, const char *s) -{ - ndr_print_string(ndr, name, s); -} - -/* - pull one component of a nbt_string -*/ -static enum ndr_err_code ndr_pull_component(struct ndr_pull *ndr, - uint8_t **component, - uint32_t *offset, - uint32_t *max_offset) -{ - uint8_t len; - uint_t loops = 0; - while (loops < 5) { - if (*offset >= ndr->data_size) { - return ndr_pull_error(ndr, NDR_ERR_STRING, - "BAD NBT NAME component"); - } - len = ndr->data[*offset]; - if (len == 0) { - *offset += 1; - *max_offset = MAX(*max_offset, *offset); - *component = NULL; - return NDR_ERR_SUCCESS; - } - if ((len & 0xC0) == 0xC0) { - /* its a label pointer */ - if (1 + *offset >= ndr->data_size) { - return ndr_pull_error(ndr, NDR_ERR_STRING, - "BAD NBT NAME component"); - } - *max_offset = MAX(*max_offset, *offset + 2); - *offset = ((len&0x3F)<<8) | ndr->data[1 + *offset]; - *max_offset = MAX(*max_offset, *offset); - loops++; - continue; - } - if ((len & 0xC0) != 0) { - /* its a reserved length field */ - return ndr_pull_error(ndr, NDR_ERR_STRING, - "BAD NBT NAME component"); - } - if (*offset + len + 2 > ndr->data_size) { - return ndr_pull_error(ndr, NDR_ERR_STRING, - "BAD NBT NAME component"); - } - *component = (uint8_t*)talloc_strndup(ndr, (const char *)&ndr->data[1 + *offset], len); - NDR_ERR_HAVE_NO_MEMORY(*component); - *offset += len + 1; - *max_offset = MAX(*max_offset, *offset); - return NDR_ERR_SUCCESS; - } - - /* too many pointers */ - return ndr_pull_error(ndr, NDR_ERR_STRING, "BAD NBT NAME component"); -} - -/** - pull a nbt_string from the wire -*/ -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_string(struct ndr_pull *ndr, int ndr_flags, const char **s) -{ - uint32_t offset = ndr->offset; - uint32_t max_offset = offset; - unsigned num_components; - char *name; - - if (!(ndr_flags & NDR_SCALARS)) { - return NDR_ERR_SUCCESS; - } - - name = NULL; - - /* break up name into a list of components */ - for (num_components=0;num_componentsoffset = max_offset; - - return NDR_ERR_SUCCESS; -} - -/** - push a nbt string to the wire -*/ -_PUBLIC_ enum ndr_err_code ndr_push_nbt_string(struct ndr_push *ndr, int ndr_flags, const char *s) -{ - if (!(ndr_flags & NDR_SCALARS)) { - return NDR_ERR_SUCCESS; - } - - while (s && *s) { - enum ndr_err_code ndr_err; - char *compname; - size_t complen; - uint32_t offset; - - /* see if we have pushed the remaing string allready, - * if so we use a label pointer to this string - */ - ndr_err = ndr_token_retrieve_cmp_fn(&ndr->nbt_string_list, s, &offset, (comparison_fn_t)strcmp, false); - if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - uint8_t b[2]; - - if (offset > 0x3FFF) { - return ndr_push_error(ndr, NDR_ERR_STRING, - "offset for nbt string label pointer %u[%08X] > 0x00003FFF", - offset, offset); - } - - b[0] = 0xC0 | (offset>>8); - b[1] = (offset & 0xFF); - - return ndr_push_bytes(ndr, b, 2); - } - - complen = strcspn(s, "."); - - /* we need to make sure the length fits into 6 bytes */ - if (complen >= 0x3F) { - return ndr_push_error(ndr, NDR_ERR_STRING, - "component length %u[%08X] > 0x00003F", - (unsigned)complen, (unsigned)complen); - } - - compname = talloc_asprintf(ndr, "%c%*.*s", - (unsigned char)complen, - (unsigned char)complen, - (unsigned char)complen, s); - NDR_ERR_HAVE_NO_MEMORY(compname); - - /* remember the current componemt + the rest of the string - * so it can be reused later - */ - NDR_CHECK(ndr_token_store(ndr, &ndr->nbt_string_list, s, ndr->offset)); - - /* push just this component into the blob */ - NDR_CHECK(ndr_push_bytes(ndr, (const uint8_t *)compname, complen+1)); - talloc_free(compname); - - s += complen; - if (*s == '.') s++; - } - - /* if we reach the end of the string and have pushed the last component - * without using a label pointer, we need to terminate the string - */ - return ndr_push_bytes(ndr, (const uint8_t *)"", 1); -} - - -/* - decompress a 'compressed' name component - */ -static bool decompress_name(char *name, enum nbt_name_type *type) -{ - int i; - for (i=0;name[2*i];i++) { - uint8_t c1 = name[2*i]; - uint8_t c2 = name[1+(2*i)]; - if (c1 < 'A' || c1 > 'P' || - c2 < 'A' || c2 > 'P') { - return false; - } - name[i] = ((c1-'A')<<4) | (c2-'A'); - } - name[i] = 0; - if (i == 16) { - *type = (enum nbt_name_type)(name[15]); - name[15] = 0; - i--; - } else { - *type = NBT_NAME_CLIENT; - } - - /* trim trailing spaces */ - for (;i>0 && name[i-1]==' ';i--) { - name[i-1] = 0; - } - - return true; -} - - -/* - compress a name component - */ -static uint8_t *compress_name(TALLOC_CTX *mem_ctx, - const uint8_t *name, enum nbt_name_type type) -{ - uint8_t *cname; - int i; - uint8_t pad_char; - - if (strlen((const char *)name) > 15) { - return NULL; - } - - cname = talloc_array(mem_ctx, uint8_t, 33); - if (cname == NULL) return NULL; - - for (i=0;name[i];i++) { - cname[2*i] = 'A' + (name[i]>>4); - cname[1+2*i] = 'A' + (name[i]&0xF); - } - if (strcmp((const char *)name, "*") == 0) { - pad_char = 0; - } else { - pad_char = ' '; - } - for (;i<15;i++) { - cname[2*i] = 'A' + (pad_char>>4); - cname[1+2*i] = 'A' + (pad_char&0xF); - } - - pad_char = type; - cname[2*i] = 'A' + (pad_char>>4); - cname[1+2*i] = 'A' + (pad_char&0xF); - - cname[32] = 0; - return cname; -} - - -/** - pull a nbt name from the wire -*/ -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_name(struct ndr_pull *ndr, int ndr_flags, struct nbt_name *r) -{ - uint8_t *scope; - char *cname; - const char *s; - bool ok; - - if (!(ndr_flags & NDR_SCALARS)) { - return NDR_ERR_SUCCESS; - } - - NDR_CHECK(ndr_pull_nbt_string(ndr, ndr_flags, &s)); - - scope = (uint8_t *)strchr(s, '.'); - if (scope) { - *scope = 0; - r->scope = talloc_strdup(ndr->current_mem_ctx, (const char *)&scope[1]); - NDR_ERR_HAVE_NO_MEMORY(r->scope); - } else { - r->scope = NULL; - } - - cname = discard_const_p(char, s); - - /* the first component is limited to 16 bytes in the DOS charset, - which is 32 in the 'compressed' form */ - if (strlen(cname) > 32) { - return ndr_pull_error(ndr, NDR_ERR_STRING, - "NBT NAME cname > 32"); - } - - /* decompress the first component */ - ok = decompress_name(cname, &r->type); - if (!ok) { - return ndr_pull_error(ndr, NDR_ERR_STRING, - "NBT NAME failed to decompress"); - } - - r->name = talloc_strdup(ndr->current_mem_ctx, cname); - NDR_ERR_HAVE_NO_MEMORY(r->name); - - talloc_free(cname); - - return NDR_ERR_SUCCESS; -} - -/** - push a nbt name to the wire -*/ -_PUBLIC_ enum ndr_err_code ndr_push_nbt_name(struct ndr_push *ndr, int ndr_flags, const struct nbt_name *r) -{ - uint8_t *cname, *fullname; - enum ndr_err_code ndr_err; - - if (!(ndr_flags & NDR_SCALARS)) { - return NDR_ERR_SUCCESS; - } - - if (strlen(r->name) > 15) { - return ndr_push_error(ndr, NDR_ERR_STRING, - "nbt_name longer as 15 chars: %s", - r->name); - } - - cname = compress_name(ndr, (const uint8_t *)r->name, r->type); - NDR_ERR_HAVE_NO_MEMORY(cname); - - if (r->scope) { - fullname = (uint8_t *)talloc_asprintf(ndr, "%s.%s", cname, r->scope); - NDR_ERR_HAVE_NO_MEMORY(fullname); - talloc_free(cname); - } else { - fullname = cname; - } - - ndr_err = ndr_push_nbt_string(ndr, ndr_flags, (const char *)fullname); - - return ndr_err; -} - - -/** - copy a nbt name structure -*/ -_PUBLIC_ NTSTATUS nbt_name_dup(TALLOC_CTX *mem_ctx, struct nbt_name *name, struct nbt_name *newname) -{ - *newname = *name; - newname->name = talloc_strdup(mem_ctx, newname->name); - NT_STATUS_HAVE_NO_MEMORY(newname->name); - newname->scope = talloc_strdup(mem_ctx, newname->scope); - if (name->scope) { - NT_STATUS_HAVE_NO_MEMORY(newname->scope); - } - return NT_STATUS_OK; -} - -/** - push a nbt name into a blob -*/ -_PUBLIC_ NTSTATUS nbt_name_to_blob(TALLOC_CTX *mem_ctx, DATA_BLOB *blob, struct nbt_name *name) -{ - enum ndr_err_code ndr_err; - - ndr_err = ndr_push_struct_blob(blob, mem_ctx, name, (ndr_push_flags_fn_t)ndr_push_nbt_name); - if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - return ndr_map_error2ntstatus(ndr_err); - } - - return NT_STATUS_OK; -} - -/** - pull a nbt name from a blob -*/ -_PUBLIC_ NTSTATUS nbt_name_from_blob(TALLOC_CTX *mem_ctx, const DATA_BLOB *blob, struct nbt_name *name) -{ - enum ndr_err_code ndr_err; - - ndr_err = ndr_pull_struct_blob(blob, mem_ctx, name, - (ndr_pull_flags_fn_t)ndr_pull_nbt_name); - if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - return ndr_map_error2ntstatus(ndr_err); - } - - return NT_STATUS_OK; -} - - -/** - choose a name to use when calling a server in a NBT session request. - we use heuristics to see if the name we have been given is a IP - address, or a too-long name. If it is then use *SMBSERVER, or a - truncated name -*/ -_PUBLIC_ void nbt_choose_called_name(TALLOC_CTX *mem_ctx, - struct nbt_name *n, const char *name, int type) -{ - n->scope = NULL; - n->type = type; - - if ((name == NULL) || is_ipaddress(name)) { - n->name = "*SMBSERVER"; - return; - } - if (strlen(name) > 15) { - const char *p = strchr(name, '.'); - char *s; - if (p - name > 15) { - n->name = "*SMBSERVER"; - return; - } - s = talloc_strndup(mem_ctx, name, PTR_DIFF(p, name)); - n->name = talloc_strdup_upper(mem_ctx, s); - return; - } - - n->name = talloc_strdup_upper(mem_ctx, name); -} - - -/* - escape a string into a form containing only a small set of characters, - the rest is hex encoded. This is similar to URL encoding -*/ -static const char *nbt_hex_encode(TALLOC_CTX *mem_ctx, const char *s) -{ - int i, len; - char *ret; - const char *valid_chars = "_-.$@ "; -#define NBT_CHAR_ALLOW(c) (isalnum((unsigned char)c) || strchr(valid_chars, c)) - - for (len=i=0;s[i];i++,len++) { - if (!NBT_CHAR_ALLOW(s[i])) { - len += 2; - } - } - - ret = talloc_array(mem_ctx, char, len+1); - if (ret == NULL) return NULL; - - for (len=i=0;s[i];i++) { - if (NBT_CHAR_ALLOW(s[i])) { - ret[len++] = s[i]; - } else { - snprintf(&ret[len], 4, "%%%02x", (unsigned char)s[i]); - len += 3; - } - } - ret[len] = 0; - - return ret; -} - - -/** - form a string for a NBT name -*/ -_PUBLIC_ char *nbt_name_string(TALLOC_CTX *mem_ctx, const struct nbt_name *name) -{ - TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx); - char *ret; - if (name->scope) { - ret = talloc_asprintf(mem_ctx, "%s<%02x>-%s", - nbt_hex_encode(tmp_ctx, name->name), - name->type, - nbt_hex_encode(tmp_ctx, name->scope)); - } else { - ret = talloc_asprintf(mem_ctx, "%s<%02x>", - nbt_hex_encode(tmp_ctx, name->name), - name->type); - } - talloc_free(tmp_ctx); - return ret; -} - -/** - pull a nbt name, WINS Replication uses another on wire format for nbt name -*/ -_PUBLIC_ enum ndr_err_code ndr_pull_wrepl_nbt_name(struct ndr_pull *ndr, int ndr_flags, const struct nbt_name **_r) -{ - struct nbt_name *r; - uint8_t *namebuf; - uint32_t namebuf_len; - - if (!(ndr_flags & NDR_SCALARS)) { - return NDR_ERR_SUCCESS; - } - - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &namebuf_len)); - if (namebuf_len < 1 || namebuf_len > 255) { - return ndr_pull_error(ndr, NDR_ERR_ALLOC, "value out of range"); - } - NDR_PULL_ALLOC_N(ndr, namebuf, namebuf_len); - NDR_CHECK(ndr_pull_array_uint8(ndr, NDR_SCALARS, namebuf, namebuf_len)); - - NDR_PULL_ALLOC(ndr, r); - - /* oh wow, what a nasty bug in windows ... */ - if (namebuf[0] == 0x1b && namebuf_len >= 16) { - namebuf[0] = namebuf[15]; - namebuf[15] = 0x1b; - } - - if (namebuf_len < 17) { - r->type = 0x00; - - r->name = talloc_strndup(r, (char *)namebuf, namebuf_len); - if (!r->name) return ndr_pull_error(ndr, NDR_ERR_ALLOC, "out of memory"); - - r->scope= NULL; - - talloc_free(namebuf); - *_r = r; - return NDR_ERR_SUCCESS; - } - - r->type = namebuf[15]; - - namebuf[15] = '\0'; - trim_string((char *)namebuf, NULL, " "); - r->name = talloc_strdup(r, (char *)namebuf); - if (!r->name) return ndr_pull_error(ndr, NDR_ERR_ALLOC, "out of memory"); - - if (namebuf_len > 18) { - r->scope = talloc_strndup(r, (char *)(namebuf+17), namebuf_len-17); - if (!r->scope) return ndr_pull_error(ndr, NDR_ERR_ALLOC, "out of memory"); - } else { - r->scope = NULL; - } - - talloc_free(namebuf); - *_r = r; - return NDR_ERR_SUCCESS; -} - -/** - push a nbt name, WINS Replication uses another on wire format for nbt name -*/ -_PUBLIC_ enum ndr_err_code ndr_push_wrepl_nbt_name(struct ndr_push *ndr, int ndr_flags, const struct nbt_name *r) -{ - uint8_t *namebuf; - uint32_t namebuf_len; - uint32_t _name_len; - uint32_t scope_len = 0; - - if (r == NULL) { - return ndr_push_error(ndr, NDR_ERR_INVALID_POINTER, - "wrepl_nbt_name NULL pointer"); - } - - if (!(ndr_flags & NDR_SCALARS)) { - return NDR_ERR_SUCCESS; - } - - _name_len = strlen(r->name); - if (_name_len > 15) { - return ndr_push_error(ndr, NDR_ERR_STRING, - "wrepl_nbt_name longer as 15 chars: %s", - r->name); - } - - if (r->scope) { - scope_len = strlen(r->scope); - } - if (scope_len > 238) { - return ndr_push_error(ndr, NDR_ERR_STRING, - "wrepl_nbt_name scope longer as 238 chars: %s", - r->scope); - } - - namebuf = (uint8_t *)talloc_asprintf(ndr, "%-15s%c%s", - r->name, 'X', - (r->scope?r->scope:"")); - if (!namebuf) return ndr_push_error(ndr, NDR_ERR_ALLOC, "out of memory"); - - namebuf_len = strlen((char *)namebuf) + 1; - - /* - * we need to set the type here, and use a place-holder in the talloc_asprintf() - * as the type can be 0x00, and then the namebuf_len = strlen(namebuf); would give wrong results - */ - namebuf[15] = r->type; - - /* oh wow, what a nasty bug in windows ... */ - if (r->type == 0x1b) { - namebuf[15] = namebuf[0]; - namebuf[0] = 0x1b; - } - - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, namebuf_len)); - NDR_CHECK(ndr_push_array_uint8(ndr, NDR_SCALARS, namebuf, namebuf_len)); - - talloc_free(namebuf); - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_wrepl_nbt_name(struct ndr_print *ndr, const char *name, const struct nbt_name *r) -{ - char *s = nbt_name_string(ndr, r); - ndr_print_string(ndr, name, s); - talloc_free(s); -} -- cgit From 70b0c8f79a427a3227ce01bc930870771076bff7 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 23 Sep 2008 02:14:26 +0200 Subject: RPC-PAC: loop in gensec_update() untill the server side is ready metze --- source4/torture/rpc/remote_pac.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/source4/torture/rpc/remote_pac.c b/source4/torture/rpc/remote_pac.c index 25368d239a..a4111d1c3e 100644 --- a/source4/torture/rpc/remote_pac.c +++ b/source4/torture/rpc/remote_pac.c @@ -116,16 +116,12 @@ static bool test_PACVerify(struct torture_context *tctx, torture_assert_ntstatus_ok(tctx, status, "gensec_update (client) failed"); } - if (client_to_server.length == 0) { - break; - } - status = gensec_update(gensec_server_context, tmp_ctx, client_to_server, &server_to_client); if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {; torture_assert_ntstatus_ok(tctx, status, "gensec_update (server) failed"); } - if (server_to_client.length == 0) { + if (NT_STATUS_IS_OK(status)) { break; } } while (1); -- cgit From 23e31350f5ba23b0b995ff3d14bfbff50cdece6c Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 11 Sep 2008 06:40:26 +0200 Subject: ntlmssp: only give away the session key, when the authentication is done metze --- source4/auth/ntlmssp/ntlmssp.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source4/auth/ntlmssp/ntlmssp.c b/source4/auth/ntlmssp/ntlmssp.c index 0b7f0da9af..cea18c45a7 100644 --- a/source4/auth/ntlmssp/ntlmssp.c +++ b/source4/auth/ntlmssp/ntlmssp.c @@ -235,6 +235,10 @@ NTSTATUS gensec_ntlmssp_session_key(struct gensec_security *gensec_security, { struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + if (gensec_ntlmssp_state->expected_state != NTLMSSP_DONE) { + return NT_STATUS_NO_USER_SESSION_KEY; + } + if (!gensec_ntlmssp_state->session_key.data) { return NT_STATUS_NO_USER_SESSION_KEY; } -- cgit From 02cffed79dc74541ac9e9c7835573e8dfad1bb05 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 11 Sep 2008 06:46:43 +0200 Subject: gensec_gssapi: only give away the session key, when the authentication is done metze --- source4/auth/gensec/gensec_gssapi.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/source4/auth/gensec/gensec_gssapi.c b/source4/auth/gensec/gensec_gssapi.c index 1334e799ae..e791226cf6 100644 --- a/source4/auth/gensec/gensec_gssapi.c +++ b/source4/auth/gensec/gensec_gssapi.c @@ -1181,6 +1181,10 @@ static NTSTATUS gensec_gssapi_session_key(struct gensec_security *gensec_securit OM_uint32 maj_stat, min_stat; krb5_keyblock *subkey; + if (gensec_gssapi_state->sasl_state != STAGE_DONE) { + return NT_STATUS_NO_USER_SESSION_KEY; + } + if (gensec_gssapi_state->session_key.data) { *session_key = gensec_gssapi_state->session_key; return NT_STATUS_OK; @@ -1200,10 +1204,7 @@ static NTSTATUS gensec_gssapi_session_key(struct gensec_security *gensec_securit *session_key = data_blob_talloc(gensec_gssapi_state, KRB5_KEY_DATA(subkey), KRB5_KEY_LENGTH(subkey)); krb5_free_keyblock(gensec_gssapi_state->smb_krb5_context->krb5_context, subkey); - if (gensec_gssapi_state->sasl_state == STAGE_DONE) { - /* only cache in the done stage */ - gensec_gssapi_state->session_key = *session_key; - } + gensec_gssapi_state->session_key = *session_key; dump_data_pw("KRB5 Session Key:\n", session_key->data, session_key->length); return NT_STATUS_OK; -- cgit From 588af6901b019d414f4319ea9a1f40cb3d0e140e Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 11 Sep 2008 06:47:06 +0200 Subject: gensec_krb5: only give away the session key, when the authentication is done metze --- source4/auth/gensec/gensec_krb5.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source4/auth/gensec/gensec_krb5.c b/source4/auth/gensec/gensec_krb5.c index 47df2ccfcc..1f54043038 100644 --- a/source4/auth/gensec/gensec_krb5.c +++ b/source4/auth/gensec/gensec_krb5.c @@ -515,6 +515,10 @@ static NTSTATUS gensec_krb5_session_key(struct gensec_security *gensec_security, krb5_keyblock *skey; krb5_error_code err = -1; + if (gensec_krb5_state->state_position != GENSEC_KRB5_DONE) { + return NT_STATUS_NO_USER_SESSION_KEY; + } + if (gensec_krb5_state->session_key.data) { *session_key = gensec_krb5_state->session_key; return NT_STATUS_OK; -- cgit From 781d7c4c1cbd34413450f251d4078a9cb8055831 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 9 Sep 2008 17:50:30 +0200 Subject: libcli/raw: give the caller the chance to prevent the talloc_free(req) in the _recv functions metze --- source4/libcli/raw/libcliraw.h | 3 +++ source4/libcli/raw/rawrequest.c | 6 +++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/source4/libcli/raw/libcliraw.h b/source4/libcli/raw/libcliraw.h index d55b4cc42c..c9cafedd4c 100644 --- a/source4/libcli/raw/libcliraw.h +++ b/source4/libcli/raw/libcliraw.h @@ -261,6 +261,9 @@ struct smbcli_request { counter by one */ uint_t sign_single_increment:1; + /* give the caller a chance to prevent the talloc_free() in the _recv() function */ + bool do_not_free; + /* the mid of this packet - used to match replies */ uint16_t mid; diff --git a/source4/libcli/raw/rawrequest.c b/source4/libcli/raw/rawrequest.c index a0e6452748..dd9b1f3e96 100644 --- a/source4/libcli/raw/rawrequest.c +++ b/source4/libcli/raw/rawrequest.c @@ -72,7 +72,11 @@ _PUBLIC_ NTSTATUS smbcli_request_destroy(struct smbcli_request *req) } status = req->status; - talloc_free(req); + + if (!req->do_not_free) { + talloc_free(req); + } + return status; } -- cgit From e00ab641b4aeafa70d035c66baf31b965a7e5734 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 9 Sep 2008 17:54:13 +0200 Subject: libcli/raw: give the caller the chance to do the signing checks on its own. metze --- source4/libcli/raw/libcliraw.h | 3 +++ source4/libcli/raw/smb_signing.c | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/source4/libcli/raw/libcliraw.h b/source4/libcli/raw/libcliraw.h index c9cafedd4c..bd9bda0db1 100644 --- a/source4/libcli/raw/libcliraw.h +++ b/source4/libcli/raw/libcliraw.h @@ -261,6 +261,9 @@ struct smbcli_request { counter by one */ uint_t sign_single_increment:1; + /* the caller wants to do the signing check */ + bool sign_caller_checks; + /* give the caller a chance to prevent the talloc_free() in the _recv() function */ bool do_not_free; diff --git a/source4/libcli/raw/smb_signing.c b/source4/libcli/raw/smb_signing.c index 1d03686d9a..ae17dadf33 100644 --- a/source4/libcli/raw/smb_signing.c +++ b/source4/libcli/raw/smb_signing.c @@ -298,6 +298,13 @@ bool smbcli_request_check_sign_mac(struct smbcli_request *req) { bool good; + if (!req->transport->negotiate.sign_info.doing_signing && + req->sign_caller_checks) { + return true; + } + + req->sign_caller_checks = false; + switch (req->transport->negotiate.sign_info.signing_state) { case SMB_SIGNING_ENGINE_OFF: -- cgit From 7deacc615e92221548fea940b0e90fe03a3ec098 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 9 Sep 2008 17:56:11 +0200 Subject: libcli/raw: in SMB_SIGNING_ENGINE_BSRSPYL state it's ok to accept any signature Even if signing is mandatory. With NTLMSSP this happens for the session setup: request1 => BSRSPYL response1 => BSRSPYL request2 => BSRSPYL response2 => and with krb5: request1 => BSRSPYL response1 => metze --- source4/libcli/raw/smb_signing.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source4/libcli/raw/smb_signing.c b/source4/libcli/raw/smb_signing.c index ae17dadf33..c23fb16128 100644 --- a/source4/libcli/raw/smb_signing.c +++ b/source4/libcli/raw/smb_signing.c @@ -310,6 +310,8 @@ bool smbcli_request_check_sign_mac(struct smbcli_request *req) case SMB_SIGNING_ENGINE_OFF: return true; case SMB_SIGNING_ENGINE_BSRSPYL: + return true; + case SMB_SIGNING_ENGINE_ON: { if (req->in.size < (HDR_SS_FIELD + 8)) { -- cgit From 8c3d96993421e8e6a9fc5d265e4caa71acbd80c8 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 23 Sep 2008 02:29:20 +0200 Subject: libcli/raw: real signing starts at seqnumber 2 metze --- source4/libcli/raw/smb_signing.c | 1 + 1 file changed, 1 insertion(+) diff --git a/source4/libcli/raw/smb_signing.c b/source4/libcli/raw/smb_signing.c index c23fb16128..826d7dd56b 100644 --- a/source4/libcli/raw/smb_signing.c +++ b/source4/libcli/raw/smb_signing.c @@ -359,6 +359,7 @@ bool smbcli_simple_set_signing(TALLOC_CTX *mem_ctx, dump_data_pw("Started Signing with key:\n", sign_info->mac_key.data, sign_info->mac_key.length); sign_info->signing_state = SMB_SIGNING_ENGINE_ON; + sign_info->next_seq_num = 2; return true; } -- cgit From c01426ce731e2cf0b04ee3a0376e613f4970fb30 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 9 Sep 2008 18:02:07 +0200 Subject: libcli/smb_composite: for spnego session setups check the smb signature manually We need to start signing when we got NT_STATUS_OK from the server and manually check the signature of the servers response. This is needed as the response might be signed with the krb5 acceptor subkey, which comes within the server response. With NTLMSSP this happens for the session setup: request1 => BSRSPYL seqnum: 0 response1 => BSRSPYL seqnum: 0 request2 => BSRSPYL seqnum: 0 response2 => seqnum: 1 and with krb5: request1 => BSRSPYL seqnum: 0 response1 => seqnum: 1 metze --- source4/libcli/smb_composite/sesssetup.c | 80 +++++++++++++++++++++++--------- 1 file changed, 57 insertions(+), 23 deletions(-) diff --git a/source4/libcli/smb_composite/sesssetup.c b/source4/libcli/smb_composite/sesssetup.c index 11ac37e257..92b49dc3d4 100644 --- a/source4/libcli/smb_composite/sesssetup.c +++ b/source4/libcli/smb_composite/sesssetup.c @@ -35,6 +35,7 @@ struct sesssetup_state { union smb_sesssetup setup; + NTSTATUS remote_status; NTSTATUS gensec_status; struct smb_composite_sesssetup *io; struct smbcli_request *req; @@ -85,8 +86,15 @@ static void request_handler(struct smbcli_request *req) DATA_BLOB session_key = data_blob(NULL, 0); DATA_BLOB null_data_blob = data_blob(NULL, 0); NTSTATUS session_key_err, nt_status; + struct smbcli_request *check_req = NULL; - c->status = smb_raw_sesssetup_recv(req, state, &state->setup); + if (req->sign_caller_checks) { + req->do_not_free = true; + check_req = req; + } + + state->remote_status = smb_raw_sesssetup_recv(req, state, &state->setup); + c->status = state->remote_status; state->req = NULL; switch (state->setup.old.level) { @@ -102,6 +110,7 @@ static void request_handler(struct smbcli_request *req) state->io, &state->req); if (NT_STATUS_IS_OK(nt_status)) { + talloc_free(check_req); c->status = nt_status; composite_continue_smb(c, state->req, request_handler, c); return; @@ -120,6 +129,7 @@ static void request_handler(struct smbcli_request *req) state->io, &state->req); if (NT_STATUS_IS_OK(nt_status)) { + talloc_free(check_req); c->status = nt_status; composite_continue_smb(c, state->req, request_handler, c); return; @@ -138,6 +148,7 @@ static void request_handler(struct smbcli_request *req) state->io, &state->req); if (NT_STATUS_IS_OK(nt_status)) { + talloc_free(check_req); c->status = nt_status; composite_continue_smb(c, state->req, request_handler, c); return; @@ -169,12 +180,16 @@ static void request_handler(struct smbcli_request *req) state->setup.spnego.in.secblob = data_blob(NULL, 0); } - /* we need to do another round of session setup. We keep going until both sides - are happy */ - session_key_err = gensec_session_key(session->gensec, &session_key); - if (NT_STATUS_IS_OK(session_key_err)) { - set_user_session_key(session, &session_key); - smbcli_transport_simple_set_signing(session->transport, session_key, null_data_blob); + if (NT_STATUS_IS_OK(state->remote_status)) { + if (state->setup.spnego.in.secblob.length) { + c->status = NT_STATUS_INTERNAL_ERROR; + break; + } + session_key_err = gensec_session_key(session->gensec, &session_key); + if (NT_STATUS_IS_OK(session_key_err)) { + set_user_session_key(session, &session_key); + smbcli_transport_simple_set_signing(session->transport, session_key, null_data_blob); + } } if (state->setup.spnego.in.secblob.length) { @@ -186,6 +201,9 @@ static void request_handler(struct smbcli_request *req) session->vuid = state->io->out.vuid; state->req = smb_raw_sesssetup_send(session, &state->setup); session->vuid = vuid; + if (state->req) { + state->req->sign_caller_checks = true; + } composite_continue_smb(c, state->req, request_handler, c); return; } @@ -196,6 +214,15 @@ static void request_handler(struct smbcli_request *req) break; } + if (check_req) { + check_req->sign_caller_checks = false; + if (!smbcli_request_check_sign_mac(check_req)) { + c->status = NT_STATUS_ACCESS_DENIED; + } + talloc_free(check_req); + check_req = NULL; + } + /* enforce the local signing required flag */ if (NT_STATUS_IS_OK(c->status) && !cli_credentials_is_anonymous(state->io->in.credentials)) { if (!session->transport->negotiate.sign_info.doing_signing @@ -222,11 +249,14 @@ static NTSTATUS session_setup_nt1(struct composite_context *c, struct smb_composite_sesssetup *io, struct smbcli_request **req) { - NTSTATUS nt_status; + NTSTATUS nt_status = NT_STATUS_INTERNAL_ERROR; struct sesssetup_state *state = talloc_get_type(c->private_data, struct sesssetup_state); DATA_BLOB names_blob = NTLMv2_generate_names_blob(state, lp_iconv_convenience(global_loadparm), session->transport->socket->hostname, lp_workgroup(global_loadparm)); - DATA_BLOB session_key; + DATA_BLOB session_key = data_blob(NULL, 0); int flags = CLI_CRED_NTLM_AUTH; + + smbcli_temp_set_signing(session->transport); + if (session->options.lanman_auth) { flags |= CLI_CRED_LANMAN_AUTH; } @@ -258,12 +288,6 @@ static NTSTATUS session_setup_nt1(struct composite_context *c, &state->setup.nt1.in.password2, NULL, &session_key); NT_STATUS_NOT_OK_RETURN(nt_status); - - smbcli_transport_simple_set_signing(session->transport, session_key, - state->setup.nt1.in.password2); - set_user_session_key(session, &session_key); - - data_blob_free(&session_key); } else if (session->options.plaintext_auth) { const char *password = cli_credentials_get_password(io->in.credentials); state->setup.nt1.in.password1 = data_blob_talloc(state, password, strlen(password)); @@ -277,6 +301,15 @@ static NTSTATUS session_setup_nt1(struct composite_context *c, if (!*req) { return NT_STATUS_NO_MEMORY; } + + if (NT_STATUS_IS_OK(nt_status)) { + smbcli_transport_simple_set_signing(session->transport, session_key, + state->setup.nt1.in.password2); + set_user_session_key(session, &session_key); + + data_blob_free(&session_key); + } + return (*req)->status; } @@ -350,9 +383,7 @@ static NTSTATUS session_setup_spnego(struct composite_context *c, struct smbcli_request **req) { struct sesssetup_state *state = talloc_get_type(c->private_data, struct sesssetup_state); - NTSTATUS status, session_key_err; - DATA_BLOB session_key = data_blob(NULL, 0); - DATA_BLOB null_data_blob = data_blob(NULL, 0); + NTSTATUS status; const char *chosen_oid = NULL; state->setup.spnego.level = RAW_SESSSETUP_SPNEGO; @@ -440,15 +471,18 @@ static NTSTATUS session_setup_spnego(struct composite_context *c, } state->gensec_status = status; - session_key_err = gensec_session_key(session->gensec, &session_key); - if (NT_STATUS_IS_OK(session_key_err)) { - smbcli_transport_simple_set_signing(session->transport, session_key, null_data_blob); - } - *req = smb_raw_sesssetup_send(session, &state->setup); if (!*req) { return NT_STATUS_NO_MEMORY; } + + /* + * we need to check the signature ourself + * as the session key might be the acceptor subkey + * which comes within the response itself + */ + (*req)->sign_caller_checks = true; + return (*req)->status; } -- cgit From 171349bc21cc727685abb5ed836d62f4ae80b496 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 23 Sep 2008 02:30:15 +0200 Subject: s4:smb_server: remove the bogus smbsrv_signing_restart() Real signing always starts with seqnumber 2, and once signing is on the session key never change anymore for the complete smb connection. metze --- source4/smb_server/smb/sesssetup.c | 19 ++----------------- source4/smb_server/smb/signing.c | 24 ------------------------ 2 files changed, 2 insertions(+), 41 deletions(-) diff --git a/source4/smb_server/smb/sesssetup.c b/source4/smb_server/smb/sesssetup.c index f45cbf1756..a12bbd5cec 100644 --- a/source4/smb_server/smb/sesssetup.c +++ b/source4/smb_server/smb/sesssetup.c @@ -193,16 +193,6 @@ static void sesssetup_nt1_send(struct auth_check_password_request *areq, goto done; } - /* Force check of the request packet, now we know the session key */ - smbsrv_signing_check_incoming(req); -/* TODO: why don't we check the result here? */ - - /* Unfortunetly win2k3 as a client doesn't sign the request - * packet here, so we have to force signing to start again */ - - smbsrv_signing_restart(req->smb_conn, &session_info->session_key, &sess->nt1.in.password2, - session_info->server_info->authenticated); - done: status = NT_STATUS_OK; failed: @@ -321,13 +311,8 @@ static void sesssetup_spnego_send(struct gensec_update_request *greq, void *priv if (!NT_STATUS_IS_OK(status)) goto failed; skey_status = gensec_session_key(smb_sess->gensec_ctx, &session_key); - if (NT_STATUS_IS_OK(skey_status) && - smbsrv_setup_signing(req->smb_conn, &session_key, NULL)) { - /* Force check of the request packet, now we know the session key */ - smbsrv_signing_check_incoming(req); - - smbsrv_signing_restart(req->smb_conn, &session_key, NULL, - session_info->server_info->authenticated); + if (NT_STATUS_IS_OK(skey_status)) { + smbsrv_setup_signing(req->smb_conn, &session_key, NULL); } /* Ensure this is marked as a 'real' vuid, not one diff --git a/source4/smb_server/smb/signing.c b/source4/smb_server/smb/signing.c index 21dc99b165..0b5cf56fdb 100644 --- a/source4/smb_server/smb/signing.c +++ b/source4/smb_server/smb/signing.c @@ -75,30 +75,6 @@ bool smbsrv_setup_signing(struct smbsrv_connection *smb_conn, &smb_conn->signing, session_key, response); } -void smbsrv_signing_restart(struct smbsrv_connection *smb_conn, - DATA_BLOB *session_key, - DATA_BLOB *response, - bool authenticated_session) -{ - if (!smb_conn->signing.seen_valid) { - DEBUG(5, ("Client did not send a valid signature on " - "SPNEGO session setup - ignored, expect good next time\n")); - /* force things back on (most clients do not sign this packet)... */ - smbsrv_setup_signing(smb_conn, session_key, response); - smb_conn->signing.next_seq_num = 2; - - /* If mandetory_signing is set, and this was an authenticated logon, then force on */ - if (smb_conn->signing.mandatory_signing && authenticated_session) { - DEBUG(5, ("Configured for mandatory signing, 'good packet seen' forced on\n")); - /* if this is mandatory, then - * pretend we have seen a - * valid packet, so we don't - * turn it off */ - smb_conn->signing.seen_valid = true; - } - } -} - bool smbsrv_init_signing(struct smbsrv_connection *smb_conn) { smb_conn->signing.mac_key = data_blob(NULL, 0); -- cgit From 61a38d91803cb3c1bf1b09915f8d97792f48966b Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 9 Sep 2008 21:10:08 +0200 Subject: selftest: test some smb signing combinations against the member server metze --- source4/selftest/samba4_tests.sh | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/source4/selftest/samba4_tests.sh b/source4/selftest/samba4_tests.sh index bdebddf260..36d52fff5a 100755 --- a/source4/selftest/samba4_tests.sh +++ b/source4/selftest/samba4_tests.sh @@ -292,6 +292,46 @@ plantest "rpc.samr.users against member server with local creds" member $VALGRIN plantest "rpc.samr.passwords against member server with local creds" member $VALGRIND $smb4torture ncacn_np:"\$NETBIOSNAME" -U"\$NETBIOSNAME/\$USERNAME"%"\$PASSWORD" "RPC-SAMR-PASSWORDS" "$*" plantest "blackbox.smbclient against member server with local creds" member $samba4srcdir/client/tests/test_smbclient.sh "\$NETBIOSNAME" "\$USERNAME" "\$PASSWORD" "\$NETBIOSNAME" "$PREFIX" +# Tests SMB signing + +for mech in \ + "-k no" \ + "-k no --option=usespnego=no" \ + "-k no --option=gensec:spengo=no" \ + "-k yes" \ + "-k yes --option=gensec:fake_gssapi_krb5=yes --option=gensec:gssapi_krb5=no"; do + for signing in \ + "--signing=on" \ + "--signing=required"; do + + signoptions="$mech $signing" + name="smb.signing on with $signoptions" + plantest "$name" dc $VALGRIND $smb4torture //"\$NETBIOSNAME"/tmp $signoptions -U"\$USERNAME"%"\$PASSWORD" BASE-XCOPY "$*" + done +done + +for mech in \ + "-k no" \ + "-k no --option=usespnego=no" \ + "-k no --option=gensec:spengo=no" \ + "-k yes" \ + "-k yes --option=gensec:fake_gssapi_krb5=yes --option=gensec:gssapi_krb5=no"; do + signoptions="$mech --signing=off" + name="smb.signing on with $signoptions" + plantest "$name domain-creds" member $VALGRIND $smb4torture //"\$NETBIOSNAME"/tmp $signoptions -U"\$DC_USERNAME"%"\$DC_PASSWORD" BASE-XCOPY "$*" +done +for mech in \ + "-k no" \ + "-k no --option=usespnego=no" \ + "-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 "$*" +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 "$*" + NBT_TESTS=`$smb4torture --list | grep "^NBT-" | xargs` for t in $NBT_TESTS; do -- cgit From 353aaf26c5f71d9a94e799a1c1e37449211e7a87 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 9 Sep 2008 21:15:54 +0200 Subject: selftest: run smb signing tests as part of make quicktest metze --- source4/samba4-quick | 1 + 1 file changed, 1 insertion(+) diff --git a/source4/samba4-quick b/source4/samba4-quick index 3627a87bbe..7bea619f18 100644 --- a/source4/samba4-quick +++ b/source4/samba4-quick @@ -35,3 +35,4 @@ rpc.altercontext rpc.join rpc.handles rpc.echo +smb.signing -- cgit From 1c2e6978b89551828b66c348be361ce9a2b8ddb4 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 23 Sep 2008 11:17:43 -0700 Subject: fixed problem with ACLs with an empty DACL list --- source4/libcli/security/access_check.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/source4/libcli/security/access_check.c b/source4/libcli/security/access_check.c index e2ede05545..d5a0a13445 100644 --- a/source4/libcli/security/access_check.c +++ b/source4/libcli/security/access_check.c @@ -38,6 +38,10 @@ static uint32_t access_check_max_allowed(const struct security_descriptor *sd, granted |= SEC_STD_DELETE; } + if (sd->dacl == NULL) { + return granted & ~denied; + } + for (i = 0;idacl->num_aces; i++) { struct security_ace *ace = &sd->dacl->aces[i]; @@ -101,10 +105,14 @@ NTSTATUS sec_access_check(const struct security_descriptor *sd, return NT_STATUS_OK; } - /* empty dacl denies access */ +#if 0 + /* tridge: previously we had empty dacl denying access, but + that can lead to undeletable directories, where + nobody can change the ACL on a directory */ if (sd->dacl == NULL || sd->dacl->num_aces == 0) { return NT_STATUS_ACCESS_DENIED; } +#endif /* the owner always gets SEC_STD_WRITE_DAC, SEC_STD_READ_CONTROL and SEC_STD_DELETE */ if ((bits_remaining & (SEC_STD_WRITE_DAC|SEC_STD_READ_CONTROL|SEC_STD_DELETE)) && @@ -116,6 +124,10 @@ NTSTATUS sec_access_check(const struct security_descriptor *sd, bits_remaining &= ~SEC_STD_DELETE; } + if (sd->dacl == NULL) { + goto done; + } + /* check each ace in turn. */ for (i=0; bits_remaining && i < sd->dacl->num_aces; i++) { struct security_ace *ace = &sd->dacl->aces[i]; @@ -143,6 +155,7 @@ NTSTATUS sec_access_check(const struct security_descriptor *sd, } } +done: if (bits_remaining != 0) { return NT_STATUS_ACCESS_DENIED; } -- cgit From 5477e1cbf90e3814713653e86af5e1d14518bc9c Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 23 Sep 2008 21:06:41 +0200 Subject: s4:lib/charset: add missing prototype of talloc_strdup_upper() metze --- source4/lib/charset/charset.h | 1 + 1 file changed, 1 insertion(+) diff --git a/source4/lib/charset/charset.h b/source4/lib/charset/charset.h index c49745cd7f..d4dae4cdad 100644 --- a/source4/lib/charset/charset.h +++ b/source4/lib/charset/charset.h @@ -97,6 +97,7 @@ size_t count_chars_w(const char *s, char c); void strupper_m(char *s); void strlower_m(char *s); char *strupper_talloc(TALLOC_CTX *ctx, const char *src); +char *talloc_strdup_upper(TALLOC_CTX *ctx, const char *src); char *strupper_talloc_n(TALLOC_CTX *ctx, const char *src, size_t n); char *strlower_talloc(TALLOC_CTX *ctx, const char *src); bool strhasupper(const char *string); -- cgit From 1f8fe94ff3a928063c91ded4571751da74d2c321 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Tue, 23 Sep 2008 22:44:21 +0200 Subject: S3 puts smb.conf and lmhosts in lib/, s4 into etc/ --- source4/dynconfig/config.mk | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source4/dynconfig/config.mk b/source4/dynconfig/config.mk index b10018384f..c0ef7f6e99 100644 --- a/source4/dynconfig/config.mk +++ b/source4/dynconfig/config.mk @@ -5,12 +5,12 @@ DYNCONFIG_OBJ_FILES = $(dynconfigsrcdir)/dynconfig.o # set these to where to find various files # These can be overridden by command line switches (see smbd(8)) # or in smb.conf (see smb.conf(5)) -CONFIGFILE = $(sysconfdir)/smb.conf +CONFIG4FILE = $(sysconfdir)/smb.conf PKGCONFIGDIR = $(libdir)/pkgconfig -LMHOSTSFILE = $(sysconfdir)/lmhosts +LMHOSTSFILE4 = $(sysconfdir)/lmhosts -$(dynconfigsrcdir)/dynconfig.o: CFLAGS+=-DCONFIGFILE=\"$(CONFIGFILE)\" -DBINDIR=\"$(bindir)\" \ - -DLMHOSTSFILE=\"$(LMHOSTSFILE)\" \ +$(dynconfigsrcdir)/dynconfig.o: CFLAGS+=-DCONFIGFILE=\"$(CONFIG4FILE)\" -DBINDIR=\"$(bindir)\" \ + -DLMHOSTSFILE=\"$(LMHOSTSFILE4)\" \ -DLOCKDIR=\"$(lockdir)\" -DPIDDIR=\"$(piddir)\" -DDATADIR=\"$(datadir)\" \ -DLOGFILEBASE=\"$(logfilebase)\" \ -DCONFIGDIR=\"$(sysconfdir)\" -DNCALRPCDIR=\"$(NCALRPCDIR)\" \ -- cgit From 8bd302ab226785cfe7f518a76a67ec74e20de84f Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 22:24:46 +0200 Subject: s3-build: let ctags/etags start from the toplevel dir. Guenther --- source3/Makefile.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source3/Makefile.in b/source3/Makefile.in index 94d8d50da8..97095fcadd 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -2649,10 +2649,10 @@ include/build_env.h: script/build_env.sh proto:: etags:: - etags `find $(srcdir) -name "*.[ch]"` + etags `find $(srcdir)/.. -name "*.[ch]"` ctags:: - ctags `find $(srcdir) -name "*.[ch]"` + ctags `find $(srcdir)/.. -name "*.[ch]"` realclean:: clean -rm -f config.log bin/.dummy script/findsmb script/gen-8bit-gap.sh -- cgit From 9d541f314fd5af59c9c4745e7f61074bce3a9f2b Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 22:48:57 +0200 Subject: s4-libcli: move nbt/netlogon helper functions up one level. Guenther --- libcli/ndr_netlogon.c | 210 +++++++++++++++++++++++++++++++++++++ libcli/netlogon.c | 239 ++++++++++++++++++++++++++++++++++++++++++ libcli/netlogon.h | 54 ++++++++++ source4/libcli/ndr_netlogon.c | 209 ------------------------------------ source4/libcli/netlogon.c | 239 ------------------------------------------ source4/libcli/netlogon.h | 54 ---------- 6 files changed, 503 insertions(+), 502 deletions(-) create mode 100644 libcli/ndr_netlogon.c create mode 100644 libcli/netlogon.c create mode 100644 libcli/netlogon.h delete mode 100644 source4/libcli/ndr_netlogon.c delete mode 100644 source4/libcli/netlogon.c delete mode 100644 source4/libcli/netlogon.h diff --git a/libcli/ndr_netlogon.c b/libcli/ndr_netlogon.c new file mode 100644 index 0000000000..ffc075fab2 --- /dev/null +++ b/libcli/ndr_netlogon.c @@ -0,0 +1,210 @@ +/* + Unix SMB/CIFS implementation. + + CLDAP server structures + + Copyright (C) Andrew Bartlett 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 . +*/ + +/* parser auto-generated by pidl, then hand-modified by abartlet */ + +#include "includes.h" +#include "../libcli/netlogon.h" + +/* Manually modified to handle the dom_sid being optional based on if it is present or all zero */ +enum ndr_err_code ndr_push_NETLOGON_SAM_LOGON_REQUEST(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_SAM_LOGON_REQUEST *r) +{ + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_push_align(ndr, 4)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->request_count)); + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->computer_name)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->user_name)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->mailslot_name)); + ndr->flags = _flags_save_string; + } + NDR_CHECK(ndr_push_samr_AcctFlags(ndr, NDR_SCALARS, r->acct_control)); + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, ndr_size_dom_sid0(&r->sid, ndr->flags))); + if (ndr_size_dom_sid0(&r->sid, ndr->flags)) { + struct ndr_push *_ndr_sid; + uint32_t _flags_save_DATA_BLOB = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN4); + NDR_CHECK(ndr_push_DATA_BLOB(ndr, NDR_SCALARS, r->_pad)); + ndr->flags = _flags_save_DATA_BLOB; + NDR_CHECK(ndr_push_subcontext_start(ndr, &_ndr_sid, 0, ndr_size_dom_sid0(&r->sid, ndr->flags))); + NDR_CHECK(ndr_push_dom_sid0(_ndr_sid, NDR_SCALARS|NDR_BUFFERS, &r->sid)); + NDR_CHECK(ndr_push_subcontext_end(ndr, _ndr_sid, 0, ndr_size_dom_sid0(&r->sid, ndr->flags))); + } + NDR_CHECK(ndr_push_netlogon_nt_version_flags(ndr, NDR_SCALARS, r->nt_version)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); + } + if (ndr_flags & NDR_BUFFERS) { + } + return NDR_ERR_SUCCESS; +} + +/* Manually modified to handle the dom_sid being optional based on if it is present (size is non-zero) or not */ +enum ndr_err_code ndr_pull_NETLOGON_SAM_LOGON_REQUEST(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_SAM_LOGON_REQUEST *r) +{ + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_pull_align(ndr, 4)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->request_count)); + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->computer_name)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->user_name)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->mailslot_name)); + ndr->flags = _flags_save_string; + } + NDR_CHECK(ndr_pull_samr_AcctFlags(ndr, NDR_SCALARS, &r->acct_control)); + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->sid_size)); + if (r->sid_size) { + uint32_t _flags_save_DATA_BLOB = ndr->flags; + struct ndr_pull *_ndr_sid; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN4); + NDR_CHECK(ndr_pull_DATA_BLOB(ndr, NDR_SCALARS, &r->_pad)); + ndr->flags = _flags_save_DATA_BLOB; + NDR_CHECK(ndr_pull_subcontext_start(ndr, &_ndr_sid, 0, r->sid_size)); + NDR_CHECK(ndr_pull_dom_sid0(_ndr_sid, NDR_SCALARS|NDR_BUFFERS, &r->sid)); + NDR_CHECK(ndr_pull_subcontext_end(ndr, _ndr_sid, 0, r->sid_size)); + } else { + ZERO_STRUCT(r->sid); + } + NDR_CHECK(ndr_pull_netlogon_nt_version_flags(ndr, NDR_SCALARS, &r->nt_version)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); + } + if (ndr_flags & NDR_BUFFERS) { + } + return NDR_ERR_SUCCESS; +} + +/* Manually modified to only push some parts of the structure if certain flags are set */ +enum ndr_err_code ndr_push_NETLOGON_SAM_LOGON_RESPONSE_EX_with_flags(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_SAM_LOGON_RESPONSE_EX *r) +{ + { + uint32_t _flags_save_STRUCT = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_push_align(ndr, 4)); + NDR_CHECK(ndr_push_netlogon_command(ndr, NDR_SCALARS, r->command)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->sbz)); + NDR_CHECK(ndr_push_nbt_server_type(ndr, NDR_SCALARS, r->server_type)); + NDR_CHECK(ndr_push_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->forest)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->dns_domain)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_dns_name)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->domain)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_name)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->user_name)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->server_site)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->client_site)); + if (r->nt_version & NETLOGON_NT_VERSION_5EX_WITH_IP) { + NDR_CHECK(ndr_push_uint8(ndr, NDR_SCALARS, ndr_size_nbt_sockaddr(&r->sockaddr, ndr->flags))); + { + struct ndr_push *_ndr_sockaddr; + NDR_CHECK(ndr_push_subcontext_start(ndr, &_ndr_sockaddr, 0, ndr_size_nbt_sockaddr(&r->sockaddr, ndr->flags))); + NDR_CHECK(ndr_push_nbt_sockaddr(_ndr_sockaddr, NDR_SCALARS|NDR_BUFFERS, &r->sockaddr)); + NDR_CHECK(ndr_push_subcontext_end(ndr, _ndr_sockaddr, 0, ndr_size_nbt_sockaddr(&r->sockaddr, ndr->flags))); + } + } + if (r->nt_version & NETLOGON_NT_VERSION_WITH_CLOSEST_SITE) { + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->next_closest_site)); + } + NDR_CHECK(ndr_push_netlogon_nt_version_flags(ndr, NDR_SCALARS, r->nt_version)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); + } + if (ndr_flags & NDR_BUFFERS) { + NDR_CHECK(ndr_push_GUID(ndr, NDR_BUFFERS, &r->domain_uuid)); + } + ndr->flags = _flags_save_STRUCT; + } + return NDR_ERR_SUCCESS; +} + +/* Manually modified to only pull some parts of the structure if certain flags provided */ +enum ndr_err_code ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_EX_with_flags(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_SAM_LOGON_RESPONSE_EX *r, + uint32_t nt_version_flags) +{ + { + uint32_t _flags_save_STRUCT = ndr->flags; + ZERO_STRUCTP(r); + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_pull_align(ndr, 4)); + NDR_CHECK(ndr_pull_netlogon_command(ndr, NDR_SCALARS, &r->command)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->sbz)); + NDR_CHECK(ndr_pull_nbt_server_type(ndr, NDR_SCALARS, &r->server_type)); + NDR_CHECK(ndr_pull_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->forest)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->dns_domain)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_dns_name)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->domain)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_name)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->user_name)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->server_site)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->client_site)); + if (nt_version_flags & NETLOGON_NT_VERSION_5EX_WITH_IP) { + NDR_CHECK(ndr_pull_uint8(ndr, NDR_SCALARS, &r->sockaddr_size)); + { + struct ndr_pull *_ndr_sockaddr; + NDR_CHECK(ndr_pull_subcontext_start(ndr, &_ndr_sockaddr, 0, r->sockaddr_size)); + NDR_CHECK(ndr_pull_nbt_sockaddr(_ndr_sockaddr, NDR_SCALARS|NDR_BUFFERS, &r->sockaddr)); + NDR_CHECK(ndr_pull_subcontext_end(ndr, _ndr_sockaddr, 0, r->sockaddr_size)); + } + } + if (nt_version_flags & NETLOGON_NT_VERSION_WITH_CLOSEST_SITE) { + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->next_closest_site)); + } + NDR_CHECK(ndr_pull_netlogon_nt_version_flags(ndr, NDR_SCALARS, &r->nt_version)); + if (r->nt_version != nt_version_flags) { + return NDR_ERR_VALIDATE; + } + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); + } + if (ndr_flags & NDR_BUFFERS) { + NDR_CHECK(ndr_pull_GUID(ndr, NDR_BUFFERS, &r->domain_uuid)); + } + ndr->flags = _flags_save_STRUCT; + } + return NDR_ERR_SUCCESS; +} diff --git a/libcli/netlogon.c b/libcli/netlogon.c new file mode 100644 index 0000000000..47d665cfa1 --- /dev/null +++ b/libcli/netlogon.c @@ -0,0 +1,239 @@ +/* + Unix SMB/CIFS implementation. + + CLDAP server structures + + Copyright (C) Andrew Bartlett 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 . +*/ + +#include "includes.h" +#include "../libcli/netlogon.h" + +NTSTATUS push_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct netlogon_samlogon_response *response) +{ + enum ndr_err_code ndr_err; + if (response->ntver == NETLOGON_NT_VERSION_1) { + ndr_err = ndr_push_struct_blob(data, mem_ctx, + iconv_convenience, + &response->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, + (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, + (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)); + return NT_STATUS_INVALID_PARAMETER; + } + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + DEBUG(2,("failed to push netlogon response of type 0x%02x\n", + response->ntver)); + return ndr_map_error2ntstatus(ndr_err); + } + return NT_STATUS_OK; +} + +NTSTATUS pull_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct netlogon_samlogon_response *response) +{ + uint32_t ntver; + enum ndr_err_code ndr_err; + + if (data->length < 8) { + return NT_STATUS_BUFFER_TOO_SMALL; + } + + /* lmnttoken */ + if (SVAL(data->data, data->length - 4) != 0xffff) { + return NT_STATUS_INVALID_NETWORK_RESPONSE; + } + /* lm20token */ + if (SVAL(data->data, data->length - 2) != 0xffff) { + return NT_STATUS_INVALID_NETWORK_RESPONSE; + } + + ntver = IVAL(data->data, data->length - 8); + + if (ntver == NETLOGON_NT_VERSION_1) { + ndr_err = ndr_pull_struct_blob_all(data, mem_ctx, + iconv_convenience, + &response->nt4, + (ndr_pull_flags_fn_t)ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_NT40); + response->ntver = NETLOGON_NT_VERSION_1; + } else if (ntver & NETLOGON_NT_VERSION_5EX) { + struct ndr_pull *ndr; + ndr = ndr_pull_init_blob(data, mem_ctx, iconv_convenience); + 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); + if (ndr->offset < ndr->data_size) { + ndr_err = ndr_pull_error(ndr, NDR_ERR_UNREAD_BYTES, + "not all bytes consumed ofs[%u] size[%u]", + ndr->offset, ndr->data_size); + } + response->ntver = NETLOGON_NT_VERSION_5EX; + + } else if (ntver & NETLOGON_NT_VERSION_5) { + ndr_err = ndr_pull_struct_blob_all(data, mem_ctx, + iconv_convenience, + &response->nt5, + (ndr_pull_flags_fn_t)ndr_pull_NETLOGON_SAM_LOGON_RESPONSE); + response->ntver = NETLOGON_NT_VERSION_5; + } else { + DEBUG(2,("failed to parse netlogon response of type 0x%02x - unknown response type\n", + ntver)); + dump_data(10, data->data, data->length); + return NT_STATUS_INVALID_NETWORK_RESPONSE; + } + + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + DEBUG(2,("failed to parse netlogon response of type 0x%02x\n", + ntver)); + dump_data(10, data->data, data->length); + return ndr_map_error2ntstatus(ndr_err); + } + return NT_STATUS_OK; +} + +void map_netlogon_samlogon_response(struct netlogon_samlogon_response *response) +{ + struct NETLOGON_SAM_LOGON_RESPONSE_EX response_5_ex; + switch (response->ntver) { + case NETLOGON_NT_VERSION_5EX: + 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->ntver = NETLOGON_NT_VERSION_5EX; + response->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->ntver = NETLOGON_NT_VERSION_5EX; + response->nt5_ex = response_5_ex; + break; + } + return; +} + +NTSTATUS push_nbt_netlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct nbt_netlogon_response *response) +{ + NTSTATUS status = NT_STATUS_INVALID_NETWORK_RESPONSE; + 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_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); + DEBUG(0,("Failed to parse netlogon packet of length %d: %s\n", + (int)data->length, nt_errstr(status))); + if (DEBUGLVL(10)) { + file_save("netlogon.dat", data->data, data->length); + } + return status; + } + status = NT_STATUS_OK; + break; + case NETLOGON_SAMLOGON: + status = push_netlogon_samlogon_response(data, mem_ctx, iconv_convenience, &response->samlogon); + break; + } + return status; +} + + +NTSTATUS pull_nbt_netlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct nbt_netlogon_response *response) +{ + NTSTATUS status = NT_STATUS_INVALID_NETWORK_RESPONSE; + enum netlogon_command command; + enum ndr_err_code ndr_err; + if (data->length < 4) { + return NT_STATUS_INVALID_NETWORK_RESPONSE; + } + + command = SVAL(data->data, 0); + + switch (command) { + case NETLOGON_RESPONSE_FROM_PDC: + ndr_err = ndr_pull_struct_blob_all(data, mem_ctx, iconv_convenience, &response->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); + DEBUG(0,("Failed to parse netlogon packet of length %d: %s\n", + (int)data->length, nt_errstr(status))); + if (DEBUGLVL(10)) { + file_save("netlogon.dat", data->data, data->length); + } + return status; + } + status = NT_STATUS_OK; + response->response_type = NETLOGON_GET_PDC; + break; + case LOGON_SAM_LOGON_RESPONSE: + case LOGON_SAM_LOGON_PAUSE_RESPONSE: + case LOGON_SAM_LOGON_USER_UNKNOWN: + 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); + response->response_type = NETLOGON_SAMLOGON; + break; + + /* These levels are queries, not responses */ + case LOGON_PRIMARY_QUERY: + case NETLOGON_ANNOUNCE_UAS: + case LOGON_SAM_LOGON_REQUEST: + status = NT_STATUS_INVALID_NETWORK_RESPONSE; + } + + return status; + +} diff --git a/libcli/netlogon.h b/libcli/netlogon.h new file mode 100644 index 0000000000..8bd9d0d90a --- /dev/null +++ b/libcli/netlogon.h @@ -0,0 +1,54 @@ +/* + Unix SMB/CIFS implementation. + + CLDAP server structures + + Copyright (C) Andrew Bartlett 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 . +*/ + +#ifndef __LIBCLI_NETLOGON_H__ +#define __LIBCLI_NETLOGON_H__ + +#include "librpc/gen_ndr/ndr_nbt.h" + +#include "librpc/gen_ndr/ndr_misc.h" +#include "librpc/gen_ndr/ndr_security.h" +#include "librpc/gen_ndr/ndr_svcctl.h" +#include "librpc/gen_ndr/ndr_samr.h" + +struct netlogon_samlogon_response +{ + uint32_t ntver; + union { + struct NETLOGON_SAM_LOGON_RESPONSE_NT40 nt4; + struct NETLOGON_SAM_LOGON_RESPONSE nt5; + struct NETLOGON_SAM_LOGON_RESPONSE_EX nt5_ex; + }; + +}; + +struct nbt_netlogon_response +{ + enum {NETLOGON_GET_PDC, NETLOGON_SAMLOGON} response_type; + union { + struct nbt_netlogon_response_from_pdc get_pdc; + struct netlogon_samlogon_response samlogon; + }; +}; + +#include "../libcli/netlogon_proto.h" +#include "../libcli/ndr_netlogon_proto.h" +#endif /* __CLDAP_SERVER_PROTO_H__ */ diff --git a/source4/libcli/ndr_netlogon.c b/source4/libcli/ndr_netlogon.c deleted file mode 100644 index 504b3b02a7..0000000000 --- a/source4/libcli/ndr_netlogon.c +++ /dev/null @@ -1,209 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - CLDAP server structures - - Copyright (C) Andrew Bartlett 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 . -*/ - -/* parser auto-generated by pidl, then hand-modified by abartlet */ - -#include "includes.h" -#include "libcli/netlogon.h" -/* Manually modified to handle the dom_sid being optional based on if it is present or all zero */ -enum ndr_err_code ndr_push_NETLOGON_SAM_LOGON_REQUEST(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_SAM_LOGON_REQUEST *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->request_count)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->computer_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->user_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->mailslot_name)); - ndr->flags = _flags_save_string; - } - NDR_CHECK(ndr_push_samr_AcctFlags(ndr, NDR_SCALARS, r->acct_control)); - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, ndr_size_dom_sid0(&r->sid, ndr->flags))); - if (ndr_size_dom_sid0(&r->sid, ndr->flags)) { - struct ndr_push *_ndr_sid; - uint32_t _flags_save_DATA_BLOB = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN4); - NDR_CHECK(ndr_push_DATA_BLOB(ndr, NDR_SCALARS, r->_pad)); - ndr->flags = _flags_save_DATA_BLOB; - NDR_CHECK(ndr_push_subcontext_start(ndr, &_ndr_sid, 0, ndr_size_dom_sid0(&r->sid, ndr->flags))); - NDR_CHECK(ndr_push_dom_sid0(_ndr_sid, NDR_SCALARS|NDR_BUFFERS, &r->sid)); - NDR_CHECK(ndr_push_subcontext_end(ndr, _ndr_sid, 0, ndr_size_dom_sid0(&r->sid, ndr->flags))); - } - NDR_CHECK(ndr_push_netlogon_nt_version_flags(ndr, NDR_SCALARS, r->nt_version)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -/* Manually modified to handle the dom_sid being optional based on if it is present (size is non-zero) or not */ -enum ndr_err_code ndr_pull_NETLOGON_SAM_LOGON_REQUEST(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_SAM_LOGON_REQUEST *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->request_count)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->computer_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->user_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->mailslot_name)); - ndr->flags = _flags_save_string; - } - NDR_CHECK(ndr_pull_samr_AcctFlags(ndr, NDR_SCALARS, &r->acct_control)); - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->sid_size)); - if (r->sid_size) { - uint32_t _flags_save_DATA_BLOB = ndr->flags; - struct ndr_pull *_ndr_sid; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN4); - NDR_CHECK(ndr_pull_DATA_BLOB(ndr, NDR_SCALARS, &r->_pad)); - ndr->flags = _flags_save_DATA_BLOB; - NDR_CHECK(ndr_pull_subcontext_start(ndr, &_ndr_sid, 0, r->sid_size)); - NDR_CHECK(ndr_pull_dom_sid0(_ndr_sid, NDR_SCALARS|NDR_BUFFERS, &r->sid)); - NDR_CHECK(ndr_pull_subcontext_end(ndr, _ndr_sid, 0, r->sid_size)); - } else { - ZERO_STRUCT(r->sid); - } - NDR_CHECK(ndr_pull_netlogon_nt_version_flags(ndr, NDR_SCALARS, &r->nt_version)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -/* Manually modified to only push some parts of the structure if certain flags are set */ -enum ndr_err_code ndr_push_NETLOGON_SAM_LOGON_RESPONSE_EX_with_flags(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_SAM_LOGON_RESPONSE_EX *r) -{ - { - uint32_t _flags_save_STRUCT = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_netlogon_command(ndr, NDR_SCALARS, r->command)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->sbz)); - NDR_CHECK(ndr_push_nbt_server_type(ndr, NDR_SCALARS, r->server_type)); - NDR_CHECK(ndr_push_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->forest)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->dns_domain)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_dns_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->domain)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->user_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->server_site)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->client_site)); - if (r->nt_version & NETLOGON_NT_VERSION_5EX_WITH_IP) { - NDR_CHECK(ndr_push_uint8(ndr, NDR_SCALARS, ndr_size_nbt_sockaddr(&r->sockaddr, ndr->flags))); - { - struct ndr_push *_ndr_sockaddr; - NDR_CHECK(ndr_push_subcontext_start(ndr, &_ndr_sockaddr, 0, ndr_size_nbt_sockaddr(&r->sockaddr, ndr->flags))); - NDR_CHECK(ndr_push_nbt_sockaddr(_ndr_sockaddr, NDR_SCALARS|NDR_BUFFERS, &r->sockaddr)); - NDR_CHECK(ndr_push_subcontext_end(ndr, _ndr_sockaddr, 0, ndr_size_nbt_sockaddr(&r->sockaddr, ndr->flags))); - } - } - if (r->nt_version & NETLOGON_NT_VERSION_WITH_CLOSEST_SITE) { - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->next_closest_site)); - } - NDR_CHECK(ndr_push_netlogon_nt_version_flags(ndr, NDR_SCALARS, r->nt_version)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - NDR_CHECK(ndr_push_GUID(ndr, NDR_BUFFERS, &r->domain_uuid)); - } - ndr->flags = _flags_save_STRUCT; - } - return NDR_ERR_SUCCESS; -} - -/* Manually modified to only pull some parts of the structure if certain flags provided */ -enum ndr_err_code ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_EX_with_flags(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_SAM_LOGON_RESPONSE_EX *r, - uint32_t nt_version_flags) -{ - { - uint32_t _flags_save_STRUCT = ndr->flags; - ZERO_STRUCTP(r); - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_netlogon_command(ndr, NDR_SCALARS, &r->command)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->sbz)); - NDR_CHECK(ndr_pull_nbt_server_type(ndr, NDR_SCALARS, &r->server_type)); - NDR_CHECK(ndr_pull_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->forest)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->dns_domain)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_dns_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->domain)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->user_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->server_site)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->client_site)); - if (nt_version_flags & NETLOGON_NT_VERSION_5EX_WITH_IP) { - NDR_CHECK(ndr_pull_uint8(ndr, NDR_SCALARS, &r->sockaddr_size)); - { - struct ndr_pull *_ndr_sockaddr; - NDR_CHECK(ndr_pull_subcontext_start(ndr, &_ndr_sockaddr, 0, r->sockaddr_size)); - NDR_CHECK(ndr_pull_nbt_sockaddr(_ndr_sockaddr, NDR_SCALARS|NDR_BUFFERS, &r->sockaddr)); - NDR_CHECK(ndr_pull_subcontext_end(ndr, _ndr_sockaddr, 0, r->sockaddr_size)); - } - } - if (nt_version_flags & NETLOGON_NT_VERSION_WITH_CLOSEST_SITE) { - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->next_closest_site)); - } - NDR_CHECK(ndr_pull_netlogon_nt_version_flags(ndr, NDR_SCALARS, &r->nt_version)); - if (r->nt_version != nt_version_flags) { - return NDR_ERR_VALIDATE; - } - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - NDR_CHECK(ndr_pull_GUID(ndr, NDR_BUFFERS, &r->domain_uuid)); - } - ndr->flags = _flags_save_STRUCT; - } - return NDR_ERR_SUCCESS; -} diff --git a/source4/libcli/netlogon.c b/source4/libcli/netlogon.c deleted file mode 100644 index 052d7cbc1e..0000000000 --- a/source4/libcli/netlogon.c +++ /dev/null @@ -1,239 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - CLDAP server structures - - Copyright (C) Andrew Bartlett 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 . -*/ - -#include "includes.h" -#include "libcli/netlogon.h" - -NTSTATUS push_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, - struct smb_iconv_convenience *iconv_convenience, - struct netlogon_samlogon_response *response) -{ - enum ndr_err_code ndr_err; - if (response->ntver == NETLOGON_NT_VERSION_1) { - ndr_err = ndr_push_struct_blob(data, mem_ctx, - iconv_convenience, - &response->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, - (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, - (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)); - return NT_STATUS_INVALID_PARAMETER; - } - if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - DEBUG(2,("failed to push netlogon response of type 0x%02x\n", - response->ntver)); - return ndr_map_error2ntstatus(ndr_err); - } - return NT_STATUS_OK; -} - -NTSTATUS pull_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, - struct smb_iconv_convenience *iconv_convenience, - struct netlogon_samlogon_response *response) -{ - uint32_t ntver; - enum ndr_err_code ndr_err; - - if (data->length < 8) { - return NT_STATUS_BUFFER_TOO_SMALL; - } - - /* lmnttoken */ - if (SVAL(data->data, data->length - 4) != 0xffff) { - return NT_STATUS_INVALID_NETWORK_RESPONSE; - } - /* lm20token */ - if (SVAL(data->data, data->length - 2) != 0xffff) { - return NT_STATUS_INVALID_NETWORK_RESPONSE; - } - - ntver = IVAL(data->data, data->length - 8); - - if (ntver == NETLOGON_NT_VERSION_1) { - ndr_err = ndr_pull_struct_blob_all(data, mem_ctx, - iconv_convenience, - &response->nt4, - (ndr_pull_flags_fn_t)ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_NT40); - response->ntver = NETLOGON_NT_VERSION_1; - } else if (ntver & NETLOGON_NT_VERSION_5EX) { - struct ndr_pull *ndr; - ndr = ndr_pull_init_blob(data, mem_ctx, iconv_convenience); - 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); - if (ndr->offset < ndr->data_size) { - ndr_err = ndr_pull_error(ndr, NDR_ERR_UNREAD_BYTES, - "not all bytes consumed ofs[%u] size[%u]", - ndr->offset, ndr->data_size); - } - response->ntver = NETLOGON_NT_VERSION_5EX; - - } else if (ntver & NETLOGON_NT_VERSION_5) { - ndr_err = ndr_pull_struct_blob_all(data, mem_ctx, - iconv_convenience, - &response->nt5, - (ndr_pull_flags_fn_t)ndr_pull_NETLOGON_SAM_LOGON_RESPONSE); - response->ntver = NETLOGON_NT_VERSION_5; - } else { - DEBUG(2,("failed to parse netlogon response of type 0x%02x - unknown response type\n", - ntver)); - dump_data(10, data->data, data->length); - return NT_STATUS_INVALID_NETWORK_RESPONSE; - } - - if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - DEBUG(2,("failed to parse netlogon response of type 0x%02x\n", - ntver)); - dump_data(10, data->data, data->length); - return ndr_map_error2ntstatus(ndr_err); - } - return NT_STATUS_OK; -} - -void map_netlogon_samlogon_response(struct netlogon_samlogon_response *response) -{ - struct NETLOGON_SAM_LOGON_RESPONSE_EX response_5_ex; - switch (response->ntver) { - case NETLOGON_NT_VERSION_5EX: - 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->ntver = NETLOGON_NT_VERSION_5EX; - response->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->ntver = NETLOGON_NT_VERSION_5EX; - response->nt5_ex = response_5_ex; - break; - } - return; -} - -NTSTATUS push_nbt_netlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, - struct smb_iconv_convenience *iconv_convenience, - struct nbt_netlogon_response *response) -{ - NTSTATUS status = NT_STATUS_INVALID_NETWORK_RESPONSE; - 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_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); - DEBUG(0,("Failed to parse netlogon packet of length %d: %s\n", - (int)data->length, nt_errstr(status))); - if (DEBUGLVL(10)) { - file_save("netlogon.dat", data->data, data->length); - } - return status; - } - status = NT_STATUS_OK; - break; - case NETLOGON_SAMLOGON: - status = push_netlogon_samlogon_response(data, mem_ctx, iconv_convenience, &response->samlogon); - break; - } - return status; -} - - -NTSTATUS pull_nbt_netlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, - struct smb_iconv_convenience *iconv_convenience, - struct nbt_netlogon_response *response) -{ - NTSTATUS status = NT_STATUS_INVALID_NETWORK_RESPONSE; - enum netlogon_command command; - enum ndr_err_code ndr_err; - if (data->length < 4) { - return NT_STATUS_INVALID_NETWORK_RESPONSE; - } - - command = SVAL(data->data, 0); - - switch (command) { - case NETLOGON_RESPONSE_FROM_PDC: - ndr_err = ndr_pull_struct_blob_all(data, mem_ctx, iconv_convenience, &response->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); - DEBUG(0,("Failed to parse netlogon packet of length %d: %s\n", - (int)data->length, nt_errstr(status))); - if (DEBUGLVL(10)) { - file_save("netlogon.dat", data->data, data->length); - } - return status; - } - status = NT_STATUS_OK; - response->response_type = NETLOGON_GET_PDC; - break; - case LOGON_SAM_LOGON_RESPONSE: - case LOGON_SAM_LOGON_PAUSE_RESPONSE: - case LOGON_SAM_LOGON_USER_UNKNOWN: - 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); - response->response_type = NETLOGON_SAMLOGON; - break; - - /* These levels are queries, not responses */ - case LOGON_PRIMARY_QUERY: - case NETLOGON_ANNOUNCE_UAS: - case LOGON_SAM_LOGON_REQUEST: - status = NT_STATUS_INVALID_NETWORK_RESPONSE; - } - - return status; - -} diff --git a/source4/libcli/netlogon.h b/source4/libcli/netlogon.h deleted file mode 100644 index 177ed3a514..0000000000 --- a/source4/libcli/netlogon.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - CLDAP server structures - - Copyright (C) Andrew Bartlett 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 . -*/ - -#ifndef __LIBCLI_NETLOGON_H__ -#define __LIBCLI_NETLOGON_H__ - -#include "librpc/gen_ndr/ndr_nbt.h" - -#include "librpc/gen_ndr/ndr_misc.h" -#include "librpc/gen_ndr/ndr_security.h" -#include "librpc/gen_ndr/ndr_svcctl.h" -#include "librpc/gen_ndr/ndr_samr.h" - -struct netlogon_samlogon_response -{ - uint32_t ntver; - union { - struct NETLOGON_SAM_LOGON_RESPONSE_NT40 nt4; - struct NETLOGON_SAM_LOGON_RESPONSE nt5; - struct NETLOGON_SAM_LOGON_RESPONSE_EX nt5_ex; - }; - -}; - -struct nbt_netlogon_response -{ - enum {NETLOGON_GET_PDC, NETLOGON_SAMLOGON} response_type; - union { - struct nbt_netlogon_response_from_pdc get_pdc; - struct netlogon_samlogon_response samlogon; - }; -}; - -#include "libcli/netlogon_proto.h" -#include "libcli/ndr_netlogon_proto.h" -#endif /* __CLDAP_SERVER_PROTO_H__ */ -- cgit From 1147d05b47dc3ff9b985555bb985f7b5117237c8 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 23:14:40 +0200 Subject: s4-nbt: use moved libcli netlogon helpers. Guenther --- source4/libcli/cldap/cldap.h | 2 +- source4/libcli/config.mk | 8 ++++---- source4/libcli/dgram/libdgram.h | 2 +- source4/librpc/idl/nbt.idl | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/source4/libcli/cldap/cldap.h b/source4/libcli/cldap/cldap.h index 7c2daf0ca2..c1a3b6b63e 100644 --- a/source4/libcli/cldap/cldap.h +++ b/source4/libcli/cldap/cldap.h @@ -20,7 +20,7 @@ */ #include "lib/util/asn1.h" -#include "libcli/netlogon.h" +#include "../libcli/netlogon.h" struct ldap_message; diff --git a/source4/libcli/config.mk b/source4/libcli/config.mk index cee51439ab..bb426ca9f6 100644 --- a/source4/libcli/config.mk +++ b/source4/libcli/config.mk @@ -61,17 +61,17 @@ $(eval $(call proto_header_template,../$(libclisrcdir)/nbt/nbt_proto.h,$(LIBCLI_ PUBLIC_DEPENDENCIES = LIBNDR \ NDR_SECURITY -LIBCLI_NDR_NETLOGON_OBJ_FILES = $(addprefix $(libclisrcdir)/, ndr_netlogon.o) +LIBCLI_NDR_NETLOGON_OBJ_FILES = $(addprefix ../$(libclisrcdir)/, ndr_netlogon.o) -$(eval $(call proto_header_template,$(libclisrcdir)/ndr_netlogon_proto.h,$(LIBCLI_NDR_NETLOGON_OBJ_FILES:.o=.c))) +$(eval $(call proto_header_template,../$(libclisrcdir)/ndr_netlogon_proto.h,$(LIBCLI_NDR_NETLOGON_OBJ_FILES:.o=.c))) [SUBSYSTEM::LIBCLI_NETLOGON] PUBLIC_DEPENDENCIES = LIBSAMBA-UTIL LIBCLI_NDR_NETLOGON -LIBCLI_NETLOGON_OBJ_FILES = $(addprefix $(libclisrcdir)/, \ +LIBCLI_NETLOGON_OBJ_FILES = $(addprefix ../$(libclisrcdir)/, \ netlogon.o) -$(eval $(call proto_header_template,$(libclisrcdir)/netlogon_proto.h,$(LIBCLI_NETLOGON_OBJ_FILES:.o=.c))) +$(eval $(call proto_header_template,../$(libclisrcdir)/netlogon_proto.h,$(LIBCLI_NETLOGON_OBJ_FILES:.o=.c))) [SUBSYSTEM::LIBCLI_DRSBLOBS] PUBLIC_DEPENDENCIES = LIBNDR diff --git a/source4/libcli/dgram/libdgram.h b/source4/libcli/dgram/libdgram.h index e1209e7a54..2f8feb5345 100644 --- a/source4/libcli/dgram/libdgram.h +++ b/source4/libcli/dgram/libdgram.h @@ -19,7 +19,7 @@ along with this program. If not, see . */ -#include "libcli/netlogon.h" +#include "../libcli/netlogon.h" /* a datagram name request diff --git a/source4/librpc/idl/nbt.idl b/source4/librpc/idl/nbt.idl index fad3a39e30..38a2b9596a 100644 --- a/source4/librpc/idl/nbt.idl +++ b/source4/librpc/idl/nbt.idl @@ -10,7 +10,7 @@ import "misc.idl", "security.idl", "svcctl.idl", "samr.idl"; [ - helper("libcli/netlogon.h", "../libcli/nbt/libnbt.h") + helper("../libcli/netlogon.h", "../libcli/nbt/libnbt.h") ] interface nbt { -- cgit From d62bc0e8458b7d952159851a9ffa9f6c580acd50 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 22:35:16 +0200 Subject: s3-nbt: start merging from samba4 idl. Guenther --- source3/librpc/idl/nbt.idl | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/source3/librpc/idl/nbt.idl b/source3/librpc/idl/nbt.idl index da1eb2ef3f..f743109594 100644 --- a/source3/librpc/idl/nbt.idl +++ b/source3/librpc/idl/nbt.idl @@ -350,16 +350,16 @@ interface nbt } nbt_netlogon_command; typedef [flag(NDR_LITTLE_ENDIAN),bitmap32bit] bitmap { - NETLOGON_VERSION_1 = 0x00000001, - NETLOGON_VERSION_5 = 0x00000002, - NETLOGON_VERSION_5EX = 0x00000004, - NETLOGON_VERSION_5EX_WITH_IP = 0x00000008, - NETLOGON_VERSION_WITH_CLOSEST_SITE = 0x00000010, - NETLOGON_VERSION_AVOID_NT4_EMUL = 0x01000000, - NETLOGON_VERSION_PDC = 0x10000000, - NETLOGON_VERSION_IP = 0x20000000, - NETLOGON_VERSION_LOCAL = 0x40000000, - NETLOGON_VERSION_GC = 0x80000000 + NETLOGON_NT_VERSION_1 = 0x00000001, + NETLOGON_NT_VERSION_5 = 0x00000002, + NETLOGON_NT_VERSION_5EX = 0x00000004, + NETLOGON_NT_VERSION_5EX_WITH_IP = 0x00000008, + NETLOGON_NT_VERSION_WITH_CLOSEST_SITE = 0x00000010, + NETLOGON_NT_VERSION_AVIOD_NT4EMUL = 0x01000000, + NETLOGON_NT_VERSION_PDC = 0x10000000, + NETLOGON_NT_VERSION_IP = 0x20000000, + NETLOGON_NT_VERSION_LOCAL = 0x40000000, + NETLOGON_NT_VERSION_GC = 0x80000000 } nbt_netlogon_version; /* query for pdc request */ -- cgit From 0950cce83db06b456d6d89e49766c725b09fe2cd Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 21:07:56 +0200 Subject: s3: re-run make samba3-idl. Guenther --- source3/librpc/gen_ndr/nbt.h | 20 ++++++++++---------- source3/librpc/gen_ndr/ndr_nbt.c | 20 ++++++++++---------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/source3/librpc/gen_ndr/nbt.h b/source3/librpc/gen_ndr/nbt.h index 0943ee1a4d..847f63b9b8 100644 --- a/source3/librpc/gen_ndr/nbt.h +++ b/source3/librpc/gen_ndr/nbt.h @@ -412,16 +412,16 @@ enum nbt_netlogon_command ; /* bitmap nbt_netlogon_version */ -#define NETLOGON_VERSION_1 ( 0x00000001 ) -#define NETLOGON_VERSION_5 ( 0x00000002 ) -#define NETLOGON_VERSION_5EX ( 0x00000004 ) -#define NETLOGON_VERSION_5EX_WITH_IP ( 0x00000008 ) -#define NETLOGON_VERSION_WITH_CLOSEST_SITE ( 0x00000010 ) -#define NETLOGON_VERSION_AVOID_NT4_EMUL ( 0x01000000 ) -#define NETLOGON_VERSION_PDC ( 0x10000000 ) -#define NETLOGON_VERSION_IP ( 0x20000000 ) -#define NETLOGON_VERSION_LOCAL ( 0x40000000 ) -#define NETLOGON_VERSION_GC ( 0x80000000 ) +#define NETLOGON_NT_VERSION_1 ( 0x00000001 ) +#define NETLOGON_NT_VERSION_5 ( 0x00000002 ) +#define NETLOGON_NT_VERSION_5EX ( 0x00000004 ) +#define NETLOGON_NT_VERSION_5EX_WITH_IP ( 0x00000008 ) +#define NETLOGON_NT_VERSION_WITH_CLOSEST_SITE ( 0x00000010 ) +#define NETLOGON_NT_VERSION_AVIOD_NT4EMUL ( 0x01000000 ) +#define NETLOGON_NT_VERSION_PDC ( 0x10000000 ) +#define NETLOGON_NT_VERSION_IP ( 0x20000000 ) +#define NETLOGON_NT_VERSION_LOCAL ( 0x40000000 ) +#define NETLOGON_NT_VERSION_GC ( 0x80000000 ) struct nbt_netlogon_query_for_pdc { const char * computer_name;/* [flag(LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM)] */ diff --git a/source3/librpc/gen_ndr/ndr_nbt.c b/source3/librpc/gen_ndr/ndr_nbt.c index 01cccd6742..d165e65329 100644 --- a/source3/librpc/gen_ndr/ndr_nbt.c +++ b/source3/librpc/gen_ndr/ndr_nbt.c @@ -1608,16 +1608,16 @@ _PUBLIC_ void ndr_print_nbt_netlogon_version(struct ndr_print *ndr, const char * ndr_set_flags(&ndr->flags, LIBNDR_FLAG_LITTLE_ENDIAN); ndr_print_uint32(ndr, name, r); ndr->depth++; - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_VERSION_1", NETLOGON_VERSION_1, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_VERSION_5", NETLOGON_VERSION_5, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_VERSION_5EX", NETLOGON_VERSION_5EX, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_VERSION_5EX_WITH_IP", NETLOGON_VERSION_5EX_WITH_IP, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_VERSION_WITH_CLOSEST_SITE", NETLOGON_VERSION_WITH_CLOSEST_SITE, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_VERSION_AVOID_NT4_EMUL", NETLOGON_VERSION_AVOID_NT4_EMUL, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_VERSION_PDC", NETLOGON_VERSION_PDC, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_VERSION_IP", NETLOGON_VERSION_IP, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_VERSION_LOCAL", NETLOGON_VERSION_LOCAL, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_VERSION_GC", NETLOGON_VERSION_GC, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_1", NETLOGON_NT_VERSION_1, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_5", NETLOGON_NT_VERSION_5, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_5EX", NETLOGON_NT_VERSION_5EX, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_5EX_WITH_IP", NETLOGON_NT_VERSION_5EX_WITH_IP, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_WITH_CLOSEST_SITE", NETLOGON_NT_VERSION_WITH_CLOSEST_SITE, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_AVIOD_NT4EMUL", NETLOGON_NT_VERSION_AVIOD_NT4EMUL, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_PDC", NETLOGON_NT_VERSION_PDC, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_IP", NETLOGON_NT_VERSION_IP, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_LOCAL", NETLOGON_NT_VERSION_LOCAL, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_GC", NETLOGON_NT_VERSION_GC, r); ndr->depth--; ndr->flags = _flags_save_BITMAP; } -- cgit From de54bac54c8276427d88f616e430d2cd486a0ca6 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 21:08:25 +0200 Subject: s3: fix NETLOGON_NT_VERSION version flags. Guenther --- source3/libads/cldap.c | 20 ++++++++++---------- source3/libsmb/dsgetdcname.c | 20 ++++++++++---------- source3/winbindd/winbindd_cm.c | 2 +- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/source3/libads/cldap.c b/source3/libads/cldap.c index 73b28b523a..b89d285e8c 100644 --- a/source3/libads/cldap.c +++ b/source3/libads/cldap.c @@ -264,7 +264,7 @@ bool ads_cldap_netlogon_5(TALLOC_CTX *mem_ctx, const char *realm, struct nbt_cldap_netlogon_5 *reply5) { - uint32_t nt_version = NETLOGON_VERSION_5 | NETLOGON_VERSION_5EX; + uint32_t nt_version = NETLOGON_NT_VERSION_5 | NETLOGON_NT_VERSION_5EX; union nbt_cldap_netlogon *reply = NULL; bool ret; @@ -273,7 +273,7 @@ bool ads_cldap_netlogon_5(TALLOC_CTX *mem_ctx, return false; } - if (nt_version != (NETLOGON_VERSION_5 | NETLOGON_VERSION_5EX)) { + if (nt_version != (NETLOGON_NT_VERSION_5 | NETLOGON_NT_VERSION_5EX)) { return false; } @@ -322,32 +322,32 @@ bool pull_mailslot_cldap_reply(TALLOC_CTX *mem_ctx, * was able to reply to, we are fine and all done. otherwise we need to * assume downgraded replies which are painfully parsed here - gd */ - if (nt_version_query & NETLOGON_VERSION_WITH_CLOSEST_SITE) { - nt_version_query &= ~NETLOGON_VERSION_WITH_CLOSEST_SITE; + if (nt_version_query & NETLOGON_NT_VERSION_WITH_CLOSEST_SITE) { + nt_version_query &= ~NETLOGON_NT_VERSION_WITH_CLOSEST_SITE; } ndr_err = ndr_pull_union_blob_all(blob, mem_ctx, r, nt_version_query, (ndr_pull_flags_fn_t)ndr_pull_nbt_cldap_netlogon); if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { goto done; } - if (nt_version_query & NETLOGON_VERSION_5EX_WITH_IP) { - nt_version_query &= ~NETLOGON_VERSION_5EX_WITH_IP; + if (nt_version_query & NETLOGON_NT_VERSION_5EX_WITH_IP) { + nt_version_query &= ~NETLOGON_NT_VERSION_5EX_WITH_IP; } ndr_err = ndr_pull_union_blob_all(blob, mem_ctx, r, nt_version_query, (ndr_pull_flags_fn_t)ndr_pull_nbt_cldap_netlogon); if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { goto done; } - if (nt_version_query & NETLOGON_VERSION_5EX) { - nt_version_query &= ~NETLOGON_VERSION_5EX; + if (nt_version_query & NETLOGON_NT_VERSION_5EX) { + nt_version_query &= ~NETLOGON_NT_VERSION_5EX; } ndr_err = ndr_pull_union_blob_all(blob, mem_ctx, r, nt_version_query, (ndr_pull_flags_fn_t)ndr_pull_nbt_cldap_netlogon); if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { goto done; } - if (nt_version_query & NETLOGON_VERSION_5) { - nt_version_query &= ~NETLOGON_VERSION_5; + if (nt_version_query & NETLOGON_NT_VERSION_5) { + nt_version_query &= ~NETLOGON_NT_VERSION_5; } ndr_err = ndr_pull_union_blob_all(blob, mem_ctx, r, nt_version_query, (ndr_pull_flags_fn_t)ndr_pull_nbt_cldap_netlogon); diff --git a/source3/libsmb/dsgetdcname.c b/source3/libsmb/dsgetdcname.c index e822635546..4cc587c58d 100644 --- a/source3/libsmb/dsgetdcname.c +++ b/source3/libsmb/dsgetdcname.c @@ -1117,19 +1117,19 @@ static uint32_t map_ds_flags_to_nt_version(uint32_t flags) uint32_t nt_version = 0; if (flags & DS_PDC_REQUIRED) { - nt_version |= NETLOGON_VERSION_PDC; + nt_version |= NETLOGON_NT_VERSION_PDC; } if (flags & DS_GC_SERVER_REQUIRED) { - nt_version |= NETLOGON_VERSION_GC; + nt_version |= NETLOGON_NT_VERSION_GC; } if (flags & DS_TRY_NEXTCLOSEST_SITE) { - nt_version |= NETLOGON_VERSION_WITH_CLOSEST_SITE; + nt_version |= NETLOGON_NT_VERSION_WITH_CLOSEST_SITE; } if (flags & DS_IP_REQUIRED) { - nt_version |= NETLOGON_VERSION_IP; + nt_version |= NETLOGON_NT_VERSION_IP; } return nt_version; @@ -1148,8 +1148,8 @@ static NTSTATUS process_dc_dns(TALLOC_CTX *mem_ctx, int i = 0; bool valid_dc = false; union nbt_cldap_netlogon *r = NULL; - uint32_t nt_version = NETLOGON_VERSION_5 | - NETLOGON_VERSION_5EX; + uint32_t nt_version = NETLOGON_NT_VERSION_5 | + NETLOGON_NT_VERSION_5EX; uint32_t ret_flags = 0; NTSTATUS status; @@ -1236,9 +1236,9 @@ static NTSTATUS process_dc_netbios(TALLOC_CTX *mem_ctx, fstring tmp_dc_name; union nbt_cldap_netlogon *r = NULL; bool store_cache = false; - uint32_t nt_version = NETLOGON_VERSION_1 | - NETLOGON_VERSION_5 | - NETLOGON_VERSION_5EX_WITH_IP; + uint32_t nt_version = NETLOGON_NT_VERSION_1 | + NETLOGON_NT_VERSION_5 | + NETLOGON_NT_VERSION_5EX_WITH_IP; if (!msg_ctx) { msg_ctx = msg_context(mem_ctx); @@ -1295,7 +1295,7 @@ static NTSTATUS process_dc_netbios(TALLOC_CTX *mem_ctx, ZERO_STRUCT(logon1); - nt_version = NETLOGON_VERSION_1; + nt_version = NETLOGON_NT_VERSION_1; logon1.nt_version = nt_version; logon1.pdc_name = tmp_dc_name; diff --git a/source3/winbindd/winbindd_cm.c b/source3/winbindd/winbindd_cm.c index ce851649ba..db43101a34 100644 --- a/source3/winbindd/winbindd_cm.c +++ b/source3/winbindd/winbindd_cm.c @@ -1080,7 +1080,7 @@ static bool dcip_to_name(TALLOC_CTX *mem_ctx, fstring name ) { struct ip_service ip_list; - uint32_t nt_version = NETLOGON_VERSION_1; + uint32_t nt_version = NETLOGON_NT_VERSION_1; ip_list.ss = *pss; ip_list.port = 0; -- cgit From 44f7c1c216d69f4c3dbe02bdf32a4241ea33e533 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 21:00:09 +0200 Subject: pidl: fix samba3 server wrt to samba4 ndr_pull_init_blob protype. this is in preparation for the final nbt merge. Guenther --- pidl/lib/Parse/Pidl/Samba3/ServerNDR.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pidl/lib/Parse/Pidl/Samba3/ServerNDR.pm b/pidl/lib/Parse/Pidl/Samba3/ServerNDR.pm index b21d3f4bbc..c565d8a572 100644 --- a/pidl/lib/Parse/Pidl/Samba3/ServerNDR.pm +++ b/pidl/lib/Parse/Pidl/Samba3/ServerNDR.pm @@ -110,7 +110,7 @@ sub ParseFunction($$) pidl "\treturn false;"; pidl "}"; pidl ""; - pidl "pull = ndr_pull_init_blob(&blob, r);"; + pidl "pull = ndr_pull_init_blob(&blob, r, NULL);"; pidl "if (pull == NULL) {"; pidl "\ttalloc_free(r);"; pidl "\treturn false;"; -- cgit From 5fa451ea84838ca9808e4090f541ea1bec7ec17c Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 20:59:30 +0200 Subject: s3: re-run make samba3-idl. Guenther --- source3/librpc/gen_ndr/srv_dfs.c | 46 ++++----- source3/librpc/gen_ndr/srv_dssetup.c | 22 ++-- source3/librpc/gen_ndr/srv_echo.c | 20 ++-- source3/librpc/gen_ndr/srv_epmapper.c | 16 +-- source3/librpc/gen_ndr/srv_eventlog.c | 48 ++++----- source3/librpc/gen_ndr/srv_initshutdown.c | 6 +- source3/librpc/gen_ndr/srv_lsa.c | 164 +++++++++++++++--------------- source3/librpc/gen_ndr/srv_netlogon.c | 94 ++++++++--------- source3/librpc/gen_ndr/srv_ntsvcs.c | 130 +++++++++++------------ source3/librpc/gen_ndr/srv_samr.c | 136 ++++++++++++------------- source3/librpc/gen_ndr/srv_srvsvc.c | 108 ++++++++++---------- source3/librpc/gen_ndr/srv_svcctl.c | 88 ++++++++-------- source3/librpc/gen_ndr/srv_winreg.c | 70 ++++++------- source3/librpc/gen_ndr/srv_wkssvc.c | 62 +++++------ 14 files changed, 505 insertions(+), 505 deletions(-) diff --git a/source3/librpc/gen_ndr/srv_dfs.c b/source3/librpc/gen_ndr/srv_dfs.c index 54b2184829..631bd82758 100644 --- a/source3/librpc/gen_ndr/srv_dfs.c +++ b/source3/librpc/gen_ndr/srv_dfs.c @@ -27,7 +27,7 @@ static bool api_dfs_GetManagerVersion(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -107,7 +107,7 @@ static bool api_dfs_Add(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -180,7 +180,7 @@ static bool api_dfs_Remove(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -253,7 +253,7 @@ static bool api_dfs_SetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -326,7 +326,7 @@ static bool api_dfs_GetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -406,7 +406,7 @@ static bool api_dfs_Enum(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -482,7 +482,7 @@ static bool api_dfs_Rename(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -555,7 +555,7 @@ static bool api_dfs_Move(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -628,7 +628,7 @@ static bool api_dfs_ManagerGetConfigInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -701,7 +701,7 @@ static bool api_dfs_ManagerSendSiteInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -774,7 +774,7 @@ static bool api_dfs_AddFtRoot(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -849,7 +849,7 @@ static bool api_dfs_RemoveFtRoot(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -924,7 +924,7 @@ static bool api_dfs_AddStdRoot(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -997,7 +997,7 @@ static bool api_dfs_RemoveStdRoot(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1070,7 +1070,7 @@ static bool api_dfs_ManagerInitialize(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1143,7 +1143,7 @@ static bool api_dfs_AddStdRootForced(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1216,7 +1216,7 @@ static bool api_dfs_GetDcAddress(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1293,7 +1293,7 @@ static bool api_dfs_SetDcAddress(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1366,7 +1366,7 @@ static bool api_dfs_FlushFtTable(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1439,7 +1439,7 @@ static bool api_dfs_Add2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1512,7 +1512,7 @@ static bool api_dfs_Remove2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1585,7 +1585,7 @@ static bool api_dfs_EnumEx(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1661,7 +1661,7 @@ static bool api_dfs_SetInfo2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; diff --git a/source3/librpc/gen_ndr/srv_dssetup.c b/source3/librpc/gen_ndr/srv_dssetup.c index 79bde30d06..2dca1c8536 100644 --- a/source3/librpc/gen_ndr/srv_dssetup.c +++ b/source3/librpc/gen_ndr/srv_dssetup.c @@ -27,7 +27,7 @@ static bool api_dssetup_DsRoleGetPrimaryDomainInformation(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -107,7 +107,7 @@ static bool api_dssetup_DsRoleDnsNameToFlatName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -180,7 +180,7 @@ static bool api_dssetup_DsRoleDcAsDc(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -253,7 +253,7 @@ static bool api_dssetup_DsRoleDcAsReplica(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -326,7 +326,7 @@ static bool api_dssetup_DsRoleDemoteDc(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -399,7 +399,7 @@ static bool api_dssetup_DsRoleGetDcOperationProgress(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -472,7 +472,7 @@ static bool api_dssetup_DsRoleGetDcOperationResults(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -545,7 +545,7 @@ static bool api_dssetup_DsRoleCancel(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -618,7 +618,7 @@ static bool api_dssetup_DsRoleServerSaveStateForUpgrade(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -691,7 +691,7 @@ static bool api_dssetup_DsRoleUpgradeDownlevelServer(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -764,7 +764,7 @@ static bool api_dssetup_DsRoleAbortDownlevelServerUpgrade(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; diff --git a/source3/librpc/gen_ndr/srv_echo.c b/source3/librpc/gen_ndr/srv_echo.c index b8b38dad13..38e9e194c8 100644 --- a/source3/librpc/gen_ndr/srv_echo.c +++ b/source3/librpc/gen_ndr/srv_echo.c @@ -27,7 +27,7 @@ static bool api_echo_AddOne(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -107,7 +107,7 @@ static bool api_echo_EchoData(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -187,7 +187,7 @@ static bool api_echo_SinkData(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -260,7 +260,7 @@ static bool api_echo_SourceData(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -340,7 +340,7 @@ static bool api_echo_TestCall(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -420,7 +420,7 @@ static bool api_echo_TestCall2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -500,7 +500,7 @@ static bool api_echo_TestSleep(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -573,7 +573,7 @@ static bool api_echo_TestEnum(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -650,7 +650,7 @@ static bool api_echo_TestSurrounding(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -725,7 +725,7 @@ static bool api_echo_TestDoublePointer(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; diff --git a/source3/librpc/gen_ndr/srv_epmapper.c b/source3/librpc/gen_ndr/srv_epmapper.c index f42598abd4..69a47b355d 100644 --- a/source3/librpc/gen_ndr/srv_epmapper.c +++ b/source3/librpc/gen_ndr/srv_epmapper.c @@ -27,7 +27,7 @@ static bool api_epm_Insert(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -100,7 +100,7 @@ static bool api_epm_Delete(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -173,7 +173,7 @@ static bool api_epm_Lookup(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -260,7 +260,7 @@ static bool api_epm_Map(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -347,7 +347,7 @@ static bool api_epm_LookupHandleFree(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -422,7 +422,7 @@ static bool api_epm_InqObject(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -495,7 +495,7 @@ static bool api_epm_MgmtDelete(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -568,7 +568,7 @@ static bool api_epm_MapAuth(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; diff --git a/source3/librpc/gen_ndr/srv_eventlog.c b/source3/librpc/gen_ndr/srv_eventlog.c index eb3fb1fe6d..946be20e0f 100644 --- a/source3/librpc/gen_ndr/srv_eventlog.c +++ b/source3/librpc/gen_ndr/srv_eventlog.c @@ -27,7 +27,7 @@ static bool api_eventlog_ClearEventLogW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -100,7 +100,7 @@ static bool api_eventlog_BackupEventLogW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -173,7 +173,7 @@ static bool api_eventlog_CloseEventLog(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -248,7 +248,7 @@ static bool api_eventlog_DeregisterEventSource(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -321,7 +321,7 @@ static bool api_eventlog_GetNumRecords(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -401,7 +401,7 @@ static bool api_eventlog_GetOldestRecord(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -481,7 +481,7 @@ static bool api_eventlog_ChangeNotify(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -554,7 +554,7 @@ static bool api_eventlog_OpenEventLogW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -634,7 +634,7 @@ static bool api_eventlog_RegisterEventSourceW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -707,7 +707,7 @@ static bool api_eventlog_OpenBackupEventLogW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -780,7 +780,7 @@ static bool api_eventlog_ReadEventLogW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -872,7 +872,7 @@ static bool api_eventlog_ReportEventW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -945,7 +945,7 @@ static bool api_eventlog_ClearEventLogA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1018,7 +1018,7 @@ static bool api_eventlog_BackupEventLogA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1091,7 +1091,7 @@ static bool api_eventlog_OpenEventLogA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1164,7 +1164,7 @@ static bool api_eventlog_RegisterEventSourceA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1237,7 +1237,7 @@ static bool api_eventlog_OpenBackupEventLogA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1310,7 +1310,7 @@ static bool api_eventlog_ReadEventLogA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1383,7 +1383,7 @@ static bool api_eventlog_ReportEventA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1456,7 +1456,7 @@ static bool api_eventlog_RegisterClusterSvc(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1529,7 +1529,7 @@ static bool api_eventlog_DeregisterClusterSvc(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1602,7 +1602,7 @@ static bool api_eventlog_WriteClusterEvents(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1675,7 +1675,7 @@ static bool api_eventlog_GetLogIntormation(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1748,7 +1748,7 @@ static bool api_eventlog_FlushEventLog(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; diff --git a/source3/librpc/gen_ndr/srv_initshutdown.c b/source3/librpc/gen_ndr/srv_initshutdown.c index 00a89661b5..1fca682c71 100644 --- a/source3/librpc/gen_ndr/srv_initshutdown.c +++ b/source3/librpc/gen_ndr/srv_initshutdown.c @@ -27,7 +27,7 @@ static bool api_initshutdown_Init(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -100,7 +100,7 @@ static bool api_initshutdown_Abort(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -173,7 +173,7 @@ static bool api_initshutdown_InitEx(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; diff --git a/source3/librpc/gen_ndr/srv_lsa.c b/source3/librpc/gen_ndr/srv_lsa.c index 41d1c9716c..f55e079773 100644 --- a/source3/librpc/gen_ndr/srv_lsa.c +++ b/source3/librpc/gen_ndr/srv_lsa.c @@ -27,7 +27,7 @@ static bool api_lsa_Close(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -102,7 +102,7 @@ static bool api_lsa_Delete(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -175,7 +175,7 @@ static bool api_lsa_EnumPrivs(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -256,7 +256,7 @@ static bool api_lsa_QuerySecurity(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -336,7 +336,7 @@ static bool api_lsa_SetSecObj(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -409,7 +409,7 @@ static bool api_lsa_ChangePassword(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -482,7 +482,7 @@ static bool api_lsa_OpenPolicy(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -562,7 +562,7 @@ static bool api_lsa_QueryInfoPolicy(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -642,7 +642,7 @@ static bool api_lsa_SetInfoPolicy(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -715,7 +715,7 @@ static bool api_lsa_ClearAuditLog(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -788,7 +788,7 @@ static bool api_lsa_CreateAccount(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -868,7 +868,7 @@ static bool api_lsa_EnumAccounts(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -949,7 +949,7 @@ static bool api_lsa_CreateTrustedDomain(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1029,7 +1029,7 @@ static bool api_lsa_EnumTrustDom(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1110,7 +1110,7 @@ static bool api_lsa_LookupNames(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1192,7 +1192,7 @@ static bool api_lsa_LookupSids(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1274,7 +1274,7 @@ static bool api_lsa_CreateSecret(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1354,7 +1354,7 @@ static bool api_lsa_OpenAccount(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1434,7 +1434,7 @@ static bool api_lsa_EnumPrivsAccount(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1514,7 +1514,7 @@ static bool api_lsa_AddPrivilegesToAccount(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1587,7 +1587,7 @@ static bool api_lsa_RemovePrivilegesFromAccount(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1660,7 +1660,7 @@ static bool api_lsa_GetQuotasForAccount(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1733,7 +1733,7 @@ static bool api_lsa_SetQuotasForAccount(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1806,7 +1806,7 @@ static bool api_lsa_GetSystemAccessAccount(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1886,7 +1886,7 @@ static bool api_lsa_SetSystemAccessAccount(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1959,7 +1959,7 @@ static bool api_lsa_OpenTrustedDomain(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2039,7 +2039,7 @@ static bool api_lsa_QueryTrustedDomainInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2119,7 +2119,7 @@ static bool api_lsa_SetInformationTrustedDomain(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2192,7 +2192,7 @@ static bool api_lsa_OpenSecret(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2272,7 +2272,7 @@ static bool api_lsa_SetSecret(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2345,7 +2345,7 @@ static bool api_lsa_QuerySecret(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2423,7 +2423,7 @@ static bool api_lsa_LookupPrivValue(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2503,7 +2503,7 @@ static bool api_lsa_LookupPrivName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2583,7 +2583,7 @@ static bool api_lsa_LookupPrivDisplayName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2669,7 +2669,7 @@ static bool api_lsa_DeleteObject(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2744,7 +2744,7 @@ static bool api_lsa_EnumAccountsWithUserRight(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2824,7 +2824,7 @@ static bool api_lsa_EnumAccountRights(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2904,7 +2904,7 @@ static bool api_lsa_AddAccountRights(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2977,7 +2977,7 @@ static bool api_lsa_RemoveAccountRights(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3050,7 +3050,7 @@ static bool api_lsa_QueryTrustedDomainInfoBySid(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3130,7 +3130,7 @@ static bool api_lsa_SetTrustedDomainInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3203,7 +3203,7 @@ static bool api_lsa_DeleteTrustedDomain(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3276,7 +3276,7 @@ static bool api_lsa_StorePrivateData(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3349,7 +3349,7 @@ static bool api_lsa_RetrievePrivateData(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3422,7 +3422,7 @@ static bool api_lsa_OpenPolicy2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3502,7 +3502,7 @@ static bool api_lsa_GetUserName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3578,7 +3578,7 @@ static bool api_lsa_QueryInfoPolicy2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3658,7 +3658,7 @@ static bool api_lsa_SetInfoPolicy2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3731,7 +3731,7 @@ static bool api_lsa_QueryTrustedDomainInfoByName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3811,7 +3811,7 @@ static bool api_lsa_SetTrustedDomainInfoByName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3884,7 +3884,7 @@ static bool api_lsa_EnumTrustedDomainsEx(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3965,7 +3965,7 @@ static bool api_lsa_CreateTrustedDomainEx(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4038,7 +4038,7 @@ static bool api_lsa_CloseTrustedDomainEx(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4113,7 +4113,7 @@ static bool api_lsa_QueryDomainInformationPolicy(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4193,7 +4193,7 @@ static bool api_lsa_SetDomainInformationPolicy(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4266,7 +4266,7 @@ static bool api_lsa_OpenTrustedDomainByName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4346,7 +4346,7 @@ static bool api_lsa_TestCall(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4419,7 +4419,7 @@ static bool api_lsa_LookupSids2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4501,7 +4501,7 @@ static bool api_lsa_LookupNames2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4583,7 +4583,7 @@ static bool api_lsa_CreateTrustedDomainEx2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4656,7 +4656,7 @@ static bool api_lsa_CREDRWRITE(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4729,7 +4729,7 @@ static bool api_lsa_CREDRREAD(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4802,7 +4802,7 @@ static bool api_lsa_CREDRENUMERATE(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4875,7 +4875,7 @@ static bool api_lsa_CREDRWRITEDOMAINCREDENTIALS(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4948,7 +4948,7 @@ static bool api_lsa_CREDRREADDOMAINCREDENTIALS(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5021,7 +5021,7 @@ static bool api_lsa_CREDRDELETE(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5094,7 +5094,7 @@ static bool api_lsa_CREDRGETTARGETINFO(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5167,7 +5167,7 @@ static bool api_lsa_CREDRPROFILELOADED(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5240,7 +5240,7 @@ static bool api_lsa_LookupNames3(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5322,7 +5322,7 @@ static bool api_lsa_CREDRGETSESSIONTYPES(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5395,7 +5395,7 @@ static bool api_lsa_LSARREGISTERAUDITEVENT(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5468,7 +5468,7 @@ static bool api_lsa_LSARGENAUDITEVENT(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5541,7 +5541,7 @@ static bool api_lsa_LSARUNREGISTERAUDITEVENT(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5614,7 +5614,7 @@ static bool api_lsa_lsaRQueryForestTrustInformation(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5694,7 +5694,7 @@ static bool api_lsa_LSARSETFORESTTRUSTINFORMATION(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5767,7 +5767,7 @@ static bool api_lsa_CREDRRENAME(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5840,7 +5840,7 @@ static bool api_lsa_LookupSids3(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5922,7 +5922,7 @@ static bool api_lsa_LookupNames4(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -6004,7 +6004,7 @@ static bool api_lsa_LSAROPENPOLICYSCE(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -6077,7 +6077,7 @@ static bool api_lsa_LSARADTREGISTERSECURITYEVENTSOURCE(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -6150,7 +6150,7 @@ static bool api_lsa_LSARADTUNREGISTERSECURITYEVENTSOURCE(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -6223,7 +6223,7 @@ static bool api_lsa_LSARADTREPORTSECURITYEVENT(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; diff --git a/source3/librpc/gen_ndr/srv_netlogon.c b/source3/librpc/gen_ndr/srv_netlogon.c index 154ef71d40..9ec98bf638 100644 --- a/source3/librpc/gen_ndr/srv_netlogon.c +++ b/source3/librpc/gen_ndr/srv_netlogon.c @@ -27,7 +27,7 @@ static bool api_netr_LogonUasLogon(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -107,7 +107,7 @@ static bool api_netr_LogonUasLogoff(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -187,7 +187,7 @@ static bool api_netr_LogonSamLogon(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -274,7 +274,7 @@ static bool api_netr_LogonSamLogoff(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -349,7 +349,7 @@ static bool api_netr_ServerReqChallenge(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -429,7 +429,7 @@ static bool api_netr_ServerAuthenticate(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -509,7 +509,7 @@ static bool api_netr_ServerPasswordSet(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -589,7 +589,7 @@ static bool api_netr_DatabaseDeltas(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -671,7 +671,7 @@ static bool api_netr_DatabaseSync(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -753,7 +753,7 @@ static bool api_netr_AccountDeltas(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -852,7 +852,7 @@ static bool api_netr_AccountSync(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -952,7 +952,7 @@ static bool api_netr_GetDcName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1032,7 +1032,7 @@ static bool api_netr_LogonControl(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1112,7 +1112,7 @@ static bool api_netr_GetAnyDCName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1192,7 +1192,7 @@ static bool api_netr_LogonControl2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1272,7 +1272,7 @@ static bool api_netr_ServerAuthenticate2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1353,7 +1353,7 @@ static bool api_netr_DatabaseSync2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1435,7 +1435,7 @@ static bool api_netr_DatabaseRedo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1516,7 +1516,7 @@ static bool api_netr_LogonControl2Ex(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1596,7 +1596,7 @@ static bool api_netr_NetrEnumerateTrustedDomains(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1676,7 +1676,7 @@ static bool api_netr_DsRGetDCName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1756,7 +1756,7 @@ static bool api_netr_NETRLOGONDUMMYROUTINE1(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1829,7 +1829,7 @@ static bool api_netr_NETRLOGONSETSERVICEBITS(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1902,7 +1902,7 @@ static bool api_netr_LogonGetTrustRid(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1982,7 +1982,7 @@ static bool api_netr_NETRLOGONCOMPUTESERVERDIGEST(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2055,7 +2055,7 @@ static bool api_netr_NETRLOGONCOMPUTECLIENTDIGEST(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2128,7 +2128,7 @@ static bool api_netr_ServerAuthenticate3(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2210,7 +2210,7 @@ static bool api_netr_DsRGetDCNameEx(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2290,7 +2290,7 @@ static bool api_netr_DsRGetSiteName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2370,7 +2370,7 @@ static bool api_netr_LogonGetDomainInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2451,7 +2451,7 @@ static bool api_netr_ServerPasswordSet2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2531,7 +2531,7 @@ static bool api_netr_ServerPasswordGet(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2617,7 +2617,7 @@ static bool api_netr_NETRLOGONSENDTOSAM(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2690,7 +2690,7 @@ static bool api_netr_DsRAddressToSitenamesW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2770,7 +2770,7 @@ static bool api_netr_DsRGetDCNameEx2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2850,7 +2850,7 @@ static bool api_netr_NETRLOGONGETTIMESERVICEPARENTDOMAIN(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2923,7 +2923,7 @@ static bool api_netr_NetrEnumerateTrustedDomainsEx(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3003,7 +3003,7 @@ static bool api_netr_DsRAddressToSitenamesExW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3083,7 +3083,7 @@ static bool api_netr_DsrGetDcSiteCoverageW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3163,7 +3163,7 @@ static bool api_netr_LogonSamLogonEx(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3250,7 +3250,7 @@ static bool api_netr_DsrEnumerateDomainTrusts(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3330,7 +3330,7 @@ static bool api_netr_DsrDeregisterDNSHostRecords(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3403,7 +3403,7 @@ static bool api_netr_ServerTrustPasswordsGet(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3495,7 +3495,7 @@ static bool api_netr_DsRGetForestTrustInformation(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3575,7 +3575,7 @@ static bool api_netr_GetForestTrustInformation(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3661,7 +3661,7 @@ static bool api_netr_LogonSamLogonWithFlags(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3749,7 +3749,7 @@ static bool api_netr_NETRSERVERGETTRUSTINFO(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; diff --git a/source3/librpc/gen_ndr/srv_ntsvcs.c b/source3/librpc/gen_ndr/srv_ntsvcs.c index d21e86db6e..cdf8c74eb1 100644 --- a/source3/librpc/gen_ndr/srv_ntsvcs.c +++ b/source3/librpc/gen_ndr/srv_ntsvcs.c @@ -27,7 +27,7 @@ static bool api_PNP_Disconnect(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -100,7 +100,7 @@ static bool api_PNP_Connect(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -173,7 +173,7 @@ static bool api_PNP_GetVersion(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -253,7 +253,7 @@ static bool api_PNP_GetGlobalState(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -326,7 +326,7 @@ static bool api_PNP_InitDetection(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -399,7 +399,7 @@ static bool api_PNP_ReportLogOn(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -472,7 +472,7 @@ static bool api_PNP_ValidateDeviceInstance(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -545,7 +545,7 @@ static bool api_PNP_GetRootDeviceInstance(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -618,7 +618,7 @@ static bool api_PNP_GetRelatedDeviceInstance(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -691,7 +691,7 @@ static bool api_PNP_EnumerateSubKeys(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -764,7 +764,7 @@ static bool api_PNP_GetDeviceList(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -837,7 +837,7 @@ static bool api_PNP_GetDeviceListSize(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -917,7 +917,7 @@ static bool api_PNP_GetDepth(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -990,7 +990,7 @@ static bool api_PNP_GetDeviceRegProp(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1073,7 +1073,7 @@ static bool api_PNP_SetDeviceRegProp(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1146,7 +1146,7 @@ static bool api_PNP_GetClassInstance(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1219,7 +1219,7 @@ static bool api_PNP_CreateKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1292,7 +1292,7 @@ static bool api_PNP_DeleteRegistryKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1365,7 +1365,7 @@ static bool api_PNP_GetClassCount(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1438,7 +1438,7 @@ static bool api_PNP_GetClassName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1511,7 +1511,7 @@ static bool api_PNP_DeleteClassKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1584,7 +1584,7 @@ static bool api_PNP_GetInterfaceDeviceAlias(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1657,7 +1657,7 @@ static bool api_PNP_GetInterfaceDeviceList(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1730,7 +1730,7 @@ static bool api_PNP_GetInterfaceDeviceListSize(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1803,7 +1803,7 @@ static bool api_PNP_RegisterDeviceClassAssociation(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1876,7 +1876,7 @@ static bool api_PNP_UnregisterDeviceClassAssociation(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1949,7 +1949,7 @@ static bool api_PNP_GetClassRegProp(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2022,7 +2022,7 @@ static bool api_PNP_SetClassRegProp(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2095,7 +2095,7 @@ static bool api_PNP_CreateDevInst(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2168,7 +2168,7 @@ static bool api_PNP_DeviceInstanceAction(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2241,7 +2241,7 @@ static bool api_PNP_GetDeviceStatus(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2314,7 +2314,7 @@ static bool api_PNP_SetDeviceProblem(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2387,7 +2387,7 @@ static bool api_PNP_DisableDevInst(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2460,7 +2460,7 @@ static bool api_PNP_UninstallDevInst(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2533,7 +2533,7 @@ static bool api_PNP_AddID(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2606,7 +2606,7 @@ static bool api_PNP_RegisterDriver(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2679,7 +2679,7 @@ static bool api_PNP_QueryRemove(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2752,7 +2752,7 @@ static bool api_PNP_RequestDeviceEject(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2825,7 +2825,7 @@ static bool api_PNP_IsDockStationPresent(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2898,7 +2898,7 @@ static bool api_PNP_RequestEjectPC(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2971,7 +2971,7 @@ static bool api_PNP_HwProfFlags(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3053,7 +3053,7 @@ static bool api_PNP_GetHwProfInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3128,7 +3128,7 @@ static bool api_PNP_AddEmptyLogConf(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3201,7 +3201,7 @@ static bool api_PNP_FreeLogConf(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3274,7 +3274,7 @@ static bool api_PNP_GetFirstLogConf(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3347,7 +3347,7 @@ static bool api_PNP_GetNextLogConf(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3420,7 +3420,7 @@ static bool api_PNP_GetLogConfPriority(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3493,7 +3493,7 @@ static bool api_PNP_AddResDes(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3566,7 +3566,7 @@ static bool api_PNP_FreeResDes(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3639,7 +3639,7 @@ static bool api_PNP_GetNextResDes(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3712,7 +3712,7 @@ static bool api_PNP_GetResDesData(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3785,7 +3785,7 @@ static bool api_PNP_GetResDesDataSize(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3858,7 +3858,7 @@ static bool api_PNP_ModifyResDes(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3931,7 +3931,7 @@ static bool api_PNP_DetectResourceLimit(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4004,7 +4004,7 @@ static bool api_PNP_QueryResConfList(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4077,7 +4077,7 @@ static bool api_PNP_SetHwProf(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4150,7 +4150,7 @@ static bool api_PNP_QueryArbitratorFreeData(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4223,7 +4223,7 @@ static bool api_PNP_QueryArbitratorFreeSize(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4296,7 +4296,7 @@ static bool api_PNP_RunDetection(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4369,7 +4369,7 @@ static bool api_PNP_RegisterNotification(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4442,7 +4442,7 @@ static bool api_PNP_UnregisterNotification(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4515,7 +4515,7 @@ static bool api_PNP_GetCustomDevProp(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4588,7 +4588,7 @@ static bool api_PNP_GetVersionInternal(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4661,7 +4661,7 @@ static bool api_PNP_GetBlockedDriverInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4734,7 +4734,7 @@ static bool api_PNP_GetServerSideDeviceInstallFlags(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; diff --git a/source3/librpc/gen_ndr/srv_samr.c b/source3/librpc/gen_ndr/srv_samr.c index 1eaa19eaf7..7d4f2c11fd 100644 --- a/source3/librpc/gen_ndr/srv_samr.c +++ b/source3/librpc/gen_ndr/srv_samr.c @@ -27,7 +27,7 @@ static bool api_samr_Connect(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -107,7 +107,7 @@ static bool api_samr_Close(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -182,7 +182,7 @@ static bool api_samr_SetSecurity(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -255,7 +255,7 @@ static bool api_samr_QuerySecurity(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -335,7 +335,7 @@ static bool api_samr_Shutdown(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -408,7 +408,7 @@ static bool api_samr_LookupDomain(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -488,7 +488,7 @@ static bool api_samr_EnumDomains(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -575,7 +575,7 @@ static bool api_samr_OpenDomain(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -655,7 +655,7 @@ static bool api_samr_QueryDomainInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -735,7 +735,7 @@ static bool api_samr_SetDomainInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -808,7 +808,7 @@ static bool api_samr_CreateDomainGroup(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -894,7 +894,7 @@ static bool api_samr_EnumDomainGroups(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -981,7 +981,7 @@ static bool api_samr_CreateUser(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1067,7 +1067,7 @@ static bool api_samr_EnumDomainUsers(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1154,7 +1154,7 @@ static bool api_samr_CreateDomAlias(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1240,7 +1240,7 @@ static bool api_samr_EnumDomainAliases(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1327,7 +1327,7 @@ static bool api_samr_GetAliasMembership(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1407,7 +1407,7 @@ static bool api_samr_LookupNames(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1493,7 +1493,7 @@ static bool api_samr_LookupRids(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1579,7 +1579,7 @@ static bool api_samr_OpenGroup(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1659,7 +1659,7 @@ static bool api_samr_QueryGroupInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1739,7 +1739,7 @@ static bool api_samr_SetGroupInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1812,7 +1812,7 @@ static bool api_samr_AddGroupMember(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1885,7 +1885,7 @@ static bool api_samr_DeleteDomainGroup(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1960,7 +1960,7 @@ static bool api_samr_DeleteGroupMember(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2033,7 +2033,7 @@ static bool api_samr_QueryGroupMember(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2113,7 +2113,7 @@ static bool api_samr_SetMemberAttributesOfGroup(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2186,7 +2186,7 @@ static bool api_samr_OpenAlias(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2266,7 +2266,7 @@ static bool api_samr_QueryAliasInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2346,7 +2346,7 @@ static bool api_samr_SetAliasInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2419,7 +2419,7 @@ static bool api_samr_DeleteDomAlias(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2494,7 +2494,7 @@ static bool api_samr_AddAliasMember(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2567,7 +2567,7 @@ static bool api_samr_DeleteAliasMember(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2640,7 +2640,7 @@ static bool api_samr_GetMembersInAlias(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2720,7 +2720,7 @@ static bool api_samr_OpenUser(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2800,7 +2800,7 @@ static bool api_samr_DeleteUser(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2875,7 +2875,7 @@ static bool api_samr_QueryUserInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2955,7 +2955,7 @@ static bool api_samr_SetUserInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3028,7 +3028,7 @@ static bool api_samr_ChangePasswordUser(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3101,7 +3101,7 @@ static bool api_samr_GetGroupsForUser(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3181,7 +3181,7 @@ static bool api_samr_QueryDisplayInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3273,7 +3273,7 @@ static bool api_samr_GetDisplayEnumerationIndex(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3353,7 +3353,7 @@ static bool api_samr_TestPrivateFunctionsDomain(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3426,7 +3426,7 @@ static bool api_samr_TestPrivateFunctionsUser(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3499,7 +3499,7 @@ static bool api_samr_GetUserPwInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3579,7 +3579,7 @@ static bool api_samr_RemoveMemberFromForeignDomain(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3652,7 +3652,7 @@ static bool api_samr_QueryDomainInfo2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3732,7 +3732,7 @@ static bool api_samr_QueryUserInfo2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3812,7 +3812,7 @@ static bool api_samr_QueryDisplayInfo2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3904,7 +3904,7 @@ static bool api_samr_GetDisplayEnumerationIndex2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3984,7 +3984,7 @@ static bool api_samr_CreateUser2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4076,7 +4076,7 @@ static bool api_samr_QueryDisplayInfo3(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4168,7 +4168,7 @@ static bool api_samr_AddMultipleMembersToAlias(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4241,7 +4241,7 @@ static bool api_samr_RemoveMultipleMembersFromAlias(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4314,7 +4314,7 @@ static bool api_samr_OemChangePasswordUser2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4387,7 +4387,7 @@ static bool api_samr_ChangePasswordUser2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4460,7 +4460,7 @@ static bool api_samr_GetDomPwInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4540,7 +4540,7 @@ static bool api_samr_Connect2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4620,7 +4620,7 @@ static bool api_samr_SetUserInfo2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4693,7 +4693,7 @@ static bool api_samr_SetBootKeyInformation(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4766,7 +4766,7 @@ static bool api_samr_GetBootKeyInformation(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4846,7 +4846,7 @@ static bool api_samr_Connect3(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4926,7 +4926,7 @@ static bool api_samr_Connect4(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5006,7 +5006,7 @@ static bool api_samr_ChangePasswordUser3(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5092,7 +5092,7 @@ static bool api_samr_Connect5(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5184,7 +5184,7 @@ static bool api_samr_RidToSid(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5264,7 +5264,7 @@ static bool api_samr_SetDsrmPassword(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -5337,7 +5337,7 @@ static bool api_samr_ValidatePassword(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; diff --git a/source3/librpc/gen_ndr/srv_srvsvc.c b/source3/librpc/gen_ndr/srv_srvsvc.c index 66faaaaf7e..60a7212805 100644 --- a/source3/librpc/gen_ndr/srv_srvsvc.c +++ b/source3/librpc/gen_ndr/srv_srvsvc.c @@ -27,7 +27,7 @@ static bool api_srvsvc_NetCharDevEnum(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -110,7 +110,7 @@ static bool api_srvsvc_NetCharDevGetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -190,7 +190,7 @@ static bool api_srvsvc_NetCharDevControl(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -263,7 +263,7 @@ static bool api_srvsvc_NetCharDevQEnum(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -346,7 +346,7 @@ static bool api_srvsvc_NetCharDevQGetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -426,7 +426,7 @@ static bool api_srvsvc_NetCharDevQSetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -501,7 +501,7 @@ static bool api_srvsvc_NetCharDevQPurge(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -574,7 +574,7 @@ static bool api_srvsvc_NetCharDevQPurgeSelf(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -647,7 +647,7 @@ static bool api_srvsvc_NetConnEnum(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -729,7 +729,7 @@ static bool api_srvsvc_NetFileEnum(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -811,7 +811,7 @@ static bool api_srvsvc_NetFileGetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -891,7 +891,7 @@ static bool api_srvsvc_NetFileClose(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -964,7 +964,7 @@ static bool api_srvsvc_NetSessEnum(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1046,7 +1046,7 @@ static bool api_srvsvc_NetSessDel(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1119,7 +1119,7 @@ static bool api_srvsvc_NetShareAdd(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1194,7 +1194,7 @@ static bool api_srvsvc_NetShareEnumAll(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1276,7 +1276,7 @@ static bool api_srvsvc_NetShareGetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1356,7 +1356,7 @@ static bool api_srvsvc_NetShareSetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1431,7 +1431,7 @@ static bool api_srvsvc_NetShareDel(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1504,7 +1504,7 @@ static bool api_srvsvc_NetShareDelSticky(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1577,7 +1577,7 @@ static bool api_srvsvc_NetShareCheck(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1657,7 +1657,7 @@ static bool api_srvsvc_NetSrvGetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1737,7 +1737,7 @@ static bool api_srvsvc_NetSrvSetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1812,7 +1812,7 @@ static bool api_srvsvc_NetDiskEnum(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1894,7 +1894,7 @@ static bool api_srvsvc_NetServerStatisticsGet(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1974,7 +1974,7 @@ static bool api_srvsvc_NetTransportAdd(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2047,7 +2047,7 @@ static bool api_srvsvc_NetTransportEnum(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2130,7 +2130,7 @@ static bool api_srvsvc_NetTransportDel(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2203,7 +2203,7 @@ static bool api_srvsvc_NetRemoteTOD(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2283,7 +2283,7 @@ static bool api_srvsvc_NetSetServiceBits(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2356,7 +2356,7 @@ static bool api_srvsvc_NetPathType(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2436,7 +2436,7 @@ static bool api_srvsvc_NetPathCanonicalize(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2517,7 +2517,7 @@ static bool api_srvsvc_NetPathCompare(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2590,7 +2590,7 @@ static bool api_srvsvc_NetNameValidate(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2663,7 +2663,7 @@ static bool api_srvsvc_NETRPRNAMECANONICALIZE(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2736,7 +2736,7 @@ static bool api_srvsvc_NetPRNameCompare(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2809,7 +2809,7 @@ static bool api_srvsvc_NetShareEnum(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2891,7 +2891,7 @@ static bool api_srvsvc_NetShareDelStart(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2971,7 +2971,7 @@ static bool api_srvsvc_NetShareDelCommit(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3046,7 +3046,7 @@ static bool api_srvsvc_NetGetFileSecurity(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3126,7 +3126,7 @@ static bool api_srvsvc_NetSetFileSecurity(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3199,7 +3199,7 @@ static bool api_srvsvc_NetServerTransportAddEx(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3272,7 +3272,7 @@ static bool api_srvsvc_NetServerSetServiceBitsEx(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3345,7 +3345,7 @@ static bool api_srvsvc_NETRDFSGETVERSION(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3418,7 +3418,7 @@ static bool api_srvsvc_NETRDFSCREATELOCALPARTITION(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3491,7 +3491,7 @@ static bool api_srvsvc_NETRDFSDELETELOCALPARTITION(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3564,7 +3564,7 @@ static bool api_srvsvc_NETRDFSSETLOCALVOLUMESTATE(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3637,7 +3637,7 @@ static bool api_srvsvc_NETRDFSSETSERVERINFO(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3710,7 +3710,7 @@ static bool api_srvsvc_NETRDFSCREATEEXITPOINT(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3783,7 +3783,7 @@ static bool api_srvsvc_NETRDFSDELETEEXITPOINT(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3856,7 +3856,7 @@ static bool api_srvsvc_NETRDFSMODIFYPREFIX(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3929,7 +3929,7 @@ static bool api_srvsvc_NETRDFSFIXLOCALVOLUME(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4002,7 +4002,7 @@ static bool api_srvsvc_NETRDFSMANAGERREPORTSITEINFO(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -4075,7 +4075,7 @@ static bool api_srvsvc_NETRSERVERTRANSPORTDELEX(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; diff --git a/source3/librpc/gen_ndr/srv_svcctl.c b/source3/librpc/gen_ndr/srv_svcctl.c index 32317ad8fe..d371ca2ec6 100644 --- a/source3/librpc/gen_ndr/srv_svcctl.c +++ b/source3/librpc/gen_ndr/srv_svcctl.c @@ -27,7 +27,7 @@ static bool api_svcctl_CloseServiceHandle(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -102,7 +102,7 @@ static bool api_svcctl_ControlService(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -182,7 +182,7 @@ static bool api_svcctl_DeleteService(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -255,7 +255,7 @@ static bool api_svcctl_LockServiceDatabase(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -335,7 +335,7 @@ static bool api_svcctl_QueryServiceObjectSecurity(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -421,7 +421,7 @@ static bool api_svcctl_SetServiceObjectSecurity(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -494,7 +494,7 @@ static bool api_svcctl_QueryServiceStatus(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -574,7 +574,7 @@ static bool api_svcctl_SetServiceStatus(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -647,7 +647,7 @@ static bool api_svcctl_UnlockServiceDatabase(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -722,7 +722,7 @@ static bool api_svcctl_NotifyBootConfigStatus(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -795,7 +795,7 @@ static bool api_svcctl_SCSetServiceBitsW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -868,7 +868,7 @@ static bool api_svcctl_ChangeServiceConfigW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -948,7 +948,7 @@ static bool api_svcctl_CreateServiceW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1029,7 +1029,7 @@ static bool api_svcctl_EnumDependentServicesW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1121,7 +1121,7 @@ static bool api_svcctl_EnumServicesStatusW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1214,7 +1214,7 @@ static bool api_svcctl_OpenSCManagerW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1294,7 +1294,7 @@ static bool api_svcctl_OpenServiceW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1374,7 +1374,7 @@ static bool api_svcctl_QueryServiceConfigW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1460,7 +1460,7 @@ static bool api_svcctl_QueryServiceLockStatusW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1546,7 +1546,7 @@ static bool api_svcctl_StartServiceW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1619,7 +1619,7 @@ static bool api_svcctl_GetServiceDisplayNameW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1700,7 +1700,7 @@ static bool api_svcctl_GetServiceKeyNameW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1781,7 +1781,7 @@ static bool api_svcctl_SCSetServiceBitsA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1854,7 +1854,7 @@ static bool api_svcctl_ChangeServiceConfigA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1934,7 +1934,7 @@ static bool api_svcctl_CreateServiceA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2014,7 +2014,7 @@ static bool api_svcctl_EnumDependentServicesA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2106,7 +2106,7 @@ static bool api_svcctl_EnumServicesStatusA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2199,7 +2199,7 @@ static bool api_svcctl_OpenSCManagerA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2279,7 +2279,7 @@ static bool api_svcctl_OpenServiceA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2352,7 +2352,7 @@ static bool api_svcctl_QueryServiceConfigA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2438,7 +2438,7 @@ static bool api_svcctl_QueryServiceLockStatusA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2524,7 +2524,7 @@ static bool api_svcctl_StartServiceA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2597,7 +2597,7 @@ static bool api_svcctl_GetServiceDisplayNameA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2678,7 +2678,7 @@ static bool api_svcctl_GetServiceKeyNameA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2759,7 +2759,7 @@ static bool api_svcctl_GetCurrentGroupeStateW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2832,7 +2832,7 @@ static bool api_svcctl_EnumServiceGroupW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2905,7 +2905,7 @@ static bool api_svcctl_ChangeServiceConfig2A(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2978,7 +2978,7 @@ static bool api_svcctl_ChangeServiceConfig2W(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3051,7 +3051,7 @@ static bool api_svcctl_QueryServiceConfig2A(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3137,7 +3137,7 @@ static bool api_svcctl_QueryServiceConfig2W(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3223,7 +3223,7 @@ static bool api_svcctl_QueryServiceStatusEx(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3309,7 +3309,7 @@ static bool api_EnumServicesStatusExA(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3408,7 +3408,7 @@ static bool api_EnumServicesStatusExW(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -3507,7 +3507,7 @@ static bool api_svcctl_SCSendTSMessage(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; diff --git a/source3/librpc/gen_ndr/srv_winreg.c b/source3/librpc/gen_ndr/srv_winreg.c index c697f44d2a..2162306322 100644 --- a/source3/librpc/gen_ndr/srv_winreg.c +++ b/source3/librpc/gen_ndr/srv_winreg.c @@ -27,7 +27,7 @@ static bool api_winreg_OpenHKCR(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -107,7 +107,7 @@ static bool api_winreg_OpenHKCU(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -187,7 +187,7 @@ static bool api_winreg_OpenHKLM(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -267,7 +267,7 @@ static bool api_winreg_OpenHKPD(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -347,7 +347,7 @@ static bool api_winreg_OpenHKU(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -427,7 +427,7 @@ static bool api_winreg_CloseKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -502,7 +502,7 @@ static bool api_winreg_CreateKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -583,7 +583,7 @@ static bool api_winreg_DeleteKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -656,7 +656,7 @@ static bool api_winreg_DeleteValue(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -729,7 +729,7 @@ static bool api_winreg_EnumKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -806,7 +806,7 @@ static bool api_winreg_EnumValue(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -885,7 +885,7 @@ static bool api_winreg_FlushKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -958,7 +958,7 @@ static bool api_winreg_GetKeySecurity(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1033,7 +1033,7 @@ static bool api_winreg_LoadKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1106,7 +1106,7 @@ static bool api_winreg_NotifyChangeKeyValue(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1179,7 +1179,7 @@ static bool api_winreg_OpenKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1259,7 +1259,7 @@ static bool api_winreg_QueryInfoKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1382,7 +1382,7 @@ static bool api_winreg_QueryValue(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1460,7 +1460,7 @@ static bool api_winreg_ReplaceKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1533,7 +1533,7 @@ static bool api_winreg_RestoreKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1606,7 +1606,7 @@ static bool api_winreg_SaveKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1679,7 +1679,7 @@ static bool api_winreg_SetKeySecurity(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1752,7 +1752,7 @@ static bool api_winreg_SetValue(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1825,7 +1825,7 @@ static bool api_winreg_UnLoadKey(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1898,7 +1898,7 @@ static bool api_winreg_InitiateSystemShutdown(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1971,7 +1971,7 @@ static bool api_winreg_AbortSystemShutdown(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2044,7 +2044,7 @@ static bool api_winreg_GetVersion(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2124,7 +2124,7 @@ static bool api_winreg_OpenHKCC(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2204,7 +2204,7 @@ static bool api_winreg_OpenHKDD(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2284,7 +2284,7 @@ static bool api_winreg_QueryMultipleValues(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2361,7 +2361,7 @@ static bool api_winreg_InitiateSystemShutdownEx(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2434,7 +2434,7 @@ static bool api_winreg_SaveKeyEx(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2507,7 +2507,7 @@ static bool api_winreg_OpenHKPT(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2587,7 +2587,7 @@ static bool api_winreg_OpenHKPN(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2667,7 +2667,7 @@ static bool api_winreg_QueryMultipleValues2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; diff --git a/source3/librpc/gen_ndr/srv_wkssvc.c b/source3/librpc/gen_ndr/srv_wkssvc.c index 227e4c1a48..68813dbba7 100644 --- a/source3/librpc/gen_ndr/srv_wkssvc.c +++ b/source3/librpc/gen_ndr/srv_wkssvc.c @@ -27,7 +27,7 @@ static bool api_wkssvc_NetWkstaGetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -107,7 +107,7 @@ static bool api_wkssvc_NetWkstaSetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -182,7 +182,7 @@ static bool api_wkssvc_NetWkstaEnumUsers(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -264,7 +264,7 @@ static bool api_wkssvc_NetrWkstaUserGetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -344,7 +344,7 @@ static bool api_wkssvc_NetrWkstaUserSetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -419,7 +419,7 @@ static bool api_wkssvc_NetWkstaTransportEnum(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -501,7 +501,7 @@ static bool api_wkssvc_NetrWkstaTransportAdd(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -576,7 +576,7 @@ static bool api_wkssvc_NetrWkstaTransportDel(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -649,7 +649,7 @@ static bool api_wkssvc_NetrUseAdd(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -724,7 +724,7 @@ static bool api_wkssvc_NetrUseGetInfo(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -804,7 +804,7 @@ static bool api_wkssvc_NetrUseDel(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -877,7 +877,7 @@ static bool api_wkssvc_NetrUseEnum(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -959,7 +959,7 @@ static bool api_wkssvc_NetrMessageBufferSend(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1032,7 +1032,7 @@ static bool api_wkssvc_NetrWorkstationStatisticsGet(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1112,7 +1112,7 @@ static bool api_wkssvc_NetrLogonDomainNameAdd(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1185,7 +1185,7 @@ static bool api_wkssvc_NetrLogonDomainNameDel(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1258,7 +1258,7 @@ static bool api_wkssvc_NetrJoinDomain(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1331,7 +1331,7 @@ static bool api_wkssvc_NetrUnjoinDomain(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1404,7 +1404,7 @@ static bool api_wkssvc_NetrRenameMachineInDomain(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1477,7 +1477,7 @@ static bool api_wkssvc_NetrValidateName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1550,7 +1550,7 @@ static bool api_wkssvc_NetrGetJoinInformation(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1631,7 +1631,7 @@ static bool api_wkssvc_NetrGetJoinableOus(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1712,7 +1712,7 @@ static bool api_wkssvc_NetrJoinDomain2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1785,7 +1785,7 @@ static bool api_wkssvc_NetrUnjoinDomain2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1858,7 +1858,7 @@ static bool api_wkssvc_NetrRenameMachineInDomain2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -1931,7 +1931,7 @@ static bool api_wkssvc_NetrValidateName2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2004,7 +2004,7 @@ static bool api_wkssvc_NetrGetJoinableOus2(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2085,7 +2085,7 @@ static bool api_wkssvc_NetrAddAlternateComputerName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2158,7 +2158,7 @@ static bool api_wkssvc_NetrRemoveAlternateComputerName(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2231,7 +2231,7 @@ static bool api_wkssvc_NetrSetPrimaryComputername(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; @@ -2304,7 +2304,7 @@ static bool api_wkssvc_NetrEnumerateComputerNames(pipes_struct *p) return false; } - pull = ndr_pull_init_blob(&blob, r); + pull = ndr_pull_init_blob(&blob, r, NULL); if (pull == NULL) { talloc_free(r); return false; -- cgit From 022947097fb6bb84ff32e279bc65d73ac5c8eb8f Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 20:43:41 +0200 Subject: s3-ndr: add stub smb_iconv_convenience to some ndr_ functions. Guenther --- source3/include/proto.h | 7 ++++--- source3/libnet/libnet_dssync_keytab.c | 2 +- source3/librpc/ndr/ndr.c | 15 ++++++++------- source3/librpc/rpc/binding.c | 2 +- source3/librpc/rpc/dcerpc.c | 2 +- source3/rpc_client/ndr.c | 2 +- 6 files changed, 16 insertions(+), 14 deletions(-) diff --git a/source3/include/proto.h b/source3/include/proto.h index a2772384c5..9ee3fc9071 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -3881,7 +3881,7 @@ NTSTATUS rpc_wkssvc_init(void); /* The following definitions come from librpc/ndr/ndr.c */ _PUBLIC_ size_t ndr_align_size(uint32_t offset, size_t n); -_PUBLIC_ struct ndr_pull *ndr_pull_init_blob(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx); +_PUBLIC_ struct ndr_pull *ndr_pull_init_blob(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, struct smb_iconv_convenience *iconv_convenience); _PUBLIC_ enum ndr_err_code ndr_pull_advance(struct ndr_pull *ndr, uint32_t size); _PUBLIC_ void ndr_pull_save(struct ndr_pull *ndr, struct ndr_pull_save *save); _PUBLIC_ void ndr_pull_restore(struct ndr_pull *ndr, struct ndr_pull_save *save); @@ -3944,8 +3944,9 @@ _PUBLIC_ uint32_t ndr_push_get_switch_value(struct ndr_push *ndr, const void *p) _PUBLIC_ uint32_t ndr_pull_get_switch_value(struct ndr_pull *ndr, const void *p); _PUBLIC_ uint32_t ndr_print_get_switch_value(struct ndr_print *ndr, const void *p); _PUBLIC_ enum ndr_err_code ndr_pull_struct_blob(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, struct smb_iconv_convenience *iconv_convenience, void *p, ndr_pull_flags_fn_t fn); -_PUBLIC_ enum ndr_err_code ndr_pull_struct_blob_all(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, void *p, - ndr_pull_flags_fn_t fn); +_PUBLIC_ enum ndr_err_code ndr_pull_struct_blob_all(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + void *p, ndr_pull_flags_fn_t fn); _PUBLIC_ enum ndr_err_code ndr_pull_union_blob(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, void *p, uint32_t level, ndr_pull_flags_fn_t fn); _PUBLIC_ enum ndr_err_code ndr_pull_union_blob_all(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, void *p, diff --git a/source3/libnet/libnet_dssync_keytab.c b/source3/libnet/libnet_dssync_keytab.c index e762ecbe49..6a3139d6ad 100644 --- a/source3/libnet/libnet_dssync_keytab.c +++ b/source3/libnet/libnet_dssync_keytab.c @@ -179,7 +179,7 @@ static NTSTATUS parse_supplemental_credentials(TALLOC_CTX *mem_ctx, bool newer_keys = false; uint32_t j; - ndr_err = ndr_pull_struct_blob_all(blob, mem_ctx, &scb, + ndr_err = ndr_pull_struct_blob_all(blob, mem_ctx, NULL, &scb, (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { status = ndr_map_error2ntstatus(ndr_err); diff --git a/source3/librpc/ndr/ndr.c b/source3/librpc/ndr/ndr.c index 624024c94d..56d5967de9 100644 --- a/source3/librpc/ndr/ndr.c +++ b/source3/librpc/ndr/ndr.c @@ -53,7 +53,7 @@ _PUBLIC_ size_t ndr_align_size(uint32_t offset, size_t n) /* initialise a ndr parse structure from a data blob */ -_PUBLIC_ struct ndr_pull *ndr_pull_init_blob(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx) +_PUBLIC_ struct ndr_pull *ndr_pull_init_blob(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, struct smb_iconv_convenience *iconv_convenience) { struct ndr_pull *ndr; @@ -810,7 +810,7 @@ _PUBLIC_ enum ndr_err_code ndr_pull_struct_blob(const DATA_BLOB *blob, ndr_pull_flags_fn_t fn) { struct ndr_pull *ndr; - ndr = ndr_pull_init_blob(blob, mem_ctx); + ndr = ndr_pull_init_blob(blob, mem_ctx, iconv_convenience); NDR_ERR_HAVE_NO_MEMORY(ndr); NDR_CHECK(fn(ndr, NDR_SCALARS|NDR_BUFFERS, p)); return NDR_ERR_SUCCESS; @@ -819,11 +819,12 @@ _PUBLIC_ enum ndr_err_code ndr_pull_struct_blob(const DATA_BLOB *blob, /* pull a struct from a blob using NDR - failing if all bytes are not consumed */ -_PUBLIC_ enum ndr_err_code ndr_pull_struct_blob_all(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, void *p, - ndr_pull_flags_fn_t fn) +_PUBLIC_ enum ndr_err_code ndr_pull_struct_blob_all(const DATA_BLOB *blob, TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + void *p, ndr_pull_flags_fn_t fn) { struct ndr_pull *ndr; - ndr = ndr_pull_init_blob(blob, mem_ctx); + ndr = ndr_pull_init_blob(blob, mem_ctx, iconv_convenience); NDR_ERR_HAVE_NO_MEMORY(ndr); NDR_CHECK(fn(ndr, NDR_SCALARS|NDR_BUFFERS, p)); if (ndr->offset < ndr->data_size) { @@ -841,7 +842,7 @@ _PUBLIC_ enum ndr_err_code ndr_pull_union_blob(const DATA_BLOB *blob, TALLOC_CTX uint32_t level, ndr_pull_flags_fn_t fn) { struct ndr_pull *ndr; - ndr = ndr_pull_init_blob(blob, mem_ctx); + ndr = ndr_pull_init_blob(blob, mem_ctx, NULL); NDR_ERR_HAVE_NO_MEMORY(ndr); NDR_CHECK(ndr_pull_set_switch_value(ndr, p, level)); NDR_CHECK(fn(ndr, NDR_SCALARS|NDR_BUFFERS, p)); @@ -856,7 +857,7 @@ _PUBLIC_ enum ndr_err_code ndr_pull_union_blob_all(const DATA_BLOB *blob, TALLOC uint32_t level, ndr_pull_flags_fn_t fn) { struct ndr_pull *ndr; - ndr = ndr_pull_init_blob(blob, mem_ctx); + ndr = ndr_pull_init_blob(blob, mem_ctx, NULL); NDR_ERR_HAVE_NO_MEMORY(ndr); NDR_CHECK(ndr_pull_set_switch_value(ndr, p, level)); NDR_CHECK(fn(ndr, NDR_SCALARS|NDR_BUFFERS, p)); diff --git a/source3/librpc/rpc/binding.c b/source3/librpc/rpc/binding.c index 01e3479c23..469c5db8d5 100644 --- a/source3/librpc/rpc/binding.c +++ b/source3/librpc/rpc/binding.c @@ -357,7 +357,7 @@ _PUBLIC_ NTSTATUS dcerpc_parse_binding(TALLOC_CTX *mem_ctx, const char *s, struc _PUBLIC_ NTSTATUS dcerpc_floor_get_lhs_data(struct epm_floor *epm_floor, struct ndr_syntax_id *syntax) { TALLOC_CTX *mem_ctx = talloc_init("floor_get_lhs_data"); - struct ndr_pull *ndr = ndr_pull_init_blob(&epm_floor->lhs.lhs_data, mem_ctx); + struct ndr_pull *ndr = ndr_pull_init_blob(&epm_floor->lhs.lhs_data, mem_ctx, NULL); enum ndr_err_code ndr_err; uint16_t if_version=0; diff --git a/source3/librpc/rpc/dcerpc.c b/source3/librpc/rpc/dcerpc.c index 58d676a9d9..7a870981fd 100644 --- a/source3/librpc/rpc/dcerpc.c +++ b/source3/librpc/rpc/dcerpc.c @@ -100,7 +100,7 @@ NTSTATUS dcerpc_ndr_request_recv(struct rpc_request *req) prs_mem_free( &r_ps ); - pull = ndr_pull_init_blob(&blob, req); + pull = ndr_pull_init_blob(&blob, req, NULL); if (pull == NULL) { return NT_STATUS_NO_MEMORY; } diff --git a/source3/rpc_client/ndr.c b/source3/rpc_client/ndr.c index 72a33137a6..5565ae3dc3 100644 --- a/source3/rpc_client/ndr.c +++ b/source3/rpc_client/ndr.c @@ -77,7 +77,7 @@ NTSTATUS cli_do_rpc_ndr(struct rpc_pipe_client *cli, prs_mem_free( &r_ps ); - pull = ndr_pull_init_blob(&blob, mem_ctx); + pull = ndr_pull_init_blob(&blob, mem_ctx, NULL); if (pull == NULL) { return NT_STATUS_NO_MEMORY; } -- cgit From 0bbbe2c21fdcbdc492b78b84897f85eb60ec5b00 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 23:41:39 +0200 Subject: pam_winbind: attempt to fix build issue on solaris, bug #5784 Guenther --- source3/nsswitch/pam_winbind.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index c28c5d2697..beb0d47baa 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -71,14 +71,22 @@ static const char *_pam_error_code_str(int err) return "PAM_ABORT"; case PAM_AUTHTOK_EXPIRED: return "PAM_AUTHTOK_EXPIRED"; +#ifdef PAM_MODULE_UNKNOWN case PAM_MODULE_UNKNOWN: return "PAM_MODULE_UNKNOWN"; +#endif +#ifdef PAM_BAD_ITEM case PAM_BAD_ITEM: return "PAM_BAD_ITEM"; +#endif +#ifdef PAM_CONV_AGAIN case PAM_CONV_AGAIN: return "PAM_CONV_AGAIN"; +#endif +#ifdef PAM_INCOMPLETE case PAM_INCOMPLETE: return "PAM_INCOMPLETE"; +#endif default: return NULL; } -- cgit From d275cc762dad1985045d381ca211e92234d9d77d Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Tue, 23 Sep 2008 15:05:45 -0700 Subject: Fix bug #5783 FindFirst fails where search pattern == mangled filename. That was an old and subtle bug. Jeremy. --- source3/smbd/filename.c | 3 +-- source3/smbd/trans2.c | 13 +++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/source3/smbd/filename.c b/source3/smbd/filename.c index 41a0b9296a..562f1e8d94 100644 --- a/source3/smbd/filename.c +++ b/source3/smbd/filename.c @@ -101,8 +101,7 @@ get any fatal errors that should immediately terminate the calling SMB processing whilst resolving. If the saved_last_component != 0, then the unmodified last component -of the pathname is returned there. This is used in an exceptional -case in reply_mv (so far). If saved_last_component == 0 then nothing +of the pathname is returned there. If saved_last_component == 0 then nothing is returned there. If last_component_wcard is true then a MS wildcard was detected and diff --git a/source3/smbd/trans2.c b/source3/smbd/trans2.c index 2e2da5cc71..1e2095a3ea 100644 --- a/source3/smbd/trans2.c +++ b/source3/smbd/trans2.c @@ -1892,7 +1892,7 @@ static void call_trans2findfirst(connection_struct *conn, bool requires_resume_key; int info_level; char *directory = NULL; - const char *mask = NULL; + char *mask = NULL; char *p; int last_entry_off=0; int dptr_num = -1; @@ -1980,7 +1980,7 @@ close_if_end = %d requires_resume_key = %d level = 0x%x, max_data_bytes = %d\n", return; } - ntstatus = unix_convert(ctx, conn, directory, True, &directory, NULL, &sbuf); + ntstatus = unix_convert(ctx, conn, directory, True, &directory, &mask, &sbuf); if (!NT_STATUS_IS_OK(ntstatus)) { reply_nterror(req, ntstatus); return; @@ -1996,10 +1996,12 @@ close_if_end = %d requires_resume_key = %d level = 0x%x, max_data_bytes = %d\n", if(p == NULL) { /* Windows and OS/2 systems treat search on the root '\' as if it were '\*' */ if((directory[0] == '.') && (directory[1] == '\0')) { - mask = "*"; + mask = talloc_strdup(ctx,"*"); + if (!mask) { + reply_nterror(req, NT_STATUS_NO_MEMORY); + return; + } mask_contains_wcard = True; - } else { - mask = directory; } directory = talloc_strdup(talloc_tos(), "./"); if (!directory) { @@ -2007,7 +2009,6 @@ close_if_end = %d requires_resume_key = %d level = 0x%x, max_data_bytes = %d\n", return; } } else { - mask = p+1; *p = 0; } -- cgit From 508527890adc7bedd47522a7dae0c96d2b2e4bae Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Tue, 23 Sep 2008 14:30:06 -0400 Subject: Merge ldb_search() and ldb_search_exp_fmt() into a simgle function. The previous ldb_search() interface made it way too easy to leak results, and being able to use a printf-like expression turns to be really useful. --- source4/auth/gensec/schannel_state.c | 2 +- source4/cldap_server/netlogon.c | 44 +++++++------- source4/dsdb/common/util.c | 29 ++++----- source4/dsdb/repl/drepl_partitions.c | 10 ++-- source4/dsdb/samdb/cracknames.c | 17 +++--- source4/dsdb/samdb/ldb_modules/kludge_acl.c | 8 +-- source4/dsdb/samdb/ldb_modules/naming_fsmo.c | 8 +-- source4/dsdb/samdb/ldb_modules/partition.c | 8 +-- source4/dsdb/samdb/ldb_modules/pdc_fsmo.c | 8 +-- source4/dsdb/samdb/ldb_modules/proxy.c | 2 +- source4/dsdb/samdb/ldb_modules/samldb.c | 10 ++-- source4/dsdb/samdb/ldb_modules/update_keytab.c | 4 +- source4/dsdb/samdb/samdb.c | 2 +- source4/dsdb/schema/schema_init.c | 33 +++++------ source4/dsdb/schema/schema_set.c | 4 +- source4/kdc/hdb-ldb.c | 17 +++--- source4/ldap_server/ldap_backend.c | 4 +- source4/ldap_server/ldap_server.c | 8 +-- source4/lib/ldb/common/ldb.c | 81 +++++++++----------------- source4/lib/ldb/common/ldb_modules.c | 2 +- source4/lib/ldb/examples/ldbreader.c | 5 +- source4/lib/ldb/include/ldb.h | 24 +++----- source4/lib/ldb/ldb.i | 3 +- source4/lib/ldb/ldb_map/ldb_map.c | 2 +- source4/lib/ldb/ldb_wrap.c | 4 +- source4/lib/ldb/nssldb/ldb-grp.c | 20 ++++--- source4/lib/ldb/nssldb/ldb-pwd.c | 15 +++-- source4/lib/ldb/tools/ldbdel.c | 2 +- source4/lib/ldb/tools/ldbedit.c | 2 +- source4/lib/ldb/tools/ldbtest.c | 4 +- source4/lib/registry/ldb.c | 24 ++++---- source4/lib/util/util_ldb.c | 3 +- source4/libnet/libnet_become_dc.c | 79 ++++++++++++------------- source4/libnet/libnet_join.c | 6 +- source4/libnet/libnet_unbecome_dc.c | 19 +++--- source4/nbt_server/wins/winsdb.c | 23 +++----- source4/ntp_signd/ntp_signd.c | 2 +- source4/param/share_ldb.c | 6 +- source4/rpc_server/drsuapi/dcesrv_drsuapi.c | 18 +++--- source4/rpc_server/lsa/lsa_init.c | 9 ++- source4/rpc_server/samr/dcesrv_samr.c | 12 ++-- source4/torture/ldap/schema.c | 4 +- source4/torture/ldap/uptodatevector.c | 10 ++-- source4/torture/local/dbspeed.c | 7 +-- source4/utils/ad2oLschema.c | 10 ++-- source4/winbind/idmap.c | 14 ++--- source4/wrepl_server/wrepl_in_call.c | 3 +- source4/wrepl_server/wrepl_scavenging.c | 9 +-- source4/wrepl_server/wrepl_server.c | 15 ++--- 49 files changed, 284 insertions(+), 371 deletions(-) diff --git a/source4/auth/gensec/schannel_state.c b/source4/auth/gensec/schannel_state.c index f0710c5581..0388b3caf6 100644 --- a/source4/auth/gensec/schannel_state.c +++ b/source4/auth/gensec/schannel_state.c @@ -195,7 +195,7 @@ NTSTATUS schannel_fetch_session_key_ldb(TALLOC_CTX *mem_ctx, return NT_STATUS_NO_MEMORY; } - ret = ldb_search_exp_fmt(ldb, mem_ctx, &res, + ret = ldb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, NULL, "(&(computerName=%s)(flatname=%s))", computer_name, domain); if (ret != LDB_SUCCESS) { diff --git a/source4/cldap_server/netlogon.c b/source4/cldap_server/netlogon.c index 0b146b3c7d..7dccd81fad 100644 --- a/source4/cldap_server/netlogon.c +++ b/source4/cldap_server/netlogon.c @@ -84,11 +84,11 @@ NTSTATUS fill_netlogon_samlogon_response(struct ldb_context *sam_ctx, struct ldb_dn *dom_dn; /* try and find the domain */ - ret = ldb_search_exp_fmt(sam_ctx, mem_ctx, &ref_res, - partitions_basedn, LDB_SCOPE_ONELEVEL, - ref_attrs, - "(&(&(objectClass=crossRef)(dnsRoot=%s))(nETBIOSName=*))", - ldb_binary_encode_string(mem_ctx, domain)); + ret = ldb_search(sam_ctx, mem_ctx, &ref_res, + partitions_basedn, LDB_SCOPE_ONELEVEL, + ref_attrs, + "(&(&(objectClass=crossRef)(dnsRoot=%s))(nETBIOSName=*))", + ldb_binary_encode_string(mem_ctx, domain)); if (ret != LDB_SUCCESS) { DEBUG(2,("Unable to find referece to '%s' in sam: %s\n", @@ -96,19 +96,17 @@ NTSTATUS fill_netlogon_samlogon_response(struct ldb_context *sam_ctx, ldb_errstring(sam_ctx))); return NT_STATUS_NO_SUCH_DOMAIN; } else if (ref_res->count == 1) { - talloc_steal(mem_ctx, dom_res); dom_dn = ldb_msg_find_attr_as_dn(sam_ctx, mem_ctx, ref_res->msgs[0], "ncName"); if (!dom_dn) { return NT_STATUS_NO_SUCH_DOMAIN; } - ret = ldb_search(sam_ctx, dom_dn, - LDB_SCOPE_BASE, "objectClass=domain", - dom_attrs, &dom_res); + ret = ldb_search(sam_ctx, mem_ctx, &dom_res, + dom_dn, LDB_SCOPE_BASE, dom_attrs, + "objectClass=domain"); if (ret != LDB_SUCCESS) { DEBUG(2,("Error finding domain '%s'/'%s' in sam: %s\n", domain, ldb_dn_get_linearized(dom_dn), ldb_errstring(sam_ctx))); return NT_STATUS_NO_SUCH_DOMAIN; } - talloc_steal(mem_ctx, dom_res); if (dom_res->count != 1) { DEBUG(2,("Error finding domain '%s'/'%s' in sam\n", domain, ldb_dn_get_linearized(dom_dn))); return NT_STATUS_NO_SUCH_DOMAIN; @@ -123,11 +121,11 @@ NTSTATUS fill_netlogon_samlogon_response(struct ldb_context *sam_ctx, struct ldb_dn *dom_dn; /* try and find the domain */ - ret = ldb_search_exp_fmt(sam_ctx, mem_ctx, &ref_res, - partitions_basedn, LDB_SCOPE_ONELEVEL, - ref_attrs, - "(&(objectClass=crossRef)(ncName=*)(nETBIOSName=%s))", - ldb_binary_encode_string(mem_ctx, netbios_domain)); + ret = ldb_search(sam_ctx, mem_ctx, &ref_res, + partitions_basedn, LDB_SCOPE_ONELEVEL, + ref_attrs, + "(&(objectClass=crossRef)(ncName=*)(nETBIOSName=%s))", + ldb_binary_encode_string(mem_ctx, netbios_domain)); if (ret != LDB_SUCCESS) { DEBUG(2,("Unable to find referece to '%s' in sam: %s\n", @@ -135,19 +133,17 @@ NTSTATUS fill_netlogon_samlogon_response(struct ldb_context *sam_ctx, ldb_errstring(sam_ctx))); return NT_STATUS_NO_SUCH_DOMAIN; } else if (ref_res->count == 1) { - talloc_steal(mem_ctx, dom_res); dom_dn = ldb_msg_find_attr_as_dn(sam_ctx, mem_ctx, ref_res->msgs[0], "ncName"); if (!dom_dn) { return NT_STATUS_NO_SUCH_DOMAIN; } - ret = ldb_search(sam_ctx, dom_dn, - LDB_SCOPE_BASE, "objectClass=domain", - dom_attrs, &dom_res); + ret = ldb_search(sam_ctx, mem_ctx, &dom_res, + dom_dn, LDB_SCOPE_BASE, dom_attrs, + "objectClass=domain"); if (ret != LDB_SUCCESS) { DEBUG(2,("Error finding domain '%s'/'%s' in sam: %s\n", domain, ldb_dn_get_linearized(dom_dn), ldb_errstring(sam_ctx))); return NT_STATUS_NO_SUCH_DOMAIN; } - talloc_steal(mem_ctx, dom_res); if (dom_res->count != 1) { DEBUG(2,("Error finding domain '%s'/'%s' in sam\n", domain, ldb_dn_get_linearized(dom_dn))); return NT_STATUS_NO_SUCH_DOMAIN; @@ -179,7 +175,7 @@ NTSTATUS fill_netlogon_samlogon_response(struct ldb_context *sam_ctx, if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { return NT_STATUS_INVALID_PARAMETER; } - ret = ldb_search_exp_fmt(sam_ctx, mem_ctx, &dom_res, + ret = ldb_search(sam_ctx, mem_ctx, &dom_res, NULL, LDB_SCOPE_SUBTREE, dom_attrs, "(&(objectCategory=DomainDNS)(objectGUID=%s))", @@ -196,7 +192,7 @@ NTSTATUS fill_netlogon_samlogon_response(struct ldb_context *sam_ctx, return NT_STATUS_INVALID_PARAMETER; } - ret = ldb_search_exp_fmt(sam_ctx, mem_ctx, &dom_res, + ret = ldb_search(sam_ctx, mem_ctx, &dom_res, NULL, LDB_SCOPE_SUBTREE, dom_attrs, "(&(objectCategory=DomainDNS)(objectSID=%s))", @@ -210,7 +206,7 @@ NTSTATUS fill_netlogon_samlogon_response(struct ldb_context *sam_ctx, return NT_STATUS_NO_SUCH_DOMAIN; } else if (dom_res->count == 1) { /* try and find the domain */ - ret = ldb_search_exp_fmt(sam_ctx, mem_ctx, &ref_res, + ret = ldb_search(sam_ctx, mem_ctx, &ref_res, partitions_basedn, LDB_SCOPE_ONELEVEL, ref_attrs, "(&(objectClass=crossRef)(ncName=%s))", @@ -260,7 +256,7 @@ NTSTATUS fill_netlogon_samlogon_response(struct ldb_context *sam_ctx, acct_control = acct_control & (ACB_TEMPDUP | ACB_NORMAL | ACB_DOMTRUST | ACB_WSTRUST | ACB_SVRTRUST); /* We must exclude disabled accounts, but otherwise do the bitwise match the client asked for */ - ret = ldb_search_exp_fmt(sam_ctx, mem_ctx, &user_res, + ret = ldb_search(sam_ctx, mem_ctx, &user_res, dom_res->msgs[0]->dn, LDB_SCOPE_SUBTREE, none_attrs, "(&(objectClass=user)(samAccountName=%s)" diff --git a/source4/dsdb/common/util.c b/source4/dsdb/common/util.c index fa8276e7b4..2b74d722a1 100644 --- a/source4/dsdb/common/util.c +++ b/source4/dsdb/common/util.c @@ -1024,7 +1024,7 @@ const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb) goto failed; } - ret = ldb_search_exp_fmt(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*"); + ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*"); if (ret != LDB_SUCCESS) { goto failed; @@ -1137,13 +1137,12 @@ struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb) } - ret = ldb_search(ldb, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, NULL, root_attrs, &root_res); + ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL); if (ret) { DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n", ldb_errstring(ldb))); goto failed; } - talloc_steal(tmp_ctx, root_res); if (root_res->count != 1) { goto failed; @@ -1189,11 +1188,10 @@ const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb) goto failed; } - ret = ldb_search(ldb, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, NULL, attrs, &res); + ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL); if (ret) { goto failed; } - talloc_steal(tmp_ctx, res); if (res->count != 1) { goto failed; @@ -1283,11 +1281,10 @@ const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb) goto failed; } - ret = ldb_search(ldb, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, NULL, attrs, &res); + ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL); if (ret) { goto failed; } - talloc_steal(tmp_ctx, res); if (res->count != 1) { goto failed; @@ -1397,14 +1394,13 @@ bool samdb_is_pdc(struct ldb_context *ldb) return false; } - ret = ldb_search(ldb, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, NULL, dom_attrs, &dom_res); + ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL); if (ret) { DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n", ldb_dn_get_linearized(ldb_get_default_basedn(ldb)), ldb_errstring(ldb))); goto failed; } - talloc_steal(tmp_ctx, dom_res); if (dom_res->count != 1) { goto failed; } @@ -1444,17 +1440,17 @@ bool samdb_is_gc(struct ldb_context *ldb) } /* Query cn=ntds settings,.... */ - ret = ldb_search(ldb, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, NULL, attrs, &res); + ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL); if (ret) { + talloc_free(tmp_ctx); return false; } if (res->count != 1) { - talloc_free(res); + talloc_free(tmp_ctx); return false; } options = ldb_msg_find_attr_as_int(res->msgs[0], "options", 0); - talloc_free(res); talloc_free(tmp_ctx); /* if options attribute has the 0x00000001 flag set, then enable the global catlog */ @@ -1478,10 +1474,9 @@ int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, if (local_ctx == NULL) return LDB_ERR_OPERATIONS_ERROR; while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) { - ret = ldb_search(ldb, sdn, LDB_SCOPE_BASE, - "(|(|(objectClass=domain)(objectClass=builtinDomain))(objectClass=samba4LocalDomain))", attrs, &res); + ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs, + "(|(|(objectClass=domain)(objectClass=builtinDomain))(objectClass=samba4LocalDomain))"); if (ret == LDB_SUCCESS) { - talloc_steal(local_ctx, res); if (res->count == 1) { break; } @@ -1955,7 +1950,7 @@ struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_result *res_domain_ref; char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name); /* find the domain's DN */ - int ret_domain = ldb_search_exp_fmt(ldb, mem_ctx, + int ret_domain = ldb_search(ldb, mem_ctx, &res_domain_ref, samdb_partitions_dn(ldb, mem_ctx), LDB_SCOPE_ONELEVEL, @@ -1967,7 +1962,7 @@ struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, } if (res_domain_ref->count == 0) { - ret_domain = ldb_search_exp_fmt(ldb, mem_ctx, + ret_domain = ldb_search(ldb, mem_ctx, &res_domain_ref, samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name), LDB_SCOPE_BASE, diff --git a/source4/dsdb/repl/drepl_partitions.c b/source4/dsdb/repl/drepl_partitions.c index 8a1c5aa31a..4f7afc0854 100644 --- a/source4/dsdb/repl/drepl_partitions.c +++ b/source4/dsdb/repl/drepl_partitions.c @@ -48,8 +48,8 @@ WERROR dreplsrv_load_partitions(struct dreplsrv_service *s) basedn = ldb_dn_new(s, s->samdb, NULL); W_ERROR_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->samdb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", attrs, &r); + ret = ldb_search(s->samdb, s, &r, basedn, LDB_SCOPE_BASE, attrs, + "(objectClass=*)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return WERR_FOOBAR; @@ -57,7 +57,6 @@ WERROR dreplsrv_load_partitions(struct dreplsrv_service *s) talloc_free(r); return WERR_FOOBAR; } - talloc_steal(s, r); el = ldb_msg_find_element(r->msgs[0], "namingContexts"); if (!el) { @@ -201,15 +200,14 @@ static WERROR dreplsrv_refresh_partition(struct dreplsrv_service *s, DEBUG(2, ("dreplsrv_refresh_partition(%s)\n", ldb_dn_get_linearized(p->dn))); - ret = ldb_search(s->samdb, p->dn, LDB_SCOPE_BASE, - "(objectClass=*)", attrs, &r); + ret = ldb_search(s->samdb, mem_ctx, &r, p->dn, LDB_SCOPE_BASE, attrs, + "(objectClass=*)"); if (ret != LDB_SUCCESS) { return WERR_FOOBAR; } else if (r->count != 1) { talloc_free(r); return WERR_FOOBAR; } - talloc_steal(mem_ctx, r); ZERO_STRUCT(p->nc); p->nc.dn = ldb_dn_alloc_linearized(p, p->dn); diff --git a/source4/dsdb/samdb/cracknames.c b/source4/dsdb/samdb/cracknames.c index 369b06c305..7324d898a6 100644 --- a/source4/dsdb/samdb/cracknames.c +++ b/source4/dsdb/samdb/cracknames.c @@ -107,8 +107,8 @@ static enum drsuapi_DsNameStatus LDB_lookup_spn_alias(krb5_context context, stru return DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR; } - ret = ldb_search(ldb_ctx, service_dn, LDB_SCOPE_BASE, "(objectClass=nTDSService)", - directory_attrs, &res); + ret = ldb_search(ldb_ctx, tmp_ctx, &res, service_dn, LDB_SCOPE_BASE, + directory_attrs, "(objectClass=nTDSService)"); if (ret != LDB_SUCCESS && ret != LDB_ERR_NO_SUCH_OBJECT) { DEBUG(1, ("ldb_search: dn: %s not found: %s", service_dn_str, ldb_errstring(ldb_ctx))); @@ -121,7 +121,6 @@ static enum drsuapi_DsNameStatus LDB_lookup_spn_alias(krb5_context context, stru DEBUG(1, ("ldb_search: dn: %s not found", service_dn_str)); return DRSUAPI_DS_NAME_STATUS_NOT_FOUND; } - talloc_steal(tmp_ctx, res); spnmappings = ldb_msg_find_element(res->msgs[0], "sPNMappings"); if (!spnmappings || spnmappings->num_values == 0) { @@ -292,7 +291,7 @@ static WERROR DsCrackNameUPN(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, realm = krb5_princ_realm(smb_krb5_context->krb5_context, principal); - ldb_ret = ldb_search_exp_fmt(sam_ctx, mem_ctx, &domain_res, + ldb_ret = ldb_search(sam_ctx, mem_ctx, &domain_res, samdb_partitions_dn(sam_ctx, mem_ctx), LDB_SCOPE_ONELEVEL, domain_attrs, @@ -737,7 +736,7 @@ static WERROR DsCrackNameOneFilter(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ if (domain_filter) { /* if we have a domain_filter look it up and set the result_basedn and the dns_domain_name */ - ldb_ret = ldb_search_exp_fmt(sam_ctx, mem_ctx, &domain_res, + ldb_ret = ldb_search(sam_ctx, mem_ctx, &domain_res, partitions_basedn, LDB_SCOPE_ONELEVEL, domain_attrs, @@ -774,7 +773,7 @@ static WERROR DsCrackNameOneFilter(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ if (domain_res) { result_basedn = samdb_result_dn(sam_ctx, mem_ctx, domain_res->msgs[0], "ncName", NULL); - ret = ldb_search_exp_fmt(sam_ctx, mem_ctx, &res, + ret = ldb_search(sam_ctx, mem_ctx, &res, result_basedn, LDB_SCOPE_SUBTREE, result_attrs, "%s", result_filter); if (ret != LDB_SUCCESS) { @@ -936,7 +935,7 @@ static WERROR DsCrackNameOneFilter(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ if (samdb_find_attribute(sam_ctx, result, "objectClass", "domain")) { - ldb_ret = ldb_search_exp_fmt(sam_ctx, mem_ctx, &domain_res, + ldb_ret = ldb_search(sam_ctx, mem_ctx, &domain_res, partitions_basedn, LDB_SCOPE_ONELEVEL, domain_attrs, @@ -976,7 +975,7 @@ static WERROR DsCrackNameOneFilter(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ return WERR_OK; } dom_sid->num_auths--; - ldb_ret = ldb_search_exp_fmt(sam_ctx, mem_ctx, &domain_res, + ldb_ret = ldb_search(sam_ctx, mem_ctx, &domain_res, NULL, LDB_SCOPE_BASE, attrs, @@ -1000,7 +999,7 @@ static WERROR DsCrackNameOneFilter(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ return WERR_OK; } - ldb_ret = ldb_search_exp_fmt(sam_ctx, mem_ctx, &domain_res2, + ldb_ret = ldb_search(sam_ctx, mem_ctx, &domain_res2, partitions_basedn, LDB_SCOPE_ONELEVEL, domain_attrs, diff --git a/source4/dsdb/samdb/ldb_modules/kludge_acl.c b/source4/dsdb/samdb/ldb_modules/kludge_acl.c index bc998a835a..6836f95873 100644 --- a/source4/dsdb/samdb/ldb_modules/kludge_acl.c +++ b/source4/dsdb/samdb/ldb_modules/kludge_acl.c @@ -409,14 +409,12 @@ static int kludge_acl_init(struct ldb_module *module) return LDB_ERR_OPERATIONS_ERROR; } - ret = ldb_search(module->ldb, ldb_dn_new(mem_ctx, module->ldb, "@KLUDGEACL"), - LDB_SCOPE_BASE, - NULL, attrs, - &res); + ret = ldb_search(module->ldb, mem_ctx, &res, + ldb_dn_new(mem_ctx, module->ldb, "@KLUDGEACL"), + LDB_SCOPE_BASE, attrs, NULL); if (ret != LDB_SUCCESS) { goto done; } - talloc_steal(mem_ctx, res); if (res->count == 0) { goto done; } diff --git a/source4/dsdb/samdb/ldb_modules/naming_fsmo.c b/source4/dsdb/samdb/ldb_modules/naming_fsmo.c index 084540f68d..70f3e8ddfd 100644 --- a/source4/dsdb/samdb/ldb_modules/naming_fsmo.c +++ b/source4/dsdb/samdb/ldb_modules/naming_fsmo.c @@ -64,10 +64,9 @@ static int naming_fsmo_init(struct ldb_module *module) } module->private_data = naming_fsmo; - ret = ldb_search(module->ldb, naming_dn, - LDB_SCOPE_BASE, - NULL, naming_attrs, - &naming_res); + ret = ldb_search(module->ldb, mem_ctx, &naming_res, + naming_dn, LDB_SCOPE_BASE, + naming_attrs, NULL); if (ret == LDB_ERR_NO_SUCH_OBJECT) { ldb_debug(module->ldb, LDB_DEBUG_WARNING, "naming_fsmo_init: no partitions dn present: (skip loading of naming contexts details)\n"); @@ -81,7 +80,6 @@ static int naming_fsmo_init(struct ldb_module *module) talloc_free(mem_ctx); return ret; } - talloc_steal(mem_ctx, naming_res); if (naming_res->count == 0) { ldb_debug(module->ldb, LDB_DEBUG_WARNING, "naming_fsmo_init: no cross-ref container present: (skip loading of naming contexts details)\n"); diff --git a/source4/dsdb/samdb/ldb_modules/partition.c b/source4/dsdb/samdb/ldb_modules/partition.c index 9cae6ab7b5..0cd0baf625 100644 --- a/source4/dsdb/samdb/ldb_modules/partition.c +++ b/source4/dsdb/samdb/ldb_modules/partition.c @@ -807,15 +807,13 @@ static int partition_init(struct ldb_module *module) return LDB_ERR_OPERATIONS_ERROR; } - ret = ldb_search(module->ldb, ldb_dn_new(mem_ctx, module->ldb, "@PARTITION"), - LDB_SCOPE_BASE, - NULL, attrs, - &res); + ret = ldb_search(module->ldb, mem_ctx, &res, + ldb_dn_new(mem_ctx, module->ldb, "@PARTITION"), + LDB_SCOPE_BASE, attrs, NULL); if (ret != LDB_SUCCESS) { talloc_free(mem_ctx); return ret; } - talloc_steal(mem_ctx, res); if (res->count == 0) { talloc_free(mem_ctx); return ldb_next_init(module); diff --git a/source4/dsdb/samdb/ldb_modules/pdc_fsmo.c b/source4/dsdb/samdb/ldb_modules/pdc_fsmo.c index 09d56d77c9..a5e7031a26 100644 --- a/source4/dsdb/samdb/ldb_modules/pdc_fsmo.c +++ b/source4/dsdb/samdb/ldb_modules/pdc_fsmo.c @@ -63,10 +63,9 @@ static int pdc_fsmo_init(struct ldb_module *module) } module->private_data = pdc_fsmo; - ret = ldb_search(module->ldb, pdc_dn, - LDB_SCOPE_BASE, - NULL, pdc_attrs, - &pdc_res); + ret = ldb_search(module->ldb, mem_ctx, &pdc_res, + pdc_dn, LDB_SCOPE_BASE, + pdc_attrs, NULL); if (ret == LDB_ERR_NO_SUCH_OBJECT) { ldb_debug(module->ldb, LDB_DEBUG_WARNING, "pdc_fsmo_init: no domain object present: (skip loading of domain details)\n"); @@ -79,7 +78,6 @@ static int pdc_fsmo_init(struct ldb_module *module) talloc_free(mem_ctx); return ret; } - talloc_steal(mem_ctx, pdc_res); if (pdc_res->count == 0) { ldb_debug(module->ldb, LDB_DEBUG_WARNING, "pdc_fsmo_init: no domain object present: (skip loading of domain details)\n"); diff --git a/source4/dsdb/samdb/ldb_modules/proxy.c b/source4/dsdb/samdb/ldb_modules/proxy.c index 0d065425ca..d0a315e45a 100644 --- a/source4/dsdb/samdb/ldb_modules/proxy.c +++ b/source4/dsdb/samdb/ldb_modules/proxy.c @@ -73,7 +73,7 @@ static int load_proxy_info(struct ldb_module *module) if (dn == NULL) { goto failed; } - ret = ldb_search(module->ldb, dn, LDB_SCOPE_BASE, NULL, NULL, &res); + ret = ldb_search(module->ldb, proxy, &res, dn, LDB_SCOPE_BASE, NULL, NULL); talloc_free(dn); if (ret != LDB_SUCCESS || res->count != 1) { ldb_debug(module->ldb, LDB_DEBUG_FATAL, "Can't find @PROXYINFO\n"); diff --git a/source4/dsdb/samdb/ldb_modules/samldb.c b/source4/dsdb/samdb/ldb_modules/samldb.c index bd491bd011..cf720669b9 100644 --- a/source4/dsdb/samdb/ldb_modules/samldb.c +++ b/source4/dsdb/samdb/ldb_modules/samldb.c @@ -131,7 +131,7 @@ static int samldb_find_next_rid(struct ldb_module *module, TALLOC_CTX *mem_ctx, int ret; const char *str; - ret = ldb_search(module->ldb, dn, LDB_SCOPE_BASE, "nextRid=*", attrs, &res); + ret = ldb_search(module->ldb, mem_ctx, &res, dn, LDB_SCOPE_BASE, attrs, "nextRid=*"); if (ret != LDB_SUCCESS) { return ret; } @@ -207,7 +207,7 @@ static int samldb_get_new_sid(struct ldb_module *module, /* find the domain sid */ - ret = ldb_search(module->ldb, dom_dn, LDB_SCOPE_BASE, "objectSid=*", attrs, &res); + ret = ldb_search(module->ldb, mem_ctx, &res, dom_dn, LDB_SCOPE_BASE, attrs, "objectSid=*"); if (ret != LDB_SUCCESS) { ldb_asprintf_errstring(module->ldb, "samldb_get_new_sid: error retrieving domain sid from %s: %s!\n", @@ -261,7 +261,7 @@ int samldb_notice_sid(struct ldb_module *module, uint32_t old_rid; /* find if this SID already exists */ - ret = ldb_search_exp_fmt(module->ldb, mem_ctx, &res, + 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) { @@ -291,7 +291,7 @@ int samldb_notice_sid(struct ldb_module *module, dom_sid->num_auths--; /* find the domain DN */ - ret = ldb_search_exp_fmt(module->ldb, mem_ctx, &dom_res, + 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)); @@ -371,7 +371,7 @@ static int samldb_generate_samAccountName(struct ldb_module *module, TALLOC_CTX 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_exp_fmt(module->ldb, + ret = ldb_search(module->ldb, mem_ctx, &res, dom_dn, LDB_SCOPE_SUBTREE, attrs, "samAccountName=%s", ldb_binary_encode_string(mem_ctx, *name)); diff --git a/source4/dsdb/samdb/ldb_modules/update_keytab.c b/source4/dsdb/samdb/ldb_modules/update_keytab.c index b36c2c9b71..68973124eb 100644 --- a/source4/dsdb/samdb/ldb_modules/update_keytab.c +++ b/source4/dsdb/samdb/ldb_modules/update_keytab.c @@ -59,8 +59,8 @@ static int add_modified(struct ldb_module *module, struct ldb_dn *dn, bool delet return LDB_ERR_OPERATIONS_ERROR; } - ret = ldb_search(module->ldb, dn, LDB_SCOPE_BASE, - filter, attrs, &res); + ret = ldb_search(module->ldb, data, &res, + dn, LDB_SCOPE_BASE, attrs, "%s", filter); if (ret != LDB_SUCCESS) { talloc_free(filter); return ret; diff --git a/source4/dsdb/samdb/samdb.c b/source4/dsdb/samdb/samdb.c index b5b7ddfdc6..5d928ebce3 100644 --- a/source4/dsdb/samdb/samdb.c +++ b/source4/dsdb/samdb/samdb.c @@ -175,7 +175,7 @@ int samdb_copy_template(struct ldb_context *ldb, } /* pull the template record */ - ret = ldb_search(templates_ldb, basedn, LDB_SCOPE_BASE, "distinguishedName=*", NULL, &res); + ret = ldb_search(templates_ldb, msg, &res, basedn, LDB_SCOPE_BASE, NULL, "distinguishedName=*"); talloc_free(basedn); if (ret != LDB_SUCCESS) { *errstring = talloc_steal(msg, ldb_errstring(templates_ldb)); diff --git a/source4/dsdb/schema/schema_init.c b/source4/dsdb/schema/schema_init.c index 3ed7daee59..d983e3c272 100644 --- a/source4/dsdb/schema/schema_init.c +++ b/source4/dsdb/schema/schema_init.c @@ -525,18 +525,21 @@ WERROR dsdb_read_prefixes_from_ldb(TALLOC_CTX *mem_ctx, struct ldb_context *ldb, return WERR_FOOBAR; } - ret = ldb_search(ldb, schema_dn, LDB_SCOPE_BASE,NULL, schema_attrs,&schema_res); + ret = ldb_search(ldb, mem_ctx, &schema_res, schema_dn, LDB_SCOPE_BASE, schema_attrs, NULL); if (ret == LDB_ERR_NO_SUCH_OBJECT) { DEBUG(0,("dsdb_read_prefixes_from_ldb: no prefix map present\n")); + talloc_free(schema_res); return WERR_FOOBAR; } else if (ret != LDB_SUCCESS) { DEBUG(0,("dsdb_read_prefixes_from_ldb: failed to search the schema head\n")); + talloc_free(schema_res); return WERR_FOOBAR; } prefix_val = ldb_msg_find_ldb_val(schema_res->msgs[0], "prefixMap"); if (!prefix_val) { DEBUG(0,("dsdb_read_prefixes_from_ldb: no prefixMap attribute found\n")); + talloc_free(schema_res); return WERR_FOOBAR; } @@ -550,9 +553,12 @@ WERROR dsdb_read_prefixes_from_ldb(TALLOC_CTX *mem_ctx, struct ldb_context *ldb, if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { DEBUG(0,("dsdb_read_prefixes_from_ldb: ndr_pull_struct_blob failed\n")); talloc_free(blob); + talloc_free(schema_res); return WERR_FOOBAR; } + talloc_free(schema_res); + if (blob->version != PREFIX_MAP_VERSION_DSDB) { DEBUG(0,("dsdb_read_prefixes_from_ldb: blob->version incorect\n")); talloc_free(blob); @@ -905,7 +911,7 @@ static int fetch_oc_recursive(struct ldb_context *ldb, struct ldb_dn *schemadn, const char *name = ldb_msg_find_attr_as_string(search_from->msgs[i], "lDAPDisplayname", NULL); - ret = ldb_search_exp_fmt(ldb, mem_ctx, &res, + ret = ldb_search(ldb, mem_ctx, &res, schemadn, LDB_SCOPE_SUBTREE, NULL, "(&(&(objectClass=classSchema)(subClassOf=%s))(!(lDAPDisplayName=%s)))", name, name); @@ -946,9 +952,9 @@ static int fetch_objectclass_schema(struct ldb_context *ldb, struct ldb_dn *sche } /* Download 'top' */ - ret = ldb_search(ldb, schemadn, LDB_SCOPE_SUBTREE, - "(&(objectClass=classSchema)(lDAPDisplayName=top))", - NULL, &top_res); + ret = ldb_search(ldb, local_ctx, &top_res, + schemadn, LDB_SCOPE_SUBTREE, NULL, + "(&(objectClass=classSchema)(lDAPDisplayName=top))"); if (ret != LDB_SUCCESS) { *error_string = talloc_asprintf(mem_ctx, "dsdb_schema: failed to search for top classSchema object: %s", @@ -956,8 +962,6 @@ static int fetch_objectclass_schema(struct ldb_context *ldb, struct ldb_dn *sche return ret; } - talloc_steal(local_ctx, top_res); - if (top_res->count != 1) { *error_string = talloc_asprintf(mem_ctx, "dsdb_schema: failed to find top classSchema object"); @@ -1008,10 +1012,8 @@ int dsdb_schema_from_schema_dn(TALLOC_CTX *mem_ctx, struct ldb_context *ldb, /* * setup the prefix mappings and schema info */ - ret = ldb_search(ldb, schema_dn, - LDB_SCOPE_BASE, - NULL, schema_attrs, - &schema_res); + ret = ldb_search(ldb, tmp_ctx, &schema_res, + schema_dn, LDB_SCOPE_BASE, schema_attrs, NULL); if (ret == LDB_ERR_NO_SUCH_OBJECT) { talloc_free(tmp_ctx); return ret; @@ -1022,7 +1024,6 @@ int dsdb_schema_from_schema_dn(TALLOC_CTX *mem_ctx, struct ldb_context *ldb, talloc_free(tmp_ctx); return ret; } - talloc_steal(tmp_ctx, schema_res); if (schema_res->count != 1) { *error_string_out = talloc_asprintf(mem_ctx, "dsdb_schema: [%u] schema heads found on a base search", @@ -1034,10 +1035,9 @@ int dsdb_schema_from_schema_dn(TALLOC_CTX *mem_ctx, struct ldb_context *ldb, /* * load the attribute definitions */ - ret = ldb_search(ldb, schema_dn, - LDB_SCOPE_ONELEVEL, - "(objectClass=attributeSchema)", NULL, - &a_res); + ret = ldb_search(ldb, tmp_ctx, &a_res, + schema_dn, LDB_SCOPE_ONELEVEL, NULL, + "(objectClass=attributeSchema)"); if (ret != LDB_SUCCESS) { *error_string_out = talloc_asprintf(mem_ctx, "dsdb_schema: failed to search attributeSchema objects: %s", @@ -1045,7 +1045,6 @@ int dsdb_schema_from_schema_dn(TALLOC_CTX *mem_ctx, struct ldb_context *ldb, talloc_free(tmp_ctx); return ret; } - talloc_steal(tmp_ctx, a_res); /* * load the objectClass definitions diff --git a/source4/dsdb/schema/schema_set.c b/source4/dsdb/schema/schema_set.c index 2303b88a05..b6e8ed46c2 100644 --- a/source4/dsdb/schema/schema_set.c +++ b/source4/dsdb/schema/schema_set.c @@ -116,7 +116,7 @@ static int dsdb_schema_set_attributes(struct ldb_context *ldb, struct dsdb_schem /* Try to avoid churning the attributes too much - we only want to do this if they have changed */ - ret = ldb_search_exp_fmt(ldb, mem_ctx, &res, msg->dn, LDB_SCOPE_BASE, NULL, "dn=%s", ldb_dn_get_linearized(msg->dn)); + ret = ldb_search(ldb, mem_ctx, &res, msg->dn, LDB_SCOPE_BASE, NULL, "dn=%s", ldb_dn_get_linearized(msg->dn)); if (ret == LDB_ERR_NO_SUCH_OBJECT) { ret = ldb_add(ldb, msg); } else if (ret != LDB_SUCCESS) { @@ -144,7 +144,7 @@ static int dsdb_schema_set_attributes(struct ldb_context *ldb, struct dsdb_schem /* Now write out the indexs, as found in the schema (if they have changed) */ - ret = ldb_search_exp_fmt(ldb, mem_ctx, &res_idx, msg_idx->dn, LDB_SCOPE_BASE, NULL, "dn=%s", ldb_dn_get_linearized(msg_idx->dn)); + ret = ldb_search(ldb, mem_ctx, &res_idx, msg_idx->dn, LDB_SCOPE_BASE, NULL, "dn=%s", ldb_dn_get_linearized(msg_idx->dn)); if (ret == LDB_ERR_NO_SUCH_OBJECT) { ret = ldb_add(ldb, msg_idx); } else if (ret != LDB_SUCCESS) { diff --git a/source4/kdc/hdb-ldb.c b/source4/kdc/hdb-ldb.c index ef3a0bcb8a..cfd72c25ac 100644 --- a/source4/kdc/hdb-ldb.c +++ b/source4/kdc/hdb-ldb.c @@ -929,8 +929,8 @@ static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_con return ENOMEM; } - lret = ldb_search(ldb_ctx, realm_dn, LDB_SCOPE_SUBTREE, filter, princ_attrs, &res); - + lret = ldb_search(ldb_ctx, mem_ctx, &res, realm_dn, + LDB_SCOPE_SUBTREE, princ_attrs, "%s", filter); if (lret != LDB_SUCCESS) { DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx))); return HDB_ERR_NOENTRY; @@ -963,8 +963,9 @@ static krb5_error_code LDB_lookup_trust(krb5_context context, struct ldb_context return ENOMEM; } - lret = ldb_search(ldb_ctx, ldb_get_default_basedn(ldb_ctx), LDB_SCOPE_SUBTREE, filter, attrs, &res); - + lret = ldb_search(ldb_ctx, mem_ctx, &res, + ldb_get_default_basedn(ldb_ctx), + LDB_SCOPE_SUBTREE, attrs, "%s", filter); if (lret != LDB_SUCCESS) { DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx))); return HDB_ERR_NOENTRY; @@ -988,7 +989,7 @@ static krb5_error_code LDB_lookup_realm(krb5_context context, struct ldb_context struct ldb_result *cross_ref_res; struct ldb_dn *partitions_basedn = samdb_partitions_dn(ldb_ctx, mem_ctx); - ret = ldb_search_exp_fmt(ldb_ctx, mem_ctx, &cross_ref_res, + ret = ldb_search(ldb_ctx, mem_ctx, &cross_ref_res, partitions_basedn, LDB_SCOPE_SUBTREE, realm_ref_attrs, "(&(&(|(&(dnsRoot=%s)(nETBIOSName=*))(nETBIOSName=%s))(objectclass=crossRef))(ncName=*))", realm, realm); @@ -1432,9 +1433,9 @@ static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flag priv->realm_ref_msgs = talloc_steal(priv, realm_ref_msgs); - lret = ldb_search(ldb_ctx, realm_dn, - LDB_SCOPE_SUBTREE, "(objectClass=user)", - user_attrs, &res); + lret = ldb_search(ldb_ctx, priv, &res, + realm_dn, LDB_SCOPE_SUBTREE, user_attrs, + "(objectClass=user)"); if (lret != LDB_SUCCESS) { talloc_free(priv); diff --git a/source4/ldap_server/ldap_backend.c b/source4/ldap_server/ldap_backend.c index 504dcf1c0f..b954038b80 100644 --- a/source4/ldap_server/ldap_backend.c +++ b/source4/ldap_server/ldap_backend.c @@ -688,8 +688,8 @@ reply: NT_STATUS_HAVE_NO_MEMORY(compare_r); if (result == LDAP_SUCCESS) { - ldb_ret = ldb_search(samdb, dn, LDB_SCOPE_BASE, filter, attrs, &res); - talloc_steal(local_ctx, res); + ldb_ret = ldb_search(samdb, local_ctx, &res, + dn, LDB_SCOPE_BASE, attrs, "%s", filter); if (ldb_ret != LDB_SUCCESS) { result = map_ldb_error(samdb, ldb_ret, &errstr); DEBUG(10,("CompareRequest: error: %s\n", errstr)); diff --git a/source4/ldap_server/ldap_server.c b/source4/ldap_server/ldap_server.c index 57a63a8516..0aa9afbdd6 100644 --- a/source4/ldap_server/ldap_server.c +++ b/source4/ldap_server/ldap_server.c @@ -253,13 +253,11 @@ static int ldapsrv_load_limits(struct ldapsrv_connection *conn) goto failed; } - ret = ldb_search(conn->ldb, basedn, LDB_SCOPE_BASE, NULL, attrs, &res); + ret = ldb_search(conn->ldb, tmp_ctx, &res, basedn, LDB_SCOPE_BASE, attrs, NULL); if (ret != LDB_SUCCESS) { goto failed; } - talloc_steal(tmp_ctx, res); - if (res->count != 1) { goto failed; } @@ -275,13 +273,11 @@ static int ldapsrv_load_limits(struct ldapsrv_connection *conn) goto failed; } - ret = ldb_search(conn->ldb, policy_dn, LDB_SCOPE_BASE, NULL, attrs2, &res); + ret = ldb_search(conn->ldb, tmp_ctx, &res, policy_dn, LDB_SCOPE_BASE, attrs2, NULL); if (ret != LDB_SUCCESS) { goto failed; } - talloc_steal(tmp_ctx, res); - if (res->count != 1) { goto failed; } diff --git a/source4/lib/ldb/common/ldb.c b/source4/lib/ldb/common/ldb.c index 9e04cc7845..3b73947b76 100644 --- a/source4/lib/ldb/common/ldb.c +++ b/source4/lib/ldb/common/ldb.c @@ -88,15 +88,14 @@ void ldb_set_default_dns(struct ldb_context *ldb) }; tmp_ctx = talloc_new(ldb); - ret = ldb_search(ldb, ldb_dn_new(tmp_ctx, ldb, NULL), LDB_SCOPE_BASE, - "(objectClass=*)", attrs, &res); + ret = ldb_search(ldb, tmp_ctx, &res, ldb_dn_new(tmp_ctx, ldb, NULL), + LDB_SCOPE_BASE, attrs, "(objectClass=*)"); if (ret != LDB_SUCCESS) { talloc_free(tmp_ctx); return; } if (res->count != 1) { - talloc_free(res); talloc_free(tmp_ctx); return; } @@ -125,7 +124,6 @@ void ldb_set_default_dns(struct ldb_context *ldb) ldb_set_opaque(ldb, "defaultNamingContext", tmp_dn); } - talloc_free(res); talloc_free(tmp_ctx); } @@ -873,25 +871,38 @@ done: note that ldb_search() will automatically replace a NULL 'base' value with the defaultNamingContext from the rootDSE if available. */ -int ldb_search(struct ldb_context *ldb, - struct ldb_dn *base, - enum ldb_scope scope, - const char *expression, - const char * const *attrs, - struct ldb_result **_res) +int ldb_search(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, + struct ldb_result **result, struct ldb_dn *base, + enum ldb_scope scope, const char * const *attrs, + const char *exp_fmt, ...) { struct ldb_request *req; - int ret; struct ldb_result *res; + char *expression; + va_list ap; + int ret; - *_res = NULL; + expression = NULL; + *result = NULL; + req = NULL; - res = talloc_zero(ldb, struct ldb_result); + res = talloc_zero(mem_ctx, struct ldb_result); if (!res) { return LDB_ERR_OPERATIONS_ERROR; } - ret = ldb_build_search_req(&req, ldb, ldb, + if (exp_fmt) { + va_start(ap, exp_fmt); + expression = talloc_vasprintf(mem_ctx, exp_fmt, ap); + va_end(ap); + + if (!expression) { + talloc_free(res); + return LDB_ERR_OPERATIONS_ERROR; + } + } + + ret = ldb_build_search_req(&req, ldb, mem_ctx, base?base:ldb_get_default_basedn(ldb), scope, expression, @@ -910,52 +921,16 @@ int ldb_search(struct ldb_context *ldb, ret = ldb_wait(req->handle, LDB_WAIT_ALL); } - talloc_free(req); - done: if (ret != LDB_SUCCESS) { talloc_free(res); - } - - *_res = res; - return ret; -} - -/* - a useful search function where you can easily define the expression and that - takes a memory context where results are allocated -*/ - -int ldb_search_exp_fmt(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, - struct ldb_result **result, struct ldb_dn *base, - enum ldb_scope scope, const char * const *attrs, - const char *exp_fmt, ...) -{ - struct ldb_result *res; - char *expression; - va_list ap; - int ret; - - res = NULL; - *result = NULL; - - va_start(ap, exp_fmt); - expression = talloc_vasprintf(mem_ctx, exp_fmt, ap); - va_end(ap); - - if ( ! expression) { - return LDB_ERR_OPERATIONS_ERROR; - } - - ret = ldb_search(ldb, base, scope, expression, attrs, &res); - - if (ret == LDB_SUCCESS) { - talloc_steal(mem_ctx, res); - *result = res; + res = NULL; } talloc_free(expression); + talloc_free(req); + *result = res; return ret; } diff --git a/source4/lib/ldb/common/ldb_modules.c b/source4/lib/ldb/common/ldb_modules.c index 4d69dc662e..c0cd616a76 100644 --- a/source4/lib/ldb/common/ldb_modules.c +++ b/source4/lib/ldb/common/ldb_modules.c @@ -419,7 +419,7 @@ int ldb_load_modules(struct ldb_context *ldb, const char *options[]) return -1; } - ret = ldb_search_exp_fmt(ldb, mods_dn, &res, mods_dn, LDB_SCOPE_BASE, attrs, "@LIST=*"); + ret = ldb_search(ldb, mods_dn, &res, mods_dn, LDB_SCOPE_BASE, attrs, "@LIST=*"); if (ret == LDB_ERR_NO_SUCH_OBJECT) { ldb_debug(ldb, LDB_DEBUG_TRACE, "no modules required by the db"); diff --git a/source4/lib/ldb/examples/ldbreader.c b/source4/lib/ldb/examples/ldbreader.c index 6e58114531..e48b3d338a 100644 --- a/source4/lib/ldb/examples/ldbreader.c +++ b/source4/lib/ldb/examples/ldbreader.c @@ -88,8 +88,9 @@ int main(int argc, const char **argv) quite fine grained results with the LDAP search syntax, however it is a bit confusing to start with. See RFC2254. */ - if (LDB_SUCCESS != ldb_search(ldb, NULL, LDB_SCOPE_DEFAULT, - expression, NULL, &resultMsg) ) { + if (LDB_SUCCESS != ldb_search(ldb, ldb, &resultMsg, + NULL, LDB_SCOPE_DEFAULT, NULL, + "%s", expression)) { printf("Problem in search\n"); exit(-1); } diff --git a/source4/lib/ldb/include/ldb.h b/source4/lib/ldb/include/ldb.h index 937029f52c..645d7866c5 100644 --- a/source4/lib/ldb/include/ldb.h +++ b/source4/lib/ldb/include/ldb.h @@ -1023,31 +1023,21 @@ struct ldb_control *ldb_request_get_control(struct ldb_request *req, const char records that match an LDAP-like search expression \param ldb the context associated with the database (from ldb_init()) + \param mem_ctx the memory context to use for the request and the results + \param result the return result \param base the Base Distinguished Name for the query (use ldb_dn_new() for an empty one) \param scope the search scope for the query - \param expression the search expression to use for this query \param attrs the search attributes for the query (pass NULL if none required) - \param res the return result + \param exp_fmt the search expression to use for this query (printf like) \return result code (LDB_SUCCESS on success, or a failure code) \note use talloc_free() to free the ldb_result returned */ -int ldb_search(struct ldb_context *ldb, - struct ldb_dn *base, - enum ldb_scope scope, - const char *expression, - const char * const *attrs, struct ldb_result **res); - -/* - * a useful search function where you can easily define the expression and - * that takes a memory context where results are allocated -*/ - -int ldb_search_exp_fmt(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, - struct ldb_result **result, struct ldb_dn *base, - enum ldb_scope scope, const char * const *attrs, - const char *exp_fmt, ...) PRINTF_ATTRIBUTE(7,8); +int ldb_search(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, + struct ldb_result **result, struct ldb_dn *base, + enum ldb_scope scope, const char * const *attrs, + const char *exp_fmt, ...) PRINTF_ATTRIBUTE(7,8); /** Add a record to the database. diff --git a/source4/lib/ldb/ldb.i b/source4/lib/ldb/ldb.i index e9496b503b..45978251f7 100644 --- a/source4/lib/ldb/ldb.i +++ b/source4/lib/ldb/ldb.i @@ -845,8 +845,7 @@ typedef struct ldb_context { %typemap(freearg,noblock=1) struct ldb_result **result_as_bool { talloc_free(*$1); } ldb_error __contains__(ldb_dn *dn, struct ldb_result **result_as_bool) { - return ldb_search($self, dn, LDB_SCOPE_BASE, NULL, NULL, - result_as_bool); + return ldb_search($self, $self, result_as_bool, dn, LDB_SCOPE_BASE, NULL, NULL); } %feature("docstring") parse_ldif "S.parse_ldif(ldif) -> iter(messages)\n" \ diff --git a/source4/lib/ldb/ldb_map/ldb_map.c b/source4/lib/ldb/ldb_map/ldb_map.c index b3f639dc67..e9129c812b 100644 --- a/source4/lib/ldb/ldb_map/ldb_map.c +++ b/source4/lib/ldb/ldb_map/ldb_map.c @@ -1256,7 +1256,7 @@ static int map_init_dns(struct ldb_module *module, struct ldb_map_context *data, return LDB_ERR_OPERATIONS_ERROR; } - ret = ldb_search(module->ldb, dn, LDB_SCOPE_BASE, NULL, attrs, &res); + ret = ldb_search(module->ldb, data, &res, dn, LDB_SCOPE_BASE, attrs, NULL); talloc_free(dn); if (ret != LDB_SUCCESS) { return ret; diff --git a/source4/lib/ldb/ldb_wrap.c b/source4/lib/ldb/ldb_wrap.c index 84e68d460e..74a59355aa 100644 --- a/source4/lib/ldb/ldb_wrap.c +++ b/source4/lib/ldb/ldb_wrap.c @@ -3204,8 +3204,8 @@ SWIGINTERN PyObject *ldb_schema_format_value(ldb *self,char const *element_name, return ret; } SWIGINTERN ldb_error ldb___contains__(ldb *self,ldb_dn *dn,struct ldb_result **result_as_bool){ - return ldb_search(self, dn, LDB_SCOPE_BASE, NULL, NULL, - result_as_bool); + return ldb_search(self, self, result_as_bool, + dn, LDB_SCOPE_BASE, NULL, NULL); } SWIGINTERN PyObject *ldb_parse_ldif(ldb *self,char const *s){ PyObject *list = PyList_New(0); diff --git a/source4/lib/ldb/nssldb/ldb-grp.c b/source4/lib/ldb/nssldb/ldb-grp.c index 71e27a9161..5e7556dc73 100644 --- a/source4/lib/ldb/nssldb/ldb-grp.c +++ b/source4/lib/ldb/nssldb/ldb-grp.c @@ -60,11 +60,12 @@ NSS_STATUS _nss_ldb_setgrent(void) } ret = ldb_search(_ldb_nss_ctx->ldb, + _ldb_nss_ctx->ldb, + &_ldb_nss_ctx->gr_res, _ldb_nss_ctx->base, LDB_SCOPE_SUBTREE, - _LDB_NSS_GRENT_FILTER, _ldb_nss_gr_attrs, - &_ldb_nss_ctx->gr_res); + _LDB_NSS_GRENT_FILTER); if (ret != LDB_SUCCESS) { return NSS_STATUS_UNAVAIL; } @@ -178,11 +179,12 @@ NSS_STATUS _nss_ldb_getgrnam_r(const char *name, struct group *result_buf, char /* search the entry */ ret = ldb_search(_ldb_nss_ctx->ldb, + _ldb_nss_ctx->ldb, + &gr_res, _ldb_nss_ctx->base, LDB_SCOPE_SUBTREE, - filter, _ldb_nss_gr_attrs, - &gr_res); + filter); if (ret != LDB_SUCCESS) { /* this is a fatal error */ *errnop = errno = ENOENT; @@ -275,11 +277,12 @@ NSS_STATUS _nss_ldb_getgrgid_r(gid_t gid, struct group *result_buf, char *buffer /* search the entry */ ret = ldb_search(_ldb_nss_ctx->ldb, + _ldb_nss_ctx->ldb, + &gr_res, _ldb_nss_ctx->base, LDB_SCOPE_SUBTREE, - filter, _ldb_nss_gr_attrs, - &gr_res); + filter); if (ret != LDB_SUCCESS) { /* this is a fatal error */ *errnop = errno = ENOENT; @@ -367,11 +370,12 @@ NSS_STATUS _nss_ldb_initgroups_dyn(const char *user, gid_t group, long int *star /* search the entry */ ret = ldb_search(_ldb_nss_ctx->ldb, + _ldb_nss_ctx->ldb, + &uid_res, _ldb_nss_ctx->base, LDB_SCOPE_SUBTREE, - filter, attrs, - &uid_res); + filter); if (ret != LDB_SUCCESS) { /* this is a fatal error */ *errnop = errno = ENOENT; diff --git a/source4/lib/ldb/nssldb/ldb-pwd.c b/source4/lib/ldb/nssldb/ldb-pwd.c index 44b0ab21ee..6ab103a6fe 100644 --- a/source4/lib/ldb/nssldb/ldb-pwd.c +++ b/source4/lib/ldb/nssldb/ldb-pwd.c @@ -47,11 +47,12 @@ NSS_STATUS _nss_ldb_setpwent(void) } ret = ldb_search(_ldb_nss_ctx->ldb, + _ldb_nss_ctx->ldb, + &_ldb_nss_ctx->pw_res, _ldb_nss_ctx->base, LDB_SCOPE_SUBTREE, - _LDB_NSS_PWENT_FILTER, _ldb_nss_pw_attrs, - &_ldb_nss_ctx->pw_res); + _LDB_NSS_PWENT_FILTER); if (ret != LDB_SUCCESS) { return NSS_STATUS_UNAVAIL; } @@ -137,11 +138,12 @@ NSS_STATUS _nss_ldb_getpwuid_r(uid_t uid, struct passwd *result_buf, char *buffe /* search the entry */ ret = ldb_search(_ldb_nss_ctx->ldb, + _ldb_nss_ctx->ldb, + &res, _ldb_nss_ctx->base, LDB_SCOPE_SUBTREE, - filter, _ldb_nss_pw_attrs, - &res); + filter); if (ret != LDB_SUCCESS) { /* this is a fatal error */ *errnop = errno = ENOENT; @@ -198,11 +200,12 @@ NSS_STATUS _nss_ldb_getpwnam_r(const char *name, struct passwd *result_buf, char /* search the entry */ ret = ldb_search(_ldb_nss_ctx->ldb, + _ldb_nss_ctx->ldb, + &res, _ldb_nss_ctx->base, LDB_SCOPE_SUBTREE, - filter, _ldb_nss_pw_attrs, - &res); + filter); if (ret != LDB_SUCCESS) { /* this is a fatal error */ *errnop = errno = ENOENT; diff --git a/source4/lib/ldb/tools/ldbdel.c b/source4/lib/ldb/tools/ldbdel.c index e66d4fb973..22d4aa6976 100644 --- a/source4/lib/ldb/tools/ldbdel.c +++ b/source4/lib/ldb/tools/ldbdel.c @@ -40,7 +40,7 @@ static int ldb_delete_recursive(struct ldb_context *ldb, struct ldb_dn *dn) const char *attrs[] = { NULL }; struct ldb_result *res; - ret = ldb_search(ldb, dn, LDB_SCOPE_SUBTREE, "distinguishedName=*", attrs, &res); + ret = ldb_search(ldb, ldb, &res, dn, LDB_SCOPE_SUBTREE, attrs, "distinguishedName=*"); if (ret != LDB_SUCCESS) return -1; for (i = 0; i < res->count; i++) { diff --git a/source4/lib/ldb/tools/ldbedit.c b/source4/lib/ldb/tools/ldbedit.c index e58a5a271e..b2a040cd09 100644 --- a/source4/lib/ldb/tools/ldbedit.c +++ b/source4/lib/ldb/tools/ldbedit.c @@ -303,7 +303,7 @@ int main(int argc, const char **argv) } } - ret = ldb_search(ldb, basedn, options->scope, expression, attrs, &result); + ret = ldb_search(ldb, ldb, &result, basedn, options->scope, attrs, "%s", expression); if (ret != LDB_SUCCESS) { printf("search failed - %s\n", ldb_errstring(ldb)); exit(1); diff --git a/source4/lib/ldb/tools/ldbtest.c b/source4/lib/ldb/tools/ldbtest.c index 169ff02da1..f3d6d621a9 100644 --- a/source4/lib/ldb/tools/ldbtest.c +++ b/source4/lib/ldb/tools/ldbtest.c @@ -227,7 +227,7 @@ static void search_uid(struct ldb_context *ldb, struct ldb_dn *basedn, int nreco int ret; expr = talloc_asprintf(ldb, "(uid=TEST%d)", uid); - ret = ldb_search(ldb, basedn, LDB_SCOPE_SUBTREE, expr, NULL, &res); + ret = ldb_search(ldb, ldb, &res, basedn, LDB_SCOPE_SUBTREE, NULL, "%s", expr); if (ret != LDB_SUCCESS || (uid < nrecords && res->count != 1)) { printf("Failed to find %s - %s\n", expr, ldb_errstring(ldb)); @@ -354,7 +354,7 @@ static void start_test_index(struct ldb_context **ldb) basedn = ldb_dn_new(*ldb, *ldb, options->basedn); - ret = ldb_search(*ldb, basedn, LDB_SCOPE_SUBTREE, "uid=test", NULL, &res); + ret = ldb_search(*ldb, *ldb, &res, basedn, LDB_SCOPE_SUBTREE, NULL, "uid=test"); if (ret != LDB_SUCCESS) { printf("Search with (uid=test) filter failed!\n"); exit(1); diff --git a/source4/lib/registry/ldb.c b/source4/lib/registry/ldb.c index a8a9ed597e..25b8c583ed 100644 --- a/source4/lib/registry/ldb.c +++ b/source4/lib/registry/ldb.c @@ -199,7 +199,7 @@ static WERROR cache_subkeys(struct ldb_key_data *kd) struct ldb_result *res; int ret; - ret = ldb_search(c, kd->dn, LDB_SCOPE_ONELEVEL, "(key=*)", NULL, &res); + ret = ldb_search(c, c, &res, kd->dn, LDB_SCOPE_ONELEVEL, NULL, "(key=*)"); if (ret != LDB_SUCCESS) { DEBUG(0, ("Error getting subkeys for '%s': %s\n", @@ -220,8 +220,8 @@ static WERROR cache_values(struct ldb_key_data *kd) struct ldb_result *res; int ret; - ret = ldb_search(c, kd->dn, LDB_SCOPE_ONELEVEL, - "(value=*)", NULL, &res); + ret = ldb_search(c, c, &res, kd->dn, LDB_SCOPE_ONELEVEL, + NULL, "(value=*)"); if (ret != LDB_SUCCESS) { DEBUG(0, ("Error getting values for '%s': %s\n", @@ -299,21 +299,25 @@ static WERROR ldb_get_value(TALLOC_CTX *mem_ctx, struct hive_key *k, int ret; char *query = talloc_asprintf(mem_ctx, "(value=%s)", name); - ret = ldb_search(c, kd->dn, LDB_SCOPE_ONELEVEL, query, NULL, &res); + ret = ldb_search(c, mem_ctx, &res, kd->dn, LDB_SCOPE_ONELEVEL, NULL, "%s", query); talloc_free(query); if (ret != LDB_SUCCESS) { DEBUG(0, ("Error getting values for '%s': %s\n", ldb_dn_get_linearized(kd->dn), ldb_errstring(c))); + talloc_free(res); return WERR_FOOBAR; } - if (res->count == 0) + if (res->count == 0) { + talloc_free(res); return WERR_BADFILE; + } reg_ldb_unpack_value(mem_ctx, lp_iconv_convenience(global_loadparm), res->msgs[0], NULL, data_type, data); + talloc_free(res); return WERR_OK; } @@ -329,7 +333,7 @@ static WERROR ldb_open_key(TALLOC_CTX *mem_ctx, const struct hive_key *h, ldap_path = reg_path_to_ldb(mem_ctx, h, name, NULL); - ret = ldb_search(c, ldap_path, LDB_SCOPE_BASE, "(key=*)", NULL, &res); + ret = ldb_search(c, mem_ctx, &res, ldap_path, LDB_SCOPE_BASE, NULL, "(key=*)"); if (ret != LDB_SUCCESS) { DEBUG(3, ("Error opening key '%s': %s\n", @@ -501,8 +505,8 @@ static WERROR ldb_del_key(const struct hive_key *key, const char *name) } /* Search for subkeys */ - ret = ldb_search(c, ldap_path, LDB_SCOPE_ONELEVEL, - "(key=*)", NULL, &res_keys); + ret = ldb_search(c, mem_ctx, &res_keys, ldap_path, LDB_SCOPE_ONELEVEL, + NULL, "(key=*)"); if (ret != LDB_SUCCESS) { DEBUG(0, ("Error getting subkeys for '%s': %s\n", @@ -512,8 +516,8 @@ static WERROR ldb_del_key(const struct hive_key *key, const char *name) } /* Search for values */ - ret = ldb_search(c, ldap_path, LDB_SCOPE_ONELEVEL, - "(value=*)", NULL, &res_vals); + ret = ldb_search(c, mem_ctx, &res_vals, ldap_path, LDB_SCOPE_ONELEVEL, + NULL, "(value=*)"); if (ret != LDB_SUCCESS) { DEBUG(0, ("Error getting values for '%s': %s\n", diff --git a/source4/lib/util/util_ldb.c b/source4/lib/util/util_ldb.c index fab729c036..0465022edd 100644 --- a/source4/lib/util/util_ldb.c +++ b/source4/lib/util/util_ldb.c @@ -52,7 +52,8 @@ int gendb_search_v(struct ldb_context *ldb, res = NULL; - ret = ldb_search(ldb, basedn, scope, expr, attrs, &res); + ret = ldb_search(ldb, mem_ctx, &res, basedn, scope, attrs, + expr?"%s":NULL, expr); if (ret == LDB_SUCCESS) { talloc_steal(mem_ctx, res->msgs); diff --git a/source4/libnet/libnet_become_dc.c b/source4/libnet/libnet_become_dc.c index 332b041e36..b9071d5eb1 100644 --- a/source4/libnet/libnet_become_dc.c +++ b/source4/libnet/libnet_become_dc.c @@ -820,8 +820,8 @@ static NTSTATUS becomeDC_ldap1_rootdse(struct libnet_BecomeDC_state *s) basedn = ldb_dn_new(s, s->ldap1.ldb, NULL); NT_STATUS_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, basedn, LDB_SCOPE_BASE, attrs, + "(objectClass=*)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); @@ -829,7 +829,6 @@ static NTSTATUS becomeDC_ldap1_rootdse(struct libnet_BecomeDC_state *s) talloc_free(r); return NT_STATUS_INVALID_NETWORK_RESPONSE; } - talloc_steal(s, r); s->ldap1.rootdse = r->msgs[0]; @@ -864,8 +863,8 @@ static NTSTATUS becomeDC_ldap1_crossref_behavior_version(struct libnet_BecomeDC_ basedn = ldb_dn_new(s, s->ldap1.ldb, s->forest.config_dn_str); NT_STATUS_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_ONELEVEL, - "(cn=Partitions)", attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, basedn, LDB_SCOPE_ONELEVEL, attrs, + "(cn=Partitions)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); @@ -893,8 +892,8 @@ static NTSTATUS becomeDC_ldap1_domain_behavior_version(struct libnet_BecomeDC_st basedn = ldb_dn_new(s, s->ldap1.ldb, s->domain.dn_str); NT_STATUS_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, basedn, LDB_SCOPE_BASE, attrs, + "(objectClass=*)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); @@ -922,8 +921,8 @@ static NTSTATUS becomeDC_ldap1_schema_object_version(struct libnet_BecomeDC_stat basedn = ldb_dn_new(s, s->ldap1.ldb, s->forest.schema_dn_str); NT_STATUS_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, basedn, LDB_SCOPE_BASE, attrs, + "(objectClass=*)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); @@ -952,8 +951,8 @@ static NTSTATUS becomeDC_ldap1_w2k3_update_revision(struct libnet_BecomeDC_state s->domain.dn_str); NT_STATUS_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, basedn, LDB_SCOPE_BASE, attrs, + "(objectClass=*)"); talloc_free(basedn); if (ret == LDB_ERR_NO_SUCH_OBJECT) { /* w2k doesn't have this object */ @@ -1000,8 +999,8 @@ static NTSTATUS becomeDC_ldap1_infrastructure_fsmo(struct libnet_BecomeDC_state s->domain.dn_str); NT_STATUS_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", _1_1_attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, basedn, LDB_SCOPE_BASE, + _1_1_attrs, "(objectClass=*)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); @@ -1013,8 +1012,8 @@ static NTSTATUS becomeDC_ldap1_infrastructure_fsmo(struct libnet_BecomeDC_state basedn = talloc_steal(s, r->msgs[0]->dn); talloc_free(r); - ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", fsmo_attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, basedn, LDB_SCOPE_BASE, + fsmo_attrs, "(objectClass=*)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); @@ -1038,8 +1037,8 @@ static NTSTATUS becomeDC_ldap1_infrastructure_fsmo(struct libnet_BecomeDC_state s->infrastructure_fsmo.server_dn_str = ldb_dn_alloc_linearized(s, server_dn); NT_STATUS_HAVE_NO_MEMORY(s->infrastructure_fsmo.server_dn_str); - ret = ldb_search(s->ldap1.ldb, server_dn, LDB_SCOPE_BASE, - "(objectClass=*)", dns_attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, server_dn, LDB_SCOPE_BASE, + dns_attrs, "(objectClass=*)"); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); } else if (r->count != 1) { @@ -1053,8 +1052,8 @@ static NTSTATUS becomeDC_ldap1_infrastructure_fsmo(struct libnet_BecomeDC_state talloc_free(r); - ret = ldb_search(s->ldap1.ldb, ntds_dn, LDB_SCOPE_BASE, - "(objectClass=*)", guid_attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, ntds_dn, LDB_SCOPE_BASE, + guid_attrs, "(objectClass=*)"); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); } else if (r->count != 1) { @@ -1097,8 +1096,8 @@ static NTSTATUS becomeDC_ldap1_rid_manager_fsmo(struct libnet_BecomeDC_state *s) basedn = ldb_dn_new(s, s->ldap1.ldb, s->domain.dn_str); NT_STATUS_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", rid_attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, basedn, LDB_SCOPE_BASE, + rid_attrs, "(objectClass=*)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); @@ -1115,8 +1114,8 @@ static NTSTATUS becomeDC_ldap1_rid_manager_fsmo(struct libnet_BecomeDC_state *s) talloc_free(r); - ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", fsmo_attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, basedn, LDB_SCOPE_BASE, + fsmo_attrs, "(objectClass=*)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); @@ -1140,8 +1139,8 @@ static NTSTATUS becomeDC_ldap1_rid_manager_fsmo(struct libnet_BecomeDC_state *s) s->rid_manager_fsmo.server_dn_str = ldb_dn_alloc_linearized(s, server_dn); NT_STATUS_HAVE_NO_MEMORY(s->rid_manager_fsmo.server_dn_str); - ret = ldb_search(s->ldap1.ldb, server_dn, LDB_SCOPE_BASE, - "(objectClass=*)", dns_attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, server_dn, LDB_SCOPE_BASE, + dns_attrs, "(objectClass=*)"); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); } else if (r->count != 1) { @@ -1155,8 +1154,8 @@ static NTSTATUS becomeDC_ldap1_rid_manager_fsmo(struct libnet_BecomeDC_state *s) talloc_free(r); - ret = ldb_search(s->ldap1.ldb, ntds_dn, LDB_SCOPE_BASE, - "(objectClass=*)", guid_attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, ntds_dn, LDB_SCOPE_BASE, + guid_attrs, "(objectClass=*)"); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); } else if (r->count != 1) { @@ -1182,8 +1181,8 @@ static NTSTATUS becomeDC_ldap1_site_object(struct libnet_BecomeDC_state *s) s->forest.config_dn_str); NT_STATUS_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", NULL, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, basedn, LDB_SCOPE_BASE, + NULL, "(objectClass=*)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); @@ -1214,7 +1213,6 @@ static NTSTATUS becomeDC_ldap1_computer_object(struct libnet_BecomeDC_state *s) int ret; struct ldb_result *r; struct ldb_dn *basedn; - char *filter; static const char *attrs[] = { "distinguishedName", "userAccountControl", @@ -1224,12 +1222,9 @@ static NTSTATUS becomeDC_ldap1_computer_object(struct libnet_BecomeDC_state *s) basedn = ldb_dn_new(s, s->ldap1.ldb, s->domain.dn_str); NT_STATUS_HAVE_NO_MEMORY(basedn); - filter = talloc_asprintf(basedn, "(&(|(objectClass=user)(objectClass=computer))(sAMAccountName=%s$))", - s->dest_dsa.netbios_name); - NT_STATUS_HAVE_NO_MEMORY(filter); - - ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_SUBTREE, - filter, attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, basedn, LDB_SCOPE_SUBTREE, attrs, + "(&(|(objectClass=user)(objectClass=computer))(sAMAccountName=%s$))", + s->dest_dsa.netbios_name); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); @@ -1263,8 +1258,8 @@ static NTSTATUS becomeDC_ldap1_server_object_1(struct libnet_BecomeDC_state *s) s->forest.config_dn_str); NT_STATUS_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", NULL, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, basedn, LDB_SCOPE_BASE, + NULL, "(objectClass=*)"); talloc_free(basedn); if (ret == LDB_ERR_NO_SUCH_OBJECT) { /* if the object doesn't exist, we'll create it later */ @@ -1320,8 +1315,8 @@ static NTSTATUS becomeDC_ldap1_server_object_2(struct libnet_BecomeDC_state *s) basedn = ldb_dn_new(s, s->ldap1.ldb, s->dest_dsa.computer_dn_str); NT_STATUS_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", attrs, &r); + ret = ldb_search(s->ldap1.ldb, s, &r, basedn, LDB_SCOPE_BASE, + attrs, "(objectClass=*)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); @@ -2908,8 +2903,8 @@ static NTSTATUS becomeDC_ldap2_move_computer(struct libnet_BecomeDC_state *s) s->domain.dn_str); NT_STATUS_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->ldap2.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", _1_1_attrs, &r); + ret = ldb_search(s->ldap2.ldb, s, &r, basedn, LDB_SCOPE_BASE, + _1_1_attrs, "(objectClass=*)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); diff --git a/source4/libnet/libnet_join.c b/source4/libnet/libnet_join.c index 5776888cb0..43f8648921 100644 --- a/source4/libnet/libnet_join.c +++ b/source4/libnet/libnet_join.c @@ -248,8 +248,8 @@ static NTSTATUS libnet_JoinADSDomain(struct libnet_context *ctx, struct libnet_J } /* search for the user's record */ - ret = ldb_search(remote_ldb, account_dn, LDB_SCOPE_BASE, - NULL, attrs, &res); + ret = ldb_search(remote_ldb, tmp_ctx, &res, + account_dn, LDB_SCOPE_BASE, attrs, NULL); if (ret != LDB_SUCCESS) { r->out.error_string = talloc_asprintf(r, "ldb_search for %s failed - %s", account_dn_str, ldb_errstring(remote_ldb)); @@ -257,8 +257,6 @@ static NTSTATUS libnet_JoinADSDomain(struct libnet_context *ctx, struct libnet_J return NT_STATUS_UNSUCCESSFUL; } - talloc_steal(tmp_ctx, res); - if (res->count != 1) { r->out.error_string = talloc_asprintf(r, "ldb_search for %s failed - found %d entries", account_dn_str, res->count); diff --git a/source4/libnet/libnet_unbecome_dc.c b/source4/libnet/libnet_unbecome_dc.c index 6a42fa2370..4eeaf1b80c 100644 --- a/source4/libnet/libnet_unbecome_dc.c +++ b/source4/libnet/libnet_unbecome_dc.c @@ -337,8 +337,8 @@ static NTSTATUS unbecomeDC_ldap_rootdse(struct libnet_UnbecomeDC_state *s) basedn = ldb_dn_new(s, s->ldap.ldb, NULL); NT_STATUS_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->ldap.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", attrs, &r); + ret = ldb_search(s->ldap.ldb, s, &r, basedn, LDB_SCOPE_BASE, attrs, + "(objectClass=*)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); @@ -346,7 +346,6 @@ static NTSTATUS unbecomeDC_ldap_rootdse(struct libnet_UnbecomeDC_state *s) talloc_free(r); return NT_STATUS_INVALID_NETWORK_RESPONSE; } - talloc_steal(s, r); s->domain.dn_str = ldb_msg_find_attr_as_string(r->msgs[0], "defaultNamingContext", NULL); if (!s->domain.dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE; @@ -371,7 +370,6 @@ static NTSTATUS unbecomeDC_ldap_computer_object(struct libnet_UnbecomeDC_state * int ret; struct ldb_result *r; struct ldb_dn *basedn; - char *filter; static const char *attrs[] = { "distinguishedName", "userAccountControl", @@ -381,12 +379,9 @@ static NTSTATUS unbecomeDC_ldap_computer_object(struct libnet_UnbecomeDC_state * basedn = ldb_dn_new(s, s->ldap.ldb, s->domain.dn_str); NT_STATUS_HAVE_NO_MEMORY(basedn); - filter = talloc_asprintf(basedn, "(&(|(objectClass=user)(objectClass=computer))(sAMAccountName=%s$))", - s->dest_dsa.netbios_name); - NT_STATUS_HAVE_NO_MEMORY(filter); - - ret = ldb_search(s->ldap.ldb, basedn, LDB_SCOPE_SUBTREE, - filter, attrs, &r); + ret = ldb_search(s->ldap.ldb, s, &r, basedn, LDB_SCOPE_SUBTREE, attrs, + "(&(|(objectClass=user)(objectClass=computer))(sAMAccountName=%s$))", + s->dest_dsa.netbios_name); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); @@ -462,8 +457,8 @@ static NTSTATUS unbecomeDC_ldap_move_computer(struct libnet_UnbecomeDC_state *s) s->domain.dn_str); NT_STATUS_HAVE_NO_MEMORY(basedn); - ret = ldb_search(s->ldap.ldb, basedn, LDB_SCOPE_BASE, - "(objectClass=*)", _1_1_attrs, &r); + ret = ldb_search(s->ldap.ldb, s, &r, basedn, LDB_SCOPE_BASE, + _1_1_attrs, "(objectClass=*)"); talloc_free(basedn); if (ret != LDB_SUCCESS) { return NT_STATUS_LDAP(ret); diff --git a/source4/nbt_server/wins/winsdb.c b/source4/nbt_server/wins/winsdb.c index c84b01f2b2..283cd1219a 100644 --- a/source4/nbt_server/wins/winsdb.c +++ b/source4/nbt_server/wins/winsdb.c @@ -45,10 +45,8 @@ uint64_t winsdb_get_maxVersion(struct winsdb_handle *h) if (!dn) goto failed; /* find the record in the WINS database */ - ret = ldb_search(ldb, dn, LDB_SCOPE_BASE, - NULL, NULL, &res); + ret = ldb_search(ldb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, NULL, NULL); if (ret != LDB_SUCCESS) goto failed; - talloc_steal(tmp_ctx, res); if (res->count > 1) goto failed; if (res->count == 1) { @@ -82,14 +80,10 @@ uint64_t winsdb_set_maxVersion(struct winsdb_handle *h, uint64_t newMaxVersion) if (!dn) goto failed; /* find the record in the WINS database */ - ret = ldb_search(wins_db, dn, LDB_SCOPE_BASE, NULL, NULL, &res); - + ret = ldb_search(wins_db, tmp_ctx, &res, dn, LDB_SCOPE_BASE, NULL, NULL); if (ret != LDB_SUCCESS) goto failed; - talloc_steal(tmp_ctx, res); if (res->count > 1) goto failed; - talloc_steal(tmp_ctx, res); - if (res->count == 1) { oldMaxVersion = ldb_msg_find_attr_as_uint64(res->msgs[0], "maxVersion", 0); } @@ -143,10 +137,8 @@ uint64_t winsdb_get_seqnumber(struct winsdb_handle *h) if (!dn) goto failed; /* find the record in the WINS database */ - ret = ldb_search(ldb, dn, LDB_SCOPE_BASE, - NULL, NULL, &res); + ret = ldb_search(ldb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, NULL, NULL); if (ret != LDB_SUCCESS) goto failed; - talloc_steal(tmp_ctx, res); if (res->count > 1) goto failed; if (res->count == 1) { @@ -589,10 +581,10 @@ NTSTATUS winsdb_lookup(struct winsdb_handle *h, time_t now = time(NULL); /* find the record in the WINS database */ - ret = ldb_search(wins_db, winsdb_dn(tmp_ctx, wins_db, name), LDB_SCOPE_BASE, - NULL, NULL, &res); + ret = ldb_search(wins_db, tmp_ctx, &res, + winsdb_dn(tmp_ctx, wins_db, name), + LDB_SCOPE_BASE, NULL, NULL); - talloc_steal(tmp_ctx, res); if (ret != LDB_SUCCESS || res->count > 1) { status = NT_STATUS_INTERNAL_DB_CORRUPTION; goto failed; @@ -964,9 +956,8 @@ static bool winsdb_check_or_add_module_list(struct event_context *ev_ctx, if (!dn) goto failed; /* find the record in the WINS database */ - ret = ldb_search(h->ldb, dn, LDB_SCOPE_BASE, NULL, NULL, &res); + ret = ldb_search(h->ldb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, NULL, NULL); if (ret != LDB_SUCCESS) goto failed; - talloc_steal(tmp_ctx, res); if (res->count > 0) goto skip; diff --git a/source4/ntp_signd/ntp_signd.c b/source4/ntp_signd/ntp_signd.c index 8bcf258e5e..c3a9a1c792 100644 --- a/source4/ntp_signd/ntp_signd.c +++ b/source4/ntp_signd/ntp_signd.c @@ -166,7 +166,7 @@ static NTSTATUS ntp_signd_recv(void *private, DATA_BLOB wrapped_input) return signing_failure(ntp_signdconn, sign_request.packet_id); } - ret = ldb_search_exp_fmt(ntp_signdconn->ntp_signd->samdb, tmp_ctx, + ret = ldb_search(ntp_signdconn->ntp_signd->samdb, tmp_ctx, &res, samdb_base_dn(ntp_signdconn->ntp_signd->samdb), LDB_SCOPE_SUBTREE, attrs, "(&(objectSid=%s)(objectClass=user))", dom_sid_string(tmp_ctx, sid)); diff --git a/source4/param/share_ldb.c b/source4/param/share_ldb.c index eba1665cc9..4896a71048 100644 --- a/source4/param/share_ldb.c +++ b/source4/param/share_ldb.c @@ -174,8 +174,8 @@ static NTSTATUS sldb_list_all(TALLOC_CTX *mem_ctx, ldb = talloc_get_type(ctx->priv_data, struct ldb_context); - ret = ldb_search(ldb, ldb_dn_new(tmp_ctx, ldb, "CN=SHARES"), LDB_SCOPE_SUBTREE, "(name=*)", NULL, &res); - talloc_steal(tmp_ctx, res); + ret = ldb_search(ldb, tmp_ctx, &res, ldb_dn_new(tmp_ctx, ldb, "CN=SHARES"), + LDB_SCOPE_SUBTREE, NULL, "(name=*)"); if (ret != LDB_SUCCESS) { talloc_free(tmp_ctx); return NT_STATUS_INTERNAL_DB_CORRUPTION; @@ -223,7 +223,7 @@ static NTSTATUS sldb_get_config(TALLOC_CTX *mem_ctx, ldb = talloc_get_type(ctx->priv_data, struct ldb_context); - ret = ldb_search_exp_fmt(ldb, tmp_ctx, &res, + ret = ldb_search(ldb, tmp_ctx, &res, ldb_dn_new(tmp_ctx, ldb, "CN=SHARES"), LDB_SCOPE_SUBTREE, NULL, "(name=%s)", name); if (ret != LDB_SUCCESS || res->count > 1) { diff --git a/source4/rpc_server/drsuapi/dcesrv_drsuapi.c b/source4/rpc_server/drsuapi/dcesrv_drsuapi.c index bbb78cb778..d555ba27bf 100644 --- a/source4/rpc_server/drsuapi/dcesrv_drsuapi.c +++ b/source4/rpc_server/drsuapi/dcesrv_drsuapi.c @@ -69,7 +69,7 @@ static WERROR dcesrv_drsuapi_DsBind(struct dcesrv_call_state *dce_call, TALLOC_C server_site_dn = samdb_server_site_dn(b_state->sam_ctx, mem_ctx); W_ERROR_HAVE_NO_MEMORY(server_site_dn); - ret = ldb_search_exp_fmt(b_state->sam_ctx, mem_ctx, &site_res, + ret = ldb_search(b_state->sam_ctx, mem_ctx, &site_res, server_site_dn, LDB_SCOPE_BASE, site_attrs, "(objectClass=*)"); if (ret != LDB_SUCCESS) { @@ -86,7 +86,7 @@ static WERROR dcesrv_drsuapi_DsBind(struct dcesrv_call_state *dce_call, TALLOC_C ntds_dn = samdb_ntds_settings_dn(b_state->sam_ctx); W_ERROR_HAVE_NO_MEMORY(ntds_dn); - ret = ldb_search_exp_fmt(b_state->sam_ctx, mem_ctx, &ntds_res, + ret = ldb_search(b_state->sam_ctx, mem_ctx, &ntds_res, ntds_dn, LDB_SCOPE_BASE, ntds_attrs, "(objectClass=*)"); if (ret != LDB_SUCCESS) { @@ -540,7 +540,7 @@ static WERROR dcesrv_drsuapi_DsGetDomainControllerInfo_1(struct drsuapi_bind_sta return WERR_UNKNOWN_LEVEL; } - ret = ldb_search_exp_fmt(b_state->sam_ctx, mem_ctx, &res, sites_dn, LDB_SCOPE_SUBTREE, attrs, + ret = ldb_search(b_state->sam_ctx, mem_ctx, &res, sites_dn, LDB_SCOPE_SUBTREE, attrs, "objectClass=server"); if (ret) { @@ -571,7 +571,7 @@ static WERROR dcesrv_drsuapi_DsGetDomainControllerInfo_1(struct drsuapi_bind_sta return WERR_NOMEM; } - ret = ldb_search_exp_fmt(b_state->sam_ctx, mem_ctx, &res_account, ref_dn, + ret = ldb_search(b_state->sam_ctx, mem_ctx, &res_account, ref_dn, LDB_SCOPE_BASE, attrs_account_1, "objectClass=computer"); if (ret == LDB_SUCCESS && res_account->count == 1) { const char *errstr; @@ -588,7 +588,7 @@ static WERROR dcesrv_drsuapi_DsGetDomainControllerInfo_1(struct drsuapi_bind_sta &domain_dn, &errstr); if (ret == LDB_SUCCESS) { - ret = ldb_search_exp_fmt(b_state->sam_ctx, mem_ctx, &res_domain, domain_dn, + ret = ldb_search(b_state->sam_ctx, mem_ctx, &res_domain, domain_dn, LDB_SCOPE_BASE, attrs_none, "fSMORoleOwner=%s", ldb_dn_get_linearized(ntds_dn)); if (ret) { @@ -641,7 +641,7 @@ static WERROR dcesrv_drsuapi_DsGetDomainControllerInfo_1(struct drsuapi_bind_sta return WERR_NOMEM; } - ret = ldb_search_exp_fmt(b_state->sam_ctx, mem_ctx, &res_ntds, ntds_dn, + ret = ldb_search(b_state->sam_ctx, mem_ctx, &res_ntds, ntds_dn, LDB_SCOPE_BASE, attrs_ntds, "objectClass=nTDSDSA"); if (ret == LDB_SUCCESS && res_ntds->count == 1) { ctr2->array[i].is_gc @@ -655,7 +655,7 @@ static WERROR dcesrv_drsuapi_DsGetDomainControllerInfo_1(struct drsuapi_bind_sta ldb_dn_get_linearized(ntds_dn), ldb_errstring(b_state->sam_ctx))); } - ret = ldb_search_exp_fmt(b_state->sam_ctx, mem_ctx, &res_site, site_dn, + ret = ldb_search(b_state->sam_ctx, mem_ctx, &res_site, site_dn, LDB_SCOPE_BASE, attrs_site, "objectClass=site"); if (ret == LDB_SUCCESS && res_site->count == 1) { ctr2->array[i].site_guid @@ -667,7 +667,7 @@ static WERROR dcesrv_drsuapi_DsGetDomainControllerInfo_1(struct drsuapi_bind_sta ldb_dn_get_linearized(site_dn), ldb_errstring(b_state->sam_ctx))); } - ret = ldb_search_exp_fmt(b_state->sam_ctx, mem_ctx, &res_account, ref_dn, + ret = ldb_search(b_state->sam_ctx, mem_ctx, &res_account, ref_dn, LDB_SCOPE_BASE, attrs_account_2, "objectClass=computer"); if (ret == LDB_SUCCESS && res_account->count == 1) { const char *errstr; @@ -685,7 +685,7 @@ static WERROR dcesrv_drsuapi_DsGetDomainControllerInfo_1(struct drsuapi_bind_sta &domain_dn, &errstr); if (ret == LDB_SUCCESS) { - ret = ldb_search_exp_fmt(b_state->sam_ctx, mem_ctx, &res_domain, domain_dn, + ret = ldb_search(b_state->sam_ctx, mem_ctx, &res_domain, domain_dn, LDB_SCOPE_BASE, attrs_none, "fSMORoleOwner=%s", ldb_dn_get_linearized(ntds_dn)); if (ret == LDB_SUCCESS && res_domain->count == 1) { diff --git a/source4/rpc_server/lsa/lsa_init.c b/source4/rpc_server/lsa/lsa_init.c index 0dc21fd9c5..e5e31c74f8 100644 --- a/source4/rpc_server/lsa/lsa_init.c +++ b/source4/rpc_server/lsa/lsa_init.c @@ -71,12 +71,11 @@ NTSTATUS dcesrv_lsa_get_policy_state(struct dcesrv_call_state *dce_call, TALLOC_ return NT_STATUS_NO_MEMORY; } - ret = ldb_search(state->sam_ldb, state->domain_dn, LDB_SCOPE_BASE, NULL, dom_attrs, &dom_res); - + ret = ldb_search(state->sam_ldb, mem_ctx, &dom_res, + state->domain_dn, LDB_SCOPE_BASE, dom_attrs, NULL); if (ret != LDB_SUCCESS) { return NT_STATUS_INVALID_SYSTEM_SERVICE; } - talloc_steal(mem_ctx, dom_res); if (dom_res->count != 1) { return NT_STATUS_NO_SUCH_DOMAIN; } @@ -95,7 +94,7 @@ NTSTATUS dcesrv_lsa_get_policy_state(struct dcesrv_call_state *dce_call, TALLOC_ talloc_free(dom_res); - ret = ldb_search_exp_fmt(state->sam_ldb, state, &ref_res, + ret = ldb_search(state->sam_ldb, state, &ref_res, partitions_basedn, LDB_SCOPE_SUBTREE, ref_attrs, "(&(objectclass=crossRef)(ncName=%s))", ldb_dn_get_linearized(state->domain_dn)); @@ -125,7 +124,7 @@ NTSTATUS dcesrv_lsa_get_policy_state(struct dcesrv_call_state *dce_call, TALLOC_ talloc_free(ref_res); - ret = ldb_search_exp_fmt(state->sam_ldb, state, &forest_ref_res, + ret = ldb_search(state->sam_ldb, state, &forest_ref_res, partitions_basedn, LDB_SCOPE_SUBTREE, ref_attrs, "(&(objectclass=crossRef)(ncName=%s))", ldb_dn_get_linearized(state->forest_dn)); diff --git a/source4/rpc_server/samr/dcesrv_samr.c b/source4/rpc_server/samr/dcesrv_samr.c index e54d518f76..9daf4f2194 100644 --- a/source4/rpc_server/samr/dcesrv_samr.c +++ b/source4/rpc_server/samr/dcesrv_samr.c @@ -341,7 +341,7 @@ static NTSTATUS dcesrv_samr_EnumDomains(struct dcesrv_call_state *dce_call, TALL partitions_basedn = samdb_partitions_dn(c_state->sam_ctx, mem_ctx); - ret = ldb_search_exp_fmt(c_state->sam_ctx, mem_ctx, &dom_res, ldb_get_default_basedn(c_state->sam_ctx), + ret = ldb_search(c_state->sam_ctx, mem_ctx, &dom_res, ldb_get_default_basedn(c_state->sam_ctx), LDB_SCOPE_SUBTREE, dom_attrs, "(|(|(objectClass=domain)(objectClass=builtinDomain))(objectClass=samba4LocalDomain))"); if (ret != LDB_SUCCESS) { DEBUG(0,("samdb: unable to find domains: %s\n", ldb_errstring(c_state->sam_ctx))); @@ -373,7 +373,7 @@ static NTSTATUS dcesrv_samr_EnumDomains(struct dcesrv_call_state *dce_call, TALL for (i=0;icount-start_i;i++) { array->entries[i].idx = start_i + i; /* try and find the domain */ - ret = ldb_search_exp_fmt(c_state->sam_ctx, mem_ctx, &ref_res, partitions_basedn, + ret = ldb_search(c_state->sam_ctx, mem_ctx, &ref_res, partitions_basedn, LDB_SCOPE_SUBTREE, ref_attrs, "(&(objectClass=crossRef)(ncName=%s))", ldb_dn_get_linearized(dom_res->msgs[i]->dn)); @@ -1502,7 +1502,7 @@ static NTSTATUS dcesrv_samr_EnumDomainUsers(struct dcesrv_call_state *dce_call, d_state = h->data; /* don't have to worry about users in the builtin domain, as there are none */ - ret = ldb_search_exp_fmt(d_state->sam_ctx, mem_ctx, &res, d_state->domain_dn, LDB_SCOPE_SUBTREE, attrs, "objectClass=user"); + ret = ldb_search(d_state->sam_ctx, mem_ctx, &res, d_state->domain_dn, LDB_SCOPE_SUBTREE, attrs, "objectClass=user"); if (ret != LDB_SUCCESS) { DEBUG(3, ("Failed to search for Domain Users in %s: %s\n", @@ -2110,7 +2110,7 @@ static NTSTATUS dcesrv_samr_QueryGroupInfo(struct dcesrv_call_state *dce_call, T a_state = h->data; - ret = ldb_search_exp_fmt(a_state->sam_ctx, mem_ctx, &res, a_state->account_dn, LDB_SCOPE_SUBTREE, attrs, "objectClass=*"); + ret = ldb_search(a_state->sam_ctx, mem_ctx, &res, a_state->account_dn, LDB_SCOPE_SUBTREE, attrs, "objectClass=*"); if (ret == LDB_ERR_NO_SUCH_OBJECT) { return NT_STATUS_NO_SUCH_GROUP; @@ -2246,7 +2246,7 @@ static NTSTATUS dcesrv_samr_AddGroupMember(struct dcesrv_call_state *dce_call, T /* In native mode, AD can also nest domain groups. Not sure yet * whether this is also available via RPC. */ - ret = ldb_search_exp_fmt(d_state->sam_ctx, mem_ctx, &res, + ret = ldb_search(d_state->sam_ctx, mem_ctx, &res, d_state->domain_dn, LDB_SCOPE_SUBTREE, attrs, "(&(objectSid=%s)(objectclass=user))", ldap_encode_ndr_dom_sid(mem_ctx, membersid)); @@ -2348,7 +2348,7 @@ static NTSTATUS dcesrv_samr_DeleteGroupMember(struct dcesrv_call_state *dce_call /* In native mode, AD can also nest domain groups. Not sure yet * whether this is also available via RPC. */ - ret = ldb_search_exp_fmt(d_state->sam_ctx, mem_ctx, &res, + ret = ldb_search(d_state->sam_ctx, mem_ctx, &res, d_state->domain_dn, LDB_SCOPE_SUBTREE, attrs, "(&(objectSid=%s)(objectclass=user))", ldap_encode_ndr_dom_sid(mem_ctx, membersid)); diff --git a/source4/torture/ldap/schema.c b/source4/torture/ldap/schema.c index 8437e7f79d..dd1d2de331 100644 --- a/source4/torture/ldap/schema.c +++ b/source4/torture/ldap/schema.c @@ -57,8 +57,8 @@ static bool test_search_rootDSE(struct ldb_context *ldb, struct test_rootDSE *ro d_printf("Testing RootDSE Search\n"); - ret = ldb_search(ldb, ldb_dn_new(ldb, ldb, NULL), LDB_SCOPE_BASE, - NULL, NULL, &r); + ret = ldb_search(ldb, ldb, &r, ldb_dn_new(ldb, ldb, NULL), + LDB_SCOPE_BASE, NULL, NULL); if (ret != LDB_SUCCESS) { return false; } else if (r->count != 1) { diff --git a/source4/torture/ldap/uptodatevector.c b/source4/torture/ldap/uptodatevector.c index 87b7e09e13..3c491dca05 100644 --- a/source4/torture/ldap/uptodatevector.c +++ b/source4/torture/ldap/uptodatevector.c @@ -57,15 +57,14 @@ static bool test_check_uptodatevector(struct torture_context *torture, torture_comment(torture, "Check replUpToDateVector on partition[%s]\n", ldb_dn_get_linearized(partition_dn)); - ret = ldb_search(ldb, partition_dn, LDB_SCOPE_BASE, - "(objectClass=*)", attrs, &r); + ret = ldb_search(ldb, torture, &r, partition_dn, LDB_SCOPE_BASE, attrs, + "(objectClass=*)"); if (ret != LDB_SUCCESS) { return false; } else if (r->count != 1) { talloc_free(r); return false; } - talloc_steal(torture, r); ZERO_STRUCT(utdv1); utdv_val1 = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector"); @@ -104,15 +103,14 @@ static bool test_check_uptodatevector(struct torture_context *torture, ret = ldb_modify(ldb, msg); if (ret != LDB_SUCCESS) return false; - ret = ldb_search(ldb, partition_dn, LDB_SCOPE_BASE, - "(objectClass=*)", attrs, &r); + ret = ldb_search(ldb, msg, &r, partition_dn, LDB_SCOPE_BASE, + attrs, "(objectClass=*)"); if (ret != LDB_SUCCESS) { return false; } else if (r->count != 1) { talloc_free(r); return false; } - talloc_steal(msg, r); ZERO_STRUCT(utdv); utdv_val = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector"); diff --git a/source4/torture/local/dbspeed.c b/source4/torture/local/dbspeed.c index 3d449a5991..9547e9ff74 100644 --- a/source4/torture/local/dbspeed.c +++ b/source4/torture/local/dbspeed.c @@ -211,21 +211,18 @@ static bool test_ldb_speed(struct torture_context *torture, const void *_data) for (count=0;timeval_elapsed(&tv) < timelimit;count++) { struct ldb_dn *dn; struct ldb_result *res; - char *expr; i = random() % torture_entries; dn = ldb_dn_new_fmt(tmp_ctx, ldb, "SID=S-1-5-21-53173311-3623041448-2049097239-%u", i); - if (ldb_search(ldb, dn, LDB_SCOPE_BASE, NULL, NULL, &res) != LDB_SUCCESS || res->count != 1) { + if (ldb_search(ldb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, NULL, NULL) != LDB_SUCCESS || res->count != 1) { torture_fail(torture, talloc_asprintf(torture, "Failed to find SID %d", i)); } talloc_free(res); talloc_free(dn); - expr = talloc_asprintf(tmp_ctx, "(UID=%u)", i); - if (ldb_search(ldb, NULL, LDB_SCOPE_SUBTREE, expr, NULL, &res) != LDB_SUCCESS || res->count != 1) { + if (ldb_search(ldb, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE, NULL, "(UID=%u)", i) != LDB_SUCCESS || res->count != 1) { torture_fail(torture, talloc_asprintf(torture, "Failed to find UID %d", i)); } talloc_free(res); - talloc_free(expr); } if (talloc_total_blocks(torture) > 100) { diff --git a/source4/utils/ad2oLschema.c b/source4/utils/ad2oLschema.c index e229bd104b..3c2ffe7a00 100644 --- a/source4/utils/ad2oLschema.c +++ b/source4/utils/ad2oLschema.c @@ -75,18 +75,16 @@ static struct ldb_dn *find_schema_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ct } /* Search for rootdse */ - ldb_ret = ldb_search(ldb, basedn, LDB_SCOPE_BASE, NULL, rootdse_attrs, &rootdse_res); + ldb_ret = ldb_search(ldb, mem_ctx, &rootdse_res, + basedn, LDB_SCOPE_BASE, rootdse_attrs, NULL); if (ldb_ret != LDB_SUCCESS) { - ldb_ret = ldb_search(ldb, basedn, LDB_SCOPE_SUBTREE, - "(&(objectClass=dMD)(cn=Schema))", - NULL, &schema_res); + ldb_ret = ldb_search(ldb, mem_ctx, &schema_res, basedn, LDB_SCOPE_SUBTREE, + NULL, "(&(objectClass=dMD)(cn=Schema))"); if (ldb_ret) { printf("cn=Schema Search failed: %s\n", ldb_errstring(ldb)); return NULL; } - talloc_steal(mem_ctx, schema_res); - if (schema_res->count != 1) { talloc_free(schema_res); printf("Failed to find rootDSE"); diff --git a/source4/winbind/idmap.c b/source4/winbind/idmap.c index 333a86445a..56ade3e8b1 100644 --- a/source4/winbind/idmap.c +++ b/source4/winbind/idmap.c @@ -54,11 +54,9 @@ static int idmap_get_bounds(struct idmap_context *idmap_ctx, uint32_t *low, dn = ldb_dn_new(tmp_ctx, ldb, "CN=CONFIG"); if (dn == NULL) goto failed; - ret = ldb_search(ldb, dn, LDB_SCOPE_BASE, NULL, NULL, &res); + ret = ldb_search(ldb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, NULL, NULL); if (ret != LDB_SUCCESS) goto failed; - talloc_steal(tmp_ctx, res); - if (res->count != 1) { ret = -1; goto failed; @@ -228,7 +226,7 @@ NTSTATUS idmap_xid_to_sid(struct idmap_context *idmap_ctx, TALLOC_CTX *mem_ctx, goto failed; } - ret = ldb_search_exp_fmt(ldb, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE, + ret = ldb_search(ldb, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE, NULL, "(&(|(type=ID_TYPE_BOTH)(type=%s))" "(xidNumber=%u))", id_type, unixid->id); if (ret != LDB_SUCCESS) { @@ -345,7 +343,7 @@ NTSTATUS idmap_sid_to_xid(struct idmap_context *idmap_ctx, TALLOC_CTX *mem_ctx, return NT_STATUS_OK; } - ret = ldb_search_exp_fmt(ldb, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE, + ret = ldb_search(ldb, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE, NULL, "(&(objectClass=sidMap)(objectSid=%s))", ldap_encode_ndr_dom_sid(tmp_ctx, sid)); if (ret != LDB_SUCCESS) { @@ -401,7 +399,7 @@ NTSTATUS idmap_sid_to_xid(struct idmap_context *idmap_ctx, TALLOC_CTX *mem_ctx, /* Redo the search to make sure noone changed the mapping while we * weren't looking */ - ret = ldb_search_exp_fmt(ldb, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE, + ret = ldb_search(ldb, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE, NULL, "(&(objectClass=sidMap)(objectSid=%s))", ldap_encode_ndr_dom_sid(tmp_ctx, sid)); if (ret != LDB_SUCCESS) { @@ -431,15 +429,13 @@ NTSTATUS idmap_sid_to_xid(struct idmap_context *idmap_ctx, TALLOC_CTX *mem_ctx, goto failed; } - ret = ldb_search(ldb, dn, LDB_SCOPE_BASE, NULL, NULL, &res); + ret = ldb_search(ldb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, NULL, NULL); if (ret != LDB_SUCCESS) { DEBUG(1, ("Search failed: %s\n", ldb_errstring(ldb))); status = NT_STATUS_NONE_MAPPED; goto failed; } - talloc_steal(tmp_ctx, res); - if (res->count != 1) { DEBUG(1, ("No CN=CONFIG record, idmap database is broken.\n")); status = NT_STATUS_NONE_MAPPED; diff --git a/source4/wrepl_server/wrepl_in_call.c b/source4/wrepl_server/wrepl_in_call.c index 0508c306e0..ac44b4d75d 100644 --- a/source4/wrepl_server/wrepl_in_call.c +++ b/source4/wrepl_server/wrepl_in_call.c @@ -262,9 +262,8 @@ static NTSTATUS wreplsrv_in_send_request(struct wreplsrv_in_call *call) (long long)owner_in->min_version, (long long)owner_in->max_version); NT_STATUS_HAVE_NO_MEMORY(filter); - ret = ldb_search(service->wins_db->ldb, NULL, LDB_SCOPE_SUBTREE, filter, NULL, &res); + ret = ldb_search(service->wins_db->ldb, call, &res, NULL, LDB_SCOPE_SUBTREE, NULL, "%s", filter); if (ret != LDB_SUCCESS) return NT_STATUS_INTERNAL_DB_CORRUPTION; - talloc_steal(call, res); DEBUG(10,("WINSREPL: filter '%s' count %d\n", filter, res->count)); if (res->count == 0) { diff --git a/source4/wrepl_server/wrepl_scavenging.c b/source4/wrepl_server/wrepl_scavenging.c index a5cd36797d..a239403e3b 100644 --- a/source4/wrepl_server/wrepl_scavenging.c +++ b/source4/wrepl_server/wrepl_scavenging.c @@ -74,9 +74,8 @@ static NTSTATUS wreplsrv_scavenging_owned_records(struct wreplsrv_service *servi "(expireTime<=%s))", owner_filter, now_timestr); NT_STATUS_HAVE_NO_MEMORY(filter); - ret = ldb_search(service->wins_db->ldb, NULL, LDB_SCOPE_SUBTREE, filter, NULL, &res); + ret = ldb_search(service->wins_db->ldb, tmp_mem, &res, NULL, LDB_SCOPE_SUBTREE, NULL, "%s", filter); if (ret != LDB_SUCCESS) return NT_STATUS_INTERNAL_DB_CORRUPTION; - talloc_steal(tmp_mem, res); DEBUG(10,("WINS scavenging: filter '%s' count %d\n", filter, res->count)); tombstone_extra_time = timeval_add(&service->startup_time, @@ -188,9 +187,8 @@ static NTSTATUS wreplsrv_scavenging_replica_non_active_records(struct wreplsrv_s "(!(recordState=%u))(expireTime<=%s))", owner_filter, WREPL_STATE_ACTIVE, now_timestr); NT_STATUS_HAVE_NO_MEMORY(filter); - ret = ldb_search(service->wins_db->ldb, NULL, LDB_SCOPE_SUBTREE, filter, NULL, &res); + ret = ldb_search(service->wins_db->ldb, tmp_mem, &res, NULL, LDB_SCOPE_SUBTREE, NULL, "%s", filter); if (ret != LDB_SUCCESS) return NT_STATUS_INTERNAL_DB_CORRUPTION; - talloc_steal(tmp_mem, res); DEBUG(10,("WINS scavenging: filter '%s' count %d\n", filter, res->count)); tombstone_extra_time = timeval_add(&service->startup_time, @@ -404,9 +402,8 @@ static NTSTATUS wreplsrv_scavenging_replica_active_records(struct wreplsrv_servi "(recordState=%u)(expireTime<=%s))", owner_filter, WREPL_STATE_ACTIVE, now_timestr); NT_STATUS_HAVE_NO_MEMORY(filter); - ret = ldb_search(service->wins_db->ldb, NULL, LDB_SCOPE_SUBTREE, filter, NULL, &res); + ret = ldb_search(service->wins_db->ldb, tmp_mem, &res, NULL, LDB_SCOPE_SUBTREE, NULL, "%s", filter); if (ret != LDB_SUCCESS) return NT_STATUS_INTERNAL_DB_CORRUPTION; - talloc_steal(tmp_mem, res); DEBUG(10,("WINS scavenging: filter '%s' count %d\n", filter, res->count)); for (i=0; i < res->count; i++) { diff --git a/source4/wrepl_server/wrepl_server.c b/source4/wrepl_server/wrepl_server.c index b703066986..48a68e4432 100644 --- a/source4/wrepl_server/wrepl_server.c +++ b/source4/wrepl_server/wrepl_server.c @@ -55,10 +55,8 @@ static uint64_t wins_config_db_get_seqnumber(struct ldb_context *ldb) if (!dn) goto failed; /* find the record in the WINS database */ - ret = ldb_search(ldb, dn, LDB_SCOPE_BASE, - NULL, NULL, &res); + ret = ldb_search(ldb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, NULL, NULL); if (ret != LDB_SUCCESS) goto failed; - talloc_steal(tmp_ctx, res); if (res->count > 1) goto failed; if (res->count == 1) { @@ -157,10 +155,10 @@ NTSTATUS wreplsrv_load_partners(struct wreplsrv_service *service) service->config.seqnumber = new_seqnumber; /* find the record in the WINS database */ - ret = ldb_search(service->config.ldb, ldb_dn_new(tmp_ctx, service->config.ldb, "CN=PARTNERS"), LDB_SCOPE_SUBTREE, - "(objectClass=wreplPartner)", NULL, &res); + ret = ldb_search(service->config.ldb, tmp_ctx, &res, + ldb_dn_new(tmp_ctx, service->config.ldb, "CN=PARTNERS"), + LDB_SCOPE_SUBTREE, NULL, "(objectClass=wreplPartner)"); if (ret != LDB_SUCCESS) goto failed; - talloc_steal(tmp_ctx, res); /* first disable all existing partners */ for (partner=service->partners; partner; partner = partner->next) { @@ -391,11 +389,10 @@ static NTSTATUS wreplsrv_load_table(struct wreplsrv_service *service) } /* find the record in the WINS database */ - ret = ldb_search(ldb, NULL, LDB_SCOPE_SUBTREE, - "(objectClass=winsRecord)", attrs, &res); + ret = ldb_search(ldb, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE, + attrs, "(objectClass=winsRecord)"); status = NT_STATUS_INTERNAL_DB_CORRUPTION; if (ret != LDB_SUCCESS) goto failed; - talloc_steal(tmp_ctx, res); for (i=0; i < res->count; i++) { wins_owner = ldb_msg_find_attr_as_string(res->msgs[i], "winsOwner", NULL); -- cgit From ed23c66bf717ec7cbd4a9950c984342a27576394 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Wed, 24 Sep 2008 01:11:38 +0200 Subject: s4: remove autogeneration of libcli/netlogon protos. we do need to have them around for samba3. Guenther --- source4/libcli/config.mk | 6 ------ 1 file changed, 6 deletions(-) diff --git a/source4/libcli/config.mk b/source4/libcli/config.mk index bb426ca9f6..1a7dcdeec1 100644 --- a/source4/libcli/config.mk +++ b/source4/libcli/config.mk @@ -55,24 +55,18 @@ LIBCLI_NBT_OBJ_FILES = $(addprefix ../$(libclisrcdir)/nbt/, \ namerefresh.o \ namerelease.o) -$(eval $(call proto_header_template,../$(libclisrcdir)/nbt/nbt_proto.h,$(LIBCLI_NBT_OBJ_FILES:.o=.c))) - [SUBSYSTEM::LIBCLI_NDR_NETLOGON] PUBLIC_DEPENDENCIES = LIBNDR \ NDR_SECURITY LIBCLI_NDR_NETLOGON_OBJ_FILES = $(addprefix ../$(libclisrcdir)/, ndr_netlogon.o) -$(eval $(call proto_header_template,../$(libclisrcdir)/ndr_netlogon_proto.h,$(LIBCLI_NDR_NETLOGON_OBJ_FILES:.o=.c))) - [SUBSYSTEM::LIBCLI_NETLOGON] PUBLIC_DEPENDENCIES = LIBSAMBA-UTIL LIBCLI_NDR_NETLOGON LIBCLI_NETLOGON_OBJ_FILES = $(addprefix ../$(libclisrcdir)/, \ netlogon.o) -$(eval $(call proto_header_template,../$(libclisrcdir)/netlogon_proto.h,$(LIBCLI_NETLOGON_OBJ_FILES:.o=.c))) - [SUBSYSTEM::LIBCLI_DRSBLOBS] PUBLIC_DEPENDENCIES = LIBNDR -- cgit From 7baaa87b93717f3762ae1f96677272fdb941f2bf Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Wed, 24 Sep 2008 01:13:51 +0200 Subject: libcli: add autogenerated libcli netlogon helper protos. Guenther --- libcli/ndr_netlogon_proto.h | 24 ++++++++++++++++++++++++ libcli/netlogon_proto.h | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 libcli/ndr_netlogon_proto.h create mode 100644 libcli/netlogon_proto.h diff --git a/libcli/ndr_netlogon_proto.h b/libcli/ndr_netlogon_proto.h new file mode 100644 index 0000000000..ca61c16138 --- /dev/null +++ b/libcli/ndr_netlogon_proto.h @@ -0,0 +1,24 @@ +#ifndef _____LIBCLI_NDR_NETLOGON_PROTO_H__ +#define _____LIBCLI_NDR_NETLOGON_PROTO_H__ + +#undef _PRINTF_ATTRIBUTE +#define _PRINTF_ATTRIBUTE(a1, a2) PRINTF_ATTRIBUTE(a1, a2) +/* This file was automatically generated by mkproto.pl. DO NOT EDIT */ + +/* this file contains prototypes for functions that are private + * to this subsystem or library. These functions should not be + * used outside this particular subsystem! */ + + +/* The following definitions come from ../libcli/ndr_netlogon.c */ + +enum ndr_err_code ndr_push_NETLOGON_SAM_LOGON_REQUEST(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_SAM_LOGON_REQUEST *r); +enum ndr_err_code ndr_pull_NETLOGON_SAM_LOGON_REQUEST(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_SAM_LOGON_REQUEST *r); +enum ndr_err_code ndr_push_NETLOGON_SAM_LOGON_RESPONSE_EX_with_flags(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_SAM_LOGON_RESPONSE_EX *r); +enum ndr_err_code ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_EX_with_flags(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_SAM_LOGON_RESPONSE_EX *r, + uint32_t nt_version_flags); +#undef _PRINTF_ATTRIBUTE +#define _PRINTF_ATTRIBUTE(a1, a2) + +#endif /* _____LIBCLI_NDR_NETLOGON_PROTO_H__ */ + diff --git a/libcli/netlogon_proto.h b/libcli/netlogon_proto.h new file mode 100644 index 0000000000..905feed876 --- /dev/null +++ b/libcli/netlogon_proto.h @@ -0,0 +1,32 @@ +#ifndef _____LIBCLI_NETLOGON_PROTO_H__ +#define _____LIBCLI_NETLOGON_PROTO_H__ + +#undef _PRINTF_ATTRIBUTE +#define _PRINTF_ATTRIBUTE(a1, a2) PRINTF_ATTRIBUTE(a1, a2) +/* This file was automatically generated by mkproto.pl. DO NOT EDIT */ + +/* this file contains prototypes for functions that are private + * to this subsystem or library. These functions should not be + * used outside this particular subsystem! */ + + +/* The following definitions come from ../libcli/netlogon.c */ + +NTSTATUS push_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct netlogon_samlogon_response *response); +NTSTATUS pull_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct netlogon_samlogon_response *response); +void map_netlogon_samlogon_response(struct netlogon_samlogon_response *response); +NTSTATUS push_nbt_netlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct nbt_netlogon_response *response); +NTSTATUS pull_nbt_netlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct nbt_netlogon_response *response); +#undef _PRINTF_ATTRIBUTE +#define _PRINTF_ATTRIBUTE(a1, a2) + +#endif /* _____LIBCLI_NETLOGON_PROTO_H__ */ + -- cgit From 3807b30f4403ade3c0c044e2bd88316b3d61a4e6 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Tue, 23 Sep 2008 16:39:57 -0700 Subject: Fix winbindd crash in an unusual failure mode. Bug #5737. Based on original patch from shargagan@novell.com Jeremy. --- source3/winbindd/winbindd_dual.c | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/source3/winbindd/winbindd_dual.c b/source3/winbindd/winbindd_dual.c index 63ce0e8d7f..1600f05eb1 100644 --- a/source3/winbindd/winbindd_dual.c +++ b/source3/winbindd/winbindd_dual.c @@ -196,10 +196,12 @@ static void async_request_fail(struct winbindd_async_request *state) TALLOC_FREE(state->reply_timeout_event); - SMB_ASSERT(state->child_pid != (pid_t)0); + /* If child exists and is not already reaped, + send kill signal to child. */ - /* If not already reaped, send kill signal to child. */ - if (state->child->pid == state->child_pid) { + if ((state->child->pid != (pid_t)0) && + (state->child->pid != (pid_t)-1) && + (state->child->pid == state->child_pid)) { kill(state->child_pid, SIGTERM); /* @@ -295,12 +297,14 @@ static void schedule_async_request(struct winbindd_child *child) } if ((child->pid == 0) && (!fork_domain_child(child))) { - /* Cancel all outstanding requests */ + /* fork_domain_child failed. + Cancel all outstanding requests */ while (request != NULL) { /* request might be free'd in the continuation */ struct winbindd_async_request *next = request->next; - request->continuation(request->private_data, False); + + async_request_fail(request); request = next; } return; -- cgit From 61a45c85dec8e65ba9782c3ec4af0e9a42895eb3 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Wed, 24 Sep 2008 01:40:13 +0200 Subject: s3: fix make everything. Guenther --- source3/librpc/tools/ndrdump.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source3/librpc/tools/ndrdump.c b/source3/librpc/tools/ndrdump.c index dc7f2be32f..08b969ae76 100644 --- a/source3/librpc/tools/ndrdump.c +++ b/source3/librpc/tools/ndrdump.c @@ -294,7 +294,7 @@ static const struct ndr_interface_table *load_iface_from_plugin(const char *plug blob.data = data; blob.length = size; - ndr_pull = ndr_pull_init_blob(&blob, mem_ctx); + ndr_pull = ndr_pull_init_blob(&blob, mem_ctx, NULL); ndr_pull->flags |= LIBNDR_FLAG_REF_ALLOC; ndr_err = f->ndr_pull(ndr_pull, NDR_IN, st); @@ -331,7 +331,7 @@ static const struct ndr_interface_table *load_iface_from_plugin(const char *plug blob.data = data; blob.length = size; - ndr_pull = ndr_pull_init_blob(&blob, mem_ctx); + ndr_pull = ndr_pull_init_blob(&blob, mem_ctx, NULL); ndr_pull->flags |= LIBNDR_FLAG_REF_ALLOC; ndr_err = f->ndr_pull(ndr_pull, flags, st); @@ -385,7 +385,7 @@ static const struct ndr_interface_table *load_iface_from_plugin(const char *plug dump_data(0, v_blob.data, v_blob.length); } - ndr_v_pull = ndr_pull_init_blob(&v_blob, mem_ctx); + ndr_v_pull = ndr_pull_init_blob(&v_blob, mem_ctx, NULL); ndr_v_pull->flags |= LIBNDR_FLAG_REF_ALLOC; ndr_err = f->ndr_pull(ndr_v_pull, flags, v_st); -- cgit From 765e5d2282959770ea9648e0f2b72e51e5b4cdd8 Mon Sep 17 00:00:00 2001 From: Karolin Seeger Date: Tue, 23 Sep 2008 16:54:05 -0700 Subject: printing: Add new parameter "cups timeout". The default timeout for connections to CUPS servers is set to 5 minutes in the CUPS libraries. The smbd hangs on startup until the timeout is reached if the CUPS server is unreachable. This parameter makes the timeout configurable. The default value is set to 30 seconds. Karolin --- docs-xml/smbdotconf/printing/cupstimeout.xml | 17 ++++++++++++++ source3/include/printing.h | 1 + source3/include/proto.h | 1 + source3/param/loadparm.c | 13 +++++++++++ source3/printing/print_cups.c | 34 +++++++++++++++++++++++----- 5 files changed, 60 insertions(+), 6 deletions(-) create mode 100644 docs-xml/smbdotconf/printing/cupstimeout.xml diff --git a/docs-xml/smbdotconf/printing/cupstimeout.xml b/docs-xml/smbdotconf/printing/cupstimeout.xml new file mode 100644 index 0000000000..727ccce67b --- /dev/null +++ b/docs-xml/smbdotconf/printing/cupstimeout.xml @@ -0,0 +1,17 @@ + + + + + This parameter determines the timeout for connections to a CUPS server + in seconds. + + + +30 +cups timeout = 10 + diff --git a/source3/include/printing.h b/source3/include/printing.h index 2788143cc5..04e30a011b 100644 --- a/source3/include/printing.h +++ b/source3/include/printing.h @@ -77,6 +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 #ifndef PRINT_SPOOL_PREFIX #define PRINT_SPOOL_PREFIX "smbprn." diff --git a/source3/include/proto.h b/source3/include/proto.h index 9ee3fc9071..6eac9d1129 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -5936,6 +5936,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); const char *lp_ctdbd_socket(void); const char **lp_cluster_addresses(void); bool lp_clustering(void); diff --git a/source3/param/loadparm.c b/source3/param/loadparm.c index 60a1fa4858..db9e990e64 100644 --- a/source3/param/loadparm.c +++ b/source3/param/loadparm.c @@ -52,6 +52,7 @@ */ #include "includes.h" +#include "printing.h" bool bLoaded = False; @@ -340,6 +341,7 @@ struct global { int iKeepalive; int iminreceivefile; struct param_opt_struct *param_opt; + int cups_timeout; }; static struct global Globals; @@ -2594,6 +2596,15 @@ static struct parm_struct parm_table[] = { .enum_list = NULL, .flags = FLAG_ADVANCED | FLAG_PRINT | FLAG_GLOBAL, }, + { + .label = "cups timeout", + .type = P_INTEGER, + .p_class = P_GLOBAL, + .ptr = &Globals.cups_timeout, + .special = NULL, + .enum_list = NULL, + .flags = FLAG_ADVANCED, + }, { .label = "iprint server", .type = P_STRING, @@ -4794,6 +4805,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; /* these parameters are set to defaults that are more appropriate for the increasing samba install base: @@ -5235,6 +5247,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_CONST_STRING(lp_ctdbd_socket, &Globals.ctdbdSocket) FN_GLOBAL_LIST(lp_cluster_addresses, &Globals.szClusterAddresses) FN_GLOBAL_BOOL(lp_clustering, &Globals.clustering) diff --git a/source3/printing/print_cups.c b/source3/printing/print_cups.c index 593c5c7a1f..2b2cf159fb 100644 --- a/source3/printing/print_cups.c +++ b/source3/printing/print_cups.c @@ -24,6 +24,17 @@ #include #include +static SIG_ATOMIC_T gotalarm; + +/*************************************************************** + Signal function to tell us we timed out. +****************************************************************/ + +static void gotalarm_sig(void) +{ + gotalarm = 1; +} + extern userdom_struct current_user_info; /* @@ -45,7 +56,15 @@ static http_t *cups_connect(void) http_t *http; char *server, *p; int port; - + int timeout = lp_cups_timeout(); + + gotalarm = 0; + + if (timeout) { + CatchSignal(SIGALRM, SIGNAL_CAST gotalarm_sig); + alarm(timeout); + } + if (lp_cups_server() != NULL && strlen(lp_cups_server()) > 0) { server = smb_xstrdup(lp_cups_server()); } else { @@ -59,15 +78,18 @@ static http_t *cups_connect(void) } else { port = ippPort(); } - + DEBUG(10, ("connecting to cups server %s:%d\n", server, port)); - if ((http = httpConnect(server, port)) == NULL) { - DEBUG(0,("Unable to connect to CUPS server %s:%d - %s\n", + http = httpConnect(server, port); + + CatchSignal(SIGALRM, SIGNAL_CAST SIG_IGN); + alarm(0); + + if (http == NULL) { + DEBUG(0,("Unable to connect to CUPS server %s:%d - %s\n", server, port, strerror(errno))); - SAFE_FREE(server); - return NULL; } SAFE_FREE(server); -- cgit From 6a689c23e83fef71a562a9009b92983d750f63cc Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 24 Sep 2008 03:16:15 +0200 Subject: Rename smbd -> samba. This reverts commit 05ea5e23cf4e70de0bd658b1c5c0ead133967091. Conflicts: source4/smbd/server.c --- source4/build/smb_build/summary.pm | 2 +- source4/cldap_server/config.mk | 2 +- source4/cluster/ctdb/example/cluster_start.sh | 8 +- source4/dsdb/config.mk | 2 +- source4/dynconfig/config.mk | 2 +- source4/kdc/config.mk | 2 +- source4/ldap_server/config.mk | 2 +- source4/nbt_server/config.mk | 2 +- source4/ntp_signd/config.mk | 2 +- source4/rpc_server/config.mk | 2 +- source4/selftest/config.mk | 12 +- source4/selftest/selftest.pl | 4 +- source4/selftest/target/Samba4.pm | 26 ++-- source4/selftest/test_win.sh | 2 +- source4/smb_server/config.mk | 2 +- source4/smbd/config.mk | 10 +- source4/smbd/samba.8.xml | 178 ++++++++++++++++++++++++++ source4/smbd/server.c | 2 +- source4/smbd/smbd.8.xml | 177 ------------------------- source4/web_server/config.mk | 2 +- source4/winbind/config.mk | 2 +- source4/wrepl_server/config.mk | 2 +- 22 files changed, 221 insertions(+), 224 deletions(-) create mode 100644 source4/smbd/samba.8.xml delete mode 100644 source4/smbd/smbd.8.xml diff --git a/source4/build/smb_build/summary.pm b/source4/build/smb_build/summary.pm index 4ea1ad525e..f6c1c50550 100644 --- a/source4/build/smb_build/summary.pm +++ b/source4/build/smb_build/summary.pm @@ -46,7 +46,7 @@ sub show($$) print "Summary:\n\n"; showitem($output, "SSL in SWAT and LDAP", ["GNUTLS"]); - showitem($output, "threads in smbd (see --with-pthread)", ["PTHREAD"]); + showitem($output, "threads in server (see --with-pthread)", ["PTHREAD"]); showitem($output, "intelligent command line editing", ["READLINE"]); showitem($output, "changing process titles (see --with-setproctitle)", ["SETPROCTITLE"]); showitem($output, "using extended attributes", ["XATTR"]); diff --git a/source4/cldap_server/config.mk b/source4/cldap_server/config.mk index 137a44d0f7..baf2620f32 100644 --- a/source4/cldap_server/config.mk +++ b/source4/cldap_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM CLDAPD [MODULE::CLDAPD] INIT_FUNCTION = server_service_cldapd_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = \ LIBCLI_CLDAP LIBNETIF process_model # End SUBSYSTEM CLDAPD diff --git a/source4/cluster/ctdb/example/cluster_start.sh b/source4/cluster/ctdb/example/cluster_start.sh index 575d031c95..825eadb483 100755 --- a/source4/cluster/ctdb/example/cluster_start.sh +++ b/source4/cluster/ctdb/example/cluster_start.sh @@ -1,12 +1,12 @@ #!/bin/sh -killall smbd +killall samba sleep 1 -killall -9 smbd +killall -9 samba killall -9 valgrind type=$1 -xterm -e $type bin/smbd -s /home/tridge/samba/samba4.svn/prefix/etc/smb.conf.node1 -M single -i & -xterm -e $type bin/smbd -s /home/tridge/samba/samba4.svn/prefix/etc/smb.conf.node2 -M single -i & +xterm -e $type bin/samba -s /home/tridge/samba/samba4.svn/prefix/etc/smb.conf.node1 -M single -i & +xterm -e $type bin/samba -s /home/tridge/samba/samba4.svn/prefix/etc/smb.conf.node2 -M single -i & diff --git a/source4/dsdb/config.mk b/source4/dsdb/config.mk index 63e8a77ce4..8bc8b6e000 100644 --- a/source4/dsdb/config.mk +++ b/source4/dsdb/config.mk @@ -46,7 +46,7 @@ $(eval $(call proto_header_template,$(dsdbsrcdir)/schema/proto.h,$(SAMDB_SCHEMA_ # Start SUBSYSTEM DREPL_SRV [MODULE::DREPL_SRV] INIT_FUNCTION = server_service_drepl_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = \ SAMDB \ process_model diff --git a/source4/dynconfig/config.mk b/source4/dynconfig/config.mk index c0ef7f6e99..699c30e764 100644 --- a/source4/dynconfig/config.mk +++ b/source4/dynconfig/config.mk @@ -3,7 +3,7 @@ DYNCONFIG_OBJ_FILES = $(dynconfigsrcdir)/dynconfig.o # set these to where to find various files -# These can be overridden by command line switches (see smbd(8)) +# 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 diff --git a/source4/kdc/config.mk b/source4/kdc/config.mk index 2c96e22cb3..b3e5bfdb92 100644 --- a/source4/kdc/config.mk +++ b/source4/kdc/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM KDC [MODULE::KDC] INIT_FUNCTION = server_service_kdc_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = \ HEIMDAL_KDC HDB_LDB # End SUBSYSTEM KDC diff --git a/source4/ldap_server/config.mk b/source4/ldap_server/config.mk index 65f5b17f9a..4c35117a72 100644 --- a/source4/ldap_server/config.mk +++ b/source4/ldap_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM LDAP [MODULE::LDAP] INIT_FUNCTION = server_service_ldap_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = CREDENTIALS \ LIBCLI_LDAP SAMDB \ process_model \ diff --git a/source4/nbt_server/config.mk b/source4/nbt_server/config.mk index 1121bfc690..951949a43f 100644 --- a/source4/nbt_server/config.mk +++ b/source4/nbt_server/config.mk @@ -70,7 +70,7 @@ $(eval $(call proto_header_template,$(nbt_serversrcdir)/nbt_server_proto.h,$(NBT [MODULE::service_nbtd] INIT_FUNCTION = server_service_nbtd_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = NBT_SERVER process_model service_nbtd_OBJ_FILES = \ diff --git a/source4/ntp_signd/config.mk b/source4/ntp_signd/config.mk index 96e0de5583..3b52a200ce 100644 --- a/source4/ntp_signd/config.mk +++ b/source4/ntp_signd/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM NTP_signd [MODULE::NTP_SIGND] INIT_FUNCTION = server_service_ntp_signd_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = \ SAMDB NDR_NTP_SIGND # End SUBSYSTEM NTP_SIGND diff --git a/source4/rpc_server/config.mk b/source4/rpc_server/config.mk index 6b1813544e..fb697d0c0f 100644 --- a/source4/rpc_server/config.mk +++ b/source4/rpc_server/config.mk @@ -206,7 +206,7 @@ PUBLIC_HEADERS += $(rpc_serversrcdir)/dcerpc_server.h [MODULE::DCESRV] INIT_FUNCTION = server_service_rpc_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = dcerpc_server DCESRV_OBJ_FILES = $(rpc_serversrcdir)/service_rpc.o diff --git a/source4/selftest/config.mk b/source4/selftest/config.mk index 5503a42cdd..2fcb71eb7a 100644 --- a/source4/selftest/config.mk +++ b/source4/selftest/config.mk @@ -52,30 +52,30 @@ testenv:: everything valgrindtest:: valgrindtest-all valgrindtest-quick:: all - SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ VALGRIND="valgrind -q --num-callers=30 --log-file=${selftest_prefix}/valgrind.log" \ $(SELFTEST) $(SELFTEST_QUICK_OPTS) --immediate --socket-wrapper $(TESTS) valgrindtest-all:: everything - SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ VALGRIND="valgrind -q --num-callers=30 --log-file=${selftest_prefix}/valgrind.log" \ $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --immediate --socket-wrapper $(TESTS) valgrindtest-env:: everything - SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/valgrind_run $(LD_LIBPATH_OVERRIDE)" \ VALGRIND="valgrind -q --num-callers=30 --log-file=${selftest_prefix}/valgrind.log" \ $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --socket-wrapper --testenv gdbtest:: gdbtest-all gdbtest-quick:: all - SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ $(SELFTEST) $(SELFTEST_QUICK_OPTS) --immediate --socket-wrapper $(TESTS) gdbtest-all:: everything - SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --immediate --socket-wrapper $(TESTS) gdbtest-env:: everything - SMBD_VALGRIND="xterm -n smbd -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ + SMBD_VALGRIND="xterm -n server -e $(srcdir)/script/gdb_run $(LD_LIBPATH_OVERRIDE)" \ $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --socket-wrapper --testenv diff --git a/source4/selftest/selftest.pl b/source4/selftest/selftest.pl index 51a354c7a4..92aa67e8d3 100755 --- a/source4/selftest/selftest.pl +++ b/source4/selftest/selftest.pl @@ -303,7 +303,7 @@ Target Specific: --expected-failures=FILE specify list of tests that is guaranteed to fail Samba4 Specific: - --ldap=openldap|fedora-ds back smbd onto specified ldap server + --ldap=openldap|fedora-ds back samba onto specified ldap server Samba3 Specific: --bindir=PATH path to binaries @@ -809,7 +809,7 @@ if ($opt_testenv) { Welcome to the Samba4 Test environment '$testenv_name' This matches the client environment used in make test -smbd is pid `cat \$PIDDIR/smbd.pid` +server is pid `cat \$PIDDIR/samba.pid` Some useful environment variables: TORTURE_OPTIONS=\$TORTURE_OPTIONS diff --git a/source4/selftest/target/Samba4.pm b/source4/selftest/target/Samba4.pm index 992e251c35..9364008ee2 100644 --- a/source4/selftest/target/Samba4.pm +++ b/source4/selftest/target/Samba4.pm @@ -116,20 +116,20 @@ sub check_or_start($$$) if (defined($ENV{SMBD_OPTIONS})) { $optarg.= " $ENV{SMBD_OPTIONS}"; } - my $ret = system("$valgrind $self->{bindir}/smbd $optarg $env_vars->{CONFIGURATION} -M single -i --leak-report-full"); + my $ret = system("$valgrind $self->{bindir}/samba $optarg $env_vars->{CONFIGURATION} -M single -i --leak-report-full"); if ($? == -1) { - print "Unable to start smbd: $ret: $!\n"; + print "Unable to start samba: $ret: $!\n"; exit 1; } unlink($env_vars->{SMBD_TEST_FIFO}); my $exit = $? >> 8; if ( $ret == 0 ) { - print "smbd exits with status $exit\n"; + print "samba exits with status $exit\n"; } elsif ( $ret & 127 ) { - print "smbd got signal ".($ret & 127)." and exits with $exit!\n"; + print "samba got signal ".($ret & 127)." and exits with $exit!\n"; } else { $ret = $? >> 8; - print "smbd failed with status $exit!\n"; + print "samba failed with status $exit!\n"; } exit $exit; } @@ -498,7 +498,7 @@ sub provision($$$$$$) { my ($self, $prefix, $server_role, $netbiosname, $netbiosalias, $swiface, $password) = @_; - my $smbd_loglevel = 1; + my $server_loglevel = 1; my $username = "administrator"; my $domain = "SAMBADOMAIN"; my $realm = "SAMBA.EXAMPLE.COM"; @@ -571,7 +571,7 @@ sub provision($$$$$$) ldb:nosync = true #We don't want to pass our self-tests if the PAC code is wrong gensec:require_pac = true - log level = $smbd_loglevel + log level = $server_loglevel [tmp] path = $tmpdir @@ -606,7 +606,7 @@ sub provision($$$$$$) cifs:server = $netbiosname cifs:share = tmp #There is no username specified here, instead the client is expected -#to log in with kerberos, and smbd will used delegated credentials. +#to log in with kerberos, and the serverwill use delegated credentials. [simple] path = $tmpdir @@ -828,8 +828,8 @@ sub provision_dc($$) $self->add_wins_config("$prefix/private") or die("Unable to add wins configuration"); - $ret->{SMBD_TEST_FIFO} = "$prefix/smbd_test.fifo"; - $ret->{SMBD_TEST_LOG} = "$prefix/smbd_test.log"; + $ret->{SMBD_TEST_FIFO} = "$prefix/server_test.fifo"; + $ret->{SMBD_TEST_LOG} = "$prefix/server_test.log"; $ret->{SMBD_TEST_LOG_POS} = 0; return $ret; } @@ -841,8 +841,8 @@ sub teardown_env($$) close(DATA); - if (-f "$envvars->{PIDDIR}/smbd.pid" ) { - open(IN, "<$envvars->{PIDDIR}/smbd.pid") or die("unable to open smbd pid file"); + if (-f "$envvars->{PIDDIR}/samba.pid" ) { + open(IN, "<$envvars->{PIDDIR}/samba.pid") or die("unable to open server pid file"); $pid = ; close(IN); @@ -858,7 +858,7 @@ sub teardown_env($$) # If it is still around, kill it if ($count > 20) { - print "smbd process $pid took more than $count seconds to exit, killing\n"; + print "server process $pid took more than $count seconds to exit, killing\n"; kill 9, $pid; } } diff --git a/source4/selftest/test_win.sh b/source4/selftest/test_win.sh index bc40620af5..17c09e6b26 100755 --- a/source4/selftest/test_win.sh +++ b/source4/selftest/test_win.sh @@ -32,7 +32,7 @@ name="NET against Windows 2003" testit "$name" smb $WINTEST_DIR/wintest_net.sh $SMBTORTURE_REMOTE_HOST \ $SMBTORTURE_USERNAME $SMBTORTURE_PASSWORD $SMBTORTURE_WORKGROUP -name="Windows 2003 against smbd" +name="Windows 2003 against samba" testit "$name" smb $WINTEST_DIR/wintest_client.sh $SMBTORTURE_REMOTE_HOST dc_tests="RPC-DRSUAPI ncacn_np ncacn_ip_tcp" diff --git a/source4/smb_server/config.mk b/source4/smb_server/config.mk index d1ec6d49e8..8ed03b17fe 100644 --- a/source4/smb_server/config.mk +++ b/source4/smb_server/config.mk @@ -2,7 +2,7 @@ # [MODULE::SERVICE_SMB] INIT_FUNCTION = server_service_smb_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = SMB_SERVER SERVICE_SMB_OBJ_FILES = $(smb_serversrcdir)/smb_server.o diff --git a/source4/smbd/config.mk b/source4/smbd/config.mk index e60f444456..b5babd4d69 100644 --- a/source4/smbd/config.mk +++ b/source4/smbd/config.mk @@ -17,9 +17,7 @@ PIDFILE_OBJ_FILES = $(smbdsrcdir)/pidfile.o $(eval $(call proto_header_template,$(smbdsrcdir)/pidfile.h,$(PIDFILE_OBJ_FILES:.o=.c))) -################################# -# Start BINARY smbd -[BINARY::smbd] +[BINARY::samba] INSTALLDIR = SBINDIR PRIVATE_DEPENDENCIES = \ process_model \ @@ -36,8 +34,6 @@ PRIVATE_DEPENDENCIES = \ share \ CLUSTER -smbd_OBJ_FILES = $(smbdsrcdir)/server.o +samba_OBJ_FILES = $(smbdsrcdir)/server.o -MANPAGES += $(smbdsrcdir)/smbd.8 -# End BINARY smbd -################################# +MANPAGES += $(smbdsrcdir)/samba.8 diff --git a/source4/smbd/samba.8.xml b/source4/smbd/samba.8.xml new file mode 100644 index 0000000000..e1ec8cabd5 --- /dev/null +++ b/source4/smbd/samba.8.xml @@ -0,0 +1,178 @@ + + + + + + samba + 8 + + + + + samba + server to provide filesharing- and directory services to clients + + + + + samba + -i + -M model + + + + + DESCRIPTION + This program is part of the samba + 7 suite. + + samba is the server daemon that + provides filesharing and directory services to Windows clients. + The server provides filespace and directory services to + clients using the SMB (or CIFS) protocol and other + related protocols such as DCE/RPC, LDAP and Kerberos. + + + + Clients supported include MSCLIENT 3.0 for DOS, Windows for + Workgroups, Windows 95/98/ME, Windows NT, Windows 2000/XP/2003, + OS/2, DAVE for Macintosh, and cifsfs for Linux. + + An extensive description of the services that the + server can provide is given in the man page for the + configuration file controlling the attributes of those + services (see smb.conf + 5. This man page will not describe the + services, but will concentrate on the administrative aspects + of running the server. + + Please note that there are significant security + implications to running this server, and the smb.conf + 5 manual page should be regarded as mandatory reading before + proceeding with installation. + + As of Samba 4, there is a single daemon that incorporates the + functionality of both smbd and nmbd that are present in older versions + of Samba. + + + + + OPTIONS + + + + -i + If this parameter is specified it causes the + server to run "interactively", not as a daemon, even if the + server is executed on the command line of a shell. Setting this + parameter negates the implicit deamon mode when run from the + command line. samba also logs to standard + output, as if the -S parameter had been + given. + + + + + -M model + This parameter can be used to specify the + "process model" samba should use. This determines + how concurrent clients are handled. Available process + models include single (everything in + a single process), standard (similar + behaviour to that of Samba 3), thread + (single process, different threads. + + + + + + + FILES + + + + /etc/rc + or whatever initialization script your + system uses). + + If running the server as a daemon at startup, + this file will need to contain an appropriate startup + sequence for the server. + + + + /etc/services + If running the server via the + meta-daemon inetd, this file + must contain a mapping of service name (e.g., netbios-ssn) + to service port (e.g., 139) and protocol type (e.g., tcp). + + + + + /usr/local/samba/lib/smb.conf + This is the default location of the smb.conf + 5 server configuration file. Other common places that systems + install this file are /usr/samba/lib/smb.conf + and /etc/samba/smb.conf. + + This file describes all the services the server + is to make available to clients. See smb.conf + 5 for more information. + + + + + + + VERSION + + This man page is correct for version 4 of + the Samba suite. + + + + DIAGNOSTICS + + Most diagnostics issued by the server are logged + in a specified log file. The log file name is specified + at compile time, but may be overridden on the command line. + + The number and nature of diagnostics available depends + on the debug level used by the server. If you have problems, set + the debug level to 3 and peruse the log files. + + Most messages are reasonably self-explanatory. Unfortunately, + at the time this man page was created, there are too many diagnostics + available in the source code to warrant describing each and every + diagnostic. At this stage your best bet is still to grep the + source code and inspect the conditions that gave rise to the + diagnostics you are seeing. + + + + SEE ALSO + hosts_access + 5 + smb.conf + 5, smbclient + 1, testparm + 1, and the + Internet RFC's rfc1001.txt, rfc1002.txt. + In addition the CIFS (formerly SMB) specification is available + as a link from the Web page + http://samba.org/cifs/. + + + + AUTHOR + + 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. + + + + diff --git a/source4/smbd/server.c b/source4/smbd/server.c index cf25693fbe..fd4b21b17f 100644 --- a/source4/smbd/server.c +++ b/source4/smbd/server.c @@ -200,7 +200,7 @@ static int binary_smbd_main(const char *binary_name, int argc, const char *argv[ extern NTSTATUS server_service_rpc_init(void); extern NTSTATUS server_service_ntp_signd_init(void); extern NTSTATUS server_service_samba3_smb_init(void); - init_module_fn static_init[] = { STATIC_smbd_MODULES }; + init_module_fn static_init[] = { STATIC_samba_MODULES }; init_module_fn *shared_init; struct event_context *event_ctx; uint16_t stdin_event_flags; diff --git a/source4/smbd/smbd.8.xml b/source4/smbd/smbd.8.xml deleted file mode 100644 index a02c2ce80a..0000000000 --- a/source4/smbd/smbd.8.xml +++ /dev/null @@ -1,177 +0,0 @@ - - - - - - smbd - 8 - - - - - smbd - server to provide filesharing- and directory services to clients - - - - - smbd - -i - -M model - - - - - DESCRIPTION - This program is part of the samba - 7 suite. - - smbd is the server daemon that - provides filesharing and directory services to Windows clients. - The server provides filespace and directory services to - clients using the SMB (or CIFS) protocol and other - related protocols such as DCE/RPC, LDAP and Kerberos. - - - - Clients supported include MSCLIENT 3.0 for DOS, Windows for - Workgroups, Windows 95/98/ME, Windows NT, Windows 2000/XP/2003, - OS/2, DAVE for Macintosh, and cifsfs for Linux. - - An extensive description of the services that the - server can provide is given in the man page for the - configuration file controlling the attributes of those - services (see smb.conf - 5. This man page will not describe the - services, but will concentrate on the administrative aspects - of running the server. - - Please note that there are significant security - implications to running this server, and the smb.conf - 5 manual page should be regarded as mandatory reading before - proceeding with installation. - - As of Samba 4, smbd also incorporates all the functionality of - nmbd. - - - - - OPTIONS - - - - -i - If this parameter is specified it causes the - server to run "interactively", not as a daemon, even if the - server is executed on the command line of a shell. Setting this - parameter negates the implicit deamon mode when run from the - command line. smbd also logs to standard - output, as if the -S parameter had been - given. - - - - - -M model - This parameter can be used to specify the - "process model" smbd should use. This determines - how concurrent clients are handled. Available process - models include single (everything in - a single process), standard (similar - behaviour to that of Samba 3), thread - (single process, different threads. - - - - - - - FILES - - - - /etc/rc - or whatever initialization script your - system uses). - - If running the server as a daemon at startup, - this file will need to contain an appropriate startup - sequence for the server. - - - - /etc/services - If running the server via the - meta-daemon inetd, this file - must contain a mapping of service name (e.g., netbios-ssn) - to service port (e.g., 139) and protocol type (e.g., tcp). - - - - - /usr/local/samba/lib/smb.conf - This is the default location of the smb.conf - 5 server configuration file. Other common places that systems - install this file are /usr/samba/lib/smb.conf - and /etc/samba/smb.conf. - - This file describes all the services the server - is to make available to clients. See smb.conf - 5 for more information. - - - - - - - VERSION - - This man page is correct for version 4 of - the Samba suite. - - - - DIAGNOSTICS - - Most diagnostics issued by the server are logged - in a specified log file. The log file name is specified - at compile time, but may be overridden on the command line. - - The number and nature of diagnostics available depends - on the debug level used by the server. If you have problems, set - the debug level to 3 and peruse the log files. - - Most messages are reasonably self-explanatory. Unfortunately, - at the time this man page was created, there are too many diagnostics - available in the source code to warrant describing each and every - diagnostic. At this stage your best bet is still to grep the - source code and inspect the conditions that gave rise to the - diagnostics you are seeing. - - - - SEE ALSO - hosts_access - 5 - smb.conf - 5, smbclient - 1, testparm - 1, and the - Internet RFC's rfc1001.txt, rfc1002.txt. - In addition the CIFS (formerly SMB) specification is available - as a link from the Web page - http://samba.org/cifs/. - - - - AUTHOR - - 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. - - - - diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index af3ac5f544..e034590111 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM WEB [MODULE::WEB] INIT_FUNCTION = server_service_web_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = LIBTLS smbcalls process_model LIBPYTHON # End SUBSYSTEM WEB ####################### diff --git a/source4/winbind/config.mk b/source4/winbind/config.mk index 1837c52891..f719f00853 100644 --- a/source4/winbind/config.mk +++ b/source4/winbind/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM WINBIND [MODULE::WINBIND] INIT_FUNCTION = server_service_winbind_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = \ WB_HELPER \ IDMAP \ diff --git a/source4/wrepl_server/config.mk b/source4/wrepl_server/config.mk index 235a897503..c7b5c3e1df 100644 --- a/source4/wrepl_server/config.mk +++ b/source4/wrepl_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM WREPL_SRV [MODULE::WREPL_SRV] INIT_FUNCTION = server_service_wrepl_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = \ LIBCLI_WREPL WINSDB process_model # End SUBSYSTEM WREPL_SRV -- cgit From 1ea185a340993653650230c293ca5139ac225d30 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Wed, 24 Sep 2008 02:25:34 +0200 Subject: s3: fix merged_build. Guenther --- source3/samba4.mk | 1 + source4/Makefile | 1 + source4/libcli/config.mk | 12 ++++++------ 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/source3/samba4.mk b/source3/samba4.mk index 2646b12a0d..28bdf029f8 100644 --- a/source3/samba4.mk +++ b/source3/samba4.mk @@ -107,6 +107,7 @@ ntvfssrcdir := $(samba4srcdir)/ntvfs ntptrsrcdir := $(samba4srcdir)/ntptr clientsrcdir := $(samba4srcdir)/client libclisrcdir := $(samba4srcdir)/libcli +libclinbtsrcdir := $(samba4srcdir)/../libcli pyscriptsrcdir := $(samba4srcdir)/scripting/python kdcsrcdir := $(samba4srcdir)/kdc smbreadlinesrcdir := $(samba4srcdir)/lib/smbreadline diff --git a/source4/Makefile b/source4/Makefile index 2a267c3e7b..11057ae5f3 100644 --- a/source4/Makefile +++ b/source4/Makefile @@ -97,6 +97,7 @@ ntvfssrcdir := ntvfs ntptrsrcdir := ntptr librpcsrcdir := librpc libclisrcdir := libcli +libclinbtsrcdir := ../libcli pyscriptsrcdir := $(srcdir)/scripting/python kdcsrcdir := kdc ntp_signdsrcdir := ntp_signd diff --git a/source4/libcli/config.mk b/source4/libcli/config.mk index 1a7dcdeec1..2f81d7cff0 100644 --- a/source4/libcli/config.mk +++ b/source4/libcli/config.mk @@ -40,15 +40,15 @@ $(eval $(call proto_header_template,$(libclisrcdir)/smb_composite/proto.h,$(LIBC [SUBSYSTEM::NDR_NBT_BUF] -NDR_NBT_BUF_OBJ_FILES = ../$(libclisrcdir)/nbt/nbtname.o +NDR_NBT_BUF_OBJ_FILES = $(libclinbtsrcdir)/nbt/nbtname.o -$(eval $(call proto_header_template,../$(libclisrcdir)/nbt/nbtname.h,$(NDR_NBT_BUF_OBJ_FILES:.o=.c))) +$(eval $(call proto_header_template,$(libclinbtsrcdir)/nbt/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 ../$(libclisrcdir)/nbt/, \ +LIBCLI_NBT_OBJ_FILES = $(addprefix $(libclinbtsrcdir)/nbt/, \ nbtsocket.o \ namequery.o \ nameregister.o \ @@ -59,12 +59,12 @@ LIBCLI_NBT_OBJ_FILES = $(addprefix ../$(libclisrcdir)/nbt/, \ PUBLIC_DEPENDENCIES = LIBNDR \ NDR_SECURITY -LIBCLI_NDR_NETLOGON_OBJ_FILES = $(addprefix ../$(libclisrcdir)/, 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 ../$(libclisrcdir)/, \ +LIBCLI_NETLOGON_OBJ_FILES = $(addprefix $(libclinbtsrcdir)/, \ netlogon.o) [SUBSYSTEM::LIBCLI_DRSBLOBS] @@ -79,7 +79,7 @@ $(eval $(call proto_header_template,$(libclisrcdir)/drsblobs_proto.h,$(LIBCLI_DR LIBRARY_REALNAME = samba/netbios.$(SHLIBEXT) PUBLIC_DEPENDENCIES = LIBCLI_NBT DYNCONFIG LIBSAMBA-HOSTCONFIG -python_netbios_OBJ_FILES = ../$(libclisrcdir)/nbt/pynbt.o +python_netbios_OBJ_FILES = $(libclinbtsrcdir)/nbt/pynbt.o $(python_libcli_nbt_OBJ_FILES): CFLAGS+=$(CFLAG_NO_UNUSED_MACROS) $(CFLAG_NO_CAST_QUAL) -- cgit From a877745dc770c93dcb14b08b5d29b9e96b63f5e3 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 22:15:38 +0200 Subject: s3-nbt: full merge of s4 nbt idl. Guenther --- source3/librpc/idl/nbt.idl | 417 ++++++++++++++++----------------------------- 1 file changed, 143 insertions(+), 274 deletions(-) diff --git a/source3/librpc/idl/nbt.idl b/source3/librpc/idl/nbt.idl index f743109594..82571d96e6 100644 --- a/source3/librpc/idl/nbt.idl +++ b/source3/librpc/idl/nbt.idl @@ -10,7 +10,7 @@ import "misc.idl", "security.idl", "svcctl.idl", "samr.idl"; [ -helper("../libcli/nbt/libnbt.h") + helper("../libcli/netlogon.h", "../libcli/nbt/libnbt.h") ] interface nbt { @@ -172,18 +172,12 @@ interface nbt * together with NBT_QTYPE_NETBIOS * for WACK replies */ -#define NBT_RES_REC_LEVEL(rr_type, rdata) (\ - (((rr_type) == NBT_QTYPE_NETBIOS) && \ - talloc_check_name(ndr, "struct ndr_push") && \ - ((rdata).data.length == 2)) \ - ? 0 : rr_type) - - typedef [flag(LIBNDR_PRINT_ARRAY_HEX)] struct { + typedef [flag(LIBNDR_PRINT_ARRAY_HEX),nopush] struct { nbt_name name; nbt_qtype rr_type; nbt_qclass rr_class; uint32 ttl; - [switch_is(NBT_RES_REC_LEVEL(rr_type, rdata))] nbt_rdata rdata; + [switch_is(rr_type)] nbt_rdata rdata; } nbt_res_rec; typedef [flag(NDR_NOALIGN|NDR_BIG_ENDIAN|NDR_PAHEX),public] struct { @@ -338,65 +332,19 @@ interface nbt } nbt_dgram_packet; - /*******************************************/ - /* \MAILSLOT\NET\NETLOGON mailslot requests */ - typedef enum { - NETLOGON_QUERY_FOR_PDC = 0x7, - NETLOGON_ANNOUNCE_UAS = 0xa, - NETLOGON_RESPONSE_FROM_PDC = 0xc, - NETLOGON_QUERY_FOR_PDC2 = 0x12, - NETLOGON_RESPONSE_FROM_PDC2 = 0x17, - NETLOGON_RESPONSE_FROM_PDC_USER = 0x19 - } nbt_netlogon_command; - - typedef [flag(NDR_LITTLE_ENDIAN),bitmap32bit] bitmap { - NETLOGON_NT_VERSION_1 = 0x00000001, - NETLOGON_NT_VERSION_5 = 0x00000002, - NETLOGON_NT_VERSION_5EX = 0x00000004, - NETLOGON_NT_VERSION_5EX_WITH_IP = 0x00000008, - NETLOGON_NT_VERSION_WITH_CLOSEST_SITE = 0x00000010, - NETLOGON_NT_VERSION_AVIOD_NT4EMUL = 0x01000000, - NETLOGON_NT_VERSION_PDC = 0x10000000, - NETLOGON_NT_VERSION_IP = 0x20000000, - NETLOGON_NT_VERSION_LOCAL = 0x40000000, - NETLOGON_NT_VERSION_GC = 0x80000000 - } nbt_netlogon_version; - - /* query for pdc request */ - typedef struct { - astring computer_name; - astring mailslot_name; - [flag(NDR_ALIGN2)] DATA_BLOB _pad; - nstring unicode_name; - nbt_netlogon_version nt_version; - uint16 lmnt_token; - uint16 lm20_token; - } nbt_netlogon_query_for_pdc; + /****************************************** + * \MAILSLOT\NET\NETLOGON mailslot requests + * and + * \MAILSLOT\NET\NTLOGON mailslot requests + */ - /* query for pdc request - new style */ - typedef struct { - uint16 request_count; - nstring computer_name; - nstring user_name; - astring mailslot_name; - uint32 unknown[2]; - nbt_netlogon_version nt_version; - uint16 lmnt_token; - uint16 lm20_token; - } nbt_netlogon_query_for_pdc2; - - /* response from pdc */ - typedef struct { - astring pdc_name; - [flag(NDR_ALIGN2)] DATA_BLOB _pad; - nstring unicode_pdc_name; - nstring domain_name; - nbt_netlogon_version nt_version; - uint16 lmnt_token; - uint16 lm20_token; - } nbt_netlogon_response_from_pdc; + typedef [public,gensize] struct { + uint32 sa_family; + [flag(NDR_BIG_ENDIAN)] ipv4address pdc_ip; + [flag(NDR_REMAINING)] DATA_BLOB remaining; + } nbt_sockaddr; - typedef [bitmap32bit] bitmap { + typedef [bitmap32bit,public] bitmap { NBT_SERVER_PDC = 0x00000001, NBT_SERVER_GC = 0x00000004, NBT_SERVER_LDAP = 0x00000008, @@ -411,111 +359,89 @@ interface nbt NBT_SERVER_FULL_SECRET_DOMAIN_6 = 0x00001000 } nbt_server_type; - typedef struct { - uint32 family; - [flag(NDR_BIG_ENDIAN)] ipv4address pdc_ip; - [flag(NDR_REMAINING)] DATA_BLOB remaining; - } nbt_dc_sock_addr; - - /* response from pdc - type2 */ - typedef struct { + typedef [bitmap32bit,public] bitmap { + NETLOGON_NT_VERSION_1 = 0x00000001, + NETLOGON_NT_VERSION_5 = 0x00000002, + NETLOGON_NT_VERSION_5EX = 0x00000004, + NETLOGON_NT_VERSION_5EX_WITH_IP = 0x00000008, + NETLOGON_NT_VERSION_WITH_CLOSEST_SITE = 0x00000010, + NETLOGON_NT_VERSION_AVIOD_NT4EMUL = 0x01000000, + NETLOGON_NT_VERSION_PDC = 0x10000000, + NETLOGON_NT_VERSION_IP = 0x20000000, + NETLOGON_NT_VERSION_LOCAL = 0x40000000, + NETLOGON_NT_VERSION_GC = 0x80000000 + } netlogon_nt_version_flags; + + typedef [enum16bit,public] enum { + LOGON_PRIMARY_QUERY = 7, /* Was also NETLOGON_QUERY_FOR_PDC */ + NETLOGON_ANNOUNCE_UAS = 10, + NETLOGON_RESPONSE_FROM_PDC = 12, + LOGON_SAM_LOGON_REQUEST = 18, /* Was also NETLOGON_QUERY_FOR_PDC2, NTLOGON_SAM_LOGON */ + LOGON_SAM_LOGON_RESPONSE = 19, /* Was also NTLOGON_SAM_LOGON_REPLY */ + LOGON_SAM_LOGON_PAUSE_RESPONSE = 20, + LOGON_SAM_LOGON_USER_UNKNOWN = 21, /* Was also NTLOGON_SAM_LOGON_REPLY15 */ + LOGON_SAM_LOGON_RESPONSE_EX = 23, /* was NETLOGON_RESPONSE_FROM_PDC2 */ + LOGON_SAM_LOGON_PAUSE_RESPONSE_EX = 24, + LOGON_SAM_LOGON_USER_UNKNOWN_EX = 25 /* was NETLOGON_RESPONSE_FROM_PDC_USER */ + } netlogon_command; + + typedef bitmap samr_AcctFlags samr_AcctFlags; + + /* query to dc hand marshaled, as it has 'optional' + * parts */ + typedef [nopull,nopush] struct { + uint16 request_count; + nstring computer_name; + nstring user_name; + astring mailslot_name; + samr_AcctFlags acct_control; + [value(ndr_size_dom_sid0(&sid, ndr->flags))] uint32 sid_size; + /* The manual alignment is required because this + * structure is marked flag(NDR_NOALIGN) via the + * nbt_netlogon_packet below. + * + * However, both MUST only be present if sid_size > 0 + */ [flag(NDR_ALIGN4)] DATA_BLOB _pad; - nbt_server_type server_type; - GUID domain_uuid; - nbt_string forest; - nbt_string dns_domain; - nbt_string pdc_dns_name; - nbt_string domain; - nbt_string pdc_name; - nbt_string user_name; - nbt_string server_site; - nbt_string client_site; - uint8 dc_sock_addr_size; - [subcontext(0),subcontext_size(dc_sock_addr_size)] nbt_dc_sock_addr dc_sock_addr; - nbt_netlogon_version nt_version; + [subcontext(0),subcontext_size(sid_size)] dom_sid0 sid; + netlogon_nt_version_flags nt_version; uint16 lmnt_token; uint16 lm20_token; - } nbt_netlogon_response_from_pdc2; - - typedef enum netr_SamDatabaseID netr_SamDatabaseID; - - /* announce change to UAS or SAM */ - typedef struct { - netr_SamDatabaseID db_index; - hyper serial; - NTTIME timestamp; - } nbt_db_change; - - /* used to announce SAM changes */ - typedef struct { - uint32 serial_lo; - time_t timestamp; - uint32 pulse; - uint32 random; - astring pdc_name; - astring domain; - [flag(NDR_ALIGN2)] DATA_BLOB _pad; - nstring unicode_pdc_name; - nstring unicode_domain; - uint32 db_count; - nbt_db_change dbchange[db_count]; - [value(ndr_size_dom_sid0(&sid, ndr->flags))] uint32 sid_size; - [subcontext(0),subcontext_size(sid_size)] dom_sid0 sid; - nbt_netlogon_version nt_version; - uint16 lmnt_token; - uint16 lm20_token; - } nbt_netlogon_announce_uas; - - typedef [nodiscriminant] union { - [case(NETLOGON_QUERY_FOR_PDC)] nbt_netlogon_query_for_pdc pdc; - [case(NETLOGON_QUERY_FOR_PDC2)] nbt_netlogon_query_for_pdc2 pdc2; - [case(NETLOGON_ANNOUNCE_UAS)] nbt_netlogon_announce_uas uas; - [case(NETLOGON_RESPONSE_FROM_PDC)] nbt_netlogon_response_from_pdc response; - [case(NETLOGON_RESPONSE_FROM_PDC2)] nbt_netlogon_response_from_pdc2 response2; - [case(NETLOGON_RESPONSE_FROM_PDC_USER)] nbt_netlogon_response_from_pdc2 response2; - } nbt_netlogon_request; + } NETLOGON_SAM_LOGON_REQUEST; typedef [flag(NDR_NOALIGN),public] struct { - nbt_netlogon_command command; - [switch_is(command)] nbt_netlogon_request req; - } nbt_netlogon_packet; - - /*******************************************/ - /* CLDAP netlogon response */ - - /* note that these structures are very similar to, but not - quite identical to, the netlogon structures above */ - - typedef struct { - nbt_netlogon_command type; - nstring pdc_name; + netlogon_command command; + nstring server; nstring user_name; - nstring domain_name; - [value(1)] nbt_netlogon_version nt_version; + nstring domain; + netlogon_nt_version_flags nt_version; uint16 lmnt_token; uint16 lm20_token; - } nbt_cldap_netlogon_1; + } NETLOGON_SAM_LOGON_RESPONSE_NT40; - typedef struct { - nbt_netlogon_command type; + typedef [flag(NDR_NOALIGN),public] struct { + netlogon_command command; nstring pdc_name; nstring user_name; nstring domain_name; GUID domain_uuid; - GUID unknown_uuid; + GUID zero_uuid; nbt_string forest; nbt_string dns_domain; nbt_string pdc_dns_name; ipv4address pdc_ip; nbt_server_type server_type; - [value(3)] nbt_netlogon_version nt_version; + netlogon_nt_version_flags nt_version; uint16 lmnt_token; uint16 lm20_token; - } nbt_cldap_netlogon_3; + } NETLOGON_SAM_LOGON_RESPONSE; - typedef [public] struct { - nbt_netlogon_command type; - uint16 sbz; + /* response from pdc hand marshaled (we have an additional + * function that uses this structure), as it has 'optional' + * parts */ + typedef [flag(NDR_NOALIGN),public] struct { + netlogon_command command; + uint16 sbz; /* From the docs */ nbt_server_type server_type; GUID domain_uuid; nbt_string forest; @@ -526,148 +452,91 @@ interface nbt nbt_string user_name; nbt_string server_site; nbt_string client_site; - [value(5)] nbt_netlogon_version nt_version; - uint16 lmnt_token; - uint16 lm20_token; - } nbt_cldap_netlogon_5; - typedef struct { - nbt_netlogon_command type; - uint16 sbz; - nbt_server_type server_type; - GUID domain_uuid; - nbt_string forest; - nbt_string dns_domain; - nbt_string pdc_dns_name; - nbt_string domain; - nbt_string pdc_name; - nbt_string user_name; - nbt_string server_site; - nbt_string client_site; - uint8 dc_sock_addr_size; - [subcontext(0),subcontext_size(dc_sock_addr_size)] nbt_dc_sock_addr dc_sock_addr; - [value(13)] nbt_netlogon_version nt_version; - uint16 lmnt_token; - uint16 lm20_token; - } nbt_cldap_netlogon_13; + /* Optional on NETLOGON_NT_VERSION_5EX_WITH_IP */ + [value(ndr_size_nbt_sockaddr(&sockaddr, ndr->flags))] uint8 sockaddr_size; + [subcontext(0),subcontext_size(sockaddr_size)] nbt_sockaddr sockaddr; - typedef [public] struct { - nbt_netlogon_command type; - uint16 sbz; - nbt_server_type server_type; - GUID domain_uuid; - nbt_string forest; - nbt_string dns_domain; - nbt_string pdc_dns_name; - nbt_string domain; - nbt_string pdc_name; - nbt_string user_name; - nbt_string server_site; - nbt_string client_site; + /* Optional on NETLOGON_NT_VERSION_WITH_CLOSEST_SITE */ nbt_string next_closest_site; - [value(15)] nbt_netlogon_version nt_version; - uint16 lmnt_token; - uint16 lm20_token; - } nbt_cldap_netlogon_15; - typedef [public] struct { - nbt_netlogon_command type; - uint16 sbz; - nbt_server_type server_type; - GUID domain_uuid; - nbt_string forest; - nbt_string dns_domain; - nbt_string pdc_dns_name; - nbt_string domain; - nbt_string pdc_name; - nbt_string user_name; - nbt_string server_site; - nbt_string client_site; - uint8 dc_sock_addr_size; - [subcontext(0),subcontext_size(dc_sock_addr_size)] nbt_dc_sock_addr dc_sock_addr; - nbt_string next_closest_site; - [value(29)] nbt_netlogon_version nt_version; + netlogon_nt_version_flags nt_version; uint16 lmnt_token; uint16 lm20_token; - } nbt_cldap_netlogon_29; - - typedef [flag(NDR_NOALIGN),public,nodiscriminant] union { - [case(0)] nbt_cldap_netlogon_1 logon1; - [case(1)] nbt_cldap_netlogon_1 logon1; - [case(2)] nbt_cldap_netlogon_3 logon3; - [case(3)] nbt_cldap_netlogon_3 logon3; - [case(4)] nbt_cldap_netlogon_5 logon5; - [case(5)] nbt_cldap_netlogon_5 logon5; - [case(6)] nbt_cldap_netlogon_5 logon5; - [case(7)] nbt_cldap_netlogon_5 logon5; - [case(8)] nbt_cldap_netlogon_13 logon13; - [case(9)] nbt_cldap_netlogon_13 logon13; - [case(10)] nbt_cldap_netlogon_13 logon13; - [case(11)] nbt_cldap_netlogon_13 logon13; - [case(12)] nbt_cldap_netlogon_13 logon13; - [case(13)] nbt_cldap_netlogon_13 logon13; - [case(14)] nbt_cldap_netlogon_13 logon13; - [case(15)] nbt_cldap_netlogon_13 logon13; - [case(16)] nbt_cldap_netlogon_1 logon1; - [case(17)] nbt_cldap_netlogon_1 logon1; - [case(18)] nbt_cldap_netlogon_3 logon3; - [case(19)] nbt_cldap_netlogon_3 logon3; - [case(20)] nbt_cldap_netlogon_15 logon15; - [case(21)] nbt_cldap_netlogon_15 logon15; - [case(22)] nbt_cldap_netlogon_15 logon15; - [case(23)] nbt_cldap_netlogon_15 logon15; - [case(24)] nbt_cldap_netlogon_15 logon15; - [case(25)] nbt_cldap_netlogon_15 logon15; - [case(26)] nbt_cldap_netlogon_15 logon15; - [case(27)] nbt_cldap_netlogon_15 logon15; - [case(28)] nbt_cldap_netlogon_15 logon15; - [case(29)] nbt_cldap_netlogon_29 logon29; - [case(30)] nbt_cldap_netlogon_29 logon29; - [case(31)] nbt_cldap_netlogon_29 logon29; - } nbt_cldap_netlogon; - - /*******************************************/ - /* \MAILSLOT\NET\NTLOGON mailslot requests */ - typedef enum { - NTLOGON_SAM_LOGON = 0x12, - NTLOGON_SAM_LOGON_REPLY = 0x13, - NTLOGON_SAM_LOGON_REPLY15 = 0x15, - NTLOGON_RESPONSE_FROM_PDC2 = 0x17 - } nbt_ntlogon_command; + } NETLOGON_SAM_LOGON_RESPONSE_EX; + /* query for pdc request */ typedef struct { - uint16 request_count; - nstring computer_name; - nstring user_name; + astring computer_name; astring mailslot_name; - samr_AcctFlags acct_control; - [value(ndr_size_dom_sid0(&sid, ndr->flags))] uint32 sid_size; - [subcontext(0),subcontext_size(sid_size)] dom_sid0 sid; - nbt_netlogon_version nt_version; + [flag(NDR_ALIGN2)] DATA_BLOB _pad; + nstring unicode_name; + netlogon_nt_version_flags nt_version; uint16 lmnt_token; uint16 lm20_token; - } nbt_ntlogon_sam_logon; + } nbt_netlogon_query_for_pdc; - typedef struct { - nstring server; - nstring user_name; - nstring domain; - nbt_netlogon_version nt_version; + /* response from pdc */ + typedef [flag(NDR_NOALIGN),public] struct { + netlogon_command command; + astring pdc_name; + [flag(NDR_ALIGN2)] DATA_BLOB _pad; + nstring unicode_pdc_name; + nstring domain_name; + netlogon_nt_version_flags nt_version; uint16 lmnt_token; uint16 lm20_token; - } nbt_ntlogon_sam_logon_reply; + } nbt_netlogon_response_from_pdc; + + typedef enum netr_SamDatabaseID netr_SamDatabaseID; + + /* used to announce SAM changes - MS-NRPC 2.2.1.5.1 */ + typedef struct { + netr_SamDatabaseID db_index; + hyper serial; + NTTIME timestamp; + } nbt_db_change_info; + + typedef struct { + uint32 serial_lo; + time_t timestamp; + uint32 pulse; + uint32 random; + astring pdc_name; + astring domain; + [flag(NDR_ALIGN2)] DATA_BLOB _pad; + nstring unicode_pdc_name; + nstring unicode_domain; + uint32 db_count; + nbt_db_change_info dbchange[db_count]; + [value(ndr_size_dom_sid0(&sid, ndr->flags))] uint32 sid_size; + [subcontext(0),subcontext_size(sid_size)] dom_sid0 sid; + uint32 message_format_version; + uint32 message_token; + } NETLOGON_DB_CHANGE; typedef [nodiscriminant] union { - [case(NTLOGON_SAM_LOGON)] nbt_ntlogon_sam_logon logon; - [case(NTLOGON_SAM_LOGON_REPLY)] nbt_ntlogon_sam_logon_reply reply; - [case(NTLOGON_SAM_LOGON_REPLY15)] nbt_ntlogon_sam_logon_reply reply; - [case(NTLOGON_RESPONSE_FROM_PDC2)] nbt_netlogon_response_from_pdc2 reply2; - } nbt_ntlogon_request; + [case(LOGON_SAM_LOGON_REQUEST)] NETLOGON_SAM_LOGON_REQUEST logon; + [case(LOGON_PRIMARY_QUERY)] nbt_netlogon_query_for_pdc pdc; + [case(NETLOGON_ANNOUNCE_UAS)] NETLOGON_DB_CHANGE uas; + } nbt_netlogon_request; + +#if 0 + [case(NETLOGON_RESPONSE_FROM_PDC)] nbt_netlogon_response_from_pdc response; + [case(NETLOGON_RESPONSE_FROM_PDC_USER)] nbt_netlogon_response_from_pdc2 response2; + + [case(LOGON_SAM_LOGON_PAUSE_RESPONSE)] NETLOGON_SAM_LOGON_RESPONSE reply; + [case(LOGON_SAM_LOGON_RESPONSE)] NETLOGON_SAM_LOGON_RESPONSE reply; + [case(LOGON_SAM_LOGON_USER_UNKNOWN)] NETLOGON_SAM_LOGON_RESPONSE reply; + [case(LOGON_SAM_LOGON_RESPONSE_EX)] NETLOGON_SAM_LOGON_RESPONSE_EX reply_ex; + [case(LOGON_SAM_LOGON_PAUSE_RESPONSE_EX)] NETLOGON_SAM_LOGON_RESPONSE_EX reply_ex; + [case(LOGON_SAM_LOGON_USER_UNKNOWN_EX)] NETLOGON_SAM_LOGON_RESPONSE_EX reply_ex; +#endif typedef [flag(NDR_NOALIGN),public] struct { - nbt_ntlogon_command command; - [switch_is(command)] nbt_ntlogon_request req; - } nbt_ntlogon_packet; + netlogon_command command; + [switch_is(command)] nbt_netlogon_request req; + } nbt_netlogon_packet; /********************************************************/ /* \MAILSLOT\BROWSE mailslot requests */ -- cgit From e867ff52d7a88e15a74edd0dbc775fb698268480 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 22:16:15 +0200 Subject: s3: re-run make samba3-idl. Guenther --- source3/librpc/gen_ndr/nbt.h | 352 ++--- source3/librpc/gen_ndr/ndr_nbt.c | 2849 ++++++++++---------------------------- source3/librpc/gen_ndr/ndr_nbt.h | 61 +- 3 files changed, 847 insertions(+), 2415 deletions(-) diff --git a/source3/librpc/gen_ndr/nbt.h b/source3/librpc/gen_ndr/nbt.h index 847f63b9b8..264b00b84f 100644 --- a/source3/librpc/gen_ndr/nbt.h +++ b/source3/librpc/gen_ndr/nbt.h @@ -228,8 +228,8 @@ struct nbt_res_rec { enum nbt_qtype rr_type; enum nbt_qclass rr_class; uint32_t ttl; - union nbt_rdata rdata;/* [switch_is(((((rr_type)==NBT_QTYPE_NETBIOS)&&talloc_check_name(ndr,"struct ndr_push")&&((rdata).data.length==2))?0:rr_type))] */ -}/* [flag(LIBNDR_PRINT_ARRAY_HEX)] */; + union nbt_rdata rdata;/* [switch_is(rr_type)] */ +}/* [nopush,flag(LIBNDR_PRINT_ARRAY_HEX)] */; struct nbt_name_packet { uint16_t name_trn_id; @@ -390,28 +390,27 @@ struct nbt_dgram_packet { union dgram_data data;/* [switch_is(msg_type)] */ }/* [public,flag(LIBNDR_FLAG_NOALIGN|LIBNDR_FLAG_BIGENDIAN|LIBNDR_PRINT_ARRAY_HEX)] */; -enum nbt_netlogon_command -#ifndef USE_UINT_ENUMS - { - NETLOGON_QUERY_FOR_PDC=0x7, - NETLOGON_ANNOUNCE_UAS=0xa, - NETLOGON_RESPONSE_FROM_PDC=0xc, - NETLOGON_QUERY_FOR_PDC2=0x12, - NETLOGON_RESPONSE_FROM_PDC2=0x17, - NETLOGON_RESPONSE_FROM_PDC_USER=0x19 -} -#else - { __donnot_use_enum_nbt_netlogon_command=0x7FFFFFFF} -#define NETLOGON_QUERY_FOR_PDC ( 0x7 ) -#define NETLOGON_ANNOUNCE_UAS ( 0xa ) -#define NETLOGON_RESPONSE_FROM_PDC ( 0xc ) -#define NETLOGON_QUERY_FOR_PDC2 ( 0x12 ) -#define NETLOGON_RESPONSE_FROM_PDC2 ( 0x17 ) -#define NETLOGON_RESPONSE_FROM_PDC_USER ( 0x19 ) -#endif -; +struct nbt_sockaddr { + uint32_t sa_family; + const char * pdc_ip;/* [flag(LIBNDR_FLAG_BIGENDIAN)] */ + DATA_BLOB remaining;/* [flag(LIBNDR_FLAG_REMAINING)] */ +}/* [gensize,public] */; -/* bitmap nbt_netlogon_version */ +/* bitmap nbt_server_type */ +#define NBT_SERVER_PDC ( 0x00000001 ) +#define NBT_SERVER_GC ( 0x00000004 ) +#define NBT_SERVER_LDAP ( 0x00000008 ) +#define NBT_SERVER_DS ( 0x00000010 ) +#define NBT_SERVER_KDC ( 0x00000020 ) +#define NBT_SERVER_TIMESERV ( 0x00000040 ) +#define NBT_SERVER_CLOSEST ( 0x00000080 ) +#define NBT_SERVER_WRITABLE ( 0x00000100 ) +#define NBT_SERVER_GOOD_TIMESERV ( 0x00000200 ) +#define NBT_SERVER_NDNC ( 0x00000400 ) +#define NBT_SERVER_SELECT_SECRET_DOMAIN_6 ( 0x00000800 ) +#define NBT_SERVER_FULL_SECRET_DOMAIN_6 ( 0x00001000 ) + +/* bitmap netlogon_nt_version_flags */ #define NETLOGON_NT_VERSION_1 ( 0x00000001 ) #define NETLOGON_NT_VERSION_5 ( 0x00000002 ) #define NETLOGON_NT_VERSION_5EX ( 0x00000004 ) @@ -423,59 +422,79 @@ enum nbt_netlogon_command #define NETLOGON_NT_VERSION_LOCAL ( 0x40000000 ) #define NETLOGON_NT_VERSION_GC ( 0x80000000 ) -struct nbt_netlogon_query_for_pdc { - const char * computer_name;/* [flag(LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM)] */ +enum netlogon_command +#ifndef USE_UINT_ENUMS + { + LOGON_PRIMARY_QUERY=7, + NETLOGON_ANNOUNCE_UAS=10, + NETLOGON_RESPONSE_FROM_PDC=12, + LOGON_SAM_LOGON_REQUEST=18, + LOGON_SAM_LOGON_RESPONSE=19, + LOGON_SAM_LOGON_PAUSE_RESPONSE=20, + LOGON_SAM_LOGON_USER_UNKNOWN=21, + LOGON_SAM_LOGON_RESPONSE_EX=23, + LOGON_SAM_LOGON_PAUSE_RESPONSE_EX=24, + LOGON_SAM_LOGON_USER_UNKNOWN_EX=25 +} +#else + { __donnot_use_enum_netlogon_command=0x7FFFFFFF} +#define LOGON_PRIMARY_QUERY ( 7 ) +#define NETLOGON_ANNOUNCE_UAS ( 10 ) +#define NETLOGON_RESPONSE_FROM_PDC ( 12 ) +#define LOGON_SAM_LOGON_REQUEST ( 18 ) +#define LOGON_SAM_LOGON_RESPONSE ( 19 ) +#define LOGON_SAM_LOGON_PAUSE_RESPONSE ( 20 ) +#define LOGON_SAM_LOGON_USER_UNKNOWN ( 21 ) +#define LOGON_SAM_LOGON_RESPONSE_EX ( 23 ) +#define LOGON_SAM_LOGON_PAUSE_RESPONSE_EX ( 24 ) +#define LOGON_SAM_LOGON_USER_UNKNOWN_EX ( 25 ) +#endif +; + +struct NETLOGON_SAM_LOGON_REQUEST { + uint16_t request_count; + const char * computer_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ + const char * user_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ const char * mailslot_name;/* [flag(LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM)] */ - DATA_BLOB _pad;/* [flag(LIBNDR_FLAG_ALIGN2)] */ - const char * unicode_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ + uint32_t acct_control; + uint32_t sid_size;/* [value(ndr_size_dom_sid0(&sid,ndr->flags))] */ + DATA_BLOB _pad;/* [flag(LIBNDR_FLAG_ALIGN4)] */ + struct dom_sid0 sid;/* [subcontext_size(sid_size),subcontext(0)] */ uint32_t nt_version; uint16_t lmnt_token; uint16_t lm20_token; -}; +}/* [nopull,nopush] */; -struct nbt_netlogon_query_for_pdc2 { - uint16_t request_count; - const char * computer_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ +struct NETLOGON_SAM_LOGON_RESPONSE_NT40 { + enum netlogon_command command; + const char * server;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ const char * user_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ - const char * mailslot_name;/* [flag(LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM)] */ - uint32_t unknown[2]; + const char * domain;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ uint32_t nt_version; uint16_t lmnt_token; uint16_t lm20_token; -}; +}/* [public,flag(LIBNDR_FLAG_NOALIGN)] */; -struct nbt_netlogon_response_from_pdc { - const char * pdc_name;/* [flag(LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM)] */ - DATA_BLOB _pad;/* [flag(LIBNDR_FLAG_ALIGN2)] */ - const char * unicode_pdc_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ +struct NETLOGON_SAM_LOGON_RESPONSE { + enum netlogon_command command; + const char * pdc_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ + const char * user_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ const char * domain_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ + struct GUID domain_uuid; + struct GUID zero_uuid; + const char * forest; + const char * dns_domain; + const char * pdc_dns_name; + const char * pdc_ip; + uint32_t server_type; uint32_t nt_version; uint16_t lmnt_token; uint16_t lm20_token; -}; - -/* bitmap nbt_server_type */ -#define NBT_SERVER_PDC ( 0x00000001 ) -#define NBT_SERVER_GC ( 0x00000004 ) -#define NBT_SERVER_LDAP ( 0x00000008 ) -#define NBT_SERVER_DS ( 0x00000010 ) -#define NBT_SERVER_KDC ( 0x00000020 ) -#define NBT_SERVER_TIMESERV ( 0x00000040 ) -#define NBT_SERVER_CLOSEST ( 0x00000080 ) -#define NBT_SERVER_WRITABLE ( 0x00000100 ) -#define NBT_SERVER_GOOD_TIMESERV ( 0x00000200 ) -#define NBT_SERVER_NDNC ( 0x00000400 ) -#define NBT_SERVER_SELECT_SECRET_DOMAIN_6 ( 0x00000800 ) -#define NBT_SERVER_FULL_SECRET_DOMAIN_6 ( 0x00001000 ) - -struct nbt_dc_sock_addr { - uint32_t family; - const char * pdc_ip;/* [flag(LIBNDR_FLAG_BIGENDIAN)] */ - DATA_BLOB remaining;/* [flag(LIBNDR_FLAG_REMAINING)] */ -}; +}/* [public,flag(LIBNDR_FLAG_NOALIGN)] */; -struct nbt_netlogon_response_from_pdc2 { - DATA_BLOB _pad;/* [flag(LIBNDR_FLAG_ALIGN4)] */ +struct NETLOGON_SAM_LOGON_RESPONSE_EX { + enum netlogon_command command; + uint16_t sbz; uint32_t server_type; struct GUID domain_uuid; const char * forest; @@ -486,22 +505,44 @@ struct nbt_netlogon_response_from_pdc2 { const char * user_name; const char * server_site; const char * client_site; - uint8_t dc_sock_addr_size; - struct nbt_dc_sock_addr dc_sock_addr;/* [subcontext_size(dc_sock_addr_size),subcontext(0)] */ + uint8_t sockaddr_size;/* [value(ndr_size_nbt_sockaddr(&sockaddr,ndr->flags))] */ + struct nbt_sockaddr sockaddr;/* [subcontext_size(sockaddr_size),subcontext(0)] */ + const char * next_closest_site; + uint32_t nt_version; + uint16_t lmnt_token; + uint16_t lm20_token; +}/* [public,flag(LIBNDR_FLAG_NOALIGN)] */; + +struct nbt_netlogon_query_for_pdc { + const char * computer_name;/* [flag(LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM)] */ + const char * mailslot_name;/* [flag(LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM)] */ + DATA_BLOB _pad;/* [flag(LIBNDR_FLAG_ALIGN2)] */ + const char * unicode_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ uint32_t nt_version; uint16_t lmnt_token; uint16_t lm20_token; }; +struct nbt_netlogon_response_from_pdc { + enum netlogon_command command; + const char * pdc_name;/* [flag(LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM)] */ + DATA_BLOB _pad;/* [flag(LIBNDR_FLAG_ALIGN2)] */ + const char * unicode_pdc_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ + const char * domain_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ + uint32_t nt_version; + uint16_t lmnt_token; + uint16_t lm20_token; +}/* [public,flag(LIBNDR_FLAG_NOALIGN)] */; + enum netr_SamDatabaseID; -struct nbt_db_change { +struct nbt_db_change_info { enum netr_SamDatabaseID db_index; uint64_t serial; NTTIME timestamp; }; -struct nbt_netlogon_announce_uas { +struct NETLOGON_DB_CHANGE { uint32_t serial_lo; time_t timestamp; uint32_t pulse; @@ -512,191 +553,24 @@ struct nbt_netlogon_announce_uas { const char * unicode_pdc_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ const char * unicode_domain;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ uint32_t db_count; - struct nbt_db_change *dbchange; + struct nbt_db_change_info *dbchange; uint32_t sid_size;/* [value(ndr_size_dom_sid0(&sid,ndr->flags))] */ struct dom_sid0 sid;/* [subcontext_size(sid_size),subcontext(0)] */ - uint32_t nt_version; - uint16_t lmnt_token; - uint16_t lm20_token; + uint32_t message_format_version; + uint32_t message_token; }; union nbt_netlogon_request { - struct nbt_netlogon_query_for_pdc pdc;/* [case(NETLOGON_QUERY_FOR_PDC)] */ - struct nbt_netlogon_query_for_pdc2 pdc2;/* [case(NETLOGON_QUERY_FOR_PDC2)] */ - struct nbt_netlogon_announce_uas uas;/* [case(NETLOGON_ANNOUNCE_UAS)] */ - struct nbt_netlogon_response_from_pdc response;/* [case(NETLOGON_RESPONSE_FROM_PDC)] */ - struct nbt_netlogon_response_from_pdc2 response2;/* [case(NETLOGON_RESPONSE_FROM_PDC2)] */ + struct NETLOGON_SAM_LOGON_REQUEST logon;/* [case(LOGON_SAM_LOGON_REQUEST)] */ + struct nbt_netlogon_query_for_pdc pdc;/* [case(LOGON_PRIMARY_QUERY)] */ + struct NETLOGON_DB_CHANGE uas;/* [case(NETLOGON_ANNOUNCE_UAS)] */ }/* [nodiscriminant] */; struct nbt_netlogon_packet { - enum nbt_netlogon_command command; + enum netlogon_command command; union nbt_netlogon_request req;/* [switch_is(command)] */ }/* [public,flag(LIBNDR_FLAG_NOALIGN)] */; -struct nbt_cldap_netlogon_1 { - enum nbt_netlogon_command type; - const char * pdc_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ - const char * user_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ - const char * domain_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ - uint32_t nt_version;/* [value] */ - uint16_t lmnt_token; - uint16_t lm20_token; -}; - -struct nbt_cldap_netlogon_3 { - enum nbt_netlogon_command type; - const char * pdc_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ - const char * user_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ - const char * domain_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ - struct GUID domain_uuid; - struct GUID unknown_uuid; - const char * forest; - const char * dns_domain; - const char * pdc_dns_name; - const char * pdc_ip; - uint32_t server_type; - uint32_t nt_version;/* [value(3)] */ - uint16_t lmnt_token; - uint16_t lm20_token; -}; - -struct nbt_cldap_netlogon_5 { - enum nbt_netlogon_command type; - uint16_t sbz; - uint32_t server_type; - struct GUID domain_uuid; - const char * forest; - const char * dns_domain; - const char * pdc_dns_name; - const char * domain; - const char * pdc_name; - const char * user_name; - const char * server_site; - const char * client_site; - uint32_t nt_version;/* [value(5)] */ - uint16_t lmnt_token; - uint16_t lm20_token; -}/* [public] */; - -struct nbt_cldap_netlogon_13 { - enum nbt_netlogon_command type; - uint16_t sbz; - uint32_t server_type; - struct GUID domain_uuid; - const char * forest; - const char * dns_domain; - const char * pdc_dns_name; - const char * domain; - const char * pdc_name; - const char * user_name; - const char * server_site; - const char * client_site; - uint8_t dc_sock_addr_size; - struct nbt_dc_sock_addr dc_sock_addr;/* [subcontext_size(dc_sock_addr_size),subcontext(0)] */ - uint32_t nt_version;/* [value(13)] */ - uint16_t lmnt_token; - uint16_t lm20_token; -}; - -struct nbt_cldap_netlogon_15 { - enum nbt_netlogon_command type; - uint16_t sbz; - uint32_t server_type; - struct GUID domain_uuid; - const char * forest; - const char * dns_domain; - const char * pdc_dns_name; - const char * domain; - const char * pdc_name; - const char * user_name; - const char * server_site; - const char * client_site; - const char * next_closest_site; - uint32_t nt_version;/* [value(15)] */ - uint16_t lmnt_token; - uint16_t lm20_token; -}/* [public] */; - -struct nbt_cldap_netlogon_29 { - enum nbt_netlogon_command type; - uint16_t sbz; - uint32_t server_type; - struct GUID domain_uuid; - const char * forest; - const char * dns_domain; - const char * pdc_dns_name; - const char * domain; - const char * pdc_name; - const char * user_name; - const char * server_site; - const char * client_site; - uint8_t dc_sock_addr_size; - struct nbt_dc_sock_addr dc_sock_addr;/* [subcontext_size(dc_sock_addr_size),subcontext(0)] */ - const char * next_closest_site; - uint32_t nt_version;/* [value(29)] */ - uint16_t lmnt_token; - uint16_t lm20_token; -}/* [public] */; - -union nbt_cldap_netlogon { - struct nbt_cldap_netlogon_1 logon1;/* [case(0)] */ - struct nbt_cldap_netlogon_3 logon3;/* [case(2)] */ - struct nbt_cldap_netlogon_5 logon5;/* [case(4)] */ - struct nbt_cldap_netlogon_13 logon13;/* [case(8)] */ - struct nbt_cldap_netlogon_15 logon15;/* [case(20)] */ - struct nbt_cldap_netlogon_29 logon29;/* [case(29)] */ -}/* [public,nodiscriminant,flag(LIBNDR_FLAG_NOALIGN)] */; - -enum nbt_ntlogon_command -#ifndef USE_UINT_ENUMS - { - NTLOGON_SAM_LOGON=0x12, - NTLOGON_SAM_LOGON_REPLY=0x13, - NTLOGON_SAM_LOGON_REPLY15=0x15, - NTLOGON_RESPONSE_FROM_PDC2=0x17 -} -#else - { __donnot_use_enum_nbt_ntlogon_command=0x7FFFFFFF} -#define NTLOGON_SAM_LOGON ( 0x12 ) -#define NTLOGON_SAM_LOGON_REPLY ( 0x13 ) -#define NTLOGON_SAM_LOGON_REPLY15 ( 0x15 ) -#define NTLOGON_RESPONSE_FROM_PDC2 ( 0x17 ) -#endif -; - -struct nbt_ntlogon_sam_logon { - uint16_t request_count; - const char * computer_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ - const char * user_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ - const char * mailslot_name;/* [flag(LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM)] */ - uint32_t acct_control; - uint32_t sid_size;/* [value(ndr_size_dom_sid0(&sid,ndr->flags))] */ - struct dom_sid0 sid;/* [subcontext_size(sid_size),subcontext(0)] */ - uint32_t nt_version; - uint16_t lmnt_token; - uint16_t lm20_token; -}; - -struct nbt_ntlogon_sam_logon_reply { - const char * server;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ - const char * user_name;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ - const char * domain;/* [flag(LIBNDR_FLAG_STR_NULLTERM)] */ - uint32_t nt_version; - uint16_t lmnt_token; - uint16_t lm20_token; -}; - -union nbt_ntlogon_request { - struct nbt_ntlogon_sam_logon logon;/* [case(NTLOGON_SAM_LOGON)] */ - struct nbt_ntlogon_sam_logon_reply reply;/* [case(NTLOGON_SAM_LOGON_REPLY)] */ - struct nbt_netlogon_response_from_pdc2 reply2;/* [case(NTLOGON_RESPONSE_FROM_PDC2)] */ -}/* [nodiscriminant] */; - -struct nbt_ntlogon_packet { - enum nbt_ntlogon_command command; - union nbt_ntlogon_request req;/* [switch_is(command)] */ -}/* [public,flag(LIBNDR_FLAG_NOALIGN)] */; - enum nbt_browse_opcode #ifndef USE_UINT_ENUMS { diff --git a/source3/librpc/gen_ndr/ndr_nbt.c b/source3/librpc/gen_ndr/ndr_nbt.c index d165e65329..84cfabda57 100644 --- a/source3/librpc/gen_ndr/ndr_nbt.c +++ b/source3/librpc/gen_ndr/ndr_nbt.c @@ -589,27 +589,6 @@ _PUBLIC_ void ndr_print_nbt_rdata(struct ndr_print *ndr, const char *name, const } } -static enum ndr_err_code ndr_push_nbt_res_rec(struct ndr_push *ndr, int ndr_flags, const struct nbt_res_rec *r) -{ - { - uint32_t _flags_save_STRUCT = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_PRINT_ARRAY_HEX); - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_nbt_name(ndr, NDR_SCALARS, &r->name)); - NDR_CHECK(ndr_push_nbt_qtype(ndr, NDR_SCALARS, r->rr_type)); - NDR_CHECK(ndr_push_nbt_qclass(ndr, NDR_SCALARS, r->rr_class)); - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->ttl)); - NDR_CHECK(ndr_push_set_switch_value(ndr, &r->rdata, ((((r->rr_type) == NBT_QTYPE_NETBIOS) && talloc_check_name(ndr, "struct ndr_push") && ((r->rdata).data.length == 2))?0:r->rr_type))); - NDR_CHECK(ndr_push_nbt_rdata(ndr, NDR_SCALARS, &r->rdata)); - } - if (ndr_flags & NDR_BUFFERS) { - } - ndr->flags = _flags_save_STRUCT; - } - return NDR_ERR_SUCCESS; -} - static enum ndr_err_code ndr_pull_nbt_res_rec(struct ndr_pull *ndr, int ndr_flags, struct nbt_res_rec *r) { { @@ -621,7 +600,7 @@ static enum ndr_err_code ndr_pull_nbt_res_rec(struct ndr_pull *ndr, int ndr_flag NDR_CHECK(ndr_pull_nbt_qtype(ndr, NDR_SCALARS, &r->rr_type)); NDR_CHECK(ndr_pull_nbt_qclass(ndr, NDR_SCALARS, &r->rr_class)); NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->ttl)); - NDR_CHECK(ndr_pull_set_switch_value(ndr, &r->rdata, ((((r->rr_type) == NBT_QTYPE_NETBIOS) && talloc_check_name(ndr, "struct ndr_push") && ((r->rdata).data.length == 2))?0:r->rr_type))); + NDR_CHECK(ndr_pull_set_switch_value(ndr, &r->rdata, r->rr_type)); NDR_CHECK(ndr_pull_nbt_rdata(ndr, NDR_SCALARS, &r->rdata)); } if (ndr_flags & NDR_BUFFERS) { @@ -642,7 +621,7 @@ _PUBLIC_ void ndr_print_nbt_res_rec(struct ndr_print *ndr, const char *name, con ndr_print_nbt_qtype(ndr, "rr_type", r->rr_type); ndr_print_nbt_qclass(ndr, "rr_class", r->rr_class); ndr_print_uint32(ndr, "ttl", r->ttl); - ndr_print_set_switch_value(ndr, &r->rdata, ((((r->rr_type) == NBT_QTYPE_NETBIOS) && talloc_check_name(ndr, "struct ndr_push") && ((r->rdata).data.length == 2))?0:r->rr_type)); + ndr_print_set_switch_value(ndr, &r->rdata, r->rr_type); ndr_print_nbt_rdata(ndr, "rdata", &r->rdata); ndr->depth--; ndr->flags = _flags_save_STRUCT; @@ -1548,13 +1527,138 @@ _PUBLIC_ void ndr_print_nbt_dgram_packet(struct ndr_print *ndr, const char *name } } -static enum ndr_err_code ndr_push_nbt_netlogon_command(struct ndr_push *ndr, int ndr_flags, enum nbt_netlogon_command r) +_PUBLIC_ enum ndr_err_code ndr_push_nbt_sockaddr(struct ndr_push *ndr, int ndr_flags, const struct nbt_sockaddr *r) +{ + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_push_align(ndr, 4)); + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->sa_family)); + { + uint32_t _flags_save_ipv4address = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_BIGENDIAN); + NDR_CHECK(ndr_push_ipv4address(ndr, NDR_SCALARS, r->pdc_ip)); + ndr->flags = _flags_save_ipv4address; + } + { + uint32_t _flags_save_DATA_BLOB = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_REMAINING); + NDR_CHECK(ndr_push_DATA_BLOB(ndr, NDR_SCALARS, r->remaining)); + ndr->flags = _flags_save_DATA_BLOB; + } + } + if (ndr_flags & NDR_BUFFERS) { + } + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ enum ndr_err_code ndr_pull_nbt_sockaddr(struct ndr_pull *ndr, int ndr_flags, struct nbt_sockaddr *r) +{ + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_pull_align(ndr, 4)); + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->sa_family)); + { + uint32_t _flags_save_ipv4address = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_BIGENDIAN); + NDR_CHECK(ndr_pull_ipv4address(ndr, NDR_SCALARS, &r->pdc_ip)); + ndr->flags = _flags_save_ipv4address; + } + { + uint32_t _flags_save_DATA_BLOB = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_REMAINING); + NDR_CHECK(ndr_pull_DATA_BLOB(ndr, NDR_SCALARS, &r->remaining)); + ndr->flags = _flags_save_DATA_BLOB; + } + } + if (ndr_flags & NDR_BUFFERS) { + } + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ void ndr_print_nbt_sockaddr(struct ndr_print *ndr, const char *name, const struct nbt_sockaddr *r) +{ + ndr_print_struct(ndr, name, "nbt_sockaddr"); + ndr->depth++; + ndr_print_uint32(ndr, "sa_family", r->sa_family); + ndr_print_ipv4address(ndr, "pdc_ip", r->pdc_ip); + ndr_print_DATA_BLOB(ndr, "remaining", r->remaining); + ndr->depth--; +} + +_PUBLIC_ size_t ndr_size_nbt_sockaddr(const struct nbt_sockaddr *r, int flags) +{ + return ndr_size_struct(r, flags, (ndr_push_flags_fn_t)ndr_push_nbt_sockaddr); +} + +_PUBLIC_ enum ndr_err_code ndr_push_nbt_server_type(struct ndr_push *ndr, int ndr_flags, uint32_t r) +{ + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r)); + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ enum ndr_err_code ndr_pull_nbt_server_type(struct ndr_pull *ndr, int ndr_flags, uint32_t *r) +{ + uint32_t v; + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &v)); + *r = v; + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ void ndr_print_nbt_server_type(struct ndr_print *ndr, const char *name, uint32_t r) +{ + ndr_print_uint32(ndr, name, r); + ndr->depth++; + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_PDC", NBT_SERVER_PDC, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_GC", NBT_SERVER_GC, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_LDAP", NBT_SERVER_LDAP, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_DS", NBT_SERVER_DS, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_KDC", NBT_SERVER_KDC, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_TIMESERV", NBT_SERVER_TIMESERV, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_CLOSEST", NBT_SERVER_CLOSEST, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_WRITABLE", NBT_SERVER_WRITABLE, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_GOOD_TIMESERV", NBT_SERVER_GOOD_TIMESERV, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_NDNC", NBT_SERVER_NDNC, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_SELECT_SECRET_DOMAIN_6", NBT_SERVER_SELECT_SECRET_DOMAIN_6, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_FULL_SECRET_DOMAIN_6", NBT_SERVER_FULL_SECRET_DOMAIN_6, r); + ndr->depth--; +} + +_PUBLIC_ enum ndr_err_code ndr_push_netlogon_nt_version_flags(struct ndr_push *ndr, int ndr_flags, uint32_t r) +{ + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r)); + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ enum ndr_err_code ndr_pull_netlogon_nt_version_flags(struct ndr_pull *ndr, int ndr_flags, uint32_t *r) +{ + uint32_t v; + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &v)); + *r = v; + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ void ndr_print_netlogon_nt_version_flags(struct ndr_print *ndr, const char *name, uint32_t r) +{ + ndr_print_uint32(ndr, name, r); + ndr->depth++; + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_1", NETLOGON_NT_VERSION_1, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_5", NETLOGON_NT_VERSION_5, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_5EX", NETLOGON_NT_VERSION_5EX, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_5EX_WITH_IP", NETLOGON_NT_VERSION_5EX_WITH_IP, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_WITH_CLOSEST_SITE", NETLOGON_NT_VERSION_WITH_CLOSEST_SITE, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_AVIOD_NT4EMUL", NETLOGON_NT_VERSION_AVIOD_NT4EMUL, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_PDC", NETLOGON_NT_VERSION_PDC, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_IP", NETLOGON_NT_VERSION_IP, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_LOCAL", NETLOGON_NT_VERSION_LOCAL, r); + ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_GC", NETLOGON_NT_VERSION_GC, r); + ndr->depth--; +} + +_PUBLIC_ enum ndr_err_code ndr_push_netlogon_command(struct ndr_push *ndr, int ndr_flags, enum netlogon_command r) { NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r)); return NDR_ERR_SUCCESS; } -static enum ndr_err_code ndr_pull_nbt_netlogon_command(struct ndr_pull *ndr, int ndr_flags, enum nbt_netlogon_command *r) +_PUBLIC_ enum ndr_err_code ndr_pull_netlogon_command(struct ndr_pull *ndr, int ndr_flags, enum netlogon_command *r) { uint16_t v; NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &v)); @@ -1562,64 +1666,353 @@ static enum ndr_err_code ndr_pull_nbt_netlogon_command(struct ndr_pull *ndr, int return NDR_ERR_SUCCESS; } -_PUBLIC_ void ndr_print_nbt_netlogon_command(struct ndr_print *ndr, const char *name, enum nbt_netlogon_command r) +_PUBLIC_ void ndr_print_netlogon_command(struct ndr_print *ndr, const char *name, enum netlogon_command r) { const char *val = NULL; switch (r) { - case NETLOGON_QUERY_FOR_PDC: val = "NETLOGON_QUERY_FOR_PDC"; break; + case LOGON_PRIMARY_QUERY: val = "LOGON_PRIMARY_QUERY"; break; case NETLOGON_ANNOUNCE_UAS: val = "NETLOGON_ANNOUNCE_UAS"; break; case NETLOGON_RESPONSE_FROM_PDC: val = "NETLOGON_RESPONSE_FROM_PDC"; break; - case NETLOGON_QUERY_FOR_PDC2: val = "NETLOGON_QUERY_FOR_PDC2"; break; - case NETLOGON_RESPONSE_FROM_PDC2: val = "NETLOGON_RESPONSE_FROM_PDC2"; break; - case NETLOGON_RESPONSE_FROM_PDC_USER: val = "NETLOGON_RESPONSE_FROM_PDC_USER"; break; + case LOGON_SAM_LOGON_REQUEST: val = "LOGON_SAM_LOGON_REQUEST"; break; + case LOGON_SAM_LOGON_RESPONSE: val = "LOGON_SAM_LOGON_RESPONSE"; break; + case LOGON_SAM_LOGON_PAUSE_RESPONSE: val = "LOGON_SAM_LOGON_PAUSE_RESPONSE"; break; + case LOGON_SAM_LOGON_USER_UNKNOWN: val = "LOGON_SAM_LOGON_USER_UNKNOWN"; break; + case LOGON_SAM_LOGON_RESPONSE_EX: val = "LOGON_SAM_LOGON_RESPONSE_EX"; break; + case LOGON_SAM_LOGON_PAUSE_RESPONSE_EX: val = "LOGON_SAM_LOGON_PAUSE_RESPONSE_EX"; break; + case LOGON_SAM_LOGON_USER_UNKNOWN_EX: val = "LOGON_SAM_LOGON_USER_UNKNOWN_EX"; break; } ndr_print_enum(ndr, name, "ENUM", val, r); } -static enum ndr_err_code ndr_push_nbt_netlogon_version(struct ndr_push *ndr, int ndr_flags, uint32_t r) +_PUBLIC_ void ndr_print_NETLOGON_SAM_LOGON_REQUEST(struct ndr_print *ndr, const char *name, const struct NETLOGON_SAM_LOGON_REQUEST *r) +{ + ndr_print_struct(ndr, name, "NETLOGON_SAM_LOGON_REQUEST"); + ndr->depth++; + ndr_print_uint16(ndr, "request_count", r->request_count); + ndr_print_string(ndr, "computer_name", r->computer_name); + ndr_print_string(ndr, "user_name", r->user_name); + ndr_print_string(ndr, "mailslot_name", r->mailslot_name); + ndr_print_samr_AcctFlags(ndr, "acct_control", r->acct_control); + ndr_print_uint32(ndr, "sid_size", (ndr->flags & LIBNDR_PRINT_SET_VALUES)?ndr_size_dom_sid0(&r->sid, ndr->flags):r->sid_size); + ndr_print_DATA_BLOB(ndr, "_pad", r->_pad); + ndr_print_dom_sid0(ndr, "sid", &r->sid); + ndr_print_netlogon_nt_version_flags(ndr, "nt_version", r->nt_version); + ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); + ndr_print_uint16(ndr, "lm20_token", r->lm20_token); + ndr->depth--; +} + +_PUBLIC_ enum ndr_err_code ndr_push_NETLOGON_SAM_LOGON_RESPONSE_NT40(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_SAM_LOGON_RESPONSE_NT40 *r) { { - uint32_t _flags_save_BITMAP = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_LITTLE_ENDIAN); - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r)); - ndr->flags = _flags_save_BITMAP; + uint32_t _flags_save_STRUCT = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_push_align(ndr, 4)); + NDR_CHECK(ndr_push_netlogon_command(ndr, NDR_SCALARS, r->command)); + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->server)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->user_name)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->domain)); + ndr->flags = _flags_save_string; + } + NDR_CHECK(ndr_push_netlogon_nt_version_flags(ndr, NDR_SCALARS, r->nt_version)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); + } + if (ndr_flags & NDR_BUFFERS) { + } + ndr->flags = _flags_save_STRUCT; } return NDR_ERR_SUCCESS; } -static enum ndr_err_code ndr_pull_nbt_netlogon_version(struct ndr_pull *ndr, int ndr_flags, uint32_t *r) +_PUBLIC_ enum ndr_err_code ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_NT40(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_SAM_LOGON_RESPONSE_NT40 *r) +{ + { + uint32_t _flags_save_STRUCT = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_pull_align(ndr, 4)); + NDR_CHECK(ndr_pull_netlogon_command(ndr, NDR_SCALARS, &r->command)); + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->server)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->user_name)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->domain)); + ndr->flags = _flags_save_string; + } + NDR_CHECK(ndr_pull_netlogon_nt_version_flags(ndr, NDR_SCALARS, &r->nt_version)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); + } + if (ndr_flags & NDR_BUFFERS) { + } + ndr->flags = _flags_save_STRUCT; + } + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ void ndr_print_NETLOGON_SAM_LOGON_RESPONSE_NT40(struct ndr_print *ndr, const char *name, const struct NETLOGON_SAM_LOGON_RESPONSE_NT40 *r) +{ + ndr_print_struct(ndr, name, "NETLOGON_SAM_LOGON_RESPONSE_NT40"); + { + uint32_t _flags_save_STRUCT = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); + ndr->depth++; + ndr_print_netlogon_command(ndr, "command", r->command); + ndr_print_string(ndr, "server", r->server); + ndr_print_string(ndr, "user_name", r->user_name); + ndr_print_string(ndr, "domain", r->domain); + ndr_print_netlogon_nt_version_flags(ndr, "nt_version", r->nt_version); + ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); + ndr_print_uint16(ndr, "lm20_token", r->lm20_token); + ndr->depth--; + ndr->flags = _flags_save_STRUCT; + } +} + +_PUBLIC_ enum ndr_err_code ndr_push_NETLOGON_SAM_LOGON_RESPONSE(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_SAM_LOGON_RESPONSE *r) +{ + { + uint32_t _flags_save_STRUCT = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_push_align(ndr, 4)); + NDR_CHECK(ndr_push_netlogon_command(ndr, NDR_SCALARS, r->command)); + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->pdc_name)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->user_name)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->domain_name)); + ndr->flags = _flags_save_string; + } + NDR_CHECK(ndr_push_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); + NDR_CHECK(ndr_push_GUID(ndr, NDR_SCALARS, &r->zero_uuid)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->forest)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->dns_domain)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_dns_name)); + NDR_CHECK(ndr_push_ipv4address(ndr, NDR_SCALARS, r->pdc_ip)); + NDR_CHECK(ndr_push_nbt_server_type(ndr, NDR_SCALARS, r->server_type)); + NDR_CHECK(ndr_push_netlogon_nt_version_flags(ndr, NDR_SCALARS, r->nt_version)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); + } + if (ndr_flags & NDR_BUFFERS) { + } + ndr->flags = _flags_save_STRUCT; + } + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ enum ndr_err_code ndr_pull_NETLOGON_SAM_LOGON_RESPONSE(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_SAM_LOGON_RESPONSE *r) +{ + { + uint32_t _flags_save_STRUCT = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_pull_align(ndr, 4)); + NDR_CHECK(ndr_pull_netlogon_command(ndr, NDR_SCALARS, &r->command)); + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->pdc_name)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->user_name)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->domain_name)); + ndr->flags = _flags_save_string; + } + NDR_CHECK(ndr_pull_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); + NDR_CHECK(ndr_pull_GUID(ndr, NDR_SCALARS, &r->zero_uuid)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->forest)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->dns_domain)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_dns_name)); + NDR_CHECK(ndr_pull_ipv4address(ndr, NDR_SCALARS, &r->pdc_ip)); + NDR_CHECK(ndr_pull_nbt_server_type(ndr, NDR_SCALARS, &r->server_type)); + NDR_CHECK(ndr_pull_netlogon_nt_version_flags(ndr, NDR_SCALARS, &r->nt_version)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); + } + if (ndr_flags & NDR_BUFFERS) { + } + ndr->flags = _flags_save_STRUCT; + } + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ void ndr_print_NETLOGON_SAM_LOGON_RESPONSE(struct ndr_print *ndr, const char *name, const struct NETLOGON_SAM_LOGON_RESPONSE *r) +{ + ndr_print_struct(ndr, name, "NETLOGON_SAM_LOGON_RESPONSE"); + { + uint32_t _flags_save_STRUCT = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); + ndr->depth++; + ndr_print_netlogon_command(ndr, "command", r->command); + ndr_print_string(ndr, "pdc_name", r->pdc_name); + ndr_print_string(ndr, "user_name", r->user_name); + ndr_print_string(ndr, "domain_name", r->domain_name); + ndr_print_GUID(ndr, "domain_uuid", &r->domain_uuid); + ndr_print_GUID(ndr, "zero_uuid", &r->zero_uuid); + ndr_print_nbt_string(ndr, "forest", r->forest); + ndr_print_nbt_string(ndr, "dns_domain", r->dns_domain); + ndr_print_nbt_string(ndr, "pdc_dns_name", r->pdc_dns_name); + ndr_print_ipv4address(ndr, "pdc_ip", r->pdc_ip); + ndr_print_nbt_server_type(ndr, "server_type", r->server_type); + ndr_print_netlogon_nt_version_flags(ndr, "nt_version", r->nt_version); + ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); + ndr_print_uint16(ndr, "lm20_token", r->lm20_token); + ndr->depth--; + ndr->flags = _flags_save_STRUCT; + } +} + +_PUBLIC_ enum ndr_err_code ndr_push_NETLOGON_SAM_LOGON_RESPONSE_EX(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_SAM_LOGON_RESPONSE_EX *r) +{ + { + uint32_t _flags_save_STRUCT = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_push_align(ndr, 4)); + NDR_CHECK(ndr_push_netlogon_command(ndr, NDR_SCALARS, r->command)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->sbz)); + NDR_CHECK(ndr_push_nbt_server_type(ndr, NDR_SCALARS, r->server_type)); + NDR_CHECK(ndr_push_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->forest)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->dns_domain)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_dns_name)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->domain)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_name)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->user_name)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->server_site)); + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->client_site)); + NDR_CHECK(ndr_push_uint8(ndr, NDR_SCALARS, ndr_size_nbt_sockaddr(&r->sockaddr, ndr->flags))); + { + struct ndr_push *_ndr_sockaddr; + NDR_CHECK(ndr_push_subcontext_start(ndr, &_ndr_sockaddr, 0, ndr_size_nbt_sockaddr(&r->sockaddr, ndr->flags))); + NDR_CHECK(ndr_push_nbt_sockaddr(_ndr_sockaddr, NDR_SCALARS, &r->sockaddr)); + NDR_CHECK(ndr_push_subcontext_end(ndr, _ndr_sockaddr, 0, ndr_size_nbt_sockaddr(&r->sockaddr, ndr->flags))); + } + NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->next_closest_site)); + NDR_CHECK(ndr_push_netlogon_nt_version_flags(ndr, NDR_SCALARS, r->nt_version)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); + } + if (ndr_flags & NDR_BUFFERS) { + } + ndr->flags = _flags_save_STRUCT; + } + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ enum ndr_err_code ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_EX(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_SAM_LOGON_RESPONSE_EX *r) { - uint32_t v; { - uint32_t _flags_save_BITMAP = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_LITTLE_ENDIAN); - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &v)); - *r = v; - ndr->flags = _flags_save_BITMAP; + uint32_t _flags_save_STRUCT = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_pull_align(ndr, 4)); + NDR_CHECK(ndr_pull_netlogon_command(ndr, NDR_SCALARS, &r->command)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->sbz)); + NDR_CHECK(ndr_pull_nbt_server_type(ndr, NDR_SCALARS, &r->server_type)); + NDR_CHECK(ndr_pull_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->forest)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->dns_domain)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_dns_name)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->domain)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_name)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->user_name)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->server_site)); + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->client_site)); + NDR_CHECK(ndr_pull_uint8(ndr, NDR_SCALARS, &r->sockaddr_size)); + { + struct ndr_pull *_ndr_sockaddr; + NDR_CHECK(ndr_pull_subcontext_start(ndr, &_ndr_sockaddr, 0, r->sockaddr_size)); + NDR_CHECK(ndr_pull_nbt_sockaddr(_ndr_sockaddr, NDR_SCALARS, &r->sockaddr)); + NDR_CHECK(ndr_pull_subcontext_end(ndr, _ndr_sockaddr, 0, r->sockaddr_size)); + } + NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->next_closest_site)); + NDR_CHECK(ndr_pull_netlogon_nt_version_flags(ndr, NDR_SCALARS, &r->nt_version)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); + } + if (ndr_flags & NDR_BUFFERS) { + } + ndr->flags = _flags_save_STRUCT; } return NDR_ERR_SUCCESS; } -_PUBLIC_ void ndr_print_nbt_netlogon_version(struct ndr_print *ndr, const char *name, uint32_t r) +_PUBLIC_ void ndr_print_NETLOGON_SAM_LOGON_RESPONSE_EX(struct ndr_print *ndr, const char *name, const struct NETLOGON_SAM_LOGON_RESPONSE_EX *r) { + ndr_print_struct(ndr, name, "NETLOGON_SAM_LOGON_RESPONSE_EX"); { - uint32_t _flags_save_BITMAP = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_LITTLE_ENDIAN); - ndr_print_uint32(ndr, name, r); + uint32_t _flags_save_STRUCT = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); ndr->depth++; - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_1", NETLOGON_NT_VERSION_1, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_5", NETLOGON_NT_VERSION_5, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_5EX", NETLOGON_NT_VERSION_5EX, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_5EX_WITH_IP", NETLOGON_NT_VERSION_5EX_WITH_IP, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_WITH_CLOSEST_SITE", NETLOGON_NT_VERSION_WITH_CLOSEST_SITE, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_AVIOD_NT4EMUL", NETLOGON_NT_VERSION_AVIOD_NT4EMUL, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_PDC", NETLOGON_NT_VERSION_PDC, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_IP", NETLOGON_NT_VERSION_IP, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_LOCAL", NETLOGON_NT_VERSION_LOCAL, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NETLOGON_NT_VERSION_GC", NETLOGON_NT_VERSION_GC, r); + ndr_print_netlogon_command(ndr, "command", r->command); + ndr_print_uint16(ndr, "sbz", r->sbz); + ndr_print_nbt_server_type(ndr, "server_type", r->server_type); + ndr_print_GUID(ndr, "domain_uuid", &r->domain_uuid); + ndr_print_nbt_string(ndr, "forest", r->forest); + ndr_print_nbt_string(ndr, "dns_domain", r->dns_domain); + ndr_print_nbt_string(ndr, "pdc_dns_name", r->pdc_dns_name); + ndr_print_nbt_string(ndr, "domain", r->domain); + ndr_print_nbt_string(ndr, "pdc_name", r->pdc_name); + ndr_print_nbt_string(ndr, "user_name", r->user_name); + ndr_print_nbt_string(ndr, "server_site", r->server_site); + ndr_print_nbt_string(ndr, "client_site", r->client_site); + ndr_print_uint8(ndr, "sockaddr_size", (ndr->flags & LIBNDR_PRINT_SET_VALUES)?ndr_size_nbt_sockaddr(&r->sockaddr, ndr->flags):r->sockaddr_size); + ndr_print_nbt_sockaddr(ndr, "sockaddr", &r->sockaddr); + ndr_print_nbt_string(ndr, "next_closest_site", r->next_closest_site); + ndr_print_netlogon_nt_version_flags(ndr, "nt_version", r->nt_version); + ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); + ndr_print_uint16(ndr, "lm20_token", r->lm20_token); ndr->depth--; - ndr->flags = _flags_save_BITMAP; + ndr->flags = _flags_save_STRUCT; } } @@ -1651,7 +2044,7 @@ static enum ndr_err_code ndr_push_nbt_netlogon_query_for_pdc(struct ndr_push *nd NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->unicode_name)); ndr->flags = _flags_save_string; } - NDR_CHECK(ndr_push_nbt_netlogon_version(ndr, NDR_SCALARS, r->nt_version)); + NDR_CHECK(ndr_push_netlogon_nt_version_flags(ndr, NDR_SCALARS, r->nt_version)); NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); } @@ -1688,7 +2081,7 @@ static enum ndr_err_code ndr_pull_nbt_netlogon_query_for_pdc(struct ndr_pull *nd NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->unicode_name)); ndr->flags = _flags_save_string; } - NDR_CHECK(ndr_pull_nbt_netlogon_version(ndr, NDR_SCALARS, &r->nt_version)); + NDR_CHECK(ndr_pull_netlogon_nt_version_flags(ndr, NDR_SCALARS, &r->nt_version)); NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); } @@ -1705,2146 +2098,322 @@ _PUBLIC_ void ndr_print_nbt_netlogon_query_for_pdc(struct ndr_print *ndr, const ndr_print_string(ndr, "mailslot_name", r->mailslot_name); ndr_print_DATA_BLOB(ndr, "_pad", r->_pad); ndr_print_string(ndr, "unicode_name", r->unicode_name); - ndr_print_nbt_netlogon_version(ndr, "nt_version", r->nt_version); + ndr_print_netlogon_nt_version_flags(ndr, "nt_version", r->nt_version); ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); ndr_print_uint16(ndr, "lm20_token", r->lm20_token); ndr->depth--; } -static enum ndr_err_code ndr_push_nbt_netlogon_query_for_pdc2(struct ndr_push *ndr, int ndr_flags, const struct nbt_netlogon_query_for_pdc2 *r) -{ - uint32_t cntr_unknown_0; - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->request_count)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->computer_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->user_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->mailslot_name)); - ndr->flags = _flags_save_string; - } - for (cntr_unknown_0 = 0; cntr_unknown_0 < 2; cntr_unknown_0++) { - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->unknown[cntr_unknown_0])); - } - NDR_CHECK(ndr_push_nbt_netlogon_version(ndr, NDR_SCALARS, r->nt_version)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -static enum ndr_err_code ndr_pull_nbt_netlogon_query_for_pdc2(struct ndr_pull *ndr, int ndr_flags, struct nbt_netlogon_query_for_pdc2 *r) -{ - uint32_t cntr_unknown_0; - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->request_count)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->computer_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->user_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->mailslot_name)); - ndr->flags = _flags_save_string; - } - for (cntr_unknown_0 = 0; cntr_unknown_0 < 2; cntr_unknown_0++) { - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->unknown[cntr_unknown_0])); - } - NDR_CHECK(ndr_pull_nbt_netlogon_version(ndr, NDR_SCALARS, &r->nt_version)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_netlogon_query_for_pdc2(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_query_for_pdc2 *r) -{ - uint32_t cntr_unknown_0; - ndr_print_struct(ndr, name, "nbt_netlogon_query_for_pdc2"); - ndr->depth++; - ndr_print_uint16(ndr, "request_count", r->request_count); - ndr_print_string(ndr, "computer_name", r->computer_name); - ndr_print_string(ndr, "user_name", r->user_name); - ndr_print_string(ndr, "mailslot_name", r->mailslot_name); - ndr->print(ndr, "%s: ARRAY(%d)", "unknown", (int)2); - ndr->depth++; - for (cntr_unknown_0=0;cntr_unknown_0<2;cntr_unknown_0++) { - char *idx_0=NULL; - if (asprintf(&idx_0, "[%d]", cntr_unknown_0) != -1) { - ndr_print_uint32(ndr, "unknown", r->unknown[cntr_unknown_0]); - free(idx_0); - } - } - ndr->depth--; - ndr_print_nbt_netlogon_version(ndr, "nt_version", r->nt_version); - ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); - ndr_print_uint16(ndr, "lm20_token", r->lm20_token); - ndr->depth--; -} - -static enum ndr_err_code ndr_push_nbt_netlogon_response_from_pdc(struct ndr_push *ndr, int ndr_flags, const struct nbt_netlogon_response_from_pdc *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->pdc_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_DATA_BLOB = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN2); - NDR_CHECK(ndr_push_DATA_BLOB(ndr, NDR_SCALARS, r->_pad)); - ndr->flags = _flags_save_DATA_BLOB; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->unicode_pdc_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->domain_name)); - ndr->flags = _flags_save_string; - } - NDR_CHECK(ndr_push_nbt_netlogon_version(ndr, NDR_SCALARS, r->nt_version)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -static enum ndr_err_code ndr_pull_nbt_netlogon_response_from_pdc(struct ndr_pull *ndr, int ndr_flags, struct nbt_netlogon_response_from_pdc *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->pdc_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_DATA_BLOB = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN2); - NDR_CHECK(ndr_pull_DATA_BLOB(ndr, NDR_SCALARS, &r->_pad)); - ndr->flags = _flags_save_DATA_BLOB; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->unicode_pdc_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->domain_name)); - ndr->flags = _flags_save_string; - } - NDR_CHECK(ndr_pull_nbt_netlogon_version(ndr, NDR_SCALARS, &r->nt_version)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_netlogon_response_from_pdc(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_response_from_pdc *r) -{ - ndr_print_struct(ndr, name, "nbt_netlogon_response_from_pdc"); - ndr->depth++; - ndr_print_string(ndr, "pdc_name", r->pdc_name); - ndr_print_DATA_BLOB(ndr, "_pad", r->_pad); - ndr_print_string(ndr, "unicode_pdc_name", r->unicode_pdc_name); - ndr_print_string(ndr, "domain_name", r->domain_name); - ndr_print_nbt_netlogon_version(ndr, "nt_version", r->nt_version); - ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); - ndr_print_uint16(ndr, "lm20_token", r->lm20_token); - ndr->depth--; -} - -static enum ndr_err_code ndr_push_nbt_server_type(struct ndr_push *ndr, int ndr_flags, uint32_t r) -{ - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r)); - return NDR_ERR_SUCCESS; -} - -static enum ndr_err_code ndr_pull_nbt_server_type(struct ndr_pull *ndr, int ndr_flags, uint32_t *r) -{ - uint32_t v; - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &v)); - *r = v; - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_server_type(struct ndr_print *ndr, const char *name, uint32_t r) -{ - ndr_print_uint32(ndr, name, r); - ndr->depth++; - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_PDC", NBT_SERVER_PDC, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_GC", NBT_SERVER_GC, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_LDAP", NBT_SERVER_LDAP, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_DS", NBT_SERVER_DS, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_KDC", NBT_SERVER_KDC, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_TIMESERV", NBT_SERVER_TIMESERV, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_CLOSEST", NBT_SERVER_CLOSEST, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_WRITABLE", NBT_SERVER_WRITABLE, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_GOOD_TIMESERV", NBT_SERVER_GOOD_TIMESERV, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_NDNC", NBT_SERVER_NDNC, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_SELECT_SECRET_DOMAIN_6", NBT_SERVER_SELECT_SECRET_DOMAIN_6, r); - ndr_print_bitmap_flag(ndr, sizeof(uint32_t), "NBT_SERVER_FULL_SECRET_DOMAIN_6", NBT_SERVER_FULL_SECRET_DOMAIN_6, r); - ndr->depth--; -} - -static enum ndr_err_code ndr_push_nbt_dc_sock_addr(struct ndr_push *ndr, int ndr_flags, const struct nbt_dc_sock_addr *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->family)); - { - uint32_t _flags_save_ipv4address = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_BIGENDIAN); - NDR_CHECK(ndr_push_ipv4address(ndr, NDR_SCALARS, r->pdc_ip)); - ndr->flags = _flags_save_ipv4address; - } - { - uint32_t _flags_save_DATA_BLOB = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_REMAINING); - NDR_CHECK(ndr_push_DATA_BLOB(ndr, NDR_SCALARS, r->remaining)); - ndr->flags = _flags_save_DATA_BLOB; - } - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -static enum ndr_err_code ndr_pull_nbt_dc_sock_addr(struct ndr_pull *ndr, int ndr_flags, struct nbt_dc_sock_addr *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->family)); - { - uint32_t _flags_save_ipv4address = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_BIGENDIAN); - NDR_CHECK(ndr_pull_ipv4address(ndr, NDR_SCALARS, &r->pdc_ip)); - ndr->flags = _flags_save_ipv4address; - } - { - uint32_t _flags_save_DATA_BLOB = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_REMAINING); - NDR_CHECK(ndr_pull_DATA_BLOB(ndr, NDR_SCALARS, &r->remaining)); - ndr->flags = _flags_save_DATA_BLOB; - } - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_dc_sock_addr(struct ndr_print *ndr, const char *name, const struct nbt_dc_sock_addr *r) -{ - ndr_print_struct(ndr, name, "nbt_dc_sock_addr"); - ndr->depth++; - ndr_print_uint32(ndr, "family", r->family); - ndr_print_ipv4address(ndr, "pdc_ip", r->pdc_ip); - ndr_print_DATA_BLOB(ndr, "remaining", r->remaining); - ndr->depth--; -} - -static enum ndr_err_code ndr_push_nbt_netlogon_response_from_pdc2(struct ndr_push *ndr, int ndr_flags, const struct nbt_netlogon_response_from_pdc2 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - { - uint32_t _flags_save_DATA_BLOB = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN4); - NDR_CHECK(ndr_push_DATA_BLOB(ndr, NDR_SCALARS, r->_pad)); - ndr->flags = _flags_save_DATA_BLOB; - } - NDR_CHECK(ndr_push_nbt_server_type(ndr, NDR_SCALARS, r->server_type)); - NDR_CHECK(ndr_push_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->forest)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->dns_domain)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_dns_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->domain)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->user_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->server_site)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->client_site)); - NDR_CHECK(ndr_push_uint8(ndr, NDR_SCALARS, r->dc_sock_addr_size)); - { - struct ndr_push *_ndr_dc_sock_addr; - NDR_CHECK(ndr_push_subcontext_start(ndr, &_ndr_dc_sock_addr, 0, r->dc_sock_addr_size)); - NDR_CHECK(ndr_push_nbt_dc_sock_addr(_ndr_dc_sock_addr, NDR_SCALARS, &r->dc_sock_addr)); - NDR_CHECK(ndr_push_subcontext_end(ndr, _ndr_dc_sock_addr, 0, r->dc_sock_addr_size)); - } - NDR_CHECK(ndr_push_nbt_netlogon_version(ndr, NDR_SCALARS, r->nt_version)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -static enum ndr_err_code ndr_pull_nbt_netlogon_response_from_pdc2(struct ndr_pull *ndr, int ndr_flags, struct nbt_netlogon_response_from_pdc2 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - { - uint32_t _flags_save_DATA_BLOB = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN4); - NDR_CHECK(ndr_pull_DATA_BLOB(ndr, NDR_SCALARS, &r->_pad)); - ndr->flags = _flags_save_DATA_BLOB; - } - NDR_CHECK(ndr_pull_nbt_server_type(ndr, NDR_SCALARS, &r->server_type)); - NDR_CHECK(ndr_pull_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->forest)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->dns_domain)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_dns_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->domain)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->user_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->server_site)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->client_site)); - NDR_CHECK(ndr_pull_uint8(ndr, NDR_SCALARS, &r->dc_sock_addr_size)); - { - struct ndr_pull *_ndr_dc_sock_addr; - NDR_CHECK(ndr_pull_subcontext_start(ndr, &_ndr_dc_sock_addr, 0, r->dc_sock_addr_size)); - NDR_CHECK(ndr_pull_nbt_dc_sock_addr(_ndr_dc_sock_addr, NDR_SCALARS, &r->dc_sock_addr)); - NDR_CHECK(ndr_pull_subcontext_end(ndr, _ndr_dc_sock_addr, 0, r->dc_sock_addr_size)); - } - NDR_CHECK(ndr_pull_nbt_netlogon_version(ndr, NDR_SCALARS, &r->nt_version)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_netlogon_response_from_pdc2(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_response_from_pdc2 *r) -{ - ndr_print_struct(ndr, name, "nbt_netlogon_response_from_pdc2"); - ndr->depth++; - ndr_print_DATA_BLOB(ndr, "_pad", r->_pad); - ndr_print_nbt_server_type(ndr, "server_type", r->server_type); - ndr_print_GUID(ndr, "domain_uuid", &r->domain_uuid); - ndr_print_nbt_string(ndr, "forest", r->forest); - ndr_print_nbt_string(ndr, "dns_domain", r->dns_domain); - ndr_print_nbt_string(ndr, "pdc_dns_name", r->pdc_dns_name); - ndr_print_nbt_string(ndr, "domain", r->domain); - ndr_print_nbt_string(ndr, "pdc_name", r->pdc_name); - ndr_print_nbt_string(ndr, "user_name", r->user_name); - ndr_print_nbt_string(ndr, "server_site", r->server_site); - ndr_print_nbt_string(ndr, "client_site", r->client_site); - ndr_print_uint8(ndr, "dc_sock_addr_size", r->dc_sock_addr_size); - ndr_print_nbt_dc_sock_addr(ndr, "dc_sock_addr", &r->dc_sock_addr); - ndr_print_nbt_netlogon_version(ndr, "nt_version", r->nt_version); - ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); - ndr_print_uint16(ndr, "lm20_token", r->lm20_token); - ndr->depth--; -} - -static enum ndr_err_code ndr_push_nbt_db_change(struct ndr_push *ndr, int ndr_flags, const struct nbt_db_change *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 8)); - NDR_CHECK(ndr_push_netr_SamDatabaseID(ndr, NDR_SCALARS, r->db_index)); - NDR_CHECK(ndr_push_hyper(ndr, NDR_SCALARS, r->serial)); - NDR_CHECK(ndr_push_NTTIME(ndr, NDR_SCALARS, r->timestamp)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -static enum ndr_err_code ndr_pull_nbt_db_change(struct ndr_pull *ndr, int ndr_flags, struct nbt_db_change *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 8)); - NDR_CHECK(ndr_pull_netr_SamDatabaseID(ndr, NDR_SCALARS, &r->db_index)); - NDR_CHECK(ndr_pull_hyper(ndr, NDR_SCALARS, &r->serial)); - NDR_CHECK(ndr_pull_NTTIME(ndr, NDR_SCALARS, &r->timestamp)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_db_change(struct ndr_print *ndr, const char *name, const struct nbt_db_change *r) -{ - ndr_print_struct(ndr, name, "nbt_db_change"); - ndr->depth++; - ndr_print_netr_SamDatabaseID(ndr, "db_index", r->db_index); - ndr_print_hyper(ndr, "serial", r->serial); - ndr_print_NTTIME(ndr, "timestamp", r->timestamp); - ndr->depth--; -} - -static enum ndr_err_code ndr_push_nbt_netlogon_announce_uas(struct ndr_push *ndr, int ndr_flags, const struct nbt_netlogon_announce_uas *r) -{ - uint32_t cntr_dbchange_0; - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 8)); - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->serial_lo)); - NDR_CHECK(ndr_push_time_t(ndr, NDR_SCALARS, r->timestamp)); - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->pulse)); - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->random)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->pdc_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->domain)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_DATA_BLOB = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN2); - NDR_CHECK(ndr_push_DATA_BLOB(ndr, NDR_SCALARS, r->_pad)); - ndr->flags = _flags_save_DATA_BLOB; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->unicode_pdc_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->unicode_domain)); - ndr->flags = _flags_save_string; - } - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->db_count)); - for (cntr_dbchange_0 = 0; cntr_dbchange_0 < r->db_count; cntr_dbchange_0++) { - NDR_CHECK(ndr_push_nbt_db_change(ndr, NDR_SCALARS, &r->dbchange[cntr_dbchange_0])); - } - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, ndr_size_dom_sid0(&r->sid, ndr->flags))); - { - struct ndr_push *_ndr_sid; - NDR_CHECK(ndr_push_subcontext_start(ndr, &_ndr_sid, 0, ndr_size_dom_sid0(&r->sid, ndr->flags))); - NDR_CHECK(ndr_push_dom_sid0(_ndr_sid, NDR_SCALARS|NDR_BUFFERS, &r->sid)); - NDR_CHECK(ndr_push_subcontext_end(ndr, _ndr_sid, 0, ndr_size_dom_sid0(&r->sid, ndr->flags))); - } - NDR_CHECK(ndr_push_nbt_netlogon_version(ndr, NDR_SCALARS, r->nt_version)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -static enum ndr_err_code ndr_pull_nbt_netlogon_announce_uas(struct ndr_pull *ndr, int ndr_flags, struct nbt_netlogon_announce_uas *r) -{ - uint32_t cntr_dbchange_0; - TALLOC_CTX *_mem_save_dbchange_0; - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 8)); - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->serial_lo)); - NDR_CHECK(ndr_pull_time_t(ndr, NDR_SCALARS, &r->timestamp)); - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->pulse)); - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->random)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->pdc_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->domain)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_DATA_BLOB = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN2); - NDR_CHECK(ndr_pull_DATA_BLOB(ndr, NDR_SCALARS, &r->_pad)); - ndr->flags = _flags_save_DATA_BLOB; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->unicode_pdc_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->unicode_domain)); - ndr->flags = _flags_save_string; - } - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->db_count)); - NDR_PULL_ALLOC_N(ndr, r->dbchange, r->db_count); - _mem_save_dbchange_0 = NDR_PULL_GET_MEM_CTX(ndr); - NDR_PULL_SET_MEM_CTX(ndr, r->dbchange, 0); - for (cntr_dbchange_0 = 0; cntr_dbchange_0 < r->db_count; cntr_dbchange_0++) { - NDR_CHECK(ndr_pull_nbt_db_change(ndr, NDR_SCALARS, &r->dbchange[cntr_dbchange_0])); - } - NDR_PULL_SET_MEM_CTX(ndr, _mem_save_dbchange_0, 0); - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->sid_size)); - { - struct ndr_pull *_ndr_sid; - NDR_CHECK(ndr_pull_subcontext_start(ndr, &_ndr_sid, 0, r->sid_size)); - NDR_CHECK(ndr_pull_dom_sid0(_ndr_sid, NDR_SCALARS|NDR_BUFFERS, &r->sid)); - NDR_CHECK(ndr_pull_subcontext_end(ndr, _ndr_sid, 0, r->sid_size)); - } - NDR_CHECK(ndr_pull_nbt_netlogon_version(ndr, NDR_SCALARS, &r->nt_version)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_netlogon_announce_uas(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_announce_uas *r) -{ - uint32_t cntr_dbchange_0; - ndr_print_struct(ndr, name, "nbt_netlogon_announce_uas"); - ndr->depth++; - ndr_print_uint32(ndr, "serial_lo", r->serial_lo); - ndr_print_time_t(ndr, "timestamp", r->timestamp); - ndr_print_uint32(ndr, "pulse", r->pulse); - ndr_print_uint32(ndr, "random", r->random); - ndr_print_string(ndr, "pdc_name", r->pdc_name); - ndr_print_string(ndr, "domain", r->domain); - ndr_print_DATA_BLOB(ndr, "_pad", r->_pad); - ndr_print_string(ndr, "unicode_pdc_name", r->unicode_pdc_name); - ndr_print_string(ndr, "unicode_domain", r->unicode_domain); - ndr_print_uint32(ndr, "db_count", r->db_count); - ndr->print(ndr, "%s: ARRAY(%d)", "dbchange", (int)r->db_count); - ndr->depth++; - for (cntr_dbchange_0=0;cntr_dbchange_0db_count;cntr_dbchange_0++) { - char *idx_0=NULL; - if (asprintf(&idx_0, "[%d]", cntr_dbchange_0) != -1) { - ndr_print_nbt_db_change(ndr, "dbchange", &r->dbchange[cntr_dbchange_0]); - free(idx_0); - } - } - ndr->depth--; - ndr_print_uint32(ndr, "sid_size", (ndr->flags & LIBNDR_PRINT_SET_VALUES)?ndr_size_dom_sid0(&r->sid, ndr->flags):r->sid_size); - ndr_print_dom_sid0(ndr, "sid", &r->sid); - ndr_print_nbt_netlogon_version(ndr, "nt_version", r->nt_version); - ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); - ndr_print_uint16(ndr, "lm20_token", r->lm20_token); - ndr->depth--; -} - -static enum ndr_err_code ndr_push_nbt_netlogon_request(struct ndr_push *ndr, int ndr_flags, const union nbt_netlogon_request *r) -{ - if (ndr_flags & NDR_SCALARS) { - int level = ndr_push_get_switch_value(ndr, r); - switch (level) { - case NETLOGON_QUERY_FOR_PDC: { - NDR_CHECK(ndr_push_nbt_netlogon_query_for_pdc(ndr, NDR_SCALARS, &r->pdc)); - break; } - - case NETLOGON_QUERY_FOR_PDC2: { - NDR_CHECK(ndr_push_nbt_netlogon_query_for_pdc2(ndr, NDR_SCALARS, &r->pdc2)); - break; } - - case NETLOGON_ANNOUNCE_UAS: { - NDR_CHECK(ndr_push_nbt_netlogon_announce_uas(ndr, NDR_SCALARS, &r->uas)); - break; } - - case NETLOGON_RESPONSE_FROM_PDC: { - NDR_CHECK(ndr_push_nbt_netlogon_response_from_pdc(ndr, NDR_SCALARS, &r->response)); - break; } - - case NETLOGON_RESPONSE_FROM_PDC2: { - NDR_CHECK(ndr_push_nbt_netlogon_response_from_pdc2(ndr, NDR_SCALARS, &r->response2)); - break; } - - case NETLOGON_RESPONSE_FROM_PDC_USER: { - NDR_CHECK(ndr_push_nbt_netlogon_response_from_pdc2(ndr, NDR_SCALARS, &r->response2)); - break; } - - default: - return ndr_push_error(ndr, NDR_ERR_BAD_SWITCH, "Bad switch value %u", level); - } - } - if (ndr_flags & NDR_BUFFERS) { - int level = ndr_push_get_switch_value(ndr, r); - switch (level) { - case NETLOGON_QUERY_FOR_PDC: - break; - - case NETLOGON_QUERY_FOR_PDC2: - break; - - case NETLOGON_ANNOUNCE_UAS: - NDR_CHECK(ndr_push_nbt_netlogon_announce_uas(ndr, NDR_BUFFERS, &r->uas)); - break; - - case NETLOGON_RESPONSE_FROM_PDC: - break; - - case NETLOGON_RESPONSE_FROM_PDC2: - break; - - case NETLOGON_RESPONSE_FROM_PDC_USER: - break; - - default: - return ndr_push_error(ndr, NDR_ERR_BAD_SWITCH, "Bad switch value %u", level); - } - } - return NDR_ERR_SUCCESS; -} - -static enum ndr_err_code ndr_pull_nbt_netlogon_request(struct ndr_pull *ndr, int ndr_flags, union nbt_netlogon_request *r) -{ - int level; - level = ndr_pull_get_switch_value(ndr, r); - if (ndr_flags & NDR_SCALARS) { - switch (level) { - case NETLOGON_QUERY_FOR_PDC: { - NDR_CHECK(ndr_pull_nbt_netlogon_query_for_pdc(ndr, NDR_SCALARS, &r->pdc)); - break; } - - case NETLOGON_QUERY_FOR_PDC2: { - NDR_CHECK(ndr_pull_nbt_netlogon_query_for_pdc2(ndr, NDR_SCALARS, &r->pdc2)); - break; } - - case NETLOGON_ANNOUNCE_UAS: { - NDR_CHECK(ndr_pull_nbt_netlogon_announce_uas(ndr, NDR_SCALARS, &r->uas)); - break; } - - case NETLOGON_RESPONSE_FROM_PDC: { - NDR_CHECK(ndr_pull_nbt_netlogon_response_from_pdc(ndr, NDR_SCALARS, &r->response)); - break; } - - case NETLOGON_RESPONSE_FROM_PDC2: { - NDR_CHECK(ndr_pull_nbt_netlogon_response_from_pdc2(ndr, NDR_SCALARS, &r->response2)); - break; } - - case NETLOGON_RESPONSE_FROM_PDC_USER: { - NDR_CHECK(ndr_pull_nbt_netlogon_response_from_pdc2(ndr, NDR_SCALARS, &r->response2)); - break; } - - default: - return ndr_pull_error(ndr, NDR_ERR_BAD_SWITCH, "Bad switch value %u", level); - } - } - if (ndr_flags & NDR_BUFFERS) { - switch (level) { - case NETLOGON_QUERY_FOR_PDC: - break; - - case NETLOGON_QUERY_FOR_PDC2: - break; - - case NETLOGON_ANNOUNCE_UAS: - NDR_CHECK(ndr_pull_nbt_netlogon_announce_uas(ndr, NDR_BUFFERS, &r->uas)); - break; - - case NETLOGON_RESPONSE_FROM_PDC: - break; - - case NETLOGON_RESPONSE_FROM_PDC2: - break; - - case NETLOGON_RESPONSE_FROM_PDC_USER: - break; - - default: - return ndr_pull_error(ndr, NDR_ERR_BAD_SWITCH, "Bad switch value %u", level); - } - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_netlogon_request(struct ndr_print *ndr, const char *name, const union nbt_netlogon_request *r) -{ - int level; - level = ndr_print_get_switch_value(ndr, r); - ndr_print_union(ndr, name, level, "nbt_netlogon_request"); - switch (level) { - case NETLOGON_QUERY_FOR_PDC: - ndr_print_nbt_netlogon_query_for_pdc(ndr, "pdc", &r->pdc); - break; - - case NETLOGON_QUERY_FOR_PDC2: - ndr_print_nbt_netlogon_query_for_pdc2(ndr, "pdc2", &r->pdc2); - break; - - case NETLOGON_ANNOUNCE_UAS: - ndr_print_nbt_netlogon_announce_uas(ndr, "uas", &r->uas); - break; - - case NETLOGON_RESPONSE_FROM_PDC: - ndr_print_nbt_netlogon_response_from_pdc(ndr, "response", &r->response); - break; - - case NETLOGON_RESPONSE_FROM_PDC2: - ndr_print_nbt_netlogon_response_from_pdc2(ndr, "response2", &r->response2); - break; - - case NETLOGON_RESPONSE_FROM_PDC_USER: - ndr_print_nbt_netlogon_response_from_pdc2(ndr, "response2", &r->response2); - break; - - default: - ndr_print_bad_level(ndr, name, level); - } -} - -_PUBLIC_ enum ndr_err_code ndr_push_nbt_netlogon_packet(struct ndr_push *ndr, int ndr_flags, const struct nbt_netlogon_packet *r) -{ - { - uint32_t _flags_save_STRUCT = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 8)); - NDR_CHECK(ndr_push_nbt_netlogon_command(ndr, NDR_SCALARS, r->command)); - NDR_CHECK(ndr_push_set_switch_value(ndr, &r->req, r->command)); - NDR_CHECK(ndr_push_nbt_netlogon_request(ndr, NDR_SCALARS, &r->req)); - } - if (ndr_flags & NDR_BUFFERS) { - NDR_CHECK(ndr_push_nbt_netlogon_request(ndr, NDR_BUFFERS, &r->req)); - } - ndr->flags = _flags_save_STRUCT; - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_netlogon_packet(struct ndr_pull *ndr, int ndr_flags, struct nbt_netlogon_packet *r) -{ - { - uint32_t _flags_save_STRUCT = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 8)); - NDR_CHECK(ndr_pull_nbt_netlogon_command(ndr, NDR_SCALARS, &r->command)); - NDR_CHECK(ndr_pull_set_switch_value(ndr, &r->req, r->command)); - NDR_CHECK(ndr_pull_nbt_netlogon_request(ndr, NDR_SCALARS, &r->req)); - } - if (ndr_flags & NDR_BUFFERS) { - NDR_CHECK(ndr_pull_nbt_netlogon_request(ndr, NDR_BUFFERS, &r->req)); - } - ndr->flags = _flags_save_STRUCT; - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_netlogon_packet(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_packet *r) -{ - ndr_print_struct(ndr, name, "nbt_netlogon_packet"); - { - uint32_t _flags_save_STRUCT = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); - ndr->depth++; - ndr_print_nbt_netlogon_command(ndr, "command", r->command); - ndr_print_set_switch_value(ndr, &r->req, r->command); - ndr_print_nbt_netlogon_request(ndr, "req", &r->req); - ndr->depth--; - ndr->flags = _flags_save_STRUCT; - } -} - -static enum ndr_err_code ndr_push_nbt_cldap_netlogon_1(struct ndr_push *ndr, int ndr_flags, const struct nbt_cldap_netlogon_1 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_nbt_netlogon_command(ndr, NDR_SCALARS, r->type)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->pdc_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->user_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->domain_name)); - ndr->flags = _flags_save_string; - } - NDR_CHECK(ndr_push_nbt_netlogon_version(ndr, NDR_SCALARS, 1)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -static enum ndr_err_code ndr_pull_nbt_cldap_netlogon_1(struct ndr_pull *ndr, int ndr_flags, struct nbt_cldap_netlogon_1 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_nbt_netlogon_command(ndr, NDR_SCALARS, &r->type)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->pdc_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->user_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->domain_name)); - ndr->flags = _flags_save_string; - } - NDR_CHECK(ndr_pull_nbt_netlogon_version(ndr, NDR_SCALARS, &r->nt_version)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_cldap_netlogon_1(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_1 *r) -{ - ndr_print_struct(ndr, name, "nbt_cldap_netlogon_1"); - ndr->depth++; - ndr_print_nbt_netlogon_command(ndr, "type", r->type); - ndr_print_string(ndr, "pdc_name", r->pdc_name); - ndr_print_string(ndr, "user_name", r->user_name); - ndr_print_string(ndr, "domain_name", r->domain_name); - ndr_print_nbt_netlogon_version(ndr, "nt_version", (ndr->flags & LIBNDR_PRINT_SET_VALUES)?1:r->nt_version); - ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); - ndr_print_uint16(ndr, "lm20_token", r->lm20_token); - ndr->depth--; -} - -static enum ndr_err_code ndr_push_nbt_cldap_netlogon_3(struct ndr_push *ndr, int ndr_flags, const struct nbt_cldap_netlogon_3 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_nbt_netlogon_command(ndr, NDR_SCALARS, r->type)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->pdc_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->user_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->domain_name)); - ndr->flags = _flags_save_string; - } - NDR_CHECK(ndr_push_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_push_GUID(ndr, NDR_SCALARS, &r->unknown_uuid)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->forest)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->dns_domain)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_dns_name)); - NDR_CHECK(ndr_push_ipv4address(ndr, NDR_SCALARS, r->pdc_ip)); - NDR_CHECK(ndr_push_nbt_server_type(ndr, NDR_SCALARS, r->server_type)); - NDR_CHECK(ndr_push_nbt_netlogon_version(ndr, NDR_SCALARS, 3)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -static enum ndr_err_code ndr_pull_nbt_cldap_netlogon_3(struct ndr_pull *ndr, int ndr_flags, struct nbt_cldap_netlogon_3 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_nbt_netlogon_command(ndr, NDR_SCALARS, &r->type)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->pdc_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->user_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->domain_name)); - ndr->flags = _flags_save_string; - } - NDR_CHECK(ndr_pull_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_pull_GUID(ndr, NDR_SCALARS, &r->unknown_uuid)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->forest)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->dns_domain)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_dns_name)); - NDR_CHECK(ndr_pull_ipv4address(ndr, NDR_SCALARS, &r->pdc_ip)); - NDR_CHECK(ndr_pull_nbt_server_type(ndr, NDR_SCALARS, &r->server_type)); - NDR_CHECK(ndr_pull_nbt_netlogon_version(ndr, NDR_SCALARS, &r->nt_version)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_cldap_netlogon_3(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_3 *r) -{ - ndr_print_struct(ndr, name, "nbt_cldap_netlogon_3"); - ndr->depth++; - ndr_print_nbt_netlogon_command(ndr, "type", r->type); - ndr_print_string(ndr, "pdc_name", r->pdc_name); - ndr_print_string(ndr, "user_name", r->user_name); - ndr_print_string(ndr, "domain_name", r->domain_name); - ndr_print_GUID(ndr, "domain_uuid", &r->domain_uuid); - ndr_print_GUID(ndr, "unknown_uuid", &r->unknown_uuid); - ndr_print_nbt_string(ndr, "forest", r->forest); - ndr_print_nbt_string(ndr, "dns_domain", r->dns_domain); - ndr_print_nbt_string(ndr, "pdc_dns_name", r->pdc_dns_name); - ndr_print_ipv4address(ndr, "pdc_ip", r->pdc_ip); - ndr_print_nbt_server_type(ndr, "server_type", r->server_type); - ndr_print_nbt_netlogon_version(ndr, "nt_version", (ndr->flags & LIBNDR_PRINT_SET_VALUES)?3:r->nt_version); - ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); - ndr_print_uint16(ndr, "lm20_token", r->lm20_token); - ndr->depth--; -} - -_PUBLIC_ enum ndr_err_code ndr_push_nbt_cldap_netlogon_5(struct ndr_push *ndr, int ndr_flags, const struct nbt_cldap_netlogon_5 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_nbt_netlogon_command(ndr, NDR_SCALARS, r->type)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->sbz)); - NDR_CHECK(ndr_push_nbt_server_type(ndr, NDR_SCALARS, r->server_type)); - NDR_CHECK(ndr_push_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->forest)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->dns_domain)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_dns_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->domain)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->user_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->server_site)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->client_site)); - NDR_CHECK(ndr_push_nbt_netlogon_version(ndr, NDR_SCALARS, 5)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_cldap_netlogon_5(struct ndr_pull *ndr, int ndr_flags, struct nbt_cldap_netlogon_5 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_nbt_netlogon_command(ndr, NDR_SCALARS, &r->type)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->sbz)); - NDR_CHECK(ndr_pull_nbt_server_type(ndr, NDR_SCALARS, &r->server_type)); - NDR_CHECK(ndr_pull_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->forest)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->dns_domain)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_dns_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->domain)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->user_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->server_site)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->client_site)); - NDR_CHECK(ndr_pull_nbt_netlogon_version(ndr, NDR_SCALARS, &r->nt_version)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_cldap_netlogon_5(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_5 *r) -{ - ndr_print_struct(ndr, name, "nbt_cldap_netlogon_5"); - ndr->depth++; - ndr_print_nbt_netlogon_command(ndr, "type", r->type); - ndr_print_uint16(ndr, "sbz", r->sbz); - ndr_print_nbt_server_type(ndr, "server_type", r->server_type); - ndr_print_GUID(ndr, "domain_uuid", &r->domain_uuid); - ndr_print_nbt_string(ndr, "forest", r->forest); - ndr_print_nbt_string(ndr, "dns_domain", r->dns_domain); - ndr_print_nbt_string(ndr, "pdc_dns_name", r->pdc_dns_name); - ndr_print_nbt_string(ndr, "domain", r->domain); - ndr_print_nbt_string(ndr, "pdc_name", r->pdc_name); - ndr_print_nbt_string(ndr, "user_name", r->user_name); - ndr_print_nbt_string(ndr, "server_site", r->server_site); - ndr_print_nbt_string(ndr, "client_site", r->client_site); - ndr_print_nbt_netlogon_version(ndr, "nt_version", (ndr->flags & LIBNDR_PRINT_SET_VALUES)?5:r->nt_version); - ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); - ndr_print_uint16(ndr, "lm20_token", r->lm20_token); - ndr->depth--; -} - -static enum ndr_err_code ndr_push_nbt_cldap_netlogon_13(struct ndr_push *ndr, int ndr_flags, const struct nbt_cldap_netlogon_13 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_nbt_netlogon_command(ndr, NDR_SCALARS, r->type)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->sbz)); - NDR_CHECK(ndr_push_nbt_server_type(ndr, NDR_SCALARS, r->server_type)); - NDR_CHECK(ndr_push_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->forest)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->dns_domain)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_dns_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->domain)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->user_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->server_site)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->client_site)); - NDR_CHECK(ndr_push_uint8(ndr, NDR_SCALARS, r->dc_sock_addr_size)); - { - struct ndr_push *_ndr_dc_sock_addr; - NDR_CHECK(ndr_push_subcontext_start(ndr, &_ndr_dc_sock_addr, 0, r->dc_sock_addr_size)); - NDR_CHECK(ndr_push_nbt_dc_sock_addr(_ndr_dc_sock_addr, NDR_SCALARS, &r->dc_sock_addr)); - NDR_CHECK(ndr_push_subcontext_end(ndr, _ndr_dc_sock_addr, 0, r->dc_sock_addr_size)); - } - NDR_CHECK(ndr_push_nbt_netlogon_version(ndr, NDR_SCALARS, 13)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -static enum ndr_err_code ndr_pull_nbt_cldap_netlogon_13(struct ndr_pull *ndr, int ndr_flags, struct nbt_cldap_netlogon_13 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_nbt_netlogon_command(ndr, NDR_SCALARS, &r->type)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->sbz)); - NDR_CHECK(ndr_pull_nbt_server_type(ndr, NDR_SCALARS, &r->server_type)); - NDR_CHECK(ndr_pull_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->forest)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->dns_domain)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_dns_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->domain)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->user_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->server_site)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->client_site)); - NDR_CHECK(ndr_pull_uint8(ndr, NDR_SCALARS, &r->dc_sock_addr_size)); - { - struct ndr_pull *_ndr_dc_sock_addr; - NDR_CHECK(ndr_pull_subcontext_start(ndr, &_ndr_dc_sock_addr, 0, r->dc_sock_addr_size)); - NDR_CHECK(ndr_pull_nbt_dc_sock_addr(_ndr_dc_sock_addr, NDR_SCALARS, &r->dc_sock_addr)); - NDR_CHECK(ndr_pull_subcontext_end(ndr, _ndr_dc_sock_addr, 0, r->dc_sock_addr_size)); - } - NDR_CHECK(ndr_pull_nbt_netlogon_version(ndr, NDR_SCALARS, &r->nt_version)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_cldap_netlogon_13(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_13 *r) -{ - ndr_print_struct(ndr, name, "nbt_cldap_netlogon_13"); - ndr->depth++; - ndr_print_nbt_netlogon_command(ndr, "type", r->type); - ndr_print_uint16(ndr, "sbz", r->sbz); - ndr_print_nbt_server_type(ndr, "server_type", r->server_type); - ndr_print_GUID(ndr, "domain_uuid", &r->domain_uuid); - ndr_print_nbt_string(ndr, "forest", r->forest); - ndr_print_nbt_string(ndr, "dns_domain", r->dns_domain); - ndr_print_nbt_string(ndr, "pdc_dns_name", r->pdc_dns_name); - ndr_print_nbt_string(ndr, "domain", r->domain); - ndr_print_nbt_string(ndr, "pdc_name", r->pdc_name); - ndr_print_nbt_string(ndr, "user_name", r->user_name); - ndr_print_nbt_string(ndr, "server_site", r->server_site); - ndr_print_nbt_string(ndr, "client_site", r->client_site); - ndr_print_uint8(ndr, "dc_sock_addr_size", r->dc_sock_addr_size); - ndr_print_nbt_dc_sock_addr(ndr, "dc_sock_addr", &r->dc_sock_addr); - ndr_print_nbt_netlogon_version(ndr, "nt_version", (ndr->flags & LIBNDR_PRINT_SET_VALUES)?13:r->nt_version); - ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); - ndr_print_uint16(ndr, "lm20_token", r->lm20_token); - ndr->depth--; -} - -_PUBLIC_ enum ndr_err_code ndr_push_nbt_cldap_netlogon_15(struct ndr_push *ndr, int ndr_flags, const struct nbt_cldap_netlogon_15 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_nbt_netlogon_command(ndr, NDR_SCALARS, r->type)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->sbz)); - NDR_CHECK(ndr_push_nbt_server_type(ndr, NDR_SCALARS, r->server_type)); - NDR_CHECK(ndr_push_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->forest)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->dns_domain)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_dns_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->domain)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->user_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->server_site)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->client_site)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->next_closest_site)); - NDR_CHECK(ndr_push_nbt_netlogon_version(ndr, NDR_SCALARS, 15)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_cldap_netlogon_15(struct ndr_pull *ndr, int ndr_flags, struct nbt_cldap_netlogon_15 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_nbt_netlogon_command(ndr, NDR_SCALARS, &r->type)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->sbz)); - NDR_CHECK(ndr_pull_nbt_server_type(ndr, NDR_SCALARS, &r->server_type)); - NDR_CHECK(ndr_pull_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->forest)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->dns_domain)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_dns_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->domain)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->user_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->server_site)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->client_site)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->next_closest_site)); - NDR_CHECK(ndr_pull_nbt_netlogon_version(ndr, NDR_SCALARS, &r->nt_version)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_cldap_netlogon_15(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_15 *r) -{ - ndr_print_struct(ndr, name, "nbt_cldap_netlogon_15"); - ndr->depth++; - ndr_print_nbt_netlogon_command(ndr, "type", r->type); - ndr_print_uint16(ndr, "sbz", r->sbz); - ndr_print_nbt_server_type(ndr, "server_type", r->server_type); - ndr_print_GUID(ndr, "domain_uuid", &r->domain_uuid); - ndr_print_nbt_string(ndr, "forest", r->forest); - ndr_print_nbt_string(ndr, "dns_domain", r->dns_domain); - ndr_print_nbt_string(ndr, "pdc_dns_name", r->pdc_dns_name); - ndr_print_nbt_string(ndr, "domain", r->domain); - ndr_print_nbt_string(ndr, "pdc_name", r->pdc_name); - ndr_print_nbt_string(ndr, "user_name", r->user_name); - ndr_print_nbt_string(ndr, "server_site", r->server_site); - ndr_print_nbt_string(ndr, "client_site", r->client_site); - ndr_print_nbt_string(ndr, "next_closest_site", r->next_closest_site); - ndr_print_nbt_netlogon_version(ndr, "nt_version", (ndr->flags & LIBNDR_PRINT_SET_VALUES)?15:r->nt_version); - ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); - ndr_print_uint16(ndr, "lm20_token", r->lm20_token); - ndr->depth--; -} - -_PUBLIC_ enum ndr_err_code ndr_push_nbt_cldap_netlogon_29(struct ndr_push *ndr, int ndr_flags, const struct nbt_cldap_netlogon_29 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_nbt_netlogon_command(ndr, NDR_SCALARS, r->type)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->sbz)); - NDR_CHECK(ndr_push_nbt_server_type(ndr, NDR_SCALARS, r->server_type)); - NDR_CHECK(ndr_push_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->forest)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->dns_domain)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_dns_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->domain)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->pdc_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->user_name)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->server_site)); - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->client_site)); - NDR_CHECK(ndr_push_uint8(ndr, NDR_SCALARS, r->dc_sock_addr_size)); - { - struct ndr_push *_ndr_dc_sock_addr; - NDR_CHECK(ndr_push_subcontext_start(ndr, &_ndr_dc_sock_addr, 0, r->dc_sock_addr_size)); - NDR_CHECK(ndr_push_nbt_dc_sock_addr(_ndr_dc_sock_addr, NDR_SCALARS, &r->dc_sock_addr)); - NDR_CHECK(ndr_push_subcontext_end(ndr, _ndr_dc_sock_addr, 0, r->dc_sock_addr_size)); - } - NDR_CHECK(ndr_push_nbt_string(ndr, NDR_SCALARS, r->next_closest_site)); - NDR_CHECK(ndr_push_nbt_netlogon_version(ndr, NDR_SCALARS, 29)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_cldap_netlogon_29(struct ndr_pull *ndr, int ndr_flags, struct nbt_cldap_netlogon_29 *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_nbt_netlogon_command(ndr, NDR_SCALARS, &r->type)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->sbz)); - NDR_CHECK(ndr_pull_nbt_server_type(ndr, NDR_SCALARS, &r->server_type)); - NDR_CHECK(ndr_pull_GUID(ndr, NDR_SCALARS, &r->domain_uuid)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->forest)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->dns_domain)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_dns_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->domain)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->pdc_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->user_name)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->server_site)); - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->client_site)); - NDR_CHECK(ndr_pull_uint8(ndr, NDR_SCALARS, &r->dc_sock_addr_size)); - { - struct ndr_pull *_ndr_dc_sock_addr; - NDR_CHECK(ndr_pull_subcontext_start(ndr, &_ndr_dc_sock_addr, 0, r->dc_sock_addr_size)); - NDR_CHECK(ndr_pull_nbt_dc_sock_addr(_ndr_dc_sock_addr, NDR_SCALARS, &r->dc_sock_addr)); - NDR_CHECK(ndr_pull_subcontext_end(ndr, _ndr_dc_sock_addr, 0, r->dc_sock_addr_size)); - } - NDR_CHECK(ndr_pull_nbt_string(ndr, NDR_SCALARS, &r->next_closest_site)); - NDR_CHECK(ndr_pull_nbt_netlogon_version(ndr, NDR_SCALARS, &r->nt_version)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); - } - if (ndr_flags & NDR_BUFFERS) { - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_cldap_netlogon_29(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_29 *r) -{ - ndr_print_struct(ndr, name, "nbt_cldap_netlogon_29"); - ndr->depth++; - ndr_print_nbt_netlogon_command(ndr, "type", r->type); - ndr_print_uint16(ndr, "sbz", r->sbz); - ndr_print_nbt_server_type(ndr, "server_type", r->server_type); - ndr_print_GUID(ndr, "domain_uuid", &r->domain_uuid); - ndr_print_nbt_string(ndr, "forest", r->forest); - ndr_print_nbt_string(ndr, "dns_domain", r->dns_domain); - ndr_print_nbt_string(ndr, "pdc_dns_name", r->pdc_dns_name); - ndr_print_nbt_string(ndr, "domain", r->domain); - ndr_print_nbt_string(ndr, "pdc_name", r->pdc_name); - ndr_print_nbt_string(ndr, "user_name", r->user_name); - ndr_print_nbt_string(ndr, "server_site", r->server_site); - ndr_print_nbt_string(ndr, "client_site", r->client_site); - ndr_print_uint8(ndr, "dc_sock_addr_size", r->dc_sock_addr_size); - ndr_print_nbt_dc_sock_addr(ndr, "dc_sock_addr", &r->dc_sock_addr); - ndr_print_nbt_string(ndr, "next_closest_site", r->next_closest_site); - ndr_print_nbt_netlogon_version(ndr, "nt_version", (ndr->flags & LIBNDR_PRINT_SET_VALUES)?29:r->nt_version); - ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); - ndr_print_uint16(ndr, "lm20_token", r->lm20_token); - ndr->depth--; -} - -_PUBLIC_ enum ndr_err_code ndr_push_nbt_cldap_netlogon(struct ndr_push *ndr, int ndr_flags, const union nbt_cldap_netlogon *r) +_PUBLIC_ enum ndr_err_code ndr_push_nbt_netlogon_response_from_pdc(struct ndr_push *ndr, int ndr_flags, const struct nbt_netlogon_response_from_pdc *r) { { - uint32_t _flags_save_UNION = ndr->flags; + uint32_t _flags_save_STRUCT = ndr->flags; ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); if (ndr_flags & NDR_SCALARS) { - int level = ndr_push_get_switch_value(ndr, r); - switch (level) { - case 0: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_1(ndr, NDR_SCALARS, &r->logon1)); - break; } - - case 1: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_1(ndr, NDR_SCALARS, &r->logon1)); - break; } - - case 2: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_3(ndr, NDR_SCALARS, &r->logon3)); - break; } - - case 3: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_3(ndr, NDR_SCALARS, &r->logon3)); - break; } - - case 4: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_5(ndr, NDR_SCALARS, &r->logon5)); - break; } - - case 5: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_5(ndr, NDR_SCALARS, &r->logon5)); - break; } - - case 6: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_5(ndr, NDR_SCALARS, &r->logon5)); - break; } - - case 7: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_5(ndr, NDR_SCALARS, &r->logon5)); - break; } - - case 8: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 9: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 10: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 11: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 12: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 13: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 14: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 15: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 16: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_1(ndr, NDR_SCALARS, &r->logon1)); - break; } - - case 17: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_1(ndr, NDR_SCALARS, &r->logon1)); - break; } - - case 18: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_3(ndr, NDR_SCALARS, &r->logon3)); - break; } - - case 19: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_3(ndr, NDR_SCALARS, &r->logon3)); - break; } - - case 20: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 21: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 22: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 23: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 24: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 25: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 26: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 27: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 28: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 29: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_29(ndr, NDR_SCALARS, &r->logon29)); - break; } - - case 30: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_29(ndr, NDR_SCALARS, &r->logon29)); - break; } - - case 31: { - NDR_CHECK(ndr_push_nbt_cldap_netlogon_29(ndr, NDR_SCALARS, &r->logon29)); - break; } - - default: - return ndr_push_error(ndr, NDR_ERR_BAD_SWITCH, "Bad switch value %u", level); - } - } - if (ndr_flags & NDR_BUFFERS) { - int level = ndr_push_get_switch_value(ndr, r); - switch (level) { - case 0: - break; - - case 1: - break; - - case 2: - break; - - case 3: - break; - - case 4: - break; - - case 5: - break; - - case 6: - break; - - case 7: - break; - - case 8: - break; - - case 9: - break; - - case 10: - break; - - case 11: - break; - - case 12: - break; - - case 13: - break; - - case 14: - break; - - case 15: - break; - - case 16: - break; - - case 17: - break; - - case 18: - break; - - case 19: - break; - - case 20: - break; - - case 21: - break; - - case 22: - break; - - case 23: - break; - - case 24: - break; - - case 25: - break; - - case 26: - break; - - case 27: - break; - - case 28: - break; - - case 29: - break; - - case 30: - break; - - case 31: - break; - - default: - return ndr_push_error(ndr, NDR_ERR_BAD_SWITCH, "Bad switch value %u", level); + NDR_CHECK(ndr_push_align(ndr, 4)); + NDR_CHECK(ndr_push_netlogon_command(ndr, NDR_SCALARS, r->command)); + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->pdc_name)); + ndr->flags = _flags_save_string; } - } - ndr->flags = _flags_save_UNION; - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_cldap_netlogon(struct ndr_pull *ndr, int ndr_flags, union nbt_cldap_netlogon *r) -{ - int level; - { - uint32_t _flags_save_UNION = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); - level = ndr_pull_get_switch_value(ndr, r); - if (ndr_flags & NDR_SCALARS) { - switch (level) { - case 0: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_1(ndr, NDR_SCALARS, &r->logon1)); - break; } - - case 1: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_1(ndr, NDR_SCALARS, &r->logon1)); - break; } - - case 2: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_3(ndr, NDR_SCALARS, &r->logon3)); - break; } - - case 3: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_3(ndr, NDR_SCALARS, &r->logon3)); - break; } - - case 4: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_5(ndr, NDR_SCALARS, &r->logon5)); - break; } - - case 5: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_5(ndr, NDR_SCALARS, &r->logon5)); - break; } - - case 6: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_5(ndr, NDR_SCALARS, &r->logon5)); - break; } - - case 7: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_5(ndr, NDR_SCALARS, &r->logon5)); - break; } - - case 8: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 9: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 10: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 11: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 12: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 13: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 14: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 15: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_13(ndr, NDR_SCALARS, &r->logon13)); - break; } - - case 16: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_1(ndr, NDR_SCALARS, &r->logon1)); - break; } - - case 17: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_1(ndr, NDR_SCALARS, &r->logon1)); - break; } - - case 18: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_3(ndr, NDR_SCALARS, &r->logon3)); - break; } - - case 19: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_3(ndr, NDR_SCALARS, &r->logon3)); - break; } - - case 20: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 21: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 22: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 23: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 24: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 25: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 26: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 27: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 28: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_15(ndr, NDR_SCALARS, &r->logon15)); - break; } - - case 29: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_29(ndr, NDR_SCALARS, &r->logon29)); - break; } - - case 30: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_29(ndr, NDR_SCALARS, &r->logon29)); - break; } - - case 31: { - NDR_CHECK(ndr_pull_nbt_cldap_netlogon_29(ndr, NDR_SCALARS, &r->logon29)); - break; } - - default: - return ndr_pull_error(ndr, NDR_ERR_BAD_SWITCH, "Bad switch value %u", level); + { + uint32_t _flags_save_DATA_BLOB = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN2); + NDR_CHECK(ndr_push_DATA_BLOB(ndr, NDR_SCALARS, r->_pad)); + ndr->flags = _flags_save_DATA_BLOB; } - } - if (ndr_flags & NDR_BUFFERS) { - switch (level) { - case 0: - break; - - case 1: - break; - - case 2: - break; - - case 3: - break; - - case 4: - break; - - case 5: - break; - - case 6: - break; - - case 7: - break; - - case 8: - break; - - case 9: - break; - - case 10: - break; - - case 11: - break; - - case 12: - break; - - case 13: - break; - - case 14: - break; - - case 15: - break; - - case 16: - break; - - case 17: - break; - - case 18: - break; - - case 19: - break; - - case 20: - break; - - case 21: - break; - - case 22: - break; - - case 23: - break; - - case 24: - break; - - case 25: - break; - - case 26: - break; - - case 27: - break; - - case 28: - break; - - case 29: - break; - - case 30: - break; - - case 31: - break; - - default: - return ndr_pull_error(ndr, NDR_ERR_BAD_SWITCH, "Bad switch value %u", level); + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->unicode_pdc_name)); + ndr->flags = _flags_save_string; } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->domain_name)); + ndr->flags = _flags_save_string; + } + NDR_CHECK(ndr_push_netlogon_nt_version_flags(ndr, NDR_SCALARS, r->nt_version)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); + } + if (ndr_flags & NDR_BUFFERS) { } - ndr->flags = _flags_save_UNION; - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_nbt_cldap_netlogon(struct ndr_print *ndr, const char *name, const union nbt_cldap_netlogon *r) -{ - int level; - { - uint32_t _flags_save_UNION = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); - level = ndr_print_get_switch_value(ndr, r); - ndr_print_union(ndr, name, level, "nbt_cldap_netlogon"); - switch (level) { - case 0: - ndr_print_nbt_cldap_netlogon_1(ndr, "logon1", &r->logon1); - break; - - case 1: - ndr_print_nbt_cldap_netlogon_1(ndr, "logon1", &r->logon1); - break; - - case 2: - ndr_print_nbt_cldap_netlogon_3(ndr, "logon3", &r->logon3); - break; - - case 3: - ndr_print_nbt_cldap_netlogon_3(ndr, "logon3", &r->logon3); - break; - - case 4: - ndr_print_nbt_cldap_netlogon_5(ndr, "logon5", &r->logon5); - break; - - case 5: - ndr_print_nbt_cldap_netlogon_5(ndr, "logon5", &r->logon5); - break; - - case 6: - ndr_print_nbt_cldap_netlogon_5(ndr, "logon5", &r->logon5); - break; - - case 7: - ndr_print_nbt_cldap_netlogon_5(ndr, "logon5", &r->logon5); - break; - - case 8: - ndr_print_nbt_cldap_netlogon_13(ndr, "logon13", &r->logon13); - break; - - case 9: - ndr_print_nbt_cldap_netlogon_13(ndr, "logon13", &r->logon13); - break; - - case 10: - ndr_print_nbt_cldap_netlogon_13(ndr, "logon13", &r->logon13); - break; - - case 11: - ndr_print_nbt_cldap_netlogon_13(ndr, "logon13", &r->logon13); - break; - - case 12: - ndr_print_nbt_cldap_netlogon_13(ndr, "logon13", &r->logon13); - break; - - case 13: - ndr_print_nbt_cldap_netlogon_13(ndr, "logon13", &r->logon13); - break; - - case 14: - ndr_print_nbt_cldap_netlogon_13(ndr, "logon13", &r->logon13); - break; - - case 15: - ndr_print_nbt_cldap_netlogon_13(ndr, "logon13", &r->logon13); - break; - - case 16: - ndr_print_nbt_cldap_netlogon_1(ndr, "logon1", &r->logon1); - break; - - case 17: - ndr_print_nbt_cldap_netlogon_1(ndr, "logon1", &r->logon1); - break; - - case 18: - ndr_print_nbt_cldap_netlogon_3(ndr, "logon3", &r->logon3); - break; - - case 19: - ndr_print_nbt_cldap_netlogon_3(ndr, "logon3", &r->logon3); - break; - - case 20: - ndr_print_nbt_cldap_netlogon_15(ndr, "logon15", &r->logon15); - break; - - case 21: - ndr_print_nbt_cldap_netlogon_15(ndr, "logon15", &r->logon15); - break; - - case 22: - ndr_print_nbt_cldap_netlogon_15(ndr, "logon15", &r->logon15); - break; - - case 23: - ndr_print_nbt_cldap_netlogon_15(ndr, "logon15", &r->logon15); - break; - - case 24: - ndr_print_nbt_cldap_netlogon_15(ndr, "logon15", &r->logon15); - break; - - case 25: - ndr_print_nbt_cldap_netlogon_15(ndr, "logon15", &r->logon15); - break; - - case 26: - ndr_print_nbt_cldap_netlogon_15(ndr, "logon15", &r->logon15); - break; - - case 27: - ndr_print_nbt_cldap_netlogon_15(ndr, "logon15", &r->logon15); - break; - - case 28: - ndr_print_nbt_cldap_netlogon_15(ndr, "logon15", &r->logon15); - break; - - case 29: - ndr_print_nbt_cldap_netlogon_29(ndr, "logon29", &r->logon29); - break; - - case 30: - ndr_print_nbt_cldap_netlogon_29(ndr, "logon29", &r->logon29); - break; - - case 31: - ndr_print_nbt_cldap_netlogon_29(ndr, "logon29", &r->logon29); - break; - - default: - ndr_print_bad_level(ndr, name, level); - } - ndr->flags = _flags_save_UNION; + ndr->flags = _flags_save_STRUCT; } -} - -static enum ndr_err_code ndr_push_nbt_ntlogon_command(struct ndr_push *ndr, int ndr_flags, enum nbt_ntlogon_command r) -{ - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r)); return NDR_ERR_SUCCESS; } -static enum ndr_err_code ndr_pull_nbt_ntlogon_command(struct ndr_pull *ndr, int ndr_flags, enum nbt_ntlogon_command *r) +_PUBLIC_ enum ndr_err_code ndr_pull_nbt_netlogon_response_from_pdc(struct ndr_pull *ndr, int ndr_flags, struct nbt_netlogon_response_from_pdc *r) { - uint16_t v; - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &v)); - *r = v; + { + uint32_t _flags_save_STRUCT = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_pull_align(ndr, 4)); + NDR_CHECK(ndr_pull_netlogon_command(ndr, NDR_SCALARS, &r->command)); + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->pdc_name)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_DATA_BLOB = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN2); + NDR_CHECK(ndr_pull_DATA_BLOB(ndr, NDR_SCALARS, &r->_pad)); + ndr->flags = _flags_save_DATA_BLOB; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->unicode_pdc_name)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->domain_name)); + ndr->flags = _flags_save_string; + } + NDR_CHECK(ndr_pull_netlogon_nt_version_flags(ndr, NDR_SCALARS, &r->nt_version)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); + } + if (ndr_flags & NDR_BUFFERS) { + } + ndr->flags = _flags_save_STRUCT; + } return NDR_ERR_SUCCESS; } -_PUBLIC_ void ndr_print_nbt_ntlogon_command(struct ndr_print *ndr, const char *name, enum nbt_ntlogon_command r) +_PUBLIC_ void ndr_print_nbt_netlogon_response_from_pdc(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_response_from_pdc *r) { - const char *val = NULL; - - switch (r) { - case NTLOGON_SAM_LOGON: val = "NTLOGON_SAM_LOGON"; break; - case NTLOGON_SAM_LOGON_REPLY: val = "NTLOGON_SAM_LOGON_REPLY"; break; - case NTLOGON_SAM_LOGON_REPLY15: val = "NTLOGON_SAM_LOGON_REPLY15"; break; - case NTLOGON_RESPONSE_FROM_PDC2: val = "NTLOGON_RESPONSE_FROM_PDC2"; break; + ndr_print_struct(ndr, name, "nbt_netlogon_response_from_pdc"); + { + uint32_t _flags_save_STRUCT = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); + ndr->depth++; + ndr_print_netlogon_command(ndr, "command", r->command); + ndr_print_string(ndr, "pdc_name", r->pdc_name); + ndr_print_DATA_BLOB(ndr, "_pad", r->_pad); + ndr_print_string(ndr, "unicode_pdc_name", r->unicode_pdc_name); + ndr_print_string(ndr, "domain_name", r->domain_name); + ndr_print_netlogon_nt_version_flags(ndr, "nt_version", r->nt_version); + ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); + ndr_print_uint16(ndr, "lm20_token", r->lm20_token); + ndr->depth--; + ndr->flags = _flags_save_STRUCT; } - ndr_print_enum(ndr, name, "ENUM", val, r); } -static enum ndr_err_code ndr_push_nbt_ntlogon_sam_logon(struct ndr_push *ndr, int ndr_flags, const struct nbt_ntlogon_sam_logon *r) +static enum ndr_err_code ndr_push_nbt_db_change_info(struct ndr_push *ndr, int ndr_flags, const struct nbt_db_change_info *r) { if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->request_count)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->computer_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->user_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->mailslot_name)); - ndr->flags = _flags_save_string; - } - NDR_CHECK(ndr_push_samr_AcctFlags(ndr, NDR_SCALARS, r->acct_control)); - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, ndr_size_dom_sid0(&r->sid, ndr->flags))); - { - struct ndr_push *_ndr_sid; - NDR_CHECK(ndr_push_subcontext_start(ndr, &_ndr_sid, 0, ndr_size_dom_sid0(&r->sid, ndr->flags))); - NDR_CHECK(ndr_push_dom_sid0(_ndr_sid, NDR_SCALARS|NDR_BUFFERS, &r->sid)); - NDR_CHECK(ndr_push_subcontext_end(ndr, _ndr_sid, 0, ndr_size_dom_sid0(&r->sid, ndr->flags))); - } - NDR_CHECK(ndr_push_nbt_netlogon_version(ndr, NDR_SCALARS, r->nt_version)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); + NDR_CHECK(ndr_push_align(ndr, 8)); + NDR_CHECK(ndr_push_netr_SamDatabaseID(ndr, NDR_SCALARS, r->db_index)); + NDR_CHECK(ndr_push_hyper(ndr, NDR_SCALARS, r->serial)); + NDR_CHECK(ndr_push_NTTIME(ndr, NDR_SCALARS, r->timestamp)); } if (ndr_flags & NDR_BUFFERS) { } return NDR_ERR_SUCCESS; } -static enum ndr_err_code ndr_pull_nbt_ntlogon_sam_logon(struct ndr_pull *ndr, int ndr_flags, struct nbt_ntlogon_sam_logon *r) +static enum ndr_err_code ndr_pull_nbt_db_change_info(struct ndr_pull *ndr, int ndr_flags, struct nbt_db_change_info *r) { if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->request_count)); - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->computer_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->user_name)); - ndr->flags = _flags_save_string; - } - { - uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->mailslot_name)); - ndr->flags = _flags_save_string; - } - NDR_CHECK(ndr_pull_samr_AcctFlags(ndr, NDR_SCALARS, &r->acct_control)); - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->sid_size)); - { - struct ndr_pull *_ndr_sid; - NDR_CHECK(ndr_pull_subcontext_start(ndr, &_ndr_sid, 0, r->sid_size)); - NDR_CHECK(ndr_pull_dom_sid0(_ndr_sid, NDR_SCALARS|NDR_BUFFERS, &r->sid)); - NDR_CHECK(ndr_pull_subcontext_end(ndr, _ndr_sid, 0, r->sid_size)); - } - NDR_CHECK(ndr_pull_nbt_netlogon_version(ndr, NDR_SCALARS, &r->nt_version)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); + NDR_CHECK(ndr_pull_align(ndr, 8)); + NDR_CHECK(ndr_pull_netr_SamDatabaseID(ndr, NDR_SCALARS, &r->db_index)); + NDR_CHECK(ndr_pull_hyper(ndr, NDR_SCALARS, &r->serial)); + NDR_CHECK(ndr_pull_NTTIME(ndr, NDR_SCALARS, &r->timestamp)); } if (ndr_flags & NDR_BUFFERS) { } return NDR_ERR_SUCCESS; } -_PUBLIC_ void ndr_print_nbt_ntlogon_sam_logon(struct ndr_print *ndr, const char *name, const struct nbt_ntlogon_sam_logon *r) +_PUBLIC_ void ndr_print_nbt_db_change_info(struct ndr_print *ndr, const char *name, const struct nbt_db_change_info *r) { - ndr_print_struct(ndr, name, "nbt_ntlogon_sam_logon"); + ndr_print_struct(ndr, name, "nbt_db_change_info"); ndr->depth++; - ndr_print_uint16(ndr, "request_count", r->request_count); - ndr_print_string(ndr, "computer_name", r->computer_name); - ndr_print_string(ndr, "user_name", r->user_name); - ndr_print_string(ndr, "mailslot_name", r->mailslot_name); - ndr_print_samr_AcctFlags(ndr, "acct_control", r->acct_control); - ndr_print_uint32(ndr, "sid_size", (ndr->flags & LIBNDR_PRINT_SET_VALUES)?ndr_size_dom_sid0(&r->sid, ndr->flags):r->sid_size); - ndr_print_dom_sid0(ndr, "sid", &r->sid); - ndr_print_nbt_netlogon_version(ndr, "nt_version", r->nt_version); - ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); - ndr_print_uint16(ndr, "lm20_token", r->lm20_token); + ndr_print_netr_SamDatabaseID(ndr, "db_index", r->db_index); + ndr_print_hyper(ndr, "serial", r->serial); + ndr_print_NTTIME(ndr, "timestamp", r->timestamp); ndr->depth--; } -static enum ndr_err_code ndr_push_nbt_ntlogon_sam_logon_reply(struct ndr_push *ndr, int ndr_flags, const struct nbt_ntlogon_sam_logon_reply *r) +static enum ndr_err_code ndr_push_NETLOGON_DB_CHANGE(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_DB_CHANGE *r) { + uint32_t cntr_dbchange_0; if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); + NDR_CHECK(ndr_push_align(ndr, 8)); + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->serial_lo)); + NDR_CHECK(ndr_push_time_t(ndr, NDR_SCALARS, r->timestamp)); + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->pulse)); + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->random)); { uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->server)); + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->pdc_name)); ndr->flags = _flags_save_string; } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->domain)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_DATA_BLOB = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN2); + NDR_CHECK(ndr_push_DATA_BLOB(ndr, NDR_SCALARS, r->_pad)); + ndr->flags = _flags_save_DATA_BLOB; + } { uint32_t _flags_save_string = ndr->flags; ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->user_name)); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->unicode_pdc_name)); ndr->flags = _flags_save_string; } { uint32_t _flags_save_string = ndr->flags; ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->domain)); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, r->unicode_domain)); ndr->flags = _flags_save_string; } - NDR_CHECK(ndr_push_nbt_netlogon_version(ndr, NDR_SCALARS, r->nt_version)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lmnt_token)); - NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->lm20_token)); + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->db_count)); + for (cntr_dbchange_0 = 0; cntr_dbchange_0 < r->db_count; cntr_dbchange_0++) { + NDR_CHECK(ndr_push_nbt_db_change_info(ndr, NDR_SCALARS, &r->dbchange[cntr_dbchange_0])); + } + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, ndr_size_dom_sid0(&r->sid, ndr->flags))); + { + struct ndr_push *_ndr_sid; + NDR_CHECK(ndr_push_subcontext_start(ndr, &_ndr_sid, 0, ndr_size_dom_sid0(&r->sid, ndr->flags))); + NDR_CHECK(ndr_push_dom_sid0(_ndr_sid, NDR_SCALARS|NDR_BUFFERS, &r->sid)); + NDR_CHECK(ndr_push_subcontext_end(ndr, _ndr_sid, 0, ndr_size_dom_sid0(&r->sid, ndr->flags))); + } + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->message_format_version)); + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->message_token)); } if (ndr_flags & NDR_BUFFERS) { } return NDR_ERR_SUCCESS; } -static enum ndr_err_code ndr_pull_nbt_ntlogon_sam_logon_reply(struct ndr_pull *ndr, int ndr_flags, struct nbt_ntlogon_sam_logon_reply *r) +static enum ndr_err_code ndr_pull_NETLOGON_DB_CHANGE(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_DB_CHANGE *r) { + uint32_t cntr_dbchange_0; + TALLOC_CTX *_mem_save_dbchange_0; if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); + NDR_CHECK(ndr_pull_align(ndr, 8)); + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->serial_lo)); + NDR_CHECK(ndr_pull_time_t(ndr, NDR_SCALARS, &r->timestamp)); + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->pulse)); + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->random)); { uint32_t _flags_save_string = ndr->flags; - ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->server)); + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->pdc_name)); + ndr->flags = _flags_save_string; + } + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->domain)); ndr->flags = _flags_save_string; } + { + uint32_t _flags_save_DATA_BLOB = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_ALIGN2); + NDR_CHECK(ndr_pull_DATA_BLOB(ndr, NDR_SCALARS, &r->_pad)); + ndr->flags = _flags_save_DATA_BLOB; + } { uint32_t _flags_save_string = ndr->flags; ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->user_name)); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->unicode_pdc_name)); ndr->flags = _flags_save_string; } { uint32_t _flags_save_string = ndr->flags; ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_NULLTERM); - NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->domain)); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->unicode_domain)); ndr->flags = _flags_save_string; } - NDR_CHECK(ndr_pull_nbt_netlogon_version(ndr, NDR_SCALARS, &r->nt_version)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lmnt_token)); - NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->lm20_token)); + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->db_count)); + NDR_PULL_ALLOC_N(ndr, r->dbchange, r->db_count); + _mem_save_dbchange_0 = NDR_PULL_GET_MEM_CTX(ndr); + NDR_PULL_SET_MEM_CTX(ndr, r->dbchange, 0); + for (cntr_dbchange_0 = 0; cntr_dbchange_0 < r->db_count; cntr_dbchange_0++) { + NDR_CHECK(ndr_pull_nbt_db_change_info(ndr, NDR_SCALARS, &r->dbchange[cntr_dbchange_0])); + } + NDR_PULL_SET_MEM_CTX(ndr, _mem_save_dbchange_0, 0); + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->sid_size)); + { + struct ndr_pull *_ndr_sid; + NDR_CHECK(ndr_pull_subcontext_start(ndr, &_ndr_sid, 0, r->sid_size)); + NDR_CHECK(ndr_pull_dom_sid0(_ndr_sid, NDR_SCALARS|NDR_BUFFERS, &r->sid)); + NDR_CHECK(ndr_pull_subcontext_end(ndr, _ndr_sid, 0, r->sid_size)); + } + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->message_format_version)); + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->message_token)); } if (ndr_flags & NDR_BUFFERS) { } return NDR_ERR_SUCCESS; } -_PUBLIC_ void ndr_print_nbt_ntlogon_sam_logon_reply(struct ndr_print *ndr, const char *name, const struct nbt_ntlogon_sam_logon_reply *r) +_PUBLIC_ void ndr_print_NETLOGON_DB_CHANGE(struct ndr_print *ndr, const char *name, const struct NETLOGON_DB_CHANGE *r) { - ndr_print_struct(ndr, name, "nbt_ntlogon_sam_logon_reply"); + uint32_t cntr_dbchange_0; + ndr_print_struct(ndr, name, "NETLOGON_DB_CHANGE"); ndr->depth++; - ndr_print_string(ndr, "server", r->server); - ndr_print_string(ndr, "user_name", r->user_name); + ndr_print_uint32(ndr, "serial_lo", r->serial_lo); + ndr_print_time_t(ndr, "timestamp", r->timestamp); + ndr_print_uint32(ndr, "pulse", r->pulse); + ndr_print_uint32(ndr, "random", r->random); + ndr_print_string(ndr, "pdc_name", r->pdc_name); ndr_print_string(ndr, "domain", r->domain); - ndr_print_nbt_netlogon_version(ndr, "nt_version", r->nt_version); - ndr_print_uint16(ndr, "lmnt_token", r->lmnt_token); - ndr_print_uint16(ndr, "lm20_token", r->lm20_token); + ndr_print_DATA_BLOB(ndr, "_pad", r->_pad); + ndr_print_string(ndr, "unicode_pdc_name", r->unicode_pdc_name); + ndr_print_string(ndr, "unicode_domain", r->unicode_domain); + ndr_print_uint32(ndr, "db_count", r->db_count); + ndr->print(ndr, "%s: ARRAY(%d)", "dbchange", (int)r->db_count); + ndr->depth++; + for (cntr_dbchange_0=0;cntr_dbchange_0db_count;cntr_dbchange_0++) { + char *idx_0=NULL; + if (asprintf(&idx_0, "[%d]", cntr_dbchange_0) != -1) { + ndr_print_nbt_db_change_info(ndr, "dbchange", &r->dbchange[cntr_dbchange_0]); + free(idx_0); + } + } + ndr->depth--; + ndr_print_uint32(ndr, "sid_size", (ndr->flags & LIBNDR_PRINT_SET_VALUES)?ndr_size_dom_sid0(&r->sid, ndr->flags):r->sid_size); + ndr_print_dom_sid0(ndr, "sid", &r->sid); + ndr_print_uint32(ndr, "message_format_version", r->message_format_version); + ndr_print_uint32(ndr, "message_token", r->message_token); ndr->depth--; } -static enum ndr_err_code ndr_push_nbt_ntlogon_request(struct ndr_push *ndr, int ndr_flags, const union nbt_ntlogon_request *r) +static enum ndr_err_code ndr_push_nbt_netlogon_request(struct ndr_push *ndr, int ndr_flags, const union nbt_netlogon_request *r) { if (ndr_flags & NDR_SCALARS) { int level = ndr_push_get_switch_value(ndr, r); switch (level) { - case NTLOGON_SAM_LOGON: { - NDR_CHECK(ndr_push_nbt_ntlogon_sam_logon(ndr, NDR_SCALARS, &r->logon)); - break; } - - case NTLOGON_SAM_LOGON_REPLY: { - NDR_CHECK(ndr_push_nbt_ntlogon_sam_logon_reply(ndr, NDR_SCALARS, &r->reply)); + case LOGON_SAM_LOGON_REQUEST: { + NDR_CHECK(ndr_push_NETLOGON_SAM_LOGON_REQUEST(ndr, NDR_SCALARS, &r->logon)); break; } - case NTLOGON_SAM_LOGON_REPLY15: { - NDR_CHECK(ndr_push_nbt_ntlogon_sam_logon_reply(ndr, NDR_SCALARS, &r->reply)); + case LOGON_PRIMARY_QUERY: { + NDR_CHECK(ndr_push_nbt_netlogon_query_for_pdc(ndr, NDR_SCALARS, &r->pdc)); break; } - case NTLOGON_RESPONSE_FROM_PDC2: { - NDR_CHECK(ndr_push_nbt_netlogon_response_from_pdc2(ndr, NDR_SCALARS, &r->reply2)); + case NETLOGON_ANNOUNCE_UAS: { + NDR_CHECK(ndr_push_NETLOGON_DB_CHANGE(ndr, NDR_SCALARS, &r->uas)); break; } default: @@ -3854,17 +2423,15 @@ static enum ndr_err_code ndr_push_nbt_ntlogon_request(struct ndr_push *ndr, int if (ndr_flags & NDR_BUFFERS) { int level = ndr_push_get_switch_value(ndr, r); switch (level) { - case NTLOGON_SAM_LOGON: - NDR_CHECK(ndr_push_nbt_ntlogon_sam_logon(ndr, NDR_BUFFERS, &r->logon)); - break; - - case NTLOGON_SAM_LOGON_REPLY: + case LOGON_SAM_LOGON_REQUEST: + NDR_CHECK(ndr_push_NETLOGON_SAM_LOGON_REQUEST(ndr, NDR_BUFFERS, &r->logon)); break; - case NTLOGON_SAM_LOGON_REPLY15: + case LOGON_PRIMARY_QUERY: break; - case NTLOGON_RESPONSE_FROM_PDC2: + case NETLOGON_ANNOUNCE_UAS: + NDR_CHECK(ndr_push_NETLOGON_DB_CHANGE(ndr, NDR_BUFFERS, &r->uas)); break; default: @@ -3874,26 +2441,22 @@ static enum ndr_err_code ndr_push_nbt_ntlogon_request(struct ndr_push *ndr, int return NDR_ERR_SUCCESS; } -static enum ndr_err_code ndr_pull_nbt_ntlogon_request(struct ndr_pull *ndr, int ndr_flags, union nbt_ntlogon_request *r) +static enum ndr_err_code ndr_pull_nbt_netlogon_request(struct ndr_pull *ndr, int ndr_flags, union nbt_netlogon_request *r) { int level; level = ndr_pull_get_switch_value(ndr, r); if (ndr_flags & NDR_SCALARS) { switch (level) { - case NTLOGON_SAM_LOGON: { - NDR_CHECK(ndr_pull_nbt_ntlogon_sam_logon(ndr, NDR_SCALARS, &r->logon)); - break; } - - case NTLOGON_SAM_LOGON_REPLY: { - NDR_CHECK(ndr_pull_nbt_ntlogon_sam_logon_reply(ndr, NDR_SCALARS, &r->reply)); + case LOGON_SAM_LOGON_REQUEST: { + NDR_CHECK(ndr_pull_NETLOGON_SAM_LOGON_REQUEST(ndr, NDR_SCALARS, &r->logon)); break; } - case NTLOGON_SAM_LOGON_REPLY15: { - NDR_CHECK(ndr_pull_nbt_ntlogon_sam_logon_reply(ndr, NDR_SCALARS, &r->reply)); + case LOGON_PRIMARY_QUERY: { + NDR_CHECK(ndr_pull_nbt_netlogon_query_for_pdc(ndr, NDR_SCALARS, &r->pdc)); break; } - case NTLOGON_RESPONSE_FROM_PDC2: { - NDR_CHECK(ndr_pull_nbt_netlogon_response_from_pdc2(ndr, NDR_SCALARS, &r->reply2)); + case NETLOGON_ANNOUNCE_UAS: { + NDR_CHECK(ndr_pull_NETLOGON_DB_CHANGE(ndr, NDR_SCALARS, &r->uas)); break; } default: @@ -3902,17 +2465,15 @@ static enum ndr_err_code ndr_pull_nbt_ntlogon_request(struct ndr_pull *ndr, int } if (ndr_flags & NDR_BUFFERS) { switch (level) { - case NTLOGON_SAM_LOGON: - NDR_CHECK(ndr_pull_nbt_ntlogon_sam_logon(ndr, NDR_BUFFERS, &r->logon)); - break; - - case NTLOGON_SAM_LOGON_REPLY: + case LOGON_SAM_LOGON_REQUEST: + NDR_CHECK(ndr_pull_NETLOGON_SAM_LOGON_REQUEST(ndr, NDR_BUFFERS, &r->logon)); break; - case NTLOGON_SAM_LOGON_REPLY15: + case LOGON_PRIMARY_QUERY: break; - case NTLOGON_RESPONSE_FROM_PDC2: + case NETLOGON_ANNOUNCE_UAS: + NDR_CHECK(ndr_pull_NETLOGON_DB_CHANGE(ndr, NDR_BUFFERS, &r->uas)); break; default: @@ -3922,26 +2483,22 @@ static enum ndr_err_code ndr_pull_nbt_ntlogon_request(struct ndr_pull *ndr, int return NDR_ERR_SUCCESS; } -_PUBLIC_ void ndr_print_nbt_ntlogon_request(struct ndr_print *ndr, const char *name, const union nbt_ntlogon_request *r) +_PUBLIC_ void ndr_print_nbt_netlogon_request(struct ndr_print *ndr, const char *name, const union nbt_netlogon_request *r) { int level; level = ndr_print_get_switch_value(ndr, r); - ndr_print_union(ndr, name, level, "nbt_ntlogon_request"); + ndr_print_union(ndr, name, level, "nbt_netlogon_request"); switch (level) { - case NTLOGON_SAM_LOGON: - ndr_print_nbt_ntlogon_sam_logon(ndr, "logon", &r->logon); - break; - - case NTLOGON_SAM_LOGON_REPLY: - ndr_print_nbt_ntlogon_sam_logon_reply(ndr, "reply", &r->reply); + case LOGON_SAM_LOGON_REQUEST: + ndr_print_NETLOGON_SAM_LOGON_REQUEST(ndr, "logon", &r->logon); break; - case NTLOGON_SAM_LOGON_REPLY15: - ndr_print_nbt_ntlogon_sam_logon_reply(ndr, "reply", &r->reply); + case LOGON_PRIMARY_QUERY: + ndr_print_nbt_netlogon_query_for_pdc(ndr, "pdc", &r->pdc); break; - case NTLOGON_RESPONSE_FROM_PDC2: - ndr_print_nbt_netlogon_response_from_pdc2(ndr, "reply2", &r->reply2); + case NETLOGON_ANNOUNCE_UAS: + ndr_print_NETLOGON_DB_CHANGE(ndr, "uas", &r->uas); break; default: @@ -3949,54 +2506,54 @@ _PUBLIC_ void ndr_print_nbt_ntlogon_request(struct ndr_print *ndr, const char *n } } -_PUBLIC_ enum ndr_err_code ndr_push_nbt_ntlogon_packet(struct ndr_push *ndr, int ndr_flags, const struct nbt_ntlogon_packet *r) +_PUBLIC_ enum ndr_err_code ndr_push_nbt_netlogon_packet(struct ndr_push *ndr, int ndr_flags, const struct nbt_netlogon_packet *r) { { uint32_t _flags_save_STRUCT = ndr->flags; ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_nbt_ntlogon_command(ndr, NDR_SCALARS, r->command)); + NDR_CHECK(ndr_push_align(ndr, 8)); + NDR_CHECK(ndr_push_netlogon_command(ndr, NDR_SCALARS, r->command)); NDR_CHECK(ndr_push_set_switch_value(ndr, &r->req, r->command)); - NDR_CHECK(ndr_push_nbt_ntlogon_request(ndr, NDR_SCALARS, &r->req)); + NDR_CHECK(ndr_push_nbt_netlogon_request(ndr, NDR_SCALARS, &r->req)); } if (ndr_flags & NDR_BUFFERS) { - NDR_CHECK(ndr_push_nbt_ntlogon_request(ndr, NDR_BUFFERS, &r->req)); + NDR_CHECK(ndr_push_nbt_netlogon_request(ndr, NDR_BUFFERS, &r->req)); } ndr->flags = _flags_save_STRUCT; } return NDR_ERR_SUCCESS; } -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_ntlogon_packet(struct ndr_pull *ndr, int ndr_flags, struct nbt_ntlogon_packet *r) +_PUBLIC_ enum ndr_err_code ndr_pull_nbt_netlogon_packet(struct ndr_pull *ndr, int ndr_flags, struct nbt_netlogon_packet *r) { { uint32_t _flags_save_STRUCT = ndr->flags; ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_nbt_ntlogon_command(ndr, NDR_SCALARS, &r->command)); + NDR_CHECK(ndr_pull_align(ndr, 8)); + NDR_CHECK(ndr_pull_netlogon_command(ndr, NDR_SCALARS, &r->command)); NDR_CHECK(ndr_pull_set_switch_value(ndr, &r->req, r->command)); - NDR_CHECK(ndr_pull_nbt_ntlogon_request(ndr, NDR_SCALARS, &r->req)); + NDR_CHECK(ndr_pull_nbt_netlogon_request(ndr, NDR_SCALARS, &r->req)); } if (ndr_flags & NDR_BUFFERS) { - NDR_CHECK(ndr_pull_nbt_ntlogon_request(ndr, NDR_BUFFERS, &r->req)); + NDR_CHECK(ndr_pull_nbt_netlogon_request(ndr, NDR_BUFFERS, &r->req)); } ndr->flags = _flags_save_STRUCT; } return NDR_ERR_SUCCESS; } -_PUBLIC_ void ndr_print_nbt_ntlogon_packet(struct ndr_print *ndr, const char *name, const struct nbt_ntlogon_packet *r) +_PUBLIC_ void ndr_print_nbt_netlogon_packet(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_packet *r) { - ndr_print_struct(ndr, name, "nbt_ntlogon_packet"); + ndr_print_struct(ndr, name, "nbt_netlogon_packet"); { uint32_t _flags_save_STRUCT = ndr->flags; ndr_set_flags(&ndr->flags, LIBNDR_FLAG_NOALIGN); ndr->depth++; - ndr_print_nbt_ntlogon_command(ndr, "command", r->command); + ndr_print_netlogon_command(ndr, "command", r->command); ndr_print_set_switch_value(ndr, &r->req, r->command); - ndr_print_nbt_ntlogon_request(ndr, "req", &r->req); + ndr_print_nbt_netlogon_request(ndr, "req", &r->req); ndr->depth--; ndr->flags = _flags_save_STRUCT; } diff --git a/source3/librpc/gen_ndr/ndr_nbt.h b/source3/librpc/gen_ndr/ndr_nbt.h index f70d1ba8df..1a0ca0c302 100644 --- a/source3/librpc/gen_ndr/ndr_nbt.h +++ b/source3/librpc/gen_ndr/ndr_nbt.h @@ -6,6 +6,7 @@ #ifndef _HEADER_NDR_nbt #define _HEADER_NDR_nbt +#include "../libcli/netlogon.h" #include "../libcli/nbt/libnbt.h" #define NDR_NBT_CALL_COUNT (0) void ndr_print_nbt_operation(struct ndr_print *ndr, const char *name, uint16_t r); @@ -30,6 +31,7 @@ void ndr_print_nbt_rdata_data(struct ndr_print *ndr, const char *name, const str enum ndr_err_code ndr_push_nbt_rdata(struct ndr_push *ndr, int ndr_flags, const union nbt_rdata *r); enum ndr_err_code ndr_pull_nbt_rdata(struct ndr_pull *ndr, int ndr_flags, union nbt_rdata *r); void ndr_print_nbt_rdata(struct ndr_print *ndr, const char *name, const union nbt_rdata *r); +enum ndr_err_code ndr_push_nbt_res_rec(struct ndr_push *ndr, int ndr_flags, const struct nbt_res_rec *r); void ndr_print_nbt_res_rec(struct ndr_print *ndr, const char *name, const struct nbt_res_rec *r); enum ndr_err_code ndr_push_nbt_name_packet(struct ndr_push *ndr, int ndr_flags, const struct nbt_name_packet *r); enum ndr_err_code ndr_pull_nbt_name_packet(struct ndr_pull *ndr, int ndr_flags, struct nbt_name_packet *r); @@ -49,42 +51,41 @@ void ndr_print_dgram_data(struct ndr_print *ndr, const char *name, const union d enum ndr_err_code ndr_push_nbt_dgram_packet(struct ndr_push *ndr, int ndr_flags, const struct nbt_dgram_packet *r); enum ndr_err_code ndr_pull_nbt_dgram_packet(struct ndr_pull *ndr, int ndr_flags, struct nbt_dgram_packet *r); void ndr_print_nbt_dgram_packet(struct ndr_print *ndr, const char *name, const struct nbt_dgram_packet *r); -void ndr_print_nbt_netlogon_command(struct ndr_print *ndr, const char *name, enum nbt_netlogon_command r); -void ndr_print_nbt_netlogon_version(struct ndr_print *ndr, const char *name, uint32_t r); +enum ndr_err_code ndr_push_nbt_sockaddr(struct ndr_push *ndr, int ndr_flags, const struct nbt_sockaddr *r); +enum ndr_err_code ndr_pull_nbt_sockaddr(struct ndr_pull *ndr, int ndr_flags, struct nbt_sockaddr *r); +void ndr_print_nbt_sockaddr(struct ndr_print *ndr, const char *name, const struct nbt_sockaddr *r); +size_t ndr_size_nbt_sockaddr(const struct nbt_sockaddr *r, int flags); +enum ndr_err_code ndr_push_nbt_server_type(struct ndr_push *ndr, int ndr_flags, uint32_t r); +enum ndr_err_code ndr_pull_nbt_server_type(struct ndr_pull *ndr, int ndr_flags, uint32_t *r); +void ndr_print_nbt_server_type(struct ndr_print *ndr, const char *name, uint32_t r); +enum ndr_err_code ndr_push_netlogon_nt_version_flags(struct ndr_push *ndr, int ndr_flags, uint32_t r); +enum ndr_err_code ndr_pull_netlogon_nt_version_flags(struct ndr_pull *ndr, int ndr_flags, uint32_t *r); +void ndr_print_netlogon_nt_version_flags(struct ndr_print *ndr, const char *name, uint32_t r); +enum ndr_err_code ndr_push_netlogon_command(struct ndr_push *ndr, int ndr_flags, enum netlogon_command r); +enum ndr_err_code ndr_pull_netlogon_command(struct ndr_pull *ndr, int ndr_flags, enum netlogon_command *r); +void ndr_print_netlogon_command(struct ndr_print *ndr, const char *name, enum netlogon_command r); +enum ndr_err_code ndr_push_NETLOGON_SAM_LOGON_REQUEST(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_SAM_LOGON_REQUEST *r); +enum ndr_err_code ndr_pull_NETLOGON_SAM_LOGON_REQUEST(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_SAM_LOGON_REQUEST *r); +void ndr_print_NETLOGON_SAM_LOGON_REQUEST(struct ndr_print *ndr, const char *name, const struct NETLOGON_SAM_LOGON_REQUEST *r); +enum ndr_err_code ndr_push_NETLOGON_SAM_LOGON_RESPONSE_NT40(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_SAM_LOGON_RESPONSE_NT40 *r); +enum ndr_err_code ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_NT40(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_SAM_LOGON_RESPONSE_NT40 *r); +void ndr_print_NETLOGON_SAM_LOGON_RESPONSE_NT40(struct ndr_print *ndr, const char *name, const struct NETLOGON_SAM_LOGON_RESPONSE_NT40 *r); +enum ndr_err_code ndr_push_NETLOGON_SAM_LOGON_RESPONSE(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_SAM_LOGON_RESPONSE *r); +enum ndr_err_code ndr_pull_NETLOGON_SAM_LOGON_RESPONSE(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_SAM_LOGON_RESPONSE *r); +void ndr_print_NETLOGON_SAM_LOGON_RESPONSE(struct ndr_print *ndr, const char *name, const struct NETLOGON_SAM_LOGON_RESPONSE *r); +enum ndr_err_code ndr_push_NETLOGON_SAM_LOGON_RESPONSE_EX(struct ndr_push *ndr, int ndr_flags, const struct NETLOGON_SAM_LOGON_RESPONSE_EX *r); +enum ndr_err_code ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_EX(struct ndr_pull *ndr, int ndr_flags, struct NETLOGON_SAM_LOGON_RESPONSE_EX *r); +void ndr_print_NETLOGON_SAM_LOGON_RESPONSE_EX(struct ndr_print *ndr, const char *name, const struct NETLOGON_SAM_LOGON_RESPONSE_EX *r); void ndr_print_nbt_netlogon_query_for_pdc(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_query_for_pdc *r); -void ndr_print_nbt_netlogon_query_for_pdc2(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_query_for_pdc2 *r); +enum ndr_err_code ndr_push_nbt_netlogon_response_from_pdc(struct ndr_push *ndr, int ndr_flags, const struct nbt_netlogon_response_from_pdc *r); +enum ndr_err_code ndr_pull_nbt_netlogon_response_from_pdc(struct ndr_pull *ndr, int ndr_flags, struct nbt_netlogon_response_from_pdc *r); void ndr_print_nbt_netlogon_response_from_pdc(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_response_from_pdc *r); -void ndr_print_nbt_server_type(struct ndr_print *ndr, const char *name, uint32_t r); -void ndr_print_nbt_dc_sock_addr(struct ndr_print *ndr, const char *name, const struct nbt_dc_sock_addr *r); -void ndr_print_nbt_netlogon_response_from_pdc2(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_response_from_pdc2 *r); -void ndr_print_nbt_db_change(struct ndr_print *ndr, const char *name, const struct nbt_db_change *r); -void ndr_print_nbt_netlogon_announce_uas(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_announce_uas *r); +void ndr_print_nbt_db_change_info(struct ndr_print *ndr, const char *name, const struct nbt_db_change_info *r); +void ndr_print_NETLOGON_DB_CHANGE(struct ndr_print *ndr, const char *name, const struct NETLOGON_DB_CHANGE *r); void ndr_print_nbt_netlogon_request(struct ndr_print *ndr, const char *name, const union nbt_netlogon_request *r); enum ndr_err_code ndr_push_nbt_netlogon_packet(struct ndr_push *ndr, int ndr_flags, const struct nbt_netlogon_packet *r); enum ndr_err_code ndr_pull_nbt_netlogon_packet(struct ndr_pull *ndr, int ndr_flags, struct nbt_netlogon_packet *r); void ndr_print_nbt_netlogon_packet(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_packet *r); -void ndr_print_nbt_cldap_netlogon_1(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_1 *r); -void ndr_print_nbt_cldap_netlogon_3(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_3 *r); -enum ndr_err_code ndr_push_nbt_cldap_netlogon_5(struct ndr_push *ndr, int ndr_flags, const struct nbt_cldap_netlogon_5 *r); -enum ndr_err_code ndr_pull_nbt_cldap_netlogon_5(struct ndr_pull *ndr, int ndr_flags, struct nbt_cldap_netlogon_5 *r); -void ndr_print_nbt_cldap_netlogon_5(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_5 *r); -void ndr_print_nbt_cldap_netlogon_13(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_13 *r); -enum ndr_err_code ndr_push_nbt_cldap_netlogon_15(struct ndr_push *ndr, int ndr_flags, const struct nbt_cldap_netlogon_15 *r); -enum ndr_err_code ndr_pull_nbt_cldap_netlogon_15(struct ndr_pull *ndr, int ndr_flags, struct nbt_cldap_netlogon_15 *r); -void ndr_print_nbt_cldap_netlogon_15(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_15 *r); -enum ndr_err_code ndr_push_nbt_cldap_netlogon_29(struct ndr_push *ndr, int ndr_flags, const struct nbt_cldap_netlogon_29 *r); -enum ndr_err_code ndr_pull_nbt_cldap_netlogon_29(struct ndr_pull *ndr, int ndr_flags, struct nbt_cldap_netlogon_29 *r); -void ndr_print_nbt_cldap_netlogon_29(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_29 *r); -enum ndr_err_code ndr_push_nbt_cldap_netlogon(struct ndr_push *ndr, int ndr_flags, const union nbt_cldap_netlogon *r); -enum ndr_err_code ndr_pull_nbt_cldap_netlogon(struct ndr_pull *ndr, int ndr_flags, union nbt_cldap_netlogon *r); -void ndr_print_nbt_cldap_netlogon(struct ndr_print *ndr, const char *name, const union nbt_cldap_netlogon *r); -void ndr_print_nbt_ntlogon_command(struct ndr_print *ndr, const char *name, enum nbt_ntlogon_command r); -void ndr_print_nbt_ntlogon_sam_logon(struct ndr_print *ndr, const char *name, const struct nbt_ntlogon_sam_logon *r); -void ndr_print_nbt_ntlogon_sam_logon_reply(struct ndr_print *ndr, const char *name, const struct nbt_ntlogon_sam_logon_reply *r); -void ndr_print_nbt_ntlogon_request(struct ndr_print *ndr, const char *name, const union nbt_ntlogon_request *r); -enum ndr_err_code ndr_push_nbt_ntlogon_packet(struct ndr_push *ndr, int ndr_flags, const struct nbt_ntlogon_packet *r); -enum ndr_err_code ndr_pull_nbt_ntlogon_packet(struct ndr_pull *ndr, int ndr_flags, struct nbt_ntlogon_packet *r); -void ndr_print_nbt_ntlogon_packet(struct ndr_print *ndr, const char *name, const struct nbt_ntlogon_packet *r); void ndr_print_nbt_browse_opcode(struct ndr_print *ndr, const char *name, enum nbt_browse_opcode r); void ndr_print_nbt_browse_host_announcement(struct ndr_print *ndr, const char *name, const struct nbt_browse_host_announcement *r); void ndr_print_nbt_browse_announcement_request(struct ndr_print *ndr, const char *name, const struct nbt_browse_announcement_request *r); -- cgit From f07431f5ba59f01975bcb8a012c94a70a0d1408b Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 23 Sep 2008 22:21:52 +0200 Subject: s3-nbt: use the new generated nbt. Guenther --- source3/Makefile.in | 2 + source3/include/includes.h | 1 + source3/include/proto.h | 100 +------------- source3/libads/cldap.c | 117 +++------------- source3/libads/ldap.c | 2 +- source3/libsmb/clidgram.c | 91 ++++-------- source3/libsmb/dsgetdcname.c | 322 +++++++++++++------------------------------ source3/utils/net_ads.c | 8 +- 8 files changed, 151 insertions(+), 492 deletions(-) diff --git a/source3/Makefile.in b/source3/Makefile.in index 97095fcadd..333c5f3001 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -377,6 +377,8 @@ LIBADS_SERVER_OBJ = libads/kerberos_verify.o libads/authdata.o \ SECRETS_OBJ = passdb/secrets.o passdb/machine_sid.o LIBNBT_OBJ = ../libcli/nbt/nbtname.o \ + ../libcli/netlogon.o \ + ../libcli/ndr_netlogon.o \ librpc/gen_ndr/ndr_nbt.o \ librpc/gen_ndr/ndr_svcctl.o diff --git a/source3/include/includes.h b/source3/include/includes.h index ccdc6d3fd3..fbf5ca6cd0 100644 --- a/source3/include/includes.h +++ b/source3/include/includes.h @@ -703,6 +703,7 @@ typedef char fstring[FSTRING_LEN]; #include "librpc/gen_ndr/notify.h" #include "librpc/gen_ndr/xattr.h" #include "librpc/gen_ndr/messaging.h" +#include "librpc/gen_ndr/ndr_nbt.h" #include "librpc/rpc/dcerpc.h" #include "nt_printing.h" #include "idmap.h" diff --git a/source3/include/proto.h b/source3/include/proto.h index 6eac9d1129..4a51835f3d 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -1927,20 +1927,15 @@ NTSTATUS kerberos_return_info3_from_pac(TALLOC_CTX *mem_ctx, struct netr_SamInfo3 **info3); /* The following definitions come from libads/cldap.c */ - bool ads_cldap_netlogon(TALLOC_CTX *mem_ctx, const char *server, const char *realm, - uint32_t *nt_version, - union nbt_cldap_netlogon **reply); + uint32_t nt_version, + struct netlogon_samlogon_response **reply); bool ads_cldap_netlogon_5(TALLOC_CTX *mem_ctx, const char *server, const char *realm, - struct nbt_cldap_netlogon_5 *reply5); -bool pull_mailslot_cldap_reply(TALLOC_CTX *mem_ctx, - const DATA_BLOB *blob, - union nbt_cldap_netlogon *r, - uint32_t *nt_version); + struct NETLOGON_SAM_LOGON_RESPONSE_EX *reply5); /* The following definitions come from libads/disp_sec.c */ @@ -2854,93 +2849,6 @@ _PUBLIC_ enum ndr_err_code ndr_push_samr_RejectReason(struct ndr_push *ndr, int _PUBLIC_ enum ndr_err_code ndr_pull_samr_RejectReason(struct ndr_pull *ndr, int ndr_flags, enum samr_RejectReason *r); _PUBLIC_ void ndr_print_samr_RejectReason(struct ndr_print *ndr, const char *name, enum samr_RejectReason r); -/* The following definitions come from librpc/gen_ndr/ndr_nbt.c */ - -_PUBLIC_ void ndr_print_nbt_operation(struct ndr_print *ndr, const char *name, uint16_t r); -_PUBLIC_ void ndr_print_nbt_name_type(struct ndr_print *ndr, const char *name, enum nbt_name_type r); -_PUBLIC_ void ndr_print_nbt_name(struct ndr_print *ndr, const char *name, const struct nbt_name *r); -_PUBLIC_ void ndr_print_nbt_qclass(struct ndr_print *ndr, const char *name, enum nbt_qclass r); -_PUBLIC_ void ndr_print_nbt_qtype(struct ndr_print *ndr, const char *name, enum nbt_qtype r); -_PUBLIC_ void ndr_print_nbt_name_question(struct ndr_print *ndr, const char *name, const struct nbt_name_question *r); -_PUBLIC_ void ndr_print_nb_flags(struct ndr_print *ndr, const char *name, uint16_t r); -_PUBLIC_ void ndr_print_nbt_rdata_address(struct ndr_print *ndr, const char *name, const struct nbt_rdata_address *r); -_PUBLIC_ void ndr_print_nbt_rdata_netbios(struct ndr_print *ndr, const char *name, const struct nbt_rdata_netbios *r); -_PUBLIC_ void ndr_print_nbt_statistics(struct ndr_print *ndr, const char *name, const struct nbt_statistics *r); -_PUBLIC_ void ndr_print_nbt_status_name(struct ndr_print *ndr, const char *name, const struct nbt_status_name *r); -_PUBLIC_ void ndr_print_nbt_rdata_status(struct ndr_print *ndr, const char *name, const struct nbt_rdata_status *r); -_PUBLIC_ void ndr_print_nbt_rdata_data(struct ndr_print *ndr, const char *name, const struct nbt_rdata_data *r); -_PUBLIC_ void ndr_print_nbt_rdata(struct ndr_print *ndr, const char *name, const union nbt_rdata *r); -_PUBLIC_ void ndr_print_nbt_res_rec(struct ndr_print *ndr, const char *name, const struct nbt_res_rec *r); -_PUBLIC_ enum ndr_err_code ndr_push_nbt_name_packet(struct ndr_push *ndr, int ndr_flags, const struct nbt_name_packet *r); -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_name_packet(struct ndr_pull *ndr, int ndr_flags, struct nbt_name_packet *r); -_PUBLIC_ void ndr_print_nbt_name_packet(struct ndr_print *ndr, const char *name, const struct nbt_name_packet *r); -_PUBLIC_ void ndr_print_dgram_msg_type(struct ndr_print *ndr, const char *name, enum dgram_msg_type r); -_PUBLIC_ void ndr_print_dgram_flags(struct ndr_print *ndr, const char *name, uint8_t r); -_PUBLIC_ void ndr_print_smb_command(struct ndr_print *ndr, const char *name, enum smb_command r); -_PUBLIC_ void ndr_print_smb_trans_body(struct ndr_print *ndr, const char *name, const struct smb_trans_body *r); -_PUBLIC_ void ndr_print_smb_body(struct ndr_print *ndr, const char *name, const union smb_body *r); -_PUBLIC_ enum ndr_err_code ndr_push_dgram_smb_packet(struct ndr_push *ndr, int ndr_flags, const struct dgram_smb_packet *r); -_PUBLIC_ enum ndr_err_code ndr_pull_dgram_smb_packet(struct ndr_pull *ndr, int ndr_flags, struct dgram_smb_packet *r); -_PUBLIC_ void ndr_print_dgram_smb_packet(struct ndr_print *ndr, const char *name, const struct dgram_smb_packet *r); -_PUBLIC_ void ndr_print_dgram_message_body(struct ndr_print *ndr, const char *name, const union dgram_message_body *r); -_PUBLIC_ void ndr_print_dgram_message(struct ndr_print *ndr, const char *name, const struct dgram_message *r); -_PUBLIC_ void ndr_print_dgram_err_code(struct ndr_print *ndr, const char *name, enum dgram_err_code r); -_PUBLIC_ void ndr_print_dgram_data(struct ndr_print *ndr, const char *name, const union dgram_data *r); -_PUBLIC_ enum ndr_err_code ndr_push_nbt_dgram_packet(struct ndr_push *ndr, int ndr_flags, const struct nbt_dgram_packet *r); -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_dgram_packet(struct ndr_pull *ndr, int ndr_flags, struct nbt_dgram_packet *r); -_PUBLIC_ void ndr_print_nbt_dgram_packet(struct ndr_print *ndr, const char *name, const struct nbt_dgram_packet *r); -_PUBLIC_ void ndr_print_nbt_netlogon_command(struct ndr_print *ndr, const char *name, enum nbt_netlogon_command r); -_PUBLIC_ void ndr_print_nbt_netlogon_version(struct ndr_print *ndr, const char *name, uint32_t r); -_PUBLIC_ void ndr_print_nbt_netlogon_query_for_pdc(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_query_for_pdc *r); -_PUBLIC_ void ndr_print_nbt_netlogon_query_for_pdc2(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_query_for_pdc2 *r); -_PUBLIC_ void ndr_print_nbt_netlogon_response_from_pdc(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_response_from_pdc *r); -_PUBLIC_ void ndr_print_nbt_server_type(struct ndr_print *ndr, const char *name, uint32_t r); -_PUBLIC_ void ndr_print_nbt_dc_sock_addr(struct ndr_print *ndr, const char *name, const struct nbt_dc_sock_addr *r); -_PUBLIC_ void ndr_print_nbt_netlogon_response_from_pdc2(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_response_from_pdc2 *r); -_PUBLIC_ void ndr_print_nbt_db_change(struct ndr_print *ndr, const char *name, const struct nbt_db_change *r); -_PUBLIC_ void ndr_print_nbt_netlogon_announce_uas(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_announce_uas *r); -_PUBLIC_ void ndr_print_nbt_netlogon_request(struct ndr_print *ndr, const char *name, const union nbt_netlogon_request *r); -_PUBLIC_ enum ndr_err_code ndr_push_nbt_netlogon_packet(struct ndr_push *ndr, int ndr_flags, const struct nbt_netlogon_packet *r); -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_netlogon_packet(struct ndr_pull *ndr, int ndr_flags, struct nbt_netlogon_packet *r); -_PUBLIC_ void ndr_print_nbt_netlogon_packet(struct ndr_print *ndr, const char *name, const struct nbt_netlogon_packet *r); -_PUBLIC_ void ndr_print_nbt_cldap_netlogon_1(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_1 *r); -_PUBLIC_ void ndr_print_nbt_cldap_netlogon_3(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_3 *r); -_PUBLIC_ enum ndr_err_code ndr_push_nbt_cldap_netlogon_5(struct ndr_push *ndr, int ndr_flags, const struct nbt_cldap_netlogon_5 *r); -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_cldap_netlogon_5(struct ndr_pull *ndr, int ndr_flags, struct nbt_cldap_netlogon_5 *r); -_PUBLIC_ void ndr_print_nbt_cldap_netlogon_5(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_5 *r); -_PUBLIC_ void ndr_print_nbt_cldap_netlogon_13(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_13 *r); -_PUBLIC_ enum ndr_err_code ndr_push_nbt_cldap_netlogon_15(struct ndr_push *ndr, int ndr_flags, const struct nbt_cldap_netlogon_15 *r); -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_cldap_netlogon_15(struct ndr_pull *ndr, int ndr_flags, struct nbt_cldap_netlogon_15 *r); -_PUBLIC_ void ndr_print_nbt_cldap_netlogon_15(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_15 *r); -_PUBLIC_ enum ndr_err_code ndr_push_nbt_cldap_netlogon_29(struct ndr_push *ndr, int ndr_flags, const struct nbt_cldap_netlogon_29 *r); -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_cldap_netlogon_29(struct ndr_pull *ndr, int ndr_flags, struct nbt_cldap_netlogon_29 *r); -_PUBLIC_ void ndr_print_nbt_cldap_netlogon_29(struct ndr_print *ndr, const char *name, const struct nbt_cldap_netlogon_29 *r); -_PUBLIC_ enum ndr_err_code ndr_push_nbt_cldap_netlogon(struct ndr_push *ndr, int ndr_flags, const union nbt_cldap_netlogon *r); -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_cldap_netlogon(struct ndr_pull *ndr, int ndr_flags, union nbt_cldap_netlogon *r); -_PUBLIC_ void ndr_print_nbt_cldap_netlogon(struct ndr_print *ndr, const char *name, const union nbt_cldap_netlogon *r); -_PUBLIC_ void ndr_print_nbt_ntlogon_command(struct ndr_print *ndr, const char *name, enum nbt_ntlogon_command r); -_PUBLIC_ void ndr_print_nbt_ntlogon_sam_logon(struct ndr_print *ndr, const char *name, const struct nbt_ntlogon_sam_logon *r); -_PUBLIC_ void ndr_print_nbt_ntlogon_sam_logon_reply(struct ndr_print *ndr, const char *name, const struct nbt_ntlogon_sam_logon_reply *r); -_PUBLIC_ void ndr_print_nbt_ntlogon_request(struct ndr_print *ndr, const char *name, const union nbt_ntlogon_request *r); -_PUBLIC_ enum ndr_err_code ndr_push_nbt_ntlogon_packet(struct ndr_push *ndr, int ndr_flags, const struct nbt_ntlogon_packet *r); -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_ntlogon_packet(struct ndr_pull *ndr, int ndr_flags, struct nbt_ntlogon_packet *r); -_PUBLIC_ void ndr_print_nbt_ntlogon_packet(struct ndr_print *ndr, const char *name, const struct nbt_ntlogon_packet *r); -_PUBLIC_ void ndr_print_nbt_browse_opcode(struct ndr_print *ndr, const char *name, enum nbt_browse_opcode r); -_PUBLIC_ void ndr_print_nbt_browse_host_announcement(struct ndr_print *ndr, const char *name, const struct nbt_browse_host_announcement *r); -_PUBLIC_ void ndr_print_nbt_browse_announcement_request(struct ndr_print *ndr, const char *name, const struct nbt_browse_announcement_request *r); -_PUBLIC_ void ndr_print_nbt_browse_election_request(struct ndr_print *ndr, const char *name, const struct nbt_browse_election_request *r); -_PUBLIC_ void ndr_print_nbt_browse_backup_list_request(struct ndr_print *ndr, const char *name, const struct nbt_browse_backup_list_request *r); -_PUBLIC_ void ndr_print_nbt_browse_backup_list_response(struct ndr_print *ndr, const char *name, const struct nbt_browse_backup_list_response *r); -_PUBLIC_ void ndr_print_nbt_browse_become_backup(struct ndr_print *ndr, const char *name, const struct nbt_browse_become_backup *r); -_PUBLIC_ void ndr_print_nbt_browse_domain_announcement(struct ndr_print *ndr, const char *name, const struct nbt_browse_domain_announcement *r); -_PUBLIC_ void ndr_print_nbt_browse_master_announcement(struct ndr_print *ndr, const char *name, const struct nbt_browse_master_announcement *r); -_PUBLIC_ void ndr_print_nbt_browse_reset_state(struct ndr_print *ndr, const char *name, const struct nbt_browse_reset_state *r); -_PUBLIC_ void ndr_print_nbt_browse_local_master_announcement(struct ndr_print *ndr, const char *name, const struct nbt_browse_local_master_announcement *r); -_PUBLIC_ void ndr_print_nbt_browse_payload(struct ndr_print *ndr, const char *name, const union nbt_browse_payload *r); -_PUBLIC_ enum ndr_err_code ndr_push_nbt_browse_packet(struct ndr_push *ndr, int ndr_flags, const struct nbt_browse_packet *r); -_PUBLIC_ enum ndr_err_code ndr_pull_nbt_browse_packet(struct ndr_pull *ndr, int ndr_flags, struct nbt_browse_packet *r); -_PUBLIC_ void ndr_print_nbt_browse_packet(struct ndr_print *ndr, const char *name, const struct nbt_browse_packet *r); - /* The following definitions come from librpc/gen_ndr/ndr_netlogon.c */ _PUBLIC_ void ndr_print_netr_UasInfo(struct ndr_print *ndr, const char *name, const struct netr_UasInfo *r); @@ -4295,7 +4203,7 @@ bool receive_getdc_response(TALLOC_CTX *mem_ctx, const char *domain_name, uint32_t *nt_version, const char **dc_name, - union nbt_cldap_netlogon **reply); + struct netlogon_samlogon_response **reply); /* The following definitions come from libsmb/clientgen.c */ diff --git a/source3/libads/cldap.c b/source3/libads/cldap.c index b89d285e8c..edabbed0e9 100644 --- a/source3/libads/cldap.c +++ b/source3/libads/cldap.c @@ -119,8 +119,8 @@ static void gotalarm_sig(void) */ static int recv_cldap_netlogon(TALLOC_CTX *mem_ctx, int sock, - uint32_t *nt_version, - union nbt_cldap_netlogon **reply) + uint32_t nt_version, + struct netlogon_samlogon_response **reply) { int ret; ASN1_DATA data; @@ -131,7 +131,8 @@ static int recv_cldap_netlogon(TALLOC_CTX *mem_ctx, int i1; /* half the time of a regular ldap timeout, not less than 3 seconds. */ unsigned int al_secs = MAX(3,lp_ldap_timeout()/2); - union nbt_cldap_netlogon *r = NULL; + struct netlogon_samlogon_response *r = NULL; + NTSTATUS status; blob = data_blob(NULL, 8192); if (blob.data == NULL) { @@ -185,7 +186,7 @@ static int recv_cldap_netlogon(TALLOC_CTX *mem_ctx, return -1; } - r = TALLOC_ZERO_P(mem_ctx, union nbt_cldap_netlogon); + r = TALLOC_ZERO_P(mem_ctx, struct netlogon_samlogon_response); if (!r) { errno = ENOMEM; data_blob_free(&os1); @@ -195,7 +196,8 @@ static int recv_cldap_netlogon(TALLOC_CTX *mem_ctx, return -1; } - if (!pull_mailslot_cldap_reply(mem_ctx, &os3, r, nt_version)) { + status = pull_netlogon_samlogon_response(&os3, mem_ctx, NULL, r); + if (!NT_STATUS_IS_OK(status)) { data_blob_free(&os1); data_blob_free(&os2); data_blob_free(&os3); @@ -204,6 +206,8 @@ static int recv_cldap_netlogon(TALLOC_CTX *mem_ctx, return -1; } + map_netlogon_samlogon_response(r); + data_blob_free(&os1); data_blob_free(&os2); data_blob_free(&os3); @@ -227,8 +231,8 @@ static int recv_cldap_netlogon(TALLOC_CTX *mem_ctx, bool ads_cldap_netlogon(TALLOC_CTX *mem_ctx, const char *server, const char *realm, - uint32_t *nt_version, - union nbt_cldap_netlogon **reply) + uint32_t nt_version, + struct netlogon_samlogon_response **reply) { int sock; int ret; @@ -240,7 +244,7 @@ bool ads_cldap_netlogon(TALLOC_CTX *mem_ctx, return False; } - ret = send_cldap_netlogon(sock, realm, global_myname(), *nt_version); + ret = send_cldap_netlogon(sock, realm, global_myname(), nt_version); if (ret != 0) { close(sock); return False; @@ -262,107 +266,24 @@ bool ads_cldap_netlogon(TALLOC_CTX *mem_ctx, bool ads_cldap_netlogon_5(TALLOC_CTX *mem_ctx, const char *server, const char *realm, - struct nbt_cldap_netlogon_5 *reply5) + struct NETLOGON_SAM_LOGON_RESPONSE_EX *reply5) { uint32_t nt_version = NETLOGON_NT_VERSION_5 | NETLOGON_NT_VERSION_5EX; - union nbt_cldap_netlogon *reply = NULL; + struct netlogon_samlogon_response *reply = NULL; bool ret; - ret = ads_cldap_netlogon(mem_ctx, server, realm, &nt_version, &reply); + ret = ads_cldap_netlogon(mem_ctx, server, realm, nt_version, &reply); if (!ret) { return false; } - if (nt_version != (NETLOGON_NT_VERSION_5 | NETLOGON_NT_VERSION_5EX)) { + if (reply->ntver != NETLOGON_NT_VERSION_5EX) { + DEBUG(0,("ads_cldap_netlogon_5: nt_version mismatch: 0x%08x\n", + reply->ntver)); return false; } - *reply5 = reply->logon5; - - return true; -} - -/**************************************************************** -****************************************************************/ - -bool pull_mailslot_cldap_reply(TALLOC_CTX *mem_ctx, - const DATA_BLOB *blob, - union nbt_cldap_netlogon *r, - uint32_t *nt_version) -{ - enum ndr_err_code ndr_err; - uint32_t nt_version_query = ((*nt_version) & 0x0000001f); - uint16_t command = 0; - - ndr_err = ndr_pull_struct_blob(blob, mem_ctx, NULL, &command, - (ndr_pull_flags_fn_t)ndr_pull_uint16); - if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - return false; - } - - switch (command) { - case 0x13: /* 19 */ - case 0x15: /* 21 */ - case 0x17: /* 23 */ - case 0x19: /* 25 */ - break; - default: - DEBUG(1,("got unexpected command: %d (0x%08x)\n", - command, command)); - return false; - } - - ndr_err = ndr_pull_union_blob_all(blob, mem_ctx, r, nt_version_query, - (ndr_pull_flags_fn_t)ndr_pull_nbt_cldap_netlogon); - if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - goto done; - } - - /* when the caller requested just those nt_version bits that the server - * was able to reply to, we are fine and all done. otherwise we need to - * assume downgraded replies which are painfully parsed here - gd */ - - if (nt_version_query & NETLOGON_NT_VERSION_WITH_CLOSEST_SITE) { - nt_version_query &= ~NETLOGON_NT_VERSION_WITH_CLOSEST_SITE; - } - ndr_err = ndr_pull_union_blob_all(blob, mem_ctx, r, nt_version_query, - (ndr_pull_flags_fn_t)ndr_pull_nbt_cldap_netlogon); - if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - goto done; - } - if (nt_version_query & NETLOGON_NT_VERSION_5EX_WITH_IP) { - nt_version_query &= ~NETLOGON_NT_VERSION_5EX_WITH_IP; - } - ndr_err = ndr_pull_union_blob_all(blob, mem_ctx, r, nt_version_query, - (ndr_pull_flags_fn_t)ndr_pull_nbt_cldap_netlogon); - if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - goto done; - } - if (nt_version_query & NETLOGON_NT_VERSION_5EX) { - nt_version_query &= ~NETLOGON_NT_VERSION_5EX; - } - ndr_err = ndr_pull_union_blob_all(blob, mem_ctx, r, nt_version_query, - (ndr_pull_flags_fn_t)ndr_pull_nbt_cldap_netlogon); - if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - goto done; - } - if (nt_version_query & NETLOGON_NT_VERSION_5) { - nt_version_query &= ~NETLOGON_NT_VERSION_5; - } - ndr_err = ndr_pull_union_blob_all(blob, mem_ctx, r, nt_version_query, - (ndr_pull_flags_fn_t)ndr_pull_nbt_cldap_netlogon); - if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - goto done; - } - - return false; - - done: - if (DEBUGLEVEL >= 10) { - NDR_PRINT_UNION_DEBUG(nbt_cldap_netlogon, nt_version_query, r); - } - - *nt_version = nt_version_query; + *reply5 = reply->nt5_ex; return true; } diff --git a/source3/libads/ldap.c b/source3/libads/ldap.c index eb45e3a0dd..bfcfcf30b9 100644 --- a/source3/libads/ldap.c +++ b/source3/libads/ldap.c @@ -176,7 +176,7 @@ bool ads_closest_dc(ADS_STRUCT *ads) static bool ads_try_connect(ADS_STRUCT *ads, const char *server, bool gc) { char *srv; - struct nbt_cldap_netlogon_5 cldap_reply; + struct NETLOGON_SAM_LOGON_RESPONSE_EX cldap_reply; TALLOC_CTX *mem_ctx = NULL; bool ret = false; diff --git a/source3/libsmb/clidgram.c b/source3/libsmb/clidgram.c index 8ee3507a04..e8799bce47 100644 --- a/source3/libsmb/clidgram.c +++ b/source3/libsmb/clidgram.c @@ -136,8 +136,8 @@ bool send_getdc_request(TALLOC_CTX *mem_ctx, struct in_addr dc_ip; const char *my_acct_name = NULL; const char *my_mailslot = NULL; - struct nbt_ntlogon_packet packet; - struct nbt_ntlogon_sam_logon *s; + struct nbt_netlogon_packet packet; + struct NETLOGON_SAM_LOGON_REQUEST *s; enum ndr_err_code ndr_err; DATA_BLOB blob; struct dom_sid my_sid; @@ -164,7 +164,7 @@ bool send_getdc_request(TALLOC_CTX *mem_ctx, return false; } - packet.command = NTLOGON_SAM_LOGON; + packet.command = LOGON_SAM_LOGON_REQUEST; s = &packet.req.logon; s->request_count = 0; @@ -178,11 +178,11 @@ bool send_getdc_request(TALLOC_CTX *mem_ctx, s->lm20_token = 0xffff; if (DEBUGLEVEL >= 10) { - NDR_PRINT_DEBUG(nbt_ntlogon_packet, &packet); + NDR_PRINT_DEBUG(nbt_netlogon_packet, &packet); } ndr_err = ndr_push_struct_blob(&blob, mem_ctx, NULL, &packet, - (ndr_push_flags_fn_t)ndr_push_nbt_ntlogon_packet); + (ndr_push_flags_fn_t)ndr_push_nbt_netlogon_packet); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { return false; } @@ -199,15 +199,16 @@ bool receive_getdc_response(TALLOC_CTX *mem_ctx, const char *domain_name, uint32_t *nt_version, const char **dc_name, - union nbt_cldap_netlogon **reply) + struct netlogon_samlogon_response **_r) { struct packet_struct *packet; const char *my_mailslot = NULL; struct in_addr dc_ip; DATA_BLOB blob; - union nbt_cldap_netlogon r; + struct netlogon_samlogon_response r; union dgram_message_body p; enum ndr_err_code ndr_err; + NTSTATUS status; const char *returned_dc = NULL; const char *returned_domain = NULL; @@ -266,66 +267,20 @@ bool receive_getdc_response(TALLOC_CTX *mem_ctx, blob = p.smb.body.trans.data; - if (!pull_mailslot_cldap_reply(mem_ctx, &blob, - &r, nt_version)) - { + ZERO_STRUCT(r); + + status = pull_netlogon_samlogon_response(&blob, mem_ctx, NULL, &r); + if (!NT_STATUS_IS_OK(status)) { return false; } - switch (*nt_version) { - case 1: - case 16: - case 17: - - returned_domain = r.logon1.domain_name; - returned_dc = r.logon1.pdc_name; - break; - case 2: - case 3: - case 18: - case 19: - returned_domain = r.logon3.domain_name; - returned_dc = r.logon3.pdc_name; - break; - case 4: - case 5: - case 6: - case 7: - returned_domain = r.logon5.domain; - returned_dc = r.logon5.pdc_name; - break; - case 8: - case 9: - case 10: - case 11: - case 12: - case 13: - case 14: - case 15: - returned_domain = r.logon13.domain; - returned_dc = r.logon13.pdc_name; - break; - case 20: - case 21: - case 22: - case 23: - case 24: - case 25: - case 26: - case 27: - case 28: - returned_domain = r.logon15.domain; - returned_dc = r.logon15.pdc_name; - break; - case 29: - case 30: - case 31: - returned_domain = r.logon29.domain; - returned_dc = r.logon29.pdc_name; - break; - default: - return false; - } + map_netlogon_samlogon_response(&r); + + /* do we still need this ? */ + *nt_version = r.ntver; + + returned_domain = r.nt5_ex.domain; + returned_dc = r.nt5_ex.pdc_name; if (!strequal(returned_domain, domain_name)) { DEBUG(3, ("GetDC: Expected domain %s, got %s\n", @@ -341,10 +296,10 @@ bool receive_getdc_response(TALLOC_CTX *mem_ctx, if (**dc_name == '\\') *dc_name += 1; if (**dc_name == '\\') *dc_name += 1; - if (reply) { - *reply = (union nbt_cldap_netlogon *)talloc_memdup( - mem_ctx, &r, sizeof(union nbt_cldap_netlogon)); - if (!*reply) { + if (_r) { + *_r = (struct netlogon_samlogon_response *)talloc_memdup( + mem_ctx, &r, sizeof(struct netlogon_samlogon_response)); + if (!*_r) { return false; } } diff --git a/source3/libsmb/dsgetdcname.c b/source3/libsmb/dsgetdcname.c index 4cc587c58d..a543e073bc 100644 --- a/source3/libsmb/dsgetdcname.c +++ b/source3/libsmb/dsgetdcname.c @@ -35,8 +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, - uint32_t nt_version, - union nbt_cldap_netlogon *r, + struct netlogon_samlogon_response *r, struct netr_DsRGetDCNameInfo **info); /**************************************************************** @@ -186,173 +185,46 @@ static NTSTATUS dsgetdcname_cache_store(TALLOC_CTX *mem_ctx, /**************************************************************** ****************************************************************/ -#define SET_STRING(x) \ - talloc_strdup(mem_ctx, x); \ - NT_STATUS_HAVE_NO_MEMORY(x); - -static NTSTATUS map_logon29_from_cldap_reply(TALLOC_CTX *mem_ctx, - uint32_t flags, - struct sockaddr_storage *ss, - uint32_t nt_version, - union nbt_cldap_netlogon *r, - struct nbt_cldap_netlogon_29 *p) -{ - char addr[INET6_ADDRSTRLEN]; - - ZERO_STRUCTP(p); - - print_sockaddr(addr, sizeof(addr), ss); - - /* FIXME */ - p->dc_sock_addr_size = 0x10; /* the w32 winsock addr size */ - p->dc_sock_addr.family = 2; /* AF_INET */ - p->dc_sock_addr.pdc_ip = talloc_strdup(mem_ctx, addr); - - switch (nt_version & 0x0000001f) { - case 0: - return NT_STATUS_INVALID_PARAMETER; - case 1: - case 16: - case 17: - p->pdc_name = SET_STRING(r->logon1.pdc_name); - p->domain = SET_STRING(r->logon1.domain_name); - - if (flags & DS_PDC_REQUIRED) { - p->server_type = NBT_SERVER_WRITABLE | - NBT_SERVER_PDC; - } - break; - case 2: - case 3: - case 18: - case 19: - p->pdc_name = SET_STRING(r->logon3.pdc_name); - p->domain = SET_STRING(r->logon3.domain_name); - p->pdc_dns_name = SET_STRING(r->logon3.pdc_dns_name); - p->dns_domain = SET_STRING(r->logon3.dns_domain); - p->server_type = r->logon3.server_type; - p->forest = SET_STRING(r->logon3.forest); - p->domain_uuid = r->logon3.domain_uuid; - - break; - case 4: - case 5: - case 6: - case 7: - p->pdc_name = SET_STRING(r->logon5.pdc_name); - p->domain = SET_STRING(r->logon5.domain); - p->pdc_dns_name = SET_STRING(r->logon5.pdc_dns_name); - p->dns_domain = SET_STRING(r->logon5.dns_domain); - p->server_type = r->logon5.server_type; - p->forest = SET_STRING(r->logon5.forest); - p->domain_uuid = r->logon5.domain_uuid; - p->server_site = SET_STRING(r->logon5.server_site); - p->client_site = SET_STRING(r->logon5.client_site); - - break; - case 8: - case 9: - case 10: - case 11: - case 12: - case 13: - case 14: - case 15: - p->pdc_name = SET_STRING(r->logon13.pdc_name); - p->domain = SET_STRING(r->logon13.domain); - p->pdc_dns_name = SET_STRING(r->logon13.pdc_dns_name); - p->dns_domain = SET_STRING(r->logon13.dns_domain); - p->server_type = r->logon13.server_type; - p->forest = SET_STRING(r->logon13.forest); - p->domain_uuid = r->logon13.domain_uuid; - p->server_site = SET_STRING(r->logon13.server_site); - p->client_site = SET_STRING(r->logon13.client_site); - - break; - case 20: - case 21: - case 22: - case 23: - case 24: - case 25: - case 26: - case 27: - case 28: - p->pdc_name = SET_STRING(r->logon15.pdc_name); - p->domain = SET_STRING(r->logon15.domain); - p->pdc_dns_name = SET_STRING(r->logon15.pdc_dns_name); - p->dns_domain = SET_STRING(r->logon15.dns_domain); - p->server_type = r->logon15.server_type; - p->forest = SET_STRING(r->logon15.forest); - p->domain_uuid = r->logon15.domain_uuid; - p->server_site = SET_STRING(r->logon15.server_site); - p->client_site = SET_STRING(r->logon15.client_site); - - break; - case 29: - case 30: - case 31: - p->pdc_name = SET_STRING(r->logon29.pdc_name); - p->domain = SET_STRING(r->logon29.domain); - p->pdc_dns_name = SET_STRING(r->logon29.pdc_dns_name); - p->dns_domain = SET_STRING(r->logon29.dns_domain); - p->server_type = r->logon29.server_type; - p->forest = SET_STRING(r->logon29.forest); - p->domain_uuid = r->logon29.domain_uuid; - p->server_site = SET_STRING(r->logon29.server_site); - p->client_site = SET_STRING(r->logon29.client_site); - p->next_closest_site = SET_STRING(r->logon29.next_closest_site); - - break; - default: - return NT_STATUS_INVALID_PARAMETER; - } - - return NT_STATUS_OK; -} - -/**************************************************************** -****************************************************************/ - static NTSTATUS store_cldap_reply(TALLOC_CTX *mem_ctx, uint32_t flags, struct sockaddr_storage *ss, uint32_t nt_version, - union nbt_cldap_netlogon *r) + struct NETLOGON_SAM_LOGON_RESPONSE_EX *r) { DATA_BLOB blob; enum ndr_err_code ndr_err; NTSTATUS status; - struct nbt_cldap_netlogon_29 logon29; + char addr[INET6_ADDRSTRLEN]; - status = map_logon29_from_cldap_reply(mem_ctx, flags, ss, - nt_version, r, &logon29); - if (!NT_STATUS_IS_OK(status)) { - return status; - } + print_sockaddr(addr, sizeof(addr), ss); + + /* FIXME */ + r->sockaddr_size = 0x10; /* the w32 winsock addr size */ + r->sockaddr.sa_family = 2; /* AF_INET */ + r->sockaddr.pdc_ip = talloc_strdup(mem_ctx, addr); - ndr_err = ndr_push_struct_blob(&blob, mem_ctx, NULL, &logon29, - (ndr_push_flags_fn_t)ndr_push_nbt_cldap_netlogon_29); + ndr_err = ndr_push_struct_blob(&blob, mem_ctx, NULL, r, + (ndr_push_flags_fn_t)ndr_push_NETLOGON_SAM_LOGON_RESPONSE_EX); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { return ndr_map_error2ntstatus(ndr_err); } - if (logon29.domain) { - status = dsgetdcname_cache_store(mem_ctx, logon29.domain, &blob); + if (r->domain) { + status = dsgetdcname_cache_store(mem_ctx, r->domain, &blob); if (!NT_STATUS_IS_OK(status)) { goto done; } - if (logon29.client_site) { - sitename_store(logon29.domain, logon29.client_site); + if (r->client_site) { + sitename_store(r->domain, r->client_site); } } - if (logon29.dns_domain) { - status = dsgetdcname_cache_store(mem_ctx, logon29.dns_domain, &blob); + if (r->dns_domain) { + status = dsgetdcname_cache_store(mem_ctx, r->dns_domain, &blob); if (!NT_STATUS_IS_OK(status)) { goto done; } - if (logon29.client_site) { - sitename_store(logon29.dns_domain, logon29.client_site); + if (r->client_site) { + sitename_store(r->dns_domain, r->client_site); } } @@ -387,7 +259,7 @@ static NTSTATUS dsgetdcname_cache_refresh(TALLOC_CTX *mem_ctx, /**************************************************************** ****************************************************************/ -static uint32_t get_cldap_reply_server_flags(union nbt_cldap_netlogon *r, +static uint32_t get_cldap_reply_server_flags(struct netlogon_samlogon_response *r, uint32_t nt_version) { switch (nt_version & 0x0000001f) { @@ -400,12 +272,12 @@ static uint32_t get_cldap_reply_server_flags(union nbt_cldap_netlogon *r, case 3: case 18: case 19: - return r->logon3.server_type; + return r->nt5.server_type; case 4: case 5: case 6: case 7: - return r->logon5.server_type; + return r->nt5_ex.server_type; case 8: case 9: case 10: @@ -414,7 +286,7 @@ static uint32_t get_cldap_reply_server_flags(union nbt_cldap_netlogon *r, case 13: case 14: case 15: - return r->logon13.server_type; + return r->nt5_ex.server_type; case 20: case 21: case 22: @@ -424,11 +296,11 @@ static uint32_t get_cldap_reply_server_flags(union nbt_cldap_netlogon *r, case 26: case 27: case 28: - return r->logon15.server_type; + return r->nt5_ex.server_type; case 29: case 30: case 31: - return r->logon29.server_type; + return r->nt5_ex.server_type; default: return 0; } @@ -486,8 +358,8 @@ static NTSTATUS dsgetdcname_cache_fetch(TALLOC_CTX *mem_ctx, DATA_BLOB blob; enum ndr_err_code ndr_err; struct netr_DsRGetDCNameInfo *info; - union nbt_cldap_netlogon p; - struct nbt_cldap_netlogon_29 r; + struct netlogon_samlogon_response p; + struct NETLOGON_SAM_LOGON_RESPONSE_EX r; NTSTATUS status; if (!gencache_init()) { @@ -509,7 +381,7 @@ static NTSTATUS dsgetdcname_cache_fetch(TALLOC_CTX *mem_ctx, } ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, NULL, &r, - (ndr_pull_flags_fn_t)ndr_pull_nbt_cldap_netlogon_29); + (ndr_pull_flags_fn_t)ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_EX); data_blob_free(&blob); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { @@ -517,10 +389,9 @@ static NTSTATUS dsgetdcname_cache_fetch(TALLOC_CTX *mem_ctx, return ndr_map_error2ntstatus(ndr_err); } - p.logon29 = r; + p.nt5_ex = r; status = make_dc_info_from_cldap_reply(mem_ctx, flags, NULL, - 29, &p, &info); if (!NT_STATUS_IS_OK(status)) { return status; @@ -916,8 +787,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, - uint32_t nt_version, - union nbt_cldap_netlogon *r, + struct netlogon_samlogon_response *r, struct netr_DsRGetDCNameInfo **info) { const char *dc_hostname = NULL; @@ -938,19 +808,19 @@ static NTSTATUS make_dc_info_from_cldap_reply(TALLOC_CTX *mem_ctx, dc_address_type = DS_ADDRESS_TYPE_INET; } - switch (nt_version & 0x0000001f) { + switch (r->ntver & 0x0000001f) { case 0: case 1: case 16: case 17: if (!ss) { - dc_address = r->logon1.pdc_name; + dc_address = r->nt4.server; dc_address_type = DS_ADDRESS_TYPE_NETBIOS; } map_dc_and_domain_names(flags, - r->logon1.pdc_name, - r->logon1.domain_name, + r->nt4.server, + r->nt4.domain, NULL, NULL, &dc_flags, @@ -966,22 +836,22 @@ static NTSTATUS make_dc_info_from_cldap_reply(TALLOC_CTX *mem_ctx, case 18: case 19: if (!ss) { - dc_address = r->logon3.pdc_ip; + dc_address = r->nt5.pdc_ip; dc_address_type = DS_ADDRESS_TYPE_INET; } map_dc_and_domain_names(flags, - r->logon3.pdc_name, - r->logon3.domain_name, - r->logon3.pdc_dns_name, - r->logon3.dns_domain, + 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->logon3.server_type; - dc_forest = r->logon3.forest; - dc_domain_guid = &r->logon3.domain_uuid; + dc_flags |= r->nt5.server_type; + dc_forest = r->nt5.forest; + dc_domain_guid = &r->nt5.domain_uuid; break; case 4: @@ -989,24 +859,24 @@ static NTSTATUS make_dc_info_from_cldap_reply(TALLOC_CTX *mem_ctx, case 6: case 7: if (!ss) { - dc_address = r->logon5.pdc_name; + dc_address = r->nt5_ex.pdc_name; dc_address_type = DS_ADDRESS_TYPE_NETBIOS; } map_dc_and_domain_names(flags, - r->logon5.pdc_name, - r->logon5.domain, - r->logon5.pdc_dns_name, - r->logon5.dns_domain, + 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->logon5.server_type; - dc_forest = r->logon5.forest; - dc_domain_guid = &r->logon5.domain_uuid; - dc_server_site = r->logon5.server_site; - dc_client_site = r->logon5.client_site; + 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: @@ -1018,24 +888,24 @@ static NTSTATUS make_dc_info_from_cldap_reply(TALLOC_CTX *mem_ctx, case 14: case 15: if (!ss) { - dc_address = r->logon13.dc_sock_addr.pdc_ip; + dc_address = r->nt5_ex.sockaddr.pdc_ip; dc_address_type = DS_ADDRESS_TYPE_INET; } map_dc_and_domain_names(flags, - r->logon13.pdc_name, - r->logon13.domain, - r->logon13.pdc_dns_name, - r->logon13.dns_domain, + 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->logon13.server_type; - dc_forest = r->logon13.forest; - dc_domain_guid = &r->logon13.domain_uuid; - dc_server_site = r->logon13.server_site; - dc_client_site = r->logon13.client_site; + 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: @@ -1048,48 +918,48 @@ static NTSTATUS make_dc_info_from_cldap_reply(TALLOC_CTX *mem_ctx, case 27: case 28: if (!ss) { - dc_address = r->logon15.pdc_name; + dc_address = r->nt5_ex.pdc_name; dc_address_type = DS_ADDRESS_TYPE_NETBIOS; } map_dc_and_domain_names(flags, - r->logon15.pdc_name, - r->logon15.domain, - r->logon15.pdc_dns_name, - r->logon15.dns_domain, + 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->logon15.server_type; - dc_forest = r->logon15.forest; - dc_domain_guid = &r->logon15.domain_uuid; - dc_server_site = r->logon15.server_site; - dc_client_site = r->logon15.client_site; + 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->logon29.dc_sock_addr.pdc_ip; + dc_address = r->nt5_ex.sockaddr.pdc_ip; dc_address_type = DS_ADDRESS_TYPE_INET; } map_dc_and_domain_names(flags, - r->logon29.pdc_name, - r->logon29.domain, - r->logon29.pdc_dns_name, - r->logon29.dns_domain, + 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->logon29.server_type; - dc_forest = r->logon29.forest; - dc_domain_guid = &r->logon29.domain_uuid; - dc_server_site = r->logon29.server_site; - dc_client_site = r->logon29.client_site; + 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: @@ -1147,7 +1017,7 @@ static NTSTATUS process_dc_dns(TALLOC_CTX *mem_ctx, { int i = 0; bool valid_dc = false; - union nbt_cldap_netlogon *r = NULL; + struct netlogon_samlogon_response *r = NULL; uint32_t nt_version = NETLOGON_NT_VERSION_5 | NETLOGON_NT_VERSION_5EX; uint32_t ret_flags = 0; @@ -1161,9 +1031,10 @@ static NTSTATUS process_dc_dns(TALLOC_CTX *mem_ctx, if (ads_cldap_netlogon(mem_ctx, dclist[i].hostname, domain_name, - &nt_version, + nt_version, &r)) { + nt_version = r->ntver; ret_flags = get_cldap_reply_server_flags(r, nt_version); if (check_cldap_reply_required_flags(ret_flags, flags)) { @@ -1180,10 +1051,10 @@ static NTSTATUS process_dc_dns(TALLOC_CTX *mem_ctx, } status = make_dc_info_from_cldap_reply(mem_ctx, flags, &dclist[i].ss, - nt_version, r, info); + r, info); if (NT_STATUS_IS_OK(status)) { return store_cldap_reply(mem_ctx, flags, &dclist[i].ss, - nt_version, r); + nt_version, &r->nt5_ex); } return status; @@ -1234,7 +1105,7 @@ static NTSTATUS process_dc_netbios(TALLOC_CTX *mem_ctx, int i; const char *dc_name = NULL; fstring tmp_dc_name; - union nbt_cldap_netlogon *r = NULL; + struct netlogon_samlogon_response *r = NULL; bool store_cache = false; uint32_t nt_version = NETLOGON_NT_VERSION_1 | NETLOGON_NT_VERSION_5 | @@ -1288,9 +1159,9 @@ static NTSTATUS process_dc_netbios(TALLOC_CTX *mem_ctx, &dclist[i].ss, tmp_dc_name)) { - struct nbt_cldap_netlogon_1 logon1; + struct NETLOGON_SAM_LOGON_RESPONSE_NT40 logon1; - r = TALLOC_ZERO_P(mem_ctx, union nbt_cldap_netlogon); + r = TALLOC_ZERO_P(mem_ctx, struct netlogon_samlogon_response); NT_STATUS_HAVE_NO_MEMORY(r); ZERO_STRUCT(logon1); @@ -1298,11 +1169,12 @@ static NTSTATUS process_dc_netbios(TALLOC_CTX *mem_ctx, nt_version = NETLOGON_NT_VERSION_1; logon1.nt_version = nt_version; - logon1.pdc_name = tmp_dc_name; - logon1.domain_name = talloc_strdup_upper(mem_ctx, domain_name); - NT_STATUS_HAVE_NO_MEMORY(logon1.domain_name); + logon1.server = tmp_dc_name; + logon1.domain = talloc_strdup_upper(mem_ctx, domain_name); + NT_STATUS_HAVE_NO_MEMORY(logon1.domain); - r->logon1 = logon1; + r->nt4 = logon1; + r->ntver = nt_version; namecache_store(tmp_dc_name, NBT_NAME_SERVER, 1, &ip_list); @@ -1315,10 +1187,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, - nt_version, r, info); + r, info); if (NT_STATUS_IS_OK(status) && store_cache) { return store_cldap_reply(mem_ctx, flags, &dclist[i].ss, - nt_version, r); + nt_version, &r->nt5_ex); } return status; diff --git a/source3/utils/net_ads.c b/source3/utils/net_ads.c index 7dbe518c3d..1ef4c152a3 100644 --- a/source3/utils/net_ads.c +++ b/source3/utils/net_ads.c @@ -43,7 +43,7 @@ static const char *assume_own_realm(struct net_context *c) static int net_ads_cldap_netlogon(struct net_context *c, ADS_STRUCT *ads) { char addr[INET6_ADDRSTRLEN]; - struct nbt_cldap_netlogon_5 reply; + struct NETLOGON_SAM_LOGON_RESPONSE_EX reply; print_sockaddr(addr, sizeof(addr), &ads->ldap.ss); if ( !ads_cldap_netlogon_5(talloc_tos(), addr, ads->server.realm, &reply ) ) { @@ -55,7 +55,7 @@ static int net_ads_cldap_netlogon(struct net_context *c, ADS_STRUCT *ads) addr); d_printf("Response Type: "); - switch (reply.type) { + switch (reply.command) { case SAMLOGON_AD_UNK_R: d_printf("SAMLOGON\n"); break; @@ -63,7 +63,7 @@ static int net_ads_cldap_netlogon(struct net_context *c, ADS_STRUCT *ads) d_printf("SAMLOGON_USER\n"); break; default: - d_printf("0x%x\n", reply.type); + d_printf("0x%x\n", reply.command); break; } @@ -359,7 +359,7 @@ static int net_ads_workgroup(struct net_context *c, int argc, const char **argv) { ADS_STRUCT *ads; char addr[INET6_ADDRSTRLEN]; - struct nbt_cldap_netlogon_5 reply; + struct NETLOGON_SAM_LOGON_RESPONSE_EX reply; if (c->display_usage) { d_printf("Usage:\n" -- cgit From 3ee016be9cb6d8d13efcf24fae5d5f0f314379c8 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Wed, 24 Sep 2008 01:16:10 +0200 Subject: libcli: add some basic debugging functions for netlogon helper. Guenther --- libcli/netlogon.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/libcli/netlogon.c b/libcli/netlogon.c index 47d665cfa1..ab5d9af8aa 100644 --- a/libcli/netlogon.c +++ b/libcli/netlogon.c @@ -82,6 +82,10 @@ NTSTATUS pull_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, &response->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); + } + } else if (ntver & NETLOGON_NT_VERSION_5EX) { struct ndr_pull *ndr; ndr = ndr_pull_init_blob(data, mem_ctx, iconv_convenience); @@ -95,6 +99,9 @@ NTSTATUS pull_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, ndr->offset, ndr->data_size); } 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); + } } else if (ntver & NETLOGON_NT_VERSION_5) { ndr_err = ndr_pull_struct_blob_all(data, mem_ctx, @@ -102,6 +109,9 @@ NTSTATUS pull_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, &response->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); + } } else { DEBUG(2,("failed to parse netlogon response of type 0x%02x - unknown response type\n", ntver)); @@ -115,6 +125,7 @@ NTSTATUS pull_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx, dump_data(10, data->data, data->length); return ndr_map_error2ntstatus(ndr_err); } + return NT_STATUS_OK; } -- cgit From 04979bcfb4f9575afc5bec58a53e840479ee3012 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Wed, 24 Sep 2008 02:44:34 +0200 Subject: s3: fix idmap_adex. Guenther --- source3/winbindd/idmap_adex/gc_util.c | 2 +- source3/winbindd/idmap_adex/idmap_adex.c | 2 +- source3/winbindd/idmap_adex/idmap_adex.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/source3/winbindd/idmap_adex/gc_util.c b/source3/winbindd/idmap_adex/gc_util.c index 87dd3c058d..6dc02336d5 100644 --- a/source3/winbindd/idmap_adex/gc_util.c +++ b/source3/winbindd/idmap_adex/gc_util.c @@ -101,7 +101,7 @@ done: ADS_STRUCT *ads = NULL; ADS_STATUS ads_status; NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; - struct nbt_cldap_netlogon_5 cldap_reply; + struct NETLOGON_SAM_LOGON_RESPONSE_EX cldap_reply; TALLOC_CTX *frame = talloc_stackframe(); if (!gc || !domain) { diff --git a/source3/winbindd/idmap_adex/idmap_adex.c b/source3/winbindd/idmap_adex/idmap_adex.c index 23ab843e95..7596b1cbd8 100644 --- a/source3/winbindd/idmap_adex/idmap_adex.c +++ b/source3/winbindd/idmap_adex/idmap_adex.c @@ -454,7 +454,7 @@ NTSTATUS idmap_adex_init(void) return NT_STATUS_OK; } -NTSTATUS nss_info_adex_init(void) +static NTSTATUS nss_info_adex_init(void) { return idmap_adex_init(); } diff --git a/source3/winbindd/idmap_adex/idmap_adex.h b/source3/winbindd/idmap_adex/idmap_adex.h index f91bba8d07..e068d5c340 100644 --- a/source3/winbindd/idmap_adex/idmap_adex.h +++ b/source3/winbindd/idmap_adex/idmap_adex.h @@ -167,7 +167,7 @@ struct likewise_cell *cell_list_head(void); bool cell_list_add(struct likewise_cell *cell); bool cell_list_remove(struct likewise_cell * cell); -void cell_list_destroy(); +void cell_list_destroy(void); void cell_destroy(struct likewise_cell *c); void cell_set_forest_searches(struct likewise_cell *c, bool search); -- cgit From 4962a4459ba73535d39eaa0fb77fd6bbf3f9bd7a Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Wed, 24 Sep 2008 03:51:25 +0200 Subject: libcli: add nbt_proto.h that is no longer autogenerated. Guenther --- libcli/nbt/nbt_proto.h | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 libcli/nbt/nbt_proto.h diff --git a/libcli/nbt/nbt_proto.h b/libcli/nbt/nbt_proto.h new file mode 100644 index 0000000000..b2e8d8525a --- /dev/null +++ b/libcli/nbt/nbt_proto.h @@ -0,0 +1,43 @@ +#ifndef _____LIBCLI_NBT_NBT_PROTO_H__ +#define _____LIBCLI_NBT_NBT_PROTO_H__ + +#undef _PRINTF_ATTRIBUTE +#define _PRINTF_ATTRIBUTE(a1, a2) PRINTF_ATTRIBUTE(a1, a2) +/* This file was automatically generated by mkproto.pl. DO NOT EDIT */ + +/* this file contains prototypes for functions that are private + * to this subsystem or library. These functions should not be + * used outside this particular subsystem! */ + + +/* The following definitions come from ../libcli/nbt/nbtsocket.c */ + +struct nbt_name_request *nbt_name_request_send(struct nbt_name_socket *nbtsock, + struct socket_address *dest, + struct nbt_name_packet *request, + int timeout, int retries, + bool allow_multiple_replies); +NTSTATUS nbt_name_request_recv(struct nbt_name_request *req); + +/* The following definitions come from ../libcli/nbt/namequery.c */ + + +/* The following definitions come from ../libcli/nbt/nameregister.c */ + +struct nbt_name_request *nbt_name_register_send(struct nbt_name_socket *nbtsock, + struct nbt_name_register *io); +NTSTATUS nbt_name_register_bcast(struct nbt_name_socket *nbtsock, + struct nbt_name_register_bcast *io); + +/* The following definitions come from ../libcli/nbt/namerefresh.c */ + +struct nbt_name_request *nbt_name_refresh_send(struct nbt_name_socket *nbtsock, + struct nbt_name_refresh *io); + +/* The following definitions come from ../libcli/nbt/namerelease.c */ + +#undef _PRINTF_ATTRIBUTE +#define _PRINTF_ATTRIBUTE(a1, a2) + +#endif /* _____LIBCLI_NBT_NBT_PROTO_H__ */ + -- cgit From b7d2ff38f54250db52c495d26a2b2923e5dcc83e Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Wed, 24 Sep 2008 03:59:53 +0200 Subject: s4:libcli/smb_composite: we only check the signature when the server return OK We need to manually free the request, otherwise the timeout handler is triggered later. metze --- source4/libcli/smb_composite/sesssetup.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/source4/libcli/smb_composite/sesssetup.c b/source4/libcli/smb_composite/sesssetup.c index 92b49dc3d4..645f5362ac 100644 --- a/source4/libcli/smb_composite/sesssetup.c +++ b/source4/libcli/smb_composite/sesssetup.c @@ -97,6 +97,15 @@ static void request_handler(struct smbcli_request *req) c->status = state->remote_status; state->req = NULL; + /* + * we only need to check the signature if the + * NT_STATUS_OK is returned + */ + if (!NT_STATUS_IS_OK(state->remote_status)) { + talloc_free(check_req); + check_req = NULL; + } + switch (state->setup.old.level) { case RAW_SESSSETUP_OLD: state->io->out.vuid = state->setup.old.out.vuid; -- cgit From 1ca2e4b99fadac78fd9c58ea9ec9973f19659203 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 24 Sep 2008 04:41:30 +0200 Subject: Use new binary name in merged build. --- source3/samba4.mk | 2 +- source4/lib/ldb/ldb_wrap.c | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/source3/samba4.mk b/source3/samba4.mk index 28bdf029f8..53ea76ed90 100644 --- a/source3/samba4.mk +++ b/source3/samba4.mk @@ -158,7 +158,7 @@ clean:: proto:: $(PROTO_HEADERS) modules:: $(PLUGINS) -all:: basics bin/smbd4 bin/regpatch4 bin/regdiff4 bin/regshell4 bin/regtree4 bin/smbclient4 +all:: basics bin/samba4 bin/regpatch4 bin/regdiff4 bin/regshell4 bin/regtree4 bin/smbclient4 torture:: basics bin/smbtorture4 everything:: basics $(patsubst %,%4,$(BINARIES)) diff --git a/source4/lib/ldb/ldb_wrap.c b/source4/lib/ldb/ldb_wrap.c index 74a59355aa..c15fd2b9ae 100644 --- a/source4/lib/ldb/ldb_wrap.c +++ b/source4/lib/ldb/ldb_wrap.c @@ -3204,8 +3204,7 @@ SWIGINTERN PyObject *ldb_schema_format_value(ldb *self,char const *element_name, return ret; } SWIGINTERN ldb_error ldb___contains__(ldb *self,ldb_dn *dn,struct ldb_result **result_as_bool){ - return ldb_search(self, self, result_as_bool, - dn, LDB_SCOPE_BASE, NULL, NULL); + return ldb_search(self, self, result_as_bool, dn, LDB_SCOPE_BASE, NULL, NULL); } SWIGINTERN PyObject *ldb_parse_ldif(ldb *self,char const *s){ PyObject *list = PyList_New(0); -- cgit From 7b20cbb1152af7f3779cbb0dd74d939d8f1637c0 Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Wed, 24 Sep 2008 01:34:10 -0400 Subject: Fix python test, we can't check only the first member, because the order is not guaranteed --- source4/lib/ldb/tests/python/ldap.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/source4/lib/ldb/tests/python/ldap.py b/source4/lib/ldb/tests/python/ldap.py index bc6f80e856..6c910b63f1 100755 --- a/source4/lib/ldb/tests/python/ldap.py +++ b/source4/lib/ldb/tests/python/ldap.py @@ -781,7 +781,10 @@ member: cn=ldaptestuser4,cn=ldaptestcontainer,""" + self.base_dn + """ self.assertTrue("objectGuid" not in res[0]) self.assertTrue("whenCreated" in res[0]) self.assertTrue("nTSecurityDescriptor" in res[0]) - self.assertEquals(res[0]["member"][0].upper(), ("CN=ldaptestuser2,CN=Users," + self.base_dn).upper()) + memberUP = [] + for m in res[0]["member"]: + memberUP.append(m.upper()) + self.assertTrue(("CN=ldaptestuser2,CN=Users," + self.base_dn).upper() in memberUP) ldb.modify_ldif(""" dn: cn=ldaptestgroup2,cn=users,""" + self.base_dn + """ -- cgit From 83b0c5d43f568222d97f9b8de985f1e39a375fb9 Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Wed, 24 Sep 2008 01:37:16 -0400 Subject: Fix nasty bug that would come up only if a client connection to a remote ldap server suddenly dies. We were creating a wrong talloc hierarchy, so the event.fde was not freed automatically as expected. This in turn made the event system call the ldap io handlers with a null packet structure, causing a segfault. Fix also the ordering in ldap_connection_dead() Thanks to Metze for the huge help in tracking down this one. --- source4/auth/gensec/gensec.h | 1 + source4/auth/gensec/socket.c | 13 +++++++------ source4/ldap_server/ldap_bind.c | 1 + source4/libcli/ldap/ldap_bind.c | 1 + source4/libcli/ldap/ldap_client.c | 21 ++++++++++++--------- 5 files changed, 22 insertions(+), 15 deletions(-) diff --git a/source4/auth/gensec/gensec.h b/source4/auth/gensec/gensec.h index 2830297ffe..84fc26d127 100644 --- a/source4/auth/gensec/gensec.h +++ b/source4/auth/gensec/gensec.h @@ -174,6 +174,7 @@ struct gensec_security; struct socket_context; NTSTATUS gensec_socket_init(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, struct socket_context *current_socket, struct event_context *ev, void (*recv_handler)(void *, uint16_t), diff --git a/source4/auth/gensec/socket.c b/source4/auth/gensec/socket.c index 27449bf610..319730e2ca 100644 --- a/source4/auth/gensec/socket.c +++ b/source4/auth/gensec/socket.c @@ -408,8 +408,10 @@ static NTSTATUS gensec_socket_send(struct socket_context *sock, } /* Turn a normal socket into a potentially GENSEC wrapped socket */ +/* CAREFUL: this function will steal 'current_socket' */ NTSTATUS gensec_socket_init(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, struct socket_context *current_socket, struct event_context *ev, void (*recv_handler)(void *, uint16_t), @@ -420,7 +422,7 @@ NTSTATUS gensec_socket_init(struct gensec_security *gensec_security, struct socket_context *new_sock; NTSTATUS nt_status; - nt_status = socket_create_with_ops(current_socket, &gensec_socket_ops, &new_sock, + nt_status = socket_create_with_ops(mem_ctx, &gensec_socket_ops, &new_sock, SOCKET_TYPE_STREAM, current_socket->flags | SOCKET_FLAG_ENCRYPT); if (!NT_STATUS_IS_OK(nt_status)) { *new_socket = NULL; @@ -432,22 +434,19 @@ NTSTATUS gensec_socket_init(struct gensec_security *gensec_security, gensec_socket = talloc(new_sock, struct gensec_socket); if (gensec_socket == NULL) { *new_socket = NULL; + talloc_free(new_sock); return NT_STATUS_NO_MEMORY; } new_sock->private_data = gensec_socket; gensec_socket->socket = current_socket; - if (talloc_reference(gensec_socket, current_socket) == NULL) { - *new_socket = NULL; - return NT_STATUS_NO_MEMORY; - } - /* Nothing to do here, if we are not actually wrapping on this socket */ if (!gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL) && !gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) { gensec_socket->wrap = false; + talloc_steal(gensec_socket, current_socket); *new_socket = new_sock; return NT_STATUS_OK; } @@ -469,6 +468,7 @@ NTSTATUS gensec_socket_init(struct gensec_security *gensec_security, gensec_socket->packet = packet_init(gensec_socket); if (gensec_socket->packet == NULL) { *new_socket = NULL; + talloc_free(new_sock); return NT_STATUS_NO_MEMORY; } @@ -481,6 +481,7 @@ NTSTATUS gensec_socket_init(struct gensec_security *gensec_security, /* TODO: full-request that knows about maximum packet size */ + talloc_steal(gensec_socket, current_socket); *new_socket = new_sock; return NT_STATUS_OK; } diff --git a/source4/ldap_server/ldap_bind.c b/source4/ldap_server/ldap_bind.c index 8357251a8f..20777e5261 100644 --- a/source4/ldap_server/ldap_bind.c +++ b/source4/ldap_server/ldap_bind.c @@ -208,6 +208,7 @@ static NTSTATUS ldapsrv_BindSASL(struct ldapsrv_call *call) } else { ctx->conn = conn; status = gensec_socket_init(conn->gensec, + conn->connection, conn->connection->socket, conn->connection->event.ctx, stream_io_handler_callback, diff --git a/source4/libcli/ldap/ldap_bind.c b/source4/libcli/ldap/ldap_bind.c index 65673116be..b66232c02e 100644 --- a/source4/libcli/ldap/ldap_bind.c +++ b/source4/libcli/ldap/ldap_bind.c @@ -387,6 +387,7 @@ _PUBLIC_ NTSTATUS ldap_bind_sasl(struct ldap_connection *conn, if (NT_STATUS_IS_OK(status)) { struct socket_context *sasl_socket; status = gensec_socket_init(conn->gensec, + conn, conn->sock, conn->event.event_ctx, ldap_read_io_handler, diff --git a/source4/libcli/ldap/ldap_client.c b/source4/libcli/ldap/ldap_client.c index 844238afdb..d7960f901a 100644 --- a/source4/libcli/ldap/ldap_client.c +++ b/source4/libcli/ldap/ldap_client.c @@ -77,6 +77,12 @@ static void ldap_connection_dead(struct ldap_connection *conn) { struct ldap_request *req; + talloc_free(conn->sock); /* this will also free event.fde */ + talloc_free(conn->packet); + conn->sock = NULL; + conn->event.fde = NULL; + conn->packet = NULL; + /* return an error for any pending request ... */ while (conn->pending) { req = conn->pending; @@ -87,12 +93,6 @@ static void ldap_connection_dead(struct ldap_connection *conn) req->async.fn(req); } } - - talloc_free(conn->sock); /* this will also free event.fde */ - talloc_free(conn->packet); - conn->sock = NULL; - conn->event.fde = NULL; - conn->packet = NULL; } static void ldap_reconnect(struct ldap_connection *conn); @@ -400,6 +400,7 @@ static void ldap_connect_got_sock(struct composite_context *ctx, talloc_steal(conn, conn->sock); if (conn->ldaps) { struct socket_context *tls_socket; + struct socket_context *tmp_socket; char *cafile = private_path(conn->sock, conn->lp_ctx, lp_tls_cafile(conn->lp_ctx)); if (!cafile || !*cafile) { @@ -414,9 +415,11 @@ static void ldap_connect_got_sock(struct composite_context *ctx, talloc_free(conn->sock); return; } - talloc_unlink(conn, conn->sock); - conn->sock = tls_socket; - talloc_steal(conn, conn->sock); + + /* the original socket, must become a child of the tls socket */ + tmp_socket = conn->sock; + conn->sock = talloc_steal(conn, tls_socket); + talloc_steal(conn->sock, tmp_socket); } conn->packet = packet_init(conn); -- cgit From 6925202bdee75d191bb5743659c53155ba1605ea Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 24 Sep 2008 15:30:23 +0200 Subject: Move source4/lib/crypto to lib/crypto. --- lib/crypto/arcfour.c | 91 +++++++++ lib/crypto/config.mk | 18 ++ lib/crypto/crc32.c | 103 ++++++++++ lib/crypto/crc32.h | 1 + lib/crypto/crypto.h | 37 ++++ lib/crypto/hmacmd5.c | 117 ++++++++++++ lib/crypto/hmacmd5.h | 38 ++++ lib/crypto/hmacmd5test.c | 98 ++++++++++ lib/crypto/hmacsha256.c | 91 +++++++++ lib/crypto/hmacsha256.h | 38 ++++ lib/crypto/md4.c | 176 +++++++++++++++++ lib/crypto/md4.h | 1 + lib/crypto/md4test.c | 83 ++++++++ lib/crypto/md5.c | 248 ++++++++++++++++++++++++ lib/crypto/md5.h | 19 ++ lib/crypto/md5test.c | 93 +++++++++ lib/crypto/sha256.c | 253 +++++++++++++++++++++++++ lib/crypto/sha256.h | 91 +++++++++ source4/Makefile | 2 +- source4/auth/credentials/credentials_ntlm.c | 2 +- source4/auth/gensec/schannel_sign.c | 2 +- source4/auth/ntlm/ntlm_check.c | 2 +- source4/auth/ntlmssp/ntlmssp_client.c | 2 +- source4/auth/ntlmssp/ntlmssp_server.c | 2 +- source4/auth/ntlmssp/ntlmssp_sign.c | 2 +- source4/dsdb/repl/replicated_objects.c | 2 +- source4/dsdb/samdb/ldb_modules/password_hash.c | 2 +- source4/kdc/hdb-ldb.c | 2 +- source4/lib/crypto/arcfour.c | 91 --------- source4/lib/crypto/config.mk | 18 -- source4/lib/crypto/crc32.c | 103 ---------- source4/lib/crypto/crc32.h | 1 - source4/lib/crypto/crypto.h | 37 ---- source4/lib/crypto/hmacmd5.c | 117 ------------ source4/lib/crypto/hmacmd5.h | 38 ---- source4/lib/crypto/hmacmd5test.c | 98 ---------- source4/lib/crypto/hmacsha256.c | 91 --------- source4/lib/crypto/hmacsha256.h | 38 ---- source4/lib/crypto/md4.c | 176 ----------------- source4/lib/crypto/md4.h | 1 - source4/lib/crypto/md4test.c | 83 -------- source4/lib/crypto/md5.c | 248 ------------------------ source4/lib/crypto/md5.h | 19 -- source4/lib/crypto/md5test.c | 93 --------- source4/lib/crypto/sha256.c | 253 ------------------------- source4/lib/crypto/sha256.h | 91 --------- source4/lib/util/genrand.c | 2 +- source4/libcli/auth/credentials.c | 2 +- source4/libcli/auth/smbencrypt.c | 2 +- source4/libcli/raw/smb_signing.c | 2 +- source4/libcli/smb2/signing.c | 2 +- source4/libnet/libnet_passwd.c | 2 +- source4/main.mk | 2 +- source4/ntp_signd/ntp_signd.c | 2 +- source4/rpc_server/lsa/dcesrv_lsa.c | 2 +- source4/rpc_server/samr/samr_password.c | 2 +- source4/torture/local/local.c | 2 +- source4/torture/rpc/dssync.c | 2 +- source4/torture/rpc/lsa.c | 2 +- source4/torture/rpc/samba3rpc.c | 2 +- source4/torture/rpc/samlogon.c | 2 +- source4/torture/rpc/samr.c | 2 +- source4/torture/rpc/samsync.c | 2 +- source4/torture/rpc/testjoin.c | 2 +- source4/torture/rpc/wkssvc.c | 2 +- 65 files changed, 1625 insertions(+), 1625 deletions(-) create mode 100644 lib/crypto/arcfour.c create mode 100644 lib/crypto/config.mk create mode 100644 lib/crypto/crc32.c create mode 100644 lib/crypto/crc32.h create mode 100644 lib/crypto/crypto.h create mode 100644 lib/crypto/hmacmd5.c create mode 100644 lib/crypto/hmacmd5.h create mode 100644 lib/crypto/hmacmd5test.c create mode 100644 lib/crypto/hmacsha256.c create mode 100644 lib/crypto/hmacsha256.h create mode 100644 lib/crypto/md4.c create mode 100644 lib/crypto/md4.h create mode 100644 lib/crypto/md4test.c create mode 100644 lib/crypto/md5.c create mode 100644 lib/crypto/md5.h create mode 100644 lib/crypto/md5test.c create mode 100644 lib/crypto/sha256.c create mode 100644 lib/crypto/sha256.h delete mode 100644 source4/lib/crypto/arcfour.c delete mode 100644 source4/lib/crypto/config.mk delete mode 100644 source4/lib/crypto/crc32.c delete mode 100644 source4/lib/crypto/crc32.h delete mode 100644 source4/lib/crypto/crypto.h delete mode 100644 source4/lib/crypto/hmacmd5.c delete mode 100644 source4/lib/crypto/hmacmd5.h delete mode 100644 source4/lib/crypto/hmacmd5test.c delete mode 100644 source4/lib/crypto/hmacsha256.c delete mode 100644 source4/lib/crypto/hmacsha256.h delete mode 100644 source4/lib/crypto/md4.c delete mode 100644 source4/lib/crypto/md4.h delete mode 100644 source4/lib/crypto/md4test.c delete mode 100644 source4/lib/crypto/md5.c delete mode 100644 source4/lib/crypto/md5.h delete mode 100644 source4/lib/crypto/md5test.c delete mode 100644 source4/lib/crypto/sha256.c delete mode 100644 source4/lib/crypto/sha256.h diff --git a/lib/crypto/arcfour.c b/lib/crypto/arcfour.c new file mode 100644 index 0000000000..94196fa1ee --- /dev/null +++ b/lib/crypto/arcfour.c @@ -0,0 +1,91 @@ +/* + Unix SMB/CIFS implementation. + + An implementation of the arcfour algorithm + + 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 . +*/ + +#include "includes.h" +#include "lib/crypto/crypto.h" + +/* initialise the arcfour sbox with key */ +_PUBLIC_ void arcfour_init(struct arcfour_state *state, const DATA_BLOB *key) +{ + int ind; + uint8_t j = 0; + for (ind = 0; ind < sizeof(state->sbox); ind++) { + state->sbox[ind] = (uint8_t)ind; + } + + for (ind = 0; ind < sizeof(state->sbox); ind++) { + uint8_t tc; + + j += (state->sbox[ind] + key->data[ind%key->length]); + + tc = state->sbox[ind]; + state->sbox[ind] = state->sbox[j]; + state->sbox[j] = tc; + } + state->index_i = 0; + state->index_j = 0; +} + +/* crypt the data with arcfour */ +_PUBLIC_ void arcfour_crypt_sbox(struct arcfour_state *state, uint8_t *data, int len) +{ + int ind; + + for (ind = 0; ind < len; ind++) { + uint8_t tc; + uint8_t t; + + state->index_i++; + state->index_j += state->sbox[state->index_i]; + + tc = state->sbox[state->index_i]; + state->sbox[state->index_i] = state->sbox[state->index_j]; + state->sbox[state->index_j] = tc; + + t = state->sbox[state->index_i] + state->sbox[state->index_j]; + data[ind] = data[ind] ^ state->sbox[t]; + } +} + +/* + arcfour encryption with a blob key +*/ +_PUBLIC_ void arcfour_crypt_blob(uint8_t *data, int len, const DATA_BLOB *key) +{ + struct arcfour_state state; + arcfour_init(&state, key); + arcfour_crypt_sbox(&state, data, len); +} + +/* + a variant that assumes a 16 byte key. This should be removed + when the last user is gone +*/ +_PUBLIC_ void arcfour_crypt(uint8_t *data, const uint8_t keystr[16], int len) +{ + DATA_BLOB key = data_blob(keystr, 16); + + arcfour_crypt_blob(data, len, &key); + + data_blob_free(&key); +} + + diff --git a/lib/crypto/config.mk b/lib/crypto/config.mk new file mode 100644 index 0000000000..ee111bd088 --- /dev/null +++ b/lib/crypto/config.mk @@ -0,0 +1,18 @@ +############################## +# Start SUBSYSTEM LIBCRYPTO +[SUBSYSTEM::LIBCRYPTO] +# End SUBSYSTEM LIBCRYPTO +############################## + +LIBCRYPTO_OBJ_FILES = $(addprefix $(libcryptosrcdir)/, \ + crc32.o md5.o hmacmd5.o md4.o \ + arcfour.o sha256.o hmacsha256.o) + +[MODULE::TORTURE_LIBCRYPTO] +SUBSYSTEM = smbtorture +PRIVATE_DEPENDENCIES = LIBCRYPTO + +TORTURE_LIBCRYPTO_OBJ_FILES = $(addprefix $(libcryptosrcdir)/, \ + md4test.o md5test.o hmacmd5test.o) + +$(eval $(call proto_header_template,$(libcryptosrcdir)/test_proto.h,$(TORTURE_LIBCRYPTO_OBJ_FILES:.o=.c))) diff --git a/lib/crypto/crc32.c b/lib/crypto/crc32.c new file mode 100644 index 0000000000..5b9d9b108d --- /dev/null +++ b/lib/crypto/crc32.c @@ -0,0 +1,103 @@ +/*- + * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or + * code or tables extracted from it, as desired without restriction. + * + * First, the polynomial itself and its table of feedback terms. The + * polynomial is + * X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0 + * + * Note that we take it "backwards" and put the highest-order term in + * the lowest-order bit. The X^32 term is "implied"; the LSB is the + * X^31 term, etc. The X^0 term (usually shown as "+1") results in + * the MSB being 1 + * + * Note that the usual hardware shift register implementation, which + * is what we're using (we're merely optimizing it by doing eight-bit + * chunks at a time) shifts bits into the lowest-order term. In our + * implementation, that means shifting towards the right. Why do we + * do it this way? Because the calculated CRC must be transmitted in + * order from highest-order term to lowest-order term. UARTs transmit + * characters in order from LSB to MSB. By storing the CRC this way + * we hand it to the UART in the order low-byte to high-byte; the UART + * sends each low-bit to hight-bit; and the result is transmission bit + * by bit from highest- to lowest-order term without requiring any bit + * shuffling on our part. Reception works similarly + * + * The feedback terms table consists of 256, 32-bit entries. Notes + * + * The table can be generated at runtime if desired; code to do so + * is shown later. It might not be obvious, but the feedback + * terms simply represent the results of eight shift/xor opera + * tions for all combinations of data and CRC register values + * + * The values must be right-shifted by eight bits by the "updcrc + * logic; the shift must be unsigned (bring in zeroes). On some + * hardware you could probably optimize the shift in assembler by + * using byte-swap instructions + * polynomial $edb88320 + * + * + * CRC32 code derived from work by Gary S. Brown. + */ + +#include "includes.h" + +static const uint32_t crc32_tab[] = { + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, + 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, + 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, + 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, + 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, + 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, + 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, + 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, + 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, + 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, + 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, + 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, + 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, + 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, + 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, + 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, + 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, + 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, + 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, + 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, + 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, + 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, + 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, + 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, + 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, + 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, + 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, + 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, + 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, + 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, + 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, + 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, + 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, + 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, + 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d +}; + +uint32_t crc32_calc_buffer(const uint8_t *buf, size_t size) +{ + const uint8_t *p; + uint32_t crc; + + p = buf; + crc = ~0U; + + while (size--) + crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8); + + return crc ^ ~0U; +} diff --git a/lib/crypto/crc32.h b/lib/crypto/crc32.h new file mode 100644 index 0000000000..7854abf865 --- /dev/null +++ b/lib/crypto/crc32.h @@ -0,0 +1 @@ +uint32_t crc32_calc_buffer(const uint8_t *buf, size_t size); diff --git a/lib/crypto/crypto.h b/lib/crypto/crypto.h new file mode 100644 index 0000000000..9cb16ad344 --- /dev/null +++ b/lib/crypto/crypto.h @@ -0,0 +1,37 @@ +/* + Unix SMB/CIFS implementation. + + Copyright (C) Andrew Tridgell 2004 + + 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 . +*/ + +#include "../lib/crypto/crc32.h" +#include "../lib/crypto/md4.h" +#include "../lib/crypto/md5.h" +#include "../lib/crypto/hmacmd5.h" +#include "../lib/crypto/sha256.h" +#include "../lib/crypto/hmacsha256.h" + +struct arcfour_state { + uint8_t sbox[256]; + uint8_t index_i; + uint8_t index_j; +}; + +void arcfour_init(struct arcfour_state *state, const DATA_BLOB *key); +void arcfour_crypt_sbox(struct arcfour_state *state, uint8_t *data, int len); +void arcfour_crypt_blob(uint8_t *data, int len, const DATA_BLOB *key); +void arcfour_crypt(uint8_t *data, const uint8_t keystr[16], int len); + diff --git a/lib/crypto/hmacmd5.c b/lib/crypto/hmacmd5.c new file mode 100644 index 0000000000..3a9ec38a27 --- /dev/null +++ b/lib/crypto/hmacmd5.c @@ -0,0 +1,117 @@ +/* + Unix SMB/CIFS implementation. + HMAC MD5 code for use in NTLMv2 + Copyright (C) Luke Kenneth Casson Leighton 1996-2000 + Copyright (C) Andrew Tridgell 1992-2000 + + 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 . +*/ + +/* taken direct from rfc2104 implementation and modified for suitable use + * for ntlmv2. + */ + +#include "includes.h" +#include "lib/crypto/crypto.h" + +/*********************************************************************** + the rfc 2104 version of hmac_md5 initialisation. +***********************************************************************/ +_PUBLIC_ void hmac_md5_init_rfc2104(const uint8_t *key, int key_len, HMACMD5Context *ctx) +{ + int i; + uint8_t tk[16]; + + /* if key is longer than 64 bytes reset it to key=MD5(key) */ + if (key_len > 64) + { + struct MD5Context tctx; + + MD5Init(&tctx); + MD5Update(&tctx, key, key_len); + MD5Final(tk, &tctx); + + key = tk; + key_len = 16; + } + + /* start out by storing key in pads */ + ZERO_STRUCT(ctx->k_ipad); + ZERO_STRUCT(ctx->k_opad); + memcpy( ctx->k_ipad, key, key_len); + memcpy( ctx->k_opad, key, key_len); + + /* XOR key with ipad and opad values */ + for (i=0; i<64; i++) + { + ctx->k_ipad[i] ^= 0x36; + ctx->k_opad[i] ^= 0x5c; + } + + MD5Init(&ctx->ctx); + MD5Update(&ctx->ctx, ctx->k_ipad, 64); +} + +/*********************************************************************** + the microsoft version of hmac_md5 initialisation. +***********************************************************************/ +_PUBLIC_ void hmac_md5_init_limK_to_64(const uint8_t *key, int key_len, + HMACMD5Context *ctx) +{ + /* if key is longer than 64 bytes truncate it */ + if (key_len > 64) + { + key_len = 64; + } + + hmac_md5_init_rfc2104(key, key_len, ctx); +} + +/*********************************************************************** + update hmac_md5 "inner" buffer +***********************************************************************/ +_PUBLIC_ void hmac_md5_update(const uint8_t *text, int text_len, HMACMD5Context *ctx) +{ + MD5Update(&ctx->ctx, text, text_len); /* then text of datagram */ +} + +/*********************************************************************** + finish off hmac_md5 "inner" buffer and generate outer one. +***********************************************************************/ +_PUBLIC_ void hmac_md5_final(uint8_t *digest, HMACMD5Context *ctx) +{ + struct MD5Context ctx_o; + + MD5Final(digest, &ctx->ctx); + + MD5Init(&ctx_o); + MD5Update(&ctx_o, ctx->k_opad, 64); + MD5Update(&ctx_o, digest, 16); + MD5Final(digest, &ctx_o); +} + +/*********************************************************** + single function to calculate an HMAC MD5 digest from data. + use the microsoft hmacmd5 init method because the key is 16 bytes. +************************************************************/ +_PUBLIC_ void hmac_md5(const uint8_t key[16], const uint8_t *data, int data_len, uint8_t *digest) +{ + HMACMD5Context ctx; + hmac_md5_init_limK_to_64(key, 16, &ctx); + if (data_len != 0) + { + hmac_md5_update(data, data_len, &ctx); + } + hmac_md5_final(digest, &ctx); +} diff --git a/lib/crypto/hmacmd5.h b/lib/crypto/hmacmd5.h new file mode 100644 index 0000000000..5769737fcd --- /dev/null +++ b/lib/crypto/hmacmd5.h @@ -0,0 +1,38 @@ +/* + Unix SMB/CIFS implementation. + Interface header: HMAC MD5 code + Copyright (C) Luke Kenneth Casson Leighton 1996-1999 + Copyright (C) Andrew Tridgell 1992-1999 + + 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 . +*/ + +#ifndef _HMAC_MD5_H + +typedef struct +{ + struct MD5Context ctx; + uint8_t k_ipad[65]; + uint8_t k_opad[65]; + +} HMACMD5Context; + +void hmac_md5_init_limK_to_64(const uint8_t *key, int key_len, + HMACMD5Context *ctx); +void hmac_md5_update(const uint8_t *text, int text_len, HMACMD5Context *ctx); +void hmac_md5_final(uint8_t *digest, HMACMD5Context *ctx); +void hmac_md5(const uint8_t key[16], const uint8_t *data, int data_len, uint8_t *digest); +void hmac_md5_init_rfc2104(const uint8_t *key, int key_len, HMACMD5Context *ctx); + +#endif /* _HMAC_MD5_H */ diff --git a/lib/crypto/hmacmd5test.c b/lib/crypto/hmacmd5test.c new file mode 100644 index 0000000000..07ed54c98d --- /dev/null +++ b/lib/crypto/hmacmd5test.c @@ -0,0 +1,98 @@ +/* + Unix SMB/CIFS implementation. + HMAC MD5 tests + Copyright (C) Stefan Metzmacher 2006 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +#include "includes.h" +#include "lib/crypto/crypto.h" + +struct torture_context; + +static DATA_BLOB data_blob_repeat_byte(uint8_t byte, size_t length) +{ + DATA_BLOB b = data_blob(NULL, length); + memset(b.data, byte, length); + return b; +} + +/* + This uses the test values from rfc 2104, 2202 +*/ +bool torture_local_crypto_hmacmd5(struct torture_context *torture) +{ + bool ret = true; + uint32_t i; + struct { + DATA_BLOB key; + DATA_BLOB data; + DATA_BLOB md5; + } testarray[8]; + + testarray[0].key = data_blob_repeat_byte(0x0b, 16); + testarray[0].data = data_blob_string_const("Hi There"); + testarray[0].md5 = strhex_to_data_blob("9294727a3638bb1c13f48ef8158bfc9d"); + + testarray[1].key = data_blob_string_const("Jefe"); + testarray[1].data = data_blob_string_const("what do ya want for nothing?"); + testarray[1].md5 = strhex_to_data_blob("750c783e6ab0b503eaa86e310a5db738"); + + testarray[2].key = data_blob_repeat_byte(0xaa, 16); + testarray[2].data = data_blob_repeat_byte(0xdd, 50); + testarray[2].md5 = strhex_to_data_blob("56be34521d144c88dbb8c733f0e8b3f6"); + + testarray[3].key = strhex_to_data_blob("0102030405060708090a0b0c0d0e0f10111213141516171819"); + testarray[3].data = data_blob_repeat_byte(0xcd, 50); + testarray[3].md5 = strhex_to_data_blob("697eaf0aca3a3aea3a75164746ffaa79"); + + testarray[4].key = data_blob_repeat_byte(0x0c, 16); + testarray[4].data = data_blob_string_const("Test With Truncation"); + testarray[4].md5 = strhex_to_data_blob("56461ef2342edc00f9bab995690efd4c"); + + testarray[5].key = data_blob_repeat_byte(0xaa, 80); + testarray[5].data = data_blob_string_const("Test Using Larger Than Block-Size Key - Hash Key First"); + testarray[5].md5 = strhex_to_data_blob("6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd"); + + testarray[6].key = data_blob_repeat_byte(0xaa, 80); + testarray[6].data = data_blob_string_const("Test Using Larger Than Block-Size Key " + "and Larger Than One Block-Size Data"); + testarray[6].md5 = strhex_to_data_blob("6f630fad67cda0ee1fb1f562db3aa53e"); + + testarray[7].key = data_blob(NULL, 0); + + for (i=0; testarray[i].key.data; i++) { + HMACMD5Context ctx; + uint8_t md5[16]; + int e; + + hmac_md5_init_rfc2104(testarray[i].key.data, testarray[i].key.length, &ctx); + hmac_md5_update(testarray[i].data.data, testarray[i].data.length, &ctx); + hmac_md5_final(md5, &ctx); + + e = memcmp(testarray[i].md5.data, + md5, + MIN(testarray[i].md5.length, sizeof(md5))); + if (e != 0) { + printf("hmacmd5 test[%u]: failed\n", i); + dump_data(0, testarray[i].key.data, testarray[i].key.length); + dump_data(0, testarray[i].data.data, testarray[i].data.length); + dump_data(0, testarray[i].md5.data, testarray[i].md5.length); + dump_data(0, md5, sizeof(md5)); + ret = false; + } + } + + return ret; +} diff --git a/lib/crypto/hmacsha256.c b/lib/crypto/hmacsha256.c new file mode 100644 index 0000000000..6b0af9ee83 --- /dev/null +++ b/lib/crypto/hmacsha256.c @@ -0,0 +1,91 @@ +/* + Unix SMB/CIFS implementation. + + Interface header: HMAC SHA-256 code + + Copyright (C) Andrew Tridgell 2008 + + based in hmacsha1.c which is: + Copyright (C) Stefan Metzmacher + + 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 . +*/ + +/* + taken direct from rfc2202 implementation and modified for suitable use + */ + +#include "includes.h" +#include "lib/crypto/crypto.h" + +/*********************************************************************** + the rfc 2104/2202 version of hmac_sha256 initialisation. +***********************************************************************/ +_PUBLIC_ void hmac_sha256_init(const uint8_t *key, size_t key_len, struct HMACSHA256Context *ctx) +{ + int i; + uint8_t tk[SHA256_DIGEST_LENGTH]; + + /* if key is longer than 64 bytes reset it to key=HASH(key) */ + if (key_len > 64) + { + SHA256_CTX tctx; + + SHA256_Init(&tctx); + SHA256_Update(&tctx, key, key_len); + SHA256_Final(tk, &tctx); + + key = tk; + key_len = SHA256_DIGEST_LENGTH; + } + + /* start out by storing key in pads */ + ZERO_STRUCT(ctx->k_ipad); + ZERO_STRUCT(ctx->k_opad); + memcpy( ctx->k_ipad, key, key_len); + memcpy( ctx->k_opad, key, key_len); + + /* XOR key with ipad and opad values */ + for (i=0; i<64; i++) + { + ctx->k_ipad[i] ^= 0x36; + ctx->k_opad[i] ^= 0x5c; + } + + SHA256_Init(&ctx->ctx); + SHA256_Update(&ctx->ctx, ctx->k_ipad, 64); +} + +/*********************************************************************** + update hmac_sha256 "inner" buffer +***********************************************************************/ +_PUBLIC_ void hmac_sha256_update(const uint8_t *data, size_t data_len, struct HMACSHA256Context *ctx) +{ + SHA256_Update(&ctx->ctx, data, data_len); /* then text of datagram */ +} + +/*********************************************************************** + finish off hmac_sha256 "inner" buffer and generate outer one. +***********************************************************************/ +_PUBLIC_ void hmac_sha256_final(uint8_t digest[SHA256_DIGEST_LENGTH], struct HMACSHA256Context *ctx) +{ + SHA256_CTX ctx_o; + + SHA256_Final(digest, &ctx->ctx); + + SHA256_Init(&ctx_o); + SHA256_Update(&ctx_o, ctx->k_opad, 64); + SHA256_Update(&ctx_o, digest, SHA256_DIGEST_LENGTH); + SHA256_Final(digest, &ctx_o); +} diff --git a/lib/crypto/hmacsha256.h b/lib/crypto/hmacsha256.h new file mode 100644 index 0000000000..8960c636c1 --- /dev/null +++ b/lib/crypto/hmacsha256.h @@ -0,0 +1,38 @@ +/* + Unix SMB/CIFS implementation. + + Interface header: HMAC SHA256 code + + Copyright (C) Andrew Tridgell 2008 + + based on hmacsha1.h which is: + + Copyright (C) Stefan Metzmacher 2006 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef _HMAC_SHA256_H + +struct HMACSHA256Context { + SHA256_CTX ctx; + uint8_t k_ipad[65]; + uint8_t k_opad[65]; +}; + +void hmac_sha256_init(const uint8_t *key, size_t key_len, struct HMACSHA256Context *ctx); +void hmac_sha256_update(const uint8_t *data, size_t data_len, struct HMACSHA256Context *ctx); +void hmac_sha256_final(uint8_t digest[20], struct HMACSHA256Context *ctx); + +#endif /* _HMAC_SHA256_H */ diff --git a/lib/crypto/md4.c b/lib/crypto/md4.c new file mode 100644 index 0000000000..7ad93ce786 --- /dev/null +++ b/lib/crypto/md4.c @@ -0,0 +1,176 @@ +/* + Unix SMB/CIFS implementation. + a implementation of MD4 designed for use in the SMB authentication protocol + Copyright (C) Andrew Tridgell 1997-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 . +*/ + +#include "includes.h" + +/* NOTE: This code makes no attempt to be fast! + + It assumes that a int is at least 32 bits long +*/ + +struct mdfour_state { + uint32_t A, B, C, D; +}; + +static uint32_t F(uint32_t X, uint32_t Y, uint32_t Z) +{ + return (X&Y) | ((~X)&Z); +} + +static uint32_t G(uint32_t X, uint32_t Y, uint32_t Z) +{ + return (X&Y) | (X&Z) | (Y&Z); +} + +static uint32_t H(uint32_t X, uint32_t Y, uint32_t Z) +{ + return X^Y^Z; +} + +static uint32_t lshift(uint32_t x, int s) +{ + x &= 0xFFFFFFFF; + return ((x<>(32-s)); +} + +#define ROUND1(a,b,c,d,k,s) a = lshift(a + F(b,c,d) + X[k], s) +#define ROUND2(a,b,c,d,k,s) a = lshift(a + G(b,c,d) + X[k] + (uint32_t)0x5A827999,s) +#define ROUND3(a,b,c,d,k,s) a = lshift(a + H(b,c,d) + X[k] + (uint32_t)0x6ED9EBA1,s) + +/* this applies md4 to 64 byte chunks */ +static void mdfour64(struct mdfour_state *s, uint32_t *M) +{ + int j; + uint32_t AA, BB, CC, DD; + uint32_t X[16]; + + for (j=0;j<16;j++) + X[j] = M[j]; + + AA = s->A; BB = s->B; CC = s->C; DD = s->D; + + ROUND1(s->A,s->B,s->C,s->D, 0, 3); ROUND1(s->D,s->A,s->B,s->C, 1, 7); + ROUND1(s->C,s->D,s->A,s->B, 2, 11); ROUND1(s->B,s->C,s->D,s->A, 3, 19); + ROUND1(s->A,s->B,s->C,s->D, 4, 3); ROUND1(s->D,s->A,s->B,s->C, 5, 7); + ROUND1(s->C,s->D,s->A,s->B, 6, 11); ROUND1(s->B,s->C,s->D,s->A, 7, 19); + ROUND1(s->A,s->B,s->C,s->D, 8, 3); ROUND1(s->D,s->A,s->B,s->C, 9, 7); + ROUND1(s->C,s->D,s->A,s->B, 10, 11); ROUND1(s->B,s->C,s->D,s->A, 11, 19); + ROUND1(s->A,s->B,s->C,s->D, 12, 3); ROUND1(s->D,s->A,s->B,s->C, 13, 7); + ROUND1(s->C,s->D,s->A,s->B, 14, 11); ROUND1(s->B,s->C,s->D,s->A, 15, 19); + + ROUND2(s->A,s->B,s->C,s->D, 0, 3); ROUND2(s->D,s->A,s->B,s->C, 4, 5); + ROUND2(s->C,s->D,s->A,s->B, 8, 9); ROUND2(s->B,s->C,s->D,s->A, 12, 13); + ROUND2(s->A,s->B,s->C,s->D, 1, 3); ROUND2(s->D,s->A,s->B,s->C, 5, 5); + ROUND2(s->C,s->D,s->A,s->B, 9, 9); ROUND2(s->B,s->C,s->D,s->A, 13, 13); + ROUND2(s->A,s->B,s->C,s->D, 2, 3); ROUND2(s->D,s->A,s->B,s->C, 6, 5); + ROUND2(s->C,s->D,s->A,s->B, 10, 9); ROUND2(s->B,s->C,s->D,s->A, 14, 13); + ROUND2(s->A,s->B,s->C,s->D, 3, 3); ROUND2(s->D,s->A,s->B,s->C, 7, 5); + ROUND2(s->C,s->D,s->A,s->B, 11, 9); ROUND2(s->B,s->C,s->D,s->A, 15, 13); + + ROUND3(s->A,s->B,s->C,s->D, 0, 3); ROUND3(s->D,s->A,s->B,s->C, 8, 9); + ROUND3(s->C,s->D,s->A,s->B, 4, 11); ROUND3(s->B,s->C,s->D,s->A, 12, 15); + ROUND3(s->A,s->B,s->C,s->D, 2, 3); ROUND3(s->D,s->A,s->B,s->C, 10, 9); + ROUND3(s->C,s->D,s->A,s->B, 6, 11); ROUND3(s->B,s->C,s->D,s->A, 14, 15); + ROUND3(s->A,s->B,s->C,s->D, 1, 3); ROUND3(s->D,s->A,s->B,s->C, 9, 9); + ROUND3(s->C,s->D,s->A,s->B, 5, 11); ROUND3(s->B,s->C,s->D,s->A, 13, 15); + ROUND3(s->A,s->B,s->C,s->D, 3, 3); ROUND3(s->D,s->A,s->B,s->C, 11, 9); + ROUND3(s->C,s->D,s->A,s->B, 7, 11); ROUND3(s->B,s->C,s->D,s->A, 15, 15); + + s->A += AA; + s->B += BB; + s->C += CC; + s->D += DD; + + s->A &= 0xFFFFFFFF; + s->B &= 0xFFFFFFFF; + s->C &= 0xFFFFFFFF; + s->D &= 0xFFFFFFFF; + + for (j=0;j<16;j++) + X[j] = 0; +} + +static void copy64(uint32_t *M, const uint8_t *in) +{ + int i; + + for (i=0;i<16;i++) + M[i] = (in[i*4+3]<<24) | (in[i*4+2]<<16) | + (in[i*4+1]<<8) | (in[i*4+0]<<0); +} + +static void copy4(uint8_t *out, uint32_t x) +{ + out[0] = x&0xFF; + out[1] = (x>>8)&0xFF; + out[2] = (x>>16)&0xFF; + out[3] = (x>>24)&0xFF; +} + +/** + * produce a md4 message digest from data of length n bytes + */ +_PUBLIC_ void mdfour(uint8_t *out, const uint8_t *in, int n) +{ + uint8_t buf[128]; + uint32_t M[16]; + uint32_t b = n * 8; + int i; + struct mdfour_state state; + + state.A = 0x67452301; + state.B = 0xefcdab89; + state.C = 0x98badcfe; + state.D = 0x10325476; + + while (n > 64) { + copy64(M, in); + mdfour64(&state, M); + in += 64; + n -= 64; + } + + for (i=0;i<128;i++) + buf[i] = 0; + memcpy(buf, in, n); + buf[n] = 0x80; + + if (n <= 55) { + copy4(buf+56, b); + copy64(M, buf); + mdfour64(&state, M); + } else { + copy4(buf+120, b); + copy64(M, buf); + mdfour64(&state, M); + copy64(M, buf+64); + mdfour64(&state, M); + } + + for (i=0;i<128;i++) + buf[i] = 0; + copy64(M, buf); + + copy4(out, state.A); + copy4(out+4, state.B); + copy4(out+8, state.C); + copy4(out+12, state.D); +} + + diff --git a/lib/crypto/md4.h b/lib/crypto/md4.h new file mode 100644 index 0000000000..234e488e4f --- /dev/null +++ b/lib/crypto/md4.h @@ -0,0 +1 @@ +void mdfour(uint8_t *out, const uint8_t *in, int n); diff --git a/lib/crypto/md4test.c b/lib/crypto/md4test.c new file mode 100644 index 0000000000..5e0451973c --- /dev/null +++ b/lib/crypto/md4test.c @@ -0,0 +1,83 @@ +/* + Unix SMB/CIFS implementation. + MD4 tests + Copyright (C) Stefan Metzmacher 2006 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "includes.h" +#include "lib/crypto/crypto.h" + +struct torture_context; + +/* + This uses the test values from rfc1320 +*/ +bool torture_local_crypto_md4(struct torture_context *torture) +{ + bool ret = true; + uint32_t i; + struct { + const char *data; + const char *md4; + } testarray[] = { + { + .data = "", + .md4 = "31d6cfe0d16ae931b73c59d7e0c089c0" + },{ + .data = "a", + .md4 = "bde52cb31de33e46245e05fbdbd6fb24" + },{ + .data = "abc", + .md4 = "a448017aaf21d8525fc10ae87aa6729d" + },{ + .data = "message digest", + .md4 = "d9130a8164549fe818874806e1c7014b" + },{ + .data = "abcdefghijklmnopqrstuvwxyz", + .md4 = "d79e1c308aa5bbcdeea8ed63df412da9" + },{ + .data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", + .md4 = "043f8582f241db351ce627e153e7f0e4" + },{ + .data = "12345678901234567890123456789012345678901234567890123456789012345678901234567890", + .md4 = "e33b4ddc9c38f2199c3e7b164fcc0536" + } + }; + + for (i=0; i < ARRAY_SIZE(testarray); i++) { + uint8_t md4[16]; + int e; + DATA_BLOB data; + DATA_BLOB md4blob; + + data = data_blob_string_const(testarray[i].data); + md4blob = strhex_to_data_blob(testarray[i].md4); + + mdfour(md4, data.data, data.length); + + e = memcmp(md4blob.data, md4, MIN(md4blob.length, sizeof(md4))); + if (e != 0) { + printf("md4 test[%u]: failed\n", i); + dump_data(0, data.data, data.length); + dump_data(0, md4blob.data, md4blob.length); + dump_data(0, md4, sizeof(md4)); + ret = false; + } + talloc_free(md4blob.data); + } + + return ret; +} diff --git a/lib/crypto/md5.c b/lib/crypto/md5.c new file mode 100644 index 0000000000..584c46ef2d --- /dev/null +++ b/lib/crypto/md5.c @@ -0,0 +1,248 @@ +/* + * This code implements the MD5 message-digest algorithm. + * The algorithm is due to Ron Rivest. This code was + * written by Colin Plumb in 1993, no copyright is claimed. + * This code is in the public domain; do with it what you wish. + * + * Equivalent code is available from RSA Data Security, Inc. + * This code has been tested against that, and is equivalent, + * except that you don't need to include two pages of legalese + * with every copy. + * + * To compute the message digest of a chunk of bytes, declare an + * MD5Context structure, pass it to MD5Init, call MD5Update as + * needed on buffers full of bytes, and then call MD5Final, which + * will fill a supplied 16-byte array with the digest. + */ + +/* This code slightly modified to fit into Samba by + abartlet@samba.org Jun 2001 */ + +#include "includes.h" + +#include "md5.h" + + +static void MD5Transform(uint32_t buf[4], uint32_t const in[16]); + +/* + * Note: this code is harmless on little-endian machines. + */ +static void byteReverse(uint8_t *buf, uint_t longs) +{ + uint32_t t; + do { + t = (uint32_t) ((uint_t) buf[3] << 8 | buf[2]) << 16 | + ((uint_t) buf[1] << 8 | buf[0]); + *(uint32_t *) buf = t; + buf += 4; + } while (--longs); +} + +/* + * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious + * initialization constants. + */ +_PUBLIC_ void MD5Init(struct MD5Context *ctx) +{ + ctx->buf[0] = 0x67452301; + ctx->buf[1] = 0xefcdab89; + ctx->buf[2] = 0x98badcfe; + ctx->buf[3] = 0x10325476; + + ctx->bits[0] = 0; + ctx->bits[1] = 0; +} + +/* + * Update context to reflect the concatenation of another buffer full + * of bytes. + */ +_PUBLIC_ void MD5Update(struct MD5Context *ctx, const uint8_t *buf, size_t len) +{ + register uint32_t t; + + /* Update bitcount */ + + t = ctx->bits[0]; + if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) + ctx->bits[1]++; /* Carry from low to high */ + ctx->bits[1] += len >> 29; + + t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ + + /* Handle any leading odd-sized chunks */ + + if (t) { + uint8_t *p = (uint8_t *) ctx->in + t; + + t = 64 - t; + if (len < t) { + memmove(p, buf, len); + return; + } + memmove(p, buf, t); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32_t *) ctx->in); + buf += t; + len -= t; + } + /* Process data in 64-byte chunks */ + + while (len >= 64) { + memmove(ctx->in, buf, 64); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32_t *) ctx->in); + buf += 64; + len -= 64; + } + + /* Handle any remaining bytes of data. */ + + memmove(ctx->in, buf, len); +} + +/* + * Final wrapup - pad to 64-byte boundary with the bit pattern + * 1 0* (64-bit count of bits processed, MSB-first) + */ +_PUBLIC_ void MD5Final(uint8_t digest[16], struct MD5Context *ctx) +{ + uint_t count; + uint8_t *p; + + /* Compute number of bytes mod 64 */ + count = (ctx->bits[0] >> 3) & 0x3F; + + /* Set the first char of padding to 0x80. This is safe since there is + always at least one byte free */ + p = ctx->in + count; + *p++ = 0x80; + + /* Bytes of padding needed to make 64 bytes */ + count = 64 - 1 - count; + + /* Pad out to 56 mod 64 */ + if (count < 8) { + /* Two lots of padding: Pad the first block to 64 bytes */ + memset(p, 0, count); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32_t *) ctx->in); + + /* Now fill the next block with 56 bytes */ + memset(ctx->in, 0, 56); + } else { + /* Pad block to 56 bytes */ + memset(p, 0, count - 8); + } + byteReverse(ctx->in, 14); + + /* Append length in bits and transform */ + ((uint32_t *) ctx->in)[14] = ctx->bits[0]; + ((uint32_t *) ctx->in)[15] = ctx->bits[1]; + + MD5Transform(ctx->buf, (uint32_t *) ctx->in); + byteReverse((uint8_t *) ctx->buf, 4); + memmove(digest, ctx->buf, 16); + memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */ +} + +/* The four core functions - F1 is optimized somewhat */ + +/* #define F1(x, y, z) (x & y | ~x & z) */ +#define F1(x, y, z) (z ^ (x & (y ^ z))) +#define F2(x, y, z) F1(z, x, y) +#define F3(x, y, z) (x ^ y ^ z) +#define F4(x, y, z) (y ^ (x | ~z)) + +/* This is the central step in the MD5 algorithm. */ +#define MD5STEP(f, w, x, y, z, data, s) \ + ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) + +/* + * The core of the MD5 algorithm, this alters an existing MD5 hash to + * reflect the addition of 16 longwords of new data. MD5Update blocks + * the data and converts bytes into longwords for this routine. + */ +static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) +{ + register uint32_t a, b, c, d; + + a = buf[0]; + b = buf[1]; + c = buf[2]; + d = buf[3]; + + MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); + MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); + MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); + MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); + MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); + MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); + MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); + MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); + MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); + MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); + MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); + MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); + MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); + MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); + MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); + MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); + + MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); + MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); + MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); + MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); + MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); + MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); + MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); + MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); + MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); + MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); + MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); + MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); + MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); + MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); + MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); + MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); + + MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); + MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); + MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); + MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); + MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); + MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); + MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); + MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); + MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); + MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); + MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); + MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); + MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); + MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); + MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); + MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); + + MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); + MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); + MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); + MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); + MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); + MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); + MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); + MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); + MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); + MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); + MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); + MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); + MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); + MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); + MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); + MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); + + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; +} diff --git a/lib/crypto/md5.h b/lib/crypto/md5.h new file mode 100644 index 0000000000..4064d6f003 --- /dev/null +++ b/lib/crypto/md5.h @@ -0,0 +1,19 @@ +#ifndef MD5_H +#define MD5_H +#ifndef HEADER_MD5_H +/* Try to avoid clashes with OpenSSL */ +#define HEADER_MD5_H +#endif + +struct MD5Context { + uint32_t buf[4]; + uint32_t bits[2]; + uint8_t in[64]; +}; + +void MD5Init(struct MD5Context *context); +void MD5Update(struct MD5Context *context, const uint8_t *buf, + size_t len); +void MD5Final(uint8_t digest[16], struct MD5Context *context); + +#endif /* !MD5_H */ diff --git a/lib/crypto/md5test.c b/lib/crypto/md5test.c new file mode 100644 index 0000000000..702e0fcf41 --- /dev/null +++ b/lib/crypto/md5test.c @@ -0,0 +1,93 @@ +/* + Unix SMB/CIFS implementation. + MD5 tests + Copyright (C) Stefan Metzmacher + + 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 . +*/ + +#include "includes.h" +#include "lib/crypto/crypto.h" + +struct torture_context; + +/* + This uses the test values from rfc1321 +*/ +bool torture_local_crypto_md5(struct torture_context *torture) +{ + bool ret = true; + uint32_t i; + struct { + const char *data; + const char *md5; + } testarray[] = { + { + .data = "", + .md5 = "d41d8cd98f00b204e9800998ecf8427e" + },{ + .data = "a", + .md5 = "0cc175b9c0f1b6a831c399e269772661" + },{ + .data = "abc", + .md5 = "900150983cd24fb0d6963f7d28e17f72" + },{ + .data = "message digest", + .md5 = "f96b697d7cb7938d525a2f31aaf161d0" + },{ + .data = "abcdefghijklmnopqrstuvwxyz", + .md5 = "c3fcd3d76192e4007dfb496cca67e13b" + },{ + .data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789", + .md5 = "d174ab98d277d9f5a5611c2c9f419d9f" + },{ + .data = "123456789012345678901234567890" + "123456789012345678901234567890" + "12345678901234567890", + .md5 = "57edf4a22be3c955ac49da2e2107b67a" + } + }; + + for (i=0; i < ARRAY_SIZE(testarray); i++) { + struct MD5Context ctx; + uint8_t md5[16]; + int e; + + DATA_BLOB data; + DATA_BLOB md5blob; + + data = data_blob_string_const(testarray[i].data); + md5blob = strhex_to_data_blob(testarray[i].md5); + + MD5Init(&ctx); + MD5Update(&ctx, data.data, data.length); + MD5Final(md5, &ctx); + + e = memcmp(md5blob.data, + md5, + MIN(md5blob.length, sizeof(md5))); + if (e != 0) { + printf("md5 test[%u]: failed\n", i); + dump_data(0, data.data, data.length); + dump_data(0, md5blob.data, md5blob.length); + dump_data(0, md5, sizeof(md5)); + ret = false; + } + talloc_free(md5blob.data); + } + + return ret; +} diff --git a/lib/crypto/sha256.c b/lib/crypto/sha256.c new file mode 100644 index 0000000000..a2def25814 --- /dev/null +++ b/lib/crypto/sha256.c @@ -0,0 +1,253 @@ +/* + based on heildal lib/hcrypto/sha256.c. Copied to lib/crypto to avoid a link + problem. Hopefully will be removed once we solve this link problem + + (tridge) + */ + +/* + * Copyright (c) 2006 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include "includes.h" +#include "sha256.h" + +#define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z))) +#define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) + +#define ROTR(x,n) (((x)>>(n)) | ((x) << (32 - (n)))) + +#define Sigma0(x) (ROTR(x,2) ^ ROTR(x,13) ^ ROTR(x,22)) +#define Sigma1(x) (ROTR(x,6) ^ ROTR(x,11) ^ ROTR(x,25)) +#define sigma0(x) (ROTR(x,7) ^ ROTR(x,18) ^ ((x)>>3)) +#define sigma1(x) (ROTR(x,17) ^ ROTR(x,19) ^ ((x)>>10)) + +#define A m->counter[0] +#define B m->counter[1] +#define C m->counter[2] +#define D m->counter[3] +#define E m->counter[4] +#define F m->counter[5] +#define G m->counter[6] +#define H m->counter[7] + +static const uint32_t constant_256[64] = { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +}; + +void +SHA256_Init (SHA256_CTX *m) +{ + m->sz[0] = 0; + m->sz[1] = 0; + A = 0x6a09e667; + B = 0xbb67ae85; + C = 0x3c6ef372; + D = 0xa54ff53a; + E = 0x510e527f; + F = 0x9b05688c; + G = 0x1f83d9ab; + H = 0x5be0cd19; +} + +static void +calc (SHA256_CTX *m, uint32_t *in) +{ + uint32_t AA, BB, CC, DD, EE, FF, GG, HH; + uint32_t data[64]; + int i; + + AA = A; + BB = B; + CC = C; + DD = D; + EE = E; + FF = F; + GG = G; + HH = H; + + for (i = 0; i < 16; ++i) + data[i] = in[i]; + for (i = 16; i < 64; ++i) + data[i] = sigma1(data[i-2]) + data[i-7] + + sigma0(data[i-15]) + data[i - 16]; + + for (i = 0; i < 64; i++) { + uint32_t T1, T2; + + T1 = HH + Sigma1(EE) + Ch(EE, FF, GG) + constant_256[i] + data[i]; + T2 = Sigma0(AA) + Maj(AA,BB,CC); + + HH = GG; + GG = FF; + FF = EE; + EE = DD + T1; + DD = CC; + CC = BB; + BB = AA; + AA = T1 + T2; + } + + A += AA; + B += BB; + C += CC; + D += DD; + E += EE; + F += FF; + G += GG; + H += HH; +} + +/* + * From `Performance analysis of MD5' by Joseph D. Touch + */ + +#if !defined(WORDS_BIGENDIAN) || defined(_CRAY) +/* Vector Crays doesn't have a good 32-bit type, or more precisely, + int32_t as defined by isn't 32 bits, and we don't + want to depend in being able to redefine this type. To cope with + this we have to clamp the result in some places to [0,2^32); no + need to do this on other machines. Did I say this was a mess? + */ + +#ifdef _CRAY +#define CRAYFIX(X) ((X) & 0xffffffff) +#else +#define CRAYFIX(X) (X) +#endif + +static inline uint32_t +cshift (uint32_t x, unsigned int n) +{ + x = CRAYFIX(x); + return CRAYFIX((x << n) | (x >> (32 - n))); +} + +static inline uint32_t +swap_uint32_t (uint32_t t) +{ + uint32_t temp1, temp2; + + temp1 = cshift(t, 16); + temp2 = temp1 >> 8; + temp1 &= 0x00ff00ff; + temp2 &= 0x00ff00ff; + temp1 <<= 8; + return temp1 | temp2; +} +#endif + +struct x32{ + unsigned int a:32; + unsigned int b:32; +}; + +void +SHA256_Update (SHA256_CTX *m, const void *v, size_t len) +{ + const unsigned char *p = v; + size_t old_sz = m->sz[0]; + size_t offset; + + m->sz[0] += len * 8; + if (m->sz[0] < old_sz) + ++m->sz[1]; + offset = (old_sz / 8) % 64; + while(len > 0){ + size_t l = MIN(len, 64 - offset); + memcpy(m->save + offset, p, l); + offset += l; + p += l; + len -= l; + if(offset == 64){ +#if !defined(WORDS_BIGENDIAN) || defined(_CRAY) + int i; + uint32_t current[16]; + struct x32 *u = (struct x32*)m->save; + for(i = 0; i < 8; i++){ + current[2*i+0] = swap_uint32_t(u[i].a); + current[2*i+1] = swap_uint32_t(u[i].b); + } + calc(m, current); +#else + calc(m, (uint32_t*)m->save); +#endif + offset = 0; + } + } +} + +void +SHA256_Final (void *res, SHA256_CTX *m) +{ + unsigned char zeros[72]; + unsigned offset = (m->sz[0] / 8) % 64; + unsigned int dstart = (120 - offset - 1) % 64 + 1; + + *zeros = 0x80; + memset (zeros + 1, 0, sizeof(zeros) - 1); + zeros[dstart+7] = (m->sz[0] >> 0) & 0xff; + zeros[dstart+6] = (m->sz[0] >> 8) & 0xff; + zeros[dstart+5] = (m->sz[0] >> 16) & 0xff; + zeros[dstart+4] = (m->sz[0] >> 24) & 0xff; + zeros[dstart+3] = (m->sz[1] >> 0) & 0xff; + zeros[dstart+2] = (m->sz[1] >> 8) & 0xff; + zeros[dstart+1] = (m->sz[1] >> 16) & 0xff; + zeros[dstart+0] = (m->sz[1] >> 24) & 0xff; + SHA256_Update (m, zeros, dstart + 8); + { + int i; + unsigned char *r = (unsigned char*)res; + + for (i = 0; i < 8; ++i) { + r[4*i+3] = m->counter[i] & 0xFF; + r[4*i+2] = (m->counter[i] >> 8) & 0xFF; + r[4*i+1] = (m->counter[i] >> 16) & 0xFF; + r[4*i] = (m->counter[i] >> 24) & 0xFF; + } + } +} diff --git a/lib/crypto/sha256.h b/lib/crypto/sha256.h new file mode 100644 index 0000000000..4a5f2cbe94 --- /dev/null +++ b/lib/crypto/sha256.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/* $Id: sha.h 17450 2006-05-05 11:11:43Z lha $ */ + +#ifndef HEIM_SHA_H +/* + based on heildal lib/hcrypto/sha.h. Copied to lib/crypto to avoid a link + problem. Hopefully will be removed once we solve this link problem + + (tridge) + */ +#define HEIM_SHA_H 1 + +#if 0 +/* symbol renaming */ +#define SHA1_Init hc_SHA1_Init +#define SHA1_Update hc_SHA1_Update +#define SHA1_Final hc_SHA1_Final +#define SHA256_Init hc_SHA256_Init +#define SHA256_Update hc_SHA256_Update +#define SHA256_Final hc_SHA256_Final +#endif + +/* + * SHA-1 + */ + +#define SHA_DIGEST_LENGTH 20 + +struct sha { + unsigned int sz[2]; + uint32_t counter[5]; + unsigned char save[64]; +}; + +typedef struct sha SHA_CTX; + +void SHA1_Init (struct sha *m); +void SHA1_Update (struct sha *m, const void *v, size_t len); +void SHA1_Final (void *res, struct sha *m); + +/* + * SHA-2 256 + */ + +#define SHA256_DIGEST_LENGTH 32 + +struct hc_sha256state { + unsigned int sz[2]; + uint32_t counter[8]; + unsigned char save[64]; +}; + +typedef struct hc_sha256state SHA256_CTX; + +void SHA256_Init (SHA256_CTX *); +void SHA256_Update (SHA256_CTX *, const void *, size_t); +void SHA256_Final (void *, SHA256_CTX *); + +#endif /* HEIM_SHA_H */ diff --git a/source4/Makefile b/source4/Makefile index 11057ae5f3..3630adce56 100644 --- a/source4/Makefile +++ b/source4/Makefile @@ -77,7 +77,7 @@ libstreamsrcdir := lib/stream libutilsrcdir := lib/util libtdrsrcdir := lib/tdr libdbwrapsrcdir := lib/dbwrap -libcryptosrcdir := lib/crypto +libcryptosrcdir := ../lib/crypto libtorturesrcdir := lib/torture smb_serversrcdir := smb_server libcompressionsrcdir := ../lib/compression diff --git a/source4/auth/credentials/credentials_ntlm.c b/source4/auth/credentials/credentials_ntlm.c index 22e273c35a..ef41971462 100644 --- a/source4/auth/credentials/credentials_ntlm.c +++ b/source4/auth/credentials/credentials_ntlm.c @@ -23,7 +23,7 @@ #include "includes.h" #include "librpc/gen_ndr/samr.h" /* for struct samrPassword */ -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "libcli/auth/libcli_auth.h" #include "auth/credentials/credentials.h" diff --git a/source4/auth/gensec/schannel_sign.c b/source4/auth/gensec/schannel_sign.c index 1e57beba08..9862a029a4 100644 --- a/source4/auth/gensec/schannel_sign.c +++ b/source4/auth/gensec/schannel_sign.c @@ -21,7 +21,7 @@ */ #include "includes.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "auth/auth.h" #include "auth/gensec/schannel.h" #include "auth/credentials/credentials.h" diff --git a/source4/auth/ntlm/ntlm_check.c b/source4/auth/ntlm/ntlm_check.c index 0dbbce0edc..62dec84f1d 100644 --- a/source4/auth/ntlm/ntlm_check.c +++ b/source4/auth/ntlm/ntlm_check.c @@ -20,7 +20,7 @@ */ #include "includes.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "librpc/gen_ndr/netlogon.h" #include "libcli/auth/libcli_auth.h" #include "param/param.h" diff --git a/source4/auth/ntlmssp/ntlmssp_client.c b/source4/auth/ntlmssp/ntlmssp_client.c index 891761860c..eb990dee9c 100644 --- a/source4/auth/ntlmssp/ntlmssp_client.c +++ b/source4/auth/ntlmssp/ntlmssp_client.c @@ -24,7 +24,7 @@ #include "includes.h" #include "auth/ntlmssp/ntlmssp.h" #include "auth/ntlmssp/msrpc_parse.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "libcli/auth/libcli_auth.h" #include "auth/credentials/credentials.h" #include "auth/gensec/gensec.h" diff --git a/source4/auth/ntlmssp/ntlmssp_server.c b/source4/auth/ntlmssp/ntlmssp_server.c index bf91be3e24..ad1ee8e871 100644 --- a/source4/auth/ntlmssp/ntlmssp_server.c +++ b/source4/auth/ntlmssp/ntlmssp_server.c @@ -24,7 +24,7 @@ #include "includes.h" #include "auth/ntlmssp/ntlmssp.h" #include "auth/ntlmssp/msrpc_parse.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "libcli/auth/libcli_auth.h" #include "auth/credentials/credentials.h" #include "auth/gensec/gensec.h" diff --git a/source4/auth/ntlmssp/ntlmssp_sign.c b/source4/auth/ntlmssp/ntlmssp_sign.c index 063b16f539..49ed48df98 100644 --- a/source4/auth/ntlmssp/ntlmssp_sign.c +++ b/source4/auth/ntlmssp/ntlmssp_sign.c @@ -23,7 +23,7 @@ #include "auth/auth.h" #include "auth/ntlmssp/ntlmssp.h" #include "auth/ntlmssp/msrpc_parse.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "auth/credentials/credentials.h" #include "auth/gensec/gensec.h" #include "param/param.h" diff --git a/source4/dsdb/repl/replicated_objects.c b/source4/dsdb/repl/replicated_objects.c index 552d83f411..2be01bac56 100644 --- a/source4/dsdb/repl/replicated_objects.c +++ b/source4/dsdb/repl/replicated_objects.c @@ -26,7 +26,7 @@ #include "librpc/gen_ndr/ndr_misc.h" #include "librpc/gen_ndr/ndr_drsuapi.h" #include "librpc/gen_ndr/ndr_drsblobs.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "libcli/auth/libcli_auth.h" #include "param/param.h" diff --git a/source4/dsdb/samdb/ldb_modules/password_hash.c b/source4/dsdb/samdb/ldb_modules/password_hash.c index 69783aefa8..6faef63c3d 100644 --- a/source4/dsdb/samdb/ldb_modules/password_hash.c +++ b/source4/dsdb/samdb/ldb_modules/password_hash.c @@ -48,7 +48,7 @@ #include "dsdb/samdb/ldb_modules/password_modules.h" #include "librpc/ndr/libndr.h" #include "librpc/gen_ndr/ndr_drsblobs.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "param/param.h" /* If we have decided there is reason to work on this request, then diff --git a/source4/kdc/hdb-ldb.c b/source4/kdc/hdb-ldb.c index cfd72c25ac..c5466f1acd 100644 --- a/source4/kdc/hdb-ldb.c +++ b/source4/kdc/hdb-ldb.c @@ -50,7 +50,7 @@ #include "param/param.h" #include "events/events.h" #include "kdc/kdc.h" -#include "lib/crypto/md4.h" +#include "../lib/crypto/md4.h" enum hdb_ldb_ent_type { HDB_LDB_ENT_TYPE_CLIENT, HDB_LDB_ENT_TYPE_SERVER, diff --git a/source4/lib/crypto/arcfour.c b/source4/lib/crypto/arcfour.c deleted file mode 100644 index 94196fa1ee..0000000000 --- a/source4/lib/crypto/arcfour.c +++ /dev/null @@ -1,91 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - An implementation of the arcfour algorithm - - 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 . -*/ - -#include "includes.h" -#include "lib/crypto/crypto.h" - -/* initialise the arcfour sbox with key */ -_PUBLIC_ void arcfour_init(struct arcfour_state *state, const DATA_BLOB *key) -{ - int ind; - uint8_t j = 0; - for (ind = 0; ind < sizeof(state->sbox); ind++) { - state->sbox[ind] = (uint8_t)ind; - } - - for (ind = 0; ind < sizeof(state->sbox); ind++) { - uint8_t tc; - - j += (state->sbox[ind] + key->data[ind%key->length]); - - tc = state->sbox[ind]; - state->sbox[ind] = state->sbox[j]; - state->sbox[j] = tc; - } - state->index_i = 0; - state->index_j = 0; -} - -/* crypt the data with arcfour */ -_PUBLIC_ void arcfour_crypt_sbox(struct arcfour_state *state, uint8_t *data, int len) -{ - int ind; - - for (ind = 0; ind < len; ind++) { - uint8_t tc; - uint8_t t; - - state->index_i++; - state->index_j += state->sbox[state->index_i]; - - tc = state->sbox[state->index_i]; - state->sbox[state->index_i] = state->sbox[state->index_j]; - state->sbox[state->index_j] = tc; - - t = state->sbox[state->index_i] + state->sbox[state->index_j]; - data[ind] = data[ind] ^ state->sbox[t]; - } -} - -/* - arcfour encryption with a blob key -*/ -_PUBLIC_ void arcfour_crypt_blob(uint8_t *data, int len, const DATA_BLOB *key) -{ - struct arcfour_state state; - arcfour_init(&state, key); - arcfour_crypt_sbox(&state, data, len); -} - -/* - a variant that assumes a 16 byte key. This should be removed - when the last user is gone -*/ -_PUBLIC_ void arcfour_crypt(uint8_t *data, const uint8_t keystr[16], int len) -{ - DATA_BLOB key = data_blob(keystr, 16); - - arcfour_crypt_blob(data, len, &key); - - data_blob_free(&key); -} - - diff --git a/source4/lib/crypto/config.mk b/source4/lib/crypto/config.mk deleted file mode 100644 index ee111bd088..0000000000 --- a/source4/lib/crypto/config.mk +++ /dev/null @@ -1,18 +0,0 @@ -############################## -# Start SUBSYSTEM LIBCRYPTO -[SUBSYSTEM::LIBCRYPTO] -# End SUBSYSTEM LIBCRYPTO -############################## - -LIBCRYPTO_OBJ_FILES = $(addprefix $(libcryptosrcdir)/, \ - crc32.o md5.o hmacmd5.o md4.o \ - arcfour.o sha256.o hmacsha256.o) - -[MODULE::TORTURE_LIBCRYPTO] -SUBSYSTEM = smbtorture -PRIVATE_DEPENDENCIES = LIBCRYPTO - -TORTURE_LIBCRYPTO_OBJ_FILES = $(addprefix $(libcryptosrcdir)/, \ - md4test.o md5test.o hmacmd5test.o) - -$(eval $(call proto_header_template,$(libcryptosrcdir)/test_proto.h,$(TORTURE_LIBCRYPTO_OBJ_FILES:.o=.c))) diff --git a/source4/lib/crypto/crc32.c b/source4/lib/crypto/crc32.c deleted file mode 100644 index 5b9d9b108d..0000000000 --- a/source4/lib/crypto/crc32.c +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or - * code or tables extracted from it, as desired without restriction. - * - * First, the polynomial itself and its table of feedback terms. The - * polynomial is - * X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0 - * - * Note that we take it "backwards" and put the highest-order term in - * the lowest-order bit. The X^32 term is "implied"; the LSB is the - * X^31 term, etc. The X^0 term (usually shown as "+1") results in - * the MSB being 1 - * - * Note that the usual hardware shift register implementation, which - * is what we're using (we're merely optimizing it by doing eight-bit - * chunks at a time) shifts bits into the lowest-order term. In our - * implementation, that means shifting towards the right. Why do we - * do it this way? Because the calculated CRC must be transmitted in - * order from highest-order term to lowest-order term. UARTs transmit - * characters in order from LSB to MSB. By storing the CRC this way - * we hand it to the UART in the order low-byte to high-byte; the UART - * sends each low-bit to hight-bit; and the result is transmission bit - * by bit from highest- to lowest-order term without requiring any bit - * shuffling on our part. Reception works similarly - * - * The feedback terms table consists of 256, 32-bit entries. Notes - * - * The table can be generated at runtime if desired; code to do so - * is shown later. It might not be obvious, but the feedback - * terms simply represent the results of eight shift/xor opera - * tions for all combinations of data and CRC register values - * - * The values must be right-shifted by eight bits by the "updcrc - * logic; the shift must be unsigned (bring in zeroes). On some - * hardware you could probably optimize the shift in assembler by - * using byte-swap instructions - * polynomial $edb88320 - * - * - * CRC32 code derived from work by Gary S. Brown. - */ - -#include "includes.h" - -static const uint32_t crc32_tab[] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d -}; - -uint32_t crc32_calc_buffer(const uint8_t *buf, size_t size) -{ - const uint8_t *p; - uint32_t crc; - - p = buf; - crc = ~0U; - - while (size--) - crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8); - - return crc ^ ~0U; -} diff --git a/source4/lib/crypto/crc32.h b/source4/lib/crypto/crc32.h deleted file mode 100644 index 7854abf865..0000000000 --- a/source4/lib/crypto/crc32.h +++ /dev/null @@ -1 +0,0 @@ -uint32_t crc32_calc_buffer(const uint8_t *buf, size_t size); diff --git a/source4/lib/crypto/crypto.h b/source4/lib/crypto/crypto.h deleted file mode 100644 index fc283f72ba..0000000000 --- a/source4/lib/crypto/crypto.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - Copyright (C) Andrew Tridgell 2004 - - 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 . -*/ - -#include "lib/crypto/crc32.h" -#include "lib/crypto/md4.h" -#include "lib/crypto/md5.h" -#include "lib/crypto/hmacmd5.h" -#include "lib/crypto/sha256.h" -#include "lib/crypto/hmacsha256.h" - -struct arcfour_state { - uint8_t sbox[256]; - uint8_t index_i; - uint8_t index_j; -}; - -void arcfour_init(struct arcfour_state *state, const DATA_BLOB *key); -void arcfour_crypt_sbox(struct arcfour_state *state, uint8_t *data, int len); -void arcfour_crypt_blob(uint8_t *data, int len, const DATA_BLOB *key); -void arcfour_crypt(uint8_t *data, const uint8_t keystr[16], int len); - diff --git a/source4/lib/crypto/hmacmd5.c b/source4/lib/crypto/hmacmd5.c deleted file mode 100644 index 3a9ec38a27..0000000000 --- a/source4/lib/crypto/hmacmd5.c +++ /dev/null @@ -1,117 +0,0 @@ -/* - Unix SMB/CIFS implementation. - HMAC MD5 code for use in NTLMv2 - Copyright (C) Luke Kenneth Casson Leighton 1996-2000 - Copyright (C) Andrew Tridgell 1992-2000 - - 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 . -*/ - -/* taken direct from rfc2104 implementation and modified for suitable use - * for ntlmv2. - */ - -#include "includes.h" -#include "lib/crypto/crypto.h" - -/*********************************************************************** - the rfc 2104 version of hmac_md5 initialisation. -***********************************************************************/ -_PUBLIC_ void hmac_md5_init_rfc2104(const uint8_t *key, int key_len, HMACMD5Context *ctx) -{ - int i; - uint8_t tk[16]; - - /* if key is longer than 64 bytes reset it to key=MD5(key) */ - if (key_len > 64) - { - struct MD5Context tctx; - - MD5Init(&tctx); - MD5Update(&tctx, key, key_len); - MD5Final(tk, &tctx); - - key = tk; - key_len = 16; - } - - /* start out by storing key in pads */ - ZERO_STRUCT(ctx->k_ipad); - ZERO_STRUCT(ctx->k_opad); - memcpy( ctx->k_ipad, key, key_len); - memcpy( ctx->k_opad, key, key_len); - - /* XOR key with ipad and opad values */ - for (i=0; i<64; i++) - { - ctx->k_ipad[i] ^= 0x36; - ctx->k_opad[i] ^= 0x5c; - } - - MD5Init(&ctx->ctx); - MD5Update(&ctx->ctx, ctx->k_ipad, 64); -} - -/*********************************************************************** - the microsoft version of hmac_md5 initialisation. -***********************************************************************/ -_PUBLIC_ void hmac_md5_init_limK_to_64(const uint8_t *key, int key_len, - HMACMD5Context *ctx) -{ - /* if key is longer than 64 bytes truncate it */ - if (key_len > 64) - { - key_len = 64; - } - - hmac_md5_init_rfc2104(key, key_len, ctx); -} - -/*********************************************************************** - update hmac_md5 "inner" buffer -***********************************************************************/ -_PUBLIC_ void hmac_md5_update(const uint8_t *text, int text_len, HMACMD5Context *ctx) -{ - MD5Update(&ctx->ctx, text, text_len); /* then text of datagram */ -} - -/*********************************************************************** - finish off hmac_md5 "inner" buffer and generate outer one. -***********************************************************************/ -_PUBLIC_ void hmac_md5_final(uint8_t *digest, HMACMD5Context *ctx) -{ - struct MD5Context ctx_o; - - MD5Final(digest, &ctx->ctx); - - MD5Init(&ctx_o); - MD5Update(&ctx_o, ctx->k_opad, 64); - MD5Update(&ctx_o, digest, 16); - MD5Final(digest, &ctx_o); -} - -/*********************************************************** - single function to calculate an HMAC MD5 digest from data. - use the microsoft hmacmd5 init method because the key is 16 bytes. -************************************************************/ -_PUBLIC_ void hmac_md5(const uint8_t key[16], const uint8_t *data, int data_len, uint8_t *digest) -{ - HMACMD5Context ctx; - hmac_md5_init_limK_to_64(key, 16, &ctx); - if (data_len != 0) - { - hmac_md5_update(data, data_len, &ctx); - } - hmac_md5_final(digest, &ctx); -} diff --git a/source4/lib/crypto/hmacmd5.h b/source4/lib/crypto/hmacmd5.h deleted file mode 100644 index 5769737fcd..0000000000 --- a/source4/lib/crypto/hmacmd5.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - Unix SMB/CIFS implementation. - Interface header: HMAC MD5 code - Copyright (C) Luke Kenneth Casson Leighton 1996-1999 - Copyright (C) Andrew Tridgell 1992-1999 - - 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 . -*/ - -#ifndef _HMAC_MD5_H - -typedef struct -{ - struct MD5Context ctx; - uint8_t k_ipad[65]; - uint8_t k_opad[65]; - -} HMACMD5Context; - -void hmac_md5_init_limK_to_64(const uint8_t *key, int key_len, - HMACMD5Context *ctx); -void hmac_md5_update(const uint8_t *text, int text_len, HMACMD5Context *ctx); -void hmac_md5_final(uint8_t *digest, HMACMD5Context *ctx); -void hmac_md5(const uint8_t key[16], const uint8_t *data, int data_len, uint8_t *digest); -void hmac_md5_init_rfc2104(const uint8_t *key, int key_len, HMACMD5Context *ctx); - -#endif /* _HMAC_MD5_H */ diff --git a/source4/lib/crypto/hmacmd5test.c b/source4/lib/crypto/hmacmd5test.c deleted file mode 100644 index 07ed54c98d..0000000000 --- a/source4/lib/crypto/hmacmd5test.c +++ /dev/null @@ -1,98 +0,0 @@ -/* - Unix SMB/CIFS implementation. - HMAC MD5 tests - Copyright (C) Stefan Metzmacher 2006 - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ -#include "includes.h" -#include "lib/crypto/crypto.h" - -struct torture_context; - -static DATA_BLOB data_blob_repeat_byte(uint8_t byte, size_t length) -{ - DATA_BLOB b = data_blob(NULL, length); - memset(b.data, byte, length); - return b; -} - -/* - This uses the test values from rfc 2104, 2202 -*/ -bool torture_local_crypto_hmacmd5(struct torture_context *torture) -{ - bool ret = true; - uint32_t i; - struct { - DATA_BLOB key; - DATA_BLOB data; - DATA_BLOB md5; - } testarray[8]; - - testarray[0].key = data_blob_repeat_byte(0x0b, 16); - testarray[0].data = data_blob_string_const("Hi There"); - testarray[0].md5 = strhex_to_data_blob("9294727a3638bb1c13f48ef8158bfc9d"); - - testarray[1].key = data_blob_string_const("Jefe"); - testarray[1].data = data_blob_string_const("what do ya want for nothing?"); - testarray[1].md5 = strhex_to_data_blob("750c783e6ab0b503eaa86e310a5db738"); - - testarray[2].key = data_blob_repeat_byte(0xaa, 16); - testarray[2].data = data_blob_repeat_byte(0xdd, 50); - testarray[2].md5 = strhex_to_data_blob("56be34521d144c88dbb8c733f0e8b3f6"); - - testarray[3].key = strhex_to_data_blob("0102030405060708090a0b0c0d0e0f10111213141516171819"); - testarray[3].data = data_blob_repeat_byte(0xcd, 50); - testarray[3].md5 = strhex_to_data_blob("697eaf0aca3a3aea3a75164746ffaa79"); - - testarray[4].key = data_blob_repeat_byte(0x0c, 16); - testarray[4].data = data_blob_string_const("Test With Truncation"); - testarray[4].md5 = strhex_to_data_blob("56461ef2342edc00f9bab995690efd4c"); - - testarray[5].key = data_blob_repeat_byte(0xaa, 80); - testarray[5].data = data_blob_string_const("Test Using Larger Than Block-Size Key - Hash Key First"); - testarray[5].md5 = strhex_to_data_blob("6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd"); - - testarray[6].key = data_blob_repeat_byte(0xaa, 80); - testarray[6].data = data_blob_string_const("Test Using Larger Than Block-Size Key " - "and Larger Than One Block-Size Data"); - testarray[6].md5 = strhex_to_data_blob("6f630fad67cda0ee1fb1f562db3aa53e"); - - testarray[7].key = data_blob(NULL, 0); - - for (i=0; testarray[i].key.data; i++) { - HMACMD5Context ctx; - uint8_t md5[16]; - int e; - - hmac_md5_init_rfc2104(testarray[i].key.data, testarray[i].key.length, &ctx); - hmac_md5_update(testarray[i].data.data, testarray[i].data.length, &ctx); - hmac_md5_final(md5, &ctx); - - e = memcmp(testarray[i].md5.data, - md5, - MIN(testarray[i].md5.length, sizeof(md5))); - if (e != 0) { - printf("hmacmd5 test[%u]: failed\n", i); - dump_data(0, testarray[i].key.data, testarray[i].key.length); - dump_data(0, testarray[i].data.data, testarray[i].data.length); - dump_data(0, testarray[i].md5.data, testarray[i].md5.length); - dump_data(0, md5, sizeof(md5)); - ret = false; - } - } - - return ret; -} diff --git a/source4/lib/crypto/hmacsha256.c b/source4/lib/crypto/hmacsha256.c deleted file mode 100644 index 6b0af9ee83..0000000000 --- a/source4/lib/crypto/hmacsha256.c +++ /dev/null @@ -1,91 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - Interface header: HMAC SHA-256 code - - Copyright (C) Andrew Tridgell 2008 - - based in hmacsha1.c which is: - Copyright (C) Stefan Metzmacher - - 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 . -*/ - -/* - taken direct from rfc2202 implementation and modified for suitable use - */ - -#include "includes.h" -#include "lib/crypto/crypto.h" - -/*********************************************************************** - the rfc 2104/2202 version of hmac_sha256 initialisation. -***********************************************************************/ -_PUBLIC_ void hmac_sha256_init(const uint8_t *key, size_t key_len, struct HMACSHA256Context *ctx) -{ - int i; - uint8_t tk[SHA256_DIGEST_LENGTH]; - - /* if key is longer than 64 bytes reset it to key=HASH(key) */ - if (key_len > 64) - { - SHA256_CTX tctx; - - SHA256_Init(&tctx); - SHA256_Update(&tctx, key, key_len); - SHA256_Final(tk, &tctx); - - key = tk; - key_len = SHA256_DIGEST_LENGTH; - } - - /* start out by storing key in pads */ - ZERO_STRUCT(ctx->k_ipad); - ZERO_STRUCT(ctx->k_opad); - memcpy( ctx->k_ipad, key, key_len); - memcpy( ctx->k_opad, key, key_len); - - /* XOR key with ipad and opad values */ - for (i=0; i<64; i++) - { - ctx->k_ipad[i] ^= 0x36; - ctx->k_opad[i] ^= 0x5c; - } - - SHA256_Init(&ctx->ctx); - SHA256_Update(&ctx->ctx, ctx->k_ipad, 64); -} - -/*********************************************************************** - update hmac_sha256 "inner" buffer -***********************************************************************/ -_PUBLIC_ void hmac_sha256_update(const uint8_t *data, size_t data_len, struct HMACSHA256Context *ctx) -{ - SHA256_Update(&ctx->ctx, data, data_len); /* then text of datagram */ -} - -/*********************************************************************** - finish off hmac_sha256 "inner" buffer and generate outer one. -***********************************************************************/ -_PUBLIC_ void hmac_sha256_final(uint8_t digest[SHA256_DIGEST_LENGTH], struct HMACSHA256Context *ctx) -{ - SHA256_CTX ctx_o; - - SHA256_Final(digest, &ctx->ctx); - - SHA256_Init(&ctx_o); - SHA256_Update(&ctx_o, ctx->k_opad, 64); - SHA256_Update(&ctx_o, digest, SHA256_DIGEST_LENGTH); - SHA256_Final(digest, &ctx_o); -} diff --git a/source4/lib/crypto/hmacsha256.h b/source4/lib/crypto/hmacsha256.h deleted file mode 100644 index 8960c636c1..0000000000 --- a/source4/lib/crypto/hmacsha256.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - Interface header: HMAC SHA256 code - - Copyright (C) Andrew Tridgell 2008 - - based on hmacsha1.h which is: - - Copyright (C) Stefan Metzmacher 2006 - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -#ifndef _HMAC_SHA256_H - -struct HMACSHA256Context { - SHA256_CTX ctx; - uint8_t k_ipad[65]; - uint8_t k_opad[65]; -}; - -void hmac_sha256_init(const uint8_t *key, size_t key_len, struct HMACSHA256Context *ctx); -void hmac_sha256_update(const uint8_t *data, size_t data_len, struct HMACSHA256Context *ctx); -void hmac_sha256_final(uint8_t digest[20], struct HMACSHA256Context *ctx); - -#endif /* _HMAC_SHA256_H */ diff --git a/source4/lib/crypto/md4.c b/source4/lib/crypto/md4.c deleted file mode 100644 index 7ad93ce786..0000000000 --- a/source4/lib/crypto/md4.c +++ /dev/null @@ -1,176 +0,0 @@ -/* - Unix SMB/CIFS implementation. - a implementation of MD4 designed for use in the SMB authentication protocol - Copyright (C) Andrew Tridgell 1997-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 . -*/ - -#include "includes.h" - -/* NOTE: This code makes no attempt to be fast! - - It assumes that a int is at least 32 bits long -*/ - -struct mdfour_state { - uint32_t A, B, C, D; -}; - -static uint32_t F(uint32_t X, uint32_t Y, uint32_t Z) -{ - return (X&Y) | ((~X)&Z); -} - -static uint32_t G(uint32_t X, uint32_t Y, uint32_t Z) -{ - return (X&Y) | (X&Z) | (Y&Z); -} - -static uint32_t H(uint32_t X, uint32_t Y, uint32_t Z) -{ - return X^Y^Z; -} - -static uint32_t lshift(uint32_t x, int s) -{ - x &= 0xFFFFFFFF; - return ((x<>(32-s)); -} - -#define ROUND1(a,b,c,d,k,s) a = lshift(a + F(b,c,d) + X[k], s) -#define ROUND2(a,b,c,d,k,s) a = lshift(a + G(b,c,d) + X[k] + (uint32_t)0x5A827999,s) -#define ROUND3(a,b,c,d,k,s) a = lshift(a + H(b,c,d) + X[k] + (uint32_t)0x6ED9EBA1,s) - -/* this applies md4 to 64 byte chunks */ -static void mdfour64(struct mdfour_state *s, uint32_t *M) -{ - int j; - uint32_t AA, BB, CC, DD; - uint32_t X[16]; - - for (j=0;j<16;j++) - X[j] = M[j]; - - AA = s->A; BB = s->B; CC = s->C; DD = s->D; - - ROUND1(s->A,s->B,s->C,s->D, 0, 3); ROUND1(s->D,s->A,s->B,s->C, 1, 7); - ROUND1(s->C,s->D,s->A,s->B, 2, 11); ROUND1(s->B,s->C,s->D,s->A, 3, 19); - ROUND1(s->A,s->B,s->C,s->D, 4, 3); ROUND1(s->D,s->A,s->B,s->C, 5, 7); - ROUND1(s->C,s->D,s->A,s->B, 6, 11); ROUND1(s->B,s->C,s->D,s->A, 7, 19); - ROUND1(s->A,s->B,s->C,s->D, 8, 3); ROUND1(s->D,s->A,s->B,s->C, 9, 7); - ROUND1(s->C,s->D,s->A,s->B, 10, 11); ROUND1(s->B,s->C,s->D,s->A, 11, 19); - ROUND1(s->A,s->B,s->C,s->D, 12, 3); ROUND1(s->D,s->A,s->B,s->C, 13, 7); - ROUND1(s->C,s->D,s->A,s->B, 14, 11); ROUND1(s->B,s->C,s->D,s->A, 15, 19); - - ROUND2(s->A,s->B,s->C,s->D, 0, 3); ROUND2(s->D,s->A,s->B,s->C, 4, 5); - ROUND2(s->C,s->D,s->A,s->B, 8, 9); ROUND2(s->B,s->C,s->D,s->A, 12, 13); - ROUND2(s->A,s->B,s->C,s->D, 1, 3); ROUND2(s->D,s->A,s->B,s->C, 5, 5); - ROUND2(s->C,s->D,s->A,s->B, 9, 9); ROUND2(s->B,s->C,s->D,s->A, 13, 13); - ROUND2(s->A,s->B,s->C,s->D, 2, 3); ROUND2(s->D,s->A,s->B,s->C, 6, 5); - ROUND2(s->C,s->D,s->A,s->B, 10, 9); ROUND2(s->B,s->C,s->D,s->A, 14, 13); - ROUND2(s->A,s->B,s->C,s->D, 3, 3); ROUND2(s->D,s->A,s->B,s->C, 7, 5); - ROUND2(s->C,s->D,s->A,s->B, 11, 9); ROUND2(s->B,s->C,s->D,s->A, 15, 13); - - ROUND3(s->A,s->B,s->C,s->D, 0, 3); ROUND3(s->D,s->A,s->B,s->C, 8, 9); - ROUND3(s->C,s->D,s->A,s->B, 4, 11); ROUND3(s->B,s->C,s->D,s->A, 12, 15); - ROUND3(s->A,s->B,s->C,s->D, 2, 3); ROUND3(s->D,s->A,s->B,s->C, 10, 9); - ROUND3(s->C,s->D,s->A,s->B, 6, 11); ROUND3(s->B,s->C,s->D,s->A, 14, 15); - ROUND3(s->A,s->B,s->C,s->D, 1, 3); ROUND3(s->D,s->A,s->B,s->C, 9, 9); - ROUND3(s->C,s->D,s->A,s->B, 5, 11); ROUND3(s->B,s->C,s->D,s->A, 13, 15); - ROUND3(s->A,s->B,s->C,s->D, 3, 3); ROUND3(s->D,s->A,s->B,s->C, 11, 9); - ROUND3(s->C,s->D,s->A,s->B, 7, 11); ROUND3(s->B,s->C,s->D,s->A, 15, 15); - - s->A += AA; - s->B += BB; - s->C += CC; - s->D += DD; - - s->A &= 0xFFFFFFFF; - s->B &= 0xFFFFFFFF; - s->C &= 0xFFFFFFFF; - s->D &= 0xFFFFFFFF; - - for (j=0;j<16;j++) - X[j] = 0; -} - -static void copy64(uint32_t *M, const uint8_t *in) -{ - int i; - - for (i=0;i<16;i++) - M[i] = (in[i*4+3]<<24) | (in[i*4+2]<<16) | - (in[i*4+1]<<8) | (in[i*4+0]<<0); -} - -static void copy4(uint8_t *out, uint32_t x) -{ - out[0] = x&0xFF; - out[1] = (x>>8)&0xFF; - out[2] = (x>>16)&0xFF; - out[3] = (x>>24)&0xFF; -} - -/** - * produce a md4 message digest from data of length n bytes - */ -_PUBLIC_ void mdfour(uint8_t *out, const uint8_t *in, int n) -{ - uint8_t buf[128]; - uint32_t M[16]; - uint32_t b = n * 8; - int i; - struct mdfour_state state; - - state.A = 0x67452301; - state.B = 0xefcdab89; - state.C = 0x98badcfe; - state.D = 0x10325476; - - while (n > 64) { - copy64(M, in); - mdfour64(&state, M); - in += 64; - n -= 64; - } - - for (i=0;i<128;i++) - buf[i] = 0; - memcpy(buf, in, n); - buf[n] = 0x80; - - if (n <= 55) { - copy4(buf+56, b); - copy64(M, buf); - mdfour64(&state, M); - } else { - copy4(buf+120, b); - copy64(M, buf); - mdfour64(&state, M); - copy64(M, buf+64); - mdfour64(&state, M); - } - - for (i=0;i<128;i++) - buf[i] = 0; - copy64(M, buf); - - copy4(out, state.A); - copy4(out+4, state.B); - copy4(out+8, state.C); - copy4(out+12, state.D); -} - - diff --git a/source4/lib/crypto/md4.h b/source4/lib/crypto/md4.h deleted file mode 100644 index 234e488e4f..0000000000 --- a/source4/lib/crypto/md4.h +++ /dev/null @@ -1 +0,0 @@ -void mdfour(uint8_t *out, const uint8_t *in, int n); diff --git a/source4/lib/crypto/md4test.c b/source4/lib/crypto/md4test.c deleted file mode 100644 index 5e0451973c..0000000000 --- a/source4/lib/crypto/md4test.c +++ /dev/null @@ -1,83 +0,0 @@ -/* - Unix SMB/CIFS implementation. - MD4 tests - Copyright (C) Stefan Metzmacher 2006 - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -#include "includes.h" -#include "lib/crypto/crypto.h" - -struct torture_context; - -/* - This uses the test values from rfc1320 -*/ -bool torture_local_crypto_md4(struct torture_context *torture) -{ - bool ret = true; - uint32_t i; - struct { - const char *data; - const char *md4; - } testarray[] = { - { - .data = "", - .md4 = "31d6cfe0d16ae931b73c59d7e0c089c0" - },{ - .data = "a", - .md4 = "bde52cb31de33e46245e05fbdbd6fb24" - },{ - .data = "abc", - .md4 = "a448017aaf21d8525fc10ae87aa6729d" - },{ - .data = "message digest", - .md4 = "d9130a8164549fe818874806e1c7014b" - },{ - .data = "abcdefghijklmnopqrstuvwxyz", - .md4 = "d79e1c308aa5bbcdeea8ed63df412da9" - },{ - .data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", - .md4 = "043f8582f241db351ce627e153e7f0e4" - },{ - .data = "12345678901234567890123456789012345678901234567890123456789012345678901234567890", - .md4 = "e33b4ddc9c38f2199c3e7b164fcc0536" - } - }; - - for (i=0; i < ARRAY_SIZE(testarray); i++) { - uint8_t md4[16]; - int e; - DATA_BLOB data; - DATA_BLOB md4blob; - - data = data_blob_string_const(testarray[i].data); - md4blob = strhex_to_data_blob(testarray[i].md4); - - mdfour(md4, data.data, data.length); - - e = memcmp(md4blob.data, md4, MIN(md4blob.length, sizeof(md4))); - if (e != 0) { - printf("md4 test[%u]: failed\n", i); - dump_data(0, data.data, data.length); - dump_data(0, md4blob.data, md4blob.length); - dump_data(0, md4, sizeof(md4)); - ret = false; - } - talloc_free(md4blob.data); - } - - return ret; -} diff --git a/source4/lib/crypto/md5.c b/source4/lib/crypto/md5.c deleted file mode 100644 index 584c46ef2d..0000000000 --- a/source4/lib/crypto/md5.c +++ /dev/null @@ -1,248 +0,0 @@ -/* - * This code implements the MD5 message-digest algorithm. - * The algorithm is due to Ron Rivest. This code was - * written by Colin Plumb in 1993, no copyright is claimed. - * This code is in the public domain; do with it what you wish. - * - * Equivalent code is available from RSA Data Security, Inc. - * This code has been tested against that, and is equivalent, - * except that you don't need to include two pages of legalese - * with every copy. - * - * To compute the message digest of a chunk of bytes, declare an - * MD5Context structure, pass it to MD5Init, call MD5Update as - * needed on buffers full of bytes, and then call MD5Final, which - * will fill a supplied 16-byte array with the digest. - */ - -/* This code slightly modified to fit into Samba by - abartlet@samba.org Jun 2001 */ - -#include "includes.h" - -#include "md5.h" - - -static void MD5Transform(uint32_t buf[4], uint32_t const in[16]); - -/* - * Note: this code is harmless on little-endian machines. - */ -static void byteReverse(uint8_t *buf, uint_t longs) -{ - uint32_t t; - do { - t = (uint32_t) ((uint_t) buf[3] << 8 | buf[2]) << 16 | - ((uint_t) buf[1] << 8 | buf[0]); - *(uint32_t *) buf = t; - buf += 4; - } while (--longs); -} - -/* - * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious - * initialization constants. - */ -_PUBLIC_ void MD5Init(struct MD5Context *ctx) -{ - ctx->buf[0] = 0x67452301; - ctx->buf[1] = 0xefcdab89; - ctx->buf[2] = 0x98badcfe; - ctx->buf[3] = 0x10325476; - - ctx->bits[0] = 0; - ctx->bits[1] = 0; -} - -/* - * Update context to reflect the concatenation of another buffer full - * of bytes. - */ -_PUBLIC_ void MD5Update(struct MD5Context *ctx, const uint8_t *buf, size_t len) -{ - register uint32_t t; - - /* Update bitcount */ - - t = ctx->bits[0]; - if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) - ctx->bits[1]++; /* Carry from low to high */ - ctx->bits[1] += len >> 29; - - t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ - - /* Handle any leading odd-sized chunks */ - - if (t) { - uint8_t *p = (uint8_t *) ctx->in + t; - - t = 64 - t; - if (len < t) { - memmove(p, buf, len); - return; - } - memmove(p, buf, t); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (uint32_t *) ctx->in); - buf += t; - len -= t; - } - /* Process data in 64-byte chunks */ - - while (len >= 64) { - memmove(ctx->in, buf, 64); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (uint32_t *) ctx->in); - buf += 64; - len -= 64; - } - - /* Handle any remaining bytes of data. */ - - memmove(ctx->in, buf, len); -} - -/* - * Final wrapup - pad to 64-byte boundary with the bit pattern - * 1 0* (64-bit count of bits processed, MSB-first) - */ -_PUBLIC_ void MD5Final(uint8_t digest[16], struct MD5Context *ctx) -{ - uint_t count; - uint8_t *p; - - /* Compute number of bytes mod 64 */ - count = (ctx->bits[0] >> 3) & 0x3F; - - /* Set the first char of padding to 0x80. This is safe since there is - always at least one byte free */ - p = ctx->in + count; - *p++ = 0x80; - - /* Bytes of padding needed to make 64 bytes */ - count = 64 - 1 - count; - - /* Pad out to 56 mod 64 */ - if (count < 8) { - /* Two lots of padding: Pad the first block to 64 bytes */ - memset(p, 0, count); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (uint32_t *) ctx->in); - - /* Now fill the next block with 56 bytes */ - memset(ctx->in, 0, 56); - } else { - /* Pad block to 56 bytes */ - memset(p, 0, count - 8); - } - byteReverse(ctx->in, 14); - - /* Append length in bits and transform */ - ((uint32_t *) ctx->in)[14] = ctx->bits[0]; - ((uint32_t *) ctx->in)[15] = ctx->bits[1]; - - MD5Transform(ctx->buf, (uint32_t *) ctx->in); - byteReverse((uint8_t *) ctx->buf, 4); - memmove(digest, ctx->buf, 16); - memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */ -} - -/* The four core functions - F1 is optimized somewhat */ - -/* #define F1(x, y, z) (x & y | ~x & z) */ -#define F1(x, y, z) (z ^ (x & (y ^ z))) -#define F2(x, y, z) F1(z, x, y) -#define F3(x, y, z) (x ^ y ^ z) -#define F4(x, y, z) (y ^ (x | ~z)) - -/* This is the central step in the MD5 algorithm. */ -#define MD5STEP(f, w, x, y, z, data, s) \ - ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) - -/* - * The core of the MD5 algorithm, this alters an existing MD5 hash to - * reflect the addition of 16 longwords of new data. MD5Update blocks - * the data and converts bytes into longwords for this routine. - */ -static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) -{ - register uint32_t a, b, c, d; - - a = buf[0]; - b = buf[1]; - c = buf[2]; - d = buf[3]; - - MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); - MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); - MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); - MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); - MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); - MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); - MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); - MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); - MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); - MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); - MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); - MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); - MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); - MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); - MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); - MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); - - MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); - MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); - MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); - MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); - MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); - MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); - MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); - MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); - MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); - MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); - MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); - MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); - MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); - MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); - MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); - MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); - - MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); - MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); - MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); - MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); - MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); - MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); - MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); - MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); - MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); - MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); - MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); - MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); - MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); - MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); - MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); - MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); - - MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); - MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); - MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); - MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); - MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); - MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); - MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); - MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); - MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); - MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); - MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); - MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); - MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); - MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); - MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); - MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); - - buf[0] += a; - buf[1] += b; - buf[2] += c; - buf[3] += d; -} diff --git a/source4/lib/crypto/md5.h b/source4/lib/crypto/md5.h deleted file mode 100644 index 4064d6f003..0000000000 --- a/source4/lib/crypto/md5.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef MD5_H -#define MD5_H -#ifndef HEADER_MD5_H -/* Try to avoid clashes with OpenSSL */ -#define HEADER_MD5_H -#endif - -struct MD5Context { - uint32_t buf[4]; - uint32_t bits[2]; - uint8_t in[64]; -}; - -void MD5Init(struct MD5Context *context); -void MD5Update(struct MD5Context *context, const uint8_t *buf, - size_t len); -void MD5Final(uint8_t digest[16], struct MD5Context *context); - -#endif /* !MD5_H */ diff --git a/source4/lib/crypto/md5test.c b/source4/lib/crypto/md5test.c deleted file mode 100644 index 702e0fcf41..0000000000 --- a/source4/lib/crypto/md5test.c +++ /dev/null @@ -1,93 +0,0 @@ -/* - Unix SMB/CIFS implementation. - MD5 tests - Copyright (C) Stefan Metzmacher - - 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 . -*/ - -#include "includes.h" -#include "lib/crypto/crypto.h" - -struct torture_context; - -/* - This uses the test values from rfc1321 -*/ -bool torture_local_crypto_md5(struct torture_context *torture) -{ - bool ret = true; - uint32_t i; - struct { - const char *data; - const char *md5; - } testarray[] = { - { - .data = "", - .md5 = "d41d8cd98f00b204e9800998ecf8427e" - },{ - .data = "a", - .md5 = "0cc175b9c0f1b6a831c399e269772661" - },{ - .data = "abc", - .md5 = "900150983cd24fb0d6963f7d28e17f72" - },{ - .data = "message digest", - .md5 = "f96b697d7cb7938d525a2f31aaf161d0" - },{ - .data = "abcdefghijklmnopqrstuvwxyz", - .md5 = "c3fcd3d76192e4007dfb496cca67e13b" - },{ - .data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789", - .md5 = "d174ab98d277d9f5a5611c2c9f419d9f" - },{ - .data = "123456789012345678901234567890" - "123456789012345678901234567890" - "12345678901234567890", - .md5 = "57edf4a22be3c955ac49da2e2107b67a" - } - }; - - for (i=0; i < ARRAY_SIZE(testarray); i++) { - struct MD5Context ctx; - uint8_t md5[16]; - int e; - - DATA_BLOB data; - DATA_BLOB md5blob; - - data = data_blob_string_const(testarray[i].data); - md5blob = strhex_to_data_blob(testarray[i].md5); - - MD5Init(&ctx); - MD5Update(&ctx, data.data, data.length); - MD5Final(md5, &ctx); - - e = memcmp(md5blob.data, - md5, - MIN(md5blob.length, sizeof(md5))); - if (e != 0) { - printf("md5 test[%u]: failed\n", i); - dump_data(0, data.data, data.length); - dump_data(0, md5blob.data, md5blob.length); - dump_data(0, md5, sizeof(md5)); - ret = false; - } - talloc_free(md5blob.data); - } - - return ret; -} diff --git a/source4/lib/crypto/sha256.c b/source4/lib/crypto/sha256.c deleted file mode 100644 index a2def25814..0000000000 --- a/source4/lib/crypto/sha256.c +++ /dev/null @@ -1,253 +0,0 @@ -/* - based on heildal lib/hcrypto/sha256.c. Copied to lib/crypto to avoid a link - problem. Hopefully will be removed once we solve this link problem - - (tridge) - */ - -/* - * Copyright (c) 2006 Kungliga Tekniska Högskolan - * (Royal Institute of Technology, Stockholm, Sweden). - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * 3. Neither the name of the Institute nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#include "includes.h" -#include "sha256.h" - -#define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z))) -#define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) - -#define ROTR(x,n) (((x)>>(n)) | ((x) << (32 - (n)))) - -#define Sigma0(x) (ROTR(x,2) ^ ROTR(x,13) ^ ROTR(x,22)) -#define Sigma1(x) (ROTR(x,6) ^ ROTR(x,11) ^ ROTR(x,25)) -#define sigma0(x) (ROTR(x,7) ^ ROTR(x,18) ^ ((x)>>3)) -#define sigma1(x) (ROTR(x,17) ^ ROTR(x,19) ^ ((x)>>10)) - -#define A m->counter[0] -#define B m->counter[1] -#define C m->counter[2] -#define D m->counter[3] -#define E m->counter[4] -#define F m->counter[5] -#define G m->counter[6] -#define H m->counter[7] - -static const uint32_t constant_256[64] = { - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -}; - -void -SHA256_Init (SHA256_CTX *m) -{ - m->sz[0] = 0; - m->sz[1] = 0; - A = 0x6a09e667; - B = 0xbb67ae85; - C = 0x3c6ef372; - D = 0xa54ff53a; - E = 0x510e527f; - F = 0x9b05688c; - G = 0x1f83d9ab; - H = 0x5be0cd19; -} - -static void -calc (SHA256_CTX *m, uint32_t *in) -{ - uint32_t AA, BB, CC, DD, EE, FF, GG, HH; - uint32_t data[64]; - int i; - - AA = A; - BB = B; - CC = C; - DD = D; - EE = E; - FF = F; - GG = G; - HH = H; - - for (i = 0; i < 16; ++i) - data[i] = in[i]; - for (i = 16; i < 64; ++i) - data[i] = sigma1(data[i-2]) + data[i-7] + - sigma0(data[i-15]) + data[i - 16]; - - for (i = 0; i < 64; i++) { - uint32_t T1, T2; - - T1 = HH + Sigma1(EE) + Ch(EE, FF, GG) + constant_256[i] + data[i]; - T2 = Sigma0(AA) + Maj(AA,BB,CC); - - HH = GG; - GG = FF; - FF = EE; - EE = DD + T1; - DD = CC; - CC = BB; - BB = AA; - AA = T1 + T2; - } - - A += AA; - B += BB; - C += CC; - D += DD; - E += EE; - F += FF; - G += GG; - H += HH; -} - -/* - * From `Performance analysis of MD5' by Joseph D. Touch - */ - -#if !defined(WORDS_BIGENDIAN) || defined(_CRAY) -/* Vector Crays doesn't have a good 32-bit type, or more precisely, - int32_t as defined by isn't 32 bits, and we don't - want to depend in being able to redefine this type. To cope with - this we have to clamp the result in some places to [0,2^32); no - need to do this on other machines. Did I say this was a mess? - */ - -#ifdef _CRAY -#define CRAYFIX(X) ((X) & 0xffffffff) -#else -#define CRAYFIX(X) (X) -#endif - -static inline uint32_t -cshift (uint32_t x, unsigned int n) -{ - x = CRAYFIX(x); - return CRAYFIX((x << n) | (x >> (32 - n))); -} - -static inline uint32_t -swap_uint32_t (uint32_t t) -{ - uint32_t temp1, temp2; - - temp1 = cshift(t, 16); - temp2 = temp1 >> 8; - temp1 &= 0x00ff00ff; - temp2 &= 0x00ff00ff; - temp1 <<= 8; - return temp1 | temp2; -} -#endif - -struct x32{ - unsigned int a:32; - unsigned int b:32; -}; - -void -SHA256_Update (SHA256_CTX *m, const void *v, size_t len) -{ - const unsigned char *p = v; - size_t old_sz = m->sz[0]; - size_t offset; - - m->sz[0] += len * 8; - if (m->sz[0] < old_sz) - ++m->sz[1]; - offset = (old_sz / 8) % 64; - while(len > 0){ - size_t l = MIN(len, 64 - offset); - memcpy(m->save + offset, p, l); - offset += l; - p += l; - len -= l; - if(offset == 64){ -#if !defined(WORDS_BIGENDIAN) || defined(_CRAY) - int i; - uint32_t current[16]; - struct x32 *u = (struct x32*)m->save; - for(i = 0; i < 8; i++){ - current[2*i+0] = swap_uint32_t(u[i].a); - current[2*i+1] = swap_uint32_t(u[i].b); - } - calc(m, current); -#else - calc(m, (uint32_t*)m->save); -#endif - offset = 0; - } - } -} - -void -SHA256_Final (void *res, SHA256_CTX *m) -{ - unsigned char zeros[72]; - unsigned offset = (m->sz[0] / 8) % 64; - unsigned int dstart = (120 - offset - 1) % 64 + 1; - - *zeros = 0x80; - memset (zeros + 1, 0, sizeof(zeros) - 1); - zeros[dstart+7] = (m->sz[0] >> 0) & 0xff; - zeros[dstart+6] = (m->sz[0] >> 8) & 0xff; - zeros[dstart+5] = (m->sz[0] >> 16) & 0xff; - zeros[dstart+4] = (m->sz[0] >> 24) & 0xff; - zeros[dstart+3] = (m->sz[1] >> 0) & 0xff; - zeros[dstart+2] = (m->sz[1] >> 8) & 0xff; - zeros[dstart+1] = (m->sz[1] >> 16) & 0xff; - zeros[dstart+0] = (m->sz[1] >> 24) & 0xff; - SHA256_Update (m, zeros, dstart + 8); - { - int i; - unsigned char *r = (unsigned char*)res; - - for (i = 0; i < 8; ++i) { - r[4*i+3] = m->counter[i] & 0xFF; - r[4*i+2] = (m->counter[i] >> 8) & 0xFF; - r[4*i+1] = (m->counter[i] >> 16) & 0xFF; - r[4*i] = (m->counter[i] >> 24) & 0xFF; - } - } -} diff --git a/source4/lib/crypto/sha256.h b/source4/lib/crypto/sha256.h deleted file mode 100644 index 4a5f2cbe94..0000000000 --- a/source4/lib/crypto/sha256.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan - * (Royal Institute of Technology, Stockholm, Sweden). - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * 3. Neither the name of the Institute nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -/* $Id: sha.h 17450 2006-05-05 11:11:43Z lha $ */ - -#ifndef HEIM_SHA_H -/* - based on heildal lib/hcrypto/sha.h. Copied to lib/crypto to avoid a link - problem. Hopefully will be removed once we solve this link problem - - (tridge) - */ -#define HEIM_SHA_H 1 - -#if 0 -/* symbol renaming */ -#define SHA1_Init hc_SHA1_Init -#define SHA1_Update hc_SHA1_Update -#define SHA1_Final hc_SHA1_Final -#define SHA256_Init hc_SHA256_Init -#define SHA256_Update hc_SHA256_Update -#define SHA256_Final hc_SHA256_Final -#endif - -/* - * SHA-1 - */ - -#define SHA_DIGEST_LENGTH 20 - -struct sha { - unsigned int sz[2]; - uint32_t counter[5]; - unsigned char save[64]; -}; - -typedef struct sha SHA_CTX; - -void SHA1_Init (struct sha *m); -void SHA1_Update (struct sha *m, const void *v, size_t len); -void SHA1_Final (void *res, struct sha *m); - -/* - * SHA-2 256 - */ - -#define SHA256_DIGEST_LENGTH 32 - -struct hc_sha256state { - unsigned int sz[2]; - uint32_t counter[8]; - unsigned char save[64]; -}; - -typedef struct hc_sha256state SHA256_CTX; - -void SHA256_Init (SHA256_CTX *); -void SHA256_Update (SHA256_CTX *, const void *, size_t); -void SHA256_Final (void *, SHA256_CTX *); - -#endif /* HEIM_SHA_H */ diff --git a/source4/lib/util/genrand.c b/source4/lib/util/genrand.c index 7df4ec4e20..cd1823a9a0 100644 --- a/source4/lib/util/genrand.c +++ b/source4/lib/util/genrand.c @@ -21,7 +21,7 @@ #include "includes.h" #include "system/filesys.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "system/locale.h" /** diff --git a/source4/libcli/auth/credentials.c b/source4/libcli/auth/credentials.c index a6cb17c12e..3c77b0836d 100644 --- a/source4/libcli/auth/credentials.c +++ b/source4/libcli/auth/credentials.c @@ -23,7 +23,7 @@ #include "includes.h" #include "system/time.h" #include "auth/auth.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "libcli/auth/libcli_auth.h" /* diff --git a/source4/libcli/auth/smbencrypt.c b/source4/libcli/auth/smbencrypt.c index b50f003b91..3af7e45002 100644 --- a/source4/libcli/auth/smbencrypt.c +++ b/source4/libcli/auth/smbencrypt.c @@ -25,7 +25,7 @@ #include "system/time.h" #include "auth/ntlmssp/ntlmssp.h" #include "auth/ntlmssp/msrpc_parse.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "libcli/auth/libcli_auth.h" #include "pstring.h" #include "param/param.h" diff --git a/source4/libcli/raw/smb_signing.c b/source4/libcli/raw/smb_signing.c index 826d7dd56b..e798f052ba 100644 --- a/source4/libcli/raw/smb_signing.c +++ b/source4/libcli/raw/smb_signing.c @@ -23,7 +23,7 @@ #include "smb.h" #include "libcli/raw/libcliraw.h" #include "libcli/raw/raw_proto.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "param/param.h" /*********************************************************** diff --git a/source4/libcli/smb2/signing.c b/source4/libcli/smb2/signing.c index de9e1e9d29..101fb00c12 100644 --- a/source4/libcli/smb2/signing.c +++ b/source4/libcli/smb2/signing.c @@ -23,7 +23,7 @@ #include "libcli/raw/libcliraw.h" #include "libcli/smb2/smb2.h" #include "libcli/smb2/smb2_calls.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" /* sign an outgoing message diff --git a/source4/libnet/libnet_passwd.c b/source4/libnet/libnet_passwd.c index 28d9ae8cbe..de2ed01abd 100644 --- a/source4/libnet/libnet_passwd.c +++ b/source4/libnet/libnet_passwd.c @@ -20,7 +20,7 @@ #include "includes.h" #include "libnet/libnet.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "libcli/auth/libcli_auth.h" #include "librpc/gen_ndr/ndr_samr_c.h" diff --git a/source4/main.mk b/source4/main.mk index 0edfa1c144..368dce9f59 100644 --- a/source4/main.mk +++ b/source4/main.mk @@ -22,7 +22,7 @@ mkinclude lib/stream/config.mk mkinclude lib/util/config.mk mkinclude lib/tdr/config.mk mkinclude lib/dbwrap/config.mk -mkinclude lib/crypto/config.mk +mkinclude ../lib/crypto/config.mk mkinclude lib/torture/config.mk mkinclude lib/basic.mk mkinclude lib/com/config.mk diff --git a/source4/ntp_signd/ntp_signd.c b/source4/ntp_signd/ntp_signd.c index c3a9a1c792..575be1e97e 100644 --- a/source4/ntp_signd/ntp_signd.c +++ b/source4/ntp_signd/ntp_signd.c @@ -34,7 +34,7 @@ #include "libcli/security/security.h" #include "lib/ldb/include/ldb.h" #include "lib/ldb/include/ldb_errors.h" -#include "lib/crypto/md5.h" +#include "../lib/crypto/md5.h" #include "system/passwd.h" /* diff --git a/source4/rpc_server/lsa/dcesrv_lsa.c b/source4/rpc_server/lsa/dcesrv_lsa.c index a1ca3b4a46..3b70f3e934 100644 --- a/source4/rpc_server/lsa/dcesrv_lsa.c +++ b/source4/rpc_server/lsa/dcesrv_lsa.c @@ -27,7 +27,7 @@ #include "auth/kerberos/kerberos.h" #include "librpc/gen_ndr/ndr_drsblobs.h" #include "librpc/gen_ndr/ndr_lsa.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" /* this type allows us to distinguish handle types diff --git a/source4/rpc_server/samr/samr_password.c b/source4/rpc_server/samr/samr_password.c index 5b8e92583b..98d998acc3 100644 --- a/source4/rpc_server/samr/samr_password.c +++ b/source4/rpc_server/samr/samr_password.c @@ -25,7 +25,7 @@ #include "rpc_server/common/common.h" #include "rpc_server/samr/dcesrv_samr.h" #include "system/time.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "dsdb/common/flags.h" #include "libcli/ldap/ldap.h" #include "dsdb/samdb/samdb.h" diff --git a/source4/torture/local/local.c b/source4/torture/local/local.c index bf53df4a11..fdefbbe131 100644 --- a/source4/torture/local/local.c +++ b/source4/torture/local/local.c @@ -23,7 +23,7 @@ #include "torture/ndr/ndr.h" #include "torture/ndr/proto.h" #include "torture/auth/proto.h" -#include "lib/crypto/test_proto.h" +#include "../lib/crypto/test_proto.h" #include "lib/registry/tests/proto.h" /* ignore me */ static struct torture_suite * diff --git a/source4/torture/rpc/dssync.c b/source4/torture/rpc/dssync.c index e9346f9605..df16c860cb 100644 --- a/source4/torture/rpc/dssync.c +++ b/source4/torture/rpc/dssync.c @@ -29,7 +29,7 @@ #include "torture/torture.h" #include "torture/ldap/proto.h" #include "libcli/auth/libcli_auth.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "auth/credentials/credentials.h" #include "libcli/auth/libcli_auth.h" #include "auth/gensec/gensec.h" diff --git a/source4/torture/rpc/lsa.c b/source4/torture/rpc/lsa.c index a13a8d8818..69bf33352b 100644 --- a/source4/torture/rpc/lsa.c +++ b/source4/torture/rpc/lsa.c @@ -29,7 +29,7 @@ #include "libcli/auth/libcli_auth.h" #include "torture/rpc/rpc.h" #include "param/param.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #define TEST_MACHINENAME "lsatestmach" static void init_lsa_String(struct lsa_String *name, const char *s) diff --git a/source4/torture/rpc/samba3rpc.c b/source4/torture/rpc/samba3rpc.c index 17342f9b86..3bbf6cf223 100644 --- a/source4/torture/rpc/samba3rpc.c +++ b/source4/torture/rpc/samba3rpc.c @@ -47,7 +47,7 @@ #include "libcli/composite/composite.h" #include "libcli/smb_composite/smb_composite.h" #include "libcli/auth/libcli_auth.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "auth/ntlmssp/ntlmssp.h" #include "libcli/security/proto.h" #include "param/param.h" diff --git a/source4/torture/rpc/samlogon.c b/source4/torture/rpc/samlogon.c index e2558ff0a9..4fbffee41e 100644 --- a/source4/torture/rpc/samlogon.c +++ b/source4/torture/rpc/samlogon.c @@ -26,7 +26,7 @@ #include "librpc/gen_ndr/ndr_netlogon_c.h" #include "librpc/gen_ndr/ndr_samr_c.h" #include "auth/auth.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "lib/cmdline/popt_common.h" #include "torture/rpc/rpc.h" #include "auth/gensec/schannel_proto.h" diff --git a/source4/torture/rpc/samr.c b/source4/torture/rpc/samr.c index 6afda6e9b5..d0aee057d3 100644 --- a/source4/torture/rpc/samr.c +++ b/source4/torture/rpc/samr.c @@ -24,7 +24,7 @@ #include "system/time.h" #include "librpc/gen_ndr/lsa.h" #include "librpc/gen_ndr/ndr_samr_c.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "libcli/auth/libcli_auth.h" #include "libcli/security/security.h" #include "torture/rpc/rpc.h" diff --git a/source4/torture/rpc/samsync.c b/source4/torture/rpc/samsync.c index 1e76de1dd2..6a02af5bb5 100644 --- a/source4/torture/rpc/samsync.c +++ b/source4/torture/rpc/samsync.c @@ -25,7 +25,7 @@ #include "torture/torture.h" #include "auth/auth.h" #include "lib/util/dlinklist.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "system/time.h" #include "torture/rpc/rpc.h" #include "auth/gensec/schannel_proto.h" diff --git a/source4/torture/rpc/testjoin.c b/source4/torture/rpc/testjoin.c index 2af8c4f872..21542e9b16 100644 --- a/source4/torture/rpc/testjoin.c +++ b/source4/torture/rpc/testjoin.c @@ -27,7 +27,7 @@ #include "includes.h" #include "torture/torture.h" #include "system/time.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "libnet/libnet.h" #include "lib/cmdline/popt_common.h" #include "lib/ldb/include/ldb.h" diff --git a/source4/torture/rpc/wkssvc.c b/source4/torture/rpc/wkssvc.c index b212a44b33..6e9937086e 100644 --- a/source4/torture/rpc/wkssvc.c +++ b/source4/torture/rpc/wkssvc.c @@ -25,7 +25,7 @@ #include "torture/rpc/rpc.h" #include "lib/cmdline/popt_common.h" #include "param/param.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" #include "libcli/auth/libcli_auth.h" #define SMBTORTURE_MACHINE_NAME "smbtrt_name" -- cgit From 45bc578664f4dae063672dde75bd442868a35992 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 24 Sep 2008 15:34:30 +0200 Subject: Use common MD5. --- source3/Makefile.in | 2 +- source3/include/includes.h | 2 +- source3/include/md5.h | 19 ---- source3/include/proto.h | 6 -- source3/lib/md5.c | 247 --------------------------------------------- 5 files changed, 2 insertions(+), 274 deletions(-) delete mode 100644 source3/include/md5.h delete mode 100644 source3/lib/md5.c diff --git a/source3/Makefile.in b/source3/Makefile.in index 333c5f3001..b20f7b1aef 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -328,7 +328,7 @@ LIB_OBJ = $(LIBSAMBAUTIL_OBJ) \ lib/substitute.o lib/fsusage.o lib/dbwrap_util.o \ lib/ms_fnmatch.o lib/select.o lib/errmap_unix.o \ lib/tallocmsg.o lib/dmallocmsg.o libsmb/smb_signing.o \ - lib/md5.o lib/hmacmd5.o lib/arc4.o lib/iconv.o \ + ../lib/crypto/md5.o lib/hmacmd5.o lib/arc4.o lib/iconv.o \ lib/pam_errors.o intl/lang_tdb.o lib/conn_tdb.o \ lib/adt_tree.o lib/gencache.o \ lib/module.o lib/events.o lib/ldap_escape.o @CHARSET_STATIC@ \ diff --git a/source3/include/includes.h b/source3/include/includes.h index fbf5ca6cd0..5543475488 100644 --- a/source3/include/includes.h +++ b/source3/include/includes.h @@ -686,7 +686,7 @@ typedef char fstring[FSTRING_LEN]; #include "authdata.h" #include "msdfs.h" #include "rap.h" -#include "md5.h" +#include "../lib/crypto/md5.h" #include "hmacmd5.h" #include "ntlmssp.h" #include "auth.h" diff --git a/source3/include/md5.h b/source3/include/md5.h deleted file mode 100644 index e4cd08ed5e..0000000000 --- a/source3/include/md5.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef MD5_H -#define MD5_H -#ifndef HEADER_MD5_H -/* Try to avoid clashes with OpenSSL */ -#define HEADER_MD5_H -#endif - -struct MD5Context { - uint32 buf[4]; - uint32 bits[2]; - unsigned char in[64]; -}; - -void MD5Init(struct MD5Context *context); -void MD5Update(struct MD5Context *context, unsigned char const *buf, - unsigned len); -void MD5Final(unsigned char digest[16], struct MD5Context *context); - -#endif /* !MD5_H */ diff --git a/source3/include/proto.h b/source3/include/proto.h index 4a51835f3d..d572a0c254 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -649,12 +649,6 @@ char *escape_rdn_val_string_alloc(const char *s); void mdfour(unsigned char *out, const unsigned char *in, int n); -/* The following definitions come from lib/md5.c */ - -void MD5Init(struct MD5Context *ctx); -void MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len); -void MD5Final(unsigned char digest[16], struct MD5Context *ctx); - /* The following definitions come from lib/module.c */ NTSTATUS smb_load_module(const char *module_name); diff --git a/source3/lib/md5.c b/source3/lib/md5.c deleted file mode 100644 index 2121b17047..0000000000 --- a/source3/lib/md5.c +++ /dev/null @@ -1,247 +0,0 @@ -/* - * This code implements the MD5 message-digest algorithm. - * The algorithm is due to Ron Rivest. This code was - * written by Colin Plumb in 1993, no copyright is claimed. - * This code is in the public domain; do with it what you wish. - * - * Equivalent code is available from RSA Data Security, Inc. - * This code has been tested against that, and is equivalent, - * except that you don't need to include two pages of legalese - * with every copy. - * - * To compute the message digest of a chunk of bytes, declare an - * MD5Context structure, pass it to MD5Init, call MD5Update as - * needed on buffers full of bytes, and then call MD5Final, which - * will fill a supplied 16-byte array with the digest. - */ - -/* This code slightly modified to fit into Samba by - abartlet@samba.org Jun 2001 */ - -#include "includes.h" - -#include "md5.h" - -static void MD5Transform(uint32 buf[4], uint32 const in[16]); - -/* - * Note: this code is harmless on little-endian machines. - */ -static void byteReverse(unsigned char *buf, unsigned longs) -{ - uint32 t; - do { - t = (uint32) ((unsigned) buf[3] << 8 | buf[2]) << 16 | - ((unsigned) buf[1] << 8 | buf[0]); - *(uint32 *) buf = t; - buf += 4; - } while (--longs); -} - -/* - * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious - * initialization constants. - */ -void MD5Init(struct MD5Context *ctx) -{ - ctx->buf[0] = 0x67452301; - ctx->buf[1] = 0xefcdab89; - ctx->buf[2] = 0x98badcfe; - ctx->buf[3] = 0x10325476; - - ctx->bits[0] = 0; - ctx->bits[1] = 0; -} - -/* - * Update context to reflect the concatenation of another buffer full - * of bytes. - */ -void MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len) -{ - register uint32 t; - - /* Update bitcount */ - - t = ctx->bits[0]; - if ((ctx->bits[0] = t + ((uint32) len << 3)) < t) - ctx->bits[1]++; /* Carry from low to high */ - ctx->bits[1] += len >> 29; - - t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ - - /* Handle any leading odd-sized chunks */ - - if (t) { - unsigned char *p = (unsigned char *) ctx->in + t; - - t = 64 - t; - if (len < t) { - memmove(p, buf, len); - return; - } - memmove(p, buf, t); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (uint32 *) ctx->in); - buf += t; - len -= t; - } - /* Process data in 64-byte chunks */ - - while (len >= 64) { - memmove(ctx->in, buf, 64); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (uint32 *) ctx->in); - buf += 64; - len -= 64; - } - - /* Handle any remaining bytes of data. */ - - memmove(ctx->in, buf, len); -} - -/* - * Final wrapup - pad to 64-byte boundary with the bit pattern - * 1 0* (64-bit count of bits processed, MSB-first) - */ -void MD5Final(unsigned char digest[16], struct MD5Context *ctx) -{ - unsigned int count; - unsigned char *p; - - /* Compute number of bytes mod 64 */ - count = (ctx->bits[0] >> 3) & 0x3F; - - /* Set the first char of padding to 0x80. This is safe since there is - always at least one byte free */ - p = ctx->in + count; - *p++ = 0x80; - - /* Bytes of padding needed to make 64 bytes */ - count = 64 - 1 - count; - - /* Pad out to 56 mod 64 */ - if (count < 8) { - /* Two lots of padding: Pad the first block to 64 bytes */ - memset(p, 0, count); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (uint32 *) ctx->in); - - /* Now fill the next block with 56 bytes */ - memset(ctx->in, 0, 56); - } else { - /* Pad block to 56 bytes */ - memset(p, 0, count - 8); - } - byteReverse(ctx->in, 14); - - /* Append length in bits and transform */ - ((uint32 *) ctx->in)[14] = ctx->bits[0]; - ((uint32 *) ctx->in)[15] = ctx->bits[1]; - - MD5Transform(ctx->buf, (uint32 *) ctx->in); - byteReverse((unsigned char *) ctx->buf, 4); - memmove(digest, ctx->buf, 16); - memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */ -} - -/* The four core functions - F1 is optimized somewhat */ - -/* #define F1(x, y, z) (x & y | ~x & z) */ -#define F1(x, y, z) (z ^ (x & (y ^ z))) -#define F2(x, y, z) F1(z, x, y) -#define F3(x, y, z) (x ^ y ^ z) -#define F4(x, y, z) (y ^ (x | ~z)) - -/* This is the central step in the MD5 algorithm. */ -#define MD5STEP(f, w, x, y, z, data, s) \ - ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) - -/* - * The core of the MD5 algorithm, this alters an existing MD5 hash to - * reflect the addition of 16 longwords of new data. MD5Update blocks - * the data and converts bytes into longwords for this routine. - */ -static void MD5Transform(uint32 buf[4], uint32 const in[16]) -{ - register uint32 a, b, c, d; - - a = buf[0]; - b = buf[1]; - c = buf[2]; - d = buf[3]; - - MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); - MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); - MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); - MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); - MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); - MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); - MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); - MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); - MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); - MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); - MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); - MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); - MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); - MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); - MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); - MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); - - MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); - MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); - MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); - MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); - MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); - MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); - MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); - MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); - MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); - MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); - MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); - MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); - MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); - MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); - MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); - MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); - - MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); - MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); - MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); - MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); - MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); - MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); - MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); - MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); - MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); - MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); - MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); - MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); - MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); - MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); - MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); - MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); - - MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); - MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); - MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); - MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); - MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); - MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); - MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); - MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); - MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); - MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); - MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); - MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); - MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); - MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); - MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); - MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); - - buf[0] += a; - buf[1] += b; - buf[2] += c; - buf[3] += d; -} -- cgit From 5709ded3ef75c48f807273eaa36bb0522e7f7b46 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 24 Sep 2008 15:37:15 +0200 Subject: Use common md4 implementation. --- source3/Makefile.in | 2 +- source3/lib/md4.c | 174 ---------------------------------------------------- 2 files changed, 1 insertion(+), 175 deletions(-) delete mode 100644 source3/lib/md4.c diff --git a/source3/Makefile.in b/source3/Makefile.in index b20f7b1aef..eb9f206298 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -315,7 +315,7 @@ LIB_OBJ = $(LIBSAMBAUTIL_OBJ) \ lib/async_sock.o \ $(TDB_LIB_OBJ) \ $(VERSION_OBJ) lib/charcnv.o lib/debug.o lib/fault.o \ - lib/interface.o lib/md4.o \ + lib/interface.o ../lib/crypto/md4.o \ lib/pidfile.o \ lib/signal.o lib/system.o lib/sendfile.o lib/recvfile.o lib/time.o \ lib/ufc.o lib/genrand.o lib/username.o \ diff --git a/source3/lib/md4.c b/source3/lib/md4.c deleted file mode 100644 index bae0091e36..0000000000 --- a/source3/lib/md4.c +++ /dev/null @@ -1,174 +0,0 @@ -/* - Unix SMB/CIFS implementation. - a implementation of MD4 designed for use in the SMB authentication protocol - Copyright (C) Andrew Tridgell 1997-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 . -*/ - -#include "includes.h" - -/* NOTE: This code makes no attempt to be fast! - - It assumes that a int is at least 32 bits long -*/ - -#if 0 -static uint32 A, B, C, D; -#else -#define A (state[0]) -#define B (state[1]) -#define C (state[2]) -#define D (state[3]) -#endif - -static uint32 F(uint32 X, uint32 Y, uint32 Z) -{ - return (X&Y) | ((~X)&Z); -} - -static uint32 G(uint32 X, uint32 Y, uint32 Z) -{ - return (X&Y) | (X&Z) | (Y&Z); -} - -static uint32 H(uint32 X, uint32 Y, uint32 Z) -{ - return X^Y^Z; -} - -static uint32 lshift(uint32 x, int s) -{ - x &= 0xFFFFFFFF; - return ((x<>(32-s)); -} - -#define ROUND1(a,b,c,d,k,s) a = lshift(a + F(b,c,d) + X[k], s) -#define ROUND2(a,b,c,d,k,s) a = lshift(a + G(b,c,d) + X[k] + (uint32)0x5A827999,s) -#define ROUND3(a,b,c,d,k,s) a = lshift(a + H(b,c,d) + X[k] + (uint32)0x6ED9EBA1,s) - -/* this applies md4 to 64 byte chunks */ -static void mdfour64(uint32_t *state, uint32 *M) -{ - int j; - uint32 AA, BB, CC, DD; - uint32 X[16]; - - for (j=0;j<16;j++) - X[j] = M[j]; - - AA = A; BB = B; CC = C; DD = D; - - ROUND1(A,B,C,D, 0, 3); ROUND1(D,A,B,C, 1, 7); - ROUND1(C,D,A,B, 2, 11); ROUND1(B,C,D,A, 3, 19); - ROUND1(A,B,C,D, 4, 3); ROUND1(D,A,B,C, 5, 7); - ROUND1(C,D,A,B, 6, 11); ROUND1(B,C,D,A, 7, 19); - ROUND1(A,B,C,D, 8, 3); ROUND1(D,A,B,C, 9, 7); - ROUND1(C,D,A,B, 10, 11); ROUND1(B,C,D,A, 11, 19); - ROUND1(A,B,C,D, 12, 3); ROUND1(D,A,B,C, 13, 7); - ROUND1(C,D,A,B, 14, 11); ROUND1(B,C,D,A, 15, 19); - - ROUND2(A,B,C,D, 0, 3); ROUND2(D,A,B,C, 4, 5); - ROUND2(C,D,A,B, 8, 9); ROUND2(B,C,D,A, 12, 13); - ROUND2(A,B,C,D, 1, 3); ROUND2(D,A,B,C, 5, 5); - ROUND2(C,D,A,B, 9, 9); ROUND2(B,C,D,A, 13, 13); - ROUND2(A,B,C,D, 2, 3); ROUND2(D,A,B,C, 6, 5); - ROUND2(C,D,A,B, 10, 9); ROUND2(B,C,D,A, 14, 13); - ROUND2(A,B,C,D, 3, 3); ROUND2(D,A,B,C, 7, 5); - ROUND2(C,D,A,B, 11, 9); ROUND2(B,C,D,A, 15, 13); - - ROUND3(A,B,C,D, 0, 3); ROUND3(D,A,B,C, 8, 9); - ROUND3(C,D,A,B, 4, 11); ROUND3(B,C,D,A, 12, 15); - ROUND3(A,B,C,D, 2, 3); ROUND3(D,A,B,C, 10, 9); - ROUND3(C,D,A,B, 6, 11); ROUND3(B,C,D,A, 14, 15); - ROUND3(A,B,C,D, 1, 3); ROUND3(D,A,B,C, 9, 9); - ROUND3(C,D,A,B, 5, 11); ROUND3(B,C,D,A, 13, 15); - ROUND3(A,B,C,D, 3, 3); ROUND3(D,A,B,C, 11, 9); - ROUND3(C,D,A,B, 7, 11); ROUND3(B,C,D,A, 15, 15); - - A += AA; B += BB; C += CC; D += DD; - - A &= 0xFFFFFFFF; B &= 0xFFFFFFFF; - C &= 0xFFFFFFFF; D &= 0xFFFFFFFF; - - for (j=0;j<16;j++) - X[j] = 0; -} - -static void copy64(uint32 *M, const unsigned char *in) -{ - int i; - - for (i=0;i<16;i++) - M[i] = (in[i*4+3]<<24) | (in[i*4+2]<<16) | - (in[i*4+1]<<8) | (in[i*4+0]<<0); -} - -static void copy4(unsigned char *out, uint32 x) -{ - out[0] = x&0xFF; - out[1] = (x>>8)&0xFF; - out[2] = (x>>16)&0xFF; - out[3] = (x>>24)&0xFF; -} - -/* produce a md4 message digest from data of length n bytes */ -void mdfour(unsigned char *out, const unsigned char *in, int n) -{ - unsigned char buf[128]; - uint32 M[16]; - uint32 state[4]; - uint32 b = n * 8; - int i; - - A = 0x67452301; - B = 0xefcdab89; - C = 0x98badcfe; - D = 0x10325476; - - while (n > 64) { - copy64(M, in); - mdfour64(state, M); - in += 64; - n -= 64; - } - - for (i=0;i<128;i++) - buf[i] = 0; - memcpy(buf, in, n); - buf[n] = 0x80; - - if (n <= 55) { - copy4(buf+56, b); - copy64(M, buf); - mdfour64(state, M); - } else { - copy4(buf+120, b); - copy64(M, buf); - mdfour64(state, M); - copy64(M, buf+64); - mdfour64(state, M); - } - - for (i=0;i<128;i++) - buf[i] = 0; - copy64(M, buf); - - copy4(out, A); - copy4(out+4, B); - copy4(out+8, C); - copy4(out+12, D); -} - - -- cgit From 2413a7200623855b93946d44bcdb949e2dc170a0 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 24 Sep 2008 15:44:34 +0200 Subject: Use shared copy of hmac5 implementation. --- lib/crypto/hmacmd5.c | 2 +- lib/crypto/hmacmd5.h | 1 + source3/Makefile.in | 2 +- source3/include/hmacmd5.h | 29 ---------- source3/include/includes.h | 2 +- source3/include/proto.h | 10 ---- source3/lib/hmacmd5.c | 135 --------------------------------------------- 7 files changed, 4 insertions(+), 177 deletions(-) delete mode 100644 source3/include/hmacmd5.h delete mode 100644 source3/lib/hmacmd5.c diff --git a/lib/crypto/hmacmd5.c b/lib/crypto/hmacmd5.c index 3a9ec38a27..0c8d1ab598 100644 --- a/lib/crypto/hmacmd5.c +++ b/lib/crypto/hmacmd5.c @@ -23,7 +23,7 @@ */ #include "includes.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/hmacmd5.h" /*********************************************************************** the rfc 2104 version of hmac_md5 initialisation. diff --git a/lib/crypto/hmacmd5.h b/lib/crypto/hmacmd5.h index 5769737fcd..d649906bb4 100644 --- a/lib/crypto/hmacmd5.h +++ b/lib/crypto/hmacmd5.h @@ -19,6 +19,7 @@ */ #ifndef _HMAC_MD5_H +#define _HMAC_MD5_H typedef struct { diff --git a/source3/Makefile.in b/source3/Makefile.in index eb9f206298..20adeeb222 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -328,7 +328,7 @@ LIB_OBJ = $(LIBSAMBAUTIL_OBJ) \ lib/substitute.o lib/fsusage.o lib/dbwrap_util.o \ lib/ms_fnmatch.o lib/select.o lib/errmap_unix.o \ lib/tallocmsg.o lib/dmallocmsg.o libsmb/smb_signing.o \ - ../lib/crypto/md5.o lib/hmacmd5.o lib/arc4.o lib/iconv.o \ + ../lib/crypto/md5.o ../lib/crypto/hmacmd5.o lib/arc4.o lib/iconv.o \ lib/pam_errors.o intl/lang_tdb.o lib/conn_tdb.o \ lib/adt_tree.o lib/gencache.o \ lib/module.o lib/events.o lib/ldap_escape.o @CHARSET_STATIC@ \ diff --git a/source3/include/hmacmd5.h b/source3/include/hmacmd5.h deleted file mode 100644 index ae588fb889..0000000000 --- a/source3/include/hmacmd5.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - Unix SMB/CIFS implementation. - Interface header: Scheduler service - Copyright (C) Luke Kenneth Casson Leighton 1996-1999 - Copyright (C) Andrew Tridgell 1992-1999 - - 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 . -*/ - -#ifndef _HMAC_MD5_H - -typedef struct { - struct MD5Context ctx; - unsigned char k_ipad[65]; - unsigned char k_opad[65]; -} HMACMD5Context; - -#endif /* _HMAC_MD5_H */ diff --git a/source3/include/includes.h b/source3/include/includes.h index 5543475488..de50eab8c5 100644 --- a/source3/include/includes.h +++ b/source3/include/includes.h @@ -687,7 +687,7 @@ typedef char fstring[FSTRING_LEN]; #include "msdfs.h" #include "rap.h" #include "../lib/crypto/md5.h" -#include "hmacmd5.h" +#include "../lib/crypto/hmacmd5.h" #include "ntlmssp.h" #include "auth.h" #include "ntdomain.h" diff --git a/source3/include/proto.h b/source3/include/proto.h index d572a0c254..a5f43aad4c 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -596,16 +596,6 @@ void set_need_random_reseed(void); void generate_random_buffer( unsigned char *out, int len); char *generate_random_str(size_t len); -/* The following definitions come from lib/hmacmd5.c */ - -void hmac_md5_init_rfc2104(const unsigned char *key, int key_len, HMACMD5Context *ctx); -void hmac_md5_init_limK_to_64(const unsigned char* key, int key_len, - HMACMD5Context *ctx); -void hmac_md5_update(const unsigned char *text, int text_len, HMACMD5Context *ctx); -void hmac_md5_final(unsigned char *digest, HMACMD5Context *ctx); -void hmac_md5( unsigned char key[16], const unsigned char *data, int data_len, - unsigned char *digest); - /* The following definitions come from lib/iconv.c */ NTSTATUS smb_register_charset(struct charset_functions *funcs) ; diff --git a/source3/lib/hmacmd5.c b/source3/lib/hmacmd5.c deleted file mode 100644 index 86db3aa236..0000000000 --- a/source3/lib/hmacmd5.c +++ /dev/null @@ -1,135 +0,0 @@ -/* - Unix SMB/CIFS implementation. - HMAC MD5 code for use in NTLMv2 - Copyright (C) Luke Kenneth Casson Leighton 1996-2000 - Copyright (C) Andrew Tridgell 1992-2000 - - 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 . -*/ - -/* taken direct from rfc2104 implementation and modified for suitable use - * for ntlmv2. - */ - -#include "includes.h" - -/*********************************************************************** - the rfc 2104 version of hmac_md5 initialisation. -***********************************************************************/ - -void hmac_md5_init_rfc2104(const unsigned char *key, int key_len, HMACMD5Context *ctx) -{ - int i; - unsigned char tk[16]; - - /* if key is longer than 64 bytes reset it to key=MD5(key) */ - if (key_len > 64) { - struct MD5Context tctx; - - MD5Init(&tctx); - MD5Update(&tctx, key, key_len); - MD5Final(tk, &tctx); - - key = tk; - key_len = 16; - } - - /* start out by storing key in pads */ - ZERO_STRUCT(ctx->k_ipad); - ZERO_STRUCT(ctx->k_opad); - memcpy( ctx->k_ipad, key, key_len); - memcpy( ctx->k_opad, key, key_len); - - /* XOR key with ipad and opad values */ - for (i=0; i<64; i++) { - ctx->k_ipad[i] ^= 0x36; - ctx->k_opad[i] ^= 0x5c; - } - - MD5Init(&ctx->ctx); - MD5Update(&ctx->ctx, ctx->k_ipad, 64); -} - -/*********************************************************************** - the microsoft version of hmac_md5 initialisation. -***********************************************************************/ - -void hmac_md5_init_limK_to_64(const unsigned char* key, int key_len, - HMACMD5Context *ctx) -{ - int i; - - /* if key is longer than 64 bytes truncate it */ - if (key_len > 64) { - key_len = 64; - } - - /* start out by storing key in pads */ - ZERO_STRUCT(ctx->k_ipad); - ZERO_STRUCT(ctx->k_opad); - memcpy( ctx->k_ipad, key, key_len); - memcpy( ctx->k_opad, key, key_len); - - /* XOR key with ipad and opad values */ - for (i=0; i<64; i++) { - ctx->k_ipad[i] ^= 0x36; - ctx->k_opad[i] ^= 0x5c; - } - - MD5Init(&ctx->ctx); - MD5Update(&ctx->ctx, ctx->k_ipad, 64); -} - -/*********************************************************************** - update hmac_md5 "inner" buffer -***********************************************************************/ - -void hmac_md5_update(const unsigned char *text, int text_len, HMACMD5Context *ctx) -{ - MD5Update(&ctx->ctx, text, text_len); /* then text of datagram */ -} - -/*********************************************************************** - finish off hmac_md5 "inner" buffer and generate outer one. -***********************************************************************/ -void hmac_md5_final(unsigned char *digest, HMACMD5Context *ctx) - -{ - struct MD5Context ctx_o; - - MD5Final(digest, &ctx->ctx); - - MD5Init(&ctx_o); - MD5Update(&ctx_o, ctx->k_opad, 64); - MD5Update(&ctx_o, digest, 16); - MD5Final(digest, &ctx_o); -} - -/*********************************************************** - single function to calculate an HMAC MD5 digest from data. - use the microsoft hmacmd5 init method because the key is 16 bytes. -************************************************************/ - -void hmac_md5( unsigned char key[16], const unsigned char *data, int data_len, - unsigned char *digest) -{ - HMACMD5Context ctx; - hmac_md5_init_limK_to_64(key, 16, &ctx); - if (data_len != 0) - { - hmac_md5_update(data, data_len, &ctx); - } - hmac_md5_final(digest, &ctx); -} - -- cgit From 3023a56b64590df9672a084b07990836e675409f Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 24 Sep 2008 16:10:34 +0200 Subject: Clean .o files in lib/ and libcli/ too. --- source4/Makefile | 3 +++ 1 file changed, 3 insertions(+) diff --git a/source4/Makefile b/source4/Makefile index 3630adce56..813f0cedd4 100644 --- a/source4/Makefile +++ b/source4/Makefile @@ -132,6 +132,9 @@ else include $(srcdir)/static_deps.mk endif +clean:: + @find ../lib ../libcli -name '*.o' -o -name '*.hd' | xargs rm -f + DEFAULT_HEADERS = $(srcdir)/lib/util/dlinklist.h \ $(srcdir)/version.h -- cgit From e3ef8803ee46710d080095e4a76e25d3280d6d8b Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 24 Sep 2008 16:10:53 +0200 Subject: Fix include paths. --- lib/crypto/arcfour.c | 2 +- lib/crypto/hmacmd5.h | 2 ++ lib/crypto/hmacmd5test.c | 2 +- lib/crypto/hmacsha256.c | 2 +- lib/crypto/md4test.c | 2 +- lib/crypto/md5test.c | 2 +- 6 files changed, 7 insertions(+), 5 deletions(-) diff --git a/lib/crypto/arcfour.c b/lib/crypto/arcfour.c index 94196fa1ee..c57e05d0e9 100644 --- a/lib/crypto/arcfour.c +++ b/lib/crypto/arcfour.c @@ -20,7 +20,7 @@ */ #include "includes.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/arcfour.h" /* initialise the arcfour sbox with key */ _PUBLIC_ void arcfour_init(struct arcfour_state *state, const DATA_BLOB *key) diff --git a/lib/crypto/hmacmd5.h b/lib/crypto/hmacmd5.h index d649906bb4..91b8ca586c 100644 --- a/lib/crypto/hmacmd5.h +++ b/lib/crypto/hmacmd5.h @@ -21,6 +21,8 @@ #ifndef _HMAC_MD5_H #define _HMAC_MD5_H +#include "../lib/crypto/md5.h" + typedef struct { struct MD5Context ctx; diff --git a/lib/crypto/hmacmd5test.c b/lib/crypto/hmacmd5test.c index 07ed54c98d..0a98404eda 100644 --- a/lib/crypto/hmacmd5test.c +++ b/lib/crypto/hmacmd5test.c @@ -17,7 +17,7 @@ along with this program. If not, see . */ #include "includes.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" struct torture_context; diff --git a/lib/crypto/hmacsha256.c b/lib/crypto/hmacsha256.c index 6b0af9ee83..53d4fe3883 100644 --- a/lib/crypto/hmacsha256.c +++ b/lib/crypto/hmacsha256.c @@ -27,7 +27,7 @@ */ #include "includes.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" /*********************************************************************** the rfc 2104/2202 version of hmac_sha256 initialisation. diff --git a/lib/crypto/md4test.c b/lib/crypto/md4test.c index 5e0451973c..dddf9e61a0 100644 --- a/lib/crypto/md4test.c +++ b/lib/crypto/md4test.c @@ -18,7 +18,7 @@ */ #include "includes.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" struct torture_context; diff --git a/lib/crypto/md5test.c b/lib/crypto/md5test.c index 702e0fcf41..1244dca753 100644 --- a/lib/crypto/md5test.c +++ b/lib/crypto/md5test.c @@ -18,7 +18,7 @@ */ #include "includes.h" -#include "lib/crypto/crypto.h" +#include "../lib/crypto/crypto.h" struct torture_context; -- cgit From d2062ab74f7684f8b6975a7415fac23389851278 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 24 Sep 2008 16:46:02 +0200 Subject: Use common crc32 implementation. --- source3/Makefile.in | 2 +- source3/include/includes.h | 1 + source3/include/proto.h | 4 -- source3/lib/crc32.c | 103 ------------------------------------------ source3/libsmb/ntlmssp_sign.c | 4 +- source3/libsmb/smbencrypt.c | 2 +- 6 files changed, 5 insertions(+), 111 deletions(-) delete mode 100644 source3/lib/crc32.c diff --git a/source3/Makefile.in b/source3/Makefile.in index 20adeeb222..9e0a1179f3 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -320,7 +320,7 @@ LIB_OBJ = $(LIBSAMBAUTIL_OBJ) \ lib/signal.o lib/system.o lib/sendfile.o lib/recvfile.o lib/time.o \ lib/ufc.o lib/genrand.o lib/username.o \ lib/util_pw.o lib/access.o lib/smbrun.o \ - lib/bitmap.o lib/crc32.o lib/dprintf.o \ + lib/bitmap.o ../lib/crypto/crc32.o lib/dprintf.o \ lib/xfile.o lib/wins_srv.o $(UTIL_REG_OBJ) \ lib/util_str.o lib/clobber.o lib/util_sid.o lib/util_uuid.o \ lib/util_unistr.o lib/util_file.o lib/data_blob.o \ diff --git a/source3/include/includes.h b/source3/include/includes.h index de50eab8c5..79495a7ecf 100644 --- a/source3/include/includes.h +++ b/source3/include/includes.h @@ -687,6 +687,7 @@ typedef char fstring[FSTRING_LEN]; #include "msdfs.h" #include "rap.h" #include "../lib/crypto/md5.h" +#include "../lib/crypto/crc32.h" #include "../lib/crypto/hmacmd5.h" #include "ntlmssp.h" #include "auth.h" diff --git a/source3/include/proto.h b/source3/include/proto.h index a5f43aad4c..b1c4d2e5d9 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -437,10 +437,6 @@ int connections_forall(int (*fn)(struct db_record *rec, void *private_data); bool connections_init(bool rw); -/* The following definitions come from lib/crc32.c */ - -uint32 crc32_calc_buffer(const char *buf, size_t size); - /* The following definitions come from lib/data_blob.c */ DATA_BLOB data_blob(const void *p, size_t length); diff --git a/source3/lib/crc32.c b/source3/lib/crc32.c deleted file mode 100644 index a4ae90c469..0000000000 --- a/source3/lib/crc32.c +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or - * code or tables extracted from it, as desired without restriction. - * - * First, the polynomial itself and its table of feedback terms. The - * polynomial is - * X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0 - * - * Note that we take it "backwards" and put the highest-order term in - * the lowest-order bit. The X^32 term is "implied"; the LSB is the - * X^31 term, etc. The X^0 term (usually shown as "+1") results in - * the MSB being 1 - * - * Note that the usual hardware shift register implementation, which - * is what we're using (we're merely optimizing it by doing eight-bit - * chunks at a time) shifts bits into the lowest-order term. In our - * implementation, that means shifting towards the right. Why do we - * do it this way? Because the calculated CRC must be transmitted in - * order from highest-order term to lowest-order term. UARTs transmit - * characters in order from LSB to MSB. By storing the CRC this way - * we hand it to the UART in the order low-byte to high-byte; the UART - * sends each low-bit to hight-bit; and the result is transmission bit - * by bit from highest- to lowest-order term without requiring any bit - * shuffling on our part. Reception works similarly - * - * The feedback terms table consists of 256, 32-bit entries. Notes - * - * The table can be generated at runtime if desired; code to do so - * is shown later. It might not be obvious, but the feedback - * terms simply represent the results of eight shift/xor opera - * tions for all combinations of data and CRC register values - * - * The values must be right-shifted by eight bits by the "updcrc - * logic; the shift must be unsigned (bring in zeroes). On some - * hardware you could probably optimize the shift in assembler by - * using byte-swap instructions - * polynomial $edb88320 - * - * - * CRC32 code derived from work by Gary S. Brown. - */ - -#include "includes.h" - -static const uint32 crc32_tab[] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d -}; - -uint32 crc32_calc_buffer(const char *buf, size_t size) -{ - const unsigned char *p; - uint32 crc; - - p = (const unsigned char *)buf; - crc = ~0U; - - while (size--) - crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8); - - return crc ^ ~0U; -} diff --git a/source3/libsmb/ntlmssp_sign.c b/source3/libsmb/ntlmssp_sign.c index 8413c8066b..1abdf61b7f 100644 --- a/source3/libsmb/ntlmssp_sign.c +++ b/source3/libsmb/ntlmssp_sign.c @@ -117,7 +117,7 @@ static NTSTATUS ntlmssp_make_packet_signature(NTLMSSP_STATE *ntlmssp_state, } else { uint32 crc; - crc = crc32_calc_buffer((const char *)data, length); + crc = crc32_calc_buffer(data, length); if (!msrpc_gen(sig, "dddd", NTLMSSP_SIGN_VERSION, 0, crc, ntlmssp_state->ntlmv1_seq_num)) { return NT_STATUS_NO_MEMORY; } @@ -265,7 +265,7 @@ NTSTATUS ntlmssp_seal_packet(NTLMSSP_STATE *ntlmssp_state, } } else { uint32 crc; - crc = crc32_calc_buffer((const char *)data, length); + crc = crc32_calc_buffer(data, length); if (!msrpc_gen(sig, "dddd", NTLMSSP_SIGN_VERSION, 0, crc, ntlmssp_state->ntlmv1_seq_num)) { return NT_STATUS_NO_MEMORY; } diff --git a/source3/libsmb/smbencrypt.c b/source3/libsmb/smbencrypt.c index 0742976635..05fd808a32 100644 --- a/source3/libsmb/smbencrypt.c +++ b/source3/libsmb/smbencrypt.c @@ -847,7 +847,7 @@ DATA_BLOB decrypt_drsuapi_blob(TALLOC_CTX *mem_ctx, * of the remaining bytes */ crc32_given = IVAL(dec_buffer.data, 0); - crc32_calc = crc32_calc_buffer((const char *)dec_buffer.data + 4 , dec_buffer.length - 4); + crc32_calc = crc32_calc_buffer(dec_buffer.data + 4 , dec_buffer.length - 4); if (crc32_given != crc32_calc) { DEBUG(1,("CRC32: given[0x%08X] calc[0x%08X]\n", crc32_given, crc32_calc)); -- cgit From f10d8b84159b5708c1dcf854758cdbd18b2bc033 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 24 Sep 2008 18:49:58 +0200 Subject: Add separate header file for arcfour. --- lib/crypto/arcfour.h | 15 +++++++++++++++ lib/crypto/crypto.h | 11 +---------- 2 files changed, 16 insertions(+), 10 deletions(-) create mode 100644 lib/crypto/arcfour.h diff --git a/lib/crypto/arcfour.h b/lib/crypto/arcfour.h new file mode 100644 index 0000000000..501b3f2fab --- /dev/null +++ b/lib/crypto/arcfour.h @@ -0,0 +1,15 @@ +#ifndef ARCFOUR_HEADER_H +#define ARCFOUR_HEADER_H + +struct arcfour_state { + uint8_t sbox[256]; + uint8_t index_i; + uint8_t index_j; +}; + +void arcfour_init(struct arcfour_state *state, const DATA_BLOB *key); +void arcfour_crypt_sbox(struct arcfour_state *state, uint8_t *data, int len); +void arcfour_crypt_blob(uint8_t *data, int len, const DATA_BLOB *key); +void arcfour_crypt(uint8_t *data, const uint8_t keystr[16], int len); + +#endif /* ARCFOUR_HEADER_H */ diff --git a/lib/crypto/crypto.h b/lib/crypto/crypto.h index 9cb16ad344..0a43cbe7d4 100644 --- a/lib/crypto/crypto.h +++ b/lib/crypto/crypto.h @@ -23,15 +23,6 @@ #include "../lib/crypto/hmacmd5.h" #include "../lib/crypto/sha256.h" #include "../lib/crypto/hmacsha256.h" +#include "../lib/crypto/arcfour.h" -struct arcfour_state { - uint8_t sbox[256]; - uint8_t index_i; - uint8_t index_j; -}; - -void arcfour_init(struct arcfour_state *state, const DATA_BLOB *key); -void arcfour_crypt_sbox(struct arcfour_state *state, uint8_t *data, int len); -void arcfour_crypt_blob(uint8_t *data, int len, const DATA_BLOB *key); -void arcfour_crypt(uint8_t *data, const uint8_t keystr[16], int len); -- cgit From 291ca9384345d8c674a96f3671d44ba09af8b787 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 24 Sep 2008 19:27:09 +0200 Subject: Use loadparm since it's required by some modules. --- source4/dsdb/samdb/ldb_modules/tests/samba3sam.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py index 2ca5b80c67..882376cb09 100644 --- a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py +++ b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py @@ -26,7 +26,7 @@ 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 datadir = os.path.join(os.path.dirname(__file__), "../../../../../testdata/samba3") @@ -76,7 +76,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): @@ -117,14 +117,14 @@ 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""" @@ -287,13 +287,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.""" -- cgit From cf1935817fce0d6c7f4d2797c18f8c116220abd4 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Tue, 9 Sep 2008 17:06:13 +0200 Subject: Cosmetic corrections for the DSDB module This commit applies some cosmetic corrections for the DSDB (Directory Server Database). --- source4/dsdb/samdb/ldb_modules/kludge_acl.c | 4 ++-- source4/dsdb/samdb/ldb_modules/proxy.c | 12 ++++++------ source4/dsdb/samdb/ldb_modules/repl_meta_data.c | 14 +++++++------- source4/dsdb/samdb/ldb_modules/schema_fsmo.c | 2 +- source4/lib/ldb-samba/ldif_handlers.c | 2 +- source4/lib/ldb_wrap.c | 2 +- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/kludge_acl.c b/source4/dsdb/samdb/ldb_modules/kludge_acl.c index 6836f95873..11e2b7ade9 100644 --- a/source4/dsdb/samdb/ldb_modules/kludge_acl.c +++ b/source4/dsdb/samdb/ldb_modules/kludge_acl.c @@ -142,7 +142,7 @@ static int kludge_acl_allowedAttributes(struct ldb_context *ldb, struct ldb_mess ldb_msg_add_string(msg, attrName, attr_list[i]); } talloc_free(mem_ctx); - return 0; + return LDB_SUCCESS; } /* read all objectClasses */ @@ -201,7 +201,7 @@ static int kludge_acl_childClasses(struct ldb_context *ldb, struct ldb_message * } } - return 0; + return LDB_SUCCESS; } diff --git a/source4/dsdb/samdb/ldb_modules/proxy.c b/source4/dsdb/samdb/ldb_modules/proxy.c index d0a315e45a..7aa78e98a9 100644 --- a/source4/dsdb/samdb/ldb_modules/proxy.c +++ b/source4/dsdb/samdb/ldb_modules/proxy.c @@ -66,7 +66,7 @@ static int load_proxy_info(struct ldb_module *module) /* see if we have already loaded it */ if (proxy->upstream != NULL) { - return 0; + return LDB_SUCCESS; } dn = ldb_dn_new(proxy, module->ldb, "@PROXYINFO"); @@ -145,7 +145,7 @@ static int load_proxy_info(struct ldb_module *module) talloc_free(res); - return 0; + return LDB_SUCCESS; failed: talloc_free(res); @@ -153,7 +153,7 @@ failed: talloc_free(proxy->newdn); talloc_free(proxy->upstream); proxy->upstream = NULL; - return -1; + return LDB_ERR_OPERATIONS_ERROR; } @@ -259,7 +259,7 @@ 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 */ @@ -269,7 +269,7 @@ static int proxy_search_bytree(struct ldb_module *module, struct ldb_request *re newreq = talloc(module, struct ldb_request); if (newreq == NULL) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } newreq->op.search.tree = proxy_convert_tree(module, req->op.search.tree); @@ -298,7 +298,7 @@ static int proxy_search_bytree(struct ldb_module *module, struct ldb_request *re if (ret != LDB_SUCCESS) { ldb_set_errstring(module->ldb, ldb_errstring(proxy->upstream)); talloc_free(newreq); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } for (i = 0; i < newreq->op.search.res->count; i++) { diff --git a/source4/dsdb/samdb/ldb_modules/repl_meta_data.c b/source4/dsdb/samdb/ldb_modules/repl_meta_data.c index dd5faf837a..34e235aec7 100644 --- a/source4/dsdb/samdb/ldb_modules/repl_meta_data.c +++ b/source4/dsdb/samdb/ldb_modules/repl_meta_data.c @@ -124,16 +124,16 @@ static int add_time_element(struct ldb_message *msg, const char *attr, time_t t) char *s; if (ldb_msg_find_element(msg, attr) != NULL) { - return 0; + return LDB_SUCCESS; } s = ldb_timestring(msg, t); if (s == NULL) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } if (ldb_msg_add_string(msg, attr, s) != 0) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } el = ldb_msg_find_element(msg, attr); @@ -141,7 +141,7 @@ static int add_time_element(struct ldb_message *msg, const char *attr, time_t t) is ignored */ el->flags = LDB_FLAG_MOD_REPLACE; - return 0; + return LDB_SUCCESS; } /* @@ -152,11 +152,11 @@ static int add_uint64_element(struct ldb_message *msg, const char *attr, uint64_ struct ldb_message_element *el; if (ldb_msg_find_element(msg, attr) != NULL) { - return 0; + return LDB_SUCCESS; } if (ldb_msg_add_fmt(msg, attr, "%llu", (unsigned long long)v) != 0) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } el = ldb_msg_find_element(msg, attr); @@ -164,7 +164,7 @@ static int add_uint64_element(struct ldb_message *msg, const char *attr, uint64_ is ignored */ el->flags = LDB_FLAG_MOD_REPLACE; - return 0; + return LDB_SUCCESS; } static int replmd_replPropertyMetaData1_attid_sort(const struct replPropertyMetaData1 *m1, diff --git a/source4/dsdb/samdb/ldb_modules/schema_fsmo.c b/source4/dsdb/samdb/ldb_modules/schema_fsmo.c index 968b19c038..7c6a6dd26f 100644 --- a/source4/dsdb/samdb/ldb_modules/schema_fsmo.c +++ b/source4/dsdb/samdb/ldb_modules/schema_fsmo.c @@ -307,7 +307,7 @@ static int generate_dITContentRules(struct ldb_context *ldb, struct ldb_message } } } - return 0; + return LDB_SUCCESS; } diff --git a/source4/lib/ldb-samba/ldif_handlers.c b/source4/lib/ldb-samba/ldif_handlers.c index a16582d294..46ea09554d 100644 --- a/source4/lib/ldb-samba/ldif_handlers.c +++ b/source4/lib/ldb-samba/ldif_handlers.c @@ -134,7 +134,7 @@ static int ldb_canonicalise_objectSid(struct ldb_context *ldb, void *mem_ctx, /* Perhaps not a string after all */ return ldb_handler_copy(ldb, mem_ctx, in, out); } - return 0; + return LDB_SUCCESS; } return ldb_handler_copy(ldb, mem_ctx, in, out); } diff --git a/source4/lib/ldb_wrap.c b/source4/lib/ldb_wrap.c index 6c683a1e33..8082f4fac5 100644 --- a/source4/lib/ldb_wrap.c +++ b/source4/lib/ldb_wrap.c @@ -84,7 +84,7 @@ static int ldb_wrap_destructor(struct ldb_context *ldb) smb_panic("probable memory leak in ldb"); #endif } - return 0; + return LDB_SUCCESS; } /* -- cgit From 9261fa997ccda8f89556b644ddd45cd86919ec2e Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Tue, 9 Sep 2008 17:36:14 +0200 Subject: Cosmetic corrections for the LDB backend modules This commit applies some cosmetic corrections for the LDB backend modules. --- source4/lib/ldb/ldb_ildap/ldb_ildap.c | 6 ++--- source4/lib/ldb/ldb_ldap/ldb_ldap.c | 18 ++++++------- source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c | 28 ++++++++++----------- source4/lib/ldb/ldb_tdb/ldb_cache.c | 22 ++++++++-------- source4/lib/ldb/ldb_tdb/ldb_pack.c | 12 ++++----- source4/lib/ldb/ldb_tdb/ldb_search.c | 42 +++++++++++++++---------------- source4/lib/ldb/ldb_tdb/ldb_tdb.c | 20 +++++++-------- source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c | 2 +- 8 files changed, 75 insertions(+), 75 deletions(-) diff --git a/source4/lib/ldb/ldb_ildap/ldb_ildap.c b/source4/lib/ldb/ldb_ildap/ldb_ildap.c index 5ad671ea2e..3a5da89c41 100644 --- a/source4/lib/ldb/ldb_ildap/ldb_ildap.c +++ b/source4/lib/ldb/ldb_ildap/ldb_ildap.c @@ -753,7 +753,7 @@ static int ildb_connect(struct ldb_context *ldb, const char *url, module = talloc(ldb, struct ldb_module); if (!module) { ldb_oom(ldb); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } talloc_set_name_const(module, "ldb_ildap backend"); module->ldb = ldb; @@ -819,11 +819,11 @@ static int ildb_connect(struct ldb_context *ldb, const char *url, } *_module = module; - return 0; + return LDB_SUCCESS; failed: talloc_free(module); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } _PUBLIC_ const struct ldb_backend_ops ldb_ldap_backend_ops = { diff --git a/source4/lib/ldb/ldb_ldap/ldb_ldap.c b/source4/lib/ldb/ldb_ldap/ldb_ldap.c index a4534c549a..5026f9c006 100644 --- a/source4/lib/ldb/ldb_ldap/ldb_ldap.c +++ b/source4/lib/ldb/ldb_ldap/ldb_ldap.c @@ -180,14 +180,14 @@ static int lldb_add_msg_attr(struct ldb_context *ldb, count = ldap_count_values_len(bval); if (count <= 0) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } el = talloc_realloc(msg, msg->elements, struct ldb_message_element, msg->num_elements + 1); if (!el) { errno = ENOMEM; - return -1; + return LDB_ERR_OPERATIONS_ERROR; } msg->elements = el; @@ -197,7 +197,7 @@ static int lldb_add_msg_attr(struct ldb_context *ldb, el->name = talloc_strdup(msg->elements, attr); if (!el->name) { errno = ENOMEM; - return -1; + return LDB_ERR_OPERATIONS_ERROR; } el->flags = 0; @@ -205,7 +205,7 @@ static int lldb_add_msg_attr(struct ldb_context *ldb, el->values = talloc_array(msg->elements, struct ldb_val, count); if (!el->values) { errno = ENOMEM; - return -1; + return LDB_ERR_OPERATIONS_ERROR; } for (i=0;ivalues[i].data = talloc_size(el->values, bval[i]->bv_len+1); if (!el->values[i].data) { errno = ENOMEM; - return -1; + return LDB_ERR_OPERATIONS_ERROR; } memcpy(el->values[i].data, bval[i]->bv_val, bval[i]->bv_len); el->values[i].data[bval[i]->bv_len] = 0; @@ -224,7 +224,7 @@ static int lldb_add_msg_attr(struct ldb_context *ldb, msg->num_elements++; - return 0; + return LDB_SUCCESS; } /* @@ -785,7 +785,7 @@ static int lldb_connect(struct ldb_context *ldb, if (module == NULL) { ldb_oom(ldb); talloc_free(lldb); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } talloc_set_name_const(module, "ldb_ldap backend"); module->ldb = ldb; @@ -819,11 +819,11 @@ static int lldb_connect(struct ldb_context *ldb, } *_module = module; - return 0; + return LDB_SUCCESS; failed: talloc_free(module); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } const struct ldb_backend_ops ldb_ldap_backend_ops = { diff --git a/source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c b/source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c index a0e63c8da1..7e4fe1d08d 100644 --- a/source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c +++ b/source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c @@ -670,10 +670,10 @@ static int lsqlite3_safe_rollback(sqlite3 *sqlite) printf("lsqlite3_safe_rollback: Error: %s\n", errmsg); free(errmsg); } - return -1; + return SQLITE_ERROR; } - return 0; + return SQLITE_OK; } /* return an eid as result */ @@ -1440,13 +1440,13 @@ static int lsql_start_trans(struct ldb_module * module) printf("lsqlite3_start_trans: error: %s\n", errmsg); free(errmsg); } - return -1; + return SQLITE_ERROR; } }; lsqlite3->trans_count++; - return 0; + return SQLITE_OK; } static int lsql_end_trans(struct ldb_module *module) @@ -1457,7 +1457,7 @@ static int lsql_end_trans(struct ldb_module *module) if (lsqlite3->trans_count > 0) { lsqlite3->trans_count--; - } else return -1; + } else return SQLITE_ERROR; if (lsqlite3->trans_count == 0) { ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg); @@ -1466,11 +1466,11 @@ static int lsql_end_trans(struct ldb_module *module) printf("lsqlite3_end_trans: error: %s\n", errmsg); free(errmsg); } - return -1; + return SQLITE_ERROR; } } - return 0; + return SQLITE_OK; } static int lsql_del_trans(struct ldb_module *module) @@ -1479,13 +1479,13 @@ static int lsql_del_trans(struct ldb_module *module) if (lsqlite3->trans_count > 0) { lsqlite3->trans_count--; - } else return -1; + } else return SQLITE_ERROR; if (lsqlite3->trans_count == 0) { return lsqlite3_safe_rollback(lsqlite3->sqlite); } - return -1; + return SQLITE_ERROR; } static int destructor(struct lsqlite3_private *lsqlite3) @@ -1493,7 +1493,7 @@ static int destructor(struct lsqlite3_private *lsqlite3) if (lsqlite3->sqlite) { sqlite3_close(lsqlite3->sqlite); } - return 0; + return SQLITE_OK; } static int lsql_request(struct ldb_module *module, struct ldb_request *req) @@ -1540,7 +1540,7 @@ static int initialize(struct lsqlite3_private *lsqlite3, /* create a local ctx */ local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context"); if (local_ctx == NULL) { - return -1; + return SQLITE_ERROR; } schema = lsqlite3_tprintf(local_ctx, @@ -1792,7 +1792,7 @@ static int initialize(struct lsqlite3_private *lsqlite3, failed: if (rollback) lsqlite3_safe_rollback(lsqlite3->sqlite); sqlite3_close(lsqlite3->sqlite); - return -1; + return SQLITE_ERROR; } /* @@ -1860,14 +1860,14 @@ static int lsqlite3_connect(struct ldb_context *ldb, } } - return 0; + return LDB_SUCCESS; failed: if (lsqlite3->sqlite != NULL) { (void) sqlite3_close(lsqlite3->sqlite); } talloc_free(lsqlite3); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } const struct ldb_backend_ops ldb_sqlite3_backend_ops = { diff --git a/source4/lib/ldb/ldb_tdb/ldb_cache.c b/source4/lib/ldb/ldb_tdb/ldb_cache.c index 2576e2c7bd..e502f1e642 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_cache.c +++ b/source4/lib/ldb/ldb_tdb/ldb_cache.c @@ -92,11 +92,11 @@ static int ltdb_attributes_flags(struct ldb_message_element *el, unsigned *v) } } if (ltdb_valid_attr_flags[j].name == NULL) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } } *v = value; - return 0; + return LDB_SUCCESS; } /* @@ -118,7 +118,7 @@ static int ltdb_attributes_load(struct ldb_module *module) goto failed; } if (r == LDB_ERR_NO_SUCH_OBJECT) { - return 0; + return LDB_SUCCESS; } /* mapping these flags onto ldap 'syntaxes' isn't strictly correct, but its close enough for now */ @@ -162,9 +162,9 @@ static int ltdb_attributes_load(struct ldb_module *module) } } - return 0; + return LDB_SUCCESS; failed: - return -1; + return LDB_ERR_OPERATIONS_ERROR; } @@ -258,7 +258,7 @@ int ltdb_cache_load(struct ldb_module *module) /* a very fast check to avoid extra database reads */ if (ltdb->cache != NULL && tdb_get_seqnum(ltdb->tdb) == ltdb->tdb_seqnum) { - return 0; + return LDB_SUCCESS; } if (ltdb->cache == NULL) { @@ -344,7 +344,7 @@ int ltdb_cache_load(struct ldb_module *module) goto failed; } - if (ltdb_attributes_load(module) == -1) { + if (ltdb_attributes_load(module) != LDB_SUCCESS) { goto failed; } @@ -353,14 +353,14 @@ done: talloc_free(baseinfo); talloc_free(baseinfo_dn); talloc_free(indexlist_dn); - return 0; + return LDB_SUCCESS; failed: talloc_free(options); talloc_free(baseinfo); talloc_free(baseinfo_dn); talloc_free(indexlist_dn); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } @@ -449,10 +449,10 @@ int ltdb_check_at_attributes_values(const struct ldb_val *value) for (i = 0; ltdb_valid_attr_flags[i].name != NULL; i++) { if ((strcmp(ltdb_valid_attr_flags[i].name, (char *)value->data) == 0)) { - return 0; + return LDB_SUCCESS; } } - return -1; + return LDB_ERR_OPERATIONS_ERROR; } diff --git a/source4/lib/ldb/ldb_tdb/ldb_pack.c b/source4/lib/ldb/ldb_tdb/ldb_pack.c index afb07dcbca..d96e7590e7 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_pack.c +++ b/source4/lib/ldb/ldb_tdb/ldb_pack.c @@ -89,7 +89,7 @@ int ltdb_pack_data(struct ldb_module *module, dn = ldb_dn_get_linearized(message->dn); if (dn == NULL) { errno = ENOMEM; - return -1; + return LDB_ERR_OPERATIONS_ERROR; } /* work out how big it needs to be */ @@ -114,7 +114,7 @@ int ltdb_pack_data(struct ldb_module *module, data->dptr = talloc_array(ldb, uint8_t, size); if (!data->dptr) { errno = ENOMEM; - return -1; + return LDB_ERR_OPERATIONS_ERROR; } data->dsize = size; @@ -147,7 +147,7 @@ int ltdb_pack_data(struct ldb_module *module, } } - return 0; + return LDB_SUCCESS; } /* @@ -207,7 +207,7 @@ int ltdb_unpack_data(struct ldb_module *module, if (message->num_elements == 0) { message->elements = NULL; - return 0; + return LDB_SUCCESS; } if (message->num_elements > remaining / 6) { @@ -281,9 +281,9 @@ int ltdb_unpack_data(struct ldb_module *module, "Error: %d bytes unread in ltdb_unpack_data\n", remaining); } - return 0; + return LDB_SUCCESS; failed: talloc_free(message->elements); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } diff --git a/source4/lib/ldb/ldb_tdb/ldb_search.c b/source4/lib/ldb/ldb_tdb/ldb_search.c index da899c361e..ce7a90e3d5 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_search.c +++ b/source4/lib/ldb/ldb_tdb/ldb_search.c @@ -262,7 +262,7 @@ int ltdb_search_dn1(struct ldb_module *module, struct ldb_dn *dn, struct ldb_mes ret = ltdb_unpack_data(module, &tdb_data, msg); free(tdb_data.dptr); - if (ret == -1) { + if (ret != LDB_SUCCESS) { return LDB_ERR_OPERATIONS_ERROR; } @@ -285,7 +285,7 @@ static int ltdb_lock_read(struct ldb_module *module) if (ltdb->in_transaction == 0) { return tdb_lockall_read(ltdb->tdb); } - return 0; + return LDB_SUCCESS; } /* @@ -297,7 +297,7 @@ static int ltdb_unlock_read(struct ldb_module *module) if (ltdb->in_transaction == 0) { return tdb_unlockall_read(ltdb->tdb); } - return 0; + return LDB_SUCCESS; } /* @@ -317,14 +317,14 @@ int ltdb_add_attr_results(struct ldb_module *module, /* pull the attributes that the user wants */ msg2 = ltdb_pull_attrs(module, mem_ctx, msg, attrs); if (!msg2) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } /* add to the results list */ res2 = talloc_realloc(mem_ctx, *res, struct ldb_message *, (*count)+2); if (!res2) { talloc_free(msg2); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } (*res) = res2; @@ -333,7 +333,7 @@ int ltdb_add_attr_results(struct ldb_module *module, (*res)[(*count)+1] = NULL; (*count)++; - return 0; + return LDB_SUCCESS; } @@ -356,7 +356,7 @@ int ltdb_filter_attrs(struct ldb_message *msg, const char * const *attrs) if (ldb_attr_cmp(attrs[i], "distinguishedName") == 0) { if (msg_add_distinguished_name(msg) != 0) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } } } @@ -366,9 +366,9 @@ int ltdb_filter_attrs(struct ldb_message *msg, const char * const *attrs) if (keep_all) { if (msg_add_distinguished_name(msg) != 0) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } - return 0; + return LDB_SUCCESS; } for (i = 0; i < msg->num_elements; i++) { @@ -387,7 +387,7 @@ int ltdb_filter_attrs(struct ldb_message *msg, const char * const *attrs) } } - return 0; + return LDB_SUCCESS; } /* @@ -402,14 +402,14 @@ static int search_func(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, voi if (key.dsize < 4 || strncmp((char *)key.dptr, "DN=", 3) != 0) { - return 0; + return LDB_SUCCESS; } ares = talloc_zero(ac, struct ldb_reply); if (!ares) { handle->status = LDB_ERR_OPERATIONS_ERROR; handle->state = LDB_ASYNC_DONE; - return -1; + return LDB_ERR_OPERATIONS_ERROR; } ares->message = ldb_msg_new(ares); @@ -417,14 +417,14 @@ static int search_func(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, voi handle->status = LDB_ERR_OPERATIONS_ERROR; handle->state = LDB_ASYNC_DONE; talloc_free(ares); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } /* unpack the record */ ret = ltdb_unpack_data(ac->module, &data, ares->message); - if (ret == -1) { + if (ret) { talloc_free(ares); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } if (!ares->message->dn) { @@ -433,7 +433,7 @@ static int search_func(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, voi handle->status = LDB_ERR_OPERATIONS_ERROR; handle->state = LDB_ASYNC_DONE; talloc_free(ares); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } } @@ -441,17 +441,17 @@ static int search_func(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, voi if (!ldb_match_msg(ac->module->ldb, ares->message, ac->tree, ac->base, ac->scope)) { talloc_free(ares); - return 0; + return LDB_SUCCESS; } /* filter the attributes that the user wants */ ret = ltdb_filter_attrs(ares->message, ac->attrs); - if (ret == -1) { + if (ret != LDB_SUCCESS) { handle->status = LDB_ERR_OPERATIONS_ERROR; handle->state = LDB_ASYNC_DONE; talloc_free(ares); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } ares->type = LDB_REPLY_ENTRY; @@ -460,10 +460,10 @@ static int search_func(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, voi if (handle->status != LDB_SUCCESS) { /* don't try to free ares here, the callback is in charge of that */ - return -1; + return LDB_ERR_OPERATIONS_ERROR; } - return 0; + return LDB_SUCCESS; } diff --git a/source4/lib/ldb/ldb_tdb/ldb_tdb.c b/source4/lib/ldb/ldb_tdb/ldb_tdb.c index 01d570c89a..b711efd1fa 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_tdb.c +++ b/source4/lib/ldb/ldb_tdb/ldb_tdb.c @@ -174,7 +174,7 @@ int ltdb_check_special_dn(struct ldb_module *module, if (! ldb_dn_is_special(msg->dn) || ! ldb_dn_check_special(msg->dn, LTDB_ATTRIBUTES)) { - return 0; + return LDB_SUCCESS; } /* we have @ATTRIBUTES, let's check attributes are fine */ @@ -188,7 +188,7 @@ int ltdb_check_special_dn(struct ldb_module *module, } } - return 0; + return LDB_SUCCESS; } @@ -231,7 +231,7 @@ int ltdb_store(struct ldb_module *module, const struct ldb_message *msg, int flg } ret = ltdb_pack_data(module, msg, &tdb_data); - if (ret == -1) { + if (ret != LDB_SUCCESS) { talloc_free(tdb_key.dptr); return LDB_ERR_OTHER; } @@ -626,7 +626,7 @@ int ltdb_modify_internal(struct ldb_module *module, } ret = ltdb_unpack_data(module, &tdb_data, msg2); - if (ret == -1) { + if (ret != LDB_SUCCESS) { ret = LDB_ERR_OTHER; goto failed; } @@ -1069,7 +1069,7 @@ static int ltdb_connect(struct ldb_context *ldb, const char *url, if (strncmp(url, "tdb://", 6) != 0) { ldb_debug(ldb, LDB_DEBUG_ERROR, "Invalid tdb URL '%s'", url); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } path = url+6; } else { @@ -1097,7 +1097,7 @@ static int ltdb_connect(struct ldb_context *ldb, const char *url, ltdb = talloc_zero(ldb, struct ltdb_private); if (!ltdb) { ldb_oom(ldb); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } /* note that we use quite a large default hash size */ @@ -1108,7 +1108,7 @@ static int ltdb_connect(struct ldb_context *ldb, const char *url, ldb_debug(ldb, LDB_DEBUG_ERROR, "Unable to open tdb '%s'\n", path); talloc_free(ltdb); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } ltdb->sequence_number = 0; @@ -1117,7 +1117,7 @@ static int ltdb_connect(struct ldb_context *ldb, const char *url, if (!module) { ldb_oom(ldb); talloc_free(ltdb); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } talloc_set_name_const(*module, "ldb_tdb backend"); (*module)->ldb = ldb; @@ -1128,10 +1128,10 @@ static int ltdb_connect(struct ldb_context *ldb, const char *url, if (ltdb_cache_load(*module) != 0) { talloc_free(*module); talloc_free(ltdb); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } - return 0; + return LDB_SUCCESS; } const struct ldb_backend_ops ldb_tdb_backend_ops = { diff --git a/source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c b/source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c index 4fea43c8c8..9d856355be 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c +++ b/source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c @@ -53,7 +53,7 @@ static int ltdb_wrap_destructor(struct ltdb_wrap *w) if (w == tdb_list) { tdb_list = w->next; } - return 0; + return LDB_SUCCESS; } static void ltdb_log_fn(struct tdb_context *tdb, enum tdb_debug_level level, const char *fmt, ...) PRINTF_ATTRIBUTE(3, 4); -- cgit From 9d849c30bc5dfb4c3b27639c52ba8c2a54d07471 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Tue, 9 Sep 2008 17:36:52 +0200 Subject: Cosmetic corrections for the LDB library This commit applies some cosmetic corrections for the LDB library. --- source4/lib/ldb/common/attrib_handlers.c | 22 +++++++++++----------- source4/lib/ldb/common/ldb_attributes.c | 8 ++++---- source4/lib/ldb/common/ldb_debug.c | 2 +- source4/lib/ldb/common/ldb_ldif.c | 18 +++++++++--------- source4/lib/ldb/common/ldb_modules.c | 6 +++--- source4/lib/ldb/modules/operational.c | 4 ++-- source4/lib/ldb/modules/paged_results.c | 2 +- source4/lib/ldb/modules/skel.c | 2 +- 8 files changed, 32 insertions(+), 32 deletions(-) diff --git a/source4/lib/ldb/common/attrib_handlers.c b/source4/lib/ldb/common/attrib_handlers.c index fb57e2dadc..6f1b0815d7 100644 --- a/source4/lib/ldb/common/attrib_handlers.c +++ b/source4/lib/ldb/common/attrib_handlers.c @@ -38,9 +38,9 @@ int ldb_handler_copy(struct ldb_context *ldb, void *mem_ctx, *out = ldb_val_dup(mem_ctx, in); if (in->length > 0 && out->data == NULL) { ldb_oom(ldb); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } - return 0; + return LDB_SUCCESS; } /* @@ -57,13 +57,13 @@ int ldb_handler_fold(struct ldb_context *ldb, void *mem_ctx, int l; if (!in || !out || !(in->data)) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } out->data = (uint8_t *)ldb_casefold(ldb, mem_ctx, (const char *)(in->data), in->length); if (out->data == NULL) { ldb_debug(ldb, LDB_DEBUG_ERROR, "ldb_handler_fold: unable to casefold string [%s]", in->data); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } s = (char *)(out->data); @@ -96,7 +96,7 @@ int ldb_handler_fold(struct ldb_context *ldb, void *mem_ctx, } out->length = strlen((char *)out->data); - return 0; + return LDB_SUCCESS; } @@ -111,14 +111,14 @@ int ldb_canonicalise_Integer(struct ldb_context *ldb, void *mem_ctx, char *end; long long i = strtoll((char *)in->data, &end, 0); if (*end != 0) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } out->data = (uint8_t *)talloc_asprintf(mem_ctx, "%lld", i); if (out->data == NULL) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } out->length = strlen((char *)out->data); - return 0; + return LDB_SUCCESS; } /* @@ -251,7 +251,7 @@ int ldb_canonicalise_dn(struct ldb_context *ldb, void *mem_ctx, } out->length = strlen((char *)out->data); - ret = 0; + ret = LDB_SUCCESS; done: talloc_free(dn); @@ -305,10 +305,10 @@ int ldb_canonicalise_utctime(struct ldb_context *ldb, void *mem_ctx, time_t t = ldb_string_to_time((char *)in->data); out->data = (uint8_t *)ldb_timestring(mem_ctx, t); if (out->data == NULL) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } out->length = strlen((char *)out->data); - return 0; + return LDB_SUCCESS; } /* diff --git a/source4/lib/ldb/common/ldb_attributes.c b/source4/lib/ldb/common/ldb_attributes.c index 747f241781..0fbb5e2bfb 100644 --- a/source4/lib/ldb/common/ldb_attributes.c +++ b/source4/lib/ldb/common/ldb_attributes.c @@ -61,7 +61,7 @@ int ldb_schema_attribute_add_with_syntax(struct ldb_context *ldb, struct ldb_schema_attribute, n); if (a == NULL) { ldb_oom(ldb); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } ldb->schema.attributes = a; @@ -70,7 +70,7 @@ int ldb_schema_attribute_add_with_syntax(struct ldb_context *ldb, if (cmp == 0) { /* silently ignore attempts to overwrite fixed attributes */ if (a[i].flags & LDB_ATTR_FLAG_FIXED) { - return 0; + return LDB_SUCCESS; } if (a[i].flags & LDB_ATTR_FLAG_ALLOCATED) { talloc_free(discard_const_p(char, a[i].name)); @@ -93,11 +93,11 @@ int ldb_schema_attribute_add_with_syntax(struct ldb_context *ldb, a[i].name = talloc_strdup(a, a[i].name); if (a[i].name == NULL) { ldb_oom(ldb); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } } - return 0; + return LDB_SUCCESS; } static const struct ldb_schema_syntax ldb_syntax_default = { diff --git a/source4/lib/ldb/common/ldb_debug.c b/source4/lib/ldb/common/ldb_debug.c index 0f78e37c1c..8e1c491f12 100644 --- a/source4/lib/ldb/common/ldb_debug.c +++ b/source4/lib/ldb/common/ldb_debug.c @@ -43,7 +43,7 @@ int ldb_set_debug(struct ldb_context *ldb, { ldb->debug_ops.debug = debug; ldb->debug_ops.context = context; - return 0; + return LDB_SUCCESS; } /* diff --git a/source4/lib/ldb/common/ldb_ldif.c b/source4/lib/ldb/common/ldb_ldif.c index fb93e17c6c..6cbd30f377 100644 --- a/source4/lib/ldb/common/ldb_ldif.c +++ b/source4/lib/ldb/common/ldb_ldif.c @@ -191,19 +191,19 @@ int ldb_should_b64_encode(const struct ldb_val *val) uint8_t *p = val->data; if (val->length == 0) { - return 0; + return LDB_SUCCESS; } if (p[0] == ' ' || p[0] == ':') { - return 1; + return LDB_ERR_OPERATIONS_ERROR; } for (i=0; ilength; i++) { if (!isprint(p[i]) || p[i] == '\n') { - return 1; + return LDB_ERR_OPERATIONS_ERROR; } } - return 0; + return LDB_SUCCESS; } /* this macro is used to handle the return checking on fprintf_fn() */ @@ -444,12 +444,12 @@ static int next_attr(void *mem_ctx, char **s, const char **attr, struct ldb_val value->length = 0; *attr = "-"; *s += 2; - return 0; + return LDB_SUCCESS; } p = strchr(*s, ':'); if (!p) { - return -1; + return LDB_ERR_OPERATIONS_ERROR; } *p++ = 0; @@ -487,7 +487,7 @@ static int next_attr(void *mem_ctx, char **s, const char **attr, struct ldb_val int len = ldb_base64_decode((char *)value->data); if (len == -1) { /* it wasn't valid base64 data */ - return -1; + return LDB_ERR_OPERATIONS_ERROR; } value->length = len; } @@ -496,11 +496,11 @@ static int next_attr(void *mem_ctx, char **s, const char **attr, struct ldb_val int len = ldb_read_data_file(mem_ctx, value); if (len == -1) { /* an error occured hile trying to retrieve the file */ - return -1; + return LDB_ERR_OPERATIONS_ERROR; } } - return 0; + return LDB_SUCCESS; } diff --git a/source4/lib/ldb/common/ldb_modules.c b/source4/lib/ldb/common/ldb_modules.c index c0cd616a76..046d36edf1 100644 --- a/source4/lib/ldb/common/ldb_modules.c +++ b/source4/lib/ldb/common/ldb_modules.c @@ -279,16 +279,16 @@ int ldb_register_module(const struct ldb_module_ops *ops) struct ops_list_entry *entry = talloc(talloc_autofree_context(), struct ops_list_entry); if (ldb_find_module_ops(ops->name) != NULL) - return -1; + return LDB_ERR_OPERATIONS_ERROR; if (entry == NULL) - return -1; + return LDB_ERR_OPERATIONS_ERROR; entry->ops = ops; entry->next = registered_modules; registered_modules = entry; - return 0; + return LDB_SUCCESS; } void *ldb_dso_load_symbol(struct ldb_context *ldb, const char *name, diff --git a/source4/lib/ldb/modules/operational.c b/source4/lib/ldb/modules/operational.c index a59e81becd..716f34d660 100644 --- a/source4/lib/ldb/modules/operational.c +++ b/source4/lib/ldb/modules/operational.c @@ -158,13 +158,13 @@ static int operational_search_post_process(struct ldb_module *module, } } - return 0; + return LDB_SUCCESS; failed: ldb_debug_set(module->ldb, LDB_DEBUG_WARNING, "operational_search_post_process failed for attribute '%s'\n", attrs[a]); - return -1; + return LDB_ERR_OPERATIONS_ERROR; } diff --git a/source4/lib/ldb/modules/paged_results.c b/source4/lib/ldb/modules/paged_results.c index b62b1f92cb..c7296a1edf 100644 --- a/source4/lib/ldb/modules/paged_results.c +++ b/source4/lib/ldb/modules/paged_results.c @@ -86,7 +86,7 @@ int store_destructor(struct results_store *store) store->priv->store = NULL; } - return 0; + return LDB_SUCCESS; } static struct results_store *new_store(struct private_data *priv) diff --git a/source4/lib/ldb/modules/skel.c b/source4/lib/ldb/modules/skel.c index 0cd29ac4b7..15df46354b 100644 --- a/source4/lib/ldb/modules/skel.c +++ b/source4/lib/ldb/modules/skel.c @@ -90,7 +90,7 @@ static int skel_destructor(struct ldb_module *ctx) struct private_data *data = talloc_get_type(ctx->private_data, struct private_data); /* put your clean-up functions here */ if (data->some_private_data) talloc_free(data->some_private_data); - return 0; + return LDB_SUCCESS; } static int skel_request(struct ldb_module *module, struct ldb_request *req) -- cgit From 57edd24ca0fd91ae4d967666dc381147654e27f7 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Tue, 9 Sep 2008 17:37:33 +0200 Subject: Cosmetic corrections for the KERBEROS library This commit applies some cosmetic corrections for the KERBEROS library. --- source4/auth/gensec/cyrus_sasl.c | 2 +- source4/auth/kerberos/kerberos.c | 4 ++-- source4/auth/kerberos/kerberos_util.c | 18 ++++++++---------- source4/auth/kerberos/krb5_init_context.c | 4 ++-- source4/kdc/hdb-ldb.c | 6 +++--- 5 files changed, 16 insertions(+), 18 deletions(-) diff --git a/source4/auth/gensec/cyrus_sasl.c b/source4/auth/gensec/cyrus_sasl.c index 06a7b8a382..6f82de82fc 100644 --- a/source4/auth/gensec/cyrus_sasl.c +++ b/source4/auth/gensec/cyrus_sasl.c @@ -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) diff --git a/source4/auth/kerberos/kerberos.c b/source4/auth/kerberos/kerberos.c index 2579ab20cc..d54664fe66 100644 --- a/source4/auth/kerberos/kerberos.c +++ b/source4/auth/kerberos/kerberos.c @@ -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) { diff --git a/source4/auth/kerberos/kerberos_util.c b/source4/auth/kerberos/kerberos_util.c index 9002715065..0567565d33 100644 --- a/source4/auth/kerberos/kerberos_util.c +++ b/source4/auth/kerberos/kerberos_util.c @@ -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, diff --git a/source4/auth/kerberos/krb5_init_context.c b/source4/auth/kerberos/krb5_init_context.c index 82e42a4560..90b542c4c4 100644 --- a/source4/auth/kerberos/krb5_init_context.c +++ b/source4/auth/kerberos/krb5_init_context.c @@ -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); diff --git a/source4/kdc/hdb-ldb.c b/source4/kdc/hdb-ldb.c index c5466f1acd..4fde75cf70 100644 --- a/source4/kdc/hdb-ldb.c +++ b/source4/kdc/hdb-ldb.c @@ -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; @@ -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; -- cgit From 79854dc48a6f5448e4a435261ad2d9e9a2bbc712 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Thu, 18 Sep 2008 15:34:58 +0200 Subject: Kerberos cosmetic changes: Revert a part of the patch Reverts a part of the patch because it changes the function of the code (suggested by Jelmer). --- source4/auth/kerberos/kerberos_util.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source4/auth/kerberos/kerberos_util.c b/source4/auth/kerberos/kerberos_util.c index 0567565d33..4704f4805f 100644 --- a/source4/auth/kerberos/kerberos_util.c +++ b/source4/auth/kerberos/kerberos_util.c @@ -243,7 +243,9 @@ static krb5_error_code salt_principal_from_credentials(TALLOC_CTX *parent_ctx, static krb5_error_code free_keytab(struct keytab_container *ktc) { - return krb5_kt_close(ktc->smb_krb5_context->krb5_context, ktc->keytab); + krb5_kt_close(ktc->smb_krb5_context->krb5_context, ktc->keytab); + + return 0; } krb5_error_code smb_krb5_open_keytab(TALLOC_CTX *mem_ctx, -- cgit From b39b6099a44ef40fc79fc68c9df740e0ef722d19 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Tue, 9 Sep 2008 17:37:33 +0200 Subject: Cosmetic corrections for the KERBEROS library This commit applies some cosmetic corrections for the KERBEROS library. --- source4/auth/kerberos/kerberos_util.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/source4/auth/kerberos/kerberos_util.c b/source4/auth/kerberos/kerberos_util.c index 4704f4805f..0567565d33 100644 --- a/source4/auth/kerberos/kerberos_util.c +++ b/source4/auth/kerberos/kerberos_util.c @@ -243,9 +243,7 @@ static krb5_error_code salt_principal_from_credentials(TALLOC_CTX *parent_ctx, 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); } krb5_error_code smb_krb5_open_keytab(TALLOC_CTX *mem_ctx, -- cgit From 9cf1a68977d56d342ca7dbe8f07c725221dc1148 Mon Sep 17 00:00:00 2001 From: Karolin Seeger Date: Wed, 24 Sep 2008 09:53:21 -0700 Subject: printing: Rename new parameter "cups timeout" to "cups connection timeout". Karolin --- docs-xml/smbdotconf/printing/cupstimeout.xml | 17 ----------------- source3/include/printing.h | 2 +- source3/include/proto.h | 2 +- source3/param/loadparm.c | 10 +++++----- source3/printing/print_cups.c | 2 +- 5 files changed, 8 insertions(+), 25 deletions(-) delete mode 100644 docs-xml/smbdotconf/printing/cupstimeout.xml diff --git a/docs-xml/smbdotconf/printing/cupstimeout.xml b/docs-xml/smbdotconf/printing/cupstimeout.xml deleted file mode 100644 index 727ccce67b..0000000000 --- a/docs-xml/smbdotconf/printing/cupstimeout.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - This parameter determines the timeout for connections to a CUPS server - in seconds. - - - -30 -cups timeout = 10 - diff --git a/source3/include/printing.h b/source3/include/printing.h index 04e30a011b..d91917b528 100644 --- a/source3/include/printing.h +++ b/source3/include/printing.h @@ -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." diff --git a/source3/include/proto.h b/source3/include/proto.h index b1c4d2e5d9..2ccf3b15f7 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -5824,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); diff --git a/source3/param/loadparm.c b/source3/param/loadparm.c index db9e990e64..87af7a3411 100644 --- a/source3/param/loadparm.c +++ b/source3/param/loadparm.c @@ -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, @@ -4805,7 +4805,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 +5247,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) diff --git a/source3/printing/print_cups.c b/source3/printing/print_cups.c index 2b2cf159fb..f9568f0a54 100644 --- a/source3/printing/print_cups.c +++ b/source3/printing/print_cups.c @@ -56,7 +56,7 @@ static http_t *cups_connect(void) http_t *http; char *server, *p; int port; - int timeout = lp_cups_timeout(); + int timeout = lp_cups_connection_timeout(); gotalarm = 0; -- cgit From ec0eab7f0b20e6f1691ce3a723e29dbf7ee3fd99 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 23 Sep 2008 10:34:06 +0200 Subject: s3:configure: add -L./bin also for the merged build metze --- source3/configure.in | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source3/configure.in b/source3/configure.in index f23f6b55be..63e17dc717 100644 --- a/source3/configure.in +++ b/source3/configure.in @@ -6276,6 +6276,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 -- cgit From 943387edc12a276d358add404e4fecd6c3aec303 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Wed, 24 Sep 2008 22:49:05 +0200 Subject: build: fix the libcryptosrcdir for the merged build metze --- source3/samba4.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/samba4.mk b/source3/samba4.mk index 53ea76ed90..3abcbe121f 100644 --- a/source3/samba4.mk +++ b/source3/samba4.mk @@ -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 -- cgit From 31e10643c998e64c0ec432553ac9193d978e43f4 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Wed, 24 Sep 2008 14:28:18 -0700 Subject: Fix bug #5790 samba returns STATUS_OBJECT_NAME_NOT_FOUND on set file disposition. We were checking that fd != -1 in file_find_di_XXX calls which is no longer needed due to a change in internal semantics. Jeremy. --- source3/smbd/files.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/source3/smbd/files.c b/source3/smbd/files.c index 17c473f028..777f8e1e23 100644 --- a/source3/smbd/files.c +++ b/source3/smbd/files.c @@ -326,8 +326,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 +347,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; } } -- cgit From b0a95ad2f68cfc87822420c22216d83c0abf0690 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 24 Sep 2008 23:59:59 +0200 Subject: Revert LDB return code patches from Matthias. --- source4/dsdb/samdb/ldb_modules/kludge_acl.c | 4 +-- source4/dsdb/samdb/ldb_modules/proxy.c | 12 +++---- source4/dsdb/samdb/ldb_modules/repl_meta_data.c | 14 ++++----- source4/dsdb/samdb/ldb_modules/schema_fsmo.c | 2 +- source4/lib/ldb-samba/ldif_handlers.c | 2 +- source4/lib/ldb/common/attrib_handlers.c | 22 ++++++------- source4/lib/ldb/common/ldb_attributes.c | 8 ++--- source4/lib/ldb/common/ldb_debug.c | 2 +- source4/lib/ldb/common/ldb_ldif.c | 18 +++++------ source4/lib/ldb/common/ldb_modules.c | 6 ++-- source4/lib/ldb/ldb_ildap/ldb_ildap.c | 6 ++-- source4/lib/ldb/ldb_ldap/ldb_ldap.c | 18 +++++------ source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c | 28 ++++++++--------- source4/lib/ldb/ldb_tdb/ldb_cache.c | 22 ++++++------- source4/lib/ldb/ldb_tdb/ldb_pack.c | 12 +++---- source4/lib/ldb/ldb_tdb/ldb_search.c | 42 ++++++++++++------------- source4/lib/ldb/ldb_tdb/ldb_tdb.c | 20 ++++++------ source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c | 2 +- source4/lib/ldb/modules/operational.c | 4 +-- source4/lib/ldb/modules/paged_results.c | 2 +- source4/lib/ldb/modules/skel.c | 2 +- source4/lib/ldb_wrap.c | 2 +- 22 files changed, 125 insertions(+), 125 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/kludge_acl.c b/source4/dsdb/samdb/ldb_modules/kludge_acl.c index 11e2b7ade9..6836f95873 100644 --- a/source4/dsdb/samdb/ldb_modules/kludge_acl.c +++ b/source4/dsdb/samdb/ldb_modules/kludge_acl.c @@ -142,7 +142,7 @@ static int kludge_acl_allowedAttributes(struct ldb_context *ldb, struct ldb_mess ldb_msg_add_string(msg, attrName, attr_list[i]); } talloc_free(mem_ctx); - return LDB_SUCCESS; + return 0; } /* read all objectClasses */ @@ -201,7 +201,7 @@ static int kludge_acl_childClasses(struct ldb_context *ldb, struct ldb_message * } } - return LDB_SUCCESS; + return 0; } diff --git a/source4/dsdb/samdb/ldb_modules/proxy.c b/source4/dsdb/samdb/ldb_modules/proxy.c index 7aa78e98a9..d0a315e45a 100644 --- a/source4/dsdb/samdb/ldb_modules/proxy.c +++ b/source4/dsdb/samdb/ldb_modules/proxy.c @@ -66,7 +66,7 @@ static int load_proxy_info(struct ldb_module *module) /* see if we have already loaded it */ if (proxy->upstream != NULL) { - return LDB_SUCCESS; + return 0; } dn = ldb_dn_new(proxy, module->ldb, "@PROXYINFO"); @@ -145,7 +145,7 @@ static int load_proxy_info(struct ldb_module *module) talloc_free(res); - return LDB_SUCCESS; + return 0; failed: talloc_free(res); @@ -153,7 +153,7 @@ failed: talloc_free(proxy->newdn); talloc_free(proxy->upstream); proxy->upstream = NULL; - return LDB_ERR_OPERATIONS_ERROR; + return -1; } @@ -259,7 +259,7 @@ static int proxy_search_bytree(struct ldb_module *module, struct ldb_request *re } if (load_proxy_info(module) != 0) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } /* see if the dn is within olddn */ @@ -269,7 +269,7 @@ static int proxy_search_bytree(struct ldb_module *module, struct ldb_request *re newreq = talloc(module, struct ldb_request); if (newreq == NULL) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } newreq->op.search.tree = proxy_convert_tree(module, req->op.search.tree); @@ -298,7 +298,7 @@ static int proxy_search_bytree(struct ldb_module *module, struct ldb_request *re if (ret != LDB_SUCCESS) { ldb_set_errstring(module->ldb, ldb_errstring(proxy->upstream)); talloc_free(newreq); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } for (i = 0; i < newreq->op.search.res->count; i++) { diff --git a/source4/dsdb/samdb/ldb_modules/repl_meta_data.c b/source4/dsdb/samdb/ldb_modules/repl_meta_data.c index 34e235aec7..dd5faf837a 100644 --- a/source4/dsdb/samdb/ldb_modules/repl_meta_data.c +++ b/source4/dsdb/samdb/ldb_modules/repl_meta_data.c @@ -124,16 +124,16 @@ static int add_time_element(struct ldb_message *msg, const char *attr, time_t t) char *s; if (ldb_msg_find_element(msg, attr) != NULL) { - return LDB_SUCCESS; + return 0; } s = ldb_timestring(msg, t); if (s == NULL) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } if (ldb_msg_add_string(msg, attr, s) != 0) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } el = ldb_msg_find_element(msg, attr); @@ -141,7 +141,7 @@ static int add_time_element(struct ldb_message *msg, const char *attr, time_t t) is ignored */ el->flags = LDB_FLAG_MOD_REPLACE; - return LDB_SUCCESS; + return 0; } /* @@ -152,11 +152,11 @@ static int add_uint64_element(struct ldb_message *msg, const char *attr, uint64_ struct ldb_message_element *el; if (ldb_msg_find_element(msg, attr) != NULL) { - return LDB_SUCCESS; + return 0; } if (ldb_msg_add_fmt(msg, attr, "%llu", (unsigned long long)v) != 0) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } el = ldb_msg_find_element(msg, attr); @@ -164,7 +164,7 @@ static int add_uint64_element(struct ldb_message *msg, const char *attr, uint64_ is ignored */ el->flags = LDB_FLAG_MOD_REPLACE; - return LDB_SUCCESS; + return 0; } static int replmd_replPropertyMetaData1_attid_sort(const struct replPropertyMetaData1 *m1, diff --git a/source4/dsdb/samdb/ldb_modules/schema_fsmo.c b/source4/dsdb/samdb/ldb_modules/schema_fsmo.c index 7c6a6dd26f..968b19c038 100644 --- a/source4/dsdb/samdb/ldb_modules/schema_fsmo.c +++ b/source4/dsdb/samdb/ldb_modules/schema_fsmo.c @@ -307,7 +307,7 @@ static int generate_dITContentRules(struct ldb_context *ldb, struct ldb_message } } } - return LDB_SUCCESS; + return 0; } diff --git a/source4/lib/ldb-samba/ldif_handlers.c b/source4/lib/ldb-samba/ldif_handlers.c index 46ea09554d..a16582d294 100644 --- a/source4/lib/ldb-samba/ldif_handlers.c +++ b/source4/lib/ldb-samba/ldif_handlers.c @@ -134,7 +134,7 @@ static int ldb_canonicalise_objectSid(struct ldb_context *ldb, void *mem_ctx, /* Perhaps not a string after all */ return ldb_handler_copy(ldb, mem_ctx, in, out); } - return LDB_SUCCESS; + return 0; } return ldb_handler_copy(ldb, mem_ctx, in, out); } diff --git a/source4/lib/ldb/common/attrib_handlers.c b/source4/lib/ldb/common/attrib_handlers.c index 6f1b0815d7..fb57e2dadc 100644 --- a/source4/lib/ldb/common/attrib_handlers.c +++ b/source4/lib/ldb/common/attrib_handlers.c @@ -38,9 +38,9 @@ int ldb_handler_copy(struct ldb_context *ldb, void *mem_ctx, *out = ldb_val_dup(mem_ctx, in); if (in->length > 0 && out->data == NULL) { ldb_oom(ldb); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } - return LDB_SUCCESS; + return 0; } /* @@ -57,13 +57,13 @@ int ldb_handler_fold(struct ldb_context *ldb, void *mem_ctx, int l; if (!in || !out || !(in->data)) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } out->data = (uint8_t *)ldb_casefold(ldb, mem_ctx, (const char *)(in->data), in->length); if (out->data == NULL) { ldb_debug(ldb, LDB_DEBUG_ERROR, "ldb_handler_fold: unable to casefold string [%s]", in->data); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } s = (char *)(out->data); @@ -96,7 +96,7 @@ int ldb_handler_fold(struct ldb_context *ldb, void *mem_ctx, } out->length = strlen((char *)out->data); - return LDB_SUCCESS; + return 0; } @@ -111,14 +111,14 @@ int ldb_canonicalise_Integer(struct ldb_context *ldb, void *mem_ctx, char *end; long long i = strtoll((char *)in->data, &end, 0); if (*end != 0) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } out->data = (uint8_t *)talloc_asprintf(mem_ctx, "%lld", i); if (out->data == NULL) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } out->length = strlen((char *)out->data); - return LDB_SUCCESS; + return 0; } /* @@ -251,7 +251,7 @@ int ldb_canonicalise_dn(struct ldb_context *ldb, void *mem_ctx, } out->length = strlen((char *)out->data); - ret = LDB_SUCCESS; + ret = 0; done: talloc_free(dn); @@ -305,10 +305,10 @@ int ldb_canonicalise_utctime(struct ldb_context *ldb, void *mem_ctx, time_t t = ldb_string_to_time((char *)in->data); out->data = (uint8_t *)ldb_timestring(mem_ctx, t); if (out->data == NULL) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } out->length = strlen((char *)out->data); - return LDB_SUCCESS; + return 0; } /* diff --git a/source4/lib/ldb/common/ldb_attributes.c b/source4/lib/ldb/common/ldb_attributes.c index 0fbb5e2bfb..747f241781 100644 --- a/source4/lib/ldb/common/ldb_attributes.c +++ b/source4/lib/ldb/common/ldb_attributes.c @@ -61,7 +61,7 @@ int ldb_schema_attribute_add_with_syntax(struct ldb_context *ldb, struct ldb_schema_attribute, n); if (a == NULL) { ldb_oom(ldb); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } ldb->schema.attributes = a; @@ -70,7 +70,7 @@ int ldb_schema_attribute_add_with_syntax(struct ldb_context *ldb, if (cmp == 0) { /* silently ignore attempts to overwrite fixed attributes */ if (a[i].flags & LDB_ATTR_FLAG_FIXED) { - return LDB_SUCCESS; + return 0; } if (a[i].flags & LDB_ATTR_FLAG_ALLOCATED) { talloc_free(discard_const_p(char, a[i].name)); @@ -93,11 +93,11 @@ int ldb_schema_attribute_add_with_syntax(struct ldb_context *ldb, a[i].name = talloc_strdup(a, a[i].name); if (a[i].name == NULL) { ldb_oom(ldb); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } } - return LDB_SUCCESS; + return 0; } static const struct ldb_schema_syntax ldb_syntax_default = { diff --git a/source4/lib/ldb/common/ldb_debug.c b/source4/lib/ldb/common/ldb_debug.c index 8e1c491f12..0f78e37c1c 100644 --- a/source4/lib/ldb/common/ldb_debug.c +++ b/source4/lib/ldb/common/ldb_debug.c @@ -43,7 +43,7 @@ int ldb_set_debug(struct ldb_context *ldb, { ldb->debug_ops.debug = debug; ldb->debug_ops.context = context; - return LDB_SUCCESS; + return 0; } /* diff --git a/source4/lib/ldb/common/ldb_ldif.c b/source4/lib/ldb/common/ldb_ldif.c index 6cbd30f377..fb93e17c6c 100644 --- a/source4/lib/ldb/common/ldb_ldif.c +++ b/source4/lib/ldb/common/ldb_ldif.c @@ -191,19 +191,19 @@ int ldb_should_b64_encode(const struct ldb_val *val) uint8_t *p = val->data; if (val->length == 0) { - return LDB_SUCCESS; + return 0; } if (p[0] == ' ' || p[0] == ':') { - return LDB_ERR_OPERATIONS_ERROR; + return 1; } for (i=0; ilength; i++) { if (!isprint(p[i]) || p[i] == '\n') { - return LDB_ERR_OPERATIONS_ERROR; + return 1; } } - return LDB_SUCCESS; + return 0; } /* this macro is used to handle the return checking on fprintf_fn() */ @@ -444,12 +444,12 @@ static int next_attr(void *mem_ctx, char **s, const char **attr, struct ldb_val value->length = 0; *attr = "-"; *s += 2; - return LDB_SUCCESS; + return 0; } p = strchr(*s, ':'); if (!p) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } *p++ = 0; @@ -487,7 +487,7 @@ static int next_attr(void *mem_ctx, char **s, const char **attr, struct ldb_val int len = ldb_base64_decode((char *)value->data); if (len == -1) { /* it wasn't valid base64 data */ - return LDB_ERR_OPERATIONS_ERROR; + return -1; } value->length = len; } @@ -496,11 +496,11 @@ static int next_attr(void *mem_ctx, char **s, const char **attr, struct ldb_val int len = ldb_read_data_file(mem_ctx, value); if (len == -1) { /* an error occured hile trying to retrieve the file */ - return LDB_ERR_OPERATIONS_ERROR; + return -1; } } - return LDB_SUCCESS; + return 0; } diff --git a/source4/lib/ldb/common/ldb_modules.c b/source4/lib/ldb/common/ldb_modules.c index 046d36edf1..c0cd616a76 100644 --- a/source4/lib/ldb/common/ldb_modules.c +++ b/source4/lib/ldb/common/ldb_modules.c @@ -279,16 +279,16 @@ int ldb_register_module(const struct ldb_module_ops *ops) struct ops_list_entry *entry = talloc(talloc_autofree_context(), struct ops_list_entry); if (ldb_find_module_ops(ops->name) != NULL) - return LDB_ERR_OPERATIONS_ERROR; + return -1; if (entry == NULL) - return LDB_ERR_OPERATIONS_ERROR; + return -1; entry->ops = ops; entry->next = registered_modules; registered_modules = entry; - return LDB_SUCCESS; + return 0; } void *ldb_dso_load_symbol(struct ldb_context *ldb, const char *name, diff --git a/source4/lib/ldb/ldb_ildap/ldb_ildap.c b/source4/lib/ldb/ldb_ildap/ldb_ildap.c index 3a5da89c41..5ad671ea2e 100644 --- a/source4/lib/ldb/ldb_ildap/ldb_ildap.c +++ b/source4/lib/ldb/ldb_ildap/ldb_ildap.c @@ -753,7 +753,7 @@ static int ildb_connect(struct ldb_context *ldb, const char *url, module = talloc(ldb, struct ldb_module); if (!module) { ldb_oom(ldb); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } talloc_set_name_const(module, "ldb_ildap backend"); module->ldb = ldb; @@ -819,11 +819,11 @@ static int ildb_connect(struct ldb_context *ldb, const char *url, } *_module = module; - return LDB_SUCCESS; + return 0; failed: talloc_free(module); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } _PUBLIC_ const struct ldb_backend_ops ldb_ldap_backend_ops = { diff --git a/source4/lib/ldb/ldb_ldap/ldb_ldap.c b/source4/lib/ldb/ldb_ldap/ldb_ldap.c index 5026f9c006..a4534c549a 100644 --- a/source4/lib/ldb/ldb_ldap/ldb_ldap.c +++ b/source4/lib/ldb/ldb_ldap/ldb_ldap.c @@ -180,14 +180,14 @@ static int lldb_add_msg_attr(struct ldb_context *ldb, count = ldap_count_values_len(bval); if (count <= 0) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } el = talloc_realloc(msg, msg->elements, struct ldb_message_element, msg->num_elements + 1); if (!el) { errno = ENOMEM; - return LDB_ERR_OPERATIONS_ERROR; + return -1; } msg->elements = el; @@ -197,7 +197,7 @@ static int lldb_add_msg_attr(struct ldb_context *ldb, el->name = talloc_strdup(msg->elements, attr); if (!el->name) { errno = ENOMEM; - return LDB_ERR_OPERATIONS_ERROR; + return -1; } el->flags = 0; @@ -205,7 +205,7 @@ static int lldb_add_msg_attr(struct ldb_context *ldb, el->values = talloc_array(msg->elements, struct ldb_val, count); if (!el->values) { errno = ENOMEM; - return LDB_ERR_OPERATIONS_ERROR; + return -1; } for (i=0;ivalues[i].data = talloc_size(el->values, bval[i]->bv_len+1); if (!el->values[i].data) { errno = ENOMEM; - return LDB_ERR_OPERATIONS_ERROR; + return -1; } memcpy(el->values[i].data, bval[i]->bv_val, bval[i]->bv_len); el->values[i].data[bval[i]->bv_len] = 0; @@ -224,7 +224,7 @@ static int lldb_add_msg_attr(struct ldb_context *ldb, msg->num_elements++; - return LDB_SUCCESS; + return 0; } /* @@ -785,7 +785,7 @@ static int lldb_connect(struct ldb_context *ldb, if (module == NULL) { ldb_oom(ldb); talloc_free(lldb); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } talloc_set_name_const(module, "ldb_ldap backend"); module->ldb = ldb; @@ -819,11 +819,11 @@ static int lldb_connect(struct ldb_context *ldb, } *_module = module; - return LDB_SUCCESS; + return 0; failed: talloc_free(module); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } const struct ldb_backend_ops ldb_ldap_backend_ops = { diff --git a/source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c b/source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c index 7e4fe1d08d..a0e63c8da1 100644 --- a/source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c +++ b/source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c @@ -670,10 +670,10 @@ static int lsqlite3_safe_rollback(sqlite3 *sqlite) printf("lsqlite3_safe_rollback: Error: %s\n", errmsg); free(errmsg); } - return SQLITE_ERROR; + return -1; } - return SQLITE_OK; + return 0; } /* return an eid as result */ @@ -1440,13 +1440,13 @@ static int lsql_start_trans(struct ldb_module * module) printf("lsqlite3_start_trans: error: %s\n", errmsg); free(errmsg); } - return SQLITE_ERROR; + return -1; } }; lsqlite3->trans_count++; - return SQLITE_OK; + return 0; } static int lsql_end_trans(struct ldb_module *module) @@ -1457,7 +1457,7 @@ static int lsql_end_trans(struct ldb_module *module) if (lsqlite3->trans_count > 0) { lsqlite3->trans_count--; - } else return SQLITE_ERROR; + } else return -1; if (lsqlite3->trans_count == 0) { ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg); @@ -1466,11 +1466,11 @@ static int lsql_end_trans(struct ldb_module *module) printf("lsqlite3_end_trans: error: %s\n", errmsg); free(errmsg); } - return SQLITE_ERROR; + return -1; } } - return SQLITE_OK; + return 0; } static int lsql_del_trans(struct ldb_module *module) @@ -1479,13 +1479,13 @@ static int lsql_del_trans(struct ldb_module *module) if (lsqlite3->trans_count > 0) { lsqlite3->trans_count--; - } else return SQLITE_ERROR; + } else return -1; if (lsqlite3->trans_count == 0) { return lsqlite3_safe_rollback(lsqlite3->sqlite); } - return SQLITE_ERROR; + return -1; } static int destructor(struct lsqlite3_private *lsqlite3) @@ -1493,7 +1493,7 @@ static int destructor(struct lsqlite3_private *lsqlite3) if (lsqlite3->sqlite) { sqlite3_close(lsqlite3->sqlite); } - return SQLITE_OK; + return 0; } static int lsql_request(struct ldb_module *module, struct ldb_request *req) @@ -1540,7 +1540,7 @@ static int initialize(struct lsqlite3_private *lsqlite3, /* create a local ctx */ local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context"); if (local_ctx == NULL) { - return SQLITE_ERROR; + return -1; } schema = lsqlite3_tprintf(local_ctx, @@ -1792,7 +1792,7 @@ static int initialize(struct lsqlite3_private *lsqlite3, failed: if (rollback) lsqlite3_safe_rollback(lsqlite3->sqlite); sqlite3_close(lsqlite3->sqlite); - return SQLITE_ERROR; + return -1; } /* @@ -1860,14 +1860,14 @@ static int lsqlite3_connect(struct ldb_context *ldb, } } - return LDB_SUCCESS; + return 0; failed: if (lsqlite3->sqlite != NULL) { (void) sqlite3_close(lsqlite3->sqlite); } talloc_free(lsqlite3); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } const struct ldb_backend_ops ldb_sqlite3_backend_ops = { diff --git a/source4/lib/ldb/ldb_tdb/ldb_cache.c b/source4/lib/ldb/ldb_tdb/ldb_cache.c index e502f1e642..2576e2c7bd 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_cache.c +++ b/source4/lib/ldb/ldb_tdb/ldb_cache.c @@ -92,11 +92,11 @@ static int ltdb_attributes_flags(struct ldb_message_element *el, unsigned *v) } } if (ltdb_valid_attr_flags[j].name == NULL) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } } *v = value; - return LDB_SUCCESS; + return 0; } /* @@ -118,7 +118,7 @@ static int ltdb_attributes_load(struct ldb_module *module) goto failed; } if (r == LDB_ERR_NO_SUCH_OBJECT) { - return LDB_SUCCESS; + return 0; } /* mapping these flags onto ldap 'syntaxes' isn't strictly correct, but its close enough for now */ @@ -162,9 +162,9 @@ static int ltdb_attributes_load(struct ldb_module *module) } } - return LDB_SUCCESS; + return 0; failed: - return LDB_ERR_OPERATIONS_ERROR; + return -1; } @@ -258,7 +258,7 @@ int ltdb_cache_load(struct ldb_module *module) /* a very fast check to avoid extra database reads */ if (ltdb->cache != NULL && tdb_get_seqnum(ltdb->tdb) == ltdb->tdb_seqnum) { - return LDB_SUCCESS; + return 0; } if (ltdb->cache == NULL) { @@ -344,7 +344,7 @@ int ltdb_cache_load(struct ldb_module *module) goto failed; } - if (ltdb_attributes_load(module) != LDB_SUCCESS) { + if (ltdb_attributes_load(module) == -1) { goto failed; } @@ -353,14 +353,14 @@ done: talloc_free(baseinfo); talloc_free(baseinfo_dn); talloc_free(indexlist_dn); - return LDB_SUCCESS; + return 0; failed: talloc_free(options); talloc_free(baseinfo); talloc_free(baseinfo_dn); talloc_free(indexlist_dn); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } @@ -449,10 +449,10 @@ int ltdb_check_at_attributes_values(const struct ldb_val *value) for (i = 0; ltdb_valid_attr_flags[i].name != NULL; i++) { if ((strcmp(ltdb_valid_attr_flags[i].name, (char *)value->data) == 0)) { - return LDB_SUCCESS; + return 0; } } - return LDB_ERR_OPERATIONS_ERROR; + return -1; } diff --git a/source4/lib/ldb/ldb_tdb/ldb_pack.c b/source4/lib/ldb/ldb_tdb/ldb_pack.c index d96e7590e7..afb07dcbca 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_pack.c +++ b/source4/lib/ldb/ldb_tdb/ldb_pack.c @@ -89,7 +89,7 @@ int ltdb_pack_data(struct ldb_module *module, dn = ldb_dn_get_linearized(message->dn); if (dn == NULL) { errno = ENOMEM; - return LDB_ERR_OPERATIONS_ERROR; + return -1; } /* work out how big it needs to be */ @@ -114,7 +114,7 @@ int ltdb_pack_data(struct ldb_module *module, data->dptr = talloc_array(ldb, uint8_t, size); if (!data->dptr) { errno = ENOMEM; - return LDB_ERR_OPERATIONS_ERROR; + return -1; } data->dsize = size; @@ -147,7 +147,7 @@ int ltdb_pack_data(struct ldb_module *module, } } - return LDB_SUCCESS; + return 0; } /* @@ -207,7 +207,7 @@ int ltdb_unpack_data(struct ldb_module *module, if (message->num_elements == 0) { message->elements = NULL; - return LDB_SUCCESS; + return 0; } if (message->num_elements > remaining / 6) { @@ -281,9 +281,9 @@ int ltdb_unpack_data(struct ldb_module *module, "Error: %d bytes unread in ltdb_unpack_data\n", remaining); } - return LDB_SUCCESS; + return 0; failed: talloc_free(message->elements); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } diff --git a/source4/lib/ldb/ldb_tdb/ldb_search.c b/source4/lib/ldb/ldb_tdb/ldb_search.c index ce7a90e3d5..da899c361e 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_search.c +++ b/source4/lib/ldb/ldb_tdb/ldb_search.c @@ -262,7 +262,7 @@ int ltdb_search_dn1(struct ldb_module *module, struct ldb_dn *dn, struct ldb_mes ret = ltdb_unpack_data(module, &tdb_data, msg); free(tdb_data.dptr); - if (ret != LDB_SUCCESS) { + if (ret == -1) { return LDB_ERR_OPERATIONS_ERROR; } @@ -285,7 +285,7 @@ static int ltdb_lock_read(struct ldb_module *module) if (ltdb->in_transaction == 0) { return tdb_lockall_read(ltdb->tdb); } - return LDB_SUCCESS; + return 0; } /* @@ -297,7 +297,7 @@ static int ltdb_unlock_read(struct ldb_module *module) if (ltdb->in_transaction == 0) { return tdb_unlockall_read(ltdb->tdb); } - return LDB_SUCCESS; + return 0; } /* @@ -317,14 +317,14 @@ int ltdb_add_attr_results(struct ldb_module *module, /* pull the attributes that the user wants */ msg2 = ltdb_pull_attrs(module, mem_ctx, msg, attrs); if (!msg2) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } /* add to the results list */ res2 = talloc_realloc(mem_ctx, *res, struct ldb_message *, (*count)+2); if (!res2) { talloc_free(msg2); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } (*res) = res2; @@ -333,7 +333,7 @@ int ltdb_add_attr_results(struct ldb_module *module, (*res)[(*count)+1] = NULL; (*count)++; - return LDB_SUCCESS; + return 0; } @@ -356,7 +356,7 @@ int ltdb_filter_attrs(struct ldb_message *msg, const char * const *attrs) if (ldb_attr_cmp(attrs[i], "distinguishedName") == 0) { if (msg_add_distinguished_name(msg) != 0) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } } } @@ -366,9 +366,9 @@ int ltdb_filter_attrs(struct ldb_message *msg, const char * const *attrs) if (keep_all) { if (msg_add_distinguished_name(msg) != 0) { - return LDB_ERR_OPERATIONS_ERROR; + return -1; } - return LDB_SUCCESS; + return 0; } for (i = 0; i < msg->num_elements; i++) { @@ -387,7 +387,7 @@ int ltdb_filter_attrs(struct ldb_message *msg, const char * const *attrs) } } - return LDB_SUCCESS; + return 0; } /* @@ -402,14 +402,14 @@ static int search_func(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, voi if (key.dsize < 4 || strncmp((char *)key.dptr, "DN=", 3) != 0) { - return LDB_SUCCESS; + return 0; } 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; + return -1; } ares->message = ldb_msg_new(ares); @@ -417,14 +417,14 @@ static int search_func(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, voi handle->status = LDB_ERR_OPERATIONS_ERROR; handle->state = LDB_ASYNC_DONE; talloc_free(ares); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } /* unpack the record */ ret = ltdb_unpack_data(ac->module, &data, ares->message); - if (ret) { + if (ret == -1) { talloc_free(ares); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } if (!ares->message->dn) { @@ -433,7 +433,7 @@ static int search_func(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, voi handle->status = LDB_ERR_OPERATIONS_ERROR; handle->state = LDB_ASYNC_DONE; talloc_free(ares); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } } @@ -441,17 +441,17 @@ static int search_func(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, voi if (!ldb_match_msg(ac->module->ldb, ares->message, ac->tree, ac->base, ac->scope)) { talloc_free(ares); - return LDB_SUCCESS; + return 0; } /* filter the attributes that the user wants */ ret = ltdb_filter_attrs(ares->message, ac->attrs); - if (ret != LDB_SUCCESS) { + if (ret == -1) { handle->status = LDB_ERR_OPERATIONS_ERROR; handle->state = LDB_ASYNC_DONE; talloc_free(ares); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } ares->type = LDB_REPLY_ENTRY; @@ -460,10 +460,10 @@ static int search_func(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, voi if (handle->status != LDB_SUCCESS) { /* don't try to free ares here, the callback is in charge of that */ - return LDB_ERR_OPERATIONS_ERROR; + return -1; } - return LDB_SUCCESS; + return 0; } diff --git a/source4/lib/ldb/ldb_tdb/ldb_tdb.c b/source4/lib/ldb/ldb_tdb/ldb_tdb.c index b711efd1fa..01d570c89a 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_tdb.c +++ b/source4/lib/ldb/ldb_tdb/ldb_tdb.c @@ -174,7 +174,7 @@ int ltdb_check_special_dn(struct ldb_module *module, if (! ldb_dn_is_special(msg->dn) || ! ldb_dn_check_special(msg->dn, LTDB_ATTRIBUTES)) { - return LDB_SUCCESS; + return 0; } /* we have @ATTRIBUTES, let's check attributes are fine */ @@ -188,7 +188,7 @@ int ltdb_check_special_dn(struct ldb_module *module, } } - return LDB_SUCCESS; + return 0; } @@ -231,7 +231,7 @@ int ltdb_store(struct ldb_module *module, const struct ldb_message *msg, int flg } ret = ltdb_pack_data(module, msg, &tdb_data); - if (ret != LDB_SUCCESS) { + if (ret == -1) { talloc_free(tdb_key.dptr); return LDB_ERR_OTHER; } @@ -626,7 +626,7 @@ int ltdb_modify_internal(struct ldb_module *module, } ret = ltdb_unpack_data(module, &tdb_data, msg2); - if (ret != LDB_SUCCESS) { + if (ret == -1) { ret = LDB_ERR_OTHER; goto failed; } @@ -1069,7 +1069,7 @@ static int ltdb_connect(struct ldb_context *ldb, const char *url, if (strncmp(url, "tdb://", 6) != 0) { ldb_debug(ldb, LDB_DEBUG_ERROR, "Invalid tdb URL '%s'", url); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } path = url+6; } else { @@ -1097,7 +1097,7 @@ static int ltdb_connect(struct ldb_context *ldb, const char *url, ltdb = talloc_zero(ldb, struct ltdb_private); if (!ltdb) { ldb_oom(ldb); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } /* note that we use quite a large default hash size */ @@ -1108,7 +1108,7 @@ static int ltdb_connect(struct ldb_context *ldb, const char *url, ldb_debug(ldb, LDB_DEBUG_ERROR, "Unable to open tdb '%s'\n", path); talloc_free(ltdb); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } ltdb->sequence_number = 0; @@ -1117,7 +1117,7 @@ static int ltdb_connect(struct ldb_context *ldb, const char *url, if (!module) { ldb_oom(ldb); talloc_free(ltdb); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } talloc_set_name_const(*module, "ldb_tdb backend"); (*module)->ldb = ldb; @@ -1128,10 +1128,10 @@ static int ltdb_connect(struct ldb_context *ldb, const char *url, if (ltdb_cache_load(*module) != 0) { talloc_free(*module); talloc_free(ltdb); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } - return LDB_SUCCESS; + return 0; } const struct ldb_backend_ops ldb_tdb_backend_ops = { diff --git a/source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c b/source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c index 9d856355be..4fea43c8c8 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c +++ b/source4/lib/ldb/ldb_tdb/ldb_tdb_wrap.c @@ -53,7 +53,7 @@ static int ltdb_wrap_destructor(struct ltdb_wrap *w) if (w == tdb_list) { tdb_list = w->next; } - return LDB_SUCCESS; + return 0; } static void ltdb_log_fn(struct tdb_context *tdb, enum tdb_debug_level level, const char *fmt, ...) PRINTF_ATTRIBUTE(3, 4); diff --git a/source4/lib/ldb/modules/operational.c b/source4/lib/ldb/modules/operational.c index 716f34d660..a59e81becd 100644 --- a/source4/lib/ldb/modules/operational.c +++ b/source4/lib/ldb/modules/operational.c @@ -158,13 +158,13 @@ static int operational_search_post_process(struct ldb_module *module, } } - return LDB_SUCCESS; + return 0; failed: ldb_debug_set(module->ldb, LDB_DEBUG_WARNING, "operational_search_post_process failed for attribute '%s'\n", attrs[a]); - return LDB_ERR_OPERATIONS_ERROR; + return -1; } diff --git a/source4/lib/ldb/modules/paged_results.c b/source4/lib/ldb/modules/paged_results.c index c7296a1edf..b62b1f92cb 100644 --- a/source4/lib/ldb/modules/paged_results.c +++ b/source4/lib/ldb/modules/paged_results.c @@ -86,7 +86,7 @@ int store_destructor(struct results_store *store) store->priv->store = NULL; } - return LDB_SUCCESS; + return 0; } static struct results_store *new_store(struct private_data *priv) diff --git a/source4/lib/ldb/modules/skel.c b/source4/lib/ldb/modules/skel.c index 15df46354b..0cd29ac4b7 100644 --- a/source4/lib/ldb/modules/skel.c +++ b/source4/lib/ldb/modules/skel.c @@ -90,7 +90,7 @@ static int skel_destructor(struct ldb_module *ctx) struct private_data *data = talloc_get_type(ctx->private_data, struct private_data); /* put your clean-up functions here */ if (data->some_private_data) talloc_free(data->some_private_data); - return LDB_SUCCESS; + return 0; } static int skel_request(struct ldb_module *module, struct ldb_request *req) diff --git a/source4/lib/ldb_wrap.c b/source4/lib/ldb_wrap.c index 8082f4fac5..6c683a1e33 100644 --- a/source4/lib/ldb_wrap.c +++ b/source4/lib/ldb_wrap.c @@ -84,7 +84,7 @@ static int ldb_wrap_destructor(struct ldb_context *ldb) smb_panic("probable memory leak in ldb"); #endif } - return LDB_SUCCESS; + return 0; } /* -- cgit From 964fb9f2492964472666cf10973e1abf6df6882c Mon Sep 17 00:00:00 2001 From: Holger Hetterich Date: Wed, 24 Sep 2008 19:01:00 -0400 Subject: SMB traffic analyzer vfs module from Holger Hetterich Used to gather data to feed to a database for live and historical analysis of usage per user, per share, etc. Helper apps to read the data still to come. This one still needs to be made ipv6 enabled (connection is made to the helper app). --- source3/Makefile.in | 5 + source3/configure.in | 4 +- source3/modules/vfs_smb_traffic_analyzer.c | 352 +++++++++++++++++++++++++++++ 3 files changed, 359 insertions(+), 2 deletions(-) create mode 100644 source3/modules/vfs_smb_traffic_analyzer.c diff --git a/source3/Makefile.in b/source3/Makefile.in index 9e0a1179f3..e541fb32e1 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -621,6 +621,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 @@ -2403,6 +2404,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 diff --git a/source3/configure.in b/source3/configure.in index 63e17dc717..8332b1e34a 100644 --- a/source3/configure.in +++ b/source3/configure.in @@ -407,7 +407,7 @@ 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" 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" @@ -6116,7 +6116,7 @@ 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) diff --git a/source3/modules/vfs_smb_traffic_analyzer.c b/source3/modules/vfs_smb_traffic_analyzer.c new file mode 100644 index 0000000000..4faa041c2f --- /dev/null +++ b/source3/modules/vfs_smb_traffic_analyzer.c @@ -0,0 +1,352 @@ +/* + * traffic-analyzer VFS module. Measure the smb traffic users create + * on the net. + * + * Copyright (C) Holger Hetterich, 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 . + */ + +#include "includes.h" +#include "safe_string.h" +#include +#include +#include + + +/* abstraction for the send_over_network function */ +#define UNIX_DOMAIN_SOCKET 1 +#define INTERNET_SOCKET 0 + + +/* Prototypes */ + +extern userdom_struct current_user_info; + +static int vfs_smb_traffic_analyzer_debug_level = DBGC_VFS; + +NTSTATUS init_samba_module(void); + +static ssize_t smb_traffic_analyzer_write(vfs_handle_struct *handle, + files_struct *fsp, const void *data, size_t n); + +static ssize_t smb_traffic_analyzer_read(vfs_handle_struct *handle, + files_struct *fsp, void *data, size_t n); + +static ssize_t smb_traffic_analyzer_pwrite(vfs_handle_struct *handle, + files_struct *fsp, const void *data, size_t n, + SMB_OFF_T offset); + +static ssize_t smb_traffic_analyzer_pread(vfs_handle_struct *handle, + files_struct *fsp, void *data, size_t n, SMB_OFF_T offset); + + +/* VFS operations we use */ + +static vfs_op_tuple smb_traffic_analyzer_tuples[] = { + + {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 init_samba_module(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: Couldn't register custom" + "debugging class!\n")); + } else { + DEBUG(3, ("smb_traffic_analyzer: Debug class number of" + "'smb_traffic_analyzer': %d\n", \ + vfs_smb_traffic_analyzer_debug_level)); + } + + return ret; +} + +/* create the timestamp in sqlite compatible format */ +static void get_timestamp( char *String ) +{ + struct timeval tv; + struct timezone tz; + struct tm *tm; + int seconds; + + gettimeofday(&tv, &tz); + tm=localtime(&tv.tv_sec); + seconds=(float) (tv.tv_usec / 1000); + + fstr_sprintf(String,"%04d-%02d-%02d %02d:%02d:%02d.%03d", \ + tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, \ + tm->tm_hour, tm->tm_min, tm->tm_sec, (int)seconds); + +} + +static int 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; + } + +} + + + +/* Send data over a internet socket */ +static void smb_traffic_analyzer_send_data_inet_socket( char *String, + vfs_handle_struct *handle, const char *file_name, + bool Write) +{ + /* Create a streaming Socket */ + const char *Hostname; + int sockfd, result; + int port; + struct sockaddr_in their_addr; + struct hostent *hp; + char Sender[200]; + char TimeStamp[200]; + int yes = 1; + connection_struct *conn; + + if ((sockfd=socket(AF_INET, SOCK_STREAM,0)) == -1) { + DEBUG(1, ("unable to create socket, error is %s", + strerror(errno))); + return; + } + if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, \ + sizeof(int)) == -1) { + DEBUG(1, ("unable to set socket options, error is %s", + strerror(errno))); + return; + } + /* get port number, target system from the config parameters */ + conn=handle->conn; + + Hostname=lp_parm_const_string(SNUM(conn), "smb_traffic_analyzer", + "host", "localhost"); + + port = atoi( lp_parm_const_string(SNUM(conn), + "smb_traffic_analyzer", "port", "9430")); + + hp = gethostbyname(Hostname); + if (hp == NULL) { + DEBUG(1, ("smb_traffic_analyzer: Unkown Hostname of" + "target system!\n")); + } + DEBUG(3,("smb_traffic_analyzer: Internet socket mode. Hostname: %s," + "Port: %i\n", Hostname, port)); + + their_addr.sin_family = AF_INET; + their_addr.sin_port = htons(port); + their_addr.sin_addr.s_addr = INADDR_ANY; + memset(their_addr.sin_zero, '\0', sizeof(their_addr.sin_zero)); + memcpy(hp->h_addr, &their_addr.sin_addr, hp->h_length); + their_addr.sin_port=htons(port); + result=connect( sockfd, &their_addr, sizeof( struct sockaddr_in)); + if ( result < 0 ) { + DEBUG(1, ("smb_traffic_analyzer: Couldn't connect to inet" + "socket!\n")); + } + safe_strcpy(Sender, String, sizeof(Sender) - 1); + safe_strcat(Sender, ",\"", sizeof(Sender) - 1); + safe_strcat(Sender, get_current_username(), sizeof(Sender) - 1); + safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); + safe_strcat(Sender, current_user_info.domain, sizeof(Sender) - 1); + safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); + if (Write) + safe_strcat(Sender, "W", sizeof(Sender) - 1); + else + safe_strcat(Sender, "R", sizeof(Sender) - 1); + safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); + safe_strcat(Sender, handle->conn->connectpath, sizeof(Sender) - 1); + safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); + safe_strcat(Sender, file_name, sizeof(Sender) - 1); + safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); + get_timestamp(TimeStamp); + safe_strcat(Sender, TimeStamp, sizeof(Sender) - 1); + safe_strcat(Sender, "\");", sizeof(Sender) - 1); + DEBUG(10, ("smb_traffic_analyzer: sending %s\n", Sender)); + if ( send(sockfd, Sender, strlen(Sender), 0) == -1 ) { + DEBUG(1, ("smb_traffic_analyzer: error sending data to socket!\n")); + return ; + } + + /* one operation, close the socket */ + close(sockfd); +} + + + +/* Send data over a unix domain socket */ +static void smb_traffic_analyzer_send_data_unix_socket( char *String , + vfs_handle_struct *handle, const char *file_name, + bool Write) +{ + /* Create the socket to stad */ + int len, sock; + struct sockaddr_un remote; + char Sender[200]; + char TimeStamp[200]; + DEBUG(7, ("smb_traffic_analyzer: Unix domain socket mode. Using " + "/var/tmp/stadsocket\n")); + if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { + DEBUG(1, ("smb_traffic_analyzer: Couldn create socket," + "make sure stad is running!\n")); + } + remote.sun_family = AF_UNIX; + safe_strcpy(remote.sun_path, "/var/tmp/stadsocket", + sizeof(remote.sun_path) - 1); + len=strlen(remote.sun_path) + sizeof(remote.sun_family); + if (connect(sock, (struct sockaddr *)&remote, len) == -1 ) { + DEBUG(1, ("smb_traffic_analyzer: Could not connect to" + "socket, make sure\nstad is running!\n")); + } + safe_strcpy(Sender, String, sizeof(Sender) - 1); + safe_strcat(Sender, ",\"", sizeof(Sender) - 1); + safe_strcat(Sender, get_current_username(), sizeof(Sender) - 1); + safe_strcat(Sender,"\",\"",sizeof(Sender) - 1); + safe_strcat(Sender, current_user_info.domain, sizeof(Sender) - 1); + safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); + if (Write) + safe_strcat(Sender, "W", sizeof(Sender) - 1); + else + safe_strcat(Sender, "R", sizeof(Sender) - 1); + safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); + safe_strcat(Sender, handle->conn->connectpath, sizeof(Sender) - 1); + safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); + safe_strcat(Sender, file_name, sizeof(Sender) - 1); + safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); + get_timestamp(TimeStamp); + safe_strcat(Sender, TimeStamp, sizeof(Sender) - 1); + safe_strcat(Sender, "\");", sizeof(Sender) - 1); + + DEBUG(10, ("smb_traffic_analyzer: sending %s\n", Sender)); + if ( send(sock, Sender, strlen(Sender), 0) == -1 ) { + DEBUG(1, ("smb_traffic_analyzer: error sending data to" + "socket!\n")); + return; + } + + /* one operation, close the socket */ + close(sock); + + return; +} + +static void smb_traffic_analyzer_send_data( char *Buffer , vfs_handle_struct \ + *handle, char *file_name, bool Write, files_struct *fsp) +{ + + if (smb_traffic_analyzer_connMode(handle) == UNIX_DOMAIN_SOCKET) { + smb_traffic_analyzer_send_data_unix_socket(Buffer, handle, \ + fsp->fsp_name, Write); + } else { + smb_traffic_analyzer_send_data_inet_socket(Buffer, handle, \ + fsp->fsp_name, Write); + } +} + + + +/* 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; + char Buffer[100]; + + result = SMB_VFS_NEXT_READ(handle, fsp, data, n); + DEBUG(10, ("smb_traffic_analyzer: READ: %s\n", fsp->fsp_name )); + + fstr_sprintf(Buffer, "%u", (uint) result); + + smb_traffic_analyzer_send_data(Buffer, handle, fsp->fsp_name, false, fsp); + 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; + char Buffer[100]; + + result = SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset); + + DEBUG(10, ("smb_traffic_analyzer: READ: %s\n", fsp->fsp_name )); + + fstr_sprintf(Buffer,"%u", (uint) result); + smb_traffic_analyzer_send_data(Buffer, handle, fsp->fsp_name, false, fsp); + + 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; + char Buffer[100]; + + result = SMB_VFS_NEXT_WRITE(handle, fsp, data, n); + + DEBUG(10, ("smb_traffic_analyzer: WRITE: %s\n", fsp->fsp_name )); + + fstr_sprintf(Buffer, "%u", (uint) result); + smb_traffic_analyzer_send_data(Buffer, handle, fsp->fsp_name, \ + true, fsp ); + 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; + char Buffer[100]; + + result = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset); + + DEBUG(10, ("smb_traffic_analyzer: PWRITE: %s\n", fsp->fsp_name )); + + fstr_sprintf(Buffer, "%u", (uint) result); + smb_traffic_analyzer_send_data(Buffer, handle, fsp->fsp_name, true, fsp); + return result; +} + -- cgit From 3eb122069b9f81196ac658375fcb828924af3e94 Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Wed, 24 Sep 2008 19:22:39 -0400 Subject: Temporary build fix for the merged build --- libcli/netlogon.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/libcli/netlogon.c b/libcli/netlogon.c index ab5d9af8aa..36d9e5fdcd 100644 --- a/libcli/netlogon.c +++ b/libcli/netlogon.c @@ -22,6 +22,13 @@ #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) -- cgit From a78ac8a46be3e7c1cf3004b85aa1ec4d0330e5d2 Mon Sep 17 00:00:00 2001 From: Jim McDonough Date: Wed, 24 Sep 2008 20:47:03 -0400 Subject: Fix the new vfs_smb_traffic_analyzer build for static links --- source3/modules/vfs_smb_traffic_analyzer.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source3/modules/vfs_smb_traffic_analyzer.c b/source3/modules/vfs_smb_traffic_analyzer.c index 4faa041c2f..237859182b 100644 --- a/source3/modules/vfs_smb_traffic_analyzer.c +++ b/source3/modules/vfs_smb_traffic_analyzer.c @@ -36,7 +36,7 @@ extern userdom_struct current_user_info; static int vfs_smb_traffic_analyzer_debug_level = DBGC_VFS; -NTSTATUS init_samba_module(void); +NTSTATUS vfs_smb_traffic_analyzer_init(void); static ssize_t smb_traffic_analyzer_write(vfs_handle_struct *handle, files_struct *fsp, const void *data, size_t n); @@ -71,7 +71,7 @@ static vfs_op_tuple smb_traffic_analyzer_tuples[] = { /* Module initialization */ -NTSTATUS init_samba_module(void) +NTSTATUS vfs_smb_traffic_analyzer_init(void) { NTSTATUS ret = smb_register_vfs(SMB_VFS_INTERFACE_VERSION, \ "smb_traffic_analyzer", smb_traffic_analyzer_tuples); -- cgit From ff542275c3e2bf432bcc303e95124374ada03675 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 23 Sep 2008 20:01:06 -0700 Subject: stricter checking of SMB2 echo body (per the spec) thanks to the bluearc test suite --- source4/smb_server/smb2/keepalive.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/source4/smb_server/smb2/keepalive.c b/source4/smb_server/smb2/keepalive.c index f40bcc485c..d1a0ef3d72 100644 --- a/source4/smb_server/smb2/keepalive.c +++ b/source4/smb_server/smb2/keepalive.c @@ -54,11 +54,16 @@ void smb2srv_keepalive_recv(struct smb2srv_request *req) { uint16_t _pad; - if (req->in.body_size < 0x04) { + if (req->in.body_size != 0x04) { smb2srv_send_error(req, NT_STATUS_FOOBAR); return; } + if (SVAL(req->in.body, 0x00) != 0x04) { + smb2srv_send_error(req, NT_STATUS_INVALID_PARAMETER); + return; + } + _pad = SVAL(req->in.body, 0x02); req->status = smb2srv_keepalive_backend(req); -- cgit From 71ae732669d641cf8b3fd7f6fa73ead4634178f1 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 08:58:16 -0700 Subject: fixed error code for bad keepalive --- source4/smb_server/smb2/keepalive.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/smb_server/smb2/keepalive.c b/source4/smb_server/smb2/keepalive.c index d1a0ef3d72..ff47d594f0 100644 --- a/source4/smb_server/smb2/keepalive.c +++ b/source4/smb_server/smb2/keepalive.c @@ -55,7 +55,7 @@ void smb2srv_keepalive_recv(struct smb2srv_request *req) uint16_t _pad; if (req->in.body_size != 0x04) { - smb2srv_send_error(req, NT_STATUS_FOOBAR); + smb2srv_send_error(req, NT_STATUS_INVALID_PARAMETER); return; } -- cgit From 9fcafbb42cbe759711db4a47c2969bd34229e4a0 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 11:28:58 -0700 Subject: support NT_STATUS_XX:NT_STATUS_YY syntax in ignore files --- source4/torture/gentest.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/source4/torture/gentest.c b/source4/torture/gentest.c index 176fc035e7..1b8f97596b 100644 --- a/source4/torture/gentest.c +++ b/source4/torture/gentest.c @@ -1165,6 +1165,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 +1180,18 @@ 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)); + printf("pattern: %s\n", s); + if (ignore_pattern(s)) { + return true; + } + current_op.mismatch = nt_errstr(status1); return false; } @@ -1348,7 +1362,7 @@ again: } \ current_op.status = status[0]; \ for (i=1;i Date: Wed, 24 Sep 2008 15:40:55 -0700 Subject: fixed uninitialised variable bug --- source4/libcli/clideltree.c | 1 + 1 file changed, 1 insertion(+) diff --git a/source4/libcli/clideltree.c b/source4/libcli/clideltree.c index d59a03f194..28563d918e 100644 --- a/source4/libcli/clideltree.c +++ b/source4/libcli/clideltree.c @@ -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; } -- cgit From 76835f103ec65bb00ff3ca11015176ea2f5ecb06 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:17:41 -0700 Subject: fixed setpathinfo in gentest to not zero the filename/handle --- source4/torture/gentest.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/source4/torture/gentest.c b/source4/torture/gentest.c index 1b8f97596b..fecdfda56e 100644 --- a/source4/torture/gentest.c +++ b/source4/torture/gentest.c @@ -1187,7 +1187,6 @@ static bool compare_status(NTSTATUS status1, NTSTATUS status2) s = talloc_asprintf(current_op.mem_ctx, "%s:%s", nt_errstr(status1), nt_errstr(status2)); - printf("pattern: %s\n", s); if (ignore_pattern(s)) { return true; } @@ -2393,9 +2392,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; @@ -2764,9 +2762,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); -- cgit From 9a50009430e2da70d3753c36d66e4168c27029d9 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:18:29 -0700 Subject: check error code for zero desired_access in SMB2 create --- source4/torture/smb2/create.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/source4/torture/smb2/create.c b/source4/torture/smb2/create.c index 4d1b4a7ed0..124e244151 100644 --- a/source4/torture/smb2/create.c +++ b/source4/torture/smb2/create.c @@ -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); -- cgit From 38e70dc47aae6b3bd7ddbcda61e0989f8d659f2b Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:19:36 -0700 Subject: be friendlier in smb2_deltree to some of the SMB2 implementations that don't handle SEC_FLAG_MAXIMUM_ALLOWED --- source4/libcli/smb2/util.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/libcli/smb2/util.c b/source4/libcli/smb2/util.c index b149b3d6ce..a360d8fbdf 100644 --- a/source4/libcli/smb2/util.c +++ b/source4/libcli/smb2/util.c @@ -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; -- cgit From 9cf3d82d6366e11d1ffee89d405083b7a577c6d6 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:20:28 -0700 Subject: added the structure for LINK_INFORMATION setfileinfo call --- source4/libcli/raw/interfaces.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/source4/libcli/raw/interfaces.h b/source4/libcli/raw/interfaces.h index 20ed441435..c2269cbbc2 100644 --- a/source4/libcli/raw/interfaces.h +++ b/source4/libcli/raw/interfaces.h @@ -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; -- cgit From b1f17b23fe58acba924ce11bb8ec700cd2a1bd7e Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:26:42 -0700 Subject: - use the current dialect first, for servers that only look at the first dialect - allow override of SMB2 port in client code --- source4/libcli/smb2/connect.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/source4/libcli/smb2/connect.c b/source4/libcli/smb2/connect.c index 43151943d3..e0b75a2542 100644 --- a/source4/libcli/smb2/connect.c +++ b/source4/libcli/smb2/connect.c @@ -27,6 +27,7 @@ #include "libcli/composite/composite.h" #include "libcli/resolve/resolve.h" #include "param/param.h" +#include "lib/cmdline/popt_common.h" struct smb2_connect_state { struct cli_credentials *credentials; @@ -184,8 +185,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 +207,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, cmdline_lp_ctx, NULL, "smb2", "ports", NULL); + if (ports == NULL) { + ports = default_ports; + } c->status = resolve_name_recv(creq, state, &addr); if (!composite_is_ok(c)) return; -- cgit From 4904882fed1e3b72ba45052323c95c0fda301d64 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:28:58 -0700 Subject: - SMB2 uses INVALID_PARAMETER not BUFFER_TOO_SMALL for buffer size errors - added a s32o16 buffer function --- source4/libcli/smb2/request.c | 54 +++++++++++++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 15 deletions(-) diff --git a/source4/libcli/smb2/request.c b/source4/libcli/smb2/request.c index 64d427f889..137e2f2f12 100644 --- a/source4/libcli/smb2/request.c +++ b/source4/libcli/smb2/request.c @@ -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); -- cgit From d3c6c71ff2d5499be152785a49ad128641330b40 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:31:57 -0700 Subject: zero access mask should give ACCESS_DENIED --- source4/ntvfs/posix/pvfs_acl.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source4/ntvfs/posix/pvfs_acl.c b/source4/ntvfs/posix/pvfs_acl.c index 57a463aba6..06a4e69004 100644 --- a/source4/ntvfs/posix/pvfs_acl.c +++ b/source4/ntvfs/posix/pvfs_acl.c @@ -511,6 +511,10 @@ NTSTATUS pvfs_access_check(struct pvfs_state *pvfs, NTSTATUS status; struct security_descriptor *sd; + if (*access_mask == 0) { + return NT_STATUS_ACCESS_DENIED; + } + if (pvfs_read_only(pvfs, *access_mask)) { return NT_STATUS_ACCESS_DENIED; } -- cgit From 7e57626d1d5a4497ecf5b4c741b8486e7ab97733 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:32:47 -0700 Subject: the offset is 16 bits in SMB2 fileinfo --- source4/smb_server/smb2/fileinfo.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/smb_server/smb2/fileinfo.c b/source4/smb_server/smb2/fileinfo.c index 6c4b8f33d5..82b006c4a1 100644 --- a/source4/smb_server/smb2/fileinfo.c +++ b/source4/smb_server/smb2/fileinfo.c @@ -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); -- cgit From a3536c4c06d9725b2e96b9a3ddc1ab14e47f472c Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:33:15 -0700 Subject: check for a 0 byte in the buffer in SMB2 read --- source4/smb_server/smb2/fileio.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/source4/smb_server/smb2/fileio.c b/source4/smb_server/smb2/fileio.c index 2c322ea587..4f4402ba33 100644 --- a/source4/smb_server/smb2/fileio.c +++ b/source4/smb_server/smb2/fileio.c @@ -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); -- cgit From 49c80cea0bc00a88336fc9bd4bb332a7a399afd5 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:34:04 -0700 Subject: cope with body_size zero in SMB2 receive --- source4/smb_server/smb2/smb2_server.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source4/smb_server/smb2/smb2_server.h b/source4/smb_server/smb2/smb2_server.h index d45e0861af..431add4ed9 100644 --- a/source4/smb_server/smb2/smb2_server.h +++ b/source4/smb_server/smb2/smb2_server.h @@ -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)); \ -- cgit From 59847fd6b6c208377f8b1bcb32347d7c4ab16911 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:34:35 -0700 Subject: log stream termination --- source4/smbd/service_stream.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source4/smbd/service_stream.c b/source4/smbd/service_stream.c index f27560f6ee..48eda46dc7 100644 --- a/source4/smbd/service_stream.c +++ b/source4/smbd/service_stream.c @@ -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) { -- cgit From 63685c7d02f2364344fd8d4a3307ee36716e4a66 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:34:58 -0700 Subject: record highest seq number in SMB2 to check for seqnum going backwards --- source4/smb_server/smb_server.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source4/smb_server/smb_server.h b/source4/smb_server/smb_server.h index 4676fc3e9c..b3c3122765 100644 --- a/source4/smb_server/smb_server.h +++ b/source4/smb_server/smb_server.h @@ -386,6 +386,8 @@ struct smbsrv_connection { struct loadparm_context *lp_ctx; bool smb2_signing_required; + + uint64_t highest_smb2_seqnum; }; struct model_ops; -- cgit From 742a99e046313760a281da67eb3ba6e7fcfa8fa6 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:36:24 -0700 Subject: - add reserved field in basic_information level - use INVALID_PARAMETER for info length mismatch to match windows behaviour - added parsing of LINK_INFORMATION level --- source4/smb_server/blob.c | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/source4/smb_server/blob.c b/source4/smb_server/blob.c index 368b81d18e..4f018a5143 100644 --- a/source4/smb_server/blob.c +++ b/source4/smb_server/blob.c @@ -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) { -- cgit From 5a5e2df5694c5dc1be2692e8547370bcdfc58ad0 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:41:36 -0700 Subject: for use in python we need to use global_loadparm --- source4/libcli/smb2/connect.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/libcli/smb2/connect.c b/source4/libcli/smb2/connect.c index e0b75a2542..db2f97bb94 100644 --- a/source4/libcli/smb2/connect.c +++ b/source4/libcli/smb2/connect.c @@ -210,7 +210,7 @@ static void continue_resolve(struct composite_context *creq) const char **ports; const char *default_ports[] = { "445", NULL }; - ports = lp_parm_string_list(state, cmdline_lp_ctx, NULL, "smb2", "ports", NULL); + ports = lp_parm_string_list(state, global_loadparm, NULL, "smb2", "ports", NULL); if (ports == NULL) { ports = default_ports; } -- cgit From eb5b3f50d17dfca198304d636033ad93410d570f Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:45:48 -0700 Subject: we should terminate the connection on a bad negprot packet size --- source4/smb_server/smb2/negprot.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source4/smb_server/smb2/negprot.c b/source4/smb_server/smb2/negprot.c index d64b36d659..49a2d12ef4 100644 --- a/source4/smb_server/smb2/negprot.c +++ b/source4/smb_server/smb2/negprot.c @@ -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; } -- cgit From d2bdb8fb1685d7ab2f23a4c4169bcc2e5c97f675 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 17:58:15 -0700 Subject: empty access mask is only denied on SMB2 --- source4/ntvfs/posix/pvfs_acl.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source4/ntvfs/posix/pvfs_acl.c b/source4/ntvfs/posix/pvfs_acl.c index 06a4e69004..d479f1e2ee 100644 --- a/source4/ntvfs/posix/pvfs_acl.c +++ b/source4/ntvfs/posix/pvfs_acl.c @@ -511,7 +511,9 @@ NTSTATUS pvfs_access_check(struct pvfs_state *pvfs, NTSTATUS status; struct security_descriptor *sd; - if (*access_mask == 0) { + /* on SMB2 a blank access mask is always denied */ + if (pvfs->ntvfs->ctx->protocol == PROTOCOL_SMB2 && + *access_mask == 0) { return NT_STATUS_ACCESS_DENIED; } -- cgit From bda97661ffd230a9b58527faebdc79f37bb8352b Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 18:28:58 -0700 Subject: fixed expansion of $USERNAME in signing tests --- source4/selftest/samba4_tests.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/selftest/samba4_tests.sh b/source4/selftest/samba4_tests.sh index 36d52fff5a..667b21975f 100755 --- a/source4/selftest/samba4_tests.sh +++ b/source4/selftest/samba4_tests.sh @@ -326,7 +326,7 @@ 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 "$*" -- cgit From 0cf717512659469a9b293685ba2a6db4742dcff7 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 24 Sep 2008 18:58:38 -0700 Subject: we need different error handling for truncated packets in NETPROT and other SMB2 operations. --- source4/libcli/smb2/smb2.h | 1 + source4/smb_server/smb2/receive.c | 41 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/source4/libcli/smb2/smb2.h b/source4/libcli/smb2/smb2.h index f00107de60..9d63a4a95f 100644 --- a/source4/libcli/smb2/smb2.h +++ b/source4/libcli/smb2/smb2.h @@ -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 diff --git a/source4/smb_server/smb2/receive.c b/source4/smb_server/smb2/receive.c index 1fe6f0b877..c3607f0a33 100644 --- a/source4/smb_server/smb2/receive.c +++ b/source4/smb_server/smb2/receive.c @@ -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; -- cgit From f27774729e8c88615b9d3d25a85cae0a1fc35c4f Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Wed, 24 Sep 2008 18:52:04 -0700 Subject: s3:lib/ldb: Don't return already freed pointer on error. metze Signed-off-by: Karolin Seeger --- source3/lib/ldb/common/ldb.c | 1 + 1 file changed, 1 insertion(+) diff --git a/source3/lib/ldb/common/ldb.c b/source3/lib/ldb/common/ldb.c index 743711b967..c8aa6afdfc 100644 --- a/source3/lib/ldb/common/ldb.c +++ b/source3/lib/ldb/common/ldb.c @@ -787,6 +787,7 @@ int ldb_search(struct ldb_context *ldb, done: if (ret != LDB_SUCCESS) { talloc_free(res); + res = NULL; } *_res = res; -- cgit From 73769e136e85fd1f6d39dad89bd84cdb7d758764 Mon Sep 17 00:00:00 2001 From: "Gerald W. Carter" Date: Tue, 23 Sep 2008 11:40:28 -0700 Subject: Document how to enable the name aliasing support in Winbind. (cherry picked from commit 6dc81eb85b11851794619a1f2769d68cd9a54fb6) --- .../smbdotconf/winbind/winbindnormalizenames.xml | 27 +++++++++++++++------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/docs-xml/smbdotconf/winbind/winbindnormalizenames.xml b/docs-xml/smbdotconf/winbind/winbindnormalizenames.xml index 28826cf5f3..5b68bca912 100644 --- a/docs-xml/smbdotconf/winbind/winbindnormalizenames.xml +++ b/docs-xml/smbdotconf/winbind/winbindnormalizenames.xml @@ -5,14 +5,25 @@ xmlns:samba="http://www.samba.org/samba/DTD/samba-doc"> This parameter controls whether winbindd will replace - whitespace in user and group names with an underscore (_) character. - For example, whether the name "Space Kadet" should be - replaced with the string "space_kadet". - 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 - + whitespace in user and group names with an underscore (_) character. + For example, whether the name "Space Kadet" should be + replaced with the string "space_kadet". + 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. + + + 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. + + no -- cgit From a089b3bb99a226e8f99884867a677672cc028f1c Mon Sep 17 00:00:00 2001 From: "Gerald W. Carter" Date: Tue, 23 Sep 2008 11:43:05 -0700 Subject: Document the new hash and adex idmap/nss_info plugins. (cherry picked from commit 77bc0be0536bcd6a3ce8283a708828bebbbffee3) --- docs-xml/manpages-3/idmap_adex.8.xml | 89 ++++++++++++++++++++++++++++++++++++ docs-xml/manpages-3/idmap_hash.8.xml | 76 ++++++++++++++++++++++++++++++ 2 files changed, 165 insertions(+) create mode 100644 docs-xml/manpages-3/idmap_adex.8.xml create mode 100644 docs-xml/manpages-3/idmap_hash.8.xml diff --git a/docs-xml/manpages-3/idmap_adex.8.xml b/docs-xml/manpages-3/idmap_adex.8.xml new file mode 100644 index 0000000000..9eb2ff7d46 --- /dev/null +++ b/docs-xml/manpages-3/idmap_adex.8.xml @@ -0,0 +1,89 @@ + + + + + + idmap_adex + 8 + Samba + System Administration tools + 3.2 + + + + + idmap_adex + Samba's idmap_adex Backend for Winbind + + + + DESCRIPTION + + 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 "Identity + Services for Unix" support on Windows 2003 R2 and later. + + + + 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). + + + + + NSS_INFO + + 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. + + + + 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. + + + + + EXAMPLES + + The following example shows how to retrieve idmappings and NSS data + from our principal and trusted AD domains. + + + + [global] + idmap backend = adex + idmap uid = 1000-4000000000 + idmap gid = 1000-4000000000 + + winbind nss info = adex + winbind normalize names = yes + + + + + AUTHOR + + + 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. + + + + diff --git a/docs-xml/manpages-3/idmap_hash.8.xml b/docs-xml/manpages-3/idmap_hash.8.xml new file mode 100644 index 0000000000..8e452b3c89 --- /dev/null +++ b/docs-xml/manpages-3/idmap_hash.8.xml @@ -0,0 +1,76 @@ + + + + + + idmap_hash + 8 + Samba + System Administration tools + 3.2 + + + + + idmap_hash + Samba's idmap_hash Backend for Winbind + + + + DESCRIPTION + 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 + "winbind normlaize names" and "winbind nss info" + parameters in smb.conf. + + + + + IDMAP OPTIONS + + + + name_map + + Specifies the absolute path to the name mapping + file used by the nss_info API. Entries in the file + are of the form "unix name + = qualified domain name"e;. + Mapping of both user and group names is supported. + + + + + + + EXAMPLES + The following example utilizes the idmap_hash plugin for + the idmap and nss_info information. + + + + [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 + + + + + AUTHOR + + + 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. + + + + -- cgit From 571f23c03cc443e88029be3a020faa499f1e10cb Mon Sep 17 00:00:00 2001 From: "Gerald W. Carter" Date: Thu, 25 Sep 2008 09:14:58 -0700 Subject: idmap_adex: Fix the nss_info install link. --- source3/Makefile.in | 1 + 1 file changed, 1 insertion(+) diff --git a/source3/Makefile.in b/source3/Makefile.in index e541fb32e1..8f9bd80da8 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -2538,6 +2538,7 @@ 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@ installscripts:: installdirs @$(SHELL) $(srcdir)/script/installscripts.sh $(INSTALLPERMS_BIN) $(DESTDIR)$(BINDIR) $(SCRIPTS) -- cgit From e9e0e9a401f581286ed8d3f1f9f277e134478ade Mon Sep 17 00:00:00 2001 From: "Gerald W. Carter" Date: Thu, 25 Sep 2008 09:41:49 -0700 Subject: idmap_hash: Fix the nss_info link during "make install" --- source3/Makefile.in | 1 + 1 file changed, 1 insertion(+) diff --git a/source3/Makefile.in b/source3/Makefile.in index 8f9bd80da8..18b1d9ad30 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -2539,6 +2539,7 @@ installmodules:: modules installdirs @$(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) -- cgit From 7e38942431697d9d9f245aa8f596189815b7586f Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Thu, 25 Sep 2008 10:06:11 -0700 Subject: Remove these no longer used include files. Jeremy. --- source3/include/libmsrpc.h | 3045 ----------------------------------- source3/include/libmsrpc_internal.h | 73 - 2 files changed, 3118 deletions(-) delete mode 100644 source3/include/libmsrpc.h delete mode 100644 source3/include/libmsrpc_internal.h diff --git a/source3/include/libmsrpc.h b/source3/include/libmsrpc.h deleted file mode 100644 index 3f2a7260ca..0000000000 --- a/source3/include/libmsrpc.h +++ /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 . - */ - -#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:
- * 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 index 623c43f9c3..0000000000 --- a/source3/include/libmsrpc_internal.h +++ /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 . - */ - -#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 */ -- cgit From 6f46002ff6b153730635bfd4a8380792a815ce6b Mon Sep 17 00:00:00 2001 From: "Gerald W. Carter" Date: Thu, 25 Sep 2008 10:43:56 -0700 Subject: idmap: Fix typo is gid2sid() that was caching using idmap_cache_set_sid2uid() --- source3/winbindd/idmap_util.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/winbindd/idmap_util.c b/source3/winbindd/idmap_util.c index b10a1a4ba9..9f876618be 100644 --- a/source3/winbindd/idmap_util.c +++ b/source3/winbindd/idmap_util.c @@ -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; } -- cgit From 81fde585516957b6a7742e0168c68df33572ed74 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Wed, 24 Sep 2008 09:05:37 +0200 Subject: s3-nbt: remove double nbt netlogon opcodes. Guenther --- source3/include/nameserv.h | 11 ----------- source3/nmbd/nmbd_processlogon.c | 30 +++++++++++++++--------------- source3/utils/net_ads.c | 8 ++++---- 3 files changed, 19 insertions(+), 30 deletions(-) diff --git a/source3/include/nameserv.h b/source3/include/nameserv.h index 4377e3330a..a7d46e72d8 100644 --- a/source3/include/nameserv.h +++ b/source3/include/nameserv.h @@ -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 diff --git a/source3/nmbd/nmbd_processlogon.c b/source3/nmbd/nmbd_processlogon.c index 474ae1ca18..814eaf7ca8 100644 --- a/source3/nmbd/nmbd_processlogon.c +++ b/source3/nmbd/nmbd_processlogon.c @@ -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/utils/net_ads.c b/source3/utils/net_ads.c index 1ef4c152a3..627374cb96 100644 --- a/source3/utils/net_ads.c +++ b/source3/utils/net_ads.c @@ -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); -- cgit From da955d7193af4c5bf76f91cf8219e051de59ce7f Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Wed, 24 Sep 2008 11:06:39 +0200 Subject: s3-nbt: further cleanup of dsgetdcname(). Guenther --- source3/libsmb/dsgetdcname.c | 188 ++++++------------------------------------- 1 file changed, 25 insertions(+), 163 deletions(-) diff --git a/source3/libsmb/dsgetdcname.c b/source3/libsmb/dsgetdcname.c index a543e073bc..89769d8a76 100644 --- a/source3/libsmb/dsgetdcname.c +++ b/source3/libsmb/dsgetdcname.c @@ -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); /**************************************************************** @@ -358,7 +358,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 +388,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 +784,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 +805,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,7 +913,7 @@ 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->nt5_ex, info); if (NT_STATUS_IS_OK(status)) { return store_cldap_reply(mem_ctx, flags, &dclist[i].ss, nt_version, &r->nt5_ex); @@ -1187,7 +1049,7 @@ 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->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); -- cgit From 917b141e7dd3e57045c76909b577570fc685fc9b Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 16 Sep 2008 17:53:06 +0200 Subject: netapi: start supporting NetUserSetInfo level 3. Guenther --- source3/lib/netapi/user.c | 53 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 46 insertions(+), 7 deletions(-) diff --git a/source3/lib/netapi/user.c b/source3/lib/netapi/user.c index 7d0c47f331..fcb87b77be 100644 --- a/source3/lib/netapi/user.c +++ b/source3/lib/netapi/user.c @@ -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: -- cgit From da6c7aa2a1ff658777d522077430f9bf410d58d3 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Thu, 25 Sep 2008 12:02:22 -0700 Subject: Use IPv4/v6 independent calls. Change safe_strcpy/cat to strlcpy/cat (this needs changing to talloc_sprintf) and fix file descriptor resource leaks in error paths. Jim and Holger please check ! Jeremy. --- source3/modules/vfs_smb_traffic_analyzer.c | 181 ++++++++++++++++------------- 1 file changed, 97 insertions(+), 84 deletions(-) diff --git a/source3/modules/vfs_smb_traffic_analyzer.c b/source3/modules/vfs_smb_traffic_analyzer.c index 237859182b..9e4cf81638 100644 --- a/source3/modules/vfs_smb_traffic_analyzer.c +++ b/source3/modules/vfs_smb_traffic_analyzer.c @@ -19,11 +19,6 @@ */ #include "includes.h" -#include "safe_string.h" -#include -#include -#include - /* abstraction for the send_over_network function */ #define UNIX_DOMAIN_SOCKET 1 @@ -127,84 +122,99 @@ static int smb_traffic_analyzer_connMode( vfs_handle_struct *handle) } - - /* Send data over a internet socket */ static void smb_traffic_analyzer_send_data_inet_socket( char *String, vfs_handle_struct *handle, const char *file_name, bool Write) { - /* Create a streaming Socket */ - const char *Hostname; - int sockfd, result; - int port; - struct sockaddr_in their_addr; - struct hostent *hp; - char Sender[200]; - char TimeStamp[200]; - int yes = 1; - connection_struct *conn; + /* Create a streaming Socket */ + const char *Hostname; + int sockfd = -1; + uint16_t port; + struct addrinfo hints; + struct addrinfo *ailist = NULL; + struct addrinfo *res = NULL; + char Sender[200]; + char TimeStamp[200]; + connection_struct *conn = handle->conn; + int ret; - if ((sockfd=socket(AF_INET, SOCK_STREAM,0)) == -1) { - DEBUG(1, ("unable to create socket, error is %s", - strerror(errno))); - return; - } - if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, \ - sizeof(int)) == -1) { - DEBUG(1, ("unable to set socket options, error is %s", - strerror(errno))); - return; - } /* get port number, target system from the config parameters */ - conn=handle->conn; - Hostname=lp_parm_const_string(SNUM(conn), "smb_traffic_analyzer", - "host", "localhost"); + "host", "localhost"); + + ZERO_STRUCT(hints); + /* By default make sure it supports TCP. */ + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_ADDRCONFIG; + + ret = getaddrinfo(Hostname, + NULL, + &hints, + &ailist); + + if (ret) { + DEBUG(3,("smb_traffic_analyzer_send_data_inet_socket: " + "getaddrinfo failed for name %s [%s]\n", + Hostname, + gai_strerror(ret) )); + return; + } port = atoi( lp_parm_const_string(SNUM(conn), "smb_traffic_analyzer", "port", "9430")); - hp = gethostbyname(Hostname); - if (hp == NULL) { - DEBUG(1, ("smb_traffic_analyzer: Unkown Hostname of" - "target system!\n")); - } DEBUG(3,("smb_traffic_analyzer: Internet socket mode. Hostname: %s," "Port: %i\n", Hostname, port)); - their_addr.sin_family = AF_INET; - their_addr.sin_port = htons(port); - their_addr.sin_addr.s_addr = INADDR_ANY; - memset(their_addr.sin_zero, '\0', sizeof(their_addr.sin_zero)); - memcpy(hp->h_addr, &their_addr.sin_addr, hp->h_length); - their_addr.sin_port=htons(port); - result=connect( sockfd, &their_addr, sizeof( struct sockaddr_in)); - if ( result < 0 ) { - DEBUG(1, ("smb_traffic_analyzer: Couldn't connect to inet" - "socket!\n")); + 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; } - safe_strcpy(Sender, String, sizeof(Sender) - 1); - safe_strcat(Sender, ",\"", sizeof(Sender) - 1); - safe_strcat(Sender, get_current_username(), sizeof(Sender) - 1); - safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); - safe_strcat(Sender, current_user_info.domain, sizeof(Sender) - 1); - safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); + + strlcpy(Sender, String, sizeof(Sender)); + strlcat(Sender, ",\"", sizeof(Sender)); + strlcat(Sender, get_current_username(), sizeof(Sender)); + strlcat(Sender, "\",\"", sizeof(Sender)); + strlcat(Sender, current_user_info.domain, sizeof(Sender)); + strlcat(Sender, "\",\"", sizeof(Sender)); if (Write) - safe_strcat(Sender, "W", sizeof(Sender) - 1); + strlcat(Sender, "W", sizeof(Sender)); else - safe_strcat(Sender, "R", sizeof(Sender) - 1); - safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); - safe_strcat(Sender, handle->conn->connectpath, sizeof(Sender) - 1); - safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); - safe_strcat(Sender, file_name, sizeof(Sender) - 1); - safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); + strlcat(Sender, "R", sizeof(Sender)); + strlcat(Sender, "\",\"", sizeof(Sender)); + strlcat(Sender, handle->conn->connectpath, sizeof(Sender)); + strlcat(Sender, "\",\"", sizeof(Sender) - 1); + strlcat(Sender, file_name, sizeof(Sender) - 1); + strlcat(Sender, "\",\"", sizeof(Sender) - 1); get_timestamp(TimeStamp); - safe_strcat(Sender, TimeStamp, sizeof(Sender) - 1); - safe_strcat(Sender, "\");", sizeof(Sender) - 1); + strlcat(Sender, TimeStamp, sizeof(Sender) - 1); + strlcat(Sender, "\");", sizeof(Sender) - 1); DEBUG(10, ("smb_traffic_analyzer: sending %s\n", Sender)); if ( send(sockfd, Sender, strlen(Sender), 0) == -1 ) { DEBUG(1, ("smb_traffic_analyzer: error sending data to socket!\n")); + close(sockfd); return ; } @@ -224,49 +234,53 @@ static void smb_traffic_analyzer_send_data_unix_socket( char *String , struct sockaddr_un remote; char Sender[200]; char TimeStamp[200]; + DEBUG(7, ("smb_traffic_analyzer: Unix domain socket mode. Using " "/var/tmp/stadsocket\n")); + if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { DEBUG(1, ("smb_traffic_analyzer: Couldn create socket," "make sure stad is running!\n")); } remote.sun_family = AF_UNIX; - safe_strcpy(remote.sun_path, "/var/tmp/stadsocket", - sizeof(remote.sun_path) - 1); + strlcpy(remote.sun_path, "/var/tmp/stadsocket", + 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: Could not connect to" "socket, make sure\nstad is running!\n")); + close(sock); + return; } - safe_strcpy(Sender, String, sizeof(Sender) - 1); - safe_strcat(Sender, ",\"", sizeof(Sender) - 1); - safe_strcat(Sender, get_current_username(), sizeof(Sender) - 1); - safe_strcat(Sender,"\",\"",sizeof(Sender) - 1); - safe_strcat(Sender, current_user_info.domain, sizeof(Sender) - 1); - safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); + strlcpy(Sender, String, sizeof(Sender)); + strlcat(Sender, ",\"", sizeof(Sender)); + strlcat(Sender, get_current_username(), sizeof(Sender)); + strlcat(Sender,"\",\"",sizeof(Sender)); + strlcat(Sender, current_user_info.domain, sizeof(Sender)); + strlcat(Sender, "\",\"", sizeof(Sender)); if (Write) - safe_strcat(Sender, "W", sizeof(Sender) - 1); + strlcat(Sender, "W", sizeof(Sender)); else - safe_strcat(Sender, "R", sizeof(Sender) - 1); - safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); - safe_strcat(Sender, handle->conn->connectpath, sizeof(Sender) - 1); - safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); - safe_strcat(Sender, file_name, sizeof(Sender) - 1); - safe_strcat(Sender, "\",\"", sizeof(Sender) - 1); + strlcat(Sender, "R", sizeof(Sender)); + strlcat(Sender, "\",\"", sizeof(Sender)); + strlcat(Sender, handle->conn->connectpath, sizeof(Sender)); + strlcat(Sender, "\",\"", sizeof(Sender)); + strlcat(Sender, file_name, sizeof(Sender)); + strlcat(Sender, "\",\"", sizeof(Sender)); get_timestamp(TimeStamp); - safe_strcat(Sender, TimeStamp, sizeof(Sender) - 1); - safe_strcat(Sender, "\");", sizeof(Sender) - 1); + strlcat(Sender, TimeStamp, sizeof(Sender)); + strlcat(Sender, "\");", sizeof(Sender)); DEBUG(10, ("smb_traffic_analyzer: sending %s\n", Sender)); if ( send(sock, Sender, strlen(Sender), 0) == -1 ) { DEBUG(1, ("smb_traffic_analyzer: error sending data to" "socket!\n")); + close(sock); return; } /* one operation, close the socket */ close(sock); - return; } @@ -291,7 +305,7 @@ static ssize_t smb_traffic_analyzer_read(vfs_handle_struct *handle, \ files_struct *fsp, void *data, size_t n) { ssize_t result; - char Buffer[100]; + fstring Buffer; result = SMB_VFS_NEXT_READ(handle, fsp, data, n); DEBUG(10, ("smb_traffic_analyzer: READ: %s\n", fsp->fsp_name )); @@ -307,7 +321,7 @@ 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; - char Buffer[100]; + fstring Buffer; result = SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset); @@ -323,7 +337,7 @@ static ssize_t smb_traffic_analyzer_write(vfs_handle_struct *handle, \ files_struct *fsp, const void *data, size_t n) { ssize_t result; - char Buffer[100]; + fstring Buffer; result = SMB_VFS_NEXT_WRITE(handle, fsp, data, n); @@ -339,7 +353,7 @@ 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; - char Buffer[100]; + fstring Buffer; result = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset); @@ -349,4 +363,3 @@ static ssize_t smb_traffic_analyzer_pwrite(vfs_handle_struct *handle, \ smb_traffic_analyzer_send_data(Buffer, handle, fsp->fsp_name, true, fsp); return result; } - -- cgit From f50ebbe29ff13d43ae8544c273247173ff12d45a Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Fri, 26 Sep 2008 01:32:16 +0200 Subject: s3-srvsvc: fix _srvsvc_NetShareAdd segfault. parm_err is not a ref pointer. Guenther --- source3/rpc_server/srv_srvsvc_nt.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source3/rpc_server/srv_srvsvc_nt.c b/source3/rpc_server/srv_srvsvc_nt.c index bb9c3687fb..fb7478653d 100644 --- a/source3/rpc_server/srv_srvsvc_nt.c +++ b/source3/rpc_server/srv_srvsvc_nt.c @@ -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); -- cgit From 694786b23c30e0a3449c7222433e3fdc7ef7c0e1 Mon Sep 17 00:00:00 2001 From: Kai Blin Date: Wed, 24 Sep 2008 23:23:01 +0200 Subject: net: Make share type lookup a function. --- source3/utils/net_proto.h | 2 ++ source3/utils/net_rap.c | 11 ++--------- source3/utils/net_rpc.c | 4 +--- source3/utils/net_util.c | 12 ++++++++++++ 4 files changed, 17 insertions(+), 12 deletions(-) diff --git a/source3/utils/net_proto.h b/source3/utils/net_proto.h index 1e355e54a3..ee4388f157 100644 --- a/source3/utils/net_proto.h +++ b/source3/utils/net_proto.h @@ -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, diff --git a/source3/utils/net_rap.c b/source3/utils/net_rap.c index 883524dc2d..32f4dd31b4 100644 --- a/source3/utils/net_rap.c +++ b/source3/utils/net_rap.c @@ -34,13 +34,6 @@ #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) diff --git a/source3/utils/net_rpc.c b/source3/utils/net_rpc.c index a849ec4c10..0e91144d33 100644 --- a/source3/utils/net_rpc.c +++ b/source3/utils/net_rpc.c @@ -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); diff --git a/source3/utils/net_util.c b/source3/utils/net_util.c index 88850d29df..fbb3c24b03 100644 --- a/source3/utils/net_util.c +++ b/source3/utils/net_util.c @@ -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"; + } +} -- cgit From cd49586b29d754e497d10ed18be5d9b27e8c4a3d Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Fri, 26 Sep 2008 23:39:32 +0200 Subject: libgpo: fix invalid cast in scripts CSE. Guenther --- source3/libgpo/gpext/scripts.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/libgpo/gpext/scripts.c b/source3/libgpo/gpext/scripts.c index c07407c3f0..02c3abaa1e 100644 --- a/source3/libgpo/gpext/scripts.c +++ b/source3/libgpo/gpext/scripts.c @@ -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); -- cgit From da8bebaa646db4c298038ba0013b47e88840977e Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Fri, 26 Sep 2008 15:17:14 -0700 Subject: Fix bug #5797 - Moving readonly files fails. Reported by infomail@lordb.de. We don't need to deny a DELETE open on a readonly file (I'm also adding a s4 torture test for this), the set_file_disposition call will return NT_STATUS_CANNOT_DELETE if the delete-on-close bit is set on a readonly file (and we already do this). Jeremy. --- source3/smbd/open.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/source3/smbd/open.c b/source3/smbd/open.c index 71191475b3..ad024a58ef 100644 --- a/source3/smbd/open.c +++ b/source3/smbd/open.c @@ -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; } -- cgit From 857609732fa92a70ce35d85d775d03362056a6c2 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Fri, 26 Sep 2008 15:20:27 -0700 Subject: Add test to show you can open for delete a readonly file. Jeremy. --- source4/torture/raw/open.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/source4/torture/raw/open.c b/source4/torture/raw/open.c index f3494ea3d0..dd5ef0d0b9 100644 --- a/source4/torture/raw/open.c +++ b/source4/torture/raw/open.c @@ -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); -- cgit From 0cb55e74eff6e0123cc8a7fe8dc81ad181f81a61 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sat, 27 Sep 2008 00:36:45 +0200 Subject: libgpo: add security CSE skeleton. Guenther --- source3/Makefile.in | 6 + source3/libgpo/gpext/security.c | 267 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 273 insertions(+) create mode 100644 source3/libgpo/gpext/security.c diff --git a/source3/Makefile.in b/source3/Makefile.in index 18b1d9ad30..c8ee9be00f 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -1139,6 +1139,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@ @@ -2416,6 +2418,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 diff --git a/source3/libgpo/gpext/security.c b/source3/libgpo/gpext/security.c new file mode 100644 index 0000000000..61a25790a8 --- /dev/null +++ b/source3/libgpo/gpext/security.c @@ -0,0 +1,267 @@ +/* + * Unix SMB/CIFS implementation. + * Group Policy Support + * Copyright (C) Guenther Deschner 2005-2007 + * + * 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 . + */ + +#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; +} -- cgit From 9c1b5f27e40b1a30b20ffd674111fdfb709b0917 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sat, 27 Sep 2008 00:38:26 +0200 Subject: libgpo: fix copyright. Guenther --- source3/libgpo/gpext/security.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/libgpo/gpext/security.c b/source3/libgpo/gpext/security.c index 61a25790a8..1d746da37f 100644 --- a/source3/libgpo/gpext/security.c +++ b/source3/libgpo/gpext/security.c @@ -1,7 +1,7 @@ /* * Unix SMB/CIFS implementation. * Group Policy Support - * Copyright (C) Guenther Deschner 2005-2007 + * 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 -- cgit From c12c69c6ee637075573350aa6f1d4b1abf84ad0b Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sat, 27 Sep 2008 00:55:42 +0200 Subject: libgpo: add gpext_security module build to configure. Guenther --- source3/configure.in | 1 + 1 file changed, 1 insertion(+) diff --git a/source3/configure.in b/source3/configure.in index 8332b1e34a..f04ddbeaa5 100644 --- a/source3/configure.in +++ b/source3/configure.in @@ -6122,6 +6122,7 @@ 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]) -- cgit From ce46f65f1703c23bad0544e14f8db464a93dbb1e Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sat, 27 Sep 2008 01:15:07 +0200 Subject: libwbclient: fix doxygen warnings. Guenther --- source3/nsswitch/libwbclient/wbc_idmap.c | 2 +- source3/nsswitch/libwbclient/wbc_pwd.c | 2 +- source3/nsswitch/libwbclient/wbc_sid.c | 6 +++--- source3/nsswitch/libwbclient/wbc_util.c | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/source3/nsswitch/libwbclient/wbc_idmap.c b/source3/nsswitch/libwbclient/wbc_idmap.c index e32d66cd71..1615fd33ee 100644 --- a/source3/nsswitch/libwbclient/wbc_idmap.c +++ b/source3/nsswitch/libwbclient/wbc_idmap.c @@ -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 **/ diff --git a/source3/nsswitch/libwbclient/wbc_pwd.c b/source3/nsswitch/libwbclient/wbc_pwd.c index b5f167369c..0d17b312ef 100644 --- a/source3/nsswitch/libwbclient/wbc_pwd.c +++ b/source3/nsswitch/libwbclient/wbc_pwd.c @@ -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 **/ diff --git a/source3/nsswitch/libwbclient/wbc_sid.c b/source3/nsswitch/libwbclient/wbc_sid.c index f4ffa4e5ca..4cfdd792b5 100644 --- a/source3/nsswitch/libwbclient/wbc_sid.c +++ b/source3/nsswitch/libwbclient/wbc_sid.c @@ -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 * diff --git a/source3/nsswitch/libwbclient/wbc_util.c b/source3/nsswitch/libwbclient/wbc_util.c index 24568f9101..8e01e6e719 100644 --- a/source3/nsswitch/libwbclient/wbc_util.c +++ b/source3/nsswitch/libwbclient/wbc_util.c @@ -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 -- cgit From fae2fce47e28ccfe5f43744200ce2ae68da3a9aa Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Sat, 27 Sep 2008 01:49:22 +0200 Subject: s4:provision: don't do the full provision in the become_dc metze --- source4/scripting/python/samba/provision.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source4/scripting/python/samba/provision.py b/source4/scripting/python/samba/provision.py index 68f61532ad..427ca975b3 100644 --- a/source4/scripting/python/samba/provision.py +++ b/source4/scripting/python/samba/provision.py @@ -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) -- cgit From 3b02b9e40ee5b1c4dbdf503fdeb0351832a1e9c9 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Fri, 26 Sep 2008 18:39:03 -0700 Subject: Second part of the fix for bug #5790 - samba returns STATUS_OBJECT_NAME_NOT_FOUND on set file disposition call. This was my fault. I use a singleton cache (positive and negative) to speed up pathname based qfileinfo/setfileinfo lookups for alternate fsp's open on the same path. I only invalidated the negative cache on adding a new file fsp, as I incorrectly imagined the new fsp was put at the *end* of the open files list. DLIST_ADD puts it at the start, meaning any subsequent open wasn't seen once the cache was set. Doh ! Jeremy. --- source3/smbd/files.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/source3/smbd/files.c b/source3/smbd/files.c index 777f8e1e23..8d06e20f81 100644 --- a/source3/smbd/files.c +++ b/source3/smbd/files.c @@ -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; -- cgit From 21c4061414f0e1af9106c50958dd5653a6f5368d Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Sat, 27 Sep 2008 22:06:27 +0200 Subject: [s3]loadparm: add a command test_lp_load to test the lp_load function. This is not like testparm, just a simple tool that runs lp_load_with_registry_shares the requested number of times. Michael --- source3/param/test_lp_load.c | 88 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 source3/param/test_lp_load.c diff --git a/source3/param/test_lp_load.c b/source3/param/test_lp_load.c new file mode 100644 index 0000000000..db1bad4726 --- /dev/null +++ b/source3/param/test_lp_load.c @@ -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 . + */ + +#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 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...] "); + + 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; +} + -- cgit From 6bfd63e0104d3f8d57e20492e27fc280695bcbb1 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Sat, 27 Sep 2008 22:08:02 +0200 Subject: [s3]build: build the new test_lp_load command. Michael --- source3/Makefile.in | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/source3/Makefile.in b/source3/Makefile.in index c8ee9be00f..61e946e7cd 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -739,6 +739,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) \ @@ -2494,6 +2498,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 -- cgit From 628ee436a1104655616ea1b25f920a2d2d24099a Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Sat, 27 Sep 2008 22:10:05 +0200 Subject: [s3]testparm: free the popt context when it is no longer used. Michael --- source3/utils/testparm.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source3/utils/testparm.c b/source3/utils/testparm.c index 527db2d805..ccbb2dd391 100644 --- a/source3/utils/testparm.c +++ b/source3/utils/testparm.c @@ -329,6 +329,8 @@ 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); -- cgit From 39f7ec3f7468d8b044f4d1d403aa60a306451d20 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Sat, 27 Sep 2008 22:10:44 +0200 Subject: [s3]testparm: give testparm one common exit point and call gfree_loadparm(). Michael --- source3/utils/testparm.c | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/source3/utils/testparm.c b/source3/utils/testparm.c index ccbb2dd391..4370d49523 100644 --- a/source3/utils/testparm.c +++ b/source3/utils/testparm.c @@ -333,7 +333,8 @@ rameter is ignored when using CUPS libraries.\n", 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) { @@ -348,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"); @@ -395,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) @@ -409,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()); @@ -430,7 +434,10 @@ rameter is ignored when using CUPS libraries.\n", } } } + +done: TALLOC_FREE(frame); - return(ret); + gfree_loadparm(); + return ret; } -- cgit From b38ed2674b42c27ec4183a84b6e73dfa1387b398 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Wed, 24 Sep 2008 20:31:39 +0200 Subject: [s3]loadparm: rename process_registry_service() to process_smbconf_service(). There is nothing registry-specific in that function. Michael --- source3/param/loadparm.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source3/param/loadparm.c b/source3/param/loadparm.c index 87af7a3411..a879859e75 100644 --- a/source3/param/loadparm.c +++ b/source3/param/loadparm.c @@ -6560,7 +6560,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 +6616,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 +6654,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; } -- cgit From 612aa3915f92a4309d24f9ba7f33f26c275fab48 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Wed, 24 Sep 2008 21:59:34 +0200 Subject: [s3]loadparm: refactor freeing of parametric options into free_param_opts(). This code was there in three places. Michael --- source3/param/loadparm.c | 75 ++++++++++++++++++++++-------------------------- 1 file changed, 34 insertions(+), 41 deletions(-) diff --git a/source3/param/loadparm.c b/source3/param/loadparm.c index a879859e75..74dff837c0 100644 --- a/source3/param/loadparm.c +++ b/source3/param/loadparm.c @@ -5390,6 +5390,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,6 +5645,35 @@ 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. ***************************************************************************/ @@ -5651,7 +5681,6 @@ static void init_service(struct service *pservice) static void free_service(struct service *pservice) { int i; - struct param_opt_struct *data, *pdata; if (!pservice) return; @@ -5677,18 +5706,7 @@ static void free_service(struct service *pservice) &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 +5748,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 +5757,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); } } @@ -8765,9 +8773,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 +8788,6 @@ bool lp_load_ex(const char *pszFname, { char *n2 = NULL; bool bRetval; - struct param_opt_struct *data, *pdata; bRetval = False; @@ -8801,22 +8805,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, -- cgit From 33d18c76f1bf5e10b52e873af5b29fabd1db7f3c Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Wed, 24 Sep 2008 22:19:26 +0200 Subject: [s3]loadparm: fix memory error - free the right param_opt->list in copy_service. Michael --- source3/param/loadparm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/param/loadparm.c b/source3/param/loadparm.c index 74dff837c0..dbfd5853f5 100644 --- a/source3/param/loadparm.c +++ b/source3/param/loadparm.c @@ -6487,7 +6487,7 @@ static void copy_service(struct service *pserviceDest, struct service *pserviceS /* If we already have same option, override it */ if (strwicmp(pdata->key, data->key) == 0) { string_free(&pdata->value); - TALLOC_FREE(data->list); + TALLOC_FREE(pdata->list); pdata->value = SMB_STRDUP(data->value); not_added = False; break; -- cgit From aa388a20053dc1809e8fcf12dbc6eddcec23d77e Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Thu, 25 Sep 2008 00:52:11 +0200 Subject: [s3]loadparm: refactor setting parametric options in list out into new function set_param_opt(). This unifies and clarifies two instances of the code. Michael --- source3/param/loadparm.c | 97 ++++++++++++++++++++++-------------------------- 1 file changed, 45 insertions(+), 52 deletions(-) diff --git a/source3/param/loadparm.c b/source3/param/loadparm.c index dbfd5853f5..fda086cacf 100644 --- a/source3/param/loadparm.c +++ b/source3/param/loadparm.c @@ -6416,13 +6416,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 && @@ -6480,27 +6518,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(pdata->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; } } @@ -7165,8 +7183,7 @@ 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); @@ -7185,33 +7202,9 @@ bool lp_do_parameter(int snum, const char *pszParmName, const char *pszParmValue frame = talloc_stackframe(); - 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); - } - } + opt_list = (snum < 0) + ? &Globals.param_opt : &ServicePtrs[snum]->param_opt; + set_param_opt(opt_list, pszParmName, pszParmValue); TALLOC_FREE(frame); return (True); -- cgit From 1578610aefe28be1b121f3a957787e98a5536b85 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Thu, 25 Sep 2008 00:54:45 +0200 Subject: [s3]loadparm: remove superfluous talloc context / talloc_stackframe call. Michael --- source3/param/loadparm.c | 5 ----- 1 file changed, 5 deletions(-) diff --git a/source3/param/loadparm.c b/source3/param/loadparm.c index fda086cacf..dc7026268b 100644 --- a/source3/param/loadparm.c +++ b/source3/param/loadparm.c @@ -7188,8 +7188,6 @@ bool lp_do_parameter(int snum, const char *pszParmName, const char *pszParmValue parmnum = map_parameter(pszParmName); if (parmnum < 0) { - TALLOC_CTX *frame; - if (strchr(pszParmName, ':') == NULL) { DEBUG(0, ("Ignoring unknown parameter \"%s\"\n", pszParmName)); @@ -7200,13 +7198,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); - TALLOC_FREE(frame); return (True); } -- cgit From e56c89b5e85f565e03818abc4fa5354bdf473dee Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Sat, 27 Sep 2008 22:13:17 +0200 Subject: [s3]loadparm: in lp_do_parameter() use function lp_local_ptr() instead of hard coded calculation. Michael --- source3/param/loadparm.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/source3/param/loadparm.c b/source3/param/loadparm.c index dc7026268b..025e3e92ad 100644 --- a/source3/param/loadparm.c +++ b/source3/param/loadparm.c @@ -7222,9 +7222,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) { -- cgit From 3358a139d2dc77eb4c842d41722b1acc24bd2cb2 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Sat, 27 Sep 2008 22:19:56 +0200 Subject: [s3]loadparm: refactor freeing of parameter data out and reduce memleak. Add new functions free_parameter(), free_parameters() and free_global_parameters() and use these in the appropriate places, reducing code duplication. Also, always TALLOC_FREE data of type P_LIST, thus reducing mem-leaks: This had not been done in init_globals before. Michael --- source3/param/loadparm.c | 88 +++++++++++++++++++++++++++++------------------- 1 file changed, 53 insertions(+), 35 deletions(-) diff --git a/source3/param/loadparm.c b/source3/param/loadparm.c index 025e3e92ad..94660317f8 100644 --- a/source3/param/loadparm.c +++ b/source3/param/loadparm.c @@ -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)); @@ -5645,6 +5686,7 @@ 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; @@ -5680,7 +5722,6 @@ static void free_param_opts(struct param_opt_struct **popts) static void free_service(struct service *pservice) { - int i; if (!pservice) return; @@ -5688,24 +5729,11 @@ 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)))); - } - free_param_opts(&pservice->param_opt); ZERO_STRUCTP(pservice); @@ -8728,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(); } -- cgit From a9a59f5f3d7f82a8065424310d3b32d796a43e75 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Mon, 29 Sep 2008 03:14:20 +0200 Subject: Fix async_connect --- source3/lib/async_sock.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source3/lib/async_sock.c b/source3/lib/async_sock.c index 1a4c27ba20..ffba6de832 100644 --- a/source3/lib/async_sock.c +++ b/source3/lib/async_sock.c @@ -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; -- cgit From ee2bcfacdf32b0c55c6a78ae1ad7b55699611d1b Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Sat, 27 Sep 2008 02:27:54 +0200 Subject: s4:dsdb: passdown DSDB_CONTROL_REPLICATED_UPDATE_OID for replicated updates We need to make sure replicated updates are handled differently in some situations, e.g. we should bypass the schema checks. metze --- source4/dsdb/samdb/ldb_modules/repl_meta_data.c | 27 ++++++++++++++++++++++--- source4/dsdb/samdb/ldb_modules/schema_fsmo.c | 10 +++++++++ source4/dsdb/samdb/samdb.h | 3 +++ source4/setup/schema_samba4.ldif | 2 ++ 4 files changed, 39 insertions(+), 3 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/repl_meta_data.c b/source4/dsdb/samdb/ldb_modules/repl_meta_data.c index dd5faf837a..fbaf461a3f 100644 --- a/source4/dsdb/samdb/ldb_modules/repl_meta_data.c +++ b/source4/dsdb/samdb/ldb_modules/repl_meta_data.c @@ -58,6 +58,9 @@ struct replmd_replicated_request { struct dsdb_extended_replicated_objects *objs; + /* the controls we pass down */ + struct ldb_control **controls; + uint32_t index_current; struct { @@ -700,7 +703,7 @@ static int replmd_replicated_apply_add(struct replmd_replicated_request *ar) ar->module->ldb, ar->sub.mem_ctx, msg, - NULL, + ar->controls, ar, replmd_replicated_apply_add_callback); if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret); @@ -951,7 +954,7 @@ static int replmd_replicated_apply_merge(struct replmd_replicated_request *ar) ar->module->ldb, ar->sub.mem_ctx, msg, - NULL, + ar->controls, ar, replmd_replicated_apply_merge_callback); if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret); @@ -1379,7 +1382,7 @@ static int replmd_replicated_uptodate_modify(struct replmd_replicated_request *a ar->module->ldb, ar->sub.mem_ctx, msg, - NULL, + ar->controls, ar, replmd_replicated_uptodate_modify_callback); if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret); @@ -1491,6 +1494,8 @@ static int replmd_extended_replicated_objects(struct ldb_module *module, struct { 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"); @@ -1511,6 +1516,22 @@ static int replmd_extended_replicated_objects(struct ldb_module *module, struct return LDB_ERR_OPERATIONS_ERROR; } + 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); + } + + ret = ldb_request_add_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID, false, NULL); + if (ret != LDB_SUCCESS) { + return ret; + } + + ar->controls = req->controls; + req->controls = ctrls; + #ifdef REPLMD_FULL_ASYNC /* TODO: activate this code when ldb support full async code */ return replmd_replicated_apply_next(ar); #else diff --git a/source4/dsdb/samdb/ldb_modules/schema_fsmo.c b/source4/dsdb/samdb/ldb_modules/schema_fsmo.c index 968b19c038..4b6e9e1d47 100644 --- a/source4/dsdb/samdb/ldb_modules/schema_fsmo.c +++ b/source4/dsdb/samdb/ldb_modules/schema_fsmo.c @@ -152,6 +152,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); diff --git a/source4/dsdb/samdb/samdb.h b/source4/dsdb/samdb/samdb.h index f24a75fd8f..93068d66ef 100644 --- a/source4/dsdb/samdb/samdb.h +++ b/source4/dsdb/samdb/samdb.h @@ -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; diff --git a/source4/setup/schema_samba4.ldif b/source4/setup/schema_samba4.ldif index 3e129e4f6b..2c007395fb 100644 --- a/source4/setup/schema_samba4.ldif +++ b/source4/setup/schema_samba4.ldif @@ -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 -- cgit From 8b7199e7b22ac727ebc65308bf08360dc9f4b0c0 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Sat, 27 Sep 2008 20:35:52 +0200 Subject: lib/tdb: increase the version number after some critial changes The tdb_transaction/traverse interaction fixes are critical. metze --- lib/tdb/configure.ac | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/tdb/configure.ac b/lib/tdb/configure.ac index 4bf2e98e8f..2feaa6f5f5 100644 --- a/lib/tdb/configure.ac +++ b/lib/tdb/configure.ac @@ -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 -- cgit From eb935e08d388aab7e02f8ec0ce58b0a62808de5c Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Sat, 27 Sep 2008 20:37:27 +0200 Subject: s4:configure: require tdb >= 1.1.3 from the system metze --- source3/samba4.m4 | 2 +- source4/configure.ac | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/source3/samba4.m4 b/source3/samba4.m4 index 728fd2d45d..81f1809210 100644 --- a/source3/samba4.m4 +++ b/source3/samba4.m4 @@ -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) diff --git a/source4/configure.ac b/source4/configure.ac index fa2d8d9950..611b8dd104 100644 --- a/source4/configure.ac +++ b/source4/configure.ac @@ -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) -- cgit From 82153740911b16871cae043b6842810499b5cb55 Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Thu, 11 Sep 2008 18:33:16 -0400 Subject: LDB ASYNC: Core files --- source4/lib/ldb/common/ldb.c | 304 +++++++++++++++++++++++----------- source4/lib/ldb/common/ldb_modules.c | 141 +++++++++++++++- source4/lib/ldb/include/ldb.h | 105 ++++++++---- source4/lib/ldb/include/ldb_private.h | 98 ++++++----- source4/lib/ldb/ldb.i | 5 +- 5 files changed, 489 insertions(+), 164 deletions(-) diff --git a/source4/lib/ldb/common/ldb.c b/source4/lib/ldb/common/ldb.c index 3b73947b76..75c8109042 100644 --- a/source4/lib/ldb/common/ldb.c +++ b/source4/lib/ldb/common/ldb.c @@ -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; diff --git a/source4/lib/ldb/common/ldb_modules.c b/source4/lib/ldb/common/ldb_modules.c index c0cd616a76..5cc8de29b4 100644 --- a/source4/lib/ldb/common/ldb_modules.c +++ b/source4/lib/ldb/common/ldb_modules.c @@ -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 diff --git a/source4/lib/ldb/include/ldb.h b/source4/lib/ldb/include/ldb.h index 645d7866c5..b1ce3ef70b 100644 --- a/source4/lib/ldb/include/ldb.h +++ b/source4/lib/ldb/include/ldb.h @@ -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 diff --git a/source4/lib/ldb/include/ldb_private.h b/source4/lib/ldb/include/ldb_private.h index 30adadcfdc..a92549d9ce 100644 --- a/source4/lib/ldb/include/ldb_private.h +++ b/source4/lib/ldb/include/ldb_private.h @@ -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 diff --git a/source4/lib/ldb/ldb.i b/source4/lib/ldb/ldb.i index 45978251f7..1e3a3169c8 100644 --- a/source4/lib/ldb/ldb.i +++ b/source4/lib/ldb/ldb.i @@ -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) { -- cgit From 0aeade2007ef789f5970efe2b69ff7fb83a12b83 Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Thu, 11 Sep 2008 18:34:11 -0400 Subject: LDB ASYNC: ldb_tdb backend --- source4/lib/ldb/ldb_tdb/ldb_index.c | 61 +++--- source4/lib/ldb/ldb_tdb/ldb_search.c | 129 +++++-------- source4/lib/ldb/ldb_tdb/ldb_tdb.c | 353 +++++++++++++++++------------------ source4/lib/ldb/ldb_tdb/ldb_tdb.h | 14 +- 4 files changed, 242 insertions(+), 315 deletions(-) diff --git a/source4/lib/ldb/ldb_tdb/ldb_index.c b/source4/lib/ldb/ldb_tdb/ldb_index.c index 269305a468..65711d9f4b 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_index.c +++ b/source4/lib/ldb/ldb_tdb/ldb_index.c @@ -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); diff --git a/source4/lib/ldb/ldb_tdb/ldb_search.c b/source4/lib/ldb/ldb_tdb/ldb_search.c index da899c361e..a220b4a628 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_search.c +++ b/source4/lib/ldb/ldb_tdb/ldb_search.c @@ -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; } diff --git a/source4/lib/ldb/ldb_tdb/ldb_tdb.c b/source4/lib/ldb/ldb_tdb/ldb_tdb.c index 01d570c89a..0087f6c44d 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_tdb.c +++ b/source4/lib/ldb/ldb_tdb/ldb_tdb.c @@ -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 @@ -39,6 +39,10 @@ * - 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; diff --git a/source4/lib/ldb/ldb_tdb/ldb_tdb.h b/source4/lib/ldb/ldb_tdb/ldb_tdb.h index 4beced30eb..223181ca0b 100644 --- a/source4/lib/ldb/ldb_tdb/ldb_tdb.h +++ b/source4/lib/ldb/ldb_tdb/ldb_tdb.h @@ -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); - -- cgit From 9f7c2548d9da848397b4730f02c7c47f23e259dc Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Thu, 11 Sep 2008 18:34:56 -0400 Subject: LDB ASYNC: other backends --- source4/lib/ldb/ldb_ildap/ldb_ildap.c | 483 ++++++++++++------------ source4/lib/ldb/ldb_ldap/ldb_ldap.c | 588 ++++++++++++++++-------------- source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c | 130 ++++--- 3 files changed, 619 insertions(+), 582 deletions(-) diff --git a/source4/lib/ldb/ldb_ildap/ldb_ildap.c b/source4/lib/ldb/ldb_ildap/ldb_ildap.c index 5ad671ea2e..4aa71e6036 100644 --- a/source4/lib/ldb/ldb_ildap/ldb_ildap.c +++ b/source4/lib/ldb/ldb_ildap/ldb_ildap.c @@ -53,17 +53,57 @@ 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; diff --git a/source4/lib/ldb/ldb_ldap/ldb_ldap.c b/source4/lib/ldb/ldb_ldap/ldb_ldap.c index a4534c549a..7caee10b47 100644 --- a/source4/lib/ldb/ldb_ldap/ldb_ldap.c +++ b/source4/lib/ldb/ldb_ldap/ldb_ldap.c @@ -45,17 +45,16 @@ 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); diff --git a/source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c b/source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c index a0e63c8da1..be99c29d1e 100644 --- a/source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c +++ b/source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c @@ -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 */ }; /* -- cgit From 4f40ee2b86007f7dc631e93e59f24f970bc25ea2 Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Thu, 11 Sep 2008 18:35:38 -0400 Subject: LDB ASYNC: core modules --- source4/lib/ldb/ldb_map/ldb_map.c | 355 ++------------ source4/lib/ldb/ldb_map/ldb_map.h | 4 +- source4/lib/ldb/ldb_map/ldb_map_inbound.c | 754 ++++++++++++++++------------- source4/lib/ldb/ldb_map/ldb_map_outbound.c | 443 ++++++++++------- source4/lib/ldb/ldb_map/ldb_map_private.h | 88 ++-- source4/lib/ldb/modules/asq.c | 419 +++++++--------- source4/lib/ldb/modules/operational.c | 102 ++-- source4/lib/ldb/modules/paged_results.c | 493 +++++++------------ source4/lib/ldb/modules/paged_searches.c | 359 ++++++-------- source4/lib/ldb/modules/rdn_name.c | 300 ++++++------ source4/lib/ldb/modules/sort.c | 369 +++++--------- 11 files changed, 1534 insertions(+), 2152 deletions(-) diff --git a/source4/lib/ldb/ldb_map/ldb_map.c b/source4/lib/ldb/ldb_map/ldb_map.c index e9129c812b..fafbb63b0a 100644 --- a/source4/lib/ldb/ldb_map/ldb_map.c +++ b/source4/lib/ldb/ldb_map/ldb_map.c @@ -3,6 +3,7 @@ Copyright (C) Jelmer Vernooij 2005 Copyright (C) Martin Kuehl 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 * ===================== */ diff --git a/source4/lib/ldb/ldb_map/ldb_map.h b/source4/lib/ldb/ldb_map/ldb_map.h index e40bb9cd7e..7f92c15b98 100644 --- a/source4/lib/ldb/ldb_map/ldb_map.h +++ b/source4/lib/ldb/ldb_map/ldb_map.h @@ -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__ */ diff --git a/source4/lib/ldb/ldb_map/ldb_map_inbound.c b/source4/lib/ldb/ldb_map/ldb_map_inbound.c index 7fc3ac4ed5..96605f23eb 100644 --- a/source4/lib/ldb/ldb_map/ldb_map_inbound.c +++ b/source4/lib/ldb/ldb_map/ldb_map_inbound.c @@ -3,6 +3,7 @@ Copyright (C) Jelmer Vernooij 2005 Copyright (C) Martin Kuehl 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 @@ -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); } diff --git a/source4/lib/ldb/ldb_map/ldb_map_outbound.c b/source4/lib/ldb/ldb_map/ldb_map_outbound.c index fbc097f313..5f524a8be3 100644 --- a/source4/lib/ldb/ldb_map/ldb_map_outbound.c +++ b/source4/lib/ldb/ldb_map/ldb_map_outbound.c @@ -4,6 +4,7 @@ Copyright (C) Jelmer Vernooij 2005 Copyright (C) Martin Kuehl 2006 Copyright (C) Andrew Bartlett 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 @@ -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; } diff --git a/source4/lib/ldb/ldb_map/ldb_map_private.h b/source4/lib/ldb/ldb_map/ldb_map_private.h index 58a9f2704e..5522125344 100644 --- a/source4/lib/ldb/ldb_map/ldb_map_private.h +++ b/source4/lib/ldb/ldb_map/ldb_map_private.h @@ -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); diff --git a/source4/lib/ldb/modules/asq.c b/source4/lib/ldb/modules/asq.c index eb27263b16..17896a006a 100644 --- a/source4/lib/ldb/modules/asq.c +++ b/source4/lib/ldb/modules/asq.c @@ -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 @@ -36,10 +36,10 @@ 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 }; diff --git a/source4/lib/ldb/modules/operational.c b/source4/lib/ldb/modules/operational.c index a59e81becd..abb1d4ca1a 100644 --- a/source4/lib/ldb/modules/operational.c +++ b/source4/lib/ldb/modules/operational.c @@ -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) diff --git a/source4/lib/ldb/modules/paged_results.c b/source4/lib/ldb/modules/paged_results.c index b62b1f92cb..d3bb83bbcd 100644 --- a/source4/lib/ldb/modules/paged_results.c +++ b/source4/lib/ldb/modules/paged_results.c @@ -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 }; diff --git a/source4/lib/ldb/modules/paged_searches.c b/source4/lib/ldb/modules/paged_searches.c index 40e87f70d6..7a728e3bb0 100644 --- a/source4/lib/ldb/modules/paged_searches.c +++ b/source4/lib/ldb/modules/paged_searches.c @@ -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 }; diff --git a/source4/lib/ldb/modules/rdn_name.c b/source4/lib/ldb/modules/rdn_name.c index 65c044c0f4..62b8ce5112 100644 --- a/source4/lib/ldb/modules/rdn_name.c +++ b/source4/lib/ldb/modules/rdn_name.c @@ -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 @@ -38,6 +38,14 @@ #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 }; diff --git a/source4/lib/ldb/modules/sort.c b/source4/lib/ldb/modules/sort.c index 746befa559..64d60f370c 100644 --- a/source4/lib/ldb/modules/sort.c +++ b/source4/lib/ldb/modules/sort.c @@ -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 }; -- cgit From 51baa8deec00244cc0a6e3d29c53932427800610 Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Thu, 11 Sep 2008 18:36:28 -0400 Subject: LDB ASYNC: samba4 modules --- source4/dsdb/samdb/ldb_modules/anr.c | 176 ++- source4/dsdb/samdb/ldb_modules/extended_dn.c | 143 +- source4/dsdb/samdb/ldb_modules/instancetype.c | 66 +- source4/dsdb/samdb/ldb_modules/kludge_acl.c | 206 +-- source4/dsdb/samdb/ldb_modules/linked_attributes.c | 1315 ++++++++-------- source4/dsdb/samdb/ldb_modules/local_password.c | 1124 ++++++++------ source4/dsdb/samdb/ldb_modules/normalise.c | 150 +- source4/dsdb/samdb/ldb_modules/objectclass.c | 752 ++++----- source4/dsdb/samdb/ldb_modules/objectguid.c | 101 +- source4/dsdb/samdb/ldb_modules/partition.c | 595 +++---- source4/dsdb/samdb/ldb_modules/password_hash.c | 731 ++++----- source4/dsdb/samdb/ldb_modules/proxy.c | 136 +- source4/dsdb/samdb/ldb_modules/ranged_results.c | 165 +- source4/dsdb/samdb/ldb_modules/repl_meta_data.c | 736 ++++----- source4/dsdb/samdb/ldb_modules/rootdse.c | 122 +- source4/dsdb/samdb/ldb_modules/samldb.c | 1633 +++++++++++++------- source4/dsdb/samdb/ldb_modules/schema_fsmo.c | 100 +- source4/dsdb/samdb/ldb_modules/show_deleted.c | 166 +- source4/dsdb/samdb/ldb_modules/simple_ldap_map.c | 53 +- source4/dsdb/samdb/ldb_modules/subtree_delete.c | 232 +-- source4/dsdb/samdb/ldb_modules/subtree_rename.c | 332 ++-- source4/dsdb/samdb/ldb_modules/update_keytab.c | 245 ++- 22 files changed, 4946 insertions(+), 4333 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/anr.c b/source4/dsdb/samdb/ldb_modules/anr.c index 4e2c527fe9..028df588d6 100644 --- a/source4/dsdb/samdb/ldb_modules/anr.c +++ b/source4/dsdb/samdb/ldb_modules/anr.c @@ -1,7 +1,8 @@ /* ldb database library - Copyright (C) Amdrew Bartlett 2007 + Copyright (C) Andrew Bartlett 2007 + Copyright (C) Simo Sorce 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;iu.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 = { diff --git a/source4/dsdb/samdb/ldb_modules/extended_dn.c b/source4/dsdb/samdb/ldb_modules/extended_dn.c index 84bf5e4843..e40190e86f 100644 --- a/source4/dsdb/samdb/ldb_modules/extended_dn.c +++ b/source4/dsdb/samdb/ldb_modules/extended_dn.c @@ -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, ";;%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, ";%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,52 +185,70 @@ 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 *); + struct ldb_request *req; - const char * const *attrs; bool remove_guid; bool remove_sid; int extended_type; }; -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) { + 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: /* 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; + 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 ac->up_callback(ldb, ac->up_context, ares); + return ldb_module_send_entry(ac->req, ares->message); -error: - talloc_free(ares); - return LDB_ERR_OPERATIONS_ERROR; + 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_search(struct ldb_module *module, struct ldb_request *req) { struct ldb_control *control; @@ -237,6 +256,7 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) struct ldb_control **saved_controls; struct extended_context *ac; struct ldb_request *down_req; + const char * const *cast_attrs = NULL; char **new_attrs; int ret; @@ -261,9 +281,7 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) } ac->module = module; - ac->up_context = req->context; - ac->up_callback = req->callback; - ac->attrs = req->op.search.attrs; + ac->req = req; ac->remove_guid = false; ac->remove_sid = false; if (extended_ctrl) { @@ -272,17 +290,6 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) 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")) { @@ -292,26 +299,38 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) ac->remove_sid = true; } if (ac->remove_guid || ac->remove_sid) { - new_attrs = copy_attrs(down_req, req->op.search.attrs); + new_attrs = copy_attrs(ac, req->op.search.attrs); if (new_attrs == NULL) { ldb_oom(module->ldb); return LDB_ERR_OPERATIONS_ERROR; } if (ac->remove_guid) { - if (!add_attrs(down_req, &new_attrs, "objectGUID")) + if (!add_attrs(ac, &new_attrs, "objectGUID")) return LDB_ERR_OPERATIONS_ERROR; } if (ac->remove_sid) { - if (!add_attrs(down_req, &new_attrs, "objectSID")) + if (!add_attrs(ac, &new_attrs, "objectSID")) return LDB_ERR_OPERATIONS_ERROR; } - - down_req->op.search.attrs = (const char * const *)new_attrs; + cast_attrs = (const char * const *)new_attrs; + } else { + cast_attrs = req->op.search.attrs; } } - down_req->controls = req->controls; + ret = ldb_build_search_req_ex(&down_req, + module->ldb, ac, + req->op.search.base, + req->op.search.scope, + req->op.search.tree, + cast_attrs, + req->controls, + ac, extended_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 @@ -320,45 +339,21 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) return LDB_ERR_OPERATIONS_ERROR; } - 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); - - /* 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; + 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); } diff --git a/source4/dsdb/samdb/ldb_modules/instancetype.c b/source4/dsdb/samdb/ldb_modules/instancetype.c index fd5aa5e18a..492ef1c92b 100644 --- a/source4/dsdb/samdb/ldb_modules/instancetype.c +++ b/source4/dsdb/samdb/ldb_modules/instancetype.c @@ -1,7 +1,7 @@ /* ldb database library - Copyright (C) Simo Sorce 2004-2006 + Copyright (C) Simo Sorce 2004-2008 Copyright (C) Andrew Bartlett 2005 Copyright (C) Andrew Tridgell 2005 Copyright (C) Stefan Metzmacher 2007 @@ -41,11 +41,43 @@ #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 = { diff --git a/source4/dsdb/samdb/ldb_modules/kludge_acl.c b/source4/dsdb/samdb/ldb_modules/kludge_acl.c index 6836f95873..24527c36c9 100644 --- a/source4/dsdb/samdb/ldb_modules/kludge_acl.c +++ b/source4/dsdb/samdb/ldb_modules/kludge_acl.c @@ -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,10 +319,9 @@ 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; - ac = talloc(req, struct kludge_acl_context); if (ac == NULL) { ldb_oom(module->ldb); @@ -301,23 +331,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 +344,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 +356,34 @@ 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); - - /* 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, + attrs, + req->controls, + ac, kludge_acl_callback, + req); + if (ret != LDB_SUCCESS) { + return LDB_ERR_OPERATIONS_ERROR; } - return ret; + /* perform the search */ + return ldb_next_request(module, down_req); } /* ANY change type */ diff --git a/source4/dsdb/samdb/ldb_modules/linked_attributes.c b/source4/dsdb/samdb/ldb_modules/linked_attributes.c index e64472432d..3b389afffb 100644 --- a/source4/dsdb/samdb/ldb_modules/linked_attributes.c +++ b/source4/dsdb/samdb/ldb_modules/linked_attributes.c @@ -2,6 +2,7 @@ ldb database library Copyright (C) Andrew Bartlett 2007 + Copyright (C) Simo Sorce 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 @@ -33,234 +34,176 @@ #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,134 @@ 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 */ + target_attr = dsdb_attribute_by_linkID(ac->schema, schema_attr->linkID + 1); + attr_name = target_attr->lDAPDisplayName; + attr_val = ldb_dn_get_linearized(ac->req->op.add.message->dn); + + 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; + } + } } - /* 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); -} - -struct merge { - struct ldb_dn *dn; - bool add; - bool ignore; -}; - -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; - } - return -1; + /* if no linked attributes are present continue */ + if (ac->ops == NULL) { + talloc_free(ac); + return ldb_next_request(module, req); } - return ret; + + /* 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; - struct merge *merged_list = NULL; + 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); + } - 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; - } + /* 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); + } - /* 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++; - } + dn = ldb_dn_get_linearized(ac->req->op.add.message->dn); - /* 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++; - } + for (i = 0; i < rc->num_elements; i++) { - /* 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; - } + 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); } - /* 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)); - } - } + search_el = ldb_msg_find_element(ares->message, + rc->el[i].name); - /* 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; + /* See if this element already exists */ + /* otherwise just ignore as + * the add has already been scheduled */ + if ( ! search_el) { + continue; } - /* 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)); + target_attr = dsdb_attribute_by_linkID(ac->schema, schema_attr->linkID + 1); + attr_name = target_attr->lDAPDisplayName; + + /* 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 +348,545 @@ 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); + "attribute %s does not have valid link target", el->name); return LDB_ERR_OBJECT_CLASS_VIOLATION; } - /* 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); + + return ldb_next_request(module, search_req); +} - ret = ldb_set_timeout_from_prev_req(module->ldb, req, new_req); +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; - if (ret != LDB_SUCCESS) { - return 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); + attr_name = target_attr->lDAPDisplayName; + } else { + target_attr = dsdb_attribute_by_linkID(ac->schema, schema_attr->linkID - 1); + 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, }; diff --git a/source4/dsdb/samdb/ldb_modules/local_password.c b/source4/dsdb/samdb/ldb_modules/local_password.c index a411c01513..622e444166 100644 --- a/source4/dsdb/samdb/ldb_modules/local_password.c +++ b/source4/dsdb/samdb/ldb_modules/local_password.c @@ -1,7 +1,7 @@ /* ldb database module - Copyright (C) Simo Sorce 2004-2006 + Copyright (C) Simo Sorce 2004-2008 Copyright (C) Andrew Bartlett 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;iremote_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;iremote_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 }; diff --git a/source4/dsdb/samdb/ldb_modules/normalise.c b/source4/dsdb/samdb/ldb_modules/normalise.c index 3306fd3c33..70513bd644 100644 --- a/source4/dsdb/samdb/ldb_modules/normalise.c +++ b/source4/dsdb/samdb/ldb_modules/normalise.c @@ -45,6 +45,14 @@ 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, diff --git a/source4/dsdb/samdb/ldb_modules/objectclass.c b/source4/dsdb/samdb/ldb_modules/objectclass.c index b048a8d8e1..2c242d47c6 100644 --- a/source4/dsdb/samdb/ldb_modules/objectclass.c +++ b/source4/dsdb/samdb/ldb_modules/objectclass.c @@ -1,7 +1,7 @@ /* ldb database library - Copyright (C) Simo Sorce 2006 + Copyright (C) Simo Sorce 2006-2008 Copyright (C) Andrew Bartlett 2005-2007 This program is free software; you can redistribute it and/or modify @@ -47,21 +47,12 @@ 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 }; diff --git a/source4/dsdb/samdb/ldb_modules/objectguid.c b/source4/dsdb/samdb/ldb_modules/objectguid.c index f62839389d..054905992d 100644 --- a/source4/dsdb/samdb/ldb_modules/objectguid.c +++ b/source4/dsdb/samdb/ldb_modules/objectguid.c @@ -1,9 +1,9 @@ /* ldb database library - Copyright (C) Simo Sorce 2004-2006 Copyright (C) Andrew Bartlett 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 = { diff --git a/source4/dsdb/samdb/ldb_modules/partition.c b/source4/dsdb/samdb/ldb_modules/partition.c index 0cd0baf625..ad2901c308 100644 --- a/source4/dsdb/samdb/ldb_modules/partition.c +++ b/source4/dsdb/samdb/ldb_modules/partition.c @@ -1,4 +1,3 @@ - /* Partitions ldb module @@ -43,61 +42,98 @@ 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; - 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 +156,201 @@ 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); + } + if (ares->error != LDB_SUCCESS) { + return ldb_module_done(ac->req, ares->controls, + ares->response, ares->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; - 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 (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, ares->error); } - talloc_free(ares); - return LDB_SUCCESS; + + /* 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); + } + + 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 +361,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 +382,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 +424,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 +451,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); @@ -366,7 +482,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; } @@ -378,7 +494,7 @@ static int partition_search(struct ldb_module *module, struct ldb_request *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]); + ret = partition_prep_request(ac, data->partitions[i]); if (ret != LDB_SUCCESS) { return ret; } @@ -390,8 +506,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) { @@ -436,7 +554,7 @@ static int partition_rename(struct ldb_module *module, struct ldb_request *req) 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; } @@ -486,24 +604,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 +633,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 +645,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 +680,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 +691,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 +716,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 +763,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 +782,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 +836,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 +854,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 +895,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 +1017,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 +1031,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 +1061,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])) { @@ -1016,72 +1156,6 @@ static int partition_init(struct ldb_module *module) 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) { - 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; - } - } - - 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); - } -} - _PUBLIC_ const struct ldb_module_ops ldb_partition_module_ops = { .name = "partition", .init_context = partition_init, @@ -1095,5 +1169,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 }; diff --git a/source4/dsdb/samdb/ldb_modules/password_hash.c b/source4/dsdb/samdb/ldb_modules/password_hash.c index 6faef63c3d..e36de3c5c4 100644 --- a/source4/dsdb/samdb/ldb_modules/password_hash.c +++ b/source4/dsdb/samdb/ldb_modules/password_hash.c @@ -1,7 +1,7 @@ /* ldb database module - Copyright (C) Simo Sorce 2004-2006 + Copyright (C) Simo Sorce 2004-2008 Copyright (C) Andrew Bartlett 2005-2006 Copyright (C) Andrew Tridgell 2004 Copyright (C) Stefan Metzmacher 2007 @@ -73,23 +73,16 @@ 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 }; diff --git a/source4/dsdb/samdb/ldb_modules/proxy.c b/source4/dsdb/samdb/ldb_modules/proxy.c index d0a315e45a..171832bbb4 100644 --- a/source4/dsdb/samdb/ldb_modules/proxy.c +++ b/source4/dsdb/samdb/ldb_modules/proxy.c @@ -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(ldb, 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;attrnum_elements;attr++) { for (v=0;velements[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;attrnum_elements;attr++) { for (v=0;velements[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,7 +318,7 @@ 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 */ @@ -267,47 +326,50 @@ static int proxy_search_bytree(struct ldb_module *module, struct ldb_request *re 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: diff --git a/source4/dsdb/samdb/ldb_modules/ranged_results.c b/source4/dsdb/samdb/ldb_modules/ranged_results.c index c6ebea1044..b8e43a7e88 100644 --- a/source4/dsdb/samdb/ldb_modules/ranged_results.c +++ b/source4/dsdb/samdb/ldb_modules/ranged_results.c @@ -32,57 +32,89 @@ #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); } diff --git a/source4/dsdb/samdb/ldb_modules/repl_meta_data.c b/source4/dsdb/samdb/ldb_modules/repl_meta_data.c index fbaf461a3f..13a979b6f8 100644 --- a/source4/dsdb/samdb/ldb_modules/repl_meta_data.c +++ b/source4/dsdb/samdb/ldb_modules/repl_meta_data.c @@ -1,7 +1,7 @@ /* ldb database library - Copyright (C) Simo Sorce 2004-2006 + Copyright (C) Simo Sorce 2004-2008 Copyright (C) Andrew Bartlett 2005 Copyright (C) Andrew Tridgell 2005 Copyright (C) Stefan Metzmacher 2007 @@ -51,8 +51,7 @@ 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; @@ -63,59 +62,23 @@ struct replmd_replicated_request { 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; } /* @@ -239,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; @@ -283,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; } @@ -304,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; } @@ -328,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; } @@ -346,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; } @@ -359,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; } @@ -374,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; } @@ -422,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; } @@ -432,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; } @@ -466,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; } @@ -525,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; } @@ -533,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; } } @@ -543,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; @@ -699,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, 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, @@ -755,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; @@ -804,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); } @@ -819,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)) { @@ -837,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); @@ -920,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); @@ -950,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, ar->controls, ar, - replmd_replicated_apply_merge_callback); + replmd_replicated_apply_merge_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) 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; - tmp_str = ldb_binary_encode(ar->sub.mem_ctx, ar->objs->objects[ar->index_current].guid_value); + 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, 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 + return ldb_next_request(ar->module, search_req); } -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); -} - -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, @@ -1104,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; @@ -1145,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)) { @@ -1168,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); @@ -1269,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")), @@ -1304,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, @@ -1378,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, ar->controls, ar, - replmd_replicated_uptodate_modify_callback); + replmd_replicated_uptodate_modify_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) 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[] = { @@ -1451,43 +1348,24 @@ 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) @@ -1511,9 +1389,16 @@ 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; } ctrls = req->controls; @@ -1532,20 +1417,7 @@ static int replmd_extended_replicated_objects(struct ldb_module *module, struct ar->controls = req->controls; req->controls = ctrls; -#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); - } - - if (req->handle->state != LDB_ASYNC_DONE) { - replmd_replicated_uptodate_vector(ar); - } - - return LDB_SUCCESS; -#endif } static int replmd_extended(struct ldb_module *module, struct ldb_request *req) @@ -1557,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 }; diff --git a/source4/dsdb/samdb/ldb_modules/rootdse.c b/source4/dsdb/samdb/ldb_modules/rootdse.c index ebc90d4cf3..0d14a54464 100644 --- a/source4/dsdb/samdb/ldb_modules/rootdse.c +++ b/source4/dsdb/samdb/ldb_modules/rootdse.c @@ -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, + req->controls, + 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) { diff --git a/source4/dsdb/samdb/ldb_modules/samldb.c b/source4/dsdb/samdb/ldb_modules/samldb.c index cf720669b9..e4fc4908a4 100644 --- a/source4/dsdb/samdb/ldb_modules/samldb.c +++ b/source4/dsdb/samdb/ldb_modules/samldb.c @@ -1,8 +1,8 @@ -/* +/* SAM ldb module - Copyright (C) Simo Sorce 2004 Copyright (C) Andrew Bartlett 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 @@ -12,12 +12,12 @@ 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 . */ @@ -37,728 +37,1305 @@ #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) { +#ifdef REAL_EVENT_SYSTEM_HOOKED_UP + return ldb_module_done(ac->req, ares->controls, + ares->response, ares->error); +#else + return ldb_request_done(req, ares->error); +#endif } - 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); +#ifdef REAL_EVENT_SYSTEM_HOOKED_UP + ret = samldb_next_step(ac); +#else + return ldb_request_done(req, LDB_SUCCESS); +#endif + break; + } + +done: + if (ret != LDB_SUCCESS) { +#ifdef REAL_EVENT_SYSTEM_HOOKED_UP + return ldb_module_done(ac->req, NULL, NULL, ret); +#else + return ldb_request_done(req, ret); +#endif } - *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; + } + + /* NOTE: this is a request on a different database! + * + * Therefore we need to do a bloody sync call + * otherwise the fake event queue will never call it + * as it runs on the main ldb context and knows + * nothing about the templates_ldb one */ +#ifdef REAL_EVENT_SYSTEM_HOOKED_UP + ev = ldb_get_event_context(ac->module->ldb); +#else + ev = event_context_init(NULL); +#endif + if (!talloc_reference(templates_ldb, ev)) { + return LDB_ERR_OPERATIONS_ERROR; + } + + 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; + } + + 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; + + /* NOTE: this is a request on a different database! + * Therefore we need to do a bloody sync call + * otherwise the fake event queue will never call it + * as it runs on the main ldb context and knows + * nothing about the templates_ldb one */ +#ifdef REAL_EVENT_SYSTEM_HOOKED_UP + return ldb_request(templates_ldb, req); +#else + ret = ldb_request(templates_ldb, req); + if (ret != LDB_SUCCESS) { + return ret; + } + ret = ldb_wait(req->handle, LDB_WAIT_ALL); + if (ret != LDB_SUCCESS) { + return ret; + } + + return samldb_next_step(ac); +#endif } -/* 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; + + case LDB_REPLY_DONE: - /* find the domain sid */ + 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; + } - ret = ldb_search(module->ldb, mem_ctx, &res, dom_dn, LDB_SCOPE_BASE, attrs, "objectSid=*"); +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); +} - return ret; +static int samldb_generate_samAccountName(struct ldb_message *msg) +{ + char *name; + + /* Format: $000000-000000000000 */ + + 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); + + 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); + } -int samldb_notice_sid(struct ldb_module *module, - TALLOC_CTX *mem_ctx, const struct dom_sid *sid) + 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); + } + + 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; } - ret = samdb_search_for_parent_domain(module->ldb, mem_ctx, msg2->dn, &dom_dn, &errstr); +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); + } + + /* we exit the samldb module here */ + return ldb_module_done(ac->req, ares->controls, + ares->response, LDB_SUCCESS); +} - ret = samdb_search_for_parent_domain(module->ldb, mem_ctx, msg2->dn, &dom_dn, &errstr); +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; + } + + 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); + + talloc_free(ares); + break; + + case LDB_REPLY_REFERRAL: + /* ignore */ + talloc_free(ares); + break; - /* TODO: userAccountControl, badPwdCount, codePage, countryCode, badPasswordTime, lastLogoff, lastLogon, pwdLastSet, primaryGroupID, accountExpires, logonCount */ + case LDB_REPLY_DONE: - if (ret == 0) { - *ret_msg = msg2; - talloc_steal(msg, msg2); + /* 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; } - talloc_free(mem_ctx); - return ret; + +done: + if (ret != LDB_SUCCESS) { + return ldb_module_done(ac->req, NULL, NULL, 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 +1354,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); diff --git a/source4/dsdb/samdb/ldb_modules/schema_fsmo.c b/source4/dsdb/samdb/ldb_modules/schema_fsmo.c index 4b6e9e1d47..56d24a2962 100644 --- a/source4/dsdb/samdb/ldb_modules/schema_fsmo.c +++ b/source4/dsdb/samdb/ldb_modules/schema_fsmo.c @@ -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) @@ -325,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 */ @@ -390,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; - ret = ldb_next_request(module, down_req); + search_context->module = module; + search_context->req = req; + search_context->schema = schema; - /* 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); } diff --git a/source4/dsdb/samdb/ldb_modules/show_deleted.c b/source4/dsdb/samdb/ldb_modules/show_deleted.c index 361cf226dc..0e3b46debe 100644 --- a/source4/dsdb/samdb/ldb_modules/show_deleted.c +++ b/source4/dsdb/samdb/ldb_modules/show_deleted.c @@ -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 */ @@ -42,36 +42,38 @@ 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); } diff --git a/source4/dsdb/samdb/ldb_modules/simple_ldap_map.c b/source4/dsdb/samdb/ldb_modules/simple_ldap_map.c index 8f92995145..d15e85ad41 100644 --- a/source4/dsdb/samdb/ldb_modules/simple_ldap_map.c +++ b/source4/dsdb/samdb/ldb_modules/simple_ldap_map.c @@ -36,6 +36,11 @@ #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; diff --git a/source4/dsdb/samdb/ldb_modules/subtree_delete.c b/source4/dsdb/samdb/ldb_modules/subtree_delete.c index 9c332d2969..10e2dc25ce 100644 --- a/source4/dsdb/samdb/ldb_modules/subtree_delete.c +++ b/source4/dsdb/samdb/ldb_modules/subtree_delete.c @@ -3,6 +3,7 @@ Copyright (C) Andrew Bartlett 2006-2007 Copyright (C) Stefan Metzmacher 2007 + Copyright (C) Simo Sorce 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 @@ -31,104 +32,88 @@ #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, }; diff --git a/source4/dsdb/samdb/ldb_modules/subtree_rename.c b/source4/dsdb/samdb/ldb_modules/subtree_rename.c index fd1388d416..d3ceb8ad97 100644 --- a/source4/dsdb/samdb/ldb_modules/subtree_rename.c +++ b/source4/dsdb/samdb/ldb_modules/subtree_rename.c @@ -30,137 +30,182 @@ #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, }; diff --git a/source4/dsdb/samdb/ldb_modules/update_keytab.c b/source4/dsdb/samdb/ldb_modules/update_keytab.c index 68973124eb..2c6cb102d9 100644 --- a/source4/dsdb/samdb/ldb_modules/update_keytab.c +++ b/source4/dsdb/samdb/ldb_modules/update_keytab.c @@ -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; -- cgit From f14a2b3386e9f44111cee010f6864602e5b833cd Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Fri, 12 Sep 2008 13:27:15 -0400 Subject: LDB ASYNC: ldb misc changes --- source4/lib/ldb/ldb_wrap.c | 22 ++---------- source4/lib/ldb/tools/ldbsearch.c | 76 +++++++++++++++++++++------------------ 2 files changed, 44 insertions(+), 54 deletions(-) diff --git a/source4/lib/ldb/ldb_wrap.c b/source4/lib/ldb/ldb_wrap.c index c15fd2b9ae..cc8099f27f 100644 --- a/source4/lib/ldb/ldb_wrap.c +++ b/source4/lib/ldb/ldb_wrap.c @@ -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) { diff --git a/source4/lib/ldb/tools/ldbsearch.c b/source4/lib/ldb/tools/ldbsearch.c index b3d1f934a6..ceabd5cd78 100644 --- a/source4/lib/ldb/tools/ldbsearch.c +++ b/source4/lib/ldb/tools/ldbsearch.c @@ -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; -- cgit From b2901da479f5e711986de48df4910910460fe7db Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Thu, 11 Sep 2008 18:38:40 -0400 Subject: LDB ASYNC: misc changes --- source4/cldap_server/rootdse.c | 21 ++++++------- source4/dsdb/samdb/cracknames.c | 5 ++- source4/ldap_server/ldap_backend.c | 35 ++++++++++----------- source4/lib/ldb_wrap.c | 13 +------- source4/libcli/ldap/ldap_client.c | 2 +- source4/torture/ldap/schema.c | 64 ++++++++++++++++++++++---------------- 6 files changed, 67 insertions(+), 73 deletions(-) diff --git a/source4/cldap_server/rootdse.c b/source4/cldap_server/rootdse.c index 4ff71c0863..65786e6708 100644 --- a/source4/cldap_server/rootdse.c +++ b/source4/cldap_server/rootdse.c @@ -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); diff --git a/source4/dsdb/samdb/cracknames.c b/source4/dsdb/samdb/cracknames.c index 7324d898a6..e02e8d81a6 100644 --- a/source4/dsdb/samdb/cracknames.c +++ b/source4/dsdb/samdb/cracknames.c @@ -797,7 +797,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 +813,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) { diff --git a/source4/ldap_server/ldap_backend.c b/source4/ldap_server/ldap_backend.c index b954038b80..ffbef3d92f 100644 --- a/source4/ldap_server/ldap_backend.c +++ b/source4/ldap_server/ldap_backend.c @@ -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); diff --git a/source4/lib/ldb_wrap.c b/source4/lib/ldb_wrap.c index 6c683a1e33..617371333f 100644 --- a/source4/lib/ldb_wrap.c +++ b/source4/lib/ldb_wrap.c @@ -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; } - - - diff --git a/source4/libcli/ldap/ldap_client.c b/source4/libcli/ldap/ldap_client.c index d7960f901a..fc5863b671 100644 --- a/source4/libcli/ldap/ldap_client.c +++ b/source4/libcli/ldap/ldap_client.c @@ -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/torture/ldap/schema.c b/source4/torture/ldap/schema.c index dd1d2de331..fdb4251c15 100644 --- a/source4/torture/ldap/schema.c +++ b/source4/torture/ldap/schema.c @@ -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; } -- cgit From cd9f993ec45c6d95e83f759ffd6bccffd90250b6 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Sat, 27 Sep 2008 21:36:18 +0200 Subject: s4:lib/ldb: disable sqlite3 backend always as it doesn't compile anymore metze --- source4/lib/ldb/libldb.m4 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source4/lib/ldb/libldb.m4 b/source4/lib/ldb/libldb.m4 index 77ebcc5ff4..5653794a88 100644 --- a/source4/lib/ldb/libldb.m4 +++ b/source4/lib/ldb/libldb.m4 @@ -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 -- cgit From 95940d75ec51d2f519a1b657e587a77304eaed08 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Mon, 29 Sep 2008 07:43:50 +0200 Subject: s4:libcli/smb2: remove unused header This hopefully fixes the build with internal popt. metze --- source4/libcli/smb2/connect.c | 1 - 1 file changed, 1 deletion(-) diff --git a/source4/libcli/smb2/connect.c b/source4/libcli/smb2/connect.c index db2f97bb94..bbfcf010ae 100644 --- a/source4/libcli/smb2/connect.c +++ b/source4/libcli/smb2/connect.c @@ -27,7 +27,6 @@ #include "libcli/composite/composite.h" #include "libcli/resolve/resolve.h" #include "param/param.h" -#include "lib/cmdline/popt_common.h" struct smb2_connect_state { struct cli_credentials *credentials; -- cgit From 59c3df814a4357d4358e6bcd3bd5d3ff6a18d995 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Mon, 29 Sep 2008 08:42:03 +0200 Subject: s4:samldb: use the code path with async ldb This removes the event_context leak that caused NT_STATUS_TOO_MANY_OPENED_FILES in the server, because of all the epool fds metze --- source4/dsdb/samdb/ldb_modules/samldb.c | 47 +++------------------------------ 1 file changed, 4 insertions(+), 43 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/samldb.c b/source4/dsdb/samdb/ldb_modules/samldb.c index e4fc4908a4..a71ffff618 100644 --- a/source4/dsdb/samdb/ldb_modules/samldb.c +++ b/source4/dsdb/samdb/ldb_modules/samldb.c @@ -154,12 +154,8 @@ static int samldb_search_template_callback(struct ldb_request *req, goto done; } if (ares->error != LDB_SUCCESS) { -#ifdef REAL_EVENT_SYSTEM_HOOKED_UP return ldb_module_done(ac->req, ares->controls, ares->response, ares->error); -#else - return ldb_request_done(req, ares->error); -#endif } switch (ares->type) { @@ -187,21 +183,13 @@ static int samldb_search_template_callback(struct ldb_request *req, case LDB_REPLY_DONE: talloc_free(ares); -#ifdef REAL_EVENT_SYSTEM_HOOKED_UP ret = samldb_next_step(ac); -#else - return ldb_request_done(req, LDB_SUCCESS); -#endif break; } done: if (ret != LDB_SUCCESS) { -#ifdef REAL_EVENT_SYSTEM_HOOKED_UP return ldb_module_done(ac->req, NULL, NULL, ret); -#else - return ldb_request_done(req, ret); -#endif } return LDB_SUCCESS; @@ -240,20 +228,7 @@ static int samldb_search_template(struct samldb_ctx *ac) return LDB_ERR_OPERATIONS_ERROR; } - /* NOTE: this is a request on a different database! - * - * Therefore we need to do a bloody sync call - * otherwise the fake event queue will never call it - * as it runs on the main ldb context and knows - * nothing about the templates_ldb one */ -#ifdef REAL_EVENT_SYSTEM_HOOKED_UP ev = ldb_get_event_context(ac->module->ldb); -#else - ev = event_context_init(NULL); -#endif - if (!talloc_reference(templates_ldb, ev)) { - return LDB_ERR_OPERATIONS_ERROR; - } templates_ldb = ldb_wrap_connect(ac->module->ldb, ev, lparm_ctx, templates_ldb_path, @@ -264,6 +239,10 @@ static int samldb_search_template(struct samldb_ctx *ac) 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) { @@ -295,25 +274,7 @@ static int samldb_search_template(struct samldb_ctx *ac) talloc_steal(req, basedn); ac->ares = NULL; - /* NOTE: this is a request on a different database! - * Therefore we need to do a bloody sync call - * otherwise the fake event queue will never call it - * as it runs on the main ldb context and knows - * nothing about the templates_ldb one */ -#ifdef REAL_EVENT_SYSTEM_HOOKED_UP return ldb_request(templates_ldb, req); -#else - ret = ldb_request(templates_ldb, req); - if (ret != LDB_SUCCESS) { - return ret; - } - ret = ldb_wait(req->handle, LDB_WAIT_ALL); - if (ret != LDB_SUCCESS) { - return ret; - } - - return samldb_next_step(ac); -#endif } static int samldb_apply_template(struct samldb_ctx *ac) -- cgit From 4fa4a524de0647644abc842f34a926b458388b09 Mon Sep 17 00:00:00 2001 From: Michael Adam Date: Mon, 29 Sep 2008 13:52:23 +0200 Subject: [s3]fix build --with-cluster-support after ndr_[pull|push]_struct blob changes. Michael --- source3/lib/ctdbd_conn.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source3/lib/ctdbd_conn.c b/source3/lib/ctdbd_conn.c index 1ae23bcf82..5075476e94 100644 --- a/source3/lib/ctdbd_conn.c +++ b/source3/lib/ctdbd_conn.c @@ -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)) { -- cgit From b8c9daac6eb8a2bcdb14c71c1ddfbfeba4b9b54d Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 17 Sep 2008 16:15:40 +1000 Subject: fixed segv on startup with trusted domains With some setups, idmap_tdb2_allocate_id can be called before the allocate backend is initialised, leading to a segv. This change ensures that the db is opened in all paths that use it --- source3/winbindd/idmap_tdb2.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/source3/winbindd/idmap_tdb2.c b/source3/winbindd/idmap_tdb2.c index 3066db6f3b..911f80c6a3 100644 --- a/source3/winbindd/idmap_tdb2.c +++ b/source3/winbindd/idmap_tdb2.c @@ -187,6 +187,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 +268,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 +459,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 +558,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")); -- cgit From a93dc2c8589428e409fca5a6c21db50db001fe92 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 17 Sep 2008 16:23:17 +1000 Subject: removed unused variables --- source3/winbindd/idmap_tdb2.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/source3/winbindd/idmap_tdb2.c b/source3/winbindd/idmap_tdb2.c index 911f80c6a3..8bde963c60 100644 --- a/source3/winbindd/idmap_tdb2.c +++ b/source3/winbindd/idmap_tdb2.c @@ -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", -- cgit From acf5f2e5b049f20049cb6c549a00ba4b95322aa0 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Mon, 15 Sep 2008 14:27:50 +1000 Subject: fixed a segfault on the ctdb destructor code --- source3/lib/dbwrap_ctdb.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/source3/lib/dbwrap_ctdb.c b/source3/lib/dbwrap_ctdb.c index 63a5ce4de6..cd37d9e917 100644 --- a/source3/lib/dbwrap_ctdb.c +++ b/source3/lib/dbwrap_ctdb.c @@ -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,13 @@ 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); + return NULL; + } + *recp = rec; + talloc_set_destructor(recp, db_ctdb_record_destructor); return rec; } -- cgit From 7caa8c85acfb6d6f8e16e95788fa5e84c031e111 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Mon, 15 Sep 2008 14:51:35 +1000 Subject: fixed an (unlikely) memory leak --- source3/lib/dbwrap_ctdb.c | 1 + 1 file changed, 1 insertion(+) diff --git a/source3/lib/dbwrap_ctdb.c b/source3/lib/dbwrap_ctdb.c index cd37d9e917..2818634b14 100644 --- a/source3/lib/dbwrap_ctdb.c +++ b/source3/lib/dbwrap_ctdb.c @@ -442,6 +442,7 @@ static struct db_record *db_ctdb_fetch_locked_persistent(struct db_ctdb_ctx *ctx recp = talloc(rec, struct db_record *); if (recp == NULL) { ctx->db->transaction_cancel(ctx->db); + talloc_free(rec); return NULL; } *recp = rec; -- cgit From 86612b1163d2dae8f707b6a038ad1a361c975973 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Wed, 17 Sep 2008 15:37:54 +1000 Subject: re-added "winbind:ignore domains" patch This option really is essential, as we discover again and again at customer sites. Due to bugs in winbind some domains are toxic. When you are installing at a site and a particular domain in a complex setup causes winbind to segfault or hang then you need a way to disable that domain and continue. In an ideal world winbind could handle arbitrarily complex ADS domains, but we are nowhere near that yet. If we ever get to that stage then we won't need this option. --- source3/winbindd/winbindd_util.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/source3/winbindd/winbindd_util.c b/source3/winbindd/winbindd_util.c index 5b5ca41a74..b8cb27c797 100644 --- a/source3/winbindd/winbindd_util.c +++ b/source3/winbindd/winbindd_util.c @@ -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 )); -- cgit From b9ccf0dc6f34fe3d63b8272f61f9e1fef7f5d885 Mon Sep 17 00:00:00 2001 From: Holger Hetterich Date: Mon, 29 Sep 2008 14:34:36 +0200 Subject: Add an initial version of a manpage for the vfs_smb_traffic_analyzer module. (cherry picked from commit 7857b783049b19d32a078927a46cb1070e863b45) --- docs-xml/manpages-3/vfs_smb_traffic_analyzer.8.xml | 157 +++++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 docs-xml/manpages-3/vfs_smb_traffic_analyzer.8.xml 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 index 0000000000..c0b1ef89e0 --- /dev/null +++ b/docs-xml/manpages-3/vfs_smb_traffic_analyzer.8.xml @@ -0,0 +1,157 @@ + + + + + + smb_traffic_analyzer + 8 + Samba + System Administration tools + 3.2 + + + + + vfs_smb_traffic_analyzer + log Samba VFS read and write operations through a socket + to a helper application + + + + + vfs objects = smb_traffic_analyzer + + + + + DESCRIPTION + + This VFS module is part of the + samba + 7 suite. + + The vfs_smb_traffic_analyzer 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/ + + vfs_smb_traffic_analyzer currently is aware + of the following VFS operations: + + + write + pwrite + read + pread + + + vfs_smb_traffic_analyzer sends the following data + in a fixed format seperated by a comma through either an internet or a + unix domain socket: + + BYTES|USER|DOMAIN|READ/WRITE|SHARE|FILENAME|TIMESTAMP + + + Description of the records: + + + BYTES - the length in bytes of the VFS operation + USER - the user who initiated the operation + DOMAIN - the domain of the user + READ/WRITE - either "W" for a write operation or "R" for read + SHARE - the name of the share on which the VFS operation occured + FILENAME - the name of the file that was used by the VFS operation + TIMESTAMP - a timestamp, formatted as "yyyy-mm-dd hh-mm-ss.ms" indicating when the VFS operation occured + + + + + This module is stackable. + + + + + + OPTIONS + + + + + smb_traffic_analyzer:mode = STRING + + 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. + + + + + + + smb_traffic_analyzer:host = STRING + + The module will send the data to the system named with + the hostname STRING. + + + + + + smb_traffic_analyzer:port = STRING + + The module will send the data using the TCP port given + in STRING + + + + + + + + + + + EXAMPLES + + The module running on share "example_share", using a unix domain socket + + + /data/example + smb_traffic_analyzer + unix_domain_socket + + + The module running on share "example_share", using an internet domain socket, + connecting to host "examplehost" on port 3491. + + + /data/example + smb_traffic_analyzer + examplehost + 3490 + + + + + + VERSION + This man page is correct for version 3.2.0 of the Samba suite. + + + + + AUTHOR + + 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. + + The original version of the VFS module and the + helper tools were created by Holger Hetterich. + + + -- cgit From ec63cd6a7f87ebbc969fa270fefdde47385217b4 Mon Sep 17 00:00:00 2001 From: Karolin Seeger Date: Mon, 29 Sep 2008 15:39:43 +0200 Subject: docs: Adapt version strings in man vfs_smb_traffic_analyzer. Karolin (cherry picked from commit 662eda8458a304b224b6bc502f8030a07030b7c2) --- docs-xml/manpages-3/vfs_smb_traffic_analyzer.8.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs-xml/manpages-3/vfs_smb_traffic_analyzer.8.xml b/docs-xml/manpages-3/vfs_smb_traffic_analyzer.8.xml index c0b1ef89e0..28c8413231 100644 --- a/docs-xml/manpages-3/vfs_smb_traffic_analyzer.8.xml +++ b/docs-xml/manpages-3/vfs_smb_traffic_analyzer.8.xml @@ -7,7 +7,7 @@ 8 Samba System Administration tools - 3.2 + 3.3 @@ -138,7 +138,7 @@ VERSION - This man page is correct for version 3.2.0 of the Samba suite. + This man page is correct for version 3.3 of the Samba suite. -- cgit From 0ee4d20adb21d2e4491ca0cbfe3c031cb89fde92 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 18 Sep 2008 05:01:47 +0200 Subject: s3:mapping_tdb: fix the del_aliasmem() function We should not cancel the transaction, when we want to delete a key. metze --- source3/groupdb/mapping_tdb.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/source3/groupdb/mapping_tdb.c b/source3/groupdb/mapping_tdb.c index 7cee53a968..29927eb592 100644 --- a/source3/groupdb/mapping_tdb.c +++ b/source3/groupdb/mapping_tdb.c @@ -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)) { -- cgit From 55e201b0a1b24e328b718b78ab8fa926bcc9e90b Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Mon, 29 Sep 2008 19:09:53 +0200 Subject: Avoid freeing fsp twice when opening new_file fails. (Debian #431696) If opening new_file fails, fsp would still be set to the files_struct of old_file. --- source3/printing/nt_printing.c | 1 + 1 file changed, 1 insertion(+) diff --git a/source3/printing/nt_printing.c b/source3/printing/nt_printing.c index ded985c260..a3b3a1021f 100644 --- a/source3/printing/nt_printing.c +++ b/source3/printing/nt_printing.c @@ -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); -- cgit From c383e8d760b64cb25c93550876280b3c9fc33e5c Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Mon, 29 Sep 2008 10:57:22 -0700 Subject: Ensure we null out fsp after a close in all paths. Jeremy. --- source3/printing/nt_printing.c | 1 + 1 file changed, 1 insertion(+) diff --git a/source3/printing/nt_printing.c b/source3/printing/nt_printing.c index a3b3a1021f..19c44d1bbb 100644 --- a/source3/printing/nt_printing.c +++ b/source3/printing/nt_printing.c @@ -1418,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 */ -- cgit From f22f04f76beba755ed5fcc7385de7b366b71032c Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Mon, 29 Sep 2008 22:47:07 +0200 Subject: Stop creating symlinks to libraries without sonames. (caused recursive symlinks overwriting the original file). --- source4/script/installlib.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source4/script/installlib.sh b/source4/script/installlib.sh index 962c9562b1..cc9ff0b9ea 100755 --- a/source4/script/installlib.sh +++ b/source4/script/installlib.sh @@ -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 -- cgit From 744667b3a9bc9d4d48e842378612b40b3539840a Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Mon, 29 Sep 2008 22:57:16 +0200 Subject: Consistently use lower case variable names for path variables. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Patch by Matthias Dieter Wallnöfer and me. --- source4/Makefile | 32 ++++++++++++++++---------------- source4/dynconfig/config.mk | 12 ++++++------ 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/source4/Makefile b/source4/Makefile index 813f0cedd4..cb4aa0e916 100644 --- a/source4/Makefile +++ b/source4/Makefile @@ -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) @@ -133,7 +133,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 +155,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 +166,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)' @@ -194,10 +194,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 +211,7 @@ installdirs:: $(DESTDIR)$(logfilebase) \ $(DESTDIR)$(privatedir)/tls \ $(DESTDIR)$(includedir) \ - $(DESTDIR)$(PKGCONFIGDIR) \ + $(DESTDIR)$(pkgconfigdir) \ $(DESTDIR)$(sysconfdir) installbin:: installdirs @@ -230,16 +230,16 @@ installdat:: installdirs installswat:: installdirs #SWAT has been disabled until further notice -# @$(SHELL) $(srcdir)/script/installswat.sh $(DESTDIR)$(SWATDIR) $(srcdir) +# @$(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) $(DESTDIR)$(bindir) 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 diff --git a/source4/dynconfig/config.mk b/source4/dynconfig/config.mk index 699c30e764..f79cdb8e75 100644 --- a/source4/dynconfig/config.mk +++ b/source4/dynconfig/config.mk @@ -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)\" -- cgit From a270ddb6e3d5bd5b72558809877d27c3c344797d Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Mon, 29 Sep 2008 14:04:48 -0700 Subject: make the schannel creentials persistent this makes testing with the WSPP test suite much easier over samba restarts --- source4/auth/gensec/schannel_state.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/auth/gensec/schannel_state.c b/source4/auth/gensec/schannel_state.c index 0388b3caf6..64c21d0c3e 100644 --- a/source4/auth/gensec/schannel_state.c +++ b/source4/auth/gensec/schannel_state.c @@ -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; } -- cgit From dd4d309cac42c353c118d50e2f47ed0d27f429fb Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Mon, 29 Sep 2008 23:34:05 +0200 Subject: Patch by Matthias that removes old SWAT support and fixes uninstall. --- source4/Makefile | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/source4/Makefile b/source4/Makefile index cb4aa0e916..8f31979f21 100644 --- a/source4/Makefile +++ b/source4/Makefile @@ -181,7 +181,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 @@ -228,10 +228,6 @@ 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) @@ -241,11 +237,12 @@ installmisc:: installdirs installpc:: installdirs @$(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" + @cd $(DESTDIR)$(bindir); rm -f $(notdir $(miscbinfiles)) $(DESTDIR)$(bindir)/%: bin/% installdirs @mkdir -p $(@D) @@ -261,19 +258,27 @@ $(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." -- cgit From 2ed71ce6bc97cbb9b854bb24ab49001910eda36d Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 00:28:06 +0200 Subject: Remove ldb_module_wait implementation - ldb_module.wait() is gone. --- source4/lib/ldb/ldb.i | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/source4/lib/ldb/ldb.i b/source4/lib/ldb/ldb.i index 1e3a3169c8..024ba1959a 100644 --- a/source4/lib/ldb/ldb.i +++ b/source4/lib/ldb/ldb.i @@ -1219,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; @@ -1308,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; } -- cgit From f379f67dd287292e3bb7b606f1bdc3fe7a8db59c Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 00:29:03 +0200 Subject: Fix installation of misc files. --- pidl/config.mk | 4 ++-- source4/Makefile | 13 +++++++++++-- source4/dynconfig/dynconfig.c | 3 --- source4/script/installmisc.sh | 6 ------ 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/pidl/config.mk b/pidl/config.mk index 07c8647ecd..45582f5d56 100644 --- a/pidl/config.mk +++ b/pidl/config.mk @@ -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) \ diff --git a/source4/Makefile b/source4/Makefile index 8f31979f21..71529305b4 100644 --- a/source4/Makefile +++ b/source4/Makefile @@ -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))) \ @@ -232,7 +241,7 @@ 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) @@ -242,7 +251,7 @@ uninstall:: uninstallbin uninstallsbin uninstalldat uninstallmisc uninstalllib u uninstallmisc:: @echo "Removing MISC files" - @cd $(DESTDIR)$(bindir); rm -f $(notdir $(miscbinfiles)) + @rm -rf $(DESTDIR)$(setupdir)/* $(DESTDIR)$(bindir)/%: bin/% installdirs @mkdir -p $(@D) diff --git a/source4/dynconfig/dynconfig.c b/source4/dynconfig/dynconfig.c index 507570318d..e0cabef317 100644 --- a/source4/dynconfig/dynconfig.c +++ b/source4/dynconfig/dynconfig.c @@ -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; diff --git a/source4/script/installmisc.sh b/source4/script/installmisc.sh index eb347307ba..2bd34b119f 100755 --- a/source4/script/installmisc.sh +++ b/source4/script/installmisc.sh @@ -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 -- cgit From 257fe87efd079ccc085e67d04c7797dbf2e84c51 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 00:32:20 +0200 Subject: Re-add uninstallplugins, there has to be at least one instance of this. --- source4/Makefile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source4/Makefile b/source4/Makefile index 71529305b4..74383b1a59 100644 --- a/source4/Makefile +++ b/source4/Makefile @@ -285,6 +285,8 @@ 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)) -- cgit From 21df9532f54ad15c308630672f3b8a6dc4ce6294 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 00:48:13 +0200 Subject: Remove unused uninstallheader script. --- source4/script/uninstallheader.sh | 35 ----------------------------------- 1 file changed, 35 deletions(-) delete mode 100755 source4/script/uninstallheader.sh diff --git a/source4/script/uninstallheader.sh b/source4/script/uninstallheader.sh deleted file mode 100755 index cb491f071a..0000000000 --- a/source4/script/uninstallheader.sh +++ /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 -- cgit From 750a848d0dbae8ea66a9f265294d7f95556c0c27 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Mon, 29 Sep 2008 16:01:07 -0700 Subject: added some more well known SIDs - thanks to the WSPP LSAT test suite --- source4/librpc/idl/security.idl | 6 ++++ source4/rpc_server/lsa/lsa_lookup.c | 43 +++++++++++++++++++++++++- source4/setup/provision_users.ldif | 60 +++++++++++++++++++++++++++++++++++++ 3 files changed, 108 insertions(+), 1 deletion(-) diff --git a/source4/librpc/idl/security.idl b/source4/librpc/idl/security.idl index 80efe46453..ac7641c0af 100644 --- a/source4/librpc/idl/security.idl +++ b/source4/librpc/idl/security.idl @@ -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"; diff --git a/source4/rpc_server/lsa/lsa_lookup.c b/source4/rpc_server/lsa/lsa_lookup.c index 30bceb8139..acd3164b69 100644 --- a/source4/rpc_server/lsa/lsa_lookup.c +++ b/source4/rpc_server/lsa/lsa_lookup.c @@ -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, } diff --git a/source4/setup/provision_users.ldif b/source4/setup/provision_users.ldif index 854c42d07c..c61cb805c4 100644 --- a/source4/setup/provision_users.ldif +++ b/source4/setup/provision_users.ldif @@ -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 -- cgit From 385015f8f2ea44e8f846e72c7bc74d4c489ae49e Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Mon, 29 Sep 2008 16:10:54 -0700 Subject: unmapped SIDs should be rid 0 not rid -1 --- source4/rpc_server/lsa/lsa_lookup.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/source4/rpc_server/lsa/lsa_lookup.c b/source4/rpc_server/lsa/lsa_lookup.c index acd3164b69..5f080e6da2 100644 --- a/source4/rpc_server/lsa/lsa_lookup.c +++ b/source4/rpc_server/lsa/lsa_lookup.c @@ -892,7 +892,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; -- cgit From c8a19f0b8373bec27f4d3638bb731963896f3ff5 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 01:29:53 +0200 Subject: Pass options struct into session initialization functions rather than using global_loadparm. --- source4/libcli/cliconnect.c | 6 +++++- source4/libcli/raw/clisession.c | 7 +++---- source4/libcli/smb_composite/connect.c | 5 ++++- source4/param/loadparm.c | 8 ++++++++ source4/param/param.h | 3 +++ source4/torture/basic/secleak.c | 5 ++++- source4/torture/raw/context.c | 26 ++++++++++++++++++-------- source4/torture/raw/lock.c | 5 ++++- source4/torture/rpc/samba3rpc.c | 8 ++++++-- 9 files changed, 55 insertions(+), 18 deletions(-) diff --git a/source4/libcli/cliconnect.c b/source4/libcli/cliconnect.c index c20a7fd935..6fb9f130a9 100644 --- a/source4/libcli/cliconnect.c +++ b/source4/libcli/cliconnect.c @@ -73,8 +73,12 @@ NTSTATUS smbcli_session_setup(struct smbcli_state *cli, { struct smb_composite_sesssetup setup; NTSTATUS status; + struct smbcli_session_options options; - cli->session = smbcli_session_init(cli->transport, cli, true); + lp_smbcli_session_options(global_loadparm, &options); + + cli->session = smbcli_session_init(cli->transport, cli, true, + options); if (!cli->session) return NT_STATUS_UNSUCCESSFUL; setup.in.sesskey = cli->transport->negotiate.sesskey; diff --git a/source4/libcli/raw/clisession.c b/source4/libcli/raw/clisession.c index ad4ca7b471..38d8f700f2 100644 --- a/source4/libcli/raw/clisession.c +++ b/source4/libcli/raw/clisession.c @@ -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; diff --git a/source4/libcli/smb_composite/connect.c b/source4/libcli/smb_composite/connect.c index e56339f96b..5f651f4865 100644 --- a/source4/libcli/smb_composite/connect.c +++ b/source4/libcli/smb_composite/connect.c @@ -229,12 +229,15 @@ static NTSTATUS connect_negprot(struct composite_context *c, { struct connect_state *state = talloc_get_type(c->private_data, struct connect_state); NTSTATUS status; + struct smbcli_session_options options; + + lp_smbcli_session_options(global_loadparm, &options); status = smb_raw_negotiate_recv(state->req); 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, options); NT_STATUS_HAVE_NO_MEMORY(state->session); /* setup for a tconx (or at least have the structure ready to diff --git a/source4/param/loadparm.c b/source4/param/loadparm.c index 15edbd1f89..0042dbd876 100644 --- a/source4/param/loadparm.c +++ b/source4/param/loadparm.c @@ -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); +} diff --git a/source4/param/param.h b/source4/param/param.h index 4ed2654692..4c6e8b79a2 100644 --- a/source4/param/param.h +++ b/source4/param/param.h @@ -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 */ diff --git a/source4/torture/basic/secleak.c b/source4/torture/basic/secleak.c index 4caeee72a4..ca1fd444d9 100644 --- a/source4/torture/basic/secleak.c +++ b/source4/torture/basic/secleak.c @@ -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); diff --git a/source4/torture/raw/context.c b/source4/torture/raw/context.c index 15e736fff5..450ad0f260 100644 --- a/source4/torture/raw/context.c +++ b/source4/torture/raw/context.c @@ -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 */ diff --git a/source4/torture/raw/lock.c b/source4/torture/raw/lock.c index cd8d606795..dbe071c9ad 100644 --- a/source4/torture/raw/lock.c +++ b/source4/torture/raw/lock.c @@ -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); diff --git a/source4/torture/rpc/samba3rpc.c b/source4/torture/rpc/samba3rpc.c index 3bbf6cf223..e030b972f8 100644 --- a/source4/torture/rpc/samba3rpc.c +++ b/source4/torture/rpc/samba3rpc.c @@ -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,6 +84,7 @@ 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), @@ -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; @@ -1670,12 +1672,14 @@ 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), @@ -1762,7 +1766,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__); -- cgit From 83183bf38190b867ca4bb7ebda1136803e36f777 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 01:38:51 +0200 Subject: Explicitly pass on session options to session setup function. --- source4/client/smbmount.c | 19 ++++++++++++++----- source4/libcli/cliconnect.c | 6 ++---- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/source4/client/smbmount.c b/source4/client/smbmount.c index 9ab6c375f2..37c9eaadc4 100644 --- a/source4/client/smbmount.c +++ b/source4/client/smbmount.c @@ -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); diff --git a/source4/libcli/cliconnect.c b/source4/libcli/cliconnect.c index 6fb9f130a9..3b1c3c5314 100644 --- a/source4/libcli/cliconnect.c +++ b/source4/libcli/cliconnect.c @@ -69,13 +69,11 @@ 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; - struct smbcli_session_options options; - - lp_smbcli_session_options(global_loadparm, &options); cli->session = smbcli_session_init(cli->transport, cli, true, options); -- cgit From 40fa4c4154aa572f39fddf16b2fefbe370910360 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Mon, 29 Sep 2008 16:50:46 -0700 Subject: we need to return NT_STATUS_INVALID_PARAMETER for bad levels in lsalookupnames2 --- source4/rpc_server/lsa/lsa_lookup.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/source4/rpc_server/lsa/lsa_lookup.c b/source4/rpc_server/lsa/lsa_lookup.c index 5f080e6da2..7bf7d849b7 100644 --- a/source4/rpc_server/lsa/lsa_lookup.c +++ b/source4/rpc_server/lsa/lsa_lookup.c @@ -862,6 +862,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); -- cgit From 28482efa5ceebdea821b9368a2761e93ee2fff59 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Mon, 29 Sep 2008 16:51:05 -0700 Subject: WSPP docs say we need to check that root_dir is NULL --- source4/rpc_server/lsa/lsa_init.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/source4/rpc_server/lsa/lsa_init.c b/source4/rpc_server/lsa/lsa_init.c index e5e31c74f8..a95cb10f9f 100644 --- a/source4/rpc_server/lsa/lsa_init.c +++ b/source4/rpc_server/lsa/lsa_init.c @@ -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; -- cgit From c951a881da60b51e06a5182c5ad9fb32482b0ab5 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Mon, 29 Sep 2008 16:51:21 -0700 Subject: added new level for lsalookupnames2 --- source4/librpc/idl/lsa.idl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source4/librpc/idl/lsa.idl b/source4/librpc/idl/lsa.idl index 9a6e4a202c..eed713f71c 100644 --- a/source4/librpc/idl/lsa.idl +++ b/source4/librpc/idl/lsa.idl @@ -387,7 +387,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 ( -- cgit From 9de1472bd1848363dfce1644ce7b971486551ec3 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 01:58:06 +0200 Subject: Remove redundant call. --- source4/librpc/rpc/dcerpc_connect.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/librpc/rpc/dcerpc_connect.c b/source4/librpc/rpc/dcerpc_connect.c index 318b8fe36d..7bdca2d986 100644 --- a/source4/librpc/rpc/dcerpc_connect.c +++ b/source4/librpc/rpc/dcerpc_connect.c @@ -137,7 +137,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; -- cgit From 43d944e6d6b66cf67ee857a62a439296738d3a59 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 01:59:10 +0200 Subject: Remove global_loadparm instance. --- source4/libnet/libnet_site.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/libnet/libnet_site.c b/source4/libnet/libnet_site.c index bb65de1f54..5647a93b8d 100644 --- a/source4/libnet/libnet_site.c +++ b/source4/libnet/libnet_site.c @@ -56,7 +56,7 @@ 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) { /* -- cgit From 755ad80e2932f2114941adeb13f8879010484ff8 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 02:07:14 +0200 Subject: Remove uses of global_loadparm. --- source4/torture/rpc/samlogon.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/source4/torture/rpc/samlogon.c b/source4/torture/rpc/samlogon.c index 4fbffee41e..b7028e6609 100644 --- a/source4/torture/rpc/samlogon.c +++ b/source4/torture/rpc/samlogon.c @@ -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; -- cgit From 4e8cb60222ea13295eaff477625164dfd61e288f Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 02:11:55 +0200 Subject: Remove global_loadparm instance. --- source4/libcli/smb_composite/fsinfo.c | 10 ++++++---- source4/torture/raw/composite.c | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/source4/libcli/smb_composite/fsinfo.c b/source4/libcli/smb_composite/fsinfo.c index 270d71f518..cd6e98547b 100644 --- a/source4/libcli/smb_composite/fsinfo.c +++ b/source4/libcli/smb_composite/fsinfo.c @@ -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; @@ -160,7 +161,7 @@ struct composite_context *smb_composite_fsinfo_send(struct smbcli_tree *tree, 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 +198,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); } diff --git a/source4/torture/raw/composite.c b/source4/torture/raw/composite.c index d73ac1327e..a151854e59 100644 --- a/source4/torture/raw/composite.c +++ b/source4/torture/raw/composite.c @@ -358,7 +358,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; itree,&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; } -- cgit From cef80957c49c972e82a634724590b5fd5d6ca78f Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 02:19:15 +0200 Subject: Remove global_loadparm instance, discard_const_p. --- source4/libnet/libnet_samdump_keytab.c | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/source4/libnet/libnet_samdump_keytab.c b/source4/libnet/libnet_samdump_keytab.c index 0c4d3e5c59..4b71b0c24d 100644 --- a/source4/libnet/libnet_samdump_keytab.c +++ b/source4/libnet/libnet_samdump_keytab.c @@ -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; -- cgit From 181ee01da67985f5db684500247d655ce72fe611 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 02:47:19 +0200 Subject: Pass session options around; saves another use of global_loadparm. --- source4/auth/ntlm/auth_server.c | 1 + source4/libcli/raw/clitree.c | 4 +++- source4/libcli/smb_composite/connect.c | 5 +---- source4/libcli/smb_composite/fetchfile.c | 1 + source4/libcli/smb_composite/fsinfo.c | 1 + source4/libcli/smb_composite/smb_composite.h | 2 ++ source4/librpc/rpc/dcerpc_connect.c | 1 + source4/ntvfs/cifs/vfs_cifs.c | 1 + source4/torture/basic/misc.c | 1 + source4/torture/raw/composite.c | 1 + source4/torture/raw/lockbench.c | 1 + source4/torture/raw/openbench.c | 1 + 12 files changed, 15 insertions(+), 5 deletions(-) diff --git a/source4/auth/ntlm/auth_server.c b/source4/auth/ntlm/auth_server.c index bb8773e75e..539ae6aa80 100644 --- a/source4/auth/ntlm/auth_server.c +++ b/source4/auth/ntlm/auth_server.c @@ -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); diff --git a/source4/libcli/raw/clitree.c b/source4/libcli/raw/clitree.c index 15cd70833c..4b5d2dc397 100644 --- a/source4/libcli/raw/clitree.c +++ b/source4/libcli/raw/clitree.c @@ -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)) { diff --git a/source4/libcli/smb_composite/connect.c b/source4/libcli/smb_composite/connect.c index 5f651f4865..a4137290bb 100644 --- a/source4/libcli/smb_composite/connect.c +++ b/source4/libcli/smb_composite/connect.c @@ -229,15 +229,12 @@ static NTSTATUS connect_negprot(struct composite_context *c, { struct connect_state *state = talloc_get_type(c->private_data, struct connect_state); NTSTATUS status; - struct smbcli_session_options options; - - lp_smbcli_session_options(global_loadparm, &options); status = smb_raw_negotiate_recv(state->req); NT_STATUS_NOT_OK_RETURN(status); /* next step is a session setup */ - state->session = smbcli_session_init(state->transport, state, true, options); + 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 diff --git a/source4/libcli/smb_composite/fetchfile.c b/source4/libcli/smb_composite/fetchfile.c index 9cd02a51f4..ff4f0e7930 100644 --- a/source4/libcli/smb_composite/fetchfile.c +++ b/source4/libcli/smb_composite/fetchfile.c @@ -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); diff --git a/source4/libcli/smb_composite/fsinfo.c b/source4/libcli/smb_composite/fsinfo.c index cd6e98547b..dc5327a29c 100644 --- a/source4/libcli/smb_composite/fsinfo.c +++ b/source4/libcli/smb_composite/fsinfo.c @@ -155,6 +155,7 @@ 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; diff --git a/source4/libcli/smb_composite/smb_composite.h b/source4/libcli/smb_composite/smb_composite.h index 7f4b9d73e4..08ca40c833 100644 --- a/source4/libcli/smb_composite/smb_composite.h +++ b/source4/libcli/smb_composite/smb_composite.h @@ -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; diff --git a/source4/librpc/rpc/dcerpc_connect.c b/source4/librpc/rpc/dcerpc_connect.c index 7bdca2d986..b117a98270 100644 --- a/source4/librpc/rpc/dcerpc_connect.c +++ b/source4/librpc/rpc/dcerpc_connect.c @@ -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 diff --git a/source4/ntvfs/cifs/vfs_cifs.c b/source4/ntvfs/cifs/vfs_cifs.c index 844fa11cc5..9bc36a1762 100644 --- a/source4/ntvfs/cifs/vfs_cifs.c +++ b/source4/ntvfs/cifs/vfs_cifs.c @@ -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; diff --git a/source4/torture/basic/misc.c b/source4/torture/basic/misc.c index 24e0324bc3..c129fd586b 100644 --- a/source4/torture/basic/misc.c +++ b/source4/torture/basic/misc.c @@ -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); diff --git a/source4/torture/raw/composite.c b/source4/torture/raw/composite.c index a151854e59..7f1f5943e1 100644 --- a/source4/torture/raw/composite.c +++ b/source4/torture/raw/composite.c @@ -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); diff --git a/source4/torture/raw/lockbench.c b/source4/torture/raw/lockbench.c index 21541d003b..26fad4235e 100644 --- a/source4/torture/raw/lockbench.c +++ b/source4/torture/raw/lockbench.c @@ -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); diff --git a/source4/torture/raw/openbench.c b/source4/torture/raw/openbench.c index 26b862c33f..ec94637445 100644 --- a/source4/torture/raw/openbench.c +++ b/source4/torture/raw/openbench.c @@ -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); -- cgit From 235b729309a17fa44fecf743db5fe6552f67f577 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 03:07:08 +0200 Subject: Cope with API changes. --- source4/client/cifsdd.c | 15 ++++++++++----- source4/client/cifsdd.h | 4 +++- source4/client/cifsddio.c | 17 +++++++++++------ source4/client/client.c | 9 ++++++--- source4/libcli/cliconnect.c | 6 ++++-- source4/torture/gentest.c | 5 ++++- source4/torture/locktest.c | 4 +++- source4/torture/locktest2.c | 19 ++++++++++++------- source4/torture/masktest.c | 9 ++++++--- source4/torture/raw/oplock.c | 5 +++-- source4/torture/raw/tconrate.c | 4 +++- source4/torture/rpc/join.c | 6 ++++-- source4/torture/rpc/samba3rpc.c | 18 ++++++++++++------ source4/torture/unix/unix_info2.c | 4 +++- source4/torture/unix/whoami.c | 4 +++- source4/torture/util_smb.c | 4 +++- 16 files changed, 90 insertions(+), 43 deletions(-) diff --git a/source4/client/cifsdd.c b/source4/client/cifsdd.c index 141b165ad4..5f07826d06 100644 --- a/source4/client/cifsdd.c +++ b/source4/client/cifsdd.c @@ -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); } diff --git a/source4/client/cifsdd.h b/source4/client/cifsdd.h index 21a4ad4882..3195e4334f 100644 --- a/source4/client/cifsdd.h +++ b/source4/client/cifsdd.h @@ -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, diff --git a/source4/client/cifsddio.c b/source4/client/cifsddio.c index 4297c30012..25194a621a 100644 --- a/source4/client/cifsddio.c +++ b/source4/client/cifsddio.c @@ -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)); diff --git a/source4/client/client.c b/source4/client/client.c index e05e195372..266bd67025 100644 --- a/source4/client/client.c +++ b/source4/client/client.c @@ -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) diff --git a/source4/libcli/cliconnect.c b/source4/libcli/cliconnect.c index 3b1c3c5314..e42b04cdc5 100644 --- a/source4/libcli/cliconnect.c +++ b/source4/libcli/cliconnect.c @@ -146,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; @@ -157,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; } diff --git a/source4/torture/gentest.c b/source4/torture/gentest.c index fecdfda56e..3bf3ad8b1b 100644 --- a/source4/torture/gentest.c +++ b/source4/torture/gentest.c @@ -214,7 +214,9 @@ static bool connect_servers(struct event_context *ev, for (j=0;jlp_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; diff --git a/source4/torture/raw/tconrate.c b/source4/torture/raw/tconrate.c index 6f0ba0d617..66ef2ae2dd 100644 --- a/source4/torture/raw/tconrate.c +++ b/source4/torture/raw/tconrate.c @@ -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", diff --git a/source4/torture/rpc/join.c b/source4/torture/rpc/join.c index 77da32d572..ee0c05360f 100644 --- a/source4/torture/rpc/join.c +++ b/source4/torture/rpc/join.c @@ -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)); diff --git a/source4/torture/rpc/samba3rpc.c b/source4/torture/rpc/samba3rpc.c index e030b972f8..260c1cc149 100644 --- a/source4/torture/rpc/samba3rpc.c +++ b/source4/torture/rpc/samba3rpc.c @@ -91,7 +91,7 @@ bool torture_bind_authcontext(struct torture_context *torture) 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)); @@ -290,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"); @@ -299,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)); @@ -1197,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) { @@ -1216,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)); @@ -1301,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)); @@ -1686,7 +1692,7 @@ bool torture_samba3_rpc_getusername(struct torture_context *torture) 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)); @@ -1713,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)); diff --git a/source4/torture/unix/unix_info2.c b/source4/torture/unix/unix_info2.c index d7482ddcf1..3bddde2a97 100644 --- a/source4/torture/unix/unix_info2.c +++ b/source4/torture/unix/unix_info2.c @@ -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", diff --git a/source4/torture/unix/whoami.c b/source4/torture/unix/whoami.c index 39d0a12ab1..d742e23e82 100644 --- a/source4/torture/unix/whoami.c +++ b/source4/torture/unix/whoami.c @@ -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", diff --git a/source4/torture/util_smb.c b/source4/torture/util_smb.c index 938e7d6c03..32e4453aca 100644 --- a/source4/torture/util_smb.c +++ b/source4/torture/util_smb.c @@ -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; -- cgit From 2ba4a79210f35df526a72c740ada5de34d6f45f4 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 03:20:46 +0200 Subject: Eliminate another global_loadparm. --- source4/smbd/process_model.h | 3 ++- source4/smbd/process_prefork.c | 2 +- source4/smbd/process_single.c | 2 +- source4/smbd/process_standard.c | 5 +++-- source4/smbd/process_thread.c | 2 +- source4/smbd/service_stream.c | 2 +- source4/smbd/service_task.c | 2 +- 7 files changed, 10 insertions(+), 8 deletions(-) diff --git a/source4/smbd/process_model.h b/source4/smbd/process_model.h index a9b33a4725..6afb66ff20 100644 --- a/source4/smbd/process_model.h +++ b/source4/smbd/process_model.h @@ -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); diff --git a/source4/smbd/process_prefork.c b/source4/smbd/process_prefork.c index 0d17e5301d..1b369613ff 100644 --- a/source4/smbd/process_prefork.c +++ b/source4/smbd/process_prefork.c @@ -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)); } diff --git a/source4/smbd/process_single.c b/source4/smbd/process_single.c index a7a27ef9e0..26afff9930 100644 --- a/source4/smbd/process_single.c +++ b/source4/smbd/process_single.c @@ -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)); } diff --git a/source4/smbd/process_standard.c b/source4/smbd/process_standard.c index c8f90209b6..0a864dabb2 100644 --- a/source4/smbd/process_standard.c +++ b/source4/smbd/process_standard.c @@ -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); diff --git a/source4/smbd/process_thread.c b/source4/smbd/process_thread.c index 540d956420..597cf587f1 100644 --- a/source4/smbd/process_thread.c +++ b/source4/smbd/process_thread.c @@ -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)); diff --git a/source4/smbd/service_stream.c b/source4/smbd/service_stream.c index 48eda46dc7..1240382944 100644 --- a/source4/smbd/service_stream.c +++ b/source4/smbd/service_stream.c @@ -79,7 +79,7 @@ void stream_terminate_connection(struct stream_connection *srv_conn, const char talloc_free(srv_conn->event.fde); srv_conn->event.fde = NULL; talloc_free(srv_conn); - model_ops->terminate(event_ctx, reason); + model_ops->terminate(event_ctx, srv_conn->lp_ctx, reason); } /** diff --git a/source4/smbd/service_task.c b/source4/smbd/service_task.c index 2274685059..9a2903e281 100644 --- a/source4/smbd/service_task.c +++ b/source4/smbd/service_task.c @@ -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); -- cgit From 5bbd73c0ff64ec5da337d327d4f6ed1de2132ed4 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 04:01:47 +0200 Subject: Remove two more uses of global loadparm by remember required details for secondary DCE/RPC connections. --- source4/librpc/rpc/dcerpc_secondary.c | 7 +++--- source4/librpc/rpc/dcerpc_sock.c | 40 +++++++++++++++++++++++------------ 2 files changed, 31 insertions(+), 16 deletions(-) diff --git a/source4/librpc/rpc/dcerpc_secondary.c b/source4/librpc/rpc/dcerpc_secondary.c index abc67ad38b..b4d5d05b61 100644 --- a/source4/librpc/rpc/dcerpc_secondary.c +++ b/source4/librpc/rpc/dcerpc_secondary.c @@ -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; diff --git a/source4/librpc/rpc/dcerpc_sock.c b/source4/librpc/rpc/dcerpc_sock.c index 7480beae33..1e2b4cde48 100644 --- a/source4/librpc/rpc/dcerpc_sock.c +++ b/source4/librpc/rpc/dcerpc_sock.c @@ -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; +} -- cgit From 4a1dabd8361c8480261d89b4ea39236ff0431897 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 04:22:24 +0200 Subject: wmi: Use cli_credentials. --- source4/lib/wmi/wmi.h | 2 +- source4/lib/wmi/wmicore.c | 14 +------------- 2 files changed, 2 insertions(+), 14 deletions(-) diff --git a/source4/lib/wmi/wmi.h b/source4/lib/wmi/wmi.h index 32543a8ca7..46c9b70cdb 100644 --- a/source4/lib/wmi/wmi.h +++ b/source4/lib/wmi/wmi.h @@ -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); diff --git a/source4/lib/wmi/wmicore.c b/source4/lib/wmi/wmicore.c index 49c1e03312..3ac6c89292 100644 --- a/source4/lib/wmi/wmicore.c +++ b/source4/lib/wmi/wmicore.c @@ -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); -- cgit From 2400b1fea2a07ad3972ee8133e37eaf2f91499d0 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 04:22:54 +0200 Subject: Fix segfault. --- source4/smbd/service_stream.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/smbd/service_stream.c b/source4/smbd/service_stream.c index 1240382944..ce5b6519a1 100644 --- a/source4/smbd/service_stream.c +++ b/source4/smbd/service_stream.c @@ -78,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; - talloc_free(srv_conn); model_ops->terminate(event_ctx, srv_conn->lp_ctx, reason); + talloc_free(srv_conn); } /** -- cgit From 454122ab091715edf02c26e0a408141c7374b693 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 06:05:05 +0200 Subject: make sure dcerpc is always initialized. --- pidl/lib/Parse/Pidl/Samba4/Python.pm | 10 ++++++++++ source4/librpc/rpc/dcerpc.c | 4 +--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/pidl/lib/Parse/Pidl/Samba4/Python.pm b/pidl/lib/Parse/Pidl/Samba4/Python.pm index 74cec5a827..fc64c35fca 100644 --- a/pidl/lib/Parse/Pidl/Samba4/Python.pm +++ b/pidl/lib/Parse/Pidl/Samba4/Python.pm @@ -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}); diff --git a/source4/librpc/rpc/dcerpc.c b/source4/librpc/rpc/dcerpc.c index 5bbcc5e91c..5cee9f27ad 100644 --- a/source4/librpc/rpc/dcerpc.c +++ b/source4/librpc/rpc/dcerpc.c @@ -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); -- cgit From 43aaa78fe6f032d8d79b558ea931e7e8240f6f9d Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 06:05:46 +0200 Subject: Update .gitignore for new pidl location. --- .gitignore | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index b87f786678..e585504ce5 100644 --- a/.gitignore +++ b/.gitignore @@ -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 -- cgit From ac5e69a999c4dcd337c5b8467aba3018df50126b Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 06:10:32 +0200 Subject: dcesrv: Remove use of global_loadparm. --- source4/rpc_server/service_rpc.c | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/source4/rpc_server/service_rpc.c b/source4/rpc_server/service_rpc.c index b68cec4c7d..2ef8591c32 100644 --- a/source4/rpc_server/service_rpc.c +++ b/source4/rpc_server/service_rpc.c @@ -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); } -- cgit From 3ff298c37be5daa015006fe5cede3980b26e570e Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 30 Sep 2008 06:43:32 +0200 Subject: s4:selftest: add "smb.signing" to anon signing tests metze --- source4/selftest/samba4_tests.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source4/selftest/samba4_tests.sh b/source4/selftest/samba4_tests.sh index 667b21975f..af8c3e94c1 100755 --- a/source4/selftest/samba4_tests.sh +++ b/source4/selftest/samba4_tests.sh @@ -328,9 +328,9 @@ for mech in \ name="smb.signing on with $signoptions" 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` -- cgit From abe0af4ab417086d413f02cadf7315a8f801a0f8 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 30 Sep 2008 04:59:24 +0200 Subject: dcerpc.idl: add DCERPC_PFC_OFFSET metze --- source4/librpc/idl/dcerpc.idl | 1 + 1 file changed, 1 insertion(+) diff --git a/source4/librpc/idl/dcerpc.idl b/source4/librpc/idl/dcerpc.idl index 1c6574b11b..a78329d990 100644 --- a/source4/librpc/idl/dcerpc.idl +++ b/source4/librpc/idl/dcerpc.idl @@ -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; -- cgit From eb1de4f0ed149dd2b348d756f091809d934309a1 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 30 Sep 2008 04:59:56 +0200 Subject: s4:librpc/rpc: correctly sign or seal rpc request with an object guid metze --- source4/librpc/rpc/dcerpc.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/source4/librpc/rpc/dcerpc.c b/source4/librpc/rpc/dcerpc.c index 5bbcc5e91c..c1e3e26ee9 100644 --- a/source4/librpc/rpc/dcerpc.c +++ b/source4/librpc/rpc/dcerpc.c @@ -334,6 +334,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 +368,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 +417,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 +430,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, -- cgit From 844b331d257b02c073cc0dc4a6e229e6b9645949 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 30 Sep 2008 05:01:19 +0200 Subject: s4:rpc_server: correctly handle dcerpc requests with object uuids metze --- source4/rpc_server/dcerpc_server.c | 8 ++++---- source4/rpc_server/dcesrv_auth.c | 10 ++++++++-- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/source4/rpc_server/dcerpc_server.c b/source4/rpc_server/dcerpc_server.c index e5f59d0cf9..893055d3b1 100644 --- a/source4/rpc_server/dcerpc_server.c +++ b/source4/rpc_server/dcerpc_server.c @@ -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); diff --git a/source4/rpc_server/dcesrv_auth.c b/source4/rpc_server/dcesrv_auth.c index 16bf4eb7ed..52d5631cfd 100644 --- a/source4/rpc_server/dcesrv_auth.c +++ b/source4/rpc_server/dcesrv_auth.c @@ -287,6 +287,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 +336,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 +352,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; -- cgit From 40e7769959e29eccf1f0f14142828c9d0b7880b6 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 30 Sep 2008 06:40:15 +0200 Subject: s4:torture/rpc: add RPC-OBJECTUUID This test shows that object uuids should be ignored if they're present in a dcerpc request. metze --- source4/torture/config.mk | 2 +- source4/torture/rpc/object_uuid.c | 87 +++++++++++++++++++++++++++++++++++++++ source4/torture/rpc/rpc.c | 1 + 3 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 source4/torture/rpc/object_uuid.c diff --git a/source4/torture/config.mk b/source4/torture/config.mk index 96da10b5df..211d09756d 100644 --- a/source4/torture/config.mk +++ b/source4/torture/config.mk @@ -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))) diff --git a/source4/torture/rpc/object_uuid.c b/source4/torture/rpc/object_uuid.c new file mode 100644 index 0000000000..5a77bd1c29 --- /dev/null +++ b/source4/torture/rpc/object_uuid.c @@ -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 . +*/ + +#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; +} diff --git a/source4/torture/rpc/rpc.c b/source4/torture/rpc/rpc.c index 85f7bde16c..c35f93e3f9 100644 --- a/source4/torture/rpc/rpc.c +++ b/source4/torture/rpc/rpc.c @@ -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)); -- cgit From 45645426c2ae541fc2c3a112cde5a7f1d857938b Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 30 Sep 2008 06:42:53 +0200 Subject: s4:selftest: make sure we test RPC-OBJECTUUID with seal metze --- source4/selftest/samba4_tests.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/selftest/samba4_tests.sh b/source4/selftest/samba4_tests.sh index af8c3e94c1..bfe386af69 100755 --- a/source4/selftest/samba4_tests.sh +++ b/source4/selftest/samba4_tests.sh @@ -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" -- cgit From 8104968004a3a7fcfe4febb9918ecbf37ba948ac Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Mon, 29 Sep 2008 21:59:04 -0700 Subject: return a more useful error message when no name resolution methods are available --- source4/libcli/resolve/resolve.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source4/libcli/resolve/resolve.c b/source4/libcli/resolve/resolve.c index d89b50e430..2b14591d68 100644 --- a/source4/libcli/resolve/resolve.c +++ b/source4/libcli/resolve/resolve.c @@ -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_HOST_UNREACHABLE); + return c; + } state->creq = setup_next_method(c); if (composite_nomem(state->creq, c)) return c; -- cgit From d87e9ba56b00962be6b797464e77619bc6f0ba2c Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Mon, 29 Sep 2008 21:59:50 -0700 Subject: setup the loadparm context for ldb in testjoin --- source4/torture/rpc/testjoin.c | 1 + 1 file changed, 1 insertion(+) diff --git a/source4/torture/rpc/testjoin.c b/source4/torture/rpc/testjoin.c index 21542e9b16..3408a1924c 100644 --- a/source4/torture/rpc/testjoin.c +++ b/source4/torture/rpc/testjoin.c @@ -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) { -- cgit From 8dd35fabbb4732cf601a93abbe0373fd53e661a1 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Wed, 24 Sep 2008 11:20:45 -0700 Subject: NetApp found that we never set the smb signing flags2. This was found during testing at the CIFS plugfest. No other client seems to honour or use this bit, but it is quite ligitimately required by the spec. Andrew Bartlett --- source4/smb_server/smb/request.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source4/smb_server/smb/request.c b/source4/smb_server/smb/request.c index c7fa2d7d8a..eb3e100b96 100644 --- a/source4/smb_server/smb/request.c +++ b/source4/smb_server/smb/request.c @@ -140,6 +140,10 @@ void smbsrv_setup_reply(struct smbsrv_request *req, uint_t wct, size_t buflen) flags2 |= FLAGS2_32_BIT_ERROR_CODES; } + if (req->smb_conn->signing.allow_smb_signing || req->smb_conn->signing.mandatory_signing) { + flags2 |= FLAGS2_SMB_SECURITY_SIGNATURES; + } + req->out.hdr = req->out.buffer + NBT_HDR_SIZE; req->out.vwv = req->out.hdr + HDR_VWV; req->out.wct = wct; -- cgit From 6ad78f01a5982666c83025a94ce4ff3729d5db6f Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Wed, 24 Sep 2008 12:53:10 -0700 Subject: Rename hdb_ldb to hdb_samba4 and load as a plugin into the kdc. This avoids one more custom patch to the Heimdal code, and provides a more standard way to produce hdb plugins in future. I've renamed from hdb_ldb to hdb_samba4 as it really is not generic ldb. Andrew Bartlett --- source4/heimdal/lib/hdb/hdb.c | 42 +- source4/heimdal/lib/hdb/hdb.h | 6 + source4/kdc/config.mk | 8 +- source4/kdc/hdb-ldb.c | 1550 ----------------------------------------- source4/kdc/hdb-samba4.c | 1550 +++++++++++++++++++++++++++++++++++++++++ source4/kdc/kdc.c | 17 +- 6 files changed, 1604 insertions(+), 1569 deletions(-) delete mode 100644 source4/kdc/hdb-ldb.c create mode 100644 source4/kdc/hdb-samba4.c diff --git a/source4/heimdal/lib/hdb/hdb.c b/source4/heimdal/lib/hdb/hdb.c index 3fddabb2d0..19c170767d 100644 --- a/source4/heimdal/lib/hdb/hdb.c +++ b/source4/heimdal/lib/hdb/hdb.c @@ -31,34 +31,27 @@ * SUCH DAMAGE. */ +#include "krb5.h" +#include "krb5_locl.h" #include "hdb_locl.h" - RCSID("$Id$"); #ifdef HAVE_DLFCN_H #include #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); diff --git a/source4/heimdal/lib/hdb/hdb.h b/source4/heimdal/lib/hdb/hdb.h index bc1b744015..5c2097ea59 100644 --- a/source4/heimdal/lib/hdb/hdb.h +++ b/source4/heimdal/lib/hdb/hdb.h @@ -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 #endif /* __HDB_H__ */ diff --git a/source4/kdc/config.mk b/source4/kdc/config.mk index b3e5bfdb92..dfd2879bd6 100644 --- a/source4/kdc/config.mk +++ b/source4/kdc/config.mk @@ -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))) diff --git a/source4/kdc/hdb-ldb.c b/source4/kdc/hdb-ldb.c deleted file mode 100644 index 4fde75cf70..0000000000 --- a/source4/kdc/hdb-ldb.c +++ /dev/null @@ -1,1550 +0,0 @@ -/* - * Copyright (c) 1999-2001, 2003, PADL Software Pty Ltd. - * Copyright (c) 2004, Andrew Bartlett . - * Copyright (c) 2004, Stefan Metzmacher - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * 3. Neither the name of PADL Software nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#include "includes.h" -#include "system/time.h" -#include "dsdb/common/flags.h" -#include "lib/ldb/include/ldb.h" -#include "lib/ldb/include/ldb_errors.h" -#include "librpc/gen_ndr/netlogon.h" -#include "auth/auth.h" -#include "auth/credentials/credentials.h" -#include "auth/auth_sam.h" -#include "util/util_ldb.h" -#include "dsdb/samdb/samdb.h" -#include "librpc/ndr/libndr.h" -#include "librpc/gen_ndr/ndr_drsblobs.h" -#include "librpc/gen_ndr/lsa.h" -#include "libcli/auth/libcli_auth.h" -#include "param/param.h" -#include "events/events.h" -#include "kdc/kdc.h" -#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 }; - -enum trust_direction { - UNKNOWN = 0, - INBOUND = LSA_TRUST_DIRECTION_INBOUND, - OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND -}; - -static const char *realm_ref_attrs[] = { - "nCName", - "dnsRoot", - NULL -}; - -static const char *trust_attrs[] = { - "trustPartner", - "trustAuthIncoming", - "trustAuthOutgoing", - "whenCreated", - "msDS-SupportedEncryptionTypes", - "trustAttributes", - "trustDirection", - "trustType", - NULL -}; - -static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val) -{ - const char *tmp; - const char *gentime; - struct tm tm; - - gentime = ldb_msg_find_attr_as_string(msg, attr, NULL); - if (!gentime) - return default_val; - - tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm); - if (tmp == NULL) { - return default_val; - } - - return timegm(&tm); -} - -static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum hdb_ldb_ent_type ent_type) -{ - HDBFlags flags = int2HDBFlags(0); - - /* we don't allow kadmin deletes */ - flags.immutable = 1; - - /* mark the principal as invalid to start with */ - flags.invalid = 1; - - flags.renewable = 1; - - /* All accounts are servers, but this may be disabled again in the caller */ - flags.server = 1; - - /* 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) { - 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) { - 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) { - 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) { - flags.client = 1; - } - flags.invalid = 0; - } - - /* Not permitted to act as a client if disabled */ - if (userAccountControl & UF_ACCOUNTDISABLE) { - flags.client = 0; - } - if (userAccountControl & UF_LOCKOUT) { - flags.invalid = 1; - } -/* - if (userAccountControl & UF_PASSWORD_NOTREQD) { - flags.invalid = 1; - } -*/ -/* - UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent -*/ - if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) { - flags.invalid = 1; - } - -/* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in LDB_message2entry() */ - -/* - if (userAccountControl & UF_MNS_LOGON_ACCOUNT) { - flags.invalid = 1; - } -*/ - if (userAccountControl & UF_SMARTCARD_REQUIRED) { - flags.require_hwauth = 1; - } - if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) { - flags.ok_as_delegate = 1; - } - if (!(userAccountControl & UF_NOT_DELEGATED)) { - flags.forwardable = 1; - flags.proxiable = 1; - } - - if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) { - flags.require_preauth = 0; - } else { - flags.require_preauth = 1; - - } - return flags; -} - -static int hdb_ldb_destructor(struct hdb_ldb_private *private) -{ - hdb_entry_ex *entry_ex = private->entry_ex; - free_hdb_entry(&entry_ex->entry); - return 0; -} - -static void hdb_ldb_free_entry(krb5_context context, hdb_entry_ex *entry_ex) -{ - talloc_free(entry_ex->ctx); -} - -static krb5_error_code LDB_message2entry_keys(krb5_context context, - struct smb_iconv_convenience *iconv_convenience, - TALLOC_CTX *mem_ctx, - struct ldb_message *msg, - unsigned int userAccountControl, - hdb_entry_ex *entry_ex) -{ - krb5_error_code ret = 0; - enum ndr_err_code ndr_err; - struct samr_Password *hash; - const struct ldb_val *sc_val; - struct supplementalCredentialsBlob scb; - struct supplementalCredentialsPackage *scpk = NULL; - bool newer_keys = false; - struct package_PrimaryKerberosBlob _pkb; - struct package_PrimaryKerberosCtr3 *pkb3 = NULL; - struct package_PrimaryKerberosCtr4 *pkb4 = NULL; - uint32_t i; - uint32_t allocated_keys = 0; - - entry_ex->entry.keys.val = NULL; - entry_ex->entry.keys.len = 0; - - entry_ex->entry.kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0); - - /* Get keys from the db */ - - hash = samdb_result_hash(mem_ctx, msg, "unicodePwd"); - sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials"); - - /* unicodePwd for enctype 0x17 (23) if present */ - if (hash) { - allocated_keys++; - } - - /* supplementalCredentials if present */ - if (sc_val) { - ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, iconv_convenience, &scb, - (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob); - if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - dump_data(0, sc_val->data, sc_val->length); - ret = EINVAL; - goto out; - } - - if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) { - NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb); - ret = EINVAL; - goto out; - } - - for (i=0; i < scb.sub.num_packages; i++) { - if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) { - scpk = &scb.sub.packages[i]; - if (!scpk->data || !scpk->data[0]) { - scpk = NULL; - continue; - } - newer_keys = true; - break; - } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) { - scpk = &scb.sub.packages[i]; - if (!scpk->data || !scpk->data[0]) { - scpk = NULL; - } - /* - * we don't break here in hope to find - * a Kerberos-Newer-Keys package - */ - } - } - } - /* - * Primary:Kerberos-Newer-Keys or Primary:Kerberos element - * of supplementalCredentials - */ - if (scpk) { - DATA_BLOB blob; - - blob = strhex_to_data_blob(scpk->data); - if (!blob.data) { - ret = ENOMEM; - goto out; - } - talloc_steal(mem_ctx, blob.data); - - /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */ - ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, iconv_convenience, &_pkb, - (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob); - if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { - krb5_set_error_string(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob"); - krb5_warnx(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob"); - ret = EINVAL; - goto out; - } - - if (newer_keys && _pkb.version != 4) { - krb5_set_error_string(context, "LDB_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4"); - krb5_warnx(context, "LDB_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4"); - ret = EINVAL; - goto out; - } - - if (!newer_keys && _pkb.version != 3) { - krb5_set_error_string(context, "LDB_message2entry_keys: could not parse Primary:Kerberos not version 3"); - krb5_warnx(context, "LDB_message2entry_keys: could not parse Primary:Kerberos not version 3"); - ret = EINVAL; - goto out; - } - - if (_pkb.version == 4) { - pkb4 = &_pkb.ctr.ctr4; - allocated_keys += pkb4->num_keys; - } else if (_pkb.version == 3) { - pkb3 = &_pkb.ctr.ctr3; - allocated_keys += pkb3->num_keys; - } - } - - if (allocated_keys == 0) { - /* oh, no password. Apparently (comment in - * hdb-ldap.c) this violates the ASN.1, but this - * allows an entry with no keys (yet). */ - return 0; - } - - /* allocate space to decode into */ - entry_ex->entry.keys.len = 0; - entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key)); - if (entry_ex->entry.keys.val == NULL) { - ret = ENOMEM; - goto out; - } - - if (hash && !(userAccountControl & UF_USE_DES_KEY_ONLY)) { - Key key; - - key.mkvno = 0; - key.salt = NULL; /* No salt for this enc type */ - - ret = krb5_keyblock_init(context, - ENCTYPE_ARCFOUR_HMAC_MD5, - hash->hash, sizeof(hash->hash), - &key.key); - if (ret) { - goto out; - } - - entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key; - entry_ex->entry.keys.len++; - } - - if (pkb4) { - for (i=0; i < pkb4->num_keys; i++) { - bool use = true; - Key key; - - if (!pkb4->keys[i].value) continue; - - if (userAccountControl & UF_USE_DES_KEY_ONLY) { - switch (pkb4->keys[i].keytype) { - case ENCTYPE_DES_CBC_CRC: - case ENCTYPE_DES_CBC_MD5: - break; - default: - use = false; - break; - } - } - - if (!use) continue; - - key.mkvno = 0; - key.salt = NULL; - - if (pkb4->salt.string) { - DATA_BLOB salt; - - salt = data_blob_string_const(pkb4->salt.string); - - key.salt = calloc(1, sizeof(*key.salt)); - if (key.salt == NULL) { - ret = ENOMEM; - goto out; - } - - key.salt->type = hdb_pw_salt; - - ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length); - if (ret) { - free(key.salt); - key.salt = NULL; - goto out; - } - } - - /* TODO: maybe pass the iteration_count somehow... */ - - ret = krb5_keyblock_init(context, - pkb4->keys[i].keytype, - pkb4->keys[i].value->data, - pkb4->keys[i].value->length, - &key.key); - if (ret) { - if (key.salt) { - free_Salt(key.salt); - free(key.salt); - key.salt = NULL; - } - goto out; - } - - entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key; - entry_ex->entry.keys.len++; - } - } else if (pkb3) { - for (i=0; i < pkb3->num_keys; i++) { - bool use = true; - Key key; - - if (!pkb3->keys[i].value) continue; - - if (userAccountControl & UF_USE_DES_KEY_ONLY) { - switch (pkb3->keys[i].keytype) { - case ENCTYPE_DES_CBC_CRC: - case ENCTYPE_DES_CBC_MD5: - break; - default: - use = false; - break; - } - } - - if (!use) continue; - - key.mkvno = 0; - key.salt = NULL; - - if (pkb3->salt.string) { - DATA_BLOB salt; - - salt = data_blob_string_const(pkb3->salt.string); - - key.salt = calloc(1, sizeof(*key.salt)); - if (key.salt == NULL) { - ret = ENOMEM; - goto out; - } - - key.salt->type = hdb_pw_salt; - - ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length); - if (ret) { - free(key.salt); - key.salt = NULL; - goto out; - } - } - - ret = krb5_keyblock_init(context, - pkb3->keys[i].keytype, - pkb3->keys[i].value->data, - pkb3->keys[i].value->length, - &key.key); - if (ret) { - if (key.salt) { - free_Salt(key.salt); - free(key.salt); - key.salt = NULL; - } - goto out; - } - - entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key; - entry_ex->entry.keys.len++; - } - } - -out: - if (ret != 0) { - entry_ex->entry.keys.len = 0; - } - if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) { - free(entry_ex->entry.keys.val); - entry_ex->entry.keys.val = NULL; - } - return ret; -} - -/* - * Construct an hdb_entry from a directory entry. - */ -static krb5_error_code LDB_message2entry(krb5_context context, HDB *db, - TALLOC_CTX *mem_ctx, krb5_const_principal principal, - enum hdb_ldb_ent_type ent_type, - struct ldb_message *msg, - struct ldb_message *realm_ref_msg, - hdb_entry_ex *entry_ex) -{ - unsigned int userAccountControl; - int i; - krb5_error_code ret = 0; - krb5_boolean is_computer = FALSE; - const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg, "dnsRoot", NULL); - char *realm = strupper_talloc(mem_ctx, dnsdomain); - struct loadparm_context *lp_ctx = ldb_get_opaque((struct ldb_context *)db->hdb_db, "loadparm"); - struct ldb_dn *domain_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, - mem_ctx, - realm_ref_msg, - "nCName", - ldb_dn_new(mem_ctx, (struct ldb_context *)db->hdb_db, NULL)); - - struct hdb_ldb_private *private; - NTTIME acct_expiry; - - struct ldb_message_element *objectclasses; - struct ldb_val computer_val; - computer_val.data = discard_const_p(uint8_t,"computer"); - computer_val.length = strlen((const char *)computer_val.data); - - objectclasses = ldb_msg_find_element(msg, "objectClass"); - - if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) { - is_computer = TRUE; - } - - memset(entry_ex, 0, sizeof(*entry_ex)); - - if (!realm) { - krb5_set_error_string(context, "talloc_strdup: out of memory"); - ret = ENOMEM; - goto out; - } - - private = talloc(mem_ctx, struct hdb_ldb_private); - if (!private) { - ret = ENOMEM; - goto out; - } - - private->entry_ex = entry_ex; - private->iconv_convenience = lp_iconv_convenience(lp_ctx); - private->netbios_name = lp_netbios_name(lp_ctx); - - talloc_set_destructor(private, hdb_ldb_destructor); - - entry_ex->ctx = private; - entry_ex->free_entry = hdb_ldb_free_entry; - - userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0); - - - entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal))); - if (ent_type == HDB_LDB_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"); - ret = ENOENT; - goto out; - } - samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL); - krb5_make_principal(context, &entry_ex->entry.principal, realm, samAccountName, NULL); - } else { - char *strdup_realm; - ret = copy_Principal(principal, entry_ex->entry.principal); - if (ret) { - krb5_clear_error_string(context); - goto out; - } - - /* While we have copied the client principal, tests - * show that Win2k3 returns the 'corrected' realm, not - * the client-specified realm. This code attempts to - * replace the client principal's realm with the one - * we determine from our records */ - - /* this has to be with malloc() */ - strdup_realm = strdup(realm); - if (!strdup_realm) { - ret = ENOMEM; - krb5_clear_error_string(context); - goto out; - } - free(*krb5_princ_realm(context, entry_ex->entry.principal)); - krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm); - } - - entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type); - - if (ent_type == HDB_LDB_ENT_TYPE_KRBTGT) { - entry_ex->entry.flags.invalid = 0; - entry_ex->entry.flags.server = 1; - entry_ex->entry.flags.forwardable = 1; - entry_ex->entry.flags.ok_as_delegate = 1; - } - - if (lp_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) { - if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) { - entry_ex->entry.flags.server = 0; - } - } - - /* use 'whenCreated' */ - entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0); - /* use '???' */ - entry_ex->entry.created_by.principal = NULL; - - entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event)); - if (entry_ex->entry.modified_by == NULL) { - krb5_set_error_string(context, "malloc: out of memory"); - ret = ENOMEM; - goto out; - } - - /* use 'whenChanged' */ - entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0); - /* use '???' */ - entry_ex->entry.modified_by->principal = NULL; - - entry_ex->entry.valid_start = NULL; - - acct_expiry = samdb_result_account_expires(msg); - if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) { - entry_ex->entry.valid_end = NULL; - } else { - entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end)); - if (entry_ex->entry.valid_end == NULL) { - ret = ENOMEM; - goto out; - } - *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry); - } - - if (ent_type != HDB_LDB_ENT_TYPE_KRBTGT) { - NTTIME must_change_time - = samdb_result_force_password_change((struct ldb_context *)db->hdb_db, mem_ctx, - domain_dn, msg); - if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) { - entry_ex->entry.pw_end = NULL; - } else { - entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end)); - if (entry_ex->entry.pw_end == NULL) { - ret = ENOMEM; - goto out; - } - *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time); - } - } else { - entry_ex->entry.pw_end = NULL; - } - - entry_ex->entry.max_life = NULL; - - entry_ex->entry.max_renew = NULL; - - entry_ex->entry.generation = NULL; - - /* Get keys from the db */ - ret = LDB_message2entry_keys(context, private->iconv_convenience, private, msg, userAccountControl, entry_ex); - if (ret) { - /* Could be bougus data in the entry, or out of memory */ - goto out; - } - - entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes))); - if (entry_ex->entry.etypes == NULL) { - krb5_clear_error_string(context); - ret = ENOMEM; - goto out; - } - entry_ex->entry.etypes->len = entry_ex->entry.keys.len; - entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int)); - if (entry_ex->entry.etypes->val == NULL) { - krb5_clear_error_string(context); - ret = ENOMEM; - goto out; - } - for (i=0; i < entry_ex->entry.etypes->len; i++) { - entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype; - } - - - private->msg = talloc_steal(private, msg); - private->realm_ref_msg = talloc_steal(private, realm_ref_msg); - private->samdb = (struct ldb_context *)db->hdb_db; - -out: - if (ret != 0) { - /* This doesn't free ent itself, that is for the eventual caller to do */ - hdb_free_entry(context, entry_ex); - } else { - talloc_steal(db, entry_ex->ctx); - } - - return ret; -} - -/* - * Construct an hdb_entry from a directory entry. - */ -static krb5_error_code LDB_trust_message2entry(krb5_context context, HDB *db, - struct loadparm_context *lp_ctx, - TALLOC_CTX *mem_ctx, krb5_const_principal principal, - enum trust_direction direction, - struct ldb_message *msg, - hdb_entry_ex *entry_ex) -{ - - const char *dnsdomain; - char *realm; - char *strdup_realm; - DATA_BLOB password_utf16; - struct samr_Password password_hash; - const struct ldb_val *password_val; - struct trustAuthInOutBlob password_blob; - struct hdb_ldb_private *private; - - enum ndr_err_code ndr_err; - int i, ret, trust_direction_flags; - - private = talloc(mem_ctx, struct hdb_ldb_private); - if (!private) { - ret = ENOMEM; - goto out; - } - - private->entry_ex = entry_ex; - private->iconv_convenience = lp_iconv_convenience(lp_ctx); - private->netbios_name = lp_netbios_name(lp_ctx); - - talloc_set_destructor(private, hdb_ldb_destructor); - - entry_ex->ctx = private; - entry_ex->free_entry = hdb_ldb_free_entry; - - /* use 'whenCreated' */ - entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0); - /* use '???' */ - entry_ex->entry.created_by.principal = NULL; - - entry_ex->entry.valid_start = NULL; - - trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0); - - if (direction == INBOUND) { - realm = strupper_talloc(mem_ctx, lp_realm(lp_ctx)); - password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming"); - - } else { /* OUTBOUND */ - dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL); - realm = strupper_talloc(mem_ctx, dnsdomain); - password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing"); - } - - if (!password_val || !(trust_direction_flags & direction)) { - ret = ENOENT; - goto out; - } - - ndr_err = ndr_pull_struct_blob_all(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; - } - - 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, - password_blob.current->array[i].AuthInfo.clear.size); - /* In the future, generate all sorts of - * hashes, but for now we can't safely convert - * the random strings windows uses into - * utf8 */ - - /* but as it is utf16 already, we can get the NT password/arcfour-hmac-md5 key */ - mdfour(password_hash.hash, password_utf16.data, password_utf16.length); - break; - } else if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) { - password_hash = password_blob.current->array[i].AuthInfo.nt4owf.password; - break; - } - } - entry_ex->entry.keys.len = 0; - entry_ex->entry.keys.val = NULL; - - if (i < password_blob.count) { - Key key; - /* Must have found a cleartext or MD4 password */ - entry_ex->entry.keys.val = calloc(1, sizeof(Key)); - - key.mkvno = 0; - key.salt = NULL; /* No salt for this enc type */ - - if (entry_ex->entry.keys.val == NULL) { - ret = ENOMEM; - goto out; - } - - ret = krb5_keyblock_init(context, - ENCTYPE_ARCFOUR_HMAC_MD5, - password_hash.hash, sizeof(password_hash.hash), - &key.key); - - entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key; - entry_ex->entry.keys.len++; - } - - ret = copy_Principal(principal, entry_ex->entry.principal); - if (ret) { - krb5_clear_error_string(context); - goto out; - } - - /* While we have copied the client principal, tests - * show that Win2k3 returns the 'corrected' realm, not - * the client-specified realm. This code attempts to - * replace the client principal's realm with the one - * we determine from our records */ - - /* this has to be with malloc() */ - strdup_realm = strdup(realm); - if (!strdup_realm) { - ret = ENOMEM; - krb5_clear_error_string(context); - goto out; - } - free(*krb5_princ_realm(context, entry_ex->entry.principal)); - krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm); - - entry_ex->entry.flags = int2HDBFlags(0); - entry_ex->entry.flags.immutable = 1; - entry_ex->entry.flags.invalid = 0; - entry_ex->entry.flags.server = 1; - entry_ex->entry.flags.require_preauth = 1; - - entry_ex->entry.pw_end = NULL; - - entry_ex->entry.max_life = NULL; - - entry_ex->entry.max_renew = NULL; - - entry_ex->entry.generation = NULL; - - entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes))); - if (entry_ex->entry.etypes == NULL) { - krb5_clear_error_string(context); - ret = ENOMEM; - goto out; - } - entry_ex->entry.etypes->len = entry_ex->entry.keys.len; - entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int)); - if (entry_ex->entry.etypes->val == NULL) { - krb5_clear_error_string(context); - ret = ENOMEM; - goto out; - } - for (i=0; i < entry_ex->entry.etypes->len; i++) { - entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype; - } - - - private->msg = talloc_steal(private, msg); - private->realm_ref_msg = NULL; - private->samdb = (struct ldb_context *)db->hdb_db; - -out: - if (ret != 0) { - /* This doesn't free ent itself, that is for the eventual caller to do */ - hdb_free_entry(context, entry_ex); - } else { - talloc_steal(db, entry_ex->ctx); - } - - return ret; - -} - -static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_context *ldb_ctx, - TALLOC_CTX *mem_ctx, - krb5_const_principal principal, - enum hdb_ldb_ent_type ent_type, - struct ldb_dn *realm_dn, - struct ldb_message ***pmsg) -{ - krb5_error_code ret; - int lret; - char *filter = NULL; - const char * const *princ_attrs = user_attrs; - - char *short_princ; - char *short_princ_talloc; - - struct ldb_result *res = NULL; - - ret = krb5_unparse_name_flags(context, principal, KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ); - - if (ret != 0) { - krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal"); - krb5_warnx(context, "LDB_lookup_principal: could not parse principal"); - return ret; - } - - short_princ_talloc = talloc_strdup(mem_ctx, short_princ); - free(short_princ); - if (!short_princ_talloc) { - krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!"); - return ENOMEM; - } - - switch (ent_type) { - case HDB_LDB_ENT_TYPE_CLIENT: - case HDB_LDB_ENT_TYPE_TRUST: - case HDB_LDB_ENT_TYPE_ANY: - /* Can't happen */ - return EINVAL; - case HDB_LDB_ENT_TYPE_KRBTGT: - filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", - KRB5_TGS_NAME); - break; - case HDB_LDB_ENT_TYPE_SERVER: - filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", - short_princ_talloc); - break; - } - - if (!filter) { - krb5_set_error_string(context, "talloc_asprintf: out of memory"); - return ENOMEM; - } - - lret = ldb_search(ldb_ctx, mem_ctx, &res, realm_dn, - LDB_SCOPE_SUBTREE, princ_attrs, "%s", filter); - if (lret != LDB_SUCCESS) { - DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx))); - return HDB_ERR_NOENTRY; - } else if (res->count == 0 || res->count > 1) { - DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count)); - talloc_free(res); - return HDB_ERR_NOENTRY; - } - talloc_steal(mem_ctx, res->msgs); - *pmsg = res->msgs; - talloc_free(res); - return 0; -} - -static krb5_error_code LDB_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx, - TALLOC_CTX *mem_ctx, - const char *realm, - struct ldb_dn *realm_dn, - struct ldb_message ***pmsg) -{ - int lret; - char *filter = NULL; - const char * const *attrs = trust_attrs; - - struct ldb_result *res = NULL; - filter = talloc_asprintf(mem_ctx, "(&(objectClass=trustedDomain)(|(flatname=%s)(trustPartner=%s)))", realm, realm); - - if (!filter) { - krb5_set_error_string(context, "talloc_asprintf: out of memory"); - return ENOMEM; - } - - lret = ldb_search(ldb_ctx, mem_ctx, &res, - ldb_get_default_basedn(ldb_ctx), - LDB_SCOPE_SUBTREE, attrs, "%s", filter); - if (lret != LDB_SUCCESS) { - DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx))); - return HDB_ERR_NOENTRY; - } else if (res->count == 0 || res->count > 1) { - DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count)); - talloc_free(res); - return HDB_ERR_NOENTRY; - } - talloc_steal(mem_ctx, res->msgs); - *pmsg = res->msgs; - talloc_free(res); - return 0; -} - -static krb5_error_code LDB_lookup_realm(krb5_context context, struct ldb_context *ldb_ctx, - TALLOC_CTX *mem_ctx, - const char *realm, - struct ldb_message ***pmsg) -{ - int ret; - struct ldb_result *cross_ref_res; - struct ldb_dn *partitions_basedn = samdb_partitions_dn(ldb_ctx, mem_ctx); - - ret = ldb_search(ldb_ctx, mem_ctx, &cross_ref_res, - partitions_basedn, LDB_SCOPE_SUBTREE, realm_ref_attrs, - "(&(&(|(&(dnsRoot=%s)(nETBIOSName=*))(nETBIOSName=%s))(objectclass=crossRef))(ncName=*))", - realm, realm); - - if (ret != LDB_SUCCESS) { - DEBUG(3, ("Failed to search to lookup realm(%s): %s\n", realm, ldb_errstring(ldb_ctx))); - talloc_free(cross_ref_res); - return HDB_ERR_NOENTRY; - } else if (cross_ref_res->count == 0 || cross_ref_res->count > 1) { - DEBUG(3, ("Failed find a single entry for realm %s: got %d\n", realm, cross_ref_res->count)); - talloc_free(cross_ref_res); - return HDB_ERR_NOENTRY; - } - - if (pmsg) { - *pmsg = cross_ref_res->msgs; - talloc_steal(mem_ctx, cross_ref_res->msgs); - } - talloc_free(cross_ref_res); - - return 0; -} - - -static krb5_error_code LDB_open(krb5_context context, HDB *db, int flags, mode_t mode) -{ - if (db->hdb_master_key_set) { - krb5_warnx(context, "LDB_open: use of a master key incompatible with LDB\n"); - krb5_set_error_string(context, "LDB_open: use of a master key incompatible with LDB\n"); - return HDB_ERR_NOENTRY; - } - - return 0; -} - -static krb5_error_code LDB_close(krb5_context context, HDB *db) -{ - return 0; -} - -static krb5_error_code LDB_lock(krb5_context context, HDB *db, int operation) -{ - return 0; -} - -static krb5_error_code LDB_unlock(krb5_context context, HDB *db) -{ - return 0; -} - -static krb5_error_code LDB_rename(krb5_context context, HDB *db, const char *new_name) -{ - return HDB_ERR_DB_INUSE; -} - -static krb5_error_code LDB_fetch_client(krb5_context context, HDB *db, - TALLOC_CTX *mem_ctx, - krb5_const_principal principal, - unsigned flags, - hdb_entry_ex *entry_ex) { - NTSTATUS nt_status; - char *principal_string; - krb5_error_code ret; - struct ldb_message **msg = NULL; - struct ldb_message **realm_ref_msg = NULL; - - ret = krb5_unparse_name(context, principal, &principal_string); - - if (ret != 0) { - return ret; - } - - nt_status = sam_get_results_principal((struct ldb_context *)db->hdb_db, - mem_ctx, principal_string, - &msg, &realm_ref_msg); - free(principal_string); - if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) { - return HDB_ERR_NOENTRY; - } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) { - return ENOMEM; - } else if (!NT_STATUS_IS_OK(nt_status)) { - return EINVAL; - } - - ret = LDB_message2entry(context, db, mem_ctx, - principal, HDB_LDB_ENT_TYPE_CLIENT, - msg[0], realm_ref_msg[0], entry_ex); - return ret; -} - -static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db, - TALLOC_CTX *mem_ctx, - krb5_const_principal principal, - unsigned flags, - hdb_entry_ex *entry_ex) -{ - krb5_error_code ret; - struct ldb_message **msg = NULL; - struct ldb_message **realm_ref_msg_1 = NULL; - struct ldb_message **realm_ref_msg_2 = NULL; - struct ldb_dn *realm_dn; - const char *realm; - - krb5_principal alloc_principal = NULL; - if (principal->name.name_string.len != 2 - || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) { - /* Not a krbtgt */ - return HDB_ERR_NOENTRY; - } - - /* krbtgt case. Either us or a trusted realm */ - - if ((LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, - mem_ctx, principal->realm, &realm_ref_msg_1) == 0) - && (LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, - mem_ctx, principal->name.name_string.val[1], &realm_ref_msg_2) == 0) - && (ldb_dn_compare(realm_ref_msg_1[0]->dn, realm_ref_msg_1[0]->dn) == 0)) { - /* us */ - /* Cludge, cludge cludge. If the realm part of krbtgt/realm, - * is in our db, then direct the caller at our primary - * krbtgt */ - - const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg_1[0], "dnsRoot", NULL); - char *realm_fixed = strupper_talloc(mem_ctx, dnsdomain); - if (!realm_fixed) { - krb5_set_error_string(context, "strupper_talloc: out of memory"); - return ENOMEM; - } - - ret = krb5_copy_principal(context, principal, &alloc_principal); - if (ret) { - return ret; - } - - free(alloc_principal->name.name_string.val[1]); - alloc_principal->name.name_string.val[1] = strdup(realm_fixed); - talloc_free(realm_fixed); - if (!alloc_principal->name.name_string.val[1]) { - krb5_set_error_string(context, "LDB_fetch: strdup() failed!"); - return ENOMEM; - } - principal = alloc_principal; - realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg_1[0], "nCName", NULL); - - ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, - mem_ctx, - principal, HDB_LDB_ENT_TYPE_KRBTGT, realm_dn, &msg); - - if (ret != 0) { - krb5_warnx(context, "LDB_fetch: could not find principal in DB"); - krb5_set_error_string(context, "LDB_fetch: could not find principal in DB"); - return ret; - } - - ret = LDB_message2entry(context, db, mem_ctx, - principal, HDB_LDB_ENT_TYPE_KRBTGT, - msg[0], realm_ref_msg_1[0], entry_ex); - if (ret != 0) { - krb5_warnx(context, "LDB_fetch: message2entry failed"); - } - return ret; - - } else { - enum trust_direction direction = UNKNOWN; - - struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(db->hdb_db, "loadparm"), struct loadparm_context); - /* Either an inbound or outbound trust */ - - if (strcasecmp(lp_realm(lp_ctx), principal->realm) == 0) { - /* look for inbound trust */ - direction = INBOUND; - realm = principal->name.name_string.val[1]; - } - - if (strcasecmp(lp_realm(lp_ctx), principal->name.name_string.val[1]) == 0) { - /* look for outbound trust */ - direction = OUTBOUND; - realm = principal->realm; - } - - /* Trusted domains are under CN=system */ - - ret = LDB_lookup_trust(context, (struct ldb_context *)db->hdb_db, - mem_ctx, - realm, realm_dn, &msg); - - if (ret != 0) { - krb5_warnx(context, "LDB_fetch: could not find principal in DB"); - krb5_set_error_string(context, "LDB_fetch: could not find principal in DB"); - return ret; - } - - ret = LDB_trust_message2entry(context, db, lp_ctx, mem_ctx, - principal, direction, - msg[0], entry_ex); - if (ret != 0) { - krb5_warnx(context, "LDB_fetch: message2entry failed"); - } - return ret; - - - /* we should lookup trusted domains */ - return HDB_ERR_NOENTRY; - } - -} - -static krb5_error_code LDB_fetch_server(krb5_context context, HDB *db, - TALLOC_CTX *mem_ctx, - krb5_const_principal principal, - unsigned flags, - hdb_entry_ex *entry_ex) -{ - krb5_error_code ret; - const char *realm; - struct ldb_message **msg = NULL; - struct ldb_message **realm_ref_msg = NULL; - struct ldb_dn *partitions_basedn = samdb_partitions_dn(db->hdb_db, mem_ctx); - if (principal->name.name_string.len >= 2) { - /* 'normal server' case */ - int ldb_ret; - NTSTATUS nt_status; - struct ldb_dn *user_dn, *domain_dn; - char *principal_string; - - ret = krb5_unparse_name_flags(context, principal, - KRB5_PRINCIPAL_UNPARSE_NO_REALM, - &principal_string); - if (ret != 0) { - return ret; - } - - /* At this point we may find the host is known to be - * in a different realm, so we should generate a - * referral instead */ - nt_status = crack_service_principal_name((struct ldb_context *)db->hdb_db, - mem_ctx, principal_string, - &user_dn, &domain_dn); - free(principal_string); - - if (!NT_STATUS_IS_OK(nt_status)) { - return HDB_ERR_NOENTRY; - } - - ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db, - mem_ctx, user_dn, &msg, user_attrs); - - if (ldb_ret != 1) { - return HDB_ERR_NOENTRY; - } - - ldb_ret = gendb_search((struct ldb_context *)db->hdb_db, - mem_ctx, partitions_basedn, &realm_ref_msg, realm_ref_attrs, - "ncName=%s", ldb_dn_get_linearized(domain_dn)); - - if (ldb_ret != 1) { - return HDB_ERR_NOENTRY; - } - - } else { - struct ldb_dn *realm_dn; - /* server as client principal case, but we must not lookup userPrincipalNames */ - - realm = krb5_principal_get_realm(context, principal); - - ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, - mem_ctx, realm, &realm_ref_msg); - if (ret != 0) { - return HDB_ERR_NOENTRY; - } - - realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL); - - ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, - mem_ctx, - principal, HDB_LDB_ENT_TYPE_SERVER, realm_dn, &msg); - - if (ret != 0) { - return ret; - } - } - - ret = LDB_message2entry(context, db, mem_ctx, - principal, HDB_LDB_ENT_TYPE_SERVER, - msg[0], realm_ref_msg[0], entry_ex); - if (ret != 0) { - krb5_warnx(context, "LDB_fetch: message2entry failed"); - } - - return ret; -} - -static krb5_error_code LDB_fetch(krb5_context context, HDB *db, - krb5_const_principal principal, - unsigned flags, - hdb_entry_ex *entry_ex) -{ - krb5_error_code ret = HDB_ERR_NOENTRY; - - TALLOC_CTX *mem_ctx = talloc_named(db, 0, "LDB_fetch context"); - - if (!mem_ctx) { - krb5_set_error_string(context, "LDB_fetch: talloc_named() failed!"); - return ENOMEM; - } - - if (flags & HDB_F_GET_CLIENT) { - ret = LDB_fetch_client(context, db, mem_ctx, principal, flags, entry_ex); - if (ret != HDB_ERR_NOENTRY) goto done; - } - if (flags & HDB_F_GET_SERVER) { - /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */ - ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex); - if (ret != HDB_ERR_NOENTRY) goto done; - - /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */ - ret = LDB_fetch_server(context, db, mem_ctx, principal, flags, entry_ex); - if (ret != HDB_ERR_NOENTRY) goto done; - } - if (flags & HDB_F_GET_KRBTGT) { - ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex); - if (ret != HDB_ERR_NOENTRY) goto done; - } - -done: - talloc_free(mem_ctx); - return ret; -} - -static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) -{ - return HDB_ERR_DB_INUSE; -} - -static krb5_error_code LDB_remove(krb5_context context, HDB *db, krb5_const_principal principal) -{ - return HDB_ERR_DB_INUSE; -} - -struct hdb_ldb_seq { - struct ldb_context *ctx; - int index; - int count; - struct ldb_message **msgs; - struct ldb_message **realm_ref_msgs; -}; - -static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) -{ - krb5_error_code ret; - struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc; - TALLOC_CTX *mem_ctx; - hdb_entry_ex entry_ex; - memset(&entry_ex, '\0', sizeof(entry_ex)); - - if (!priv) { - return HDB_ERR_NOENTRY; - } - - mem_ctx = talloc_named(priv, 0, "LDB_seq context"); - - if (!mem_ctx) { - krb5_set_error_string(context, "LDB_seq: talloc_named() failed!"); - return ENOMEM; - } - - if (priv->index < priv->count) { - ret = LDB_message2entry(context, db, mem_ctx, - NULL, HDB_LDB_ENT_TYPE_ANY, - priv->msgs[priv->index++], - priv->realm_ref_msgs[0], entry); - } else { - ret = HDB_ERR_NOENTRY; - } - - if (ret != 0) { - talloc_free(priv); - db->hdb_dbc = NULL; - } else { - talloc_free(mem_ctx); - } - - return ret; -} - -static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags, - hdb_entry_ex *entry) -{ - struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db; - struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc; - char *realm; - struct ldb_dn *realm_dn = NULL; - struct ldb_result *res = NULL; - struct ldb_message **realm_ref_msgs = NULL; - krb5_error_code ret; - TALLOC_CTX *mem_ctx; - int lret; - - if (priv) { - talloc_free(priv); - db->hdb_dbc = NULL; - } - - priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq); - if (!priv) { - krb5_set_error_string(context, "talloc: out of memory"); - return ENOMEM; - } - - priv->ctx = ldb_ctx; - priv->index = 0; - priv->msgs = NULL; - priv->realm_ref_msgs = NULL; - priv->count = 0; - - mem_ctx = talloc_named(priv, 0, "LDB_firstkey context"); - - if (!mem_ctx) { - krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!"); - return ENOMEM; - } - - ret = krb5_get_default_realm(context, &realm); - if (ret != 0) { - talloc_free(priv); - return ret; - } - - ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, - mem_ctx, realm, &realm_ref_msgs); - - free(realm); - - if (ret != 0) { - talloc_free(priv); - krb5_warnx(context, "LDB_firstkey: could not find realm\n"); - return HDB_ERR_NOENTRY; - } - - realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msgs[0], "nCName", NULL); - - priv->realm_ref_msgs = talloc_steal(priv, realm_ref_msgs); - - lret = ldb_search(ldb_ctx, priv, &res, - realm_dn, LDB_SCOPE_SUBTREE, user_attrs, - "(objectClass=user)"); - - if (lret != LDB_SUCCESS) { - talloc_free(priv); - return HDB_ERR_NOENTRY; - } - - priv->count = res->count; - priv->msgs = talloc_steal(priv, res->msgs); - talloc_free(res); - - db->hdb_dbc = priv; - - ret = LDB_seq(context, db, flags, entry); - - if (ret != 0) { - talloc_free(priv); - db->hdb_dbc = NULL; - } else { - talloc_free(mem_ctx); - } - return ret; -} - -static krb5_error_code LDB_nextkey(krb5_context context, HDB *db, unsigned flags, - hdb_entry_ex *entry) -{ - return LDB_seq(context, db, flags, entry); -} - -static krb5_error_code LDB_destroy(krb5_context context, HDB *db) -{ - talloc_free(db); - return 0; -} - -/* This interface is to be called by the KDC, which is expecting Samba - * calling conventions. It is also called by a wrapper - * (hdb_ldb_create) from the kpasswdd -> krb5 -> keytab_hdb -> hdb - * code */ - -NTSTATUS kdc_hdb_ldb_create(TALLOC_CTX *mem_ctx, - struct event_context *ev_ctx, - struct loadparm_context *lp_ctx, - krb5_context context, struct HDB **db, const char *arg) -{ - NTSTATUS nt_status; - struct auth_session_info *session_info; - *db = talloc(mem_ctx, HDB); - if (!*db) { - krb5_set_error_string(context, "malloc: out of memory"); - return NT_STATUS_NO_MEMORY; - } - - (*db)->hdb_master_key_set = 0; - (*db)->hdb_db = NULL; - - nt_status = auth_system_session_info(*db, lp_ctx, &session_info); - if (!NT_STATUS_IS_OK(nt_status)) { - return nt_status; - } - - /* The idea here is very simple. Using Kerberos to - * authenticate the KDC to the LDAP server is higly likely to - * be circular. - * - * In future we may set this up to use EXERNAL and SSL - * certificates, for now it will almost certainly be NTLMSSP - */ - - cli_credentials_set_kerberos_state(session_info->credentials, - CRED_DONT_USE_KERBEROS); - - /* Setup the link to LDB */ - (*db)->hdb_db = samdb_connect(*db, ev_ctx, lp_ctx, session_info); - if ((*db)->hdb_db == NULL) { - DEBUG(1, ("hdb_ldb_create: Cannot open samdb for KDC backend!")); - return NT_STATUS_CANT_ACCESS_DOMAIN_INFO; - } - - (*db)->hdb_dbc = NULL; - (*db)->hdb_open = LDB_open; - (*db)->hdb_close = LDB_close; - (*db)->hdb_fetch = LDB_fetch; - (*db)->hdb_store = LDB_store; - (*db)->hdb_remove = LDB_remove; - (*db)->hdb_firstkey = LDB_firstkey; - (*db)->hdb_nextkey = LDB_nextkey; - (*db)->hdb_lock = LDB_lock; - (*db)->hdb_unlock = LDB_unlock; - (*db)->hdb_rename = LDB_rename; - /* we don't implement these, as we are not a lockable database */ - (*db)->hdb__get = NULL; - (*db)->hdb__put = NULL; - /* kadmin should not be used for deletes - use other tools instead */ - (*db)->hdb__del = NULL; - (*db)->hdb_destroy = LDB_destroy; - - return NT_STATUS_OK; -} - -krb5_error_code hdb_ldb_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); - - if (NT_STATUS_IS_OK(nt_status)) { - return 0; - } - return EINVAL; -} diff --git a/source4/kdc/hdb-samba4.c b/source4/kdc/hdb-samba4.c new file mode 100644 index 0000000000..d7317f17d4 --- /dev/null +++ b/source4/kdc/hdb-samba4.c @@ -0,0 +1,1550 @@ +/* + * Copyright (c) 1999-2001, 2003, PADL Software Pty Ltd. + * Copyright (c) 2004, Andrew Bartlett . + * Copyright (c) 2004, Stefan Metzmacher + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of PADL Software nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include "includes.h" +#include "system/time.h" +#include "dsdb/common/flags.h" +#include "lib/ldb/include/ldb.h" +#include "lib/ldb/include/ldb_errors.h" +#include "librpc/gen_ndr/netlogon.h" +#include "auth/auth.h" +#include "auth/credentials/credentials.h" +#include "auth/auth_sam.h" +#include "util/util_ldb.h" +#include "dsdb/samdb/samdb.h" +#include "librpc/ndr/libndr.h" +#include "librpc/gen_ndr/ndr_drsblobs.h" +#include "librpc/gen_ndr/lsa.h" +#include "libcli/auth/libcli_auth.h" +#include "param/param.h" +#include "events/events.h" +#include "kdc/kdc.h" +#include "../lib/crypto/md4.h" + +enum hdb_ldb_ent_type +{ 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, + INBOUND = LSA_TRUST_DIRECTION_INBOUND, + OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND +}; + +static const char *realm_ref_attrs[] = { + "nCName", + "dnsRoot", + NULL +}; + +static const char *trust_attrs[] = { + "trustPartner", + "trustAuthIncoming", + "trustAuthOutgoing", + "whenCreated", + "msDS-SupportedEncryptionTypes", + "trustAttributes", + "trustDirection", + "trustType", + NULL +}; + +static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val) +{ + const char *tmp; + const char *gentime; + struct tm tm; + + gentime = ldb_msg_find_attr_as_string(msg, attr, NULL); + if (!gentime) + return default_val; + + tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm); + if (tmp == NULL) { + return default_val; + } + + return timegm(&tm); +} + +static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum hdb_ldb_ent_type ent_type) +{ + HDBFlags flags = int2HDBFlags(0); + + /* we don't allow kadmin deletes */ + flags.immutable = 1; + + /* mark the principal as invalid to start with */ + flags.invalid = 1; + + flags.renewable = 1; + + /* All accounts are servers, but this may be disabled again in the caller */ + flags.server = 1; + + /* Account types - clear the invalid bit if it turns out to be valid */ + if (userAccountControl & UF_NORMAL_ACCOUNT) { + 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_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_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_SAMBA4_ENT_TYPE_CLIENT || ent_type == HDB_SAMBA4_ENT_TYPE_ANY) { + flags.client = 1; + } + flags.invalid = 0; + } + + /* Not permitted to act as a client if disabled */ + if (userAccountControl & UF_ACCOUNTDISABLE) { + flags.client = 0; + } + if (userAccountControl & UF_LOCKOUT) { + flags.invalid = 1; + } +/* + if (userAccountControl & UF_PASSWORD_NOTREQD) { + flags.invalid = 1; + } +*/ +/* + UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent +*/ + if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) { + flags.invalid = 1; + } + +/* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in LDB_message2entry() */ + +/* + if (userAccountControl & UF_MNS_LOGON_ACCOUNT) { + flags.invalid = 1; + } +*/ + if (userAccountControl & UF_SMARTCARD_REQUIRED) { + flags.require_hwauth = 1; + } + if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) { + flags.ok_as_delegate = 1; + } + if (!(userAccountControl & UF_NOT_DELEGATED)) { + flags.forwardable = 1; + flags.proxiable = 1; + } + + if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) { + flags.require_preauth = 0; + } else { + flags.require_preauth = 1; + + } + return flags; +} + +static int hdb_ldb_destructor(struct hdb_ldb_private *private) +{ + hdb_entry_ex *entry_ex = private->entry_ex; + free_hdb_entry(&entry_ex->entry); + return 0; +} + +static void hdb_ldb_free_entry(krb5_context context, hdb_entry_ex *entry_ex) +{ + talloc_free(entry_ex->ctx); +} + +static krb5_error_code LDB_message2entry_keys(krb5_context context, + struct smb_iconv_convenience *iconv_convenience, + TALLOC_CTX *mem_ctx, + struct ldb_message *msg, + unsigned int userAccountControl, + hdb_entry_ex *entry_ex) +{ + krb5_error_code ret = 0; + enum ndr_err_code ndr_err; + struct samr_Password *hash; + const struct ldb_val *sc_val; + struct supplementalCredentialsBlob scb; + struct supplementalCredentialsPackage *scpk = NULL; + bool newer_keys = false; + struct package_PrimaryKerberosBlob _pkb; + struct package_PrimaryKerberosCtr3 *pkb3 = NULL; + struct package_PrimaryKerberosCtr4 *pkb4 = NULL; + uint32_t i; + uint32_t allocated_keys = 0; + + entry_ex->entry.keys.val = NULL; + entry_ex->entry.keys.len = 0; + + entry_ex->entry.kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0); + + /* Get keys from the db */ + + hash = samdb_result_hash(mem_ctx, msg, "unicodePwd"); + sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials"); + + /* unicodePwd for enctype 0x17 (23) if present */ + if (hash) { + allocated_keys++; + } + + /* supplementalCredentials if present */ + if (sc_val) { + ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, iconv_convenience, &scb, + (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + dump_data(0, sc_val->data, sc_val->length); + ret = EINVAL; + goto out; + } + + if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) { + NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb); + ret = EINVAL; + goto out; + } + + for (i=0; i < scb.sub.num_packages; i++) { + if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) { + scpk = &scb.sub.packages[i]; + if (!scpk->data || !scpk->data[0]) { + scpk = NULL; + continue; + } + newer_keys = true; + break; + } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) { + scpk = &scb.sub.packages[i]; + if (!scpk->data || !scpk->data[0]) { + scpk = NULL; + } + /* + * we don't break here in hope to find + * a Kerberos-Newer-Keys package + */ + } + } + } + /* + * Primary:Kerberos-Newer-Keys or Primary:Kerberos element + * of supplementalCredentials + */ + if (scpk) { + DATA_BLOB blob; + + blob = strhex_to_data_blob(scpk->data); + if (!blob.data) { + ret = ENOMEM; + goto out; + } + talloc_steal(mem_ctx, blob.data); + + /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */ + ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, iconv_convenience, &_pkb, + (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + krb5_set_error_string(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob"); + krb5_warnx(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob"); + ret = EINVAL; + goto out; + } + + if (newer_keys && _pkb.version != 4) { + krb5_set_error_string(context, "LDB_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4"); + krb5_warnx(context, "LDB_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4"); + ret = EINVAL; + goto out; + } + + if (!newer_keys && _pkb.version != 3) { + krb5_set_error_string(context, "LDB_message2entry_keys: could not parse Primary:Kerberos not version 3"); + krb5_warnx(context, "LDB_message2entry_keys: could not parse Primary:Kerberos not version 3"); + ret = EINVAL; + goto out; + } + + if (_pkb.version == 4) { + pkb4 = &_pkb.ctr.ctr4; + allocated_keys += pkb4->num_keys; + } else if (_pkb.version == 3) { + pkb3 = &_pkb.ctr.ctr3; + allocated_keys += pkb3->num_keys; + } + } + + if (allocated_keys == 0) { + /* oh, no password. Apparently (comment in + * hdb-ldap.c) this violates the ASN.1, but this + * allows an entry with no keys (yet). */ + return 0; + } + + /* allocate space to decode into */ + entry_ex->entry.keys.len = 0; + entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key)); + if (entry_ex->entry.keys.val == NULL) { + ret = ENOMEM; + goto out; + } + + if (hash && !(userAccountControl & UF_USE_DES_KEY_ONLY)) { + Key key; + + key.mkvno = 0; + key.salt = NULL; /* No salt for this enc type */ + + ret = krb5_keyblock_init(context, + ENCTYPE_ARCFOUR_HMAC_MD5, + hash->hash, sizeof(hash->hash), + &key.key); + if (ret) { + goto out; + } + + entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key; + entry_ex->entry.keys.len++; + } + + if (pkb4) { + for (i=0; i < pkb4->num_keys; i++) { + bool use = true; + Key key; + + if (!pkb4->keys[i].value) continue; + + if (userAccountControl & UF_USE_DES_KEY_ONLY) { + switch (pkb4->keys[i].keytype) { + case ENCTYPE_DES_CBC_CRC: + case ENCTYPE_DES_CBC_MD5: + break; + default: + use = false; + break; + } + } + + if (!use) continue; + + key.mkvno = 0; + key.salt = NULL; + + if (pkb4->salt.string) { + DATA_BLOB salt; + + salt = data_blob_string_const(pkb4->salt.string); + + key.salt = calloc(1, sizeof(*key.salt)); + if (key.salt == NULL) { + ret = ENOMEM; + goto out; + } + + key.salt->type = hdb_pw_salt; + + ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length); + if (ret) { + free(key.salt); + key.salt = NULL; + goto out; + } + } + + /* TODO: maybe pass the iteration_count somehow... */ + + ret = krb5_keyblock_init(context, + pkb4->keys[i].keytype, + pkb4->keys[i].value->data, + pkb4->keys[i].value->length, + &key.key); + if (ret) { + if (key.salt) { + free_Salt(key.salt); + free(key.salt); + key.salt = NULL; + } + goto out; + } + + entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key; + entry_ex->entry.keys.len++; + } + } else if (pkb3) { + for (i=0; i < pkb3->num_keys; i++) { + bool use = true; + Key key; + + if (!pkb3->keys[i].value) continue; + + if (userAccountControl & UF_USE_DES_KEY_ONLY) { + switch (pkb3->keys[i].keytype) { + case ENCTYPE_DES_CBC_CRC: + case ENCTYPE_DES_CBC_MD5: + break; + default: + use = false; + break; + } + } + + if (!use) continue; + + key.mkvno = 0; + key.salt = NULL; + + if (pkb3->salt.string) { + DATA_BLOB salt; + + salt = data_blob_string_const(pkb3->salt.string); + + key.salt = calloc(1, sizeof(*key.salt)); + if (key.salt == NULL) { + ret = ENOMEM; + goto out; + } + + key.salt->type = hdb_pw_salt; + + ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length); + if (ret) { + free(key.salt); + key.salt = NULL; + goto out; + } + } + + ret = krb5_keyblock_init(context, + pkb3->keys[i].keytype, + pkb3->keys[i].value->data, + pkb3->keys[i].value->length, + &key.key); + if (ret) { + if (key.salt) { + free_Salt(key.salt); + free(key.salt); + key.salt = NULL; + } + goto out; + } + + entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key; + entry_ex->entry.keys.len++; + } + } + +out: + if (ret != 0) { + entry_ex->entry.keys.len = 0; + } + if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) { + free(entry_ex->entry.keys.val); + entry_ex->entry.keys.val = NULL; + } + return ret; +} + +/* + * Construct an hdb_entry from a directory entry. + */ +static krb5_error_code LDB_message2entry(krb5_context context, HDB *db, + TALLOC_CTX *mem_ctx, krb5_const_principal principal, + enum hdb_ldb_ent_type ent_type, + struct ldb_message *msg, + struct ldb_message *realm_ref_msg, + hdb_entry_ex *entry_ex) +{ + unsigned int userAccountControl; + int i; + krb5_error_code ret = 0; + krb5_boolean is_computer = FALSE; + const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg, "dnsRoot", NULL); + char *realm = strupper_talloc(mem_ctx, dnsdomain); + struct loadparm_context *lp_ctx = ldb_get_opaque((struct ldb_context *)db->hdb_db, "loadparm"); + struct ldb_dn *domain_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, + mem_ctx, + realm_ref_msg, + "nCName", + ldb_dn_new(mem_ctx, (struct ldb_context *)db->hdb_db, NULL)); + + struct hdb_ldb_private *private; + NTTIME acct_expiry; + + struct ldb_message_element *objectclasses; + struct ldb_val computer_val; + computer_val.data = discard_const_p(uint8_t,"computer"); + computer_val.length = strlen((const char *)computer_val.data); + + objectclasses = ldb_msg_find_element(msg, "objectClass"); + + if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) { + is_computer = TRUE; + } + + memset(entry_ex, 0, sizeof(*entry_ex)); + + if (!realm) { + krb5_set_error_string(context, "talloc_strdup: out of memory"); + ret = ENOMEM; + goto out; + } + + private = talloc(mem_ctx, struct hdb_ldb_private); + if (!private) { + ret = ENOMEM; + goto out; + } + + private->entry_ex = entry_ex; + private->iconv_convenience = lp_iconv_convenience(lp_ctx); + private->netbios_name = lp_netbios_name(lp_ctx); + + talloc_set_destructor(private, hdb_ldb_destructor); + + entry_ex->ctx = private; + entry_ex->free_entry = hdb_ldb_free_entry; + + userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0); + + + entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal))); + 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"); + ret = ENOENT; + goto out; + } + samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL); + krb5_make_principal(context, &entry_ex->entry.principal, realm, samAccountName, NULL); + } else { + char *strdup_realm; + ret = copy_Principal(principal, entry_ex->entry.principal); + if (ret) { + krb5_clear_error_string(context); + goto out; + } + + /* While we have copied the client principal, tests + * show that Win2k3 returns the 'corrected' realm, not + * the client-specified realm. This code attempts to + * replace the client principal's realm with the one + * we determine from our records */ + + /* this has to be with malloc() */ + strdup_realm = strdup(realm); + if (!strdup_realm) { + ret = ENOMEM; + krb5_clear_error_string(context); + goto out; + } + free(*krb5_princ_realm(context, entry_ex->entry.principal)); + krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm); + } + + entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type); + + 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; + entry_ex->entry.flags.ok_as_delegate = 1; + } + + if (lp_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) { + if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) { + entry_ex->entry.flags.server = 0; + } + } + + /* use 'whenCreated' */ + entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0); + /* use '???' */ + entry_ex->entry.created_by.principal = NULL; + + entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event)); + if (entry_ex->entry.modified_by == NULL) { + krb5_set_error_string(context, "malloc: out of memory"); + ret = ENOMEM; + goto out; + } + + /* use 'whenChanged' */ + entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0); + /* use '???' */ + entry_ex->entry.modified_by->principal = NULL; + + entry_ex->entry.valid_start = NULL; + + acct_expiry = samdb_result_account_expires(msg); + if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) { + entry_ex->entry.valid_end = NULL; + } else { + entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end)); + if (entry_ex->entry.valid_end == NULL) { + ret = ENOMEM; + goto out; + } + *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry); + } + + 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); + if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) { + entry_ex->entry.pw_end = NULL; + } else { + entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end)); + if (entry_ex->entry.pw_end == NULL) { + ret = ENOMEM; + goto out; + } + *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time); + } + } else { + entry_ex->entry.pw_end = NULL; + } + + entry_ex->entry.max_life = NULL; + + entry_ex->entry.max_renew = NULL; + + entry_ex->entry.generation = NULL; + + /* Get keys from the db */ + ret = LDB_message2entry_keys(context, private->iconv_convenience, private, msg, userAccountControl, entry_ex); + if (ret) { + /* Could be bougus data in the entry, or out of memory */ + goto out; + } + + entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes))); + if (entry_ex->entry.etypes == NULL) { + krb5_clear_error_string(context); + ret = ENOMEM; + goto out; + } + entry_ex->entry.etypes->len = entry_ex->entry.keys.len; + entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int)); + if (entry_ex->entry.etypes->val == NULL) { + krb5_clear_error_string(context); + ret = ENOMEM; + goto out; + } + for (i=0; i < entry_ex->entry.etypes->len; i++) { + entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype; + } + + + private->msg = talloc_steal(private, msg); + private->realm_ref_msg = talloc_steal(private, realm_ref_msg); + private->samdb = (struct ldb_context *)db->hdb_db; + +out: + if (ret != 0) { + /* This doesn't free ent itself, that is for the eventual caller to do */ + hdb_free_entry(context, entry_ex); + } else { + talloc_steal(db, entry_ex->ctx); + } + + return ret; +} + +/* + * Construct an hdb_entry from a directory entry. + */ +static krb5_error_code LDB_trust_message2entry(krb5_context context, HDB *db, + struct loadparm_context *lp_ctx, + TALLOC_CTX *mem_ctx, krb5_const_principal principal, + enum trust_direction direction, + struct ldb_message *msg, + hdb_entry_ex *entry_ex) +{ + + const char *dnsdomain; + char *realm; + char *strdup_realm; + DATA_BLOB password_utf16; + struct samr_Password password_hash; + const struct ldb_val *password_val; + struct trustAuthInOutBlob password_blob; + struct hdb_ldb_private *private; + + enum ndr_err_code ndr_err; + int i, ret, trust_direction_flags; + + private = talloc(mem_ctx, struct hdb_ldb_private); + if (!private) { + ret = ENOMEM; + goto out; + } + + private->entry_ex = entry_ex; + private->iconv_convenience = lp_iconv_convenience(lp_ctx); + private->netbios_name = lp_netbios_name(lp_ctx); + + talloc_set_destructor(private, hdb_ldb_destructor); + + entry_ex->ctx = private; + entry_ex->free_entry = hdb_ldb_free_entry; + + /* use 'whenCreated' */ + entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0); + /* use '???' */ + entry_ex->entry.created_by.principal = NULL; + + entry_ex->entry.valid_start = NULL; + + trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0); + + if (direction == INBOUND) { + realm = strupper_talloc(mem_ctx, lp_realm(lp_ctx)); + password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming"); + + } else { /* OUTBOUND */ + dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL); + realm = strupper_talloc(mem_ctx, dnsdomain); + password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing"); + } + + if (!password_val || !(trust_direction_flags & direction)) { + ret = ENOENT; + goto out; + } + + ndr_err = ndr_pull_struct_blob_all(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; + } + + 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, + password_blob.current->array[i].AuthInfo.clear.size); + /* In the future, generate all sorts of + * hashes, but for now we can't safely convert + * the random strings windows uses into + * utf8 */ + + /* but as it is utf16 already, we can get the NT password/arcfour-hmac-md5 key */ + mdfour(password_hash.hash, password_utf16.data, password_utf16.length); + break; + } else if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) { + password_hash = password_blob.current->array[i].AuthInfo.nt4owf.password; + break; + } + } + entry_ex->entry.keys.len = 0; + entry_ex->entry.keys.val = NULL; + + if (i < password_blob.count) { + Key key; + /* Must have found a cleartext or MD4 password */ + entry_ex->entry.keys.val = calloc(1, sizeof(Key)); + + key.mkvno = 0; + key.salt = NULL; /* No salt for this enc type */ + + if (entry_ex->entry.keys.val == NULL) { + ret = ENOMEM; + goto out; + } + + ret = krb5_keyblock_init(context, + ENCTYPE_ARCFOUR_HMAC_MD5, + password_hash.hash, sizeof(password_hash.hash), + &key.key); + + entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key; + entry_ex->entry.keys.len++; + } + + ret = copy_Principal(principal, entry_ex->entry.principal); + if (ret) { + krb5_clear_error_string(context); + goto out; + } + + /* While we have copied the client principal, tests + * show that Win2k3 returns the 'corrected' realm, not + * the client-specified realm. This code attempts to + * replace the client principal's realm with the one + * we determine from our records */ + + /* this has to be with malloc() */ + strdup_realm = strdup(realm); + if (!strdup_realm) { + ret = ENOMEM; + krb5_clear_error_string(context); + goto out; + } + free(*krb5_princ_realm(context, entry_ex->entry.principal)); + krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm); + + entry_ex->entry.flags = int2HDBFlags(0); + entry_ex->entry.flags.immutable = 1; + entry_ex->entry.flags.invalid = 0; + entry_ex->entry.flags.server = 1; + entry_ex->entry.flags.require_preauth = 1; + + entry_ex->entry.pw_end = NULL; + + entry_ex->entry.max_life = NULL; + + entry_ex->entry.max_renew = NULL; + + entry_ex->entry.generation = NULL; + + entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes))); + if (entry_ex->entry.etypes == NULL) { + krb5_clear_error_string(context); + ret = ENOMEM; + goto out; + } + entry_ex->entry.etypes->len = entry_ex->entry.keys.len; + entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int)); + if (entry_ex->entry.etypes->val == NULL) { + krb5_clear_error_string(context); + ret = ENOMEM; + goto out; + } + for (i=0; i < entry_ex->entry.etypes->len; i++) { + entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype; + } + + + private->msg = talloc_steal(private, msg); + private->realm_ref_msg = NULL; + private->samdb = (struct ldb_context *)db->hdb_db; + +out: + if (ret != 0) { + /* This doesn't free ent itself, that is for the eventual caller to do */ + hdb_free_entry(context, entry_ex); + } else { + talloc_steal(db, entry_ex->ctx); + } + + return ret; + +} + +static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_context *ldb_ctx, + TALLOC_CTX *mem_ctx, + krb5_const_principal principal, + enum hdb_ldb_ent_type ent_type, + struct ldb_dn *realm_dn, + struct ldb_message ***pmsg) +{ + krb5_error_code ret; + int lret; + char *filter = NULL; + const char * const *princ_attrs = user_attrs; + + char *short_princ; + char *short_princ_talloc; + + struct ldb_result *res = NULL; + + ret = krb5_unparse_name_flags(context, principal, KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ); + + if (ret != 0) { + krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal"); + krb5_warnx(context, "LDB_lookup_principal: could not parse principal"); + return ret; + } + + short_princ_talloc = talloc_strdup(mem_ctx, short_princ); + free(short_princ); + if (!short_princ_talloc) { + krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!"); + return ENOMEM; + } + + switch (ent_type) { + 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_SAMBA4_ENT_TYPE_KRBTGT: + filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", + KRB5_TGS_NAME); + break; + case HDB_SAMBA4_ENT_TYPE_SERVER: + filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", + short_princ_talloc); + break; + } + + if (!filter) { + krb5_set_error_string(context, "talloc_asprintf: out of memory"); + return ENOMEM; + } + + lret = ldb_search(ldb_ctx, mem_ctx, &res, realm_dn, + LDB_SCOPE_SUBTREE, princ_attrs, "%s", filter); + if (lret != LDB_SUCCESS) { + DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx))); + return HDB_ERR_NOENTRY; + } else if (res->count == 0 || res->count > 1) { + DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count)); + talloc_free(res); + return HDB_ERR_NOENTRY; + } + talloc_steal(mem_ctx, res->msgs); + *pmsg = res->msgs; + talloc_free(res); + return 0; +} + +static krb5_error_code LDB_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx, + TALLOC_CTX *mem_ctx, + const char *realm, + struct ldb_dn *realm_dn, + struct ldb_message ***pmsg) +{ + int lret; + char *filter = NULL; + const char * const *attrs = trust_attrs; + + struct ldb_result *res = NULL; + filter = talloc_asprintf(mem_ctx, "(&(objectClass=trustedDomain)(|(flatname=%s)(trustPartner=%s)))", realm, realm); + + if (!filter) { + krb5_set_error_string(context, "talloc_asprintf: out of memory"); + return ENOMEM; + } + + lret = ldb_search(ldb_ctx, mem_ctx, &res, + ldb_get_default_basedn(ldb_ctx), + LDB_SCOPE_SUBTREE, attrs, "%s", filter); + if (lret != LDB_SUCCESS) { + DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx))); + return HDB_ERR_NOENTRY; + } else if (res->count == 0 || res->count > 1) { + DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count)); + talloc_free(res); + return HDB_ERR_NOENTRY; + } + talloc_steal(mem_ctx, res->msgs); + *pmsg = res->msgs; + talloc_free(res); + return 0; +} + +static krb5_error_code LDB_lookup_realm(krb5_context context, struct ldb_context *ldb_ctx, + TALLOC_CTX *mem_ctx, + const char *realm, + struct ldb_message ***pmsg) +{ + int ret; + struct ldb_result *cross_ref_res; + struct ldb_dn *partitions_basedn = samdb_partitions_dn(ldb_ctx, mem_ctx); + + ret = ldb_search(ldb_ctx, mem_ctx, &cross_ref_res, + partitions_basedn, LDB_SCOPE_SUBTREE, realm_ref_attrs, + "(&(&(|(&(dnsRoot=%s)(nETBIOSName=*))(nETBIOSName=%s))(objectclass=crossRef))(ncName=*))", + realm, realm); + + if (ret != LDB_SUCCESS) { + DEBUG(3, ("Failed to search to lookup realm(%s): %s\n", realm, ldb_errstring(ldb_ctx))); + talloc_free(cross_ref_res); + return HDB_ERR_NOENTRY; + } else if (cross_ref_res->count == 0 || cross_ref_res->count > 1) { + DEBUG(3, ("Failed find a single entry for realm %s: got %d\n", realm, cross_ref_res->count)); + talloc_free(cross_ref_res); + return HDB_ERR_NOENTRY; + } + + if (pmsg) { + *pmsg = cross_ref_res->msgs; + talloc_steal(mem_ctx, cross_ref_res->msgs); + } + talloc_free(cross_ref_res); + + return 0; +} + + +static krb5_error_code LDB_open(krb5_context context, HDB *db, int flags, mode_t mode) +{ + if (db->hdb_master_key_set) { + krb5_warnx(context, "LDB_open: use of a master key incompatible with LDB\n"); + krb5_set_error_string(context, "LDB_open: use of a master key incompatible with LDB\n"); + return HDB_ERR_NOENTRY; + } + + return 0; +} + +static krb5_error_code LDB_close(krb5_context context, HDB *db) +{ + return 0; +} + +static krb5_error_code LDB_lock(krb5_context context, HDB *db, int operation) +{ + return 0; +} + +static krb5_error_code LDB_unlock(krb5_context context, HDB *db) +{ + return 0; +} + +static krb5_error_code LDB_rename(krb5_context context, HDB *db, const char *new_name) +{ + return HDB_ERR_DB_INUSE; +} + +static krb5_error_code LDB_fetch_client(krb5_context context, HDB *db, + TALLOC_CTX *mem_ctx, + krb5_const_principal principal, + unsigned flags, + hdb_entry_ex *entry_ex) { + NTSTATUS nt_status; + char *principal_string; + krb5_error_code ret; + struct ldb_message **msg = NULL; + struct ldb_message **realm_ref_msg = NULL; + + ret = krb5_unparse_name(context, principal, &principal_string); + + if (ret != 0) { + return ret; + } + + nt_status = sam_get_results_principal((struct ldb_context *)db->hdb_db, + mem_ctx, principal_string, + &msg, &realm_ref_msg); + free(principal_string); + if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) { + return HDB_ERR_NOENTRY; + } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) { + return ENOMEM; + } else if (!NT_STATUS_IS_OK(nt_status)) { + return EINVAL; + } + + ret = LDB_message2entry(context, db, mem_ctx, + principal, HDB_SAMBA4_ENT_TYPE_CLIENT, + msg[0], realm_ref_msg[0], entry_ex); + return ret; +} + +static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db, + TALLOC_CTX *mem_ctx, + krb5_const_principal principal, + unsigned flags, + hdb_entry_ex *entry_ex) +{ + krb5_error_code ret; + struct ldb_message **msg = NULL; + struct ldb_message **realm_ref_msg_1 = NULL; + struct ldb_message **realm_ref_msg_2 = NULL; + struct ldb_dn *realm_dn; + const char *realm; + + krb5_principal alloc_principal = NULL; + if (principal->name.name_string.len != 2 + || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) { + /* Not a krbtgt */ + return HDB_ERR_NOENTRY; + } + + /* krbtgt case. Either us or a trusted realm */ + + if ((LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, + mem_ctx, principal->realm, &realm_ref_msg_1) == 0) + && (LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, + mem_ctx, principal->name.name_string.val[1], &realm_ref_msg_2) == 0) + && (ldb_dn_compare(realm_ref_msg_1[0]->dn, realm_ref_msg_1[0]->dn) == 0)) { + /* us */ + /* Cludge, cludge cludge. If the realm part of krbtgt/realm, + * is in our db, then direct the caller at our primary + * krbtgt */ + + const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg_1[0], "dnsRoot", NULL); + char *realm_fixed = strupper_talloc(mem_ctx, dnsdomain); + if (!realm_fixed) { + krb5_set_error_string(context, "strupper_talloc: out of memory"); + return ENOMEM; + } + + ret = krb5_copy_principal(context, principal, &alloc_principal); + if (ret) { + return ret; + } + + free(alloc_principal->name.name_string.val[1]); + alloc_principal->name.name_string.val[1] = strdup(realm_fixed); + talloc_free(realm_fixed); + if (!alloc_principal->name.name_string.val[1]) { + krb5_set_error_string(context, "LDB_fetch: strdup() failed!"); + return ENOMEM; + } + principal = alloc_principal; + realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg_1[0], "nCName", NULL); + + ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, + mem_ctx, + principal, HDB_SAMBA4_ENT_TYPE_KRBTGT, realm_dn, &msg); + + if (ret != 0) { + krb5_warnx(context, "LDB_fetch: could not find principal in DB"); + krb5_set_error_string(context, "LDB_fetch: could not find principal in DB"); + return ret; + } + + ret = LDB_message2entry(context, db, mem_ctx, + 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"); + } + return ret; + + } else { + enum trust_direction direction = UNKNOWN; + + struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(db->hdb_db, "loadparm"), struct loadparm_context); + /* Either an inbound or outbound trust */ + + if (strcasecmp(lp_realm(lp_ctx), principal->realm) == 0) { + /* look for inbound trust */ + direction = INBOUND; + realm = principal->name.name_string.val[1]; + } + + if (strcasecmp(lp_realm(lp_ctx), principal->name.name_string.val[1]) == 0) { + /* look for outbound trust */ + direction = OUTBOUND; + realm = principal->realm; + } + + /* Trusted domains are under CN=system */ + + ret = LDB_lookup_trust(context, (struct ldb_context *)db->hdb_db, + mem_ctx, + realm, realm_dn, &msg); + + if (ret != 0) { + krb5_warnx(context, "LDB_fetch: could not find principal in DB"); + krb5_set_error_string(context, "LDB_fetch: could not find principal in DB"); + return ret; + } + + ret = LDB_trust_message2entry(context, db, lp_ctx, mem_ctx, + principal, direction, + msg[0], entry_ex); + if (ret != 0) { + krb5_warnx(context, "LDB_fetch: message2entry failed"); + } + return ret; + + + /* we should lookup trusted domains */ + return HDB_ERR_NOENTRY; + } + +} + +static krb5_error_code LDB_fetch_server(krb5_context context, HDB *db, + TALLOC_CTX *mem_ctx, + krb5_const_principal principal, + unsigned flags, + hdb_entry_ex *entry_ex) +{ + krb5_error_code ret; + const char *realm; + struct ldb_message **msg = NULL; + struct ldb_message **realm_ref_msg = NULL; + struct ldb_dn *partitions_basedn = samdb_partitions_dn(db->hdb_db, mem_ctx); + if (principal->name.name_string.len >= 2) { + /* 'normal server' case */ + int ldb_ret; + NTSTATUS nt_status; + struct ldb_dn *user_dn, *domain_dn; + char *principal_string; + + ret = krb5_unparse_name_flags(context, principal, + KRB5_PRINCIPAL_UNPARSE_NO_REALM, + &principal_string); + if (ret != 0) { + return ret; + } + + /* At this point we may find the host is known to be + * in a different realm, so we should generate a + * referral instead */ + nt_status = crack_service_principal_name((struct ldb_context *)db->hdb_db, + mem_ctx, principal_string, + &user_dn, &domain_dn); + free(principal_string); + + if (!NT_STATUS_IS_OK(nt_status)) { + return HDB_ERR_NOENTRY; + } + + ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db, + mem_ctx, user_dn, &msg, user_attrs); + + if (ldb_ret != 1) { + return HDB_ERR_NOENTRY; + } + + ldb_ret = gendb_search((struct ldb_context *)db->hdb_db, + mem_ctx, partitions_basedn, &realm_ref_msg, realm_ref_attrs, + "ncName=%s", ldb_dn_get_linearized(domain_dn)); + + if (ldb_ret != 1) { + return HDB_ERR_NOENTRY; + } + + } else { + struct ldb_dn *realm_dn; + /* server as client principal case, but we must not lookup userPrincipalNames */ + + realm = krb5_principal_get_realm(context, principal); + + ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, + mem_ctx, realm, &realm_ref_msg); + if (ret != 0) { + return HDB_ERR_NOENTRY; + } + + realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL); + + ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, + mem_ctx, + principal, HDB_SAMBA4_ENT_TYPE_SERVER, realm_dn, &msg); + + if (ret != 0) { + return ret; + } + } + + ret = LDB_message2entry(context, db, mem_ctx, + principal, HDB_SAMBA4_ENT_TYPE_SERVER, + msg[0], realm_ref_msg[0], entry_ex); + if (ret != 0) { + krb5_warnx(context, "LDB_fetch: message2entry failed"); + } + + return ret; +} + +static krb5_error_code LDB_fetch(krb5_context context, HDB *db, + krb5_const_principal principal, + unsigned flags, + hdb_entry_ex *entry_ex) +{ + krb5_error_code ret = HDB_ERR_NOENTRY; + + TALLOC_CTX *mem_ctx = talloc_named(db, 0, "LDB_fetch context"); + + if (!mem_ctx) { + krb5_set_error_string(context, "LDB_fetch: talloc_named() failed!"); + return ENOMEM; + } + + if (flags & HDB_F_GET_CLIENT) { + ret = LDB_fetch_client(context, db, mem_ctx, principal, flags, entry_ex); + if (ret != HDB_ERR_NOENTRY) goto done; + } + if (flags & HDB_F_GET_SERVER) { + /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */ + ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex); + if (ret != HDB_ERR_NOENTRY) goto done; + + /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */ + ret = LDB_fetch_server(context, db, mem_ctx, principal, flags, entry_ex); + if (ret != HDB_ERR_NOENTRY) goto done; + } + if (flags & HDB_F_GET_KRBTGT) { + ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex); + if (ret != HDB_ERR_NOENTRY) goto done; + } + +done: + talloc_free(mem_ctx); + return ret; +} + +static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) +{ + return HDB_ERR_DB_INUSE; +} + +static krb5_error_code LDB_remove(krb5_context context, HDB *db, krb5_const_principal principal) +{ + return HDB_ERR_DB_INUSE; +} + +struct hdb_ldb_seq { + struct ldb_context *ctx; + int index; + int count; + struct ldb_message **msgs; + struct ldb_message **realm_ref_msgs; +}; + +static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) +{ + krb5_error_code ret; + struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc; + TALLOC_CTX *mem_ctx; + hdb_entry_ex entry_ex; + memset(&entry_ex, '\0', sizeof(entry_ex)); + + if (!priv) { + return HDB_ERR_NOENTRY; + } + + mem_ctx = talloc_named(priv, 0, "LDB_seq context"); + + if (!mem_ctx) { + krb5_set_error_string(context, "LDB_seq: talloc_named() failed!"); + return ENOMEM; + } + + if (priv->index < priv->count) { + ret = LDB_message2entry(context, db, mem_ctx, + NULL, HDB_SAMBA4_ENT_TYPE_ANY, + priv->msgs[priv->index++], + priv->realm_ref_msgs[0], entry); + } else { + ret = HDB_ERR_NOENTRY; + } + + if (ret != 0) { + talloc_free(priv); + db->hdb_dbc = NULL; + } else { + talloc_free(mem_ctx); + } + + return ret; +} + +static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags, + hdb_entry_ex *entry) +{ + struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db; + struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc; + char *realm; + struct ldb_dn *realm_dn = NULL; + struct ldb_result *res = NULL; + struct ldb_message **realm_ref_msgs = NULL; + krb5_error_code ret; + TALLOC_CTX *mem_ctx; + int lret; + + if (priv) { + talloc_free(priv); + db->hdb_dbc = NULL; + } + + priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq); + if (!priv) { + krb5_set_error_string(context, "talloc: out of memory"); + return ENOMEM; + } + + priv->ctx = ldb_ctx; + priv->index = 0; + priv->msgs = NULL; + priv->realm_ref_msgs = NULL; + priv->count = 0; + + mem_ctx = talloc_named(priv, 0, "LDB_firstkey context"); + + if (!mem_ctx) { + krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!"); + return ENOMEM; + } + + ret = krb5_get_default_realm(context, &realm); + if (ret != 0) { + talloc_free(priv); + return ret; + } + + ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, + mem_ctx, realm, &realm_ref_msgs); + + free(realm); + + if (ret != 0) { + talloc_free(priv); + krb5_warnx(context, "LDB_firstkey: could not find realm\n"); + return HDB_ERR_NOENTRY; + } + + realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msgs[0], "nCName", NULL); + + priv->realm_ref_msgs = talloc_steal(priv, realm_ref_msgs); + + lret = ldb_search(ldb_ctx, priv, &res, + realm_dn, LDB_SCOPE_SUBTREE, user_attrs, + "(objectClass=user)"); + + if (lret != LDB_SUCCESS) { + talloc_free(priv); + return HDB_ERR_NOENTRY; + } + + priv->count = res->count; + priv->msgs = talloc_steal(priv, res->msgs); + talloc_free(res); + + db->hdb_dbc = priv; + + ret = LDB_seq(context, db, flags, entry); + + if (ret != 0) { + talloc_free(priv); + db->hdb_dbc = NULL; + } else { + talloc_free(mem_ctx); + } + return ret; +} + +static krb5_error_code LDB_nextkey(krb5_context context, HDB *db, unsigned flags, + hdb_entry_ex *entry) +{ + return LDB_seq(context, db, flags, entry); +} + +static krb5_error_code LDB_destroy(krb5_context context, HDB *db) +{ + talloc_free(db); + return 0; +} + +/* This interface is to be called by the KDC, which is expecting Samba + * calling conventions. It is also called by a wrapper + * (hdb_ldb_create) from the kpasswdd -> krb5 -> keytab_hdb -> hdb + * code */ + +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) +{ + NTSTATUS nt_status; + struct auth_session_info *session_info; + *db = talloc(mem_ctx, HDB); + if (!*db) { + krb5_set_error_string(context, "malloc: out of memory"); + return NT_STATUS_NO_MEMORY; + } + + (*db)->hdb_master_key_set = 0; + (*db)->hdb_db = NULL; + + nt_status = auth_system_session_info(*db, lp_ctx, &session_info); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + /* The idea here is very simple. Using Kerberos to + * authenticate the KDC to the LDAP server is higly likely to + * be circular. + * + * In future we may set this up to use EXERNAL and SSL + * certificates, for now it will almost certainly be NTLMSSP + */ + + cli_credentials_set_kerberos_state(session_info->credentials, + CRED_DONT_USE_KERBEROS); + + /* Setup the link to LDB */ + (*db)->hdb_db = samdb_connect(*db, ev_ctx, lp_ctx, session_info); + if ((*db)->hdb_db == NULL) { + DEBUG(1, ("hdb_ldb_create: Cannot open samdb for KDC backend!")); + return NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + } + + (*db)->hdb_dbc = NULL; + (*db)->hdb_open = LDB_open; + (*db)->hdb_close = LDB_close; + (*db)->hdb_fetch = LDB_fetch; + (*db)->hdb_store = LDB_store; + (*db)->hdb_remove = LDB_remove; + (*db)->hdb_firstkey = LDB_firstkey; + (*db)->hdb_nextkey = LDB_nextkey; + (*db)->hdb_lock = LDB_lock; + (*db)->hdb_unlock = LDB_unlock; + (*db)->hdb_rename = LDB_rename; + /* we don't implement these, as we are not a lockable database */ + (*db)->hdb__get = NULL; + (*db)->hdb__put = NULL; + /* kadmin should not be used for deletes - use other tools instead */ + (*db)->hdb__del = NULL; + (*db)->hdb_destroy = LDB_destroy; + + return NT_STATUS_OK; +} + +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_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; + } + return EINVAL; +} diff --git a/source4/kdc/kdc.c b/source4/kdc/kdc.c index 030eb23c10..83c6f1c2ee 100644 --- a/source4/kdc/kdc.c +++ b/source4/kdc/kdc.c @@ -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"); -- cgit From 15b686198120cca0aaa305edc0a5e3242b4fa869 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Wed, 24 Sep 2008 12:53:40 -0700 Subject: Use the new 'samba4' name for our internal hdb plugin. --- source4/setup/secrets_dc.ldif | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/setup/secrets_dc.ldif b/source4/setup/secrets_dc.ldif index abc5860cf7..8ae5578e6b 100644 --- a/source4/setup/secrets_dc.ldif +++ b/source4/setup/secrets_dc.ldif @@ -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, -- cgit From 64195b72be6c251412500984c2a5c103e376d3c6 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Mon, 29 Sep 2008 21:36:21 -0700 Subject: Fix parsing of the trust passwords in LSA CreateTrustedDomainEx* --- source4/libcli/config.mk | 8 -- source4/libcli/drsblobs.c | 179 ------------------------------ source4/librpc/config.mk | 4 +- source4/librpc/idl/drsblobs.idl | 25 +++-- source4/librpc/ndr/ndr_drsblobs.c | 213 ++++++++++++++++++++++++++++++++++++ source4/rpc_server/lsa/dcesrv_lsa.c | 8 +- source4/torture/rpc/lsa.c | 6 +- 7 files changed, 239 insertions(+), 204 deletions(-) delete mode 100644 source4/libcli/drsblobs.c create mode 100644 source4/librpc/ndr/ndr_drsblobs.c diff --git a/source4/libcli/config.mk b/source4/libcli/config.mk index 2f81d7cff0..d68a2a2ce3 100644 --- a/source4/libcli/config.mk +++ b/source4/libcli/config.mk @@ -67,14 +67,6 @@ 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))) - [PYTHON::python_netbios] LIBRARY_REALNAME = samba/netbios.$(SHLIBEXT) PUBLIC_DEPENDENCIES = LIBCLI_NBT DYNCONFIG LIBSAMBA-HOSTCONFIG diff --git a/source4/libcli/drsblobs.c b/source4/libcli/drsblobs.c deleted file mode 100644 index 126f2ccc40..0000000000 --- a/source4/libcli/drsblobs.c +++ /dev/null @@ -1,179 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - Manually parsed structures found in the DRS protocol - - Copyright (C) Andrew Bartlett 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 . -*/ - -#include "includes.h" -#include "libcli/drsblobs.h" - -/* parser auto-generated by pidl, then hand-modified by abartlet */ - -/* Modified to have 'count' specified */ -static enum ndr_err_code ndr_push_AuthenticationInformationArray_with_count(struct ndr_push *ndr, int ndr_flags, int count, - const struct AuthenticationInformationArray *r) -{ - uint32_t cntr_array_0; - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - for (cntr_array_0 = 0; cntr_array_0 < count; cntr_array_0++) { - NDR_CHECK(ndr_push_AuthenticationInformation(ndr, NDR_SCALARS, &r->array[cntr_array_0])); - } - } - if (ndr_flags & NDR_BUFFERS) { - for (cntr_array_0 = 0; cntr_array_0 < count; cntr_array_0++) { - NDR_CHECK(ndr_push_AuthenticationInformation(ndr, NDR_BUFFERS, &r->array[cntr_array_0])); - } - } - return NDR_ERR_SUCCESS; -} - -/* Modified to have 'count' specified, and to allocate the array */ -static enum ndr_err_code ndr_pull_AuthenticationInformationArray_with_count(struct ndr_pull *ndr, int ndr_flags, int count, struct AuthenticationInformationArray *r) -{ - uint32_t cntr_array_0; - TALLOC_CTX *_mem_save_array_0; - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_PULL_ALLOC_N(ndr, r->array, count); - _mem_save_array_0 = NDR_PULL_GET_MEM_CTX(ndr); - NDR_PULL_SET_MEM_CTX(ndr, r->array, 0); - for (cntr_array_0 = 0; cntr_array_0 < count; cntr_array_0++) { - NDR_CHECK(ndr_pull_AuthenticationInformation(ndr, NDR_SCALARS, &r->array[cntr_array_0])); - } - NDR_PULL_SET_MEM_CTX(ndr, _mem_save_array_0, 0); - } - if (ndr_flags & NDR_BUFFERS) { - for (cntr_array_0 = 0; cntr_array_0 < count; cntr_array_0++) { - NDR_CHECK(ndr_pull_AuthenticationInformation(ndr, NDR_BUFFERS, &r->array[cntr_array_0])); - } - } - return NDR_ERR_SUCCESS; -} - -/* Modified to have 'count' specified */ -_PUBLIC_ void ndr_print_AuthenticationInformationArray_with_count(struct ndr_print *ndr, const char *name, int count, const struct AuthenticationInformationArray *r) -{ - uint32_t cntr_array_0; - ndr_print_struct(ndr, name, "AuthenticationInformationArray"); - ndr->depth++; - ndr->print(ndr, "%s: ARRAY(%d)", "array", (int)1); - ndr->depth++; - for (cntr_array_0=0;cntr_array_0array[cntr_array_0]); - free(idx_0); - } - } - ndr->depth--; - ndr->depth--; -} - -/* Modified to call AuthenticationInformationArray with 'count' specified */ -_PUBLIC_ enum ndr_err_code ndr_push_trustAuthInOutBlob(struct ndr_push *ndr, int ndr_flags, const struct trustAuthInOutBlob *r) -{ - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_push_align(ndr, 4)); - NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->count)); - NDR_CHECK(ndr_push_relative_ptr1(ndr, r->current)); - NDR_CHECK(ndr_push_relative_ptr1(ndr, r->previous)); - } - if (ndr_flags & NDR_BUFFERS) { - if (r->current) { - NDR_CHECK(ndr_push_relative_ptr2(ndr, r->current)); - NDR_CHECK(ndr_push_AuthenticationInformationArray_with_count(ndr, NDR_SCALARS|NDR_BUFFERS, r->count, r->current)); - } - if (r->previous) { - NDR_CHECK(ndr_push_relative_ptr2(ndr, r->previous)); - NDR_CHECK(ndr_push_AuthenticationInformationArray_with_count(ndr, NDR_SCALARS|NDR_BUFFERS, r->count, r->previous)); - } - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ enum ndr_err_code ndr_pull_trustAuthInOutBlob(struct ndr_pull *ndr, int ndr_flags, struct trustAuthInOutBlob *r) -{ - uint32_t _ptr_current; - TALLOC_CTX *_mem_save_current_0; - uint32_t _ptr_previous; - TALLOC_CTX *_mem_save_previous_0; - if (ndr_flags & NDR_SCALARS) { - NDR_CHECK(ndr_pull_align(ndr, 4)); - NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->count)); - NDR_CHECK(ndr_pull_generic_ptr(ndr, &_ptr_current)); - if (_ptr_current) { - NDR_PULL_ALLOC(ndr, r->current); - NDR_CHECK(ndr_pull_relative_ptr1(ndr, r->current, _ptr_current)); - } else { - r->current = NULL; - } - NDR_CHECK(ndr_pull_generic_ptr(ndr, &_ptr_previous)); - if (_ptr_previous) { - NDR_PULL_ALLOC(ndr, r->previous); - NDR_CHECK(ndr_pull_relative_ptr1(ndr, r->previous, _ptr_previous)); - } else { - r->previous = NULL; - } - } - if (ndr_flags & NDR_BUFFERS) { - if (r->current) { - uint32_t _relative_save_offset; - _relative_save_offset = ndr->offset; - NDR_CHECK(ndr_pull_relative_ptr2(ndr, r->current)); - _mem_save_current_0 = NDR_PULL_GET_MEM_CTX(ndr); - NDR_PULL_SET_MEM_CTX(ndr, r->current, 0); - NDR_CHECK(ndr_pull_AuthenticationInformationArray_with_count(ndr, NDR_SCALARS|NDR_BUFFERS, r->count, r->current)); - NDR_PULL_SET_MEM_CTX(ndr, _mem_save_current_0, 0); - ndr->offset = _relative_save_offset; - } - if (r->previous) { - uint32_t _relative_save_offset; - _relative_save_offset = ndr->offset; - NDR_CHECK(ndr_pull_relative_ptr2(ndr, r->previous)); - _mem_save_previous_0 = NDR_PULL_GET_MEM_CTX(ndr); - NDR_PULL_SET_MEM_CTX(ndr, r->previous, 0); - NDR_CHECK(ndr_pull_AuthenticationInformationArray_with_count(ndr, NDR_SCALARS|NDR_BUFFERS, r->count, r->previous)); - NDR_PULL_SET_MEM_CTX(ndr, _mem_save_previous_0, 0); - ndr->offset = _relative_save_offset; - } - } - return NDR_ERR_SUCCESS; -} - -_PUBLIC_ void ndr_print_trustAuthInOutBlob(struct ndr_print *ndr, const char *name, const struct trustAuthInOutBlob *r) -{ - ndr_print_struct(ndr, name, "trustAuthInOutBlob"); - ndr->depth++; - ndr_print_uint32(ndr, "count", r->count); - ndr_print_ptr(ndr, "current", r->current); - ndr->depth++; - if (r->current) { - ndr_print_AuthenticationInformationArray_with_count(ndr, "current", r->count, r->current); - } - ndr->depth--; - ndr_print_ptr(ndr, "previous", r->previous); - ndr->depth++; - if (r->previous) { - ndr_print_AuthenticationInformationArray_with_count(ndr, "previous", r->count, r->previous); - } - ndr->depth--; - ndr->depth--; -} - - diff --git a/source4/librpc/config.mk b/source4/librpc/config.mk index cf41f9884a..41dd17e428 100644 --- a/source4/librpc/config.mk +++ b/source4/librpc/config.mk @@ -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 diff --git a/source4/librpc/idl/drsblobs.idl b/source4/librpc/idl/drsblobs.idl index 6b1f649ff5..31fe8a359e 100644 --- a/source4/librpc/idl/drsblobs.idl +++ b/source4/librpc/idl/drsblobs.idl @@ -415,18 +415,27 @@ interface drsblobs { [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; - + typedef [public,gensize] struct { + uint32 count; + [relative] AuthenticationInformation *current[count]; + } trustCurrentPasswords; + void decode_trustAuthInOut( [in] trustAuthInOutBlob blob ); + 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; diff --git a/source4/librpc/ndr/ndr_drsblobs.c b/source4/librpc/ndr/ndr_drsblobs.c new file mode 100644 index 0000000000..47a6bb60c9 --- /dev/null +++ b/source4/librpc/ndr/ndr_drsblobs.c @@ -0,0 +1,213 @@ +/* + Unix SMB/CIFS implementation. + + Manually parsed structures found in the DRS protocol + + Copyright (C) Andrew Bartlett 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 . +*/ + +#include "includes.h" +#include "libcli/drsblobs.h" + +/* parser auto-generated by pidl, then hand-modified by abartlet */ + +/* Modified to have 'count' specified */ +static enum ndr_err_code ndr_push_AuthenticationInformationArray_with_count(struct ndr_push *ndr, int ndr_flags, int count, + const struct AuthenticationInformationArray *r) +{ + uint32_t cntr_array_0; + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_push_align(ndr, 4)); + for (cntr_array_0 = 0; cntr_array_0 < count; cntr_array_0++) { + NDR_CHECK(ndr_push_AuthenticationInformation(ndr, NDR_SCALARS, &r->array[cntr_array_0])); + } + } + if (ndr_flags & NDR_BUFFERS) { + for (cntr_array_0 = 0; cntr_array_0 < count; cntr_array_0++) { + NDR_CHECK(ndr_push_AuthenticationInformation(ndr, NDR_BUFFERS, &r->array[cntr_array_0])); + } + } + return NDR_ERR_SUCCESS; +} + +/* Modified to have 'count' specified, and to allocate the array */ +static enum ndr_err_code ndr_pull_AuthenticationInformationArray_with_count(struct ndr_pull *ndr, int ndr_flags, int count, struct AuthenticationInformationArray *r) +{ + uint32_t cntr_array_0; + TALLOC_CTX *_mem_save_array_0; + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_pull_align(ndr, 4)); + NDR_PULL_ALLOC_N(ndr, r->array, count); + _mem_save_array_0 = NDR_PULL_GET_MEM_CTX(ndr); + NDR_PULL_SET_MEM_CTX(ndr, r->array, 0); + for (cntr_array_0 = 0; cntr_array_0 < count; cntr_array_0++) { + NDR_CHECK(ndr_pull_AuthenticationInformation(ndr, NDR_SCALARS, &r->array[cntr_array_0])); + } + NDR_PULL_SET_MEM_CTX(ndr, _mem_save_array_0, 0); + } + if (ndr_flags & NDR_BUFFERS) { + for (cntr_array_0 = 0; cntr_array_0 < count; cntr_array_0++) { + NDR_CHECK(ndr_pull_AuthenticationInformation(ndr, NDR_BUFFERS, &r->array[cntr_array_0])); + } + } + return NDR_ERR_SUCCESS; +} + +/* Modified to have 'count' specified */ +_PUBLIC_ void ndr_print_AuthenticationInformationArray_with_count(struct ndr_print *ndr, const char *name, int count, const struct AuthenticationInformationArray *r) +{ + uint32_t cntr_array_0; + ndr_print_struct(ndr, name, "AuthenticationInformationArray"); + ndr->depth++; + ndr->print(ndr, "%s: ARRAY(%d)", "array", (int)1); + ndr->depth++; + for (cntr_array_0=0;cntr_array_0array[cntr_array_0]); + free(idx_0); + } + } + ndr->depth--; + ndr->depth--; +} + +/* Modified to call AuthenticationInformationArray with 'count' specified */ +_PUBLIC_ enum ndr_err_code ndr_push_trustAuthInOutBlob(struct ndr_push *ndr, int ndr_flags, const struct trustAuthInOutBlob *r) +{ + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_push_align(ndr, 4)); + NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->count)); + NDR_CHECK(ndr_push_relative_ptr1(ndr, r->current)); + NDR_CHECK(ndr_push_relative_ptr1(ndr, r->previous)); + } + if (ndr_flags & NDR_BUFFERS) { + if (r->current) { + NDR_CHECK(ndr_push_relative_ptr2(ndr, r->current)); + NDR_CHECK(ndr_push_AuthenticationInformationArray_with_count(ndr, NDR_SCALARS|NDR_BUFFERS, r->count, r->current)); + } + if (r->previous) { + NDR_CHECK(ndr_push_relative_ptr2(ndr, r->previous)); + NDR_CHECK(ndr_push_AuthenticationInformationArray_with_count(ndr, NDR_SCALARS|NDR_BUFFERS, r->count, r->previous)); + } + } + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ enum ndr_err_code ndr_pull_trustAuthInOutBlob(struct ndr_pull *ndr, int ndr_flags, struct trustAuthInOutBlob *r) +{ + uint32_t _ptr_current; + TALLOC_CTX *_mem_save_current_0; + uint32_t _ptr_previous; + TALLOC_CTX *_mem_save_previous_0; + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_pull_align(ndr, 4)); + NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->count)); + NDR_CHECK(ndr_pull_generic_ptr(ndr, &_ptr_current)); + if (_ptr_current) { + NDR_PULL_ALLOC(ndr, r->current); + NDR_CHECK(ndr_pull_relative_ptr1(ndr, r->current, _ptr_current)); + } else { + r->current = NULL; + } + NDR_CHECK(ndr_pull_generic_ptr(ndr, &_ptr_previous)); + if (_ptr_previous) { + NDR_PULL_ALLOC(ndr, r->previous); + NDR_CHECK(ndr_pull_relative_ptr1(ndr, r->previous, _ptr_previous)); + } else { + r->previous = NULL; + } + } + if (ndr_flags & NDR_BUFFERS) { + if (r->current) { + uint32_t _relative_save_offset; + _relative_save_offset = ndr->offset; + NDR_CHECK(ndr_pull_relative_ptr2(ndr, r->current)); + _mem_save_current_0 = NDR_PULL_GET_MEM_CTX(ndr); + NDR_PULL_SET_MEM_CTX(ndr, r->current, 0); + NDR_CHECK(ndr_pull_AuthenticationInformationArray_with_count(ndr, NDR_SCALARS|NDR_BUFFERS, r->count, r->current)); + NDR_PULL_SET_MEM_CTX(ndr, _mem_save_current_0, 0); + ndr->offset = _relative_save_offset; + } + if (r->previous) { + uint32_t _relative_save_offset; + _relative_save_offset = ndr->offset; + NDR_CHECK(ndr_pull_relative_ptr2(ndr, r->previous)); + _mem_save_previous_0 = NDR_PULL_GET_MEM_CTX(ndr); + NDR_PULL_SET_MEM_CTX(ndr, r->previous, 0); + NDR_CHECK(ndr_pull_AuthenticationInformationArray_with_count(ndr, NDR_SCALARS|NDR_BUFFERS, r->count, r->previous)); + NDR_PULL_SET_MEM_CTX(ndr, _mem_save_previous_0, 0); + ndr->offset = _relative_save_offset; + } + } + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ void ndr_print_trustAuthInOutBlob(struct ndr_print *ndr, const char *name, const struct trustAuthInOutBlob *r) +{ + ndr_print_struct(ndr, name, "trustAuthInOutBlob"); + ndr->depth++; + ndr_print_uint32(ndr, "count", r->count); + ndr_print_ptr(ndr, "current", r->current); + ndr->depth++; + if (r->current) { + ndr_print_AuthenticationInformationArray_with_count(ndr, "current", r->count, r->current); + } + ndr->depth--; + ndr_print_ptr(ndr, "previous", r->previous); + ndr->depth++; + if (r->previous) { + ndr_print_AuthenticationInformationArray_with_count(ndr, "previous", r->count, r->previous); + } + ndr->depth--; + 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; +} + diff --git a/source4/rpc_server/lsa/dcesrv_lsa.c b/source4/rpc_server/lsa/dcesrv_lsa.c index 3b70f3e934..4c3c708d4a 100644 --- a/source4/rpc_server/lsa/dcesrv_lsa.c +++ b/source4/rpc_server/lsa/dcesrv_lsa.c @@ -626,7 +626,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; @@ -679,7 +679,7 @@ 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; } @@ -689,7 +689,7 @@ static NTSTATUS dcesrv_lsa_CreateTrustedDomain_base(struct dcesrv_call_state *dc ndr_err = ndr_push_struct_blob(&trustAuthIncoming, mem_ctx, lp_iconv_convenience(dce_call->conn->dce_ctx->lp_ctx), &auth_struct.incoming, - (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob); + (ndr_push_flags_fn_t)ndr_push_trustDomainPasswords); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { return NT_STATUS_INVALID_PARAMETER; } @@ -701,7 +701,7 @@ static NTSTATUS dcesrv_lsa_CreateTrustedDomain_base(struct dcesrv_call_state *dc ndr_err = ndr_push_struct_blob(&trustAuthOutgoing, mem_ctx, lp_iconv_convenience(dce_call->conn->dce_ctx->lp_ctx), &auth_struct.outgoing, - (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob); + (ndr_push_flags_fn_t)ndr_push_trustDomainPasswords); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { return NT_STATUS_INVALID_PARAMETER; } diff --git a/source4/torture/rpc/lsa.c b/source4/torture/rpc/lsa.c index 69bf33352b..af5ee4f6e1 100644 --- a/source4/torture/rpc/lsa.c +++ b/source4/torture/rpc/lsa.c @@ -2077,7 +2077,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]; @@ -2125,9 +2125,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; } -- cgit From 04edf11bee9f248241c46ce809870163a16d3ba0 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Mon, 29 Sep 2008 22:34:30 -0700 Subject: Rework to match new trustDomainPasswords IDL --- source4/rpc_server/lsa/dcesrv_lsa.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/source4/rpc_server/lsa/dcesrv_lsa.c b/source4/rpc_server/lsa/dcesrv_lsa.c index 4c3c708d4a..7b15241b96 100644 --- a/source4/rpc_server/lsa/dcesrv_lsa.c +++ b/source4/rpc_server/lsa/dcesrv_lsa.c @@ -859,11 +859,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 +871,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); -- cgit From e622325155a13fd9f6f85a767d345344f18eca41 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 30 Sep 2008 08:41:16 +0200 Subject: s4:smb_server/smb: FLAGS2_SMB_SECURITY_SIGNATURES should only be echoed, not set always metze --- source4/smb_server/smb/request.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/source4/smb_server/smb/request.c b/source4/smb_server/smb/request.c index eb3e100b96..241c262857 100644 --- a/source4/smb_server/smb/request.c +++ b/source4/smb_server/smb/request.c @@ -135,15 +135,16 @@ 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; } - if (req->smb_conn->signing.allow_smb_signing || req->smb_conn->signing.mandatory_signing) { - flags2 |= FLAGS2_SMB_SECURITY_SIGNATURES; - } - req->out.hdr = req->out.buffer + NBT_HDR_SIZE; req->out.vwv = req->out.hdr + HDR_VWV; req->out.wct = wct; -- cgit From 394f24b374e1fda8dc8222b71ce164a1a79efde6 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 30 Sep 2008 09:04:52 +0200 Subject: s4:drsblob: fix the build metze --- source4/libcli/drsblobs.h | 28 ---------------------------- source4/librpc/ndr/ndr_drsblobs.c | 2 +- 2 files changed, 1 insertion(+), 29 deletions(-) delete mode 100644 source4/libcli/drsblobs.h diff --git a/source4/libcli/drsblobs.h b/source4/libcli/drsblobs.h deleted file mode 100644 index 8fee4114be..0000000000 --- a/source4/libcli/drsblobs.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - Manually parsed structures found in the DRS protocol - - Copyright (C) Andrew Bartlett 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 . -*/ - -#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__ */ diff --git a/source4/librpc/ndr/ndr_drsblobs.c b/source4/librpc/ndr/ndr_drsblobs.c index 47a6bb60c9..aecb0c3b16 100644 --- a/source4/librpc/ndr/ndr_drsblobs.c +++ b/source4/librpc/ndr/ndr_drsblobs.c @@ -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 */ -- cgit From 7f1c02cd7a8f4238041406acab061f34c587c69a Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 15:24:46 +0200 Subject: Enable winreg Python tests - authentication works now. --- source4/samba4-skip | 1 - source4/scripting/python/samba/tests/dcerpc/rpcecho.py | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/source4/samba4-skip b/source4/samba4-skip index 5fa40ee706..e3e2d2d525 100644 --- a/source4/samba4-skip +++ b/source4/samba4-skip @@ -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 diff --git a/source4/scripting/python/samba/tests/dcerpc/rpcecho.py b/source4/scripting/python/samba/tests/dcerpc/rpcecho.py index 12638e2397..06790736b8 100644 --- a/source4/scripting/python/samba/tests/dcerpc/rpcecho.py +++ b/source4/scripting/python/samba/tests/dcerpc/rpcecho.py @@ -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) -- cgit From a36b6c5a42212e175ece8e9f5aa74f2741ec8868 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 16:02:09 +0200 Subject: Make Sid member variables accessible from Python. --- source4/libcli/security/security.i | 6 ++ source4/libcli/security/security.py | 4 ++ source4/libcli/security/security_wrap.c | 118 ++++++++++++++++++++++++++++++++ 3 files changed, 128 insertions(+) diff --git a/source4/libcli/security/security.i b/source4/libcli/security/security.i index 6ba106bb5f..420439d147 100644 --- a/source4/libcli/security/security.i +++ b/source4/libcli/security/security.i @@ -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); diff --git a/source4/libcli/security/security.py b/source4/libcli/security/security.py index c310dde56b..8afb3eda61 100644 --- a/source4/libcli/security/security.py +++ b/source4/libcli/security/security.py @@ -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): diff --git a/source4/libcli/security/security_wrap.c b/source4/libcli/security/security_wrap.c index b7d66b5aec..f7e3c2fb21 100644 --- a/source4/libcli/security/security_wrap.c +++ b/source4/libcli/security/security_wrap.c @@ -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}, -- cgit From 3d8323fbff85709ab64ea039044a555975821b7f Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 16:02:21 +0200 Subject: Compare sids in samba3sam tests. --- source4/dsdb/samdb/ldb_modules/tests/samba3sam.py | 32 +++++++++++++++-------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py index 882376cb09..1fc531902d 100644 --- a/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py +++ b/source4/dsdb/samdb/ldb_modules/tests/samba3sam.py @@ -27,6 +27,9 @@ import ldb from ldb import SCOPE_DEFAULT, SCOPE_BASE, SCOPE_SUBTREE from samba import Ldb, substitute_var 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") @@ -112,6 +115,18 @@ 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): @@ -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"])) @@ -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 -- cgit From 717b36c672441f8cd86bf550ab0fabc52a3a3821 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 30 Sep 2008 07:14:31 -0700 Subject: merged a bugfix for the idtree code from the Linux kernel. This matches commit 7aae6dd80e265aa9402ed507caaff4a5dba55069 in the kernel. Many thanks to Jim Houston for pointing out this fix to us --- source4/lib/util/idtree.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/source4/lib/util/idtree.c b/source4/lib/util/idtree.c index 1e2cc2976a..392f4e81f8 100644 --- a/source4/lib/util/idtree.c +++ b/source4/lib/util/idtree.c @@ -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; -- cgit From 4f07894c29996eb3e30fc79287d224ec2dbd80ee Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 30 Sep 2008 07:17:02 -0700 Subject: The author of the upstream code asked for this code to be GPLv2+ not GPLv3 --- source4/lib/util/idtree.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/lib/util/idtree.c b/source4/lib/util/idtree.c index 392f4e81f8..193922973f 100644 --- a/source4/lib/util/idtree.c +++ b/source4/lib/util/idtree.c @@ -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, -- cgit From e0af9601e1535b847e3c82e334d6a9de2ff3580d Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 16:41:21 +0200 Subject: Fix FHS flag, rename to --enable-fhs since it's a feature flag and doesn't take any arguments. --- source4/build/m4/check_path.m4 | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/source4/build/m4/check_path.m4 b/source4/build/m4/check_path.m4 index 51d5daa913..666dd3b0ae 100644 --- a/source4/build/m4/check_path.m4 +++ b/source4/build/m4/check_path.m4 @@ -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 -- cgit From 40a6a28170881e567d130c10bec700441423d1e8 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 30 Sep 2008 17:11:39 +0200 Subject: Move Samba4-specific files into source4/ --- BUGS4.txt | 24 --- NEWS4 | 508 ----------------------------------------------------------- TODO4 | 278 -------------------------------- source4/BUGS | 24 +++ source4/NEWS | 508 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ source4/TODO | 278 ++++++++++++++++++++++++++++++++ 6 files changed, 810 insertions(+), 810 deletions(-) delete mode 100644 BUGS4.txt delete mode 100644 NEWS4 delete mode 100644 TODO4 create mode 100644 source4/BUGS create mode 100644 source4/NEWS create mode 100644 source4/TODO diff --git a/BUGS4.txt b/BUGS4.txt deleted file mode 100644 index 1a9790ddd9..0000000000 --- a/BUGS4.txt +++ /dev/null @@ -1,24 +0,0 @@ -Samba4 alpha4 is not a final Samba release. That is more a reference -to Samba4's lack of the features we expect you will need than a -statement of code quality, but clearly it hasn't seen a broad -deployment yet. If you were to upgrade Samba3 (or indeed Windows) to -Samba4, you would find many things work, but that other key features -you may have relied on simply are not there yet. - -For example, while Samba 3.0 is an excellent member of a Active -Directory domain, Samba4 is happier as a domain controller, and it is -in this role where it has seen deployment into production. - -Samba4 is subjected to an awesome battery of tests on an -automated basis, we have found Samba4 to be very stable in it's -behaviour. We have to recommend against upgrading production servers -from Samba 3 to Samba 4 at this stage, because there may be the features on -which you may rely that are not present, or the mapping of -your configuration and user database may not be complete. - -If you are upgrading, or looking to develop, test or deploy Samba4, you should -backup all configuration and data. - -We welcome your testing, please file bug reports at -https://bugzilla.samba.org/, product: Samba4. Please include as much -information as possible, such as GIT revision number and backtraces. diff --git a/NEWS4 b/NEWS4 deleted file mode 100644 index 8a63719a0e..0000000000 --- a/NEWS4 +++ /dev/null @@ -1,508 +0,0 @@ -This file aims to document the major changes since the latest released version -of Samba, 3.0. Samba 4.0 contains rewrites of several subsystems -and uses a different internal format for most data. Since this -file is an initial draft, please update missing items. - -One of the main goals of Samba 4 was Active Directory Domain Controller -support. This means Samba now implements several protocols that are required -by AD such as Kerberos and DNS. - -An (experimental) upgrade script that performs a one-way upgrade -from Samba 3 is available in source/setup/upgrade. - -Removal of nmbd and introduction of process models -================================================== -smbd now implements several network protocols other than just CIFS and -DCE/RPC. nmbd's functionality has been merged into smbd. smbd supports -various 'process models' that specify how concurrent connections are -handled (when to fork, use threads, etc). - -Introduction of LDB -=================== -Samba now stores most of its persistent data in a LDAP-like database -called LDB (see ldb(7) for more info). - -Removed SWAT -================== -Unlike previous versions, Samba4 does not provide a web interface at this time. - -Built-in KDC -============ -Samba4 ships with an integrated KDC (Kerberos Key Distribution -Center). Backed directly onto our main internal database, and -integrated with custom code to handle the PAC, Samba4's KDC is an -integral part of our support for AD logon protocols. - -Built-in LDAP Server -==================== -Like the situation with the KDC, Samba4 ships with it's own LDAP -server, included to provide simple, built-in LDAP services in an AD -(rather than distinctly standards) matching manner. The database is -LDB, and it shares that in common with the rest of Samba. - -Changed configuration options -============================= -Several configuration options have been removed in Samba4 while others have -been introduced. This section contains a summary of changes to smb.conf and -where these settings moved. Configuration options that have disappeared may be -re-added later when the functionality that uses them gets reimplemented in -Samba 4. - -The 'security' parameter has been split up. It is now only used to choose -between the 'user' and 'share' security levels (the latter is not supported -in Samba 4 yet). The other values of this option and the 'domain master' and -'domain logons' parameters have been merged into a 'server role' parameter -that can be either 'domain controller', 'member server' or 'standalone'. Note that -member server support does not work yet. - -The following parameters have been removed: -- passdb backend: accounts are now stored in a LDB-based SAM database, - see 'sam database' below. -- update encrypted -- public -- guest ok -- client schannel -- server schannel -- allow trusted domains -- hosts equiv -- map to guest -- smb passwd file -- algorithmic rid base -- root directory -- root dir -- root -- guest account -- enable privileges -- pam password change -- passwd program -- passwd chat debug -- passwd chat timeout -- check password script -- username map -- username level -- unix password sync -- restrict anonymous -- username -- user -- users -- invalid users -- valid users -- admin users -- read list -- write list -- printer admin -- force user -- force group -- group -- write ok -- writeable -- writable -- acl check permissions -- acl group control -- acl map full control -- create mask -- create mode -- force create mode -- security mask -- force security mode -- directory mask -- directory mode -- force directory mode -- directory security mask -- force directory security mode -- force unknown acl user -- inherit permissions -- inherit acls -- inherit owner -- guest only -- only guest -- only user -- allow hosts -- deny hosts -- preload modules -- use kerberos keytab -- syslog -- syslog only -- max log size -- debug timestamp -- timestamp logs -- debug hires timestamp -- debug pid -- debug uid -- allocation roundup size -- aio read size -- aio write size -- aio write behind -- large readwrite -- protocol -- read bmpx -- reset on zero vc -- acl compatibility -- defer sharing violations -- ea support -- nt acl support -- nt pipe support -- profile acls -- map acl inherit -- afs share -- max ttl -- client use spnego -- enable asu support -- svcctl list -- block size -- change notify timeout -- deadtime -- getwd cache -- keepalive -- kernel change notify -- lpq cache time -- max smbd processes -- max disk size -- max open files -- min print space -- strict allocate -- sync always -- use mmap -- use sendfile -- hostname lookups -- write cache size -- name cache timeout -- max reported print jobs -- load printers -- printcap cache time -- printcap name -- printcap -- printing -- cups options -- cups server -- iprint server -- print command -- disable spoolss -- enable spoolss -- lpq command -- lprm command -- lppause command -- lpresume command -- queuepause command -- queueresume command -- enumports command -- addprinter command -- deleteprinter command -- show add printer wizard -- os2 driver map -- use client driver -- default devmode -- force printername -- mangling method -- mangle prefix -- default case -- case sensitive -- casesignames -- preserve case -- short preserve case -- mangling char -- hide dot files -- hide special files -- hide unreadable -- hide unwriteable files -- delete veto files -- veto files -- hide files -- veto oplock files -- map readonly -- mangled names -- mangled map -- max stat cache size -- stat cache -- store dos attributes -- machine password timeout -- add user script -- rename user script -- delete user script -- add group script -- delete group script -- add user to group script -- delete user from group script -- set primary group script -- add machine script -- shutdown script -- abort shutdown script -- username map script -- logon script -- logon path -- logon drive -- logon home -- domain logons -- os level -- lm announce -- lm interval -- domain master -- browse list -- enhanced browsing -- wins proxy -- wins hook -- wins partners -- blocking locks -- fake oplocks -- kernel oplocks -- locking -- lock spin count -- lock spin time -- level2 oplocks -- oplock break wait time -- oplock contention limit -- posix locking -- share modes -- ldap server -- ldap port -- ldap admin dn -- ldap delete dn -- ldap group suffix -- ldap idmap suffix -- ldap machine suffix -- ldap passwd sync -- ldap password sync -- ldap replication sleep -- ldap suffix -- ldap ssl -- ldap timeout -- ldap page size -- ldap user suffix -- add share command -- change share command -- delete share command -- eventlog list -- utmp directory -- wtmp directory -- utmp -- default service -- default -- message command -- dfree cache time -- dfree command -- get quota command -- set quota command -- remote announce -- remote browse sync -- homedir map -- afs username map -- afs token lifetime -- log nt token command -- time offset -- NIS homedir -- preexec -- exec -- preexec close -- postexec -- root preexec -- root preexec close -- root postexec -- set directory -- wide links -- follow symlinks -- dont descend -- magic script -- magic output -- delete readonly -- dos filemode -- dos filetimes -- dos filetime resolution -- fake directory create times -- panic action -- vfs objects -- vfs object -- msdfs root -- msdfs proxy -- host msdfs -- enable rid algorithm -- passdb expand explicit -- idmap backend -- idmap uid -- winbind uid -- idmap gid -- winbind gid -- template homedir -- template shell -- winbind separator -- winbind cache time -- winbind enum users -- winbind enum groups -- winbind use default domain -- winbind trusted domains only -- winbind nested groups -- winbind max idle children -- winbind nss info - -The following parameters have been added: -+ rpc big endian (G) - Make Samba fake it is running on a bigendian machine when using DCE/RPC. - Useful for debugging. - - Default: no - -+ case insensitive filesystem (S) - Set to true if this share is located on a case-insensitive filesystem. - This disables looking for a filename by trying all possible combinations of - uppercase/lowercase characters and thus speeds up operations when a - file cannot be found. - - Default: no - -+ js include (G) - Path to JavaScript library. - - Default: Set at compile-time - -+ setup directory - Path to data used by provisioning script. - - Default: Set at compile-time - -+ ncalrpc dir - Directory to use for UNIX sockets used by the 'ncalrpc' DCE/RPC transport. - - Default: Set at compile-time - -+ ntvfs handler - Backend to the NT VFS to use (more than one can be specified). Available - backends include: - - - posix: - Maps POSIX FS semantics to NT semantics - - - simple: - Very simple backend (original testing backend). - - - unixuid: - Sets up user credentials based on POSIX gid/uid. - - - cifs: - Proxies a remote CIFS FS. Mainly useful for testing. - - - nbench: - Filter module that saves data useful to the nbench benchmark suite. - - - ipc: - Allows using SMB for inter process communication. Only used for - the IPC$ share. - - - print: - Allows printing over SMB. This is LANMAN-style printing (?), not - the be confused with the spoolss DCE/RPC interface used by later - versions of Windows. - - Default: unixuid default - -+ ntptr providor - FIXME - -+ dcerpc endpoint servers - What DCE/RPC servers to start. - - Default: epmapper srvsvc wkssvc rpcecho samr netlogon lsarpc spoolss drsuapi winreg dssetup - -+ server services - Services Samba should provide. - - Default: smb rpc nbt wrepl ldap cldap web kdc - -+ sam database - Location of the SAM (account database) database. This should be a - LDB URL. - - Default: set at compile-time - -+ spoolss database - Spoolss (printer) DCE/RPC server database. This should be a LDB URL. - - Default: set at compile-time - -+ wins config database - WINS configuration database location. This should be a LDB URL. - - Default: set at compile-time - -+ wins database - WINS database location. This should be a LDB URL. - - Default: set at compile-time - -+ client use spnego principal - Tells the client to use the Kerberos service principal specified by the - server during the security protocol negotation rather than - looking up the principal itself (cifs/hostname). - - Default: false - -+ nbt port - TCP/IP Port used by the NetBIOS over TCP/IP (NBT) implementation. - - Default: 137 - -+ dgram port - UDP/IP port used by the NetBIOS over TCP/IP (NBT) implementation. - - Default: 138 - -+ cldap port - UDP/IP port used by the CLDAP protocol. - - Default: 389 - -+ krb5 port - IP port used by the kerberos KDC. - - Default: 88 - -+ kpasswd port - IP port used by the kerberos password change protocol. - - Default: 464 - -+ web port - TCP/IP port SWAT should listen on. - - Default: 901 - -+ tls enabled - Enable TLS support for SWAT - - Default: true - -+ tls keyfile - Path to TLS key file (PEM format) to be used by SWAT. If no - path is specified, Samba will create a key. - - Default: none - -+ tls certfile - Path to TLS certificate file (PEM format) to be used by SWAT. If no - path is specified, Samba will create a certificate. - - Default: none - -+ tls cafile - Path to CA authority file Samba will use to sign TLS keys it generates. If - no path is specified, Samba will create a self-signed CA certificate. - - Default: none - -+ tls crlfile - Path to TLS certificate revocation lists file. - - Default: none - -+ swat directory - SWAT data directory. - - Default: set at compile-time - -+ large readwrite - Indicate the CIFS server is able to do large reads/writes. - - Default: true - -+ unicode - Enable/disable unicode support in the protocol. - - Default: true diff --git a/TODO4 b/TODO4 deleted file mode 100644 index 14df8a507a..0000000000 --- a/TODO4 +++ /dev/null @@ -1,278 +0,0 @@ -source/build/smb_build/TODO -source/lib/registry/TODO -source/lib/tdr/TODO -source/pidl/TODO - -- seperate adminlog mechanism (as opposed to the current DEBUG log, - which is not really aimed at administrators but more at developers) - Perhaps similar to eventlog so we can also use eventlog to retrieve the data? - -- testsuite for the 'net' tool - -- and a lot of other stuff - -Configuration options -===================== - -The following options don't exist in Samba4 yet -or are not converted by the upgrade script -or will be removed: - -- update encrypted -- public -- guest ok -- client schannel -- server schannel -- allow trusted domains -- hosts equiv -- map to guest -- algorithmic rid base -- root directory -- root dir -- root -- guest account -- enable privileges -- pam password change -- passwd program -- passwd chat debug -- passwd chat timeout -- check password script -- username map -- username level -- unix password sync -- restrict anonymous -- username -- user -- users -- invalid users -- valid users -- admin users -- read list -- write list -- printer admin -- force user -- force group -- group -- write ok -- writeable -- writable -- acl check permissions -- acl group control -- acl map full control -- create mask -- create mode -- force create mode -- security mask -- force security mode -- directory mask -- directory mode -- force directory mode -- directory security mask -- force directory security mode -- force unknown acl user -- inherit permissions -- inherit acls -- inherit owner -- guest only -- only guest -- only user -- allow hosts -- deny hosts -- preload modules -- use kerberos keytab -- syslog -- syslog only -- max log size -- debug timestamp -- timestamp logs -- debug hires timestamp -- debug pid -- debug uid -- allocation roundup size -- aio read size -- aio write size -- aio write behind -- large readwrite -- protocol -- read bmpx -- reset on zero vc -- acl compatibility -- defer sharing violations -- ea support -- nt acl support -- nt pipe support -- profile acls -- map acl inherit -- afs share -- max ttl -- client use spnego -- enable asu support -- svcctl list -- block size -- change notify timeout -- deadtime -- getwd cache -- keepalive -- kernel change notify -- lpq cache time -- max smbd processes -- max disk size -- max open files -- min print space -- strict allocate -- sync always -- use mmap -- use sendfile -- hostname lookups -- write cache size -- name cache timeout -- max reported print jobs -- load printers -- printcap cache time -- printcap name -- printcap -- printing -- cups options -- cups server -- iprint server -- print command -- disable spoolss -- enable spoolss -- lpq command -- lprm command -- lppause command -- lpresume command -- queuepause command -- queueresume command -- enumports command -- addprinter command -- deleteprinter command -- show add printer wizard -- os2 driver map -- use client driver -- default devmode -- force printername -- mangling method -- mangle prefix -- default case -- case sensitive -- casesignames -- preserve case -- short preserve case -- mangling char -- hide dot files -- hide special files -- hide unreadable -- hide unwriteable files -- delete veto files -- veto files -- hide files -- veto oplock files -- map readonly -- mangled names -- mangled map -- max stat cache size -- stat cache -- store dos attributes -- machine password timeout -- add user script -- rename user script -- delete user script -- add group script -- delete group script -- add user to group script -- delete user from group script -- set primary group script -- add machine script -- shutdown script -- abort shutdown script -- username map script -- logon script -- logon path -- logon drive -- logon home -- domain logons -- os level -- lm announce -- lm interval -- domain master -- browse list -- enhanced browsing -- wins proxy -- blocking locks -- fake oplocks -- kernel oplocks -- locking -- lock spin count -- lock spin time -- oplocks -- level2 oplocks -- oplock break wait time -- oplock contention limit -- posix locking -- share modes -- add share command -- change share command -- delete share command -- eventlog list -- utmp directory -- wtmp directory -- utmp -- default service -- default -- message command -- dfree cache time -- dfree command -- get quota command -- set quota command -- remote announce -- remote browse sync -- homedir map -- afs username map -- afs token lifetime -- log nt token command -- time offset -- NIS homedir -- preexec -- exec -- preexec close -- postexec -- root preexec -- root preexec close -- root postexec -- set directory -- wide links -- follow symlinks -- dont descend -- magic script -- magic output -- delete readonly -- dos filemode -- dos filetimes -- dos filetime resolution -- fake directory create times -- panic action -- vfs objects -- vfs object -- msdfs root -- msdfs proxy -- host msdfs -- enable rid algorithm -- passdb expand explicit -- idmap backend -- idmap uid -- winbind uid -- idmap gid -- winbind gid -- template homedir -- template shell -- winbind separator -- winbind cache time -- winbind enum users -- winbind enum groups -- winbind use default domain -- winbind trusted domains only -- winbind nested groups -- winbind max idle children -- winbind nss info - diff --git a/source4/BUGS b/source4/BUGS new file mode 100644 index 0000000000..1a9790ddd9 --- /dev/null +++ b/source4/BUGS @@ -0,0 +1,24 @@ +Samba4 alpha4 is not a final Samba release. That is more a reference +to Samba4's lack of the features we expect you will need than a +statement of code quality, but clearly it hasn't seen a broad +deployment yet. If you were to upgrade Samba3 (or indeed Windows) to +Samba4, you would find many things work, but that other key features +you may have relied on simply are not there yet. + +For example, while Samba 3.0 is an excellent member of a Active +Directory domain, Samba4 is happier as a domain controller, and it is +in this role where it has seen deployment into production. + +Samba4 is subjected to an awesome battery of tests on an +automated basis, we have found Samba4 to be very stable in it's +behaviour. We have to recommend against upgrading production servers +from Samba 3 to Samba 4 at this stage, because there may be the features on +which you may rely that are not present, or the mapping of +your configuration and user database may not be complete. + +If you are upgrading, or looking to develop, test or deploy Samba4, you should +backup all configuration and data. + +We welcome your testing, please file bug reports at +https://bugzilla.samba.org/, product: Samba4. Please include as much +information as possible, such as GIT revision number and backtraces. diff --git a/source4/NEWS b/source4/NEWS new file mode 100644 index 0000000000..8a63719a0e --- /dev/null +++ b/source4/NEWS @@ -0,0 +1,508 @@ +This file aims to document the major changes since the latest released version +of Samba, 3.0. Samba 4.0 contains rewrites of several subsystems +and uses a different internal format for most data. Since this +file is an initial draft, please update missing items. + +One of the main goals of Samba 4 was Active Directory Domain Controller +support. This means Samba now implements several protocols that are required +by AD such as Kerberos and DNS. + +An (experimental) upgrade script that performs a one-way upgrade +from Samba 3 is available in source/setup/upgrade. + +Removal of nmbd and introduction of process models +================================================== +smbd now implements several network protocols other than just CIFS and +DCE/RPC. nmbd's functionality has been merged into smbd. smbd supports +various 'process models' that specify how concurrent connections are +handled (when to fork, use threads, etc). + +Introduction of LDB +=================== +Samba now stores most of its persistent data in a LDAP-like database +called LDB (see ldb(7) for more info). + +Removed SWAT +================== +Unlike previous versions, Samba4 does not provide a web interface at this time. + +Built-in KDC +============ +Samba4 ships with an integrated KDC (Kerberos Key Distribution +Center). Backed directly onto our main internal database, and +integrated with custom code to handle the PAC, Samba4's KDC is an +integral part of our support for AD logon protocols. + +Built-in LDAP Server +==================== +Like the situation with the KDC, Samba4 ships with it's own LDAP +server, included to provide simple, built-in LDAP services in an AD +(rather than distinctly standards) matching manner. The database is +LDB, and it shares that in common with the rest of Samba. + +Changed configuration options +============================= +Several configuration options have been removed in Samba4 while others have +been introduced. This section contains a summary of changes to smb.conf and +where these settings moved. Configuration options that have disappeared may be +re-added later when the functionality that uses them gets reimplemented in +Samba 4. + +The 'security' parameter has been split up. It is now only used to choose +between the 'user' and 'share' security levels (the latter is not supported +in Samba 4 yet). The other values of this option and the 'domain master' and +'domain logons' parameters have been merged into a 'server role' parameter +that can be either 'domain controller', 'member server' or 'standalone'. Note that +member server support does not work yet. + +The following parameters have been removed: +- passdb backend: accounts are now stored in a LDB-based SAM database, + see 'sam database' below. +- update encrypted +- public +- guest ok +- client schannel +- server schannel +- allow trusted domains +- hosts equiv +- map to guest +- smb passwd file +- algorithmic rid base +- root directory +- root dir +- root +- guest account +- enable privileges +- pam password change +- passwd program +- passwd chat debug +- passwd chat timeout +- check password script +- username map +- username level +- unix password sync +- restrict anonymous +- username +- user +- users +- invalid users +- valid users +- admin users +- read list +- write list +- printer admin +- force user +- force group +- group +- write ok +- writeable +- writable +- acl check permissions +- acl group control +- acl map full control +- create mask +- create mode +- force create mode +- security mask +- force security mode +- directory mask +- directory mode +- force directory mode +- directory security mask +- force directory security mode +- force unknown acl user +- inherit permissions +- inherit acls +- inherit owner +- guest only +- only guest +- only user +- allow hosts +- deny hosts +- preload modules +- use kerberos keytab +- syslog +- syslog only +- max log size +- debug timestamp +- timestamp logs +- debug hires timestamp +- debug pid +- debug uid +- allocation roundup size +- aio read size +- aio write size +- aio write behind +- large readwrite +- protocol +- read bmpx +- reset on zero vc +- acl compatibility +- defer sharing violations +- ea support +- nt acl support +- nt pipe support +- profile acls +- map acl inherit +- afs share +- max ttl +- client use spnego +- enable asu support +- svcctl list +- block size +- change notify timeout +- deadtime +- getwd cache +- keepalive +- kernel change notify +- lpq cache time +- max smbd processes +- max disk size +- max open files +- min print space +- strict allocate +- sync always +- use mmap +- use sendfile +- hostname lookups +- write cache size +- name cache timeout +- max reported print jobs +- load printers +- printcap cache time +- printcap name +- printcap +- printing +- cups options +- cups server +- iprint server +- print command +- disable spoolss +- enable spoolss +- lpq command +- lprm command +- lppause command +- lpresume command +- queuepause command +- queueresume command +- enumports command +- addprinter command +- deleteprinter command +- show add printer wizard +- os2 driver map +- use client driver +- default devmode +- force printername +- mangling method +- mangle prefix +- default case +- case sensitive +- casesignames +- preserve case +- short preserve case +- mangling char +- hide dot files +- hide special files +- hide unreadable +- hide unwriteable files +- delete veto files +- veto files +- hide files +- veto oplock files +- map readonly +- mangled names +- mangled map +- max stat cache size +- stat cache +- store dos attributes +- machine password timeout +- add user script +- rename user script +- delete user script +- add group script +- delete group script +- add user to group script +- delete user from group script +- set primary group script +- add machine script +- shutdown script +- abort shutdown script +- username map script +- logon script +- logon path +- logon drive +- logon home +- domain logons +- os level +- lm announce +- lm interval +- domain master +- browse list +- enhanced browsing +- wins proxy +- wins hook +- wins partners +- blocking locks +- fake oplocks +- kernel oplocks +- locking +- lock spin count +- lock spin time +- level2 oplocks +- oplock break wait time +- oplock contention limit +- posix locking +- share modes +- ldap server +- ldap port +- ldap admin dn +- ldap delete dn +- ldap group suffix +- ldap idmap suffix +- ldap machine suffix +- ldap passwd sync +- ldap password sync +- ldap replication sleep +- ldap suffix +- ldap ssl +- ldap timeout +- ldap page size +- ldap user suffix +- add share command +- change share command +- delete share command +- eventlog list +- utmp directory +- wtmp directory +- utmp +- default service +- default +- message command +- dfree cache time +- dfree command +- get quota command +- set quota command +- remote announce +- remote browse sync +- homedir map +- afs username map +- afs token lifetime +- log nt token command +- time offset +- NIS homedir +- preexec +- exec +- preexec close +- postexec +- root preexec +- root preexec close +- root postexec +- set directory +- wide links +- follow symlinks +- dont descend +- magic script +- magic output +- delete readonly +- dos filemode +- dos filetimes +- dos filetime resolution +- fake directory create times +- panic action +- vfs objects +- vfs object +- msdfs root +- msdfs proxy +- host msdfs +- enable rid algorithm +- passdb expand explicit +- idmap backend +- idmap uid +- winbind uid +- idmap gid +- winbind gid +- template homedir +- template shell +- winbind separator +- winbind cache time +- winbind enum users +- winbind enum groups +- winbind use default domain +- winbind trusted domains only +- winbind nested groups +- winbind max idle children +- winbind nss info + +The following parameters have been added: ++ rpc big endian (G) + Make Samba fake it is running on a bigendian machine when using DCE/RPC. + Useful for debugging. + + Default: no + ++ case insensitive filesystem (S) + Set to true if this share is located on a case-insensitive filesystem. + This disables looking for a filename by trying all possible combinations of + uppercase/lowercase characters and thus speeds up operations when a + file cannot be found. + + Default: no + ++ js include (G) + Path to JavaScript library. + + Default: Set at compile-time + ++ setup directory + Path to data used by provisioning script. + + Default: Set at compile-time + ++ ncalrpc dir + Directory to use for UNIX sockets used by the 'ncalrpc' DCE/RPC transport. + + Default: Set at compile-time + ++ ntvfs handler + Backend to the NT VFS to use (more than one can be specified). Available + backends include: + + - posix: + Maps POSIX FS semantics to NT semantics + + - simple: + Very simple backend (original testing backend). + + - unixuid: + Sets up user credentials based on POSIX gid/uid. + + - cifs: + Proxies a remote CIFS FS. Mainly useful for testing. + + - nbench: + Filter module that saves data useful to the nbench benchmark suite. + + - ipc: + Allows using SMB for inter process communication. Only used for + the IPC$ share. + + - print: + Allows printing over SMB. This is LANMAN-style printing (?), not + the be confused with the spoolss DCE/RPC interface used by later + versions of Windows. + + Default: unixuid default + ++ ntptr providor + FIXME + ++ dcerpc endpoint servers + What DCE/RPC servers to start. + + Default: epmapper srvsvc wkssvc rpcecho samr netlogon lsarpc spoolss drsuapi winreg dssetup + ++ server services + Services Samba should provide. + + Default: smb rpc nbt wrepl ldap cldap web kdc + ++ sam database + Location of the SAM (account database) database. This should be a + LDB URL. + + Default: set at compile-time + ++ spoolss database + Spoolss (printer) DCE/RPC server database. This should be a LDB URL. + + Default: set at compile-time + ++ wins config database + WINS configuration database location. This should be a LDB URL. + + Default: set at compile-time + ++ wins database + WINS database location. This should be a LDB URL. + + Default: set at compile-time + ++ client use spnego principal + Tells the client to use the Kerberos service principal specified by the + server during the security protocol negotation rather than + looking up the principal itself (cifs/hostname). + + Default: false + ++ nbt port + TCP/IP Port used by the NetBIOS over TCP/IP (NBT) implementation. + + Default: 137 + ++ dgram port + UDP/IP port used by the NetBIOS over TCP/IP (NBT) implementation. + + Default: 138 + ++ cldap port + UDP/IP port used by the CLDAP protocol. + + Default: 389 + ++ krb5 port + IP port used by the kerberos KDC. + + Default: 88 + ++ kpasswd port + IP port used by the kerberos password change protocol. + + Default: 464 + ++ web port + TCP/IP port SWAT should listen on. + + Default: 901 + ++ tls enabled + Enable TLS support for SWAT + + Default: true + ++ tls keyfile + Path to TLS key file (PEM format) to be used by SWAT. If no + path is specified, Samba will create a key. + + Default: none + ++ tls certfile + Path to TLS certificate file (PEM format) to be used by SWAT. If no + path is specified, Samba will create a certificate. + + Default: none + ++ tls cafile + Path to CA authority file Samba will use to sign TLS keys it generates. If + no path is specified, Samba will create a self-signed CA certificate. + + Default: none + ++ tls crlfile + Path to TLS certificate revocation lists file. + + Default: none + ++ swat directory + SWAT data directory. + + Default: set at compile-time + ++ large readwrite + Indicate the CIFS server is able to do large reads/writes. + + Default: true + ++ unicode + Enable/disable unicode support in the protocol. + + Default: true diff --git a/source4/TODO b/source4/TODO new file mode 100644 index 0000000000..5efebed1b3 --- /dev/null +++ b/source4/TODO @@ -0,0 +1,278 @@ +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) + Perhaps similar to eventlog so we can also use eventlog to retrieve the data? + +- testsuite for the 'net' tool + +- and a lot of other stuff + +Configuration options +===================== + +The following options don't exist in Samba4 yet +or are not converted by the upgrade script +or will be removed: + +- update encrypted +- public +- guest ok +- client schannel +- server schannel +- allow trusted domains +- hosts equiv +- map to guest +- algorithmic rid base +- root directory +- root dir +- root +- guest account +- enable privileges +- pam password change +- passwd program +- passwd chat debug +- passwd chat timeout +- check password script +- username map +- username level +- unix password sync +- restrict anonymous +- username +- user +- users +- invalid users +- valid users +- admin users +- read list +- write list +- printer admin +- force user +- force group +- group +- write ok +- writeable +- writable +- acl check permissions +- acl group control +- acl map full control +- create mask +- create mode +- force create mode +- security mask +- force security mode +- directory mask +- directory mode +- force directory mode +- directory security mask +- force directory security mode +- force unknown acl user +- inherit permissions +- inherit acls +- inherit owner +- guest only +- only guest +- only user +- allow hosts +- deny hosts +- preload modules +- use kerberos keytab +- syslog +- syslog only +- max log size +- debug timestamp +- timestamp logs +- debug hires timestamp +- debug pid +- debug uid +- allocation roundup size +- aio read size +- aio write size +- aio write behind +- large readwrite +- protocol +- read bmpx +- reset on zero vc +- acl compatibility +- defer sharing violations +- ea support +- nt acl support +- nt pipe support +- profile acls +- map acl inherit +- afs share +- max ttl +- client use spnego +- enable asu support +- svcctl list +- block size +- change notify timeout +- deadtime +- getwd cache +- keepalive +- kernel change notify +- lpq cache time +- max smbd processes +- max disk size +- max open files +- min print space +- strict allocate +- sync always +- use mmap +- use sendfile +- hostname lookups +- write cache size +- name cache timeout +- max reported print jobs +- load printers +- printcap cache time +- printcap name +- printcap +- printing +- cups options +- cups server +- iprint server +- print command +- disable spoolss +- enable spoolss +- lpq command +- lprm command +- lppause command +- lpresume command +- queuepause command +- queueresume command +- enumports command +- addprinter command +- deleteprinter command +- show add printer wizard +- os2 driver map +- use client driver +- default devmode +- force printername +- mangling method +- mangle prefix +- default case +- case sensitive +- casesignames +- preserve case +- short preserve case +- mangling char +- hide dot files +- hide special files +- hide unreadable +- hide unwriteable files +- delete veto files +- veto files +- hide files +- veto oplock files +- map readonly +- mangled names +- mangled map +- max stat cache size +- stat cache +- store dos attributes +- machine password timeout +- add user script +- rename user script +- delete user script +- add group script +- delete group script +- add user to group script +- delete user from group script +- set primary group script +- add machine script +- shutdown script +- abort shutdown script +- username map script +- logon script +- logon path +- logon drive +- logon home +- domain logons +- os level +- lm announce +- lm interval +- domain master +- browse list +- enhanced browsing +- wins proxy +- blocking locks +- fake oplocks +- kernel oplocks +- locking +- lock spin count +- lock spin time +- oplocks +- level2 oplocks +- oplock break wait time +- oplock contention limit +- posix locking +- share modes +- add share command +- change share command +- delete share command +- eventlog list +- utmp directory +- wtmp directory +- utmp +- default service +- default +- message command +- dfree cache time +- dfree command +- get quota command +- set quota command +- remote announce +- remote browse sync +- homedir map +- afs username map +- afs token lifetime +- log nt token command +- time offset +- NIS homedir +- preexec +- exec +- preexec close +- postexec +- root preexec +- root preexec close +- root postexec +- set directory +- wide links +- follow symlinks +- dont descend +- magic script +- magic output +- delete readonly +- dos filemode +- dos filetimes +- dos filetime resolution +- fake directory create times +- panic action +- vfs objects +- vfs object +- msdfs root +- msdfs proxy +- host msdfs +- enable rid algorithm +- passdb expand explicit +- idmap backend +- idmap uid +- winbind uid +- idmap gid +- winbind gid +- template homedir +- template shell +- winbind separator +- winbind cache time +- winbind enum users +- winbind enum groups +- winbind use default domain +- winbind trusted domains only +- winbind nested groups +- winbind max idle children +- winbind nss info + -- cgit From be050125b60028ab05dfd685291d2163c2e5903a Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 30 Sep 2008 08:42:12 -0700 Subject: - make bcast name resolution match other name resolution modules for host not found errors - when we have no resolve context return NT_STATUS_OBJECT_NAME_NOT_FOUND --- source4/libcli/resolve/bcast.c | 8 +++++++- source4/libcli/resolve/resolve.c | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/source4/libcli/resolve/bcast.c b/source4/libcli/resolve/bcast.c index 2e2eb05397..ca78a2ce43 100644 --- a/source4/libcli/resolve/bcast.c +++ b/source4/libcli/resolve/bcast.c @@ -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; } /* diff --git a/source4/libcli/resolve/resolve.c b/source4/libcli/resolve/resolve.c index 2b14591d68..dbc4a2ede7 100644 --- a/source4/libcli/resolve/resolve.c +++ b/source4/libcli/resolve/resolve.c @@ -166,7 +166,7 @@ struct composite_context *resolve_name_send(struct resolve_context *ctx, state->method = ctx->methods; if (state->method == NULL) { - composite_error(c, NT_STATUS_HOST_UNREACHABLE); + composite_error(c, NT_STATUS_BAD_NETWORK_NAME); return c; } state->creq = setup_next_method(c); -- cgit From dab5d4abbce7fc54427e5eb130e36860ffa74685 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 30 Sep 2008 08:44:06 -0700 Subject: cope with NULL attr --- source4/rpc_server/lsa/lsa_init.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source4/rpc_server/lsa/lsa_init.c b/source4/rpc_server/lsa/lsa_init.c index a95cb10f9f..8d8417109f 100644 --- a/source4/rpc_server/lsa/lsa_init.c +++ b/source4/rpc_server/lsa/lsa_init.c @@ -199,7 +199,7 @@ NTSTATUS dcesrv_lsa_OpenPolicy2(struct dcesrv_call_state *dce_call, TALLOC_CTX * ZERO_STRUCTP(r->out.handle); - if (r->in.attr == NULL || + if (r->in.attr != NULL && r->in.attr->root_dir != NULL) { /* MS-LSAD 3.1.4.4.1 */ return NT_STATUS_INVALID_PARAMETER; @@ -217,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; -- cgit From ef6fc37add1fd9164eb143c953fde0d5a9fc584a Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 30 Sep 2008 08:44:31 -0700 Subject: check call status not rpc fault code when calling to different levels of calls --- source4/rpc_server/lsa/lsa_lookup.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source4/rpc_server/lsa/lsa_lookup.c b/source4/rpc_server/lsa/lsa_lookup.c index 7bf7d849b7..a71bd57516 100644 --- a/source4/rpc_server/lsa/lsa_lookup.c +++ b/source4/rpc_server/lsa/lsa_lookup.c @@ -649,7 +649,7 @@ 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) { + if (NT_STATUS_IS_ERR(status)) { return status; } @@ -682,7 +682,7 @@ 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) { + if (NT_STATUS_IS_ERR(status)) { return status; } @@ -836,7 +836,7 @@ NTSTATUS dcesrv_lsa_LookupNames4(struct dcesrv_call_state *dce_call, TALLOC_CTX r2.out.count = r->out.count; status = dcesrv_lsa_LookupNames3(dce_call, mem_ctx, &r2); - if (dce_call->fault_code != 0) { + if (NT_STATUS_IS_ERR(status)) { return status; } @@ -955,7 +955,7 @@ NTSTATUS dcesrv_lsa_LookupNames(struct dcesrv_call_state *dce_call, TALLOC_CTX * r2.out.count = r->out.count; status = dcesrv_lsa_LookupNames2(dce_call, mem_ctx, &r2); - if (dce_call->fault_code != 0) { + if (NT_STATUS_IS_ERR(status)) { return status; } -- cgit From ee97097783aa146b0b2f88c15f3764a420797e1a Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Tue, 30 Sep 2008 18:10:04 +0200 Subject: Use UTF8 rather than the possibly different UNIX charset. --- source4/lib/registry/tests/generic.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source4/lib/registry/tests/generic.c b/source4/lib/registry/tests/generic.c index 6eae26bc46..2b7eb838ba 100644 --- a/source4/lib/registry/tests/generic.c +++ b/source4/lib/registry/tests/generic.c @@ -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); -- cgit From a238f17e2785da4f11411c6a4dd20fdcb3c349b6 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Tue, 30 Sep 2008 12:33:00 -0700 Subject: Add in test name visible on the wire or in debug logs so you can see when particular tests start. Jeremy. --- source4/torture/raw/notify.c | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/source4/torture/raw/notify.c b/source4/torture/raw/notify.c index 25c91eb88b..14ee23158a 100644 --- a/source4/torture/raw/notify.c +++ b/source4/torture/raw/notify.c @@ -583,7 +583,8 @@ 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) \ + smbcli_unlink(cli->tree, test_name); \ do { for (mask=i=0;i<32;i++) { \ struct smbcli_request *req; \ status = smb_raw_open(cli->tree, tctx, &io); \ @@ -643,21 +644,21 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t } 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 +666,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 +674,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 +682,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 +690,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 +698,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 +706,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 +719,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 +730,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 +738,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 +746,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 +755,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 +763,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"));, -- cgit From 687ce0b60a3913b0f2eca2365a5ab56e78523ab5 Mon Sep 17 00:00:00 2001 From: root Date: Tue, 30 Sep 2008 12:44:24 -0700 Subject: Use a getatr instead to make things cleaner. Jeremy. --- source4/torture/raw/notify.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/source4/torture/raw/notify.c b/source4/torture/raw/notify.c index 14ee23158a..d7541b7c71 100644 --- a/source4/torture/raw/notify.c +++ b/source4/torture/raw/notify.c @@ -584,7 +584,8 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t notify.nttrans.in.recursive = true; #define NOTIFY_MASK_TEST(test_name, setup, op, cleanup, Action, expected, nchanges) \ - smbcli_unlink(cli->tree, test_name); \ + 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); \ @@ -641,7 +642,8 @@ 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("testing mkdir",;, -- cgit From 97d57d03640664416500efb1f1cf8e5a4a9522d8 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Tue, 30 Sep 2008 13:26:41 -0700 Subject: Fix the make test problem Karolin reported. Now rename_open_files actually works correctly we must emit the change notify before we change the name, not before. Jeremy. --- source3/smbd/reply.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source3/smbd/reply.c b/source3/smbd/reply.c index 6933533672..8bfa28faea 100644 --- a/source3/smbd/reply.c +++ b/source3/smbd/reply.c @@ -5583,10 +5583,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 -- cgit From 69fe3a5ddd6af872bc686ff2161b9b6a5e5c62a2 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 30 Sep 2008 13:42:30 -0700 Subject: fixed a number of places in our LSA server where we should return the sid/name array even when all are unmapped. If we don't fill in the array then the windows client runtime crashes --- source4/librpc/idl/lsa.idl | 2 +- source4/rpc_server/lsa/lsa_lookup.c | 24 +++++++++++++----------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/source4/librpc/idl/lsa.idl b/source4/librpc/idl/lsa.idl index eed713f71c..e1c4499022 100644 --- a/source4/librpc/idl/lsa.idl +++ b/source4/librpc/idl/lsa.idl @@ -1052,7 +1052,7 @@ import "misc.idl", "security.idl"; lsa_SidType sid_type; dom_sid2 *sid; uint32 sid_index; - uint32 unknown; + uint32 flags; } lsa_TranslatedSid3; typedef struct { diff --git a/source4/rpc_server/lsa/lsa_lookup.c b/source4/rpc_server/lsa/lsa_lookup.c index a71bd57516..0ffb0572ee 100644 --- a/source4/rpc_server/lsa/lsa_lookup.c +++ b/source4/rpc_server/lsa/lsa_lookup.c @@ -620,6 +620,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) { @@ -649,9 +651,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 (NT_STATUS_IS_ERR(status)) { - return status; - } r->out.domains = r2.out.domains; r->out.names = r2.out.names; @@ -671,6 +670,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; @@ -761,7 +762,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) { @@ -771,13 +772,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)++; } @@ -806,6 +807,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) { @@ -836,9 +839,6 @@ NTSTATUS dcesrv_lsa_LookupNames4(struct dcesrv_call_state *dce_call, TALLOC_CTX r2.out.count = r->out.count; status = dcesrv_lsa_LookupNames3(dce_call, mem_ctx, &r2); - if (NT_STATUS_IS_ERR(status)) { - return status; - } r->out.domains = r2.out.domains; r->out.sids = r2.out.sids; @@ -913,7 +913,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; @@ -944,6 +944,8 @@ 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; @@ -955,7 +957,7 @@ NTSTATUS dcesrv_lsa_LookupNames(struct dcesrv_call_state *dce_call, TALLOC_CTX * r2.out.count = r->out.count; status = dcesrv_lsa_LookupNames2(dce_call, mem_ctx, &r2); - if (NT_STATUS_IS_ERR(status)) { + if (r2.out.sids == NULL) { return status; } -- cgit From 2c978bbfa92b7fe29c17e40ad6d8059814b78399 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 30 Sep 2008 13:57:23 -0700 Subject: handle NULL strings in strchr_m() and strrchr_m() This is needed for the LSA server code which needs to cope with a NULL names passed to lsa_LookupNames3() --- source4/lib/charset/util_unistr.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/source4/lib/charset/util_unistr.c b/source4/lib/charset/util_unistr.c index a8ff88423a..5f3b2c53f1 100644 --- a/source4/lib/charset/util_unistr.c +++ b/source4/lib/charset/util_unistr.c @@ -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) { -- cgit From 14378d7c4cfff171e7c005c210abe253a2d7dea3 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Tue, 30 Sep 2008 14:03:01 -0700 Subject: add a test for a LSA lookupnames with a NULL string --- source4/torture/rpc/lsa.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/source4/torture/rpc/lsa.c b/source4/torture/rpc/lsa.c index af5ee4f6e1..45f67afd69 100644 --- a/source4/torture/rpc/lsa.c +++ b/source4/torture/rpc/lsa.c @@ -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"); -- cgit From 321191d5e2ec1eaf22728dcee944e0a250a7725d Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Tue, 30 Sep 2008 15:13:19 -0700 Subject: Restructure the module so it connects to the remote data sink on connect, and closes the socket on client disconnect. This should make it much more efficient. Store the remote fd in a private data pointer off the handle. Finally we need to remove the fstrings and convert to allocated buffer storage. Jeremy. --- source3/modules/vfs_smb_traffic_analyzer.c | 306 +++++++++++++++-------------- 1 file changed, 156 insertions(+), 150 deletions(-) diff --git a/source3/modules/vfs_smb_traffic_analyzer.c b/source3/modules/vfs_smb_traffic_analyzer.c index 9e4cf81638..cd843e6ad4 100644 --- a/source3/modules/vfs_smb_traffic_analyzer.c +++ b/source3/modules/vfs_smb_traffic_analyzer.c @@ -31,67 +31,8 @@ extern userdom_struct current_user_info; static int vfs_smb_traffic_analyzer_debug_level = DBGC_VFS; -NTSTATUS vfs_smb_traffic_analyzer_init(void); - -static ssize_t smb_traffic_analyzer_write(vfs_handle_struct *handle, - files_struct *fsp, const void *data, size_t n); - -static ssize_t smb_traffic_analyzer_read(vfs_handle_struct *handle, - files_struct *fsp, void *data, size_t n); - -static ssize_t smb_traffic_analyzer_pwrite(vfs_handle_struct *handle, - files_struct *fsp, const void *data, size_t n, - SMB_OFF_T offset); - -static ssize_t smb_traffic_analyzer_pread(vfs_handle_struct *handle, - files_struct *fsp, void *data, size_t n, SMB_OFF_T offset); - - -/* VFS operations we use */ - -static vfs_op_tuple smb_traffic_analyzer_tuples[] = { - - {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: Couldn't register custom" - "debugging class!\n")); - } else { - DEBUG(3, ("smb_traffic_analyzer: Debug class number of" - "'smb_traffic_analyzer': %d\n", \ - vfs_smb_traffic_analyzer_debug_level)); - } - - return ret; -} - /* create the timestamp in sqlite compatible format */ -static void get_timestamp( char *String ) +static void get_timestamp(fstring str) { struct timeval tv; struct timezone tz; @@ -102,13 +43,13 @@ static void get_timestamp( char *String ) tm=localtime(&tv.tv_sec); seconds=(float) (tv.tv_usec / 1000); - fstr_sprintf(String,"%04d-%02d-%02d %02d:%02d:%02d.%03d", \ + fstr_sprintf(str,"%04d-%02d-%02d %02d:%02d:%02d.%03d", \ tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, \ tm->tm_hour, tm->tm_min, tm->tm_sec, (int)seconds); } -static int smb_traffic_analyzer_connMode( vfs_handle_struct *handle) +static int smb_traffic_analyzer_connMode(vfs_handle_struct *handle) { connection_struct *conn = handle->conn; const char *Mode; @@ -122,10 +63,9 @@ static int smb_traffic_analyzer_connMode( vfs_handle_struct *handle) } -/* Send data over a internet socket */ -static void smb_traffic_analyzer_send_data_inet_socket( char *String, - vfs_handle_struct *handle, const char *file_name, - bool Write) +/* Connect to an internet socket */ + +static int smb_traffic_analyzer_connect_inet_socket(vfs_handle_struct *handle) { /* Create a streaming Socket */ const char *Hostname; @@ -134,13 +74,11 @@ static void smb_traffic_analyzer_send_data_inet_socket( char *String, struct addrinfo hints; struct addrinfo *ailist = NULL; struct addrinfo *res = NULL; - char Sender[200]; - char TimeStamp[200]; connection_struct *conn = handle->conn; int ret; /* get port number, target system from the config parameters */ - Hostname=lp_parm_const_string(SNUM(conn), "smb_traffic_analyzer", + Hostname=lp_parm_const_string(SNUM(conn), "smb_traffic_analyzer", "host", "localhost"); ZERO_STRUCT(hints); @@ -154,14 +92,14 @@ static void smb_traffic_analyzer_send_data_inet_socket( char *String, &ailist); if (ret) { - DEBUG(3,("smb_traffic_analyzer_send_data_inet_socket: " + DEBUG(3,("smb_traffic_analyzer_connect_inet_socket: " "getaddrinfo failed for name %s [%s]\n", Hostname, gai_strerror(ret) )); - return; + return -1; } - port = atoi( lp_parm_const_string(SNUM(conn), + port = atoi( lp_parm_const_string(SNUM(conn), "smb_traffic_analyzer", "port", "9430")); DEBUG(3,("smb_traffic_analyzer: Internet socket mode. Hostname: %s," @@ -188,116 +126,129 @@ static void smb_traffic_analyzer_send_data_inet_socket( char *String, } if (sockfd == -1) { - DEBUG(1, ("smb_traffic_analyzer: unable to create socket, error is %s", + DEBUG(1, ("smb_traffic_analyzer: unable to create " + "socket, error is %s", strerror(errno))); - return; + return -1; } - strlcpy(Sender, String, sizeof(Sender)); - strlcat(Sender, ",\"", sizeof(Sender)); - strlcat(Sender, get_current_username(), sizeof(Sender)); - strlcat(Sender, "\",\"", sizeof(Sender)); - strlcat(Sender, current_user_info.domain, sizeof(Sender)); - strlcat(Sender, "\",\"", sizeof(Sender)); - if (Write) - strlcat(Sender, "W", sizeof(Sender)); - else - strlcat(Sender, "R", sizeof(Sender)); - strlcat(Sender, "\",\"", sizeof(Sender)); - strlcat(Sender, handle->conn->connectpath, sizeof(Sender)); - strlcat(Sender, "\",\"", sizeof(Sender) - 1); - strlcat(Sender, file_name, sizeof(Sender) - 1); - strlcat(Sender, "\",\"", sizeof(Sender) - 1); - get_timestamp(TimeStamp); - strlcat(Sender, TimeStamp, sizeof(Sender) - 1); - strlcat(Sender, "\");", sizeof(Sender) - 1); - DEBUG(10, ("smb_traffic_analyzer: sending %s\n", Sender)); - if ( send(sockfd, Sender, strlen(Sender), 0) == -1 ) { - DEBUG(1, ("smb_traffic_analyzer: error sending data to socket!\n")); - close(sockfd); - return ; - } - - /* one operation, close the socket */ - close(sockfd); + return sockfd; } +/* Connect to a unix domain socket */ - -/* Send data over a unix domain socket */ -static void smb_traffic_analyzer_send_data_unix_socket( char *String , - vfs_handle_struct *handle, const char *file_name, - bool Write) +static int smb_traffic_analyzer_connect_unix_socket(vfs_handle_struct *handle) { /* Create the socket to stad */ int len, sock; struct sockaddr_un remote; - char Sender[200]; - char TimeStamp[200]; - DEBUG(7, ("smb_traffic_analyzer: Unix domain socket mode. Using " + DEBUG(7, ("smb_traffic_analyzer_connect_unix_socket: " + "Unix domain socket mode. Using " "/var/tmp/stadsocket\n")); if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { - DEBUG(1, ("smb_traffic_analyzer: Couldn create socket," + 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, "/var/tmp/stadsocket", + strlcpy(remote.sun_path, "/var/tmp/stadsocket", 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: Could not connect to" + 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; +} + +/* Send data over a socket */ + +static void smb_traffic_analyzer_send_data(vfs_handle_struct *handle, + char *str, + const char *file_name, + bool Write) +{ + int *psockfd = NULL; + char Sender[200]; + char TimeStamp[200]; + + SMB_VFS_HANDLE_GET_DATA(handle, psockfd, int, return); + + if (psockfd == NULL || *psockfd == -1) { + DEBUG(1, ("smb_traffic_analyzer_send_data: socket is " + "closed\n")); return; } - strlcpy(Sender, String, sizeof(Sender)); + + strlcpy(Sender, str, sizeof(Sender)); strlcat(Sender, ",\"", sizeof(Sender)); strlcat(Sender, get_current_username(), sizeof(Sender)); - strlcat(Sender,"\",\"",sizeof(Sender)); + strlcat(Sender, "\",\"", sizeof(Sender)); strlcat(Sender, current_user_info.domain, sizeof(Sender)); strlcat(Sender, "\",\"", sizeof(Sender)); - if (Write) + if (Write) strlcat(Sender, "W", sizeof(Sender)); else strlcat(Sender, "R", sizeof(Sender)); strlcat(Sender, "\",\"", sizeof(Sender)); strlcat(Sender, handle->conn->connectpath, sizeof(Sender)); - strlcat(Sender, "\",\"", sizeof(Sender)); - strlcat(Sender, file_name, sizeof(Sender)); - strlcat(Sender, "\",\"", sizeof(Sender)); - get_timestamp(TimeStamp); - strlcat(Sender, TimeStamp, sizeof(Sender)); - strlcat(Sender, "\");", sizeof(Sender)); - - DEBUG(10, ("smb_traffic_analyzer: sending %s\n", Sender)); - if ( send(sock, Sender, strlen(Sender), 0) == -1 ) { - DEBUG(1, ("smb_traffic_analyzer: error sending data to" - "socket!\n")); - close(sock); - return; + strlcat(Sender, "\",\"", sizeof(Sender) - 1); + strlcat(Sender, file_name, sizeof(Sender) - 1); + strlcat(Sender, "\",\"", sizeof(Sender) - 1); + get_timestamp(TimeStamp); + strlcat(Sender, TimeStamp, sizeof(Sender) - 1); + strlcat(Sender, "\");", sizeof(Sender) - 1); + DEBUG(10, ("smb_traffic_analyzer_send_data_socket: sending %s\n", + Sender)); + if (send(*psockfd, Sender, strlen(Sender), 0) == -1 ) { + DEBUG(1, ("smb_traffic_analyzer_send_data_socket: " + "error sending data to socket!\n")); + return ; } +} - /* one operation, close the socket */ - close(sock); - return; +static void smb_traffic_analyzer_free_data(void **pptr) +{ + int *pfd = *(int **)pptr; + if(!pfd) { + return; + } + if (*pfd != -1) { + close(*pfd); + } + TALLOC_FREE(pfd); } -static void smb_traffic_analyzer_send_data( char *Buffer , vfs_handle_struct \ - *handle, char *file_name, bool Write, files_struct *fsp) +static int smb_traffic_analyzer_connect(struct vfs_handle_struct *handle, + const char *service, + const char *user) { + int *pfd = TALLOC_P(handle, int); - if (smb_traffic_analyzer_connMode(handle) == UNIX_DOMAIN_SOCKET) { - smb_traffic_analyzer_send_data_unix_socket(Buffer, handle, \ - fsp->fsp_name, Write); - } else { - smb_traffic_analyzer_send_data_inet_socket(Buffer, handle, \ - fsp->fsp_name, Write); - } -} + if (!pfd) { + errno = ENOMEM; + return -1; + } + if (smb_traffic_analyzer_connMode(handle) == UNIX_DOMAIN_SOCKET) { + *pfd = smb_traffic_analyzer_connect_unix_socket(handle); + } else { + *pfd = smb_traffic_analyzer_connect_inet_socket(handle); + } + if (*pfd == -1) { + return -1; + } + /* Store the private data. */ + SMB_VFS_HANDLE_SET_DATA(handle, pfd, smb_traffic_analyzer_free_data, + int, return -1); + return SMB_VFS_NEXT_CONNECT(handle, service, user); +} /* VFS Functions: write, read, pread, pwrite for now */ @@ -308,11 +259,14 @@ static ssize_t smb_traffic_analyzer_read(vfs_handle_struct *handle, \ fstring Buffer; result = SMB_VFS_NEXT_READ(handle, fsp, data, n); - DEBUG(10, ("smb_traffic_analyzer: READ: %s\n", fsp->fsp_name )); + DEBUG(10, ("smb_traffic_analyzer_read: READ: %s\n", fsp->fsp_name )); fstr_sprintf(Buffer, "%u", (uint) result); - smb_traffic_analyzer_send_data(Buffer, handle, fsp->fsp_name, false, fsp); + smb_traffic_analyzer_send_data(handle, + Buffer, + fsp->fsp_name, + false); return result; } @@ -325,10 +279,13 @@ static ssize_t smb_traffic_analyzer_pread(vfs_handle_struct *handle, \ result = SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset); - DEBUG(10, ("smb_traffic_analyzer: READ: %s\n", fsp->fsp_name )); + DEBUG(10, ("smb_traffic_analyzer_pread: PREAD: %s\n", fsp->fsp_name )); fstr_sprintf(Buffer,"%u", (uint) result); - smb_traffic_analyzer_send_data(Buffer, handle, fsp->fsp_name, false, fsp); + smb_traffic_analyzer_send_data(handle, + Buffer, + fsp->fsp_name, + false); return result; } @@ -341,11 +298,13 @@ static ssize_t smb_traffic_analyzer_write(vfs_handle_struct *handle, \ result = SMB_VFS_NEXT_WRITE(handle, fsp, data, n); - DEBUG(10, ("smb_traffic_analyzer: WRITE: %s\n", fsp->fsp_name )); + DEBUG(10, ("smb_traffic_analyzer_write: WRITE: %s\n", fsp->fsp_name )); fstr_sprintf(Buffer, "%u", (uint) result); - smb_traffic_analyzer_send_data(Buffer, handle, fsp->fsp_name, \ - true, fsp ); + smb_traffic_analyzer_send_data(handle, + Buffer, + fsp->fsp_name, + true); return result; } @@ -357,9 +316,56 @@ static ssize_t smb_traffic_analyzer_pwrite(vfs_handle_struct *handle, \ result = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset); - DEBUG(10, ("smb_traffic_analyzer: PWRITE: %s\n", fsp->fsp_name )); + DEBUG(10, ("smb_traffic_analyzer_pwrite: PWRITE: %s\n", fsp->fsp_name )); fstr_sprintf(Buffer, "%u", (uint) result); - smb_traffic_analyzer_send_data(Buffer, handle, fsp->fsp_name, true, fsp); + smb_traffic_analyzer_send_data(handle, + Buffer, + 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; +} -- cgit From 4e6445a0720d7265f0bddff71cd2e17d6b2ac057 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Tue, 30 Sep 2008 15:21:58 -0700 Subject: Remove current_user_info - not needed. Jeremy. --- source3/modules/vfs_expand_msdfs.c | 2 +- source3/modules/vfs_smb_traffic_analyzer.c | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/source3/modules/vfs_expand_msdfs.c b/source3/modules/vfs_expand_msdfs.c index 0d09d213e1..c22ab66e14 100644 --- a/source3/modules/vfs_expand_msdfs.c +++ b/source3/modules/vfs_expand_msdfs.c @@ -147,7 +147,7 @@ static char *expand_msdfs_target(TALLOC_CTX *ctx, conn->connectpath, conn->server_info->utok.gid, conn->server_info->sanitized_username, - pdb_get_domain(conn->server_info->sam_account), + pdb_get_domain(handle->conn->server_info->sam_account), targethost); DEBUG(10, ("Expanded targethost to %s\n", targethost)); diff --git a/source3/modules/vfs_smb_traffic_analyzer.c b/source3/modules/vfs_smb_traffic_analyzer.c index cd843e6ad4..12c893fae7 100644 --- a/source3/modules/vfs_smb_traffic_analyzer.c +++ b/source3/modules/vfs_smb_traffic_analyzer.c @@ -27,8 +27,6 @@ /* Prototypes */ -extern userdom_struct current_user_info; - static int vfs_smb_traffic_analyzer_debug_level = DBGC_VFS; /* create the timestamp in sqlite compatible format */ @@ -187,9 +185,9 @@ static void smb_traffic_analyzer_send_data(vfs_handle_struct *handle, strlcpy(Sender, str, sizeof(Sender)); strlcat(Sender, ",\"", sizeof(Sender)); - strlcat(Sender, get_current_username(), sizeof(Sender)); + strlcat(Sender, handle->conn->server_info->sanitized_username, sizeof(Sender)); strlcat(Sender, "\",\"", sizeof(Sender)); - strlcat(Sender, current_user_info.domain, sizeof(Sender)); + strlcat(Sender, pdb_get_domain(handle->conn->server_info->sam_account), sizeof(Sender)); strlcat(Sender, "\",\"", sizeof(Sender)); if (Write) strlcat(Sender, "W", sizeof(Sender)); -- cgit From 5d7d18b7e827930018ab30fc5e738b5a5cd90789 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Tue, 30 Sep 2008 15:26:26 -0700 Subject: Revert erroneous commit. Jeremy. --- source3/modules/vfs_expand_msdfs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/modules/vfs_expand_msdfs.c b/source3/modules/vfs_expand_msdfs.c index c22ab66e14..0d09d213e1 100644 --- a/source3/modules/vfs_expand_msdfs.c +++ b/source3/modules/vfs_expand_msdfs.c @@ -147,7 +147,7 @@ static char *expand_msdfs_target(TALLOC_CTX *ctx, conn->connectpath, conn->server_info->utok.gid, conn->server_info->sanitized_username, - pdb_get_domain(handle->conn->server_info->sam_account), + pdb_get_domain(conn->server_info->sam_account), targethost); DEBUG(10, ("Expanded targethost to %s\n", targethost)); -- cgit From c164ff2be5f9af7cc83e43d8c54b54186444fac0 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Tue, 30 Sep 2008 16:19:37 -0700 Subject: Convert to allocated strings. Use write_data(), not send as this doesn't correctly deal with EINTR. Jim and Holger please check this still works. Jeremy. --- source3/modules/vfs_smb_traffic_analyzer.c | 100 ++++++++++++----------------- 1 file changed, 42 insertions(+), 58 deletions(-) diff --git a/source3/modules/vfs_smb_traffic_analyzer.c b/source3/modules/vfs_smb_traffic_analyzer.c index 12c893fae7..3925424214 100644 --- a/source3/modules/vfs_smb_traffic_analyzer.c +++ b/source3/modules/vfs_smb_traffic_analyzer.c @@ -24,29 +24,8 @@ #define UNIX_DOMAIN_SOCKET 1 #define INTERNET_SOCKET 0 - -/* Prototypes */ - static int vfs_smb_traffic_analyzer_debug_level = DBGC_VFS; -/* create the timestamp in sqlite compatible format */ -static void get_timestamp(fstring str) -{ - struct timeval tv; - struct timezone tz; - struct tm *tm; - int seconds; - - gettimeofday(&tv, &tz); - tm=localtime(&tv.tv_sec); - seconds=(float) (tv.tv_usec / 1000); - - fstr_sprintf(str,"%04d-%02d-%02d %02d:%02d:%02d.%03d", \ - tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, \ - tm->tm_hour, tm->tm_min, tm->tm_sec, (int)seconds); - -} - static int smb_traffic_analyzer_connMode(vfs_handle_struct *handle) { connection_struct *conn = handle->conn; @@ -58,7 +37,6 @@ static int smb_traffic_analyzer_connMode(vfs_handle_struct *handle) } else { return INTERNET_SOCKET; } - } /* Connect to an internet socket */ @@ -167,13 +145,16 @@ static int smb_traffic_analyzer_connect_unix_socket(vfs_handle_struct *handle) /* Send data over a socket */ static void smb_traffic_analyzer_send_data(vfs_handle_struct *handle, - char *str, + ssize_t result, const char *file_name, bool Write) { int *psockfd = NULL; - char Sender[200]; - char TimeStamp[200]; + struct timeval tv; + struct tm *tm = NULL; + int seconds; + char *str = NULL; + size_t len; SMB_VFS_HANDLE_GET_DATA(handle, psockfd, int, return); @@ -183,27 +164,39 @@ static void smb_traffic_analyzer_send_data(vfs_handle_struct *handle, return; } - strlcpy(Sender, str, sizeof(Sender)); - strlcat(Sender, ",\"", sizeof(Sender)); - strlcat(Sender, handle->conn->server_info->sanitized_username, sizeof(Sender)); - strlcat(Sender, "\",\"", sizeof(Sender)); - strlcat(Sender, pdb_get_domain(handle->conn->server_info->sam_account), sizeof(Sender)); - strlcat(Sender, "\",\"", sizeof(Sender)); - if (Write) - strlcat(Sender, "W", sizeof(Sender)); - else - strlcat(Sender, "R", sizeof(Sender)); - strlcat(Sender, "\",\"", sizeof(Sender)); - strlcat(Sender, handle->conn->connectpath, sizeof(Sender)); - strlcat(Sender, "\",\"", sizeof(Sender) - 1); - strlcat(Sender, file_name, sizeof(Sender) - 1); - strlcat(Sender, "\",\"", sizeof(Sender) - 1); - get_timestamp(TimeStamp); - strlcat(Sender, TimeStamp, sizeof(Sender) - 1); - strlcat(Sender, "\");", sizeof(Sender) - 1); + GetTimeOfDay(&tv); + tm=localtime(&tv.tv_sec); + if (!tm) { + return; + } + seconds=(float) (tv.tv_usec / 1000); + + str = talloc_asprintf(talloc_tos(), + "%u,\"%s\",\"%s\",\"%c\",\"%s\",\"%s\"," + "\"%04d-%02d-%02d %02d:%02d:%02d.%03d\");", + (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", - Sender)); - if (send(*psockfd, Sender, strlen(Sender), 0) == -1 ) { + str)); + if (write_data(*psockfd, str, len) != len) { DEBUG(1, ("smb_traffic_analyzer_send_data_socket: " "error sending data to socket!\n")); return ; @@ -254,15 +247,12 @@ static ssize_t smb_traffic_analyzer_read(vfs_handle_struct *handle, \ files_struct *fsp, void *data, size_t n) { ssize_t result; - fstring Buffer; result = SMB_VFS_NEXT_READ(handle, fsp, data, n); DEBUG(10, ("smb_traffic_analyzer_read: READ: %s\n", fsp->fsp_name )); - fstr_sprintf(Buffer, "%u", (uint) result); - smb_traffic_analyzer_send_data(handle, - Buffer, + result, fsp->fsp_name, false); return result; @@ -273,15 +263,13 @@ 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; - fstring Buffer; result = SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset); DEBUG(10, ("smb_traffic_analyzer_pread: PREAD: %s\n", fsp->fsp_name )); - fstr_sprintf(Buffer,"%u", (uint) result); smb_traffic_analyzer_send_data(handle, - Buffer, + result, fsp->fsp_name, false); @@ -292,15 +280,13 @@ static ssize_t smb_traffic_analyzer_write(vfs_handle_struct *handle, \ files_struct *fsp, const void *data, size_t n) { ssize_t result; - fstring Buffer; result = SMB_VFS_NEXT_WRITE(handle, fsp, data, n); DEBUG(10, ("smb_traffic_analyzer_write: WRITE: %s\n", fsp->fsp_name )); - fstr_sprintf(Buffer, "%u", (uint) result); smb_traffic_analyzer_send_data(handle, - Buffer, + result, fsp->fsp_name, true); return result; @@ -310,15 +296,13 @@ 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; - fstring Buffer; result = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset); DEBUG(10, ("smb_traffic_analyzer_pwrite: PWRITE: %s\n", fsp->fsp_name )); - fstr_sprintf(Buffer, "%u", (uint) result); smb_traffic_analyzer_send_data(handle, - Buffer, + result, fsp->fsp_name, true); return result; -- cgit From d56a81f60a820e6a4a3f2617c4fdd4f88e7853cd Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 1 Oct 2008 17:27:42 +0200 Subject: Update to refer to 3 and 4, not just Samba 3. --- README.Coding | 65 +++++++++++++++++++++++++++++------------------------------ 1 file changed, 32 insertions(+), 33 deletions(-) diff --git a/README.Coding b/README.Coding index 8063ae8691..c1b6641a5a 100644 --- a/README.Coding +++ b/README.Coding @@ -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 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) { -- cgit From 90d1481cf6b100988f9a6157674d03ed677f280f Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 1 Oct 2008 17:28:12 +0200 Subject: Fix formatting to be compatible with ReST. --- prog_guide4.txt | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/prog_guide4.txt b/prog_guide4.txt index 2f5be5f791..cc20c262d8 100644 --- a/prog_guide4.txt +++ b/prog_guide4.txt @@ -7,6 +7,8 @@ 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 the time to read through this document. @@ -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 -- cgit From bdd80734c977336b09f64cd55d76815de49a5fee Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 1 Oct 2008 17:29:16 +0200 Subject: Fix header. --- prog_guide4.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/prog_guide4.txt b/prog_guide4.txt index cc20c262d8..8d6ff56964 100644 --- a/prog_guide4.txt +++ b/prog_guide4.txt @@ -5,7 +5,7 @@ FROM A FEW PEOPLE. DON'T TAKE THIS AS THE FINAL VERSION YET. Samba4 Programming Guide ------------------------- +======================== .. contents:: -- cgit From ca44340891d60de7e48bb263c7debd45cc3f3ed0 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 1 Oct 2008 18:06:55 +0200 Subject: Fix some syntax errors for use with ReST. --- lib/talloc/talloc_guide.txt | 43 ++++++++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/lib/talloc/talloc_guide.txt b/lib/talloc/talloc_guide.txt index 18663b370d..3201fe6f0f 100644 --- a/lib/talloc/talloc_guide.txt +++ b/lib/talloc/talloc_guide.txt @@ -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) =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -- cgit From 370cbe0060cb2670c7f65100954dac6c63030ca0 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Wed, 1 Oct 2008 12:50:29 -0700 Subject: Turn the socket connections into a refcounted list - in the common case there'll now only be one socket per smbd. Changed the format of the wire data to (a) include a version number (V1) as the first element. (b) removed the ";)" at the end an replaced it with a "\n". Receiver can change back if needed, and now receiver can just log "as-is" to a text file (making testing easier). Added my (C). Sorry Holger, but I've changed quite a bit now. Jeremy. --- source3/modules/vfs_smb_traffic_analyzer.c | 139 ++++++++++++++++++++--------- 1 file changed, 95 insertions(+), 44 deletions(-) diff --git a/source3/modules/vfs_smb_traffic_analyzer.c b/source3/modules/vfs_smb_traffic_analyzer.c index 3925424214..ff61768495 100644 --- a/source3/modules/vfs_smb_traffic_analyzer.c +++ b/source3/modules/vfs_smb_traffic_analyzer.c @@ -3,6 +3,7 @@ * 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 @@ -21,12 +22,14 @@ #include "includes.h" /* abstraction for the send_over_network function */ -#define UNIX_DOMAIN_SOCKET 1 -#define INTERNET_SOCKET 0 + +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 int smb_traffic_analyzer_connMode(vfs_handle_struct *handle) +static enum sock_type smb_traffic_analyzer_connMode(vfs_handle_struct *handle) { connection_struct *conn = handle->conn; const char *Mode; @@ -41,28 +44,22 @@ static int smb_traffic_analyzer_connMode(vfs_handle_struct *handle) /* Connect to an internet socket */ -static int smb_traffic_analyzer_connect_inet_socket(vfs_handle_struct *handle) +static int smb_traffic_analyzer_connect_inet_socket(vfs_handle_struct *handle, + const char *name, uint16_t port) { /* Create a streaming Socket */ - const char *Hostname; int sockfd = -1; - uint16_t port; struct addrinfo hints; struct addrinfo *ailist = NULL; struct addrinfo *res = NULL; - connection_struct *conn = handle->conn; int ret; - /* get port number, target system from the config parameters */ - Hostname=lp_parm_const_string(SNUM(conn), "smb_traffic_analyzer", - "host", "localhost"); - ZERO_STRUCT(hints); /* By default make sure it supports TCP. */ hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_ADDRCONFIG; - ret = getaddrinfo(Hostname, + ret = getaddrinfo(name, NULL, &hints, &ailist); @@ -70,16 +67,13 @@ static int smb_traffic_analyzer_connect_inet_socket(vfs_handle_struct *handle) if (ret) { DEBUG(3,("smb_traffic_analyzer_connect_inet_socket: " "getaddrinfo failed for name %s [%s]\n", - Hostname, + name, gai_strerror(ret) )); return -1; } - port = atoi( lp_parm_const_string(SNUM(conn), - "smb_traffic_analyzer", "port", "9430")); - DEBUG(3,("smb_traffic_analyzer: Internet socket mode. Hostname: %s," - "Port: %i\n", Hostname, port)); + "Port: %i\n", name, port)); for (res = ailist; res; res = res->ai_next) { struct sockaddr_storage ss; @@ -113,15 +107,16 @@ static int smb_traffic_analyzer_connect_inet_socket(vfs_handle_struct *handle) /* Connect to a unix domain socket */ -static int smb_traffic_analyzer_connect_unix_socket(vfs_handle_struct *handle) +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 " - "/var/tmp/stadsocket\n")); + "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: " @@ -129,7 +124,7 @@ static int smb_traffic_analyzer_connect_unix_socket(vfs_handle_struct *handle) "make sure stad is running!\n")); } remote.sun_family = AF_UNIX; - strlcpy(remote.sun_path, "/var/tmp/stadsocket", + 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 ) { @@ -142,6 +137,16 @@ static int smb_traffic_analyzer_connect_unix_socket(vfs_handle_struct *handle) 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, @@ -149,16 +154,16 @@ static void smb_traffic_analyzer_send_data(vfs_handle_struct *handle, const char *file_name, bool Write) { - int *psockfd = NULL; + struct refcounted_sock *rf_sock = NULL; struct timeval tv; struct tm *tm = NULL; int seconds; char *str = NULL; size_t len; - SMB_VFS_HANDLE_GET_DATA(handle, psockfd, int, return); + SMB_VFS_HANDLE_GET_DATA(handle, rf_sock, struct refcounted_sock, return); - if (psockfd == NULL || *psockfd == -1) { + if (rf_sock == NULL || rf_sock->sock == -1) { DEBUG(1, ("smb_traffic_analyzer_send_data: socket is " "closed\n")); return; @@ -172,8 +177,8 @@ static void smb_traffic_analyzer_send_data(vfs_handle_struct *handle, seconds=(float) (tv.tv_usec / 1000); str = talloc_asprintf(talloc_tos(), - "%u,\"%s\",\"%s\",\"%c\",\"%s\",\"%s\"," - "\"%04d-%02d-%02d %02d:%02d:%02d.%03d\");", + "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), @@ -196,48 +201,94 @@ static void smb_traffic_analyzer_send_data(vfs_handle_struct *handle, DEBUG(10, ("smb_traffic_analyzer_send_data_socket: sending %s\n", str)); - if (write_data(*psockfd, str, len) != len) { + 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) { - int *pfd = *(int **)pptr; - if(!pfd) { + struct refcounted_sock *rf_sock = *(struct refcounted_sock **)pptr; + if (rf_sock == NULL) { return; } - if (*pfd != -1) { - close(*pfd); + rf_sock->ref_count--; + if (rf_sock->ref_count != 0) { + return; + } + if (rf_sock->sock != -1) { + close(rf_sock->sock); } - TALLOC_FREE(pfd); + 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) { - int *pfd = TALLOC_P(handle, int); + 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")); - if (!pfd) { - errno = ENOMEM; - return -1; + /* 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 (smb_traffic_analyzer_connMode(handle) == UNIX_DOMAIN_SOCKET) { - *pfd = smb_traffic_analyzer_connect_unix_socket(handle); + /* If we're connected already, just increase the + * reference count. */ + if (rf_sock) { + rf_sock->ref_count++; } else { - *pfd = smb_traffic_analyzer_connect_inet_socket(handle); - } - if (*pfd == -1) { - return -1; + /* 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, pfd, smb_traffic_analyzer_free_data, - int, return -1); + 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); } -- cgit From e4f5bfb34b7a515e2cf107eb94489260594b8733 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Wed, 1 Oct 2008 13:15:54 -0700 Subject: Fix use of DLIST_REMOVE as spotted by Constantine Vetoshev . This API is unusual in that if used to remove a non-list head it nulls out the next and prev pointers. This is what you want for debugging (don't want an entry removed from the list to be still virtually linked into it) but means there is no consistent idiom for use as the next and prev pointers get trashed on removal from the list, meaning you must save them yourself. You can use it one way when deleting everything via the head pointer, as this preserves the next pointer, but you *must* use it another way when not deleting everything via the head pointer. Fix all known uses of this (the main one is in conn_free_internal() and would not free all the private data entries for vfs modules. The other changes in web/statuspage.c and winbindd_util.c are not strictly neccessary, as the head pointer is being used, but I've done them for consistency. Long term we must revisit this as this API is too hard to use correctly. Jeremy. --- source3/smbd/conn.c | 2 +- source3/web/statuspage.c | 5 +++-- source3/winbindd/winbindd_util.c | 3 +-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/source3/smbd/conn.c b/source3/smbd/conn.c index b9433bb965..7f34d2b8e2 100644 --- a/source3/smbd/conn.c +++ b/source3/smbd/conn.c @@ -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; diff --git a/source3/web/statuspage.c b/source3/web/statuspage.c index ce24c7cddd..e684a075c2 100644 --- a/source3/web/statuspage.c +++ b/source3/web/statuspage.c @@ -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); diff --git a/source3/winbindd/winbindd_util.c b/source3/winbindd/winbindd_util.c index b8cb27c797..fdfc8ed9d1 100644 --- a/source3/winbindd/winbindd_util.c +++ b/source3/winbindd/winbindd_util.c @@ -1075,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; -- cgit From ea85ceefa945f1fee2bb10441a3cc8e35216733b Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Wed, 1 Oct 2008 15:01:05 -0700 Subject: Whitespace cleanup. Jeremy. --- source3/printing/print_cups.c | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/source3/printing/print_cups.c b/source3/printing/print_cups.c index f9568f0a54..97584cbe05 100644 --- a/source3/printing/print_cups.c +++ b/source3/printing/print_cups.c @@ -7,12 +7,12 @@ * 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 . */ @@ -109,7 +109,7 @@ bool cups_cache_reload(void) { "printer-name", "printer-info" - }; + }; bool ret = False; DEBUG(5, ("reloading cups printcap cache\n")); @@ -657,8 +657,8 @@ static int cups_job_submit(int snum, struct printjob *pjob) 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 */ num_options = 0; @@ -666,7 +666,7 @@ static int cups_job_submit(int snum, struct printjob *pjob) num_options = cupsParseOptions(lp_cups_options(snum), num_options, &options); if ( num_options ) - cupsEncodeOptions(request, num_options, options); + cupsEncodeOptions(request, num_options, options); /* * Do the request and get back a response... @@ -712,7 +712,7 @@ 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; @@ -751,10 +751,10 @@ 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 ); @@ -1316,22 +1316,22 @@ bool cups_pull_comment_location(NT_PRINTER_INFO_LEVEL_2 *printer) /* 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) ) { DEBUG(5,("cups_pull_comment_location: Using cups comment: %s\n", - attr->values[0].string.text)); + attr->values[0].string.text)); strlcpy(printer->comment, attr->values[0].string.text, 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) ) { DEBUG(5,("cups_pull_comment_location: Using cups location: %s\n", - attr->values[0].string.text)); + attr->values[0].string.text)); fstrcpy(printer->location,attr->values[0].string.text); } -- cgit From 3bfb53caa86ece1d7ff1bf3c7759f003203d4247 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Wed, 1 Oct 2008 16:40:41 -0700 Subject: Fix bug #5080. Access to cups-printers via samba broken with cups 1.3.4, Unsupported character set. Cups 1.3.4 expects utf8 to be used in all messages to/from the server. We may be using a different character set so we need to use talloc utf8 push/pull functions in all communication. Needs more testing. Don't release until I've done a thorough test. I also have a version for 3.2.x. Jeremy. --- source3/printing/print_cups.c | 341 +++++++++++++++++++++++++++++++----------- 1 file changed, 251 insertions(+), 90 deletions(-) diff --git a/source3/printing/print_cups.c b/source3/printing/print_cups.c index 97584cbe05..b46d83bb01 100644 --- a/source3/printing/print_cups.c +++ b/source3/printing/print_cups.c @@ -2,6 +2,7 @@ * 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 @@ -17,6 +18,10 @@ * along with this program; if not, see . */ +/* + * 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_connection_timeout(); - - gotalarm = 0; - - if (timeout) { - CatchSignal(SIGALRM, SIGNAL_CAST gotalarm_sig); - alarm(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,12 @@ static http_t *cups_connect(void) server, port, strerror(errno))); } - SAFE_FREE(server); return http; } bool cups_cache_reload(void) { + TALLOC_CTX *frame = talloc_stackframe(); http_t *http = NULL; /* HTTP connection to server */ ipp_t *request = NULL, /* IPP Request */ *response = NULL; /* IPP Response */ @@ -111,6 +122,7 @@ bool cups_cache_reload(void) "printer-info" }; bool ret = False; + size_t size; DEBUG(5, ("reloading cups printcap cache\n")); @@ -124,7 +136,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 +157,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 +197,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; } @@ -225,7 +249,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 +289,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; } @@ -299,6 +335,7 @@ bool cups_cache_reload(void) if (http) httpClose(http); + TALLOC_FREE(frame); return ret; } @@ -309,13 +346,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 +368,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 +390,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 +399,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 +432,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 +443,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 +465,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 +487,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 +496,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 +528,7 @@ static int cups_job_pause(int snum, struct printjob *pjob) if (http) httpClose(http); + TALLOC_FREE(frame); return ret; } @@ -489,13 +539,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 +561,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 +583,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 +592,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 +624,7 @@ static int cups_job_resume(int snum, struct printjob *pjob) if (http) httpClose(http); + TALLOC_FREE(frame); return ret; } @@ -579,6 +635,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 +646,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 +666,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 +689,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,8 +718,14 @@ 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; } @@ -661,9 +736,12 @@ static int cups_job_submit(int snum, struct printjob *pjob) * 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); @@ -672,8 +750,11 @@ static int cups_job_submit(int snum, struct printjob *pjob) * 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 +781,7 @@ static int cups_job_submit(int snum, struct printjob *pjob) if (http) httpClose(http); - SAFE_FREE(new_jobname); + TALLOC_FREE(frame); return ret; } @@ -715,7 +796,8 @@ static int cups_queue_get(const char *sharename, 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 +808,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", @@ -757,9 +840,10 @@ static int cups_queue_get(const char *sharename, (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 +855,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 +883,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 +988,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 +1029,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 +1057,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 +1100,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 +1126,7 @@ static int cups_queue_get(const char *sharename, if (http) httpClose(http); + TALLOC_FREE(frame); return qcount; } @@ -1033,13 +1137,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 +1160,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 +1182,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 +1227,7 @@ static int cups_queue_pause(int snum) if (http) httpClose(http); + TALLOC_FREE(frame); return ret; } @@ -1124,13 +1238,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 +1261,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 +1283,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 +1328,7 @@ static int cups_queue_resume(int snum) if (http) httpClose(http); + TALLOC_FREE(frame); return ret; } @@ -1226,15 +1350,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 +1367,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 +1381,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 +1393,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,21 +1447,34 @@ 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) ) { + 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 */ @@ -1330,21 +1482,29 @@ bool cups_pull_comment_location(NT_PRINTER_INFO_LEVEL_2 *printer) && (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 +1519,7 @@ bool cups_pull_comment_location(NT_PRINTER_INFO_LEVEL_2 *printer) if (http) httpClose(http); + TALLOC_FREE(frame); return ret; } -- cgit From 9097a67def72ea41e85a4acb5d7cbcc46adaaa84 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Thu, 2 Oct 2008 02:17:04 +0200 Subject: Fix bug 5798: "CFLAGS info lost in configure" Michael, please check and merge to the other branches if it's right. Thanks, Volker --- source3/configure.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/configure.in b/source3/configure.in index f04ddbeaa5..545a5653de 100644 --- a/source3/configure.in +++ b/source3/configure.in @@ -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) -- cgit From 8641b54a736c5c924bf38cf4574d1f8e34d2d0cd Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Thu, 2 Oct 2008 03:37:52 +0200 Subject: Attempt to fix the build on IRIX Under irix, "sa_family" is a #define to sa_union.sa_generic.sa_family2 --- source3/librpc/gen_ndr/nbt.h | 2 +- source3/librpc/gen_ndr/ndr_nbt.c | 6 +++--- source3/librpc/idl/nbt.idl | 2 +- source3/libsmb/dsgetdcname.c | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/source3/librpc/gen_ndr/nbt.h b/source3/librpc/gen_ndr/nbt.h index 264b00b84f..4b872d7936 100644 --- a/source3/librpc/gen_ndr/nbt.h +++ b/source3/librpc/gen_ndr/nbt.h @@ -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] */; diff --git a/source3/librpc/gen_ndr/ndr_nbt.c b/source3/librpc/gen_ndr/ndr_nbt.c index 84cfabda57..c02b539da5 100644 --- a/source3/librpc/gen_ndr/ndr_nbt.c +++ b/source3/librpc/gen_ndr/ndr_nbt.c @@ -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--; diff --git a/source3/librpc/idl/nbt.idl b/source3/librpc/idl/nbt.idl index 82571d96e6..f3590fcf2b 100644 --- a/source3/librpc/idl/nbt.idl +++ b/source3/librpc/idl/nbt.idl @@ -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; diff --git a/source3/libsmb/dsgetdcname.c b/source3/libsmb/dsgetdcname.c index 89769d8a76..d2ede1d875 100644 --- a/source3/libsmb/dsgetdcname.c +++ b/source3/libsmb/dsgetdcname.c @@ -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, -- cgit From af1c802791e3c9f54220d8c80c3de79ef422d726 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Thu, 2 Oct 2008 08:09:25 +0200 Subject: The IRIX compiler does not like embedded unnamed unions --- libcli/netlogon.c | 83 +++++++++++++++++++--------------- libcli/netlogon.h | 4 +- source3/libads/cldap.c | 2 +- source3/libsmb/clidgram.c | 4 +- source3/libsmb/dsgetdcname.c | 20 ++++----- source4/cldap_server/netlogon.c | 80 ++++++++++++++++----------------- source4/libnet/libnet_become_dc.c | 2 +- source4/libnet/libnet_site.c | 5 ++- source4/libnet/libnet_unbecome_dc.c | 2 +- source4/nbt_server/dgram/netlogon.c | 4 +- source4/nbt_server/irpc.c | 9 ++-- source4/torture/ldap/cldap.c | 88 ++++++++++++++++++------------------- source4/torture/nbt/dgram.c | 42 +++++++++--------- source4/torture/rpc/dssync.c | 6 +-- 14 files changed, 183 insertions(+), 168 deletions(-) diff --git a/libcli/netlogon.c b/libcli/netlogon.c index 36d9e5fdcd..acfce61cca 100644 --- a/libcli/netlogon.c +++ b/libcli/netlogon.c @@ -37,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)); @@ -86,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) { @@ -99,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]", @@ -107,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", @@ -144,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; @@ -185,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); @@ -199,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; @@ -221,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); @@ -241,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; diff --git a/libcli/netlogon.h b/libcli/netlogon.h index 8bd9d0d90a..6ca3de3366 100644 --- a/libcli/netlogon.h +++ b/libcli/netlogon.h @@ -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" diff --git a/source3/libads/cldap.c b/source3/libads/cldap.c index edabbed0e9..c37220c903 100644 --- a/source3/libads/cldap.c +++ b/source3/libads/cldap.c @@ -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; } diff --git a/source3/libsmb/clidgram.c b/source3/libsmb/clidgram.c index e8799bce47..611ae0870c 100644 --- a/source3/libsmb/clidgram.c +++ b/source3/libsmb/clidgram.c @@ -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", diff --git a/source3/libsmb/dsgetdcname.c b/source3/libsmb/dsgetdcname.c index d2ede1d875..18010aaa1c 100644 --- a/source3/libsmb/dsgetdcname.c +++ b/source3/libsmb/dsgetdcname.c @@ -272,12 +272,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 +286,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 +296,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; } @@ -913,10 +913,10 @@ static NTSTATUS process_dc_dns(TALLOC_CTX *mem_ctx, } status = make_dc_info_from_cldap_reply(mem_ctx, flags, &dclist[i].ss, - &r->nt5_ex, 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; @@ -1035,7 +1035,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); @@ -1049,10 +1049,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->nt5_ex, 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; diff --git a/source4/cldap_server/netlogon.c b/source4/cldap_server/netlogon.c index 7dccd81fad..aac74f5d77 100644 --- a/source4/cldap_server/netlogon.c +++ b/source4/cldap_server/netlogon.c @@ -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; diff --git a/source4/libnet/libnet_become_dc.c b/source4/libnet/libnet_become_dc.c index b9071d5eb1..4cbebbf6d0 100644 --- a/source4/libnet/libnet_become_dc.c +++ b/source4/libnet/libnet_become_dc.c @@ -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; diff --git a/source4/libnet/libnet_site.c b/source4/libnet/libnet_site.c index 5647a93b8d..4a32ab92ed 100644 --- a/source4/libnet/libnet_site.c +++ b/source4/libnet/libnet_site.c @@ -58,7 +58,8 @@ NTSTATUS libnet_FindSite(TALLOC_CTX *ctx, struct libnet_context *lctx, struct li 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); diff --git a/source4/libnet/libnet_unbecome_dc.c b/source4/libnet/libnet_unbecome_dc.c index 4eeaf1b80c..3a9a5cebd8 100644 --- a/source4/libnet/libnet_unbecome_dc.c +++ b/source4/libnet/libnet_unbecome_dc.c @@ -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; diff --git a/source4/nbt_server/dgram/netlogon.c b/source4/nbt_server/dgram/netlogon.c index 5e95270b7d..1bc3e2b62f 100644 --- a/source4/nbt_server/dgram/netlogon.c +++ b/source4/nbt_server/dgram/netlogon.c @@ -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))); diff --git a/source4/nbt_server/irpc.c b/source4/nbt_server/irpc.c index 8f1f74afcf..fc61372ead 100644 --- a/source4/nbt_server/irpc.c +++ b/source4/nbt_server/irpc.c @@ -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; diff --git a/source4/torture/ldap/cldap.c b/source4/torture/ldap/cldap.c index 3730193c86..23b0554c4f 100644 --- a/source4/torture/ldap/cldap.c +++ b/source4/torture/ldap/cldap.c @@ -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; diff --git a/source4/torture/nbt/dgram.c b/source4/torture/nbt/dgram.c index eac2b1fe30..5d26d65e0c 100644 --- a/source4/torture/nbt/dgram.c +++ b/source4/torture/nbt/dgram.c @@ -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; diff --git a/source4/torture/rpc/dssync.c b/source4/torture/rpc/dssync.c index df16c860cb..41bb168619 100644 --- a/source4/torture/rpc/dssync.c +++ b/source4/torture/rpc/dssync.c @@ -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); -- cgit From 5fc7fb48a0d7da8c4d0eec580c37b8a503faecce Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 2 Oct 2008 11:23:21 +0200 Subject: s4:lib/ldb: fix stupid dn parsing bugs metze --- source4/lib/ldb/common/ldb_dn.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source4/lib/ldb/common/ldb_dn.c b/source4/lib/ldb/common/ldb_dn.c index c0d36cfbf3..e36aea4e69 100644 --- a/source4/lib/ldb/common/ldb_dn.c +++ b/source4/lib/ldb/common/ldb_dn.c @@ -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, "length >= 5 && strncasecmp((const char *)strdn->data, "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, "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) { @@ -256,25 +374,190 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) struct ldb_control **saved_controls; struct extended_context *ac; struct ldb_request *down_req; - const char * const *cast_attrs = NULL; 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, "'); + 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(ac->module->ldb); + return ldb_module_done(ac->req, NULL, NULL, + LDB_ERR_OPERATIONS_ERROR); + } + valstr = ldb_binary_encode(req, binary); + data_blob_free(&binary); + if (!valstr) { + ldb_oom(ac->module->ldb); + return ldb_module_done(ac->req, NULL, NULL, + 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(ac->module->ldb); + return ldb_module_done(ac->req, NULL, NULL, + LDB_ERR_OPERATIONS_ERROR); + } + base_dn_scope = LDB_SCOPE_SUBTREE; + base_dn_attrs = dnattr; + } else if (strncasecmp(dn, "'); + 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(ac->module->ldb); + return ldb_module_done(ac->req, NULL, NULL, + LDB_ERR_OPERATIONS_ERROR); + } + valstr = ldb_binary_encode(req, binary); + data_blob_free(&binary); + if (!valstr) { + ldb_oom(ac->module->ldb); + return ldb_module_done(ac->req, NULL, NULL, + 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(ac->module->ldb); + return ldb_module_done(ac->req, NULL, NULL, + LDB_ERR_OPERATIONS_ERROR); + } + base_dn_scope = LDB_SCOPE_SUBTREE; + base_dn_attrs = dnattr; + } else if (strncasecmp(dn, "module->ldb); + return ldb_module_done(ac->req, NULL, NULL, + 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(ac->module->ldb); + return ldb_module_done(ac->req, NULL, NULL, + LDB_ERR_OPERATIONS_ERROR); + } + base_dn_filter = talloc_strdup(req, "(objectClass=*)"); + if (!base_dn_filter) { + ldb_oom(ac->module->ldb); + return ldb_module_done(ac->req, NULL, NULL, + 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; @@ -282,49 +565,75 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) ac->module = module; 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; - } - /* 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 (! is_attr_in_list(req->op.search.attrs, "objectSID")) { - ac->remove_sid = true; + if (control) { + ac->inject = true; + if (extended_ctrl) { + ac->extended_type = extended_ctrl->type; + } else { + ac->extended_type = 0; } - 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; + + /* 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(ac, &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(ac, &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; + } + + 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; } - cast_attrs = (const char * const *)new_attrs; - } else { - cast_attrs = req->op.search.attrs; } } + 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; + } + + /* perform the search */ + return 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, - cast_attrs, + ac->cast_attrs, req->controls, ac, extended_callback, req); @@ -332,11 +641,13 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) 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; + 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; + } } /* perform the search */ -- cgit From 8aff4430308b36ae1a1a6629d67bba87eebb0dde Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 2 Oct 2008 02:44:25 +0200 Subject: s4:kludge_acl: just fake support for the SD_FLAGS control metze --- source4/dsdb/samdb/ldb_modules/kludge_acl.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/source4/dsdb/samdb/ldb_modules/kludge_acl.c b/source4/dsdb/samdb/ldb_modules/kludge_acl.c index 24527c36c9..6e6da5581d 100644 --- a/source4/dsdb/samdb/ldb_modules/kludge_acl.c +++ b/source4/dsdb/samdb/ldb_modules/kludge_acl.c @@ -321,6 +321,8 @@ static int kludge_acl_search(struct ldb_module *module, struct ldb_request *req) struct kludge_private_data *data; const char * const *attrs; int ret, i; + struct ldb_control *sd_control; + struct ldb_control **sd_saved_controls; ac = talloc(req, struct kludge_acl_context); if (ac == NULL) { @@ -382,6 +384,17 @@ static int kludge_acl_search(struct ldb_module *module, struct ldb_request *req) return LDB_ERR_OPERATIONS_ERROR; } + /* 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; + } + } + /* perform the search */ return ldb_next_request(module, down_req); } @@ -462,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); -- cgit From 3ebf3f316b003000b77499f494cf4d017ef870ad Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 2 Oct 2008 11:05:02 +0200 Subject: s4:linked_attributes: fix a crash bug when the definition of a target attribute is missing 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. Our schema is extracted from windows 2003, so we have the problem. As the NET-API-BECOME-DC test triggers this bug, windows 2003 seems to just skip creating a backlink. metze --- source4/dsdb/samdb/ldb_modules/linked_attributes.c | 38 ++++++++++++++++++++-- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/linked_attributes.c b/source4/dsdb/samdb/ldb_modules/linked_attributes.c index 3b389afffb..14fd107d81 100644 --- a/source4/dsdb/samdb/ldb_modules/linked_attributes.c +++ b/source4/dsdb/samdb/ldb_modules/linked_attributes.c @@ -217,6 +217,17 @@ static int linked_attributes_add(struct ldb_module *module, struct ldb_request * /* Even link IDs are for the originating attribute */ 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; attr_val = ldb_dn_get_linearized(ac->req->op.add.message->dn); @@ -301,6 +312,16 @@ static int la_mod_search_callback(struct ldb_request *req, struct ldb_reply *are } 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; /* make sure we manage each value */ @@ -399,9 +420,14 @@ static int linked_attributes_modify(struct ldb_module *module, struct ldb_reques /* Now find the target attribute */ 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", el->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; } attr_name = target_attr->lDAPDisplayName; @@ -654,9 +680,15 @@ static int la_op_search_callback(struct ldb_request *req, 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++) { -- cgit From 551bbd853c87002fe068b5fb2a044c424ab7e874 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 2 Oct 2008 11:11:14 +0200 Subject: s4:partition: pass down the SEARCH_OPTIONS control as uncritical metze --- source4/dsdb/samdb/ldb_modules/partition.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/source4/dsdb/samdb/ldb_modules/partition.c b/source4/dsdb/samdb/ldb_modules/partition.c index ad2901c308..ad3518e6b2 100644 --- a/source4/dsdb/samdb/ldb_modules/partition.c +++ b/source4/dsdb/samdb/ldb_modules/partition.c @@ -466,6 +466,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 */ -- cgit From 81b3358f2a61c38ddd9d10accea8a4fe432f3085 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 2 Oct 2008 11:22:33 +0200 Subject: s4:partition: register DOMAIN_SCOPE and SEARCH_OPTIONS controls metze --- source4/dsdb/samdb/ldb_modules/partition.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/source4/dsdb/samdb/ldb_modules/partition.c b/source4/dsdb/samdb/ldb_modules/partition.c index ad3518e6b2..f600c72748 100644 --- a/source4/dsdb/samdb/ldb_modules/partition.c +++ b/source4/dsdb/samdb/ldb_modules/partition.c @@ -1160,6 +1160,20 @@ static int partition_init(struct ldb_module *module) } } + 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; + } + + 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; + } + talloc_free(mem_ctx); return ldb_next_init(module); } -- cgit From 1e24fd3ba20ace6e8f7e974dd7b7fc1738ade8be Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 2 Oct 2008 11:20:10 +0200 Subject: s4:rootdse: for now don't pass down controls for the rootdse search metze --- source4/dsdb/samdb/ldb_modules/rootdse.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/dsdb/samdb/ldb_modules/rootdse.c b/source4/dsdb/samdb/ldb_modules/rootdse.c index 0d14a54464..b38e182cf7 100644 --- a/source4/dsdb/samdb/ldb_modules/rootdse.c +++ b/source4/dsdb/samdb/ldb_modules/rootdse.c @@ -318,7 +318,7 @@ static int rootdse_search(struct ldb_module *module, struct ldb_request *req) LDB_SCOPE_BASE, NULL, req->op.search.attrs, - req->controls, + NULL,/* for now skip the controls from the client */ ac, rootdse_callback, req); if (ret != LDB_SUCCESS) { -- cgit From 3c9f3c32d1290b8e6c438a197602afe3e96ae828 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 2 Oct 2008 11:25:13 +0200 Subject: s4:drsuapi.idl: fix some fields in drsuapi_DsRemoveDSServer() metze --- source4/libnet/libnet_unbecome_dc.c | 7 +------ source4/librpc/idl/drsuapi.idl | 4 ++-- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/source4/libnet/libnet_unbecome_dc.c b/source4/libnet/libnet_unbecome_dc.c index 3a9a5cebd8..2ee3c641b2 100644 --- a/source4/libnet/libnet_unbecome_dc.c +++ b/source4/libnet/libnet_unbecome_dc.c @@ -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); } diff --git a/source4/librpc/idl/drsuapi.idl b/source4/librpc/idl/drsuapi.idl index 0a5a081dd7..76858b2d5c 100644 --- a/source4/librpc/idl/drsuapi.idl +++ b/source4/librpc/idl/drsuapi.idl @@ -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 { -- cgit From f0c17496366547f14638763a6b8859c365f18792 Mon Sep 17 00:00:00 2001 From: Derrell Lipman Date: Thu, 2 Oct 2008 09:03:32 -0400 Subject: Fix bug 5805: don't close stdout - When calling setup_logging multiple times, the code was closing the debug file descriptor before opening or assigning the new one. We don't, however, want to close the debug file descriptor if it is stdout. Derrell --- source3/lib/debug.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source3/lib/debug.c b/source3/lib/debug.c index d835ea7c17..d91b55dd23 100644 --- a/source3/lib/debug.c +++ b/source3/lib/debug.c @@ -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; -- cgit From 05994005a35b940efc9cd8d1b3b0eebf2d2e38d7 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 2 Oct 2008 11:56:12 +0200 Subject: s4:setup: add wellknownObjects to the domain object metze --- source4/setup/provision_basedn_modify.ldif | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/source4/setup/provision_basedn_modify.ldif b/source4/setup/provision_basedn_modify.ldif index 63332e937b..a7b501e8a8 100644 --- a/source4/setup/provision_basedn_modify.ldif +++ b/source4/setup/provision_basedn_modify.ldif @@ -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} -- cgit From a25fac13ebd6ffc1e5eac25182636cfa298435f4 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 2 Oct 2008 18:49:11 +0200 Subject: s4:blackblox/test_ldb: test searches via wellknownObjects metze --- testprogs/blackbox/test_ldb.sh | 62 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/testprogs/blackbox/test_ldb.sh b/testprogs/blackbox/test_ldb.sh index 8e1af99719..7a657d2e8d 100755 --- a/testprogs/blackbox/test_ldb.sh +++ b/testprogs/blackbox/test_ldb.sh @@ -117,5 +117,67 @@ echo "Search Options Control Query test returned 0 items" failed=`expr $failed + 1` fi +function wellkown_object_test() { + local guid=$1 + local object=$2 + local basedns + local dn + local r + local c + local n + local failed=0 + + basedns=" " + 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 +} + +wellkown_object_test 22B70C67D56E4EFB91E9300FCA3DC1AA ForeignSecurityPrincipals +st=$? +if [ x"$st" != x"0" ]; then + failed=`expr $failed + $st` +fi +wellkown_object_test 2FBAC1870ADE11D297C400C04FD8D5CD Infrastructure +st=$? +if [ x"$st" != x"0" ]; then + failed=`expr $failed + $st` +fi +wellkown_object_test AB1D30F3768811D1ADED00C04FD8D5CD System +st=$? +if [ x"$st" != x"0" ]; then + failed=`expr $failed + $st` +fi +wellkown_object_test A361B2FFFFD211D1AA4B00C04FD7D83A Domain Controllers +st=$? +if [ x"$st" != x"0" ]; then + failed=`expr $failed + $st` +fi +wellkown_object_test AA312825768811D1ADED00C04FD8D5CD Computers +st=$? +if [ x"$st" != x"0" ]; then + failed=`expr $failed + $st` +fi +wellkown_object_test A9D1CA15768811D1ADED00C04FD8D5CD Users +st=$? +if [ x"$st" != x"0" ]; then + failed=`expr $failed + $st` +fi exit $failed -- cgit From e0dbac6873b816384f570ad8a7ceea7c96573d00 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Thu, 2 Oct 2008 12:21:11 -0700 Subject: Don't reject a successful alloc :-(. Jeremy. --- source3/printing/print_cups.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/printing/print_cups.c b/source3/printing/print_cups.c index b46d83bb01..b9bed7a138 100644 --- a/source3/printing/print_cups.c +++ b/source3/printing/print_cups.c @@ -71,7 +71,7 @@ static http_t *cups_connect(TALLOC_CTX *frame) } else { server = talloc_strdup(frame,cupsServer()); } - if (server) { + if (!server) { return NULL; } -- cgit From b174765d54c202eb507b1caaed95c33bcd54d243 Mon Sep 17 00:00:00 2001 From: Simo Sorce Date: Thu, 2 Oct 2008 17:15:00 -0400 Subject: Fix crash bugs in error paths: ac is not yet initialized here, and we don't need to call ldb_module_done in the main module functions, we can directly return an error. ldb_module_done() is for callbacks --- source4/dsdb/samdb/ldb_modules/extended_dn.c | 45 +++++++++++----------------- 1 file changed, 18 insertions(+), 27 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/extended_dn.c b/source4/dsdb/samdb/ldb_modules/extended_dn.c index 6a7ed4e7c6..88a8887056 100644 --- a/source4/dsdb/samdb/ldb_modules/extended_dn.c +++ b/source4/dsdb/samdb/ldb_modules/extended_dn.c @@ -426,16 +426,14 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) DATA_BLOB binary; binary = strhex_to_data_blob(str); if (!binary.data) { - ldb_oom(ac->module->ldb); - return ldb_module_done(ac->req, NULL, NULL, - LDB_ERR_OPERATIONS_ERROR); + ldb_oom(module->ldb); + return LDB_ERR_OPERATIONS_ERROR; } valstr = ldb_binary_encode(req, binary); data_blob_free(&binary); if (!valstr) { - ldb_oom(ac->module->ldb); - return ldb_module_done(ac->req, NULL, NULL, - LDB_ERR_OPERATIONS_ERROR); + ldb_oom(module->ldb); + return LDB_ERR_OPERATIONS_ERROR; } } @@ -443,9 +441,8 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) base_dn = ldb_get_default_basedn(module->ldb); base_dn_filter = talloc_asprintf(req, "(objectSid=%s)", valstr); if (!base_dn_filter) { - ldb_oom(ac->module->ldb); - return ldb_module_done(ac->req, NULL, NULL, - LDB_ERR_OPERATIONS_ERROR); + ldb_oom(module->ldb); + return LDB_ERR_OPERATIONS_ERROR; } base_dn_scope = LDB_SCOPE_SUBTREE; base_dn_attrs = dnattr; @@ -476,16 +473,14 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) DATA_BLOB binary; binary = strhex_to_data_blob(str); if (!binary.data) { - ldb_oom(ac->module->ldb); - return ldb_module_done(ac->req, NULL, NULL, - LDB_ERR_OPERATIONS_ERROR); + ldb_oom(module->ldb); + return LDB_ERR_OPERATIONS_ERROR; } valstr = ldb_binary_encode(req, binary); data_blob_free(&binary); if (!valstr) { - ldb_oom(ac->module->ldb); - return ldb_module_done(ac->req, NULL, NULL, - LDB_ERR_OPERATIONS_ERROR); + ldb_oom(module->ldb); + return LDB_ERR_OPERATIONS_ERROR; } } @@ -493,9 +488,8 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) base_dn = ldb_get_default_basedn(module->ldb); base_dn_filter = talloc_asprintf(req, "(objectGUID=%s)", valstr); if (!base_dn_filter) { - ldb_oom(ac->module->ldb); - return ldb_module_done(ac->req, NULL, NULL, - LDB_ERR_OPERATIONS_ERROR); + ldb_oom(module->ldb); + return LDB_ERR_OPERATIONS_ERROR; } base_dn_scope = LDB_SCOPE_SUBTREE; base_dn_attrs = dnattr; @@ -513,9 +507,8 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) wellknown_object = talloc_asprintf(req, "B:32:%s:", &dn[8]); if (!wellknown_object) { - ldb_oom(ac->module->ldb); - return ldb_module_done(ac->req, NULL, NULL, - LDB_ERR_OPERATIONS_ERROR); + ldb_oom(module->ldb); + return LDB_ERR_OPERATIONS_ERROR; } tail_str = p; @@ -527,15 +520,13 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req) base_dn = ldb_dn_new(req, module->ldb, tail_str); if (!base_dn) { - ldb_oom(ac->module->ldb); - return ldb_module_done(ac->req, NULL, NULL, - LDB_ERR_OPERATIONS_ERROR); + ldb_oom(module->ldb); + return LDB_ERR_OPERATIONS_ERROR; } base_dn_filter = talloc_strdup(req, "(objectClass=*)"); if (!base_dn_filter) { - ldb_oom(ac->module->ldb); - return ldb_module_done(ac->req, NULL, NULL, - LDB_ERR_OPERATIONS_ERROR); + ldb_oom(module->ldb); + return LDB_ERR_OPERATIONS_ERROR; } base_dn_scope = LDB_SCOPE_BASE; base_dn_attrs = wkattr; -- cgit From 89a67bb60c3b88d5054a81085fb400930cfd5c55 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Thu, 2 Oct 2008 21:55:26 -0700 Subject: we need to listen on all interfaces in the CLDAP server as the windows CDLAP client ignores replies from the wrong IP --- source4/cldap_server/cldap_server.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/source4/cldap_server/cldap_server.c b/source4/cldap_server/cldap_server.c index 310fb564e0..240f2b1dc2 100644 --- a/source4/cldap_server/cldap_server.c +++ b/source4/cldap_server/cldap_server.c @@ -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 Date: Thu, 2 Oct 2008 21:57:27 -0700 Subject: fixed a talloc error in the rpc handle desctructor - destructors should not try to free the ptr they are given --- source4/rpc_server/handles.c | 1 - 1 file changed, 1 deletion(-) diff --git a/source4/rpc_server/handles.c b/source4/rpc_server/handles.c index 47174b6eeb..4831fb063d 100644 --- a/source4/rpc_server/handles.c +++ b/source4/rpc_server/handles.c @@ -29,7 +29,6 @@ static int dcesrv_handle_destructor(struct dcesrv_handle *h) { DLIST_REMOVE(h->context->handles, h); - talloc_free(h); return 0; } -- cgit From c5fdb82d3280a0c94c9b15be0090c08675338159 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Thu, 2 Oct 2008 21:58:46 -0700 Subject: fixed the sense of ldb base dn comparisons in two places, and use a direct comparison instead of a sub-tree comparison in another this fixes basedn searches on the global catalog port --- source4/cldap_server/netlogon.c | 2 +- source4/dsdb/samdb/ldb_modules/partition.c | 4 ++-- source4/dsdb/samdb/ldb_modules/proxy.c | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/source4/cldap_server/netlogon.c b/source4/cldap_server/netlogon.c index 7dccd81fad..b31e89b7a5 100644 --- a/source4/cldap_server/netlogon.c +++ b/source4/cldap_server/netlogon.c @@ -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; } diff --git a/source4/dsdb/samdb/ldb_modules/partition.c b/source4/dsdb/samdb/ldb_modules/partition.c index ad2901c308..7cc19a1012 100644 --- a/source4/dsdb/samdb/ldb_modules/partition.c +++ b/source4/dsdb/samdb/ldb_modules/partition.c @@ -493,7 +493,7 @@ static int partition_search(struct ldb_module *module, struct ldb_request *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) { + if (ldb_dn_compare_base(data->partitions[i]->dn, req->op.search.base) == 0) { ret = partition_prep_request(ac, data->partitions[i]); if (ret != LDB_SUCCESS) { return ret; @@ -578,7 +578,7 @@ static int partition_rename(struct ldb_module *module, struct ldb_request *req) } for (i=0; data && data->partitions && data->partitions[i]; i++) { - if (ldb_dn_compare_base(req->op.rename.olddn, data->partitions[i]->dn) == 0) { + if (ldb_dn_compare_base(data->partitions[i]->dn, req->op.rename.olddn) == 0) { matched = i; } } diff --git a/source4/dsdb/samdb/ldb_modules/proxy.c b/source4/dsdb/samdb/ldb_modules/proxy.c index 171832bbb4..18b0649dda 100644 --- a/source4/dsdb/samdb/ldb_modules/proxy.c +++ b/source4/dsdb/samdb/ldb_modules/proxy.c @@ -233,7 +233,7 @@ static void proxy_convert_record(struct ldb_context *ldb, int attr, v; /* fix the message DN */ - if (ldb_dn_compare_base(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); } @@ -322,7 +322,7 @@ static int proxy_search_bytree(struct ldb_module *module, struct ldb_request *re } /* 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; } -- cgit From 63e908e4b4b07455e14ac04d8efb3c4a3d043692 Mon Sep 17 00:00:00 2001 From: Matthias Dieter Wallnöfer Date: Fri, 3 Oct 2008 14:29:47 +0200 Subject: Fix regressions in patchfile after last patch, several other minor fixes. --- source4/lib/registry/patchfile.c | 42 +++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/source4/lib/registry/patchfile.c b/source4/lib/registry/patchfile.c index d49d46250d..a6f947ee78 100644 --- a/source4/lib/registry/patchfile.c +++ b/source4/lib/registry/patchfile.c @@ -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; -- cgit From 8e1d93e6a692676744c267dfd0d95802ff036a5f Mon Sep 17 00:00:00 2001 From: "Gerald (Jerry) Carter" Date: Fri, 3 Oct 2008 10:51:21 -0500 Subject: libaddns: Use the same prerequisite for DDNS update as Windows XP. Hostname, TYPE: CNAME, CLASS: NONE This has to have been broken for ages. I cannot see how it would have worked in any environment. --- source3/libaddns/dnsrecord.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source3/libaddns/dnsrecord.c b/source3/libaddns/dnsrecord.c index 500cbd6681..559c2644d4 100644 --- a/source3/libaddns/dnsrecord.c +++ b/source3/libaddns/dnsrecord.c @@ -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; -- cgit From c7625979ceb350d90d87d2add6ed7156440072c3 Mon Sep 17 00:00:00 2001 From: "Gerald (Jerry) Carter" Date: Fri, 3 Oct 2008 10:51:54 -0500 Subject: net_dns: Make "lwinet ads dns register" honor the "interfaces" parameter. This is helpful on multihomed hosts that only require a subset of IP addresses be registered with DNS. --- source3/utils/net_dns.c | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/source3/utils/net_dns.c b/source3/utils/net_dns.c index 14d45e2b0f..46f38d42f6 100644 --- a/source3/utils/net_dns.c +++ b/source3/utils/net_dns.c @@ -150,9 +150,10 @@ int get_my_ip_address( struct sockaddr_storage **pp_ss ) 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 +164,17 @@ int get_my_ip_address( struct sockaddr_storage **pp_ss ) } for ( i=0; i Date: Fri, 3 Oct 2008 12:21:53 -0700 Subject: fixed the partition module and the GC handling - when multiple partitions are searched, consider the search a success if any of the partitions return success - only search the right subset of partitions, looking at the scope and basedn of the search This fixes several errors with GC searches --- source4/dsdb/samdb/ldb_modules/partition.c | 42 +++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/partition.c b/source4/dsdb/samdb/ldb_modules/partition.c index 7cc19a1012..1274061e77 100644 --- a/source4/dsdb/samdb/ldb_modules/partition.c +++ b/source4/dsdb/samdb/ldb_modules/partition.c @@ -50,6 +50,7 @@ struct part_request { struct partition_context { struct ldb_module *module; struct ldb_request *req; + bool got_success; struct part_request *part_req; int num_requests; @@ -170,7 +171,8 @@ static int partition_req_callback(struct ldb_request *req, return ldb_module_done(ac->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR); } - if (ares->error != LDB_SUCCESS) { + + if (ares->error != LDB_SUCCESS && !ac->got_success) { return ldb_module_done(ac->req, ares->controls, ares->response, ares->error); } @@ -191,6 +193,9 @@ static int partition_req_callback(struct ldb_request *req, 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) { @@ -210,7 +215,8 @@ static int partition_req_callback(struct ldb_request *req, if (ac->finished_requests == ac->num_requests) { /* this was the last one, call callback */ return ldb_module_done(ac->req, ares->controls, - ares->response, ares->error); + ares->response, + ac->got_success?LDB_SUCCESS:ares->error); } /* not the last, now call the next one */ @@ -492,13 +498,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(data->partitions[i]->dn, req->op.search.base) == 0) { + 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 */ -- cgit From 4b9cc7d478438e34217add83b2647d47d52268a7 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Fri, 3 Oct 2008 14:05:33 -0700 Subject: Document "cups connection timeout". Jeremy. --- .../smbdotconf/printing/cupsconnectiontimeout.xml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 docs-xml/smbdotconf/printing/cupsconnectiontimeout.xml diff --git a/docs-xml/smbdotconf/printing/cupsconnectiontimeout.xml b/docs-xml/smbdotconf/printing/cupsconnectiontimeout.xml new file mode 100644 index 0000000000..1c7df15c3c --- /dev/null +++ b/docs-xml/smbdotconf/printing/cupsconnectiontimeout.xml @@ -0,0 +1,20 @@ + + + + This parameter is only applicable if is set to cups. + + + + 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. + + + +30 +60 + -- cgit From f6c883b4b00f4cd751cd312a27bddffb3be9c059 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Fri, 3 Oct 2008 14:18:35 -0700 Subject: Simply our main loop processing. A lot :-). Correctly use events for all the previous "special" cases. A step on the way to adding signals to the events and being able to merge the S3 event system with the S4 one. Jeremy. --- source3/auth/auth_domain.c | 65 +++++++++++++++ source3/include/proto.h | 3 +- source3/lib/dummysmbd.c | 15 ++++ source3/printing/notify.c | 26 ++++++ source3/smbd/process.c | 193 +++------------------------------------------ source3/smbd/reply.c | 3 - source3/smbd/server.c | 31 ++++++++ 7 files changed, 148 insertions(+), 188 deletions(-) diff --git a/source3/auth/auth_domain.c b/source3/auth/auth_domain.c index c25e62ab80..f11dbe60ee 100644 --- a/source3/auth/auth_domain.c +++ b/source3/auth/auth_domain.c @@ -26,6 +26,71 @@ 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/include/proto.h b/source3/include/proto.h index 2ccf3b15f7..6799106217 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -43,7 +43,8 @@ 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); /* The following definitions come from auth/auth_ntlmssp.c */ diff --git a/source3/lib/dummysmbd.c b/source3/lib/dummysmbd.c index dbe886e3d1..5c624bdebf 100644 --- a/source3/lib/dummysmbd.c +++ b/source3/lib/dummysmbd.c @@ -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; +} diff --git a/source3/printing/notify.c b/source3/printing/notify.c index 23df17c389..f6599c413d 100644 --- a/source3/printing/notify.c +++ b/source3/printing/notify.c @@ -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, diff --git a/source3/smbd/process.c b/source3/smbd/process.c index b2d19e11e3..32629fd392 100644 --- a/source3/smbd/process.c +++ b/source3/smbd/process.c @@ -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. diff --git a/source3/smbd/reply.c b/source3/smbd/reply.c index 8bfa28faea..0226d314f7 100644 --- a/source3/smbd/reply.c +++ b/source3/smbd/reply.c @@ -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; @@ -4611,8 +4610,6 @@ void reply_echo(struct smb_request *req) TALLOC_FREE(req->outbuf); - smb_echo_count++; - END_PROFILE(SMBecho); return; } diff --git a/source3/smbd/server.c b/source3/smbd/server.c index 53116f3d98..69a483e4fc 100644 --- a/source3/smbd/server.c +++ b/source3/smbd/server.c @@ -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()) { -- cgit From a9390d3047b7b7aba6f73c20e3dff292f7600a9f Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Fri, 3 Oct 2008 14:58:41 -0700 Subject: Correctly fix smbclient to terminate on eof from server. Jeremy. --- source3/client/client.c | 13 +++++++++++-- source3/include/proto.h | 1 + source3/lib/readline.c | 13 ++++++++++++- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/source3/client/client.c b/source3/client/client.c index 7af7d30108..4d6bf8f198 100644 --- a/source3/client/client.c +++ b/source3/client/client.c @@ -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); @@ -4419,7 +4423,12 @@ static void readline_callback(void) { unsigned char garbage[16]; memset(garbage, 0xf0, sizeof(garbage)); - cli_echo(cli, 1, data_blob_const(garbage, sizeof(garbage))); + if (!cli_echo(cli, 1, data_blob_const(garbage, sizeof(garbage)))) { + DEBUG(0, ("SMBecho failed. Maybe server has closed " + "the connection\n")); + finished = true; + smb_readline_done(); + } } } @@ -4431,7 +4440,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; diff --git a/source3/include/proto.h b/source3/include/proto.h index 6799106217..7cdcba19ab 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -708,6 +708,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); diff --git a/source3/lib/readline.c b/source3/lib/readline.c index 254f55c86a..fd57799b57 100644 --- a/source3/lib/readline.c +++ b/source3/lib/readline.c @@ -45,6 +45,16 @@ # define RL_COMPLETION_CAST #endif /* HAVE_NEW_LIBREADLINE */ +static bool smb_rl_done; + +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 +79,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 +97,7 @@ static char *smb_readline_replacement(const char *prompt, void (*callback)(void) callback(); } } + return NULL; } /**************************************************************************** -- cgit From e13270d7ac1b8d1a85e67e3b84ca9bfdf88aa0cd Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Fri, 3 Oct 2008 17:08:39 -0700 Subject: fixed the ldb blackbox test to work with non-bourne shells (as needed by ubuntu) fixed spelling of 'wellknown' --- testprogs/blackbox/test_ldb.sh | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/testprogs/blackbox/test_ldb.sh b/testprogs/blackbox/test_ldb.sh index 7a657d2e8d..1774dbc7a3 100755 --- a/testprogs/blackbox/test_ldb.sh +++ b/testprogs/blackbox/test_ldb.sh @@ -117,7 +117,7 @@ echo "Search Options Control Query test returned 0 items" failed=`expr $failed + 1` fi -function wellkown_object_test() { +wellknown_object_test() { local guid=$1 local object=$2 local basedns @@ -149,32 +149,32 @@ function wellkown_object_test() { return $failed } -wellkown_object_test 22B70C67D56E4EFB91E9300FCA3DC1AA ForeignSecurityPrincipals +wellknown_object_test 22B70C67D56E4EFB91E9300FCA3DC1AA ForeignSecurityPrincipals st=$? if [ x"$st" != x"0" ]; then failed=`expr $failed + $st` fi -wellkown_object_test 2FBAC1870ADE11D297C400C04FD8D5CD Infrastructure +wellknown_object_test 2FBAC1870ADE11D297C400C04FD8D5CD Infrastructure st=$? if [ x"$st" != x"0" ]; then failed=`expr $failed + $st` fi -wellkown_object_test AB1D30F3768811D1ADED00C04FD8D5CD System +wellknown_object_test AB1D30F3768811D1ADED00C04FD8D5CD System st=$? if [ x"$st" != x"0" ]; then failed=`expr $failed + $st` fi -wellkown_object_test A361B2FFFFD211D1AA4B00C04FD7D83A Domain Controllers +wellknown_object_test A361B2FFFFD211D1AA4B00C04FD7D83A Domain Controllers st=$? if [ x"$st" != x"0" ]; then failed=`expr $failed + $st` fi -wellkown_object_test AA312825768811D1ADED00C04FD8D5CD Computers +wellknown_object_test AA312825768811D1ADED00C04FD8D5CD Computers st=$? if [ x"$st" != x"0" ]; then failed=`expr $failed + $st` fi -wellkown_object_test A9D1CA15768811D1ADED00C04FD8D5CD Users +wellknown_object_test A9D1CA15768811D1ADED00C04FD8D5CD Users st=$? if [ x"$st" != x"0" ]; then failed=`expr $failed + $st` -- cgit From 025ff92f59512fd530f4f68306fea77b26061682 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Fri, 3 Oct 2008 17:10:53 -0700 Subject: expanded the netlogon test to better simulate the WSPP NRPC test that we had some trouble with --- source4/torture/rpc/netlogon.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/source4/torture/rpc/netlogon.c b/source4/torture/rpc/netlogon.c index 2522062696..3d4c594d05 100644 --- a/source4/torture/rpc/netlogon.c +++ b/source4/torture/rpc/netlogon.c @@ -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); -- cgit From ba5ef49f831dbbfec1a360cd4644999de822e2bc Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Fri, 3 Oct 2008 17:52:59 -0700 Subject: updated the LSA and NETLOGON servers with fixes resulting from the AD plugfest in Redmond --- source4/librpc/idl/lsa.idl | 39 ++++++++++------- source4/librpc/idl/netlogon.idl | 61 +++++++++++++++++++++------ source4/rpc_server/lsa/dcesrv_lsa.c | 57 ++++++++++++++++++++++--- source4/rpc_server/lsa/lsa_lookup.c | 32 ++++++++++---- source4/rpc_server/netlogon/dcerpc_netlogon.c | 44 ++++++++++++++++--- source4/torture/ndr/lsa.c | 8 ++-- source4/torture/rpc/lsa.c | 30 +++++++++---- 7 files changed, 211 insertions(+), 60 deletions(-) diff --git a/source4/librpc/idl/lsa.idl b/source4/librpc/idl/lsa.idl index e1c4499022..4dce6d6d1e 100644 --- a/source4/librpc/idl/lsa.idl +++ b/source4/librpc/idl/lsa.idl @@ -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 ( @@ -1009,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 */ @@ -1068,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 */ @@ -1148,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, @@ -1156,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 */ diff --git a/source4/librpc/idl/netlogon.idl b/source4/librpc/idl/netlogon.idl index 8a36922fdd..22e90878e7 100644 --- a/source4/librpc/idl/netlogon.idl +++ b/source4/librpc/idl/netlogon.idl @@ -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, diff --git a/source4/rpc_server/lsa/dcesrv_lsa.c b/source4/rpc_server/lsa/dcesrv_lsa.c index 7b15241b96..5e3be84cc5 100644 --- a/source4/rpc_server/lsa/dcesrv_lsa.c +++ b/source4/rpc_server/lsa/dcesrv_lsa.c @@ -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) @@ -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; } @@ -1004,7 +1048,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 +1132,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 +1272,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 +2830,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); } diff --git a/source4/rpc_server/lsa/lsa_lookup.c b/source4/rpc_server/lsa/lsa_lookup.c index 0ffb0572ee..2375a6d27a 100644 --- a/source4/rpc_server/lsa/lsa_lookup.c +++ b/source4/rpc_server/lsa/lsa_lookup.c @@ -525,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; @@ -583,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; @@ -683,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 (NT_STATUS_IS_ERR(status)) { - 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) { @@ -727,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; @@ -830,10 +845,11 @@ 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; @@ -952,8 +968,8 @@ NTSTATUS dcesrv_lsa_LookupNames(struct dcesrv_call_state *dce_call, TALLOC_CTX * 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); diff --git a/source4/rpc_server/netlogon/dcerpc_netlogon.c b/source4/rpc_server/netlogon/dcerpc_netlogon.c index cceb2a62ac..beb1c4eb06 100644 --- a/source4/rpc_server/netlogon/dcerpc_netlogon.c +++ b/source4/rpc_server/netlogon/dcerpc_netlogon.c @@ -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; @@ -898,20 +899,36 @@ 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 { + info->forest.string = "bludom.tridgell.net"; /* need ldb search */ + } + 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"); } @@ -942,11 +959,16 @@ static NTSTATUS dcesrv_netr_LogonGetDomainInfo(struct dcesrv_call_state *dce_cal const char *local_domain; + NDR_PRINT_IN_DEBUG(netr_LogonGetDomainInfo, r); + status = dcesrv_netr_creds_server_step_check(dce_call->event_ctx, dce_call->conn->dce_ctx->lp_ctx, r->in.computer_name, mem_ctx, 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,19 +1014,29 @@ 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;itrusts[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 = "blu.bludom.tridgell.net"; + 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; + NDR_PRINT_OUT_DEBUG(netr_LogonGetDomainInfo, r); + return NT_STATUS_OK; } diff --git a/source4/torture/ndr/lsa.c b/source4/torture/ndr/lsa.c index a72a03fa38..0d6d786882 100644 --- a/source4/torture/ndr/lsa.c +++ b/source4/torture/ndr/lsa.c @@ -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"); diff --git a/source4/torture/rpc/lsa.c b/source4/torture/rpc/lsa.c index 45f67afd69..efbdecab13 100644 --- a/source4/torture/rpc/lsa.c +++ b/source4/torture/rpc/lsa.c @@ -338,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; @@ -383,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; @@ -425,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; @@ -2243,7 +2243,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; @@ -2262,7 +2262,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; @@ -2352,7 +2359,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; @@ -2458,7 +2472,6 @@ bool torture_rpc_lsa(struct torture_context *tctx) if (!join) { ret = false; } - if (!test_LookupNames_wellknown(p, tctx, handle)) { ret = false; } @@ -2482,7 +2495,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; } -- cgit From af9dc6381da52c686d797a54d69b486214000cb5 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Fri, 3 Oct 2008 17:57:37 -0700 Subject: Fix the build farm. In this branch cli_echo returns NTSTATUS. Jeremy --- source3/client/client.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/source3/client/client.c b/source3/client/client.c index 4d6bf8f198..eb9f31bdf2 100644 --- a/source3/client/client.c +++ b/source3/client/client.c @@ -4421,9 +4421,12 @@ 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)); - if (!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; -- cgit From 0e0371b78a8d445cd0a08bd102a9a2c4952c235f Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sat, 4 Oct 2008 21:52:11 +0200 Subject: "gwen/cc" does not like the double const :-) --- source3/libnet/libnet_proto.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/libnet/libnet_proto.h b/source3/libnet/libnet_proto.h index 43046a44c0..69a16c1c7d 100644 --- a/source3/libnet/libnet_proto.h +++ b/source3/libnet/libnet_proto.h @@ -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 -- cgit From 87f496f3c1ff5c8fd72bcfb6b4af7cb539d5bc47 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sat, 4 Oct 2008 22:07:14 +0200 Subject: Fix a potential NULL deref in line 258 found by the IBM checker --- source3/libaddns/dnsmarshall.c | 1 + 1 file changed, 1 insertion(+) diff --git a/source3/libaddns/dnsmarshall.c b/source3/libaddns/dnsmarshall.c index 8c3389eb9b..5530290c57 100644 --- a/source3/libaddns/dnsmarshall.c +++ b/source3/libaddns/dnsmarshall.c @@ -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); -- cgit From 9eea6929e3420a0035ec3c0e3f1b4dd24847bbfa Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sat, 4 Oct 2008 22:15:03 +0200 Subject: Fix an uninitialized variable found by the IBM Checker --- source3/libads/ldap.c | 1 + 1 file changed, 1 insertion(+) diff --git a/source3/libads/ldap.c b/source3/libads/ldap.c index bfcfcf30b9..40f052281d 100644 --- a/source3/libads/ldap.c +++ b/source3/libads/ldap.c @@ -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; -- cgit From 80665a0b5abbdd8df735e1ccdab3206399beba0b Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sat, 4 Oct 2008 22:17:30 +0200 Subject: Fix an unlikely memleak found by the IBM checker --- source3/libads/util.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source3/libads/util.c b/source3/libads/util.c index 72f5dee80c..d23c36f326 100644 --- a/source3/libads/util.c +++ b/source3/libads/util.c @@ -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); } -- cgit From fe67306fc626333da4f03f6f2a823de9cc2b6cc2 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Sun, 5 Oct 2008 08:17:16 +1100 Subject: removed some debug lines I left in the last commit --- source4/rpc_server/netlogon/dcerpc_netlogon.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/source4/rpc_server/netlogon/dcerpc_netlogon.c b/source4/rpc_server/netlogon/dcerpc_netlogon.c index beb1c4eb06..64d0f77303 100644 --- a/source4/rpc_server/netlogon/dcerpc_netlogon.c +++ b/source4/rpc_server/netlogon/dcerpc_netlogon.c @@ -959,8 +959,6 @@ static NTSTATUS dcesrv_netr_LogonGetDomainInfo(struct dcesrv_call_state *dce_cal const char *local_domain; - NDR_PRINT_IN_DEBUG(netr_LogonGetDomainInfo, r); - status = dcesrv_netr_creds_server_step_check(dce_call->event_ctx, dce_call->conn->dce_ctx->lp_ctx, r->in.computer_name, mem_ctx, r->in.credential, @@ -1035,8 +1033,6 @@ static NTSTATUS dcesrv_netr_LogonGetDomainInfo(struct dcesrv_call_state *dce_cal r->out.info.info1 = info1; - NDR_PRINT_OUT_DEBUG(netr_LogonGetDomainInfo, r); - return NT_STATUS_OK; } -- cgit From de5edb1d0c0d60b337d2cbb7151db47d31bfa8d4 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Sun, 5 Oct 2008 15:48:46 +1100 Subject: remove dependencies on my home domain (in other words, don't do commits in airports) --- source4/rpc_server/netlogon/dcerpc_netlogon.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/source4/rpc_server/netlogon/dcerpc_netlogon.c b/source4/rpc_server/netlogon/dcerpc_netlogon.c index 64d0f77303..d5f7d2afae 100644 --- a/source4/rpc_server/netlogon/dcerpc_netlogon.c +++ b/source4/rpc_server/netlogon/dcerpc_netlogon.c @@ -918,7 +918,8 @@ static NTSTATUS fill_domain_trust_info(TALLOC_CTX *mem_ctx, /* MS-NRPC 3.5.4.3.9 - must be set to NULL for trust list */ info->forest.string = NULL; } else { - info->forest.string = "bludom.tridgell.net"; /* need ldb search */ + /* TODO: we need a common function for pulling the forest */ + info->forest.string = samdb_result_string(ref_res, "dnsRoot", NULL); } if (is_local) { @@ -1026,7 +1027,7 @@ static NTSTATUS dcesrv_netr_LogonGetDomainInfo(struct dcesrv_call_state *dce_cal true, true); NT_STATUS_NOT_OK_RETURN(status); - info1->dns_hostname.string = "blu.bludom.tridgell.net"; + 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 */ -- cgit From 6ee4e81ad13fba417a4e50b5c162a799e44adf27 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sun, 5 Oct 2008 10:55:30 +0200 Subject: Fix an uninitialized variable warning Not sure if we can ever not get domain and dns_domain, but gcc complained --- source3/libsmb/dsgetdcname.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source3/libsmb/dsgetdcname.c b/source3/libsmb/dsgetdcname.c index 18010aaa1c..08ab8cad14 100644 --- a/source3/libsmb/dsgetdcname.c +++ b/source3/libsmb/dsgetdcname.c @@ -228,6 +228,8 @@ static NTSTATUS store_cldap_reply(TALLOC_CTX *mem_ctx, } } + status = NT_STATUS_OK; + done: data_blob_free(&blob); -- cgit From 01ecd766c86ad49c7d8b9095bef76b5dcc71d757 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sun, 5 Oct 2008 13:12:31 +0200 Subject: OS/X does not have rl_done in readline.h --- source3/lib/readline.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/source3/lib/readline.c b/source3/lib/readline.c index fd57799b57..cafb5a9f62 100644 --- a/source3/lib/readline.c +++ b/source3/lib/readline.c @@ -47,6 +47,14 @@ 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; -- cgit From 8670235f2a2b9ef4b6863c185bd2ab57acd7e57a Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sun, 5 Oct 2008 13:58:09 +0200 Subject: Fix some missing error handlings --- source3/lib/netapi/file.c | 3 ++- source3/lib/netapi/getdc.c | 4 ++++ source3/lib/netapi/share.c | 3 ++- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/source3/lib/netapi/file.c b/source3/lib/netapi/file.c index 036af32f38..0d66be0eb1 100644 --- a/source3/lib/netapi/file.c +++ b/source3/lib/netapi/file.c @@ -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; } diff --git a/source3/lib/netapi/getdc.c b/source3/lib/netapi/getdc.c index 07a6544af1..76c0d0be2a 100644 --- a/source3/lib/netapi/getdc.c +++ b/source3/lib/netapi/getdc.c @@ -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; diff --git a/source3/lib/netapi/share.c b/source3/lib/netapi/share.c index 1d0e1810f1..e6aed36064 100644 --- a/source3/lib/netapi/share.c +++ b/source3/lib/netapi/share.c @@ -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; } -- cgit From 9bb6bae4ef5c02cb2b6c325e228fc4f4d4366167 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sun, 5 Oct 2008 15:48:55 +0200 Subject: Remove an unused variable --- source3/utils/net_dns.c | 1 - 1 file changed, 1 deletion(-) diff --git a/source3/utils/net_dns.c b/source3/utils/net_dns.c index 46f38d42f6..4e617a1968 100644 --- a/source3/utils/net_dns.c +++ b/source3/utils/net_dns.c @@ -145,7 +145,6 @@ 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; -- cgit From 9542b2fe60482382459d387294fb92c182f35d64 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sun, 5 Oct 2008 16:09:18 +0200 Subject: Re-enable build of smb_samba3.c after the rename smbd->samba --- source4/smb_server/config.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/smb_server/config.mk b/source4/smb_server/config.mk index 8ed03b17fe..6a1a50ffbf 100644 --- a/source4/smb_server/config.mk +++ b/source4/smb_server/config.mk @@ -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 -- cgit From 1a228b442e9382167872fb863529001ac71d7567 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sun, 5 Oct 2008 20:47:00 +0200 Subject: smbd3 is unhappy if stderr is not open --- source4/smb_server/smb_samba3.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source4/smb_server/smb_samba3.c b/source4/smb_server/smb_samba3.c index 7b3229892f..259d29039d 100644 --- a/source4/smb_server/smb_samba3.c +++ b/source4/smb_server/smb_samba3.c @@ -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); } -- cgit From 41ee314438fe15d3bdd6a86ad5acf953c255011c Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Sun, 5 Oct 2008 16:14:27 +0200 Subject: Fix some nonempty blank lines --- source3/libsmb/cliquota.c | 50 +++++++++++++++++++++++------------------------ 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/source3/libsmb/cliquota.c b/source3/libsmb/cliquota.c index f369d28dff..dcdfec241d 100644 --- a/source3/libsmb/cliquota.c +++ b/source3/libsmb/cliquota.c @@ -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 . */ @@ -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 { -- cgit From bb4e9d72dd7de46ae4635ff5fbe5427b2a93e7cc Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Thu, 2 Oct 2008 19:31:56 +0200 Subject: s4:blackbox/test_ldb: test search by and metze --- testprogs/blackbox/test_ldb.sh | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/testprogs/blackbox/test_ldb.sh b/testprogs/blackbox/test_ldb.sh index 1774dbc7a3..5209abeb2c 100755 --- a/testprogs/blackbox/test_ldb.sh +++ b/testprogs/blackbox/test_ldb.sh @@ -180,4 +180,29 @@ 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 -- cgit From f3ba7fc0b973ea66ee57fe0e1be73b3bcefc07fb Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Mon, 22 Sep 2008 19:23:21 +0200 Subject: Store a local schannel key in secrets.tdb --- source3/include/proto.h | 2 ++ source3/include/secrets.h | 2 ++ source3/passdb/secrets.c | 25 +++++++++++++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/source3/include/proto.h b/source3/include/proto.h index 7cdcba19ab..41544da8c9 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -6421,6 +6421,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 */ diff --git a/source3/include/secrets.h b/source3/include/secrets.h index d9f457558b..3c8e2ccf81 100644 --- a/source3/include/secrets.h +++ b/source3/include/secrets.h @@ -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" diff --git a/source3/passdb/secrets.c b/source3/passdb/secrets.c index 4527ae7127..306d4d0a35 100644 --- a/source3/passdb/secrets.c +++ b/source3/passdb/secrets.c @@ -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 * -- cgit From 2f6026248ec9a84f6a263622f1753e98c89eb543 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Mon, 22 Sep 2008 19:24:59 +0200 Subject: Add dyn_NCALRPCDIR --- source3/Makefile.in | 2 ++ source3/dynconfig.c | 1 + source3/include/dynconfig.h | 4 ++++ source3/m4/check_path.m4 | 19 +++++++++++++++++++ 4 files changed, 26 insertions(+) diff --git a/source3/Makefile.in b/source3/Makefile.in index 61e946e7cd..1bb2b87a4a 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -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)\" \ diff --git a/source3/dynconfig.c b/source3/dynconfig.c index 3a54507599..6125f9944c 100644 --- a/source3/dynconfig.c +++ b/source3/dynconfig.c @@ -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) diff --git a/source3/include/dynconfig.h b/source3/include/dynconfig.h index 758bde33cc..8267064f23 100644 --- a/source3/include/dynconfig.h +++ b/source3/include/dynconfig.h @@ -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/m4/check_path.m4 b/source3/m4/check_path.m4 index 7aa8c213e0..40a97d3674 100644 --- a/source3/m4/check_path.m4 +++ b/source3/m4/check_path.m4 @@ -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) -- cgit From 439086099ad97a49c93102af1e6edafabea64b6f Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Mon, 22 Sep 2008 19:29:05 +0200 Subject: Add netlogond auth method This authenticates against a local running samba4 using SamLogonEx. We retrieve the machine password using samba4's mymachinepwd script and store the schannel key for re-use in secrets.tdb. --- source3/Makefile.in | 5 + source3/auth/auth_netlogond.c | 321 ++++++++++++++++++++++++++++++++++++++++++ source3/configure.in | 3 +- source3/include/proto.h | 2 + 4 files changed, 330 insertions(+), 1 deletion(-) create mode 100644 source3/auth/auth_netlogond.c diff --git a/source3/Makefile.in b/source3/Makefile.in index 1bb2b87a4a..eb6a05cba5 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -638,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 \ @@ -2197,6 +2198,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) diff --git a/source3/auth/auth_netlogond.c b/source3/auth/auth_netlogond.c new file mode 100644 index 0000000000..a57f3b74a3 --- /dev/null +++ b/source3/auth/auth_netlogond.c @@ -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 . +*/ + +#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; +} diff --git a/source3/configure.in b/source3/configure.in index 545a5653de..1eba4a0a58 100644 --- a/source3/configure.in +++ b/source3/configure.in @@ -404,7 +404,7 @@ 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 vfs_smb_traffic_analyzer" @@ -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) diff --git a/source3/include/proto.h b/source3/include/proto.h index 41544da8c9..30e309cd4e 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -46,6 +46,8 @@ bool password_ok(const char *smb_name, DATA_BLOB password_blob); 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 */ NTSTATUS auth_ntlmssp_start(AUTH_NTLMSSP_STATE **auth_ntlmssp_state); -- cgit From 6aa8613b11b596fed115849262e96524b84a8fbe Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Mon, 6 Oct 2008 10:57:13 +0200 Subject: Log in the parent winbind log where a request is going --- source3/winbindd/winbindd_dual.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source3/winbindd/winbindd_dual.c b/source3/winbindd/winbindd_dual.c index 1600f05eb1..f6a9c1f26d 100644 --- a/source3/winbindd/winbindd_dual.c +++ b/source3/winbindd/winbindd_dual.c @@ -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) { -- cgit From f4095b62a8030cb9d929bb113f3488f3917b8f9b Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Mon, 6 Oct 2008 14:49:10 +0200 Subject: If name_to_fqdn fails, retry with the dns domain the DC gave us This is a workaround for the cases where you want to join under a netbios name that is different from your hostname, i.e. a name that can not be found in /etc/hosts or dns. In these cases, name_to_fqdn fails or gives invalid results. --- source3/libnet/libnet_join.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/source3/libnet/libnet_join.c b/source3/libnet/libnet_join.c index a39dee676f..ab8af0be6b 100644 --- a/source3/libnet/libnet_join.c +++ b/source3/libnet/libnet_join.c @@ -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); -- cgit From 999b69d176a967aad8b6a871632d1869757181aa Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Wed, 1 Oct 2008 02:27:09 +0200 Subject: s4:gensec: pass down want_features to the spnego backend mech metze --- source4/auth/gensec/gensec.c | 8 +++++++- source4/auth/gensec/gensec.h | 2 ++ source4/auth/gensec/spnego.c | 15 +++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/source4/auth/gensec/gensec.c b/source4/auth/gensec/gensec.c index 0edb34d740..5d57383d2a 100644 --- a/source4/auth/gensec/gensec.c +++ b/source4/auth/gensec/gensec.c @@ -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); } /** diff --git a/source4/auth/gensec/gensec.h b/source4/auth/gensec/gensec.h index 84fc26d127..0b31882ddd 100644 --- a/source4/auth/gensec/gensec.h +++ b/source4/auth/gensec/gensec.h @@ -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; diff --git a/source4/auth/gensec/spnego.c b/source4/auth/gensec/spnego.c index 1855e0583d..bf991616bd 100644 --- a/source4/auth/gensec/spnego.c +++ b/source4/auth/gensec/spnego.c @@ -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 -- cgit From 9e492b1ba2ccf2d7c62ef7295b33260687e3aeae Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Mon, 6 Oct 2008 19:39:53 +0200 Subject: s4:rpc_server: tell the gensec layer that we want to do header signing Note: header signing is still off by default, as the gensec backends don't support it together with seal yet. metze --- source4/rpc_server/dcesrv_auth.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source4/rpc_server/dcesrv_auth.c b/source4/rpc_server/dcesrv_auth.c index 52d5631cfd..bef7e4be78 100644 --- a/source4/rpc_server/dcesrv_auth.c +++ b/source4/rpc_server/dcesrv_auth.c @@ -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; } -- cgit From 338f658a5a300e21cc69b1a84ebbdc7d63262448 Mon Sep 17 00:00:00 2001 From: "Gerald (Jerry) Carter" Date: Mon, 6 Oct 2008 11:34:45 -0500 Subject: idmap_adex: Add log messages to dc_add_domain for easier debugging. Part of continue work on BUG 5806. --- source3/winbindd/idmap_adex/domain_util.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/source3/winbindd/idmap_adex/domain_util.c b/source3/winbindd/idmap_adex/domain_util.c index ab31ccef7a..6851503cc8 100644 --- a/source3/winbindd/idmap_adex/domain_util.c +++ b/source3/winbindd/idmap_adex/domain_util.c @@ -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); -- cgit From 2a35985283be45adbba63b5d7ced8499bcb64f59 Mon Sep 17 00:00:00 2001 From: "Gerald (Jerry) Carter" Date: Mon, 6 Oct 2008 11:47:57 -0500 Subject: idmap_adex: Add more debugging to the basic search function. Log the dn of all located entries in order to verify search results. --- source3/winbindd/idmap_adex/likewise_cell.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/source3/winbindd/idmap_adex/likewise_cell.c b/source3/winbindd/idmap_adex/likewise_cell.c index 77eeee406b..7723b3e015 100644 --- a/source3/winbindd/idmap_adex/likewise_cell.c +++ b/source3/winbindd/idmap_adex/likewise_cell.c @@ -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 : "")); + SAFE_FREE(dn); + } + } + return status; } -- cgit From c412a930ad19da866503e6d8ccb71fb3191fc6d2 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Fri, 3 Oct 2008 16:25:59 -0700 Subject: Fix Domain Trust creation with Windows 2008 (and many other tools) A dITConentRules attribute (unlike objectClasses) must not contain a 'SUP'. The ADSI layer in Windows would download the whole schema, and validate it. Thanks to the team at Microsoft for very long debugging session to find this. Andrew Bartlett --- source4/dsdb/schema/schema_description.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/source4/dsdb/schema/schema_description.c b/source4/dsdb/schema/schema_description.c index 6884c5284e..e152f44b97 100644 --- a/source4/dsdb/schema/schema_description.c +++ b/source4/dsdb/schema/schema_description.c @@ -309,7 +309,11 @@ char *schema_class_to_dITContentRule(TALLOC_CTX *mem_ctx, const struct dsdb_clas 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; -- cgit From 7d9f18609b25463d306c0c150fe0da7f065860fd Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Fri, 3 Oct 2008 16:36:04 -0700 Subject: Remove DESCRIPTION from generated schema lines. This is not permitted in the AD aggregate schema, and more trouble than it is worth in the OpenLDAP schema due to escaping issues. Andrew Bartlett --- source4/dsdb/schema/schema_description.c | 21 +-------------------- source4/utils/ad2oLschema.c | 14 ++++++++++---- 2 files changed, 11 insertions(+), 24 deletions(-) diff --git a/source4/dsdb/schema/schema_description.c b/source4/dsdb/schema/schema_description.c index e152f44b97..c3c37b4653 100644 --- a/source4/dsdb/schema/schema_description.c +++ b/source4/dsdb/schema/schema_description.c @@ -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,7 +290,6 @@ char *schema_class_to_dITContentRule(TALLOC_CTX *mem_ctx, const struct dsdb_clas class->governsID_oid, class->lDAPDisplayName, (const char **)aux_class_list, - NULL, NULL, /* Must not specify a * SUP (subclass) in * ditContentRules diff --git a/source4/utils/ad2oLschema.c b/source4/utils/ad2oLschema.c index 3c2ffe7a00..c579112b45 100644 --- a/source4/utils/ad2oLschema.c +++ b/source4/utils/ad2oLschema.c @@ -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, -- cgit From c0240d78351e489c5aca7e729aac045157080088 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Sat, 4 Oct 2008 10:25:46 -0700 Subject: Remove compleatly bogus rename test in partitions module. --- source4/dsdb/samdb/ldb_modules/partition.c | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/partition.c b/source4/dsdb/samdb/ldb_modules/partition.c index 8e4483a78e..b452b66d56 100644 --- a/source4/dsdb/samdb/ldb_modules/partition.c +++ b/source4/dsdb/samdb/ldb_modules/partition.c @@ -589,7 +589,6 @@ 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; @@ -619,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(data->partitions[i]->dn, req->op.rename.olddn) == 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); } -- cgit From 8256717c766fb8e145c2f4b5acb3502f4d7c57d9 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Tue, 30 Sep 2008 14:24:58 -0700 Subject: Implement 'type unknown' names in the CrackNames code. This guesses the type by running each of the possible options. Andrew Bartlett --- source4/dsdb/samdb/cracknames.c | 58 ++++++++++++++++++++++++++------ source4/librpc/idl/drsuapi.idl | 2 +- source4/torture/rpc/drsuapi_cracknames.c | 1 + 3 files changed, 50 insertions(+), 11 deletions(-) diff --git a/source4/dsdb/samdb/cracknames.c b/source4/dsdb/samdb/cracknames.c index e02e8d81a6..ca87159c58 100644 --- a/source4/dsdb/samdb/cracknames.c +++ b/source4/dsdb/samdb/cracknames.c @@ -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; @@ -1265,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) { @@ -1282,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); diff --git a/source4/librpc/idl/drsuapi.idl b/source4/librpc/idl/drsuapi.idl index 76858b2d5c..a41bc9cf19 100644 --- a/source4/librpc/idl/drsuapi.idl +++ b/source4/librpc/idl/drsuapi.idl @@ -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, diff --git a/source4/torture/rpc/drsuapi_cracknames.c b/source4/torture/rpc/drsuapi_cracknames.c index fbda69df57..a9a614953d 100644 --- a/source4/torture/rpc/drsuapi_cracknames.c +++ b/source4/torture/rpc/drsuapi_cracknames.c @@ -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, -- cgit From 8cdb3ebe27814629cb17d2a438c89780c5cecfdf Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Wed, 1 Oct 2008 13:10:11 -0700 Subject: Clarify use of manual parsers in trustInOutBlob (drsblobs.idl) --- source4/librpc/idl/drsblobs.idl | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/source4/librpc/idl/drsblobs.idl b/source4/librpc/idl/drsblobs.idl index 31fe8a359e..4274d2000a 100644 --- a/source4/librpc/idl/drsblobs.idl +++ b/source4/librpc/idl/drsblobs.idl @@ -409,21 +409,23 @@ 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; + void decode_trustAuthInOut( + [in] trustAuthInOutBlob blob + ); + typedef [public,gensize] struct { uint32 count; [relative] AuthenticationInformation *current[count]; } trustCurrentPasswords; - void decode_trustAuthInOut( - [in] trustAuthInOutBlob blob - ); - typedef [public,nopull] struct { uint8 confounder[512]; [subcontext(0),subcontext_size(outgoing_size)] trustCurrentPasswords outgoing; -- cgit From 8e1c0470d72ca85d837bbdd4aec0ca2f27a7a29f Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Wed, 1 Oct 2008 13:10:35 -0700 Subject: Add in secure channel type used by AD trusts --- source4/librpc/idl/misc.idl | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/source4/librpc/idl/misc.idl b/source4/librpc/idl/misc.idl index 8331977398..791b86466c 100644 --- a/source4/librpc/idl/misc.idl +++ b/source4/librpc/idl/misc.idl @@ -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 */ -- cgit From 99d0eb4fb701c500f0175ca9a38482160bdb08e4 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Wed, 1 Oct 2008 13:11:11 -0700 Subject: Make RPC-LSA test for enumeration conditions more strict --- source4/torture/rpc/lsa.c | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/source4/torture/rpc/lsa.c b/source4/torture/rpc/lsa.c index efbdecab13..245ed1e41b 100644 --- a/source4/torture/rpc/lsa.c +++ b/source4/torture/rpc/lsa.c @@ -1899,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) { @@ -1950,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) { @@ -2115,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; @@ -2160,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) { @@ -2188,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; } } -- cgit From 1a29fd1cf5436c850c7de180668a7a33f9b034d8 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Wed, 1 Oct 2008 13:12:15 -0700 Subject: Store trusted domain passwords in the LSA server --- source4/rpc_server/lsa/dcesrv_lsa.c | 68 ++++++++++++++++++++++++++++++++++--- 1 file changed, 64 insertions(+), 4 deletions(-) diff --git a/source4/rpc_server/lsa/dcesrv_lsa.c b/source4/rpc_server/lsa/dcesrv_lsa.c index 5e3be84cc5..836fd8dc62 100644 --- a/source4/rpc_server/lsa/dcesrv_lsa.c +++ b/source4/rpc_server/lsa/dcesrv_lsa.c @@ -727,13 +727,46 @@ static NTSTATUS dcesrv_lsa_CreateTrustedDomain_base(struct dcesrv_call_state *dc 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, - (ndr_push_flags_fn_t)ndr_push_trustDomainPasswords); + &incoming, + (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { return NT_STATUS_INVALID_PARAMETER; } @@ -742,10 +775,37 @@ 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, - (ndr_push_flags_fn_t)ndr_push_trustDomainPasswords); + &outgoing, + (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { return NT_STATUS_INVALID_PARAMETER; } -- cgit From 320d402180ac2d8505aec2664feaddbd63e5b17e Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Wed, 1 Oct 2008 13:31:22 -0700 Subject: Start implementing AD-style trusted domains in Samba4's NETLOGON server --- source4/rpc_server/netlogon/dcerpc_netlogon.c | 52 +++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/source4/rpc_server/netlogon/dcerpc_netlogon.c b/source4/rpc_server/netlogon/dcerpc_netlogon.c index d5f7d2afae..b948d1210e 100644 --- a/source4/rpc_server/netlogon/dcerpc_netlogon.c +++ b/source4/rpc_server/netlogon/dcerpc_netlogon.c @@ -87,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; @@ -101,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", @@ -130,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)); -- cgit From 912209ac84395ef0e2fca0556b1e4bec34367b5c Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Wed, 1 Oct 2008 16:00:33 -0700 Subject: Use the trust password version as kvno for trusts in Kerberos. --- source4/kdc/hdb-samba4.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/source4/kdc/hdb-samba4.c b/source4/kdc/hdb-samba4.c index d7317f17d4..818c4a12fd 100644 --- a/source4/kdc/hdb-samba4.c +++ b/source4/kdc/hdb-samba4.c @@ -717,6 +717,7 @@ static krb5_error_code LDB_trust_message2entry(krb5_context context, HDB *db, enum ndr_err_code ndr_err; int i, ret, trust_direction_flags; + uint32_t kvno; private = talloc(mem_ctx, struct hdb_ldb_private); if (!private) { @@ -764,6 +765,12 @@ static krb5_error_code LDB_trust_message2entry(krb5_context context, HDB *db, goto out; } + 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, -- cgit From 6a5547742f0b87017e4d21c80ec8facece6688d0 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Thu, 2 Oct 2008 11:29:34 -0700 Subject: Allow the PAC to be passed along during cross-realm authentication --- source4/heimdal/kdc/krb5tgs.c | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/source4/heimdal/kdc/krb5tgs.c b/source4/heimdal/kdc/krb5tgs.c index 19dff5e01d..d557da2a5b 100644 --- a/source4/heimdal/kdc/krb5tgs.c +++ b/source4/heimdal/kdc/krb5tgs.c @@ -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 */ -- cgit From c3b28c7a81c04a0f019b6c1e543a65d6d48b0b2c Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Thu, 2 Oct 2008 11:30:14 -0700 Subject: Fix cross-realm authentication in Samba4's KDC. --- source4/kdc/hdb-samba4.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/source4/kdc/hdb-samba4.c b/source4/kdc/hdb-samba4.c index 818c4a12fd..5b7f55822e 100644 --- a/source4/kdc/hdb-samba4.c +++ b/source4/kdc/hdb-samba4.c @@ -758,7 +758,7 @@ 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; @@ -813,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); @@ -1155,7 +1157,7 @@ static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db, 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; @@ -1193,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; -- cgit From e0a4d7f467d9727563adaaa97961edd06886490e Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Fri, 3 Oct 2008 16:36:49 -0700 Subject: Set default trust kvno to -1 --- source4/kdc/hdb-samba4.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/kdc/hdb-samba4.c b/source4/kdc/hdb-samba4.c index 5b7f55822e..51f464cd09 100644 --- a/source4/kdc/hdb-samba4.c +++ b/source4/kdc/hdb-samba4.c @@ -717,7 +717,6 @@ static krb5_error_code LDB_trust_message2entry(krb5_context context, HDB *db, enum ndr_err_code ndr_err; int i, ret, trust_direction_flags; - uint32_t kvno; private = talloc(mem_ctx, struct hdb_ldb_private); if (!private) { @@ -765,6 +764,7 @@ static krb5_error_code LDB_trust_message2entry(krb5_context context, HDB *db, 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; -- cgit From f19086872ec734fff3f2119712ff24117bec4e5e Mon Sep 17 00:00:00 2001 From: Tim Prouty Date: Mon, 6 Oct 2008 16:41:46 -0700 Subject: Fixed "declaration shadows global declaration" warnings. The patch simply uses a more descriptive variable name for tcp_seq. ../lib/socket_wrapper/socket_wrapper.c:753: warning: declaration of 'tcp_seq' shadows a global declaration /usr/include/netinet/tcp.h:40: warning: shadowed declaration is here ../lib/socket_wrapper/socket_wrapper.c: In function `swrap_marshall_packet': ../lib/socket_wrapper/socket_wrapper.c:919: warning: declaration of 'tcp_seq' shadows a global declaration /usr/include/netinet/tcp.h:40: warning: shadowed declaration is here --- lib/socket_wrapper/socket_wrapper.c | 38 ++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/lib/socket_wrapper/socket_wrapper.c b/lib/socket_wrapper/socket_wrapper.c index e8d27adc37..ecb6142cfc 100644 --- a/lib/socket_wrapper/socket_wrapper.c +++ b/lib/socket_wrapper/socket_wrapper.c @@ -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_seq_num, 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_seq_num); 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num = 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_seq_num, tcp_ack, tcp_ctl, unreachable, packet_len); } -- cgit From cde1b09d68e496f8f531336088433e9546b2864d Mon Sep 17 00:00:00 2001 From: Tim Prouty Date: Mon, 6 Oct 2008 17:09:48 -0700 Subject: Fixed build warning "passing arg from incompatible pointer type" The fix explicitly makes the conversion from timeval to time_t using the existing time utility functions. Compiling modules/vfs_smb_traffic_analyzer.c modules/vfs_smb_traffic_analyzer.c: In function `smb_traffic_analyzer_send_data': modules/vfs_smb_traffic_analyzer.c:173: warning: passing arg 1 of `localtime' from incompatible pointer type --- source3/modules/vfs_smb_traffic_analyzer.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source3/modules/vfs_smb_traffic_analyzer.c b/source3/modules/vfs_smb_traffic_analyzer.c index ff61768495..9b4c1b3e25 100644 --- a/source3/modules/vfs_smb_traffic_analyzer.c +++ b/source3/modules/vfs_smb_traffic_analyzer.c @@ -156,6 +156,7 @@ static void smb_traffic_analyzer_send_data(vfs_handle_struct *handle, { struct refcounted_sock *rf_sock = NULL; struct timeval tv; + time_t tv_sec; struct tm *tm = NULL; int seconds; char *str = NULL; @@ -170,7 +171,8 @@ static void smb_traffic_analyzer_send_data(vfs_handle_struct *handle, } GetTimeOfDay(&tv); - tm=localtime(&tv.tv_sec); + tv_sec = convert_timespec_to_time_t(convert_timeval_to_timespec(tv)); + tm = localtime(&tv_sec); if (!tm) { return; } -- cgit From abf00f710dc3a4b3fab8058a4c4f0df37b1baac4 Mon Sep 17 00:00:00 2001 From: Tim Prouty Date: Tue, 7 Oct 2008 10:56:30 -0700 Subject: Changed variable name from f19086872ec734fff3f2119712ff24117bec4e5e to match v3-[23]-test --- lib/socket_wrapper/socket_wrapper.c | 38 ++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/lib/socket_wrapper/socket_wrapper.c b/lib/socket_wrapper/socket_wrapper.c index ecb6142cfc..9d61976950 100644 --- a/lib/socket_wrapper/socket_wrapper.c +++ b/lib/socket_wrapper/socket_wrapper.c @@ -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_num, + 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_num); + 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_num = 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_num = 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_num = 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_num = 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_num = 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_num = 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_num = 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_num = 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_num = 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_num = 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_num = 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_num = 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_num = 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_num = 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_num = 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_num = 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_num, tcp_ack, tcp_ctl, unreachable, + tcp_seqno, tcp_ack, tcp_ctl, unreachable, packet_len); } -- cgit From 2024d87cf5ffa0633225ed189fa48f0f56151e7e Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Tue, 7 Oct 2008 14:43:42 -0700 Subject: Make map_errno_from_nt_status() a generic call, not just a cli specific one. Remove some unused calls from vfs_acl_xattr. Test for SD's on existing files. Jeremy. --- source3/include/proto.h | 1 + source3/lib/errmap_unix.c | 136 ++++++++++++++++++++++++++++++++++++++ source3/libsmb/clierror.c | 140 +--------------------------------------- source3/modules/vfs_acl_xattr.c | 58 ++++++++++------- 4 files changed, 175 insertions(+), 160 deletions(-) diff --git a/source3/include/proto.h b/source3/include/proto.h index 30e309cd4e..d7acdcb910 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -515,6 +515,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 */ diff --git a/source3/lib/errmap_unix.c b/source3/lib/errmap_unix.c index 2cd2386c5c..9adb237096 100644 --- a/source3/lib/errmap_unix.c +++ b/source3/lib/errmap_unix.c @@ -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; +} diff --git a/source3/libsmb/clierror.c b/source3/libsmb/clierror.c index 36746419f7..54f8a7a43c 100644 --- a/source3/libsmb/clierror.c +++ b/source3/libsmb/clierror.c @@ -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); } /* diff --git a/source3/modules/vfs_acl_xattr.c b/source3/modules/vfs_acl_xattr.c index a2f3477b76..80e44e51fc 100644 --- a/source3/modules/vfs_acl_xattr.c +++ b/source3/modules/vfs_acl_xattr.c @@ -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) { @@ -312,9 +328,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 */ -- cgit From 20b73b1309a74eee3fbf37738407584dce63bb78 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Mon, 6 Oct 2008 04:54:48 +0200 Subject: Print proper error if include file can't be found. --- pidl/lib/Parse/Pidl/ODL.pm | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pidl/lib/Parse/Pidl/ODL.pm b/pidl/lib/Parse/Pidl/ODL.pm index ad8c76f622..c49cdfb795 100644 --- a/pidl/lib/Parse/Pidl/ODL.pm +++ b/pidl/lib/Parse/Pidl/ODL.pm @@ -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; -- cgit From c024fb7d5745dbca96b969c88284b70ac7c520e4 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Mon, 6 Oct 2008 16:00:10 +0200 Subject: Allow 'make testenv-dc', 'make testenv-member', etc. --- source4/selftest/config.mk | 3 +++ 1 file changed, 3 insertions(+) diff --git a/source4/selftest/config.mk b/source4/selftest/config.mk index 2fcb71eb7a..e4bb2df0ad 100644 --- a/source4/selftest/config.mk +++ b/source4/selftest/config.mk @@ -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 -- cgit From 8da78b732554a88bee0f1dd547e329fe8d82b7f9 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 8 Oct 2008 01:48:44 +0200 Subject: Move subunit helper utility to specific subunit directory. --- lib/unit | 36 ++++++++++++++++++++++++++++++++++++ source4/script/harness2subunit.pl | 36 ------------------------------------ source4/selftest/samba4_tests.sh | 2 +- 3 files changed, 37 insertions(+), 37 deletions(-) create mode 100755 lib/unit delete mode 100755 source4/script/harness2subunit.pl diff --git a/lib/unit b/lib/unit new file mode 100755 index 0000000000..45f515540b --- /dev/null +++ b/lib/unit @@ -0,0 +1,36 @@ +#!/usr/bin/perl +# Simple script that converts Perl test harness output to +# Subunit +# Copyright (C) 2008 Jelmer Vernooij +# Published under the GNU GPL, v3 or later + +my $firstline = 1; +my $error = 0; +while() { + if ($firstline) { + $firstline = 0; + next; + } + if (/^not ok (\d+) - (.*)$/) { + print "test: $2\n"; + print "failure: $2\n"; + $error = 1; + } elsif (/^ok (\d+) - (.*)$/) { + print "test: $2\n"; + print "success: $2\n"; + } elsif (/^ok (\d+)$/) { + print "test: $1\n"; + print "success: $1\n"; + } elsif (/^ok (\d+) # skip (.*)$/) { + print "test: $1\n"; + print "skip: $1 [\n$2\n]\n"; + } elsif (/^not ok (\d+)$/) { + print "test: $1\n"; + print "failure: $1\n"; + $error = 1; + } else { + print; + } +} +exit $error; + diff --git a/source4/script/harness2subunit.pl b/source4/script/harness2subunit.pl deleted file mode 100755 index 45f515540b..0000000000 --- a/source4/script/harness2subunit.pl +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/perl -# Simple script that converts Perl test harness output to -# Subunit -# Copyright (C) 2008 Jelmer Vernooij -# Published under the GNU GPL, v3 or later - -my $firstline = 1; -my $error = 0; -while() { - if ($firstline) { - $firstline = 0; - next; - } - if (/^not ok (\d+) - (.*)$/) { - print "test: $2\n"; - print "failure: $2\n"; - $error = 1; - } elsif (/^ok (\d+) - (.*)$/) { - print "test: $2\n"; - print "success: $2\n"; - } elsif (/^ok (\d+)$/) { - print "test: $1\n"; - print "success: $1\n"; - } elsif (/^ok (\d+) # skip (.*)$/) { - print "test: $1\n"; - print "skip: $1 [\n$2\n]\n"; - } elsif (/^not ok (\d+)$/) { - print "test: $1\n"; - print "failure: $1\n"; - $error = 1; - } else { - print; - } -} -exit $error; - diff --git a/source4/selftest/samba4_tests.sh b/source4/selftest/samba4_tests.sh index bfe386af69..7ddaf9f996 100755 --- a/source4/selftest/samba4_tests.sh +++ b/source4/selftest/samba4_tests.sh @@ -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" -- cgit From 3ecde315d3ef6d13ea3811d34deb51f87cdeaa6d Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 8 Oct 2008 01:58:42 +0200 Subject: Import tests for subunit python module. --- source4/scripting/python/subunit/tests/TestUtil.py | 80 +++ source4/scripting/python/subunit/tests/__init__.py | 25 + .../python/subunit/tests/sample-script.py | 11 + .../python/subunit/tests/sample-two-script.py | 7 + .../python/subunit/tests/test_test_protocol.py | 730 +++++++++++++++++++++ source4/selftest/samba4_tests.sh | 1 + 6 files changed, 854 insertions(+) create mode 100644 source4/scripting/python/subunit/tests/TestUtil.py create mode 100644 source4/scripting/python/subunit/tests/__init__.py create mode 100755 source4/scripting/python/subunit/tests/sample-script.py create mode 100755 source4/scripting/python/subunit/tests/sample-two-script.py create mode 100644 source4/scripting/python/subunit/tests/test_test_protocol.py diff --git a/source4/scripting/python/subunit/tests/TestUtil.py b/source4/scripting/python/subunit/tests/TestUtil.py new file mode 100644 index 0000000000..1b5ba9c293 --- /dev/null +++ b/source4/scripting/python/subunit/tests/TestUtil.py @@ -0,0 +1,80 @@ +# Copyright (c) 2004 Canonical Limited +# Author: Robert Collins +# +# 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/source4/scripting/python/subunit/tests/__init__.py b/source4/scripting/python/subunit/tests/__init__.py new file mode 100644 index 0000000000..544d0e704f --- /dev/null +++ b/source4/scripting/python/subunit/tests/__init__.py @@ -0,0 +1,25 @@ +# +# subunit: extensions to python unittest to get test results from subprocesses. +# Copyright (C) 2005 Robert Collins +# +# 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/source4/scripting/python/subunit/tests/sample-script.py b/source4/scripting/python/subunit/tests/sample-script.py new file mode 100755 index 0000000000..223d2f5d9f --- /dev/null +++ b/source4/scripting/python/subunit/tests/sample-script.py @@ -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/source4/scripting/python/subunit/tests/sample-two-script.py b/source4/scripting/python/subunit/tests/sample-two-script.py new file mode 100755 index 0000000000..d5550842bf --- /dev/null +++ b/source4/scripting/python/subunit/tests/sample-two-script.py @@ -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/source4/scripting/python/subunit/tests/test_test_protocol.py b/source4/scripting/python/subunit/tests/test_test_protocol.py new file mode 100644 index 0000000000..af31584a97 --- /dev/null +++ b/source4/scripting/python/subunit/tests/test_test_protocol.py @@ -0,0 +1,730 @@ +# +# subunit: extensions to python unittest to get test results from subprocesses. +# Copyright (C) 2005 Robert Collins +# +# 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("", "%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 diff --git a/source4/selftest/samba4_tests.sh b/source4/selftest/samba4_tests.sh index 7ddaf9f996..9fc71a104f 100755 --- a/source4/selftest/samba4_tests.sh +++ b/source4/selftest/samba4_tests.sh @@ -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 -- cgit From 68837ff597bd39ff215ef30b4616692d2e31b1b4 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 7 Oct 2008 01:23:34 +0200 Subject: Fix syntax errors in minschema. --- source4/scripting/bin/minschema | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/source4/scripting/bin/minschema b/source4/scripting/bin/minschema index 111557126d..e7d7ed4979 100755 --- a/source4/scripting/bin/minschema +++ b/source4/scripting/bin/minschema @@ -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 ") @@ -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 -- cgit From f9facb51207713d1f294038e68909ba7701c61e4 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 8 Oct 2008 02:17:47 +0200 Subject: Move all subunit files to lib directory. --- lib/subunit/python/__init__.py | 388 +++++++++++ lib/subunit/python/tests/TestUtil.py | 80 +++ lib/subunit/python/tests/__init__.py | 25 + lib/subunit/python/tests/sample-script.py | 11 + lib/subunit/python/tests/sample-two-script.py | 7 + lib/subunit/python/tests/test_test_protocol.py | 730 +++++++++++++++++++++ source4/scripting/bin/subunitrun | 1 + source4/scripting/python/config.mk | 4 +- source4/scripting/python/subunit/__init__.py | 388 ----------- source4/scripting/python/subunit/tests/TestUtil.py | 80 --- source4/scripting/python/subunit/tests/__init__.py | 25 - .../python/subunit/tests/sample-script.py | 11 - .../python/subunit/tests/sample-two-script.py | 7 - .../python/subunit/tests/test_test_protocol.py | 730 --------------------- 14 files changed, 1244 insertions(+), 1243 deletions(-) create mode 100644 lib/subunit/python/__init__.py create mode 100644 lib/subunit/python/tests/TestUtil.py create mode 100644 lib/subunit/python/tests/__init__.py create mode 100755 lib/subunit/python/tests/sample-script.py create mode 100755 lib/subunit/python/tests/sample-two-script.py create mode 100644 lib/subunit/python/tests/test_test_protocol.py delete mode 100644 source4/scripting/python/subunit/__init__.py delete mode 100644 source4/scripting/python/subunit/tests/TestUtil.py delete mode 100644 source4/scripting/python/subunit/tests/__init__.py delete mode 100755 source4/scripting/python/subunit/tests/sample-script.py delete mode 100755 source4/scripting/python/subunit/tests/sample-two-script.py delete mode 100644 source4/scripting/python/subunit/tests/test_test_protocol.py diff --git a/lib/subunit/python/__init__.py b/lib/subunit/python/__init__.py new file mode 100644 index 0000000000..406cd8765b --- /dev/null +++ b/lib/subunit/python/__init__.py @@ -0,0 +1,388 @@ +# +# subunit: extensions to python unittest to get test results from subprocesses. +# Copyright (C) 2005 Robert Collins +# Copyright (C) 2007 Jelmer Vernooij +# +# 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, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +import os +from StringIO import StringIO +import sys +import unittest + +def test_suite(): + import subunit.tests + return subunit.tests.test_suite() + + +def join_dir(base_path, path): + """ + Returns an absolute path to C{path}, calculated relative to the parent + of C{base_path}. + + @param base_path: A path to a file or directory. + @param path: An absolute path, or a path relative to the containing + directory of C{base_path}. + + @return: An absolute path to C{path}. + """ + return os.path.join(os.path.dirname(os.path.abspath(base_path)), path) + + +class TestProtocolServer(object): + """A class for receiving results from a TestProtocol client.""" + + OUTSIDE_TEST = 0 + TEST_STARTED = 1 + READING_FAILURE = 2 + READING_ERROR = 3 + + def __init__(self, client, stream=sys.stdout): + """Create a TestProtocol server instance. + + client should be an object that provides + - startTest + - addSuccess + - addFailure + - addError + - stopTest + methods, i.e. a TestResult. + """ + self.state = TestProtocolServer.OUTSIDE_TEST + self.client = client + self._stream = stream + + def _addError(self, offset, line): + if (self.state == TestProtocolServer.TEST_STARTED and + self.current_test_description == line[offset:-1]): + self.state = TestProtocolServer.OUTSIDE_TEST + self.current_test_description = None + self.client.addError(self._current_test, RemoteError("")) + self.client.stopTest(self._current_test) + self._current_test = None + elif (self.state == TestProtocolServer.TEST_STARTED and + self.current_test_description + " [" == line[offset:-1]): + self.state = TestProtocolServer.READING_ERROR + self._message = "" + else: + self.stdOutLineReceived(line) + + def _addFailure(self, offset, line): + if (self.state == TestProtocolServer.TEST_STARTED and + self.current_test_description == line[offset:-1]): + self.state = TestProtocolServer.OUTSIDE_TEST + self.current_test_description = None + self.client.addFailure(self._current_test, RemoteError()) + self.client.stopTest(self._current_test) + elif (self.state == TestProtocolServer.TEST_STARTED and + self.current_test_description + " [" == line[offset:-1]): + self.state = TestProtocolServer.READING_FAILURE + self._message = "" + else: + self.stdOutLineReceived(line) + + def _addSuccess(self, offset, line): + if (self.state == TestProtocolServer.TEST_STARTED and + self.current_test_description == line[offset:-1]): + self.client.addSuccess(self._current_test) + self.client.stopTest(self._current_test) + self.current_test_description = None + self._current_test = None + self.state = TestProtocolServer.OUTSIDE_TEST + else: + self.stdOutLineReceived(line) + + def _appendMessage(self, line): + if line[0:2] == " ]": + # quoted ] start + self._message += line[1:] + else: + self._message += line + + def endQuote(self, line): + if self.state == TestProtocolServer.READING_FAILURE: + self.state = TestProtocolServer.OUTSIDE_TEST + self.current_test_description = None + self.client.addFailure(self._current_test, + RemoteError(self._message)) + self.client.stopTest(self._current_test) + elif self.state == TestProtocolServer.READING_ERROR: + self.state = TestProtocolServer.OUTSIDE_TEST + self.current_test_description = None + self.client.addError(self._current_test, + RemoteError(self._message)) + self.client.stopTest(self._current_test) + else: + self.stdOutLineReceived(line) + + def lineReceived(self, line): + """Call the appropriate local method for the received line.""" + if line == "]\n": + self.endQuote(line) + elif (self.state == TestProtocolServer.READING_FAILURE or + self.state == TestProtocolServer.READING_ERROR): + self._appendMessage(line) + else: + parts = line.split(None, 1) + if len(parts) == 2: + cmd, rest = parts + offset = len(cmd) + 1 + cmd = cmd.strip(':') + if cmd in ('test', 'testing'): + self._startTest(offset, line) + elif cmd == 'error': + self._addError(offset, line) + elif cmd == 'failure': + self._addFailure(offset, line) + elif cmd in ('success', 'successful'): + self._addSuccess(offset, line) + else: + self.stdOutLineReceived(line) + else: + self.stdOutLineReceived(line) + + def lostConnection(self): + """The input connection has finished.""" + if self.state == TestProtocolServer.TEST_STARTED: + self.client.addError(self._current_test, + RemoteError("lost connection during test '%s'" + % self.current_test_description)) + self.client.stopTest(self._current_test) + elif self.state == TestProtocolServer.READING_ERROR: + self.client.addError(self._current_test, + RemoteError("lost connection during " + "error report of test " + "'%s'" % + self.current_test_description)) + self.client.stopTest(self._current_test) + elif self.state == TestProtocolServer.READING_FAILURE: + self.client.addError(self._current_test, + RemoteError("lost connection during " + "failure report of test " + "'%s'" % + self.current_test_description)) + self.client.stopTest(self._current_test) + + def readFrom(self, pipe): + for line in pipe.readlines(): + self.lineReceived(line) + self.lostConnection() + + def _startTest(self, offset, line): + """Internal call to change state machine. Override startTest().""" + if self.state == TestProtocolServer.OUTSIDE_TEST: + self.state = TestProtocolServer.TEST_STARTED + self._current_test = RemotedTestCase(line[offset:-1]) + self.current_test_description = line[offset:-1] + self.client.startTest(self._current_test) + else: + self.stdOutLineReceived(line) + + def stdOutLineReceived(self, line): + self._stream.write(line) + + +class RemoteException(Exception): + """An exception that occured remotely to python.""" + + def __eq__(self, other): + try: + return self.args == other.args + except AttributeError: + return False + + +class TestProtocolClient(unittest.TestResult): + """A class that looks like a TestResult and informs a TestProtocolServer.""" + + def __init__(self, stream): + super(TestProtocolClient, self).__init__() + self._stream = stream + + def addError(self, test, error): + """Report an error in test test.""" + self._stream.write("error: %s [\n" % (test.shortDescription() or str(test))) + for line in self._exc_info_to_string(error, test).splitlines(): + self._stream.write("%s\n" % line) + self._stream.write("]\n") + super(TestProtocolClient, self).addError(test, error) + + def addFailure(self, test, error): + """Report a failure in test test.""" + self._stream.write("failure: %s [\n" % (test.shortDescription() or str(test))) + for line in self._exc_info_to_string(error, test).splitlines(): + self._stream.write("%s\n" % line) + self._stream.write("]\n") + super(TestProtocolClient, self).addFailure(test, error) + + def addSuccess(self, test): + """Report a success in a test.""" + self._stream.write("successful: %s\n" % (test.shortDescription() or str(test))) + super(TestProtocolClient, self).addSuccess(test) + + def startTest(self, test): + """Mark a test as starting its test run.""" + self._stream.write("test: %s\n" % (test.shortDescription() or str(test))) + super(TestProtocolClient, self).startTest(test) + + +def RemoteError(description=""): + if description == "": + description = "\n" + return (RemoteException, RemoteException(description), None) + + +class RemotedTestCase(unittest.TestCase): + """A class to represent test cases run in child processes.""" + + def __eq__ (self, other): + try: + return self.__description == other.__description + except AttributeError: + return False + + def __init__(self, description): + """Create a psuedo test case with description description.""" + self.__description = description + + def error(self, label): + raise NotImplementedError("%s on RemotedTestCases is not permitted." % + label) + + def setUp(self): + self.error("setUp") + + def tearDown(self): + self.error("tearDown") + + def shortDescription(self): + return self.__description + + def id(self): + return "%s.%s" % (self._strclass(), self.__description) + + def __str__(self): + return "%s (%s)" % (self.__description, self._strclass()) + + def __repr__(self): + return "<%s description='%s'>" % \ + (self._strclass(), self.__description) + + def run(self, result=None): + if result is None: result = self.defaultTestResult() + result.startTest(self) + result.addError(self, RemoteError("Cannot run RemotedTestCases.\n")) + result.stopTest(self) + + def _strclass(self): + cls = self.__class__ + return "%s.%s" % (cls.__module__, cls.__name__) + + +class ExecTestCase(unittest.TestCase): + """A test case which runs external scripts for test fixtures.""" + + def __init__(self, methodName='runTest'): + """Create an instance of the class that will use the named test + method when executed. Raises a ValueError if the instance does + not have a method with the specified name. + """ + unittest.TestCase.__init__(self, methodName) + testMethod = getattr(self, methodName) + self.script = join_dir(sys.modules[self.__class__.__module__].__file__, + testMethod.__doc__) + + def countTestCases(self): + return 1 + + def run(self, result=None): + if result is None: result = self.defaultTestResult() + self._run(result) + + def debug(self): + """Run the test without collecting errors in a TestResult""" + self._run(unittest.TestResult()) + + def _run(self, result): + protocol = TestProtocolServer(result) + output = os.popen(self.script, mode='r') + protocol.readFrom(output) + + +class IsolatedTestCase(unittest.TestCase): + """A TestCase which runs its tests in a forked process.""" + + def run(self, result=None): + if result is None: result = self.defaultTestResult() + run_isolated(unittest.TestCase, self, result) + + +class IsolatedTestSuite(unittest.TestSuite): + """A TestCase which runs its tests in a forked process.""" + + def run(self, result=None): + if result is None: result = unittest.TestResult() + run_isolated(unittest.TestSuite, self, result) + + +def run_isolated(klass, self, result): + """Run a test suite or case in a subprocess, using the run method on klass. + """ + c2pread, c2pwrite = os.pipe() + # fixme - error -> result + # now fork + pid = os.fork() + if pid == 0: + # Child + # Close parent's pipe ends + os.close(c2pread) + # Dup fds for child + os.dup2(c2pwrite, 1) + # Close pipe fds. + os.close(c2pwrite) + + # at this point, sys.stdin is redirected, now we want + # to filter it to escape ]'s. + ### XXX: test and write that bit. + + result = TestProtocolClient(sys.stdout) + klass.run(self, result) + sys.stdout.flush() + sys.stderr.flush() + # exit HARD, exit NOW. + os._exit(0) + else: + # Parent + # Close child pipe ends + os.close(c2pwrite) + # hookup a protocol engine + protocol = TestProtocolServer(result) + protocol.readFrom(os.fdopen(c2pread, 'rU')) + os.waitpid(pid, 0) + # TODO return code evaluation. + return result + + +class SubunitTestRunner(object): + def __init__(self, stream=sys.stdout): + self.stream = stream + + def run(self, test): + "Run the given test case or test suite." + result = TestProtocolClient(self.stream) + test(result) + return result + diff --git a/lib/subunit/python/tests/TestUtil.py b/lib/subunit/python/tests/TestUtil.py new file mode 100644 index 0000000000..1b5ba9c293 --- /dev/null +++ b/lib/subunit/python/tests/TestUtil.py @@ -0,0 +1,80 @@ +# Copyright (c) 2004 Canonical Limited +# Author: Robert Collins +# +# 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/tests/__init__.py b/lib/subunit/python/tests/__init__.py new file mode 100644 index 0000000000..544d0e704f --- /dev/null +++ b/lib/subunit/python/tests/__init__.py @@ -0,0 +1,25 @@ +# +# subunit: extensions to python unittest to get test results from subprocesses. +# Copyright (C) 2005 Robert Collins +# +# 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/tests/sample-script.py b/lib/subunit/python/tests/sample-script.py new file mode 100755 index 0000000000..223d2f5d9f --- /dev/null +++ b/lib/subunit/python/tests/sample-script.py @@ -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/tests/sample-two-script.py b/lib/subunit/python/tests/sample-two-script.py new file mode 100755 index 0000000000..d5550842bf --- /dev/null +++ b/lib/subunit/python/tests/sample-two-script.py @@ -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/tests/test_test_protocol.py b/lib/subunit/python/tests/test_test_protocol.py new file mode 100644 index 0000000000..af31584a97 --- /dev/null +++ b/lib/subunit/python/tests/test_test_protocol.py @@ -0,0 +1,730 @@ +# +# subunit: extensions to python unittest to get test results from subprocesses. +# Copyright (C) 2005 Robert Collins +# +# 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("", "%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 diff --git a/source4/scripting/bin/subunitrun b/source4/scripting/bin/subunitrun index 6f1086ad37..bc35c7ce22 100755 --- a/source4/scripting/bin/subunitrun +++ b/source4/scripting/bin/subunitrun @@ -21,6 +21,7 @@ import sys # Find right directory when running from source tree sys.path.insert(0, "bin/python") +sys.path.insert(0, "../lib/subunit/python") from subunit import SubunitTestRunner from unittest import TestProgram diff --git a/source4/scripting/python/config.mk b/source4/scripting/python/config.mk index b494ee6e8d..c88728a9fd 100644 --- a/source4/scripting/python/config.mk +++ b/source4/scripting/python/config.mk @@ -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 diff --git a/source4/scripting/python/subunit/__init__.py b/source4/scripting/python/subunit/__init__.py deleted file mode 100644 index 406cd8765b..0000000000 --- a/source4/scripting/python/subunit/__init__.py +++ /dev/null @@ -1,388 +0,0 @@ -# -# subunit: extensions to python unittest to get test results from subprocesses. -# Copyright (C) 2005 Robert Collins -# Copyright (C) 2007 Jelmer Vernooij -# -# 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, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# - -import os -from StringIO import StringIO -import sys -import unittest - -def test_suite(): - import subunit.tests - return subunit.tests.test_suite() - - -def join_dir(base_path, path): - """ - Returns an absolute path to C{path}, calculated relative to the parent - of C{base_path}. - - @param base_path: A path to a file or directory. - @param path: An absolute path, or a path relative to the containing - directory of C{base_path}. - - @return: An absolute path to C{path}. - """ - return os.path.join(os.path.dirname(os.path.abspath(base_path)), path) - - -class TestProtocolServer(object): - """A class for receiving results from a TestProtocol client.""" - - OUTSIDE_TEST = 0 - TEST_STARTED = 1 - READING_FAILURE = 2 - READING_ERROR = 3 - - def __init__(self, client, stream=sys.stdout): - """Create a TestProtocol server instance. - - client should be an object that provides - - startTest - - addSuccess - - addFailure - - addError - - stopTest - methods, i.e. a TestResult. - """ - self.state = TestProtocolServer.OUTSIDE_TEST - self.client = client - self._stream = stream - - def _addError(self, offset, line): - if (self.state == TestProtocolServer.TEST_STARTED and - self.current_test_description == line[offset:-1]): - self.state = TestProtocolServer.OUTSIDE_TEST - self.current_test_description = None - self.client.addError(self._current_test, RemoteError("")) - self.client.stopTest(self._current_test) - self._current_test = None - elif (self.state == TestProtocolServer.TEST_STARTED and - self.current_test_description + " [" == line[offset:-1]): - self.state = TestProtocolServer.READING_ERROR - self._message = "" - else: - self.stdOutLineReceived(line) - - def _addFailure(self, offset, line): - if (self.state == TestProtocolServer.TEST_STARTED and - self.current_test_description == line[offset:-1]): - self.state = TestProtocolServer.OUTSIDE_TEST - self.current_test_description = None - self.client.addFailure(self._current_test, RemoteError()) - self.client.stopTest(self._current_test) - elif (self.state == TestProtocolServer.TEST_STARTED and - self.current_test_description + " [" == line[offset:-1]): - self.state = TestProtocolServer.READING_FAILURE - self._message = "" - else: - self.stdOutLineReceived(line) - - def _addSuccess(self, offset, line): - if (self.state == TestProtocolServer.TEST_STARTED and - self.current_test_description == line[offset:-1]): - self.client.addSuccess(self._current_test) - self.client.stopTest(self._current_test) - self.current_test_description = None - self._current_test = None - self.state = TestProtocolServer.OUTSIDE_TEST - else: - self.stdOutLineReceived(line) - - def _appendMessage(self, line): - if line[0:2] == " ]": - # quoted ] start - self._message += line[1:] - else: - self._message += line - - def endQuote(self, line): - if self.state == TestProtocolServer.READING_FAILURE: - self.state = TestProtocolServer.OUTSIDE_TEST - self.current_test_description = None - self.client.addFailure(self._current_test, - RemoteError(self._message)) - self.client.stopTest(self._current_test) - elif self.state == TestProtocolServer.READING_ERROR: - self.state = TestProtocolServer.OUTSIDE_TEST - self.current_test_description = None - self.client.addError(self._current_test, - RemoteError(self._message)) - self.client.stopTest(self._current_test) - else: - self.stdOutLineReceived(line) - - def lineReceived(self, line): - """Call the appropriate local method for the received line.""" - if line == "]\n": - self.endQuote(line) - elif (self.state == TestProtocolServer.READING_FAILURE or - self.state == TestProtocolServer.READING_ERROR): - self._appendMessage(line) - else: - parts = line.split(None, 1) - if len(parts) == 2: - cmd, rest = parts - offset = len(cmd) + 1 - cmd = cmd.strip(':') - if cmd in ('test', 'testing'): - self._startTest(offset, line) - elif cmd == 'error': - self._addError(offset, line) - elif cmd == 'failure': - self._addFailure(offset, line) - elif cmd in ('success', 'successful'): - self._addSuccess(offset, line) - else: - self.stdOutLineReceived(line) - else: - self.stdOutLineReceived(line) - - def lostConnection(self): - """The input connection has finished.""" - if self.state == TestProtocolServer.TEST_STARTED: - self.client.addError(self._current_test, - RemoteError("lost connection during test '%s'" - % self.current_test_description)) - self.client.stopTest(self._current_test) - elif self.state == TestProtocolServer.READING_ERROR: - self.client.addError(self._current_test, - RemoteError("lost connection during " - "error report of test " - "'%s'" % - self.current_test_description)) - self.client.stopTest(self._current_test) - elif self.state == TestProtocolServer.READING_FAILURE: - self.client.addError(self._current_test, - RemoteError("lost connection during " - "failure report of test " - "'%s'" % - self.current_test_description)) - self.client.stopTest(self._current_test) - - def readFrom(self, pipe): - for line in pipe.readlines(): - self.lineReceived(line) - self.lostConnection() - - def _startTest(self, offset, line): - """Internal call to change state machine. Override startTest().""" - if self.state == TestProtocolServer.OUTSIDE_TEST: - self.state = TestProtocolServer.TEST_STARTED - self._current_test = RemotedTestCase(line[offset:-1]) - self.current_test_description = line[offset:-1] - self.client.startTest(self._current_test) - else: - self.stdOutLineReceived(line) - - def stdOutLineReceived(self, line): - self._stream.write(line) - - -class RemoteException(Exception): - """An exception that occured remotely to python.""" - - def __eq__(self, other): - try: - return self.args == other.args - except AttributeError: - return False - - -class TestProtocolClient(unittest.TestResult): - """A class that looks like a TestResult and informs a TestProtocolServer.""" - - def __init__(self, stream): - super(TestProtocolClient, self).__init__() - self._stream = stream - - def addError(self, test, error): - """Report an error in test test.""" - self._stream.write("error: %s [\n" % (test.shortDescription() or str(test))) - for line in self._exc_info_to_string(error, test).splitlines(): - self._stream.write("%s\n" % line) - self._stream.write("]\n") - super(TestProtocolClient, self).addError(test, error) - - def addFailure(self, test, error): - """Report a failure in test test.""" - self._stream.write("failure: %s [\n" % (test.shortDescription() or str(test))) - for line in self._exc_info_to_string(error, test).splitlines(): - self._stream.write("%s\n" % line) - self._stream.write("]\n") - super(TestProtocolClient, self).addFailure(test, error) - - def addSuccess(self, test): - """Report a success in a test.""" - self._stream.write("successful: %s\n" % (test.shortDescription() or str(test))) - super(TestProtocolClient, self).addSuccess(test) - - def startTest(self, test): - """Mark a test as starting its test run.""" - self._stream.write("test: %s\n" % (test.shortDescription() or str(test))) - super(TestProtocolClient, self).startTest(test) - - -def RemoteError(description=""): - if description == "": - description = "\n" - return (RemoteException, RemoteException(description), None) - - -class RemotedTestCase(unittest.TestCase): - """A class to represent test cases run in child processes.""" - - def __eq__ (self, other): - try: - return self.__description == other.__description - except AttributeError: - return False - - def __init__(self, description): - """Create a psuedo test case with description description.""" - self.__description = description - - def error(self, label): - raise NotImplementedError("%s on RemotedTestCases is not permitted." % - label) - - def setUp(self): - self.error("setUp") - - def tearDown(self): - self.error("tearDown") - - def shortDescription(self): - return self.__description - - def id(self): - return "%s.%s" % (self._strclass(), self.__description) - - def __str__(self): - return "%s (%s)" % (self.__description, self._strclass()) - - def __repr__(self): - return "<%s description='%s'>" % \ - (self._strclass(), self.__description) - - def run(self, result=None): - if result is None: result = self.defaultTestResult() - result.startTest(self) - result.addError(self, RemoteError("Cannot run RemotedTestCases.\n")) - result.stopTest(self) - - def _strclass(self): - cls = self.__class__ - return "%s.%s" % (cls.__module__, cls.__name__) - - -class ExecTestCase(unittest.TestCase): - """A test case which runs external scripts for test fixtures.""" - - def __init__(self, methodName='runTest'): - """Create an instance of the class that will use the named test - method when executed. Raises a ValueError if the instance does - not have a method with the specified name. - """ - unittest.TestCase.__init__(self, methodName) - testMethod = getattr(self, methodName) - self.script = join_dir(sys.modules[self.__class__.__module__].__file__, - testMethod.__doc__) - - def countTestCases(self): - return 1 - - def run(self, result=None): - if result is None: result = self.defaultTestResult() - self._run(result) - - def debug(self): - """Run the test without collecting errors in a TestResult""" - self._run(unittest.TestResult()) - - def _run(self, result): - protocol = TestProtocolServer(result) - output = os.popen(self.script, mode='r') - protocol.readFrom(output) - - -class IsolatedTestCase(unittest.TestCase): - """A TestCase which runs its tests in a forked process.""" - - def run(self, result=None): - if result is None: result = self.defaultTestResult() - run_isolated(unittest.TestCase, self, result) - - -class IsolatedTestSuite(unittest.TestSuite): - """A TestCase which runs its tests in a forked process.""" - - def run(self, result=None): - if result is None: result = unittest.TestResult() - run_isolated(unittest.TestSuite, self, result) - - -def run_isolated(klass, self, result): - """Run a test suite or case in a subprocess, using the run method on klass. - """ - c2pread, c2pwrite = os.pipe() - # fixme - error -> result - # now fork - pid = os.fork() - if pid == 0: - # Child - # Close parent's pipe ends - os.close(c2pread) - # Dup fds for child - os.dup2(c2pwrite, 1) - # Close pipe fds. - os.close(c2pwrite) - - # at this point, sys.stdin is redirected, now we want - # to filter it to escape ]'s. - ### XXX: test and write that bit. - - result = TestProtocolClient(sys.stdout) - klass.run(self, result) - sys.stdout.flush() - sys.stderr.flush() - # exit HARD, exit NOW. - os._exit(0) - else: - # Parent - # Close child pipe ends - os.close(c2pwrite) - # hookup a protocol engine - protocol = TestProtocolServer(result) - protocol.readFrom(os.fdopen(c2pread, 'rU')) - os.waitpid(pid, 0) - # TODO return code evaluation. - return result - - -class SubunitTestRunner(object): - def __init__(self, stream=sys.stdout): - self.stream = stream - - def run(self, test): - "Run the given test case or test suite." - result = TestProtocolClient(self.stream) - test(result) - return result - diff --git a/source4/scripting/python/subunit/tests/TestUtil.py b/source4/scripting/python/subunit/tests/TestUtil.py deleted file mode 100644 index 1b5ba9c293..0000000000 --- a/source4/scripting/python/subunit/tests/TestUtil.py +++ /dev/null @@ -1,80 +0,0 @@ -# Copyright (c) 2004 Canonical Limited -# Author: Robert Collins -# -# 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/source4/scripting/python/subunit/tests/__init__.py b/source4/scripting/python/subunit/tests/__init__.py deleted file mode 100644 index 544d0e704f..0000000000 --- a/source4/scripting/python/subunit/tests/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# -# subunit: extensions to python unittest to get test results from subprocesses. -# Copyright (C) 2005 Robert Collins -# -# 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/source4/scripting/python/subunit/tests/sample-script.py b/source4/scripting/python/subunit/tests/sample-script.py deleted file mode 100755 index 223d2f5d9f..0000000000 --- a/source4/scripting/python/subunit/tests/sample-script.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/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/source4/scripting/python/subunit/tests/sample-two-script.py b/source4/scripting/python/subunit/tests/sample-two-script.py deleted file mode 100755 index d5550842bf..0000000000 --- a/source4/scripting/python/subunit/tests/sample-two-script.py +++ /dev/null @@ -1,7 +0,0 @@ -#!/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/source4/scripting/python/subunit/tests/test_test_protocol.py b/source4/scripting/python/subunit/tests/test_test_protocol.py deleted file mode 100644 index af31584a97..0000000000 --- a/source4/scripting/python/subunit/tests/test_test_protocol.py +++ /dev/null @@ -1,730 +0,0 @@ -# -# subunit: extensions to python unittest to get test results from subprocesses. -# Copyright (C) 2005 Robert Collins -# -# 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("", "%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 -- cgit From df4e9c7066059f072420d869ba6d2f383838afad Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 8 Oct 2008 02:23:51 +0200 Subject: Fix path apparently gone wrong by cherrypick. --- lib/subunit/harness2subunit.pl | 36 ++++++++++++++++++++++++++++++++++++ lib/unit | 36 ------------------------------------ 2 files changed, 36 insertions(+), 36 deletions(-) create mode 100755 lib/subunit/harness2subunit.pl delete mode 100755 lib/unit diff --git a/lib/subunit/harness2subunit.pl b/lib/subunit/harness2subunit.pl new file mode 100755 index 0000000000..45f515540b --- /dev/null +++ b/lib/subunit/harness2subunit.pl @@ -0,0 +1,36 @@ +#!/usr/bin/perl +# Simple script that converts Perl test harness output to +# Subunit +# Copyright (C) 2008 Jelmer Vernooij +# Published under the GNU GPL, v3 or later + +my $firstline = 1; +my $error = 0; +while() { + if ($firstline) { + $firstline = 0; + next; + } + if (/^not ok (\d+) - (.*)$/) { + print "test: $2\n"; + print "failure: $2\n"; + $error = 1; + } elsif (/^ok (\d+) - (.*)$/) { + print "test: $2\n"; + print "success: $2\n"; + } elsif (/^ok (\d+)$/) { + print "test: $1\n"; + print "success: $1\n"; + } elsif (/^ok (\d+) # skip (.*)$/) { + print "test: $1\n"; + print "skip: $1 [\n$2\n]\n"; + } elsif (/^not ok (\d+)$/) { + print "test: $1\n"; + print "failure: $1\n"; + $error = 1; + } else { + print; + } +} +exit $error; + diff --git a/lib/unit b/lib/unit deleted file mode 100755 index 45f515540b..0000000000 --- a/lib/unit +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/perl -# Simple script that converts Perl test harness output to -# Subunit -# Copyright (C) 2008 Jelmer Vernooij -# Published under the GNU GPL, v3 or later - -my $firstline = 1; -my $error = 0; -while() { - if ($firstline) { - $firstline = 0; - next; - } - if (/^not ok (\d+) - (.*)$/) { - print "test: $2\n"; - print "failure: $2\n"; - $error = 1; - } elsif (/^ok (\d+) - (.*)$/) { - print "test: $2\n"; - print "success: $2\n"; - } elsif (/^ok (\d+)$/) { - print "test: $1\n"; - print "success: $1\n"; - } elsif (/^ok (\d+) # skip (.*)$/) { - print "test: $1\n"; - print "skip: $1 [\n$2\n]\n"; - } elsif (/^not ok (\d+)$/) { - print "test: $1\n"; - print "failure: $1\n"; - $error = 1; - } else { - print; - } -} -exit $error; - -- cgit From ec5d09dbff94d909f5ef65fb30165672947455b8 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Tue, 7 Oct 2008 17:50:01 -0700 Subject: Update vfs version as I've added a const to the security_descriptor paramter in fset_nt_acl(). Need to watch the build farm to make sure I haven't broken the AIX or Solaris ACL modules. Jeremy. --- examples/VFS/skel_opaque.c | 2 +- examples/VFS/skel_transparent.c | 2 +- source3/include/proto.h | 4 ++-- source3/include/vfs.h | 5 ++-- source3/modules/nfs4_acls.c | 10 +++----- source3/modules/vfs_acl_xattr.c | 4 ++-- source3/modules/vfs_afsacl.c | 10 ++++---- source3/modules/vfs_aixacl2.c | 4 ++-- source3/modules/vfs_default.c | 2 +- source3/modules/vfs_full_audit.c | 4 ++-- source3/modules/vfs_gpfs.c | 4 ++-- source3/modules/vfs_zfsacl.c | 4 ++-- source3/smbd/posix_acls.c | 51 ++++++++++++++++++++-------------------- 13 files changed, 52 insertions(+), 54 deletions(-) diff --git a/examples/VFS/skel_opaque.c b/examples/VFS/skel_opaque.c index 89d8ce5239..3df1fcd5bf 100644 --- a/examples/VFS/skel_opaque.c +++ b/examples/VFS/skel_opaque.c @@ -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; diff --git a/examples/VFS/skel_transparent.c b/examples/VFS/skel_transparent.c index ea8530d855..e6dee97775 100644 --- a/examples/VFS/skel_transparent.c +++ b/examples/VFS/skel_transparent.c @@ -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); } diff --git a/source3/include/proto.h b/source3/include/proto.h index d7acdcb910..efa29be16d 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -9923,14 +9923,14 @@ 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 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, diff --git a/source3/include/vfs.h b/source3/include/vfs.h index 9b72f69328..a3d38f6a25 100644 --- a/source3/include/vfs.h +++ b/source3/include/vfs.h @@ -108,8 +108,9 @@ /* 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. */ diff --git a/source3/modules/nfs4_acls.c b/source3/modules/nfs4_acls.c index 9e28db8b39..f1b8cfffce 100644 --- a/source3/modules/nfs4_acls.c +++ b/source3/modules/nfs4_acls.c @@ -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; @@ -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; diff --git a/source3/modules/vfs_acl_xattr.c b/source3/modules/vfs_acl_xattr.c index 80e44e51fc..2b3fc2ebb2 100644 --- a/source3/modules/vfs_acl_xattr.c +++ b/source3/modules/vfs_acl_xattr.c @@ -238,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; @@ -307,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; diff --git a/source3/modules/vfs_afsacl.c b/source3/modules/vfs_afsacl.c index 9409f3fa20..c78369ac13 100644 --- a/source3/modules/vfs_afsacl.c +++ b/source3/modules/vfs_afsacl.c @@ -717,12 +717,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 +737,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 +887,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 +1040,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); } diff --git a/source3/modules/vfs_aixacl2.c b/source3/modules/vfs_aixacl2.c index 23c4d88134..a078b9f9f6 100644 --- a/source3/modules/vfs_aixacl2.c +++ b/source3/modules/vfs_aixacl2.c @@ -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); } diff --git a/source3/modules/vfs_default.c b/source3/modules/vfs_default.c index 381aa18561..372cdf2d53 100644 --- a/source3/modules/vfs_default.c +++ b/source3/modules/vfs_default.c @@ -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; diff --git a/source3/modules/vfs_full_audit.c b/source3/modules/vfs_full_audit.c index 1224ec3edb..9fadcd9e0c 100644 --- a/source3/modules/vfs_full_audit.c +++ b/source3/modules/vfs_full_audit.c @@ -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; diff --git a/source3/modules/vfs_gpfs.c b/source3/modules/vfs_gpfs.c index 39d2bb6c38..29ea7f0abe 100644 --- a/source3/modules/vfs_gpfs.c +++ b/source3/modules/vfs_gpfs.c @@ -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); } diff --git a/source3/modules/vfs_zfsacl.c b/source3/modules/vfs_zfsacl.c index e933e47317..3688b2386e 100644 --- a/source3/modules/vfs_zfsacl.c +++ b/source3/modules/vfs_zfsacl.c @@ -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); } diff --git a/source3/smbd/posix_acls.c b/source3/smbd/posix_acls.c index 7479aea076..48ea993e28 100644 --- a/source3/smbd/posix_acls.c +++ b/source3/smbd/posix_acls.c @@ -988,7 +988,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 +1329,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 +2018,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; @@ -3224,25 +3228,25 @@ int try_chown(connection_struct *conn, const char *fname, uid_t uid, gid_t gid) ****************************************************************************/ static NTSTATUS append_parent_acl(files_struct *fsp, - SMB_STRUCT_STAT *psbuf, - SEC_DESC *psd, + 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 +3402,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 +3417,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 +3528,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, -- cgit From 859facda89ff3589e87c4cbe1708578769d7c535 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Tue, 7 Oct 2008 17:56:32 -0700 Subject: Fix const warning. Jeremy. --- source3/modules/vfs_acl_xattr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/modules/vfs_acl_xattr.c b/source3/modules/vfs_acl_xattr.c index 2b3fc2ebb2..4a8f6fec01 100644 --- a/source3/modules/vfs_acl_xattr.c +++ b/source3/modules/vfs_acl_xattr.c @@ -257,7 +257,7 @@ static NTSTATUS create_acl_blob(const 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( -- cgit From f8a02a1a804fdb8640989595e2b57df86281c0f7 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 8 Oct 2008 03:33:38 +0200 Subject: Fix subunit files location after cherrypicks. --- lib/subunit/python/__init__.py | 388 ----------- lib/subunit/python/subunit/__init__.py | 388 +++++++++++ lib/subunit/python/subunit/tests/TestUtil.py | 80 +++ lib/subunit/python/subunit/tests/__init__.py | 25 + lib/subunit/python/subunit/tests/sample-script.py | 11 + .../python/subunit/tests/sample-two-script.py | 7 + .../python/subunit/tests/test_test_protocol.py | 730 +++++++++++++++++++++ lib/subunit/python/tests/TestUtil.py | 80 --- lib/subunit/python/tests/__init__.py | 25 - lib/subunit/python/tests/sample-script.py | 11 - lib/subunit/python/tests/sample-two-script.py | 7 - lib/subunit/python/tests/test_test_protocol.py | 730 --------------------- source4/lib/ldb/tests/python/ldap.py | 1 + source4/scripting/bin/subunitrun | 2 +- 14 files changed, 1243 insertions(+), 1242 deletions(-) delete mode 100644 lib/subunit/python/__init__.py create mode 100644 lib/subunit/python/subunit/__init__.py create mode 100644 lib/subunit/python/subunit/tests/TestUtil.py create mode 100644 lib/subunit/python/subunit/tests/__init__.py create mode 100755 lib/subunit/python/subunit/tests/sample-script.py create mode 100755 lib/subunit/python/subunit/tests/sample-two-script.py create mode 100644 lib/subunit/python/subunit/tests/test_test_protocol.py delete mode 100644 lib/subunit/python/tests/TestUtil.py delete mode 100644 lib/subunit/python/tests/__init__.py delete mode 100755 lib/subunit/python/tests/sample-script.py delete mode 100755 lib/subunit/python/tests/sample-two-script.py delete mode 100644 lib/subunit/python/tests/test_test_protocol.py diff --git a/lib/subunit/python/__init__.py b/lib/subunit/python/__init__.py deleted file mode 100644 index 406cd8765b..0000000000 --- a/lib/subunit/python/__init__.py +++ /dev/null @@ -1,388 +0,0 @@ -# -# subunit: extensions to python unittest to get test results from subprocesses. -# Copyright (C) 2005 Robert Collins -# Copyright (C) 2007 Jelmer Vernooij -# -# 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, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# - -import os -from StringIO import StringIO -import sys -import unittest - -def test_suite(): - import subunit.tests - return subunit.tests.test_suite() - - -def join_dir(base_path, path): - """ - Returns an absolute path to C{path}, calculated relative to the parent - of C{base_path}. - - @param base_path: A path to a file or directory. - @param path: An absolute path, or a path relative to the containing - directory of C{base_path}. - - @return: An absolute path to C{path}. - """ - return os.path.join(os.path.dirname(os.path.abspath(base_path)), path) - - -class TestProtocolServer(object): - """A class for receiving results from a TestProtocol client.""" - - OUTSIDE_TEST = 0 - TEST_STARTED = 1 - READING_FAILURE = 2 - READING_ERROR = 3 - - def __init__(self, client, stream=sys.stdout): - """Create a TestProtocol server instance. - - client should be an object that provides - - startTest - - addSuccess - - addFailure - - addError - - stopTest - methods, i.e. a TestResult. - """ - self.state = TestProtocolServer.OUTSIDE_TEST - self.client = client - self._stream = stream - - def _addError(self, offset, line): - if (self.state == TestProtocolServer.TEST_STARTED and - self.current_test_description == line[offset:-1]): - self.state = TestProtocolServer.OUTSIDE_TEST - self.current_test_description = None - self.client.addError(self._current_test, RemoteError("")) - self.client.stopTest(self._current_test) - self._current_test = None - elif (self.state == TestProtocolServer.TEST_STARTED and - self.current_test_description + " [" == line[offset:-1]): - self.state = TestProtocolServer.READING_ERROR - self._message = "" - else: - self.stdOutLineReceived(line) - - def _addFailure(self, offset, line): - if (self.state == TestProtocolServer.TEST_STARTED and - self.current_test_description == line[offset:-1]): - self.state = TestProtocolServer.OUTSIDE_TEST - self.current_test_description = None - self.client.addFailure(self._current_test, RemoteError()) - self.client.stopTest(self._current_test) - elif (self.state == TestProtocolServer.TEST_STARTED and - self.current_test_description + " [" == line[offset:-1]): - self.state = TestProtocolServer.READING_FAILURE - self._message = "" - else: - self.stdOutLineReceived(line) - - def _addSuccess(self, offset, line): - if (self.state == TestProtocolServer.TEST_STARTED and - self.current_test_description == line[offset:-1]): - self.client.addSuccess(self._current_test) - self.client.stopTest(self._current_test) - self.current_test_description = None - self._current_test = None - self.state = TestProtocolServer.OUTSIDE_TEST - else: - self.stdOutLineReceived(line) - - def _appendMessage(self, line): - if line[0:2] == " ]": - # quoted ] start - self._message += line[1:] - else: - self._message += line - - def endQuote(self, line): - if self.state == TestProtocolServer.READING_FAILURE: - self.state = TestProtocolServer.OUTSIDE_TEST - self.current_test_description = None - self.client.addFailure(self._current_test, - RemoteError(self._message)) - self.client.stopTest(self._current_test) - elif self.state == TestProtocolServer.READING_ERROR: - self.state = TestProtocolServer.OUTSIDE_TEST - self.current_test_description = None - self.client.addError(self._current_test, - RemoteError(self._message)) - self.client.stopTest(self._current_test) - else: - self.stdOutLineReceived(line) - - def lineReceived(self, line): - """Call the appropriate local method for the received line.""" - if line == "]\n": - self.endQuote(line) - elif (self.state == TestProtocolServer.READING_FAILURE or - self.state == TestProtocolServer.READING_ERROR): - self._appendMessage(line) - else: - parts = line.split(None, 1) - if len(parts) == 2: - cmd, rest = parts - offset = len(cmd) + 1 - cmd = cmd.strip(':') - if cmd in ('test', 'testing'): - self._startTest(offset, line) - elif cmd == 'error': - self._addError(offset, line) - elif cmd == 'failure': - self._addFailure(offset, line) - elif cmd in ('success', 'successful'): - self._addSuccess(offset, line) - else: - self.stdOutLineReceived(line) - else: - self.stdOutLineReceived(line) - - def lostConnection(self): - """The input connection has finished.""" - if self.state == TestProtocolServer.TEST_STARTED: - self.client.addError(self._current_test, - RemoteError("lost connection during test '%s'" - % self.current_test_description)) - self.client.stopTest(self._current_test) - elif self.state == TestProtocolServer.READING_ERROR: - self.client.addError(self._current_test, - RemoteError("lost connection during " - "error report of test " - "'%s'" % - self.current_test_description)) - self.client.stopTest(self._current_test) - elif self.state == TestProtocolServer.READING_FAILURE: - self.client.addError(self._current_test, - RemoteError("lost connection during " - "failure report of test " - "'%s'" % - self.current_test_description)) - self.client.stopTest(self._current_test) - - def readFrom(self, pipe): - for line in pipe.readlines(): - self.lineReceived(line) - self.lostConnection() - - def _startTest(self, offset, line): - """Internal call to change state machine. Override startTest().""" - if self.state == TestProtocolServer.OUTSIDE_TEST: - self.state = TestProtocolServer.TEST_STARTED - self._current_test = RemotedTestCase(line[offset:-1]) - self.current_test_description = line[offset:-1] - self.client.startTest(self._current_test) - else: - self.stdOutLineReceived(line) - - def stdOutLineReceived(self, line): - self._stream.write(line) - - -class RemoteException(Exception): - """An exception that occured remotely to python.""" - - def __eq__(self, other): - try: - return self.args == other.args - except AttributeError: - return False - - -class TestProtocolClient(unittest.TestResult): - """A class that looks like a TestResult and informs a TestProtocolServer.""" - - def __init__(self, stream): - super(TestProtocolClient, self).__init__() - self._stream = stream - - def addError(self, test, error): - """Report an error in test test.""" - self._stream.write("error: %s [\n" % (test.shortDescription() or str(test))) - for line in self._exc_info_to_string(error, test).splitlines(): - self._stream.write("%s\n" % line) - self._stream.write("]\n") - super(TestProtocolClient, self).addError(test, error) - - def addFailure(self, test, error): - """Report a failure in test test.""" - self._stream.write("failure: %s [\n" % (test.shortDescription() or str(test))) - for line in self._exc_info_to_string(error, test).splitlines(): - self._stream.write("%s\n" % line) - self._stream.write("]\n") - super(TestProtocolClient, self).addFailure(test, error) - - def addSuccess(self, test): - """Report a success in a test.""" - self._stream.write("successful: %s\n" % (test.shortDescription() or str(test))) - super(TestProtocolClient, self).addSuccess(test) - - def startTest(self, test): - """Mark a test as starting its test run.""" - self._stream.write("test: %s\n" % (test.shortDescription() or str(test))) - super(TestProtocolClient, self).startTest(test) - - -def RemoteError(description=""): - if description == "": - description = "\n" - return (RemoteException, RemoteException(description), None) - - -class RemotedTestCase(unittest.TestCase): - """A class to represent test cases run in child processes.""" - - def __eq__ (self, other): - try: - return self.__description == other.__description - except AttributeError: - return False - - def __init__(self, description): - """Create a psuedo test case with description description.""" - self.__description = description - - def error(self, label): - raise NotImplementedError("%s on RemotedTestCases is not permitted." % - label) - - def setUp(self): - self.error("setUp") - - def tearDown(self): - self.error("tearDown") - - def shortDescription(self): - return self.__description - - def id(self): - return "%s.%s" % (self._strclass(), self.__description) - - def __str__(self): - return "%s (%s)" % (self.__description, self._strclass()) - - def __repr__(self): - return "<%s description='%s'>" % \ - (self._strclass(), self.__description) - - def run(self, result=None): - if result is None: result = self.defaultTestResult() - result.startTest(self) - result.addError(self, RemoteError("Cannot run RemotedTestCases.\n")) - result.stopTest(self) - - def _strclass(self): - cls = self.__class__ - return "%s.%s" % (cls.__module__, cls.__name__) - - -class ExecTestCase(unittest.TestCase): - """A test case which runs external scripts for test fixtures.""" - - def __init__(self, methodName='runTest'): - """Create an instance of the class that will use the named test - method when executed. Raises a ValueError if the instance does - not have a method with the specified name. - """ - unittest.TestCase.__init__(self, methodName) - testMethod = getattr(self, methodName) - self.script = join_dir(sys.modules[self.__class__.__module__].__file__, - testMethod.__doc__) - - def countTestCases(self): - return 1 - - def run(self, result=None): - if result is None: result = self.defaultTestResult() - self._run(result) - - def debug(self): - """Run the test without collecting errors in a TestResult""" - self._run(unittest.TestResult()) - - def _run(self, result): - protocol = TestProtocolServer(result) - output = os.popen(self.script, mode='r') - protocol.readFrom(output) - - -class IsolatedTestCase(unittest.TestCase): - """A TestCase which runs its tests in a forked process.""" - - def run(self, result=None): - if result is None: result = self.defaultTestResult() - run_isolated(unittest.TestCase, self, result) - - -class IsolatedTestSuite(unittest.TestSuite): - """A TestCase which runs its tests in a forked process.""" - - def run(self, result=None): - if result is None: result = unittest.TestResult() - run_isolated(unittest.TestSuite, self, result) - - -def run_isolated(klass, self, result): - """Run a test suite or case in a subprocess, using the run method on klass. - """ - c2pread, c2pwrite = os.pipe() - # fixme - error -> result - # now fork - pid = os.fork() - if pid == 0: - # Child - # Close parent's pipe ends - os.close(c2pread) - # Dup fds for child - os.dup2(c2pwrite, 1) - # Close pipe fds. - os.close(c2pwrite) - - # at this point, sys.stdin is redirected, now we want - # to filter it to escape ]'s. - ### XXX: test and write that bit. - - result = TestProtocolClient(sys.stdout) - klass.run(self, result) - sys.stdout.flush() - sys.stderr.flush() - # exit HARD, exit NOW. - os._exit(0) - else: - # Parent - # Close child pipe ends - os.close(c2pwrite) - # hookup a protocol engine - protocol = TestProtocolServer(result) - protocol.readFrom(os.fdopen(c2pread, 'rU')) - os.waitpid(pid, 0) - # TODO return code evaluation. - return result - - -class SubunitTestRunner(object): - def __init__(self, stream=sys.stdout): - self.stream = stream - - def run(self, test): - "Run the given test case or test suite." - result = TestProtocolClient(self.stream) - test(result) - return result - diff --git a/lib/subunit/python/subunit/__init__.py b/lib/subunit/python/subunit/__init__.py new file mode 100644 index 0000000000..406cd8765b --- /dev/null +++ b/lib/subunit/python/subunit/__init__.py @@ -0,0 +1,388 @@ +# +# subunit: extensions to python unittest to get test results from subprocesses. +# Copyright (C) 2005 Robert Collins +# Copyright (C) 2007 Jelmer Vernooij +# +# 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, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +import os +from StringIO import StringIO +import sys +import unittest + +def test_suite(): + import subunit.tests + return subunit.tests.test_suite() + + +def join_dir(base_path, path): + """ + Returns an absolute path to C{path}, calculated relative to the parent + of C{base_path}. + + @param base_path: A path to a file or directory. + @param path: An absolute path, or a path relative to the containing + directory of C{base_path}. + + @return: An absolute path to C{path}. + """ + return os.path.join(os.path.dirname(os.path.abspath(base_path)), path) + + +class TestProtocolServer(object): + """A class for receiving results from a TestProtocol client.""" + + OUTSIDE_TEST = 0 + TEST_STARTED = 1 + READING_FAILURE = 2 + READING_ERROR = 3 + + def __init__(self, client, stream=sys.stdout): + """Create a TestProtocol server instance. + + client should be an object that provides + - startTest + - addSuccess + - addFailure + - addError + - stopTest + methods, i.e. a TestResult. + """ + self.state = TestProtocolServer.OUTSIDE_TEST + self.client = client + self._stream = stream + + def _addError(self, offset, line): + if (self.state == TestProtocolServer.TEST_STARTED and + self.current_test_description == line[offset:-1]): + self.state = TestProtocolServer.OUTSIDE_TEST + self.current_test_description = None + self.client.addError(self._current_test, RemoteError("")) + self.client.stopTest(self._current_test) + self._current_test = None + elif (self.state == TestProtocolServer.TEST_STARTED and + self.current_test_description + " [" == line[offset:-1]): + self.state = TestProtocolServer.READING_ERROR + self._message = "" + else: + self.stdOutLineReceived(line) + + def _addFailure(self, offset, line): + if (self.state == TestProtocolServer.TEST_STARTED and + self.current_test_description == line[offset:-1]): + self.state = TestProtocolServer.OUTSIDE_TEST + self.current_test_description = None + self.client.addFailure(self._current_test, RemoteError()) + self.client.stopTest(self._current_test) + elif (self.state == TestProtocolServer.TEST_STARTED and + self.current_test_description + " [" == line[offset:-1]): + self.state = TestProtocolServer.READING_FAILURE + self._message = "" + else: + self.stdOutLineReceived(line) + + def _addSuccess(self, offset, line): + if (self.state == TestProtocolServer.TEST_STARTED and + self.current_test_description == line[offset:-1]): + self.client.addSuccess(self._current_test) + self.client.stopTest(self._current_test) + self.current_test_description = None + self._current_test = None + self.state = TestProtocolServer.OUTSIDE_TEST + else: + self.stdOutLineReceived(line) + + def _appendMessage(self, line): + if line[0:2] == " ]": + # quoted ] start + self._message += line[1:] + else: + self._message += line + + def endQuote(self, line): + if self.state == TestProtocolServer.READING_FAILURE: + self.state = TestProtocolServer.OUTSIDE_TEST + self.current_test_description = None + self.client.addFailure(self._current_test, + RemoteError(self._message)) + self.client.stopTest(self._current_test) + elif self.state == TestProtocolServer.READING_ERROR: + self.state = TestProtocolServer.OUTSIDE_TEST + self.current_test_description = None + self.client.addError(self._current_test, + RemoteError(self._message)) + self.client.stopTest(self._current_test) + else: + self.stdOutLineReceived(line) + + def lineReceived(self, line): + """Call the appropriate local method for the received line.""" + if line == "]\n": + self.endQuote(line) + elif (self.state == TestProtocolServer.READING_FAILURE or + self.state == TestProtocolServer.READING_ERROR): + self._appendMessage(line) + else: + parts = line.split(None, 1) + if len(parts) == 2: + cmd, rest = parts + offset = len(cmd) + 1 + cmd = cmd.strip(':') + if cmd in ('test', 'testing'): + self._startTest(offset, line) + elif cmd == 'error': + self._addError(offset, line) + elif cmd == 'failure': + self._addFailure(offset, line) + elif cmd in ('success', 'successful'): + self._addSuccess(offset, line) + else: + self.stdOutLineReceived(line) + else: + self.stdOutLineReceived(line) + + def lostConnection(self): + """The input connection has finished.""" + if self.state == TestProtocolServer.TEST_STARTED: + self.client.addError(self._current_test, + RemoteError("lost connection during test '%s'" + % self.current_test_description)) + self.client.stopTest(self._current_test) + elif self.state == TestProtocolServer.READING_ERROR: + self.client.addError(self._current_test, + RemoteError("lost connection during " + "error report of test " + "'%s'" % + self.current_test_description)) + self.client.stopTest(self._current_test) + elif self.state == TestProtocolServer.READING_FAILURE: + self.client.addError(self._current_test, + RemoteError("lost connection during " + "failure report of test " + "'%s'" % + self.current_test_description)) + self.client.stopTest(self._current_test) + + def readFrom(self, pipe): + for line in pipe.readlines(): + self.lineReceived(line) + self.lostConnection() + + def _startTest(self, offset, line): + """Internal call to change state machine. Override startTest().""" + if self.state == TestProtocolServer.OUTSIDE_TEST: + self.state = TestProtocolServer.TEST_STARTED + self._current_test = RemotedTestCase(line[offset:-1]) + self.current_test_description = line[offset:-1] + self.client.startTest(self._current_test) + else: + self.stdOutLineReceived(line) + + def stdOutLineReceived(self, line): + self._stream.write(line) + + +class RemoteException(Exception): + """An exception that occured remotely to python.""" + + def __eq__(self, other): + try: + return self.args == other.args + except AttributeError: + return False + + +class TestProtocolClient(unittest.TestResult): + """A class that looks like a TestResult and informs a TestProtocolServer.""" + + def __init__(self, stream): + super(TestProtocolClient, self).__init__() + self._stream = stream + + def addError(self, test, error): + """Report an error in test test.""" + self._stream.write("error: %s [\n" % (test.shortDescription() or str(test))) + for line in self._exc_info_to_string(error, test).splitlines(): + self._stream.write("%s\n" % line) + self._stream.write("]\n") + super(TestProtocolClient, self).addError(test, error) + + def addFailure(self, test, error): + """Report a failure in test test.""" + self._stream.write("failure: %s [\n" % (test.shortDescription() or str(test))) + for line in self._exc_info_to_string(error, test).splitlines(): + self._stream.write("%s\n" % line) + self._stream.write("]\n") + super(TestProtocolClient, self).addFailure(test, error) + + def addSuccess(self, test): + """Report a success in a test.""" + self._stream.write("successful: %s\n" % (test.shortDescription() or str(test))) + super(TestProtocolClient, self).addSuccess(test) + + def startTest(self, test): + """Mark a test as starting its test run.""" + self._stream.write("test: %s\n" % (test.shortDescription() or str(test))) + super(TestProtocolClient, self).startTest(test) + + +def RemoteError(description=""): + if description == "": + description = "\n" + return (RemoteException, RemoteException(description), None) + + +class RemotedTestCase(unittest.TestCase): + """A class to represent test cases run in child processes.""" + + def __eq__ (self, other): + try: + return self.__description == other.__description + except AttributeError: + return False + + def __init__(self, description): + """Create a psuedo test case with description description.""" + self.__description = description + + def error(self, label): + raise NotImplementedError("%s on RemotedTestCases is not permitted." % + label) + + def setUp(self): + self.error("setUp") + + def tearDown(self): + self.error("tearDown") + + def shortDescription(self): + return self.__description + + def id(self): + return "%s.%s" % (self._strclass(), self.__description) + + def __str__(self): + return "%s (%s)" % (self.__description, self._strclass()) + + def __repr__(self): + return "<%s description='%s'>" % \ + (self._strclass(), self.__description) + + def run(self, result=None): + if result is None: result = self.defaultTestResult() + result.startTest(self) + result.addError(self, RemoteError("Cannot run RemotedTestCases.\n")) + result.stopTest(self) + + def _strclass(self): + cls = self.__class__ + return "%s.%s" % (cls.__module__, cls.__name__) + + +class ExecTestCase(unittest.TestCase): + """A test case which runs external scripts for test fixtures.""" + + def __init__(self, methodName='runTest'): + """Create an instance of the class that will use the named test + method when executed. Raises a ValueError if the instance does + not have a method with the specified name. + """ + unittest.TestCase.__init__(self, methodName) + testMethod = getattr(self, methodName) + self.script = join_dir(sys.modules[self.__class__.__module__].__file__, + testMethod.__doc__) + + def countTestCases(self): + return 1 + + def run(self, result=None): + if result is None: result = self.defaultTestResult() + self._run(result) + + def debug(self): + """Run the test without collecting errors in a TestResult""" + self._run(unittest.TestResult()) + + def _run(self, result): + protocol = TestProtocolServer(result) + output = os.popen(self.script, mode='r') + protocol.readFrom(output) + + +class IsolatedTestCase(unittest.TestCase): + """A TestCase which runs its tests in a forked process.""" + + def run(self, result=None): + if result is None: result = self.defaultTestResult() + run_isolated(unittest.TestCase, self, result) + + +class IsolatedTestSuite(unittest.TestSuite): + """A TestCase which runs its tests in a forked process.""" + + def run(self, result=None): + if result is None: result = unittest.TestResult() + run_isolated(unittest.TestSuite, self, result) + + +def run_isolated(klass, self, result): + """Run a test suite or case in a subprocess, using the run method on klass. + """ + c2pread, c2pwrite = os.pipe() + # fixme - error -> result + # now fork + pid = os.fork() + if pid == 0: + # Child + # Close parent's pipe ends + os.close(c2pread) + # Dup fds for child + os.dup2(c2pwrite, 1) + # Close pipe fds. + os.close(c2pwrite) + + # at this point, sys.stdin is redirected, now we want + # to filter it to escape ]'s. + ### XXX: test and write that bit. + + result = TestProtocolClient(sys.stdout) + klass.run(self, result) + sys.stdout.flush() + sys.stderr.flush() + # exit HARD, exit NOW. + os._exit(0) + else: + # Parent + # Close child pipe ends + os.close(c2pwrite) + # hookup a protocol engine + protocol = TestProtocolServer(result) + protocol.readFrom(os.fdopen(c2pread, 'rU')) + os.waitpid(pid, 0) + # TODO return code evaluation. + return result + + +class SubunitTestRunner(object): + def __init__(self, stream=sys.stdout): + self.stream = stream + + def run(self, test): + "Run the given test case or test suite." + result = TestProtocolClient(self.stream) + test(result) + return result + diff --git a/lib/subunit/python/subunit/tests/TestUtil.py b/lib/subunit/python/subunit/tests/TestUtil.py new file mode 100644 index 0000000000..1b5ba9c293 --- /dev/null +++ b/lib/subunit/python/subunit/tests/TestUtil.py @@ -0,0 +1,80 @@ +# Copyright (c) 2004 Canonical Limited +# Author: Robert Collins +# +# 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 index 0000000000..544d0e704f --- /dev/null +++ b/lib/subunit/python/subunit/tests/__init__.py @@ -0,0 +1,25 @@ +# +# subunit: extensions to python unittest to get test results from subprocesses. +# Copyright (C) 2005 Robert Collins +# +# 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 index 0000000000..223d2f5d9f --- /dev/null +++ b/lib/subunit/python/subunit/tests/sample-script.py @@ -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 index 0000000000..d5550842bf --- /dev/null +++ b/lib/subunit/python/subunit/tests/sample-two-script.py @@ -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 index 0000000000..af31584a97 --- /dev/null +++ b/lib/subunit/python/subunit/tests/test_test_protocol.py @@ -0,0 +1,730 @@ +# +# subunit: extensions to python unittest to get test results from subprocesses. +# Copyright (C) 2005 Robert Collins +# +# 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("", "%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 diff --git a/lib/subunit/python/tests/TestUtil.py b/lib/subunit/python/tests/TestUtil.py deleted file mode 100644 index 1b5ba9c293..0000000000 --- a/lib/subunit/python/tests/TestUtil.py +++ /dev/null @@ -1,80 +0,0 @@ -# Copyright (c) 2004 Canonical Limited -# Author: Robert Collins -# -# 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/tests/__init__.py b/lib/subunit/python/tests/__init__.py deleted file mode 100644 index 544d0e704f..0000000000 --- a/lib/subunit/python/tests/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# -# subunit: extensions to python unittest to get test results from subprocesses. -# Copyright (C) 2005 Robert Collins -# -# 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/tests/sample-script.py b/lib/subunit/python/tests/sample-script.py deleted file mode 100755 index 223d2f5d9f..0000000000 --- a/lib/subunit/python/tests/sample-script.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/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/tests/sample-two-script.py b/lib/subunit/python/tests/sample-two-script.py deleted file mode 100755 index d5550842bf..0000000000 --- a/lib/subunit/python/tests/sample-two-script.py +++ /dev/null @@ -1,7 +0,0 @@ -#!/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/tests/test_test_protocol.py b/lib/subunit/python/tests/test_test_protocol.py deleted file mode 100644 index af31584a97..0000000000 --- a/lib/subunit/python/tests/test_test_protocol.py +++ /dev/null @@ -1,730 +0,0 @@ -# -# subunit: extensions to python unittest to get test results from subprocesses. -# Copyright (C) 2005 Robert Collins -# -# 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("", "%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 diff --git a/source4/lib/ldb/tests/python/ldap.py b/source4/lib/ldb/tests/python/ldap.py index 6c910b63f1..e2cc658521 100755 --- a/source4/lib/ldb/tests/python/ldap.py +++ b/source4/lib/ldb/tests/python/ldap.py @@ -8,6 +8,7 @@ import sys import time sys.path.append("bin/python") +sys.path.append("../lib/subunit/python") import samba.getopt as options diff --git a/source4/scripting/bin/subunitrun b/source4/scripting/bin/subunitrun index bc35c7ce22..e7737bdbec 100755 --- a/source4/scripting/bin/subunitrun +++ b/source4/scripting/bin/subunitrun @@ -21,7 +21,7 @@ import sys # Find right directory when running from source tree sys.path.insert(0, "bin/python") -sys.path.insert(0, "../lib/subunit/python") +sys.path.insert(1, "../lib/subunit/python") from subunit import SubunitTestRunner from unittest import TestProgram -- cgit From 6e493fc631647c1c4d19f77dd9f625202bd889f2 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 8 Oct 2008 11:56:46 +0200 Subject: Add manpage for nmblookup, move nmblookup closer to nbt library. --- source4/libcli/config.mk | 14 ++ source4/libcli/nbt/man/nmblookup.1.xml | 223 +++++++++++++++++++ source4/libcli/nbt/tools/nmblookup.c | 381 +++++++++++++++++++++++++++++++++ source4/utils/config.mk | 17 -- source4/utils/nmblookup.c | 381 --------------------------------- 5 files changed, 618 insertions(+), 398 deletions(-) create mode 100644 source4/libcli/nbt/man/nmblookup.1.xml create mode 100644 source4/libcli/nbt/tools/nmblookup.c delete mode 100644 source4/utils/nmblookup.c diff --git a/source4/libcli/config.mk b/source4/libcli/config.mk index d68a2a2ce3..8e8587ffa4 100644 --- a/source4/libcli/config.mk +++ b/source4/libcli/config.mk @@ -55,6 +55,20 @@ LIBCLI_NBT_OBJ_FILES = $(addprefix $(libclinbtsrcdir)/nbt/, \ 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 diff --git a/source4/libcli/nbt/man/nmblookup.1.xml b/source4/libcli/nbt/man/nmblookup.1.xml new file mode 100644 index 0000000000..85640da033 --- /dev/null +++ b/source4/libcli/nbt/man/nmblookup.1.xml @@ -0,0 +1,223 @@ + + + + + + nmblookup + 1 + Samba + User Commands + 3.2 + + + + + nmblookup + NetBIOS over TCP/IP client used to lookup NetBIOS + names + + + + + nmblookup + -M + -R + -S + -r + -A + -h + -B <broadcast address> + -U <unicast address> + -d <debug level> + -s <smb config file> + -i <NetBIOS scope> + -T + -f + name + + + + + DESCRIPTION + + This tool is part of the samba + 7 suite. + + nmblookup 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. + + + + OPTIONS + + + + -M + Searches for a master browser by looking + up the NetBIOS name name with a + type of 0x1d. If + name is "-" then it does a lookup on the special name + __MSBROWSE__. Please note that in order to + use the name "-", you need to make sure "-" isn't parsed as an + argument, e.g. use : + nmblookup -M -- -. + + + + -R + 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. + + + + + -S + 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. + + + + + + -r + 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 nmbd + 8 daemon is running on this machine it also binds to this port. + + + + + + -A + Interpret name as + an IP Address and do a node status query on this address. + + + + + + &popt.common.connection; + &stdarg.help; + + + -B <broadcast address> + 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 interfaces + parameter of the smb.conf + 5 file. + + + + + + + -U <unicast address> + Do a unicast query to the specified address or + host unicast address. This option + (along with the -R option) is needed to + query a WINS server. + + + &stdarg.server.debug; + &popt.common.samba; + + + -T + 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 + + IP address .... NetBIOS name + + pair that is the normal output. + + + + -f + + 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. + + + + + + name + 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 '#<type>' to the name. This name may also be + '*', which will return all registered names within a broadcast + area. + + + + + + + EXAMPLES + + nmblookup can be used to query + a WINS server (in the same way nslookup is + used to query DNS servers). To query a WINS server, nmblookup + must be called like this: + + nmblookup -U server -R 'name' + + For example, running : + + nmblookup -U samba.org -R 'IRIX#1B' + + would query the WINS server samba.org for the domain + master browser (1B name type) for the IRIX workgroup. + + + + VERSION + + This man page is correct for version 3 of + the Samba suite. + + + + SEE ALSO + nmbd + 8, samba + 7, and smb.conf + 5. + + + + AUTHOR + + 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. + + 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 + ftp://ftp.icce.rug.nl/pub/unix/) 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. + + + diff --git a/source4/libcli/nbt/tools/nmblookup.c b/source4/libcli/nbt/tools/nmblookup.c new file mode 100644 index 0000000000..0d98cb99de --- /dev/null +++ b/source4/libcli/nbt/tools/nmblookup.c @@ -0,0 +1,381 @@ +/* + Unix SMB/CIFS implementation. + + NBT client - used to lookup netbios names + + Copyright (C) Andrew Tridgell 1994-2005 + Copyright (C) Jelmer Vernooij 2003 (Conversion to popt) + + 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 . + +*/ + +#include "includes.h" +#include "lib/cmdline/popt_common.h" +#include "lib/socket/socket.h" +#include "lib/events/events.h" +#include "system/network.h" +#include "system/locale.h" +#include "lib/socket/netif.h" +#include "librpc/gen_ndr/nbt.h" +#include "../libcli/nbt/libnbt.h" +#include "param/param.h" + +/* command line options */ +static struct { + const char *broadcast_address; + const char *unicast_address; + bool find_master; + bool wins_lookup; + bool node_status; + bool root_port; + bool lookup_by_ip; + bool case_sensitive; +} options; + +/* + clean any binary from a node name +*/ +static const char *clean_name(TALLOC_CTX *mem_ctx, const char *name) +{ + char *ret = talloc_strdup(mem_ctx, name); + int i; + for (i=0;ret[i];i++) { + if (!isprint((unsigned char)ret[i])) ret[i] = '.'; + } + return ret; +} + +/* + turn a node status flags field into a string +*/ +static char *node_status_flags(TALLOC_CTX *mem_ctx, uint16_t flags) +{ + char *ret; + const char *group = " "; + const char *type = "B"; + + if (flags & NBT_NM_GROUP) { + group = ""; + } + + switch (flags & NBT_NM_OWNER_TYPE) { + case NBT_NODE_B: + type = "B"; + break; + case NBT_NODE_P: + type = "P"; + break; + case NBT_NODE_M: + type = "M"; + break; + case NBT_NODE_H: + type = "H"; + break; + } + + ret = talloc_asprintf(mem_ctx, "%s %s", group, type); + + if (flags & NBT_NM_DEREGISTER) { + ret = talloc_asprintf_append_buffer(ret, " "); + } + if (flags & NBT_NM_CONFLICT) { + ret = talloc_asprintf_append_buffer(ret, " "); + } + if (flags & NBT_NM_ACTIVE) { + ret = talloc_asprintf_append_buffer(ret, " "); + } + if (flags & NBT_NM_PERMANENT) { + ret = talloc_asprintf_append_buffer(ret, " "); + } + + return ret; +} + +/* do a single node status */ +static bool do_node_status(struct nbt_name_socket *nbtsock, + const char *addr, uint16_t port) +{ + struct nbt_name_status io; + NTSTATUS status; + + io.in.name.name = "*"; + io.in.name.type = NBT_NAME_CLIENT; + io.in.name.scope = NULL; + io.in.dest_addr = addr; + io.in.dest_port = port; + io.in.timeout = 1; + io.in.retries = 2; + + status = nbt_name_status(nbtsock, nbtsock, &io); + if (NT_STATUS_IS_OK(status)) { + int i; + printf("Node status reply from %s\n", + io.out.reply_from); + for (i=0;i %s\n", + clean_name(nbtsock, io.out.status.names[i].name), + io.out.status.names[i].type, + node_status_flags(nbtsock, io.out.status.names[i].nb_flags)); + } + printf("\n\tMAC Address = %02X-%02X-%02X-%02X-%02X-%02X\n", + io.out.status.statistics.unit_id[0], + io.out.status.statistics.unit_id[1], + io.out.status.statistics.unit_id[2], + io.out.status.statistics.unit_id[3], + io.out.status.statistics.unit_id[4], + io.out.status.statistics.unit_id[5]); + return true; + } + + return false; +} + +/* do a single node query */ +static NTSTATUS do_node_query(struct nbt_name_socket *nbtsock, + const char *addr, + uint16_t port, + const char *node_name, + enum nbt_name_type node_type, + bool broadcast) +{ + struct nbt_name_query io; + NTSTATUS status; + int i; + + io.in.name.name = node_name; + io.in.name.type = node_type; + io.in.name.scope = NULL; + io.in.dest_addr = addr; + io.in.dest_port = port; + io.in.broadcast = broadcast; + io.in.wins_lookup = options.wins_lookup; + io.in.timeout = 1; + io.in.retries = 2; + + status = nbt_name_query(nbtsock, nbtsock, &io); + NT_STATUS_NOT_OK_RETURN(status); + + for (i=0;i\n", + io.out.reply_addrs[i], + io.out.name.name, + io.out.name.type); + } + if (options.node_status && io.out.num_addrs > 0) { + do_node_status(nbtsock, io.out.reply_addrs[0], port); + } + + return status; +} + + +static bool process_one(struct loadparm_context *lp_ctx, struct event_context *ev, + struct interface *ifaces, const char *name, int nbt_port) +{ + TALLOC_CTX *tmp_ctx = talloc_new(NULL); + enum nbt_name_type node_type = NBT_NAME_CLIENT; + char *node_name, *p; + struct socket_address *all_zero_addr; + struct nbt_name_socket *nbtsock; + NTSTATUS status = NT_STATUS_OK; + bool ret = true; + + if (!options.case_sensitive) { + name = strupper_talloc(tmp_ctx, name); + } + + if (options.find_master) { + node_type = NBT_NAME_MASTER; + if (*name == '-' || *name == '_') { + name = "\01\02__MSBROWSE__\02"; + node_type = NBT_NAME_MS; + } + } + + p = strchr(name, '#'); + if (p) { + node_name = talloc_strndup(tmp_ctx, name, PTR_DIFF(p,name)); + node_type = (enum nbt_name_type)strtol(p+1, NULL, 16); + } else { + node_name = talloc_strdup(tmp_ctx, name); + } + + nbtsock = nbt_name_socket_init(tmp_ctx, ev, lp_iconv_convenience(lp_ctx)); + + if (options.root_port) { + all_zero_addr = socket_address_from_strings(tmp_ctx, nbtsock->sock->backend_name, + "0.0.0.0", NBT_NAME_SERVICE_PORT); + + if (!all_zero_addr) { + talloc_free(tmp_ctx); + return false; + } + + status = socket_listen(nbtsock->sock, all_zero_addr, 0, 0); + if (!NT_STATUS_IS_OK(status)) { + printf("Failed to bind to local port 137 - %s\n", nt_errstr(status)); + talloc_free(tmp_ctx); + return false; + } + } + + if (options.lookup_by_ip) { + ret = do_node_status(nbtsock, name, nbt_port); + talloc_free(tmp_ctx); + return ret; + } + + if (options.broadcast_address) { + status = do_node_query(nbtsock, options.broadcast_address, nbt_port, + node_name, node_type, true); + } else if (options.unicast_address) { + status = do_node_query(nbtsock, options.unicast_address, + nbt_port, node_name, node_type, false); + } else { + int i, num_interfaces; + + num_interfaces = iface_count(ifaces); + for (i=0;i as an IP Address", NULL }, + + { "case-sensitive", 0, POPT_ARG_NONE, NULL, OPT_CASE_SENSITIVE, + "Don't uppercase the name before sending", NULL }, + + POPT_COMMON_SAMBA + { 0, 0, 0, 0 } + }; + + pc = poptGetContext("nmblookup", argc, argv, long_options, + POPT_CONTEXT_KEEP_FIRST); + + poptSetOtherOptionHelp(pc, " ..."); + + while ((opt = poptGetNextOpt(pc)) != -1) { + switch(opt) { + case OPT_BROADCAST_ADDRESS: + options.broadcast_address = poptGetOptArg(pc); + break; + case OPT_UNICAST_ADDRESS: + options.unicast_address = poptGetOptArg(pc); + break; + case OPT_FIND_MASTER: + options.find_master = true; + break; + case OPT_WINS_LOOKUP: + options.wins_lookup = true; + break; + case OPT_NODE_STATUS: + options.node_status = true; + break; + case OPT_ROOT_PORT: + options.root_port = true; + break; + case OPT_LOOKUP_BY_IP: + options.lookup_by_ip = true; + break; + case OPT_CASE_SENSITIVE: + options.case_sensitive = true; + break; + } + } + + /* swallow argv[0] */ + poptGetArg(pc); + + if(!poptPeekArg(pc)) { + poptPrintUsage(pc, stderr, 0); + exit(1); + } + + load_interfaces(NULL, lp_interfaces(cmdline_lp_ctx), &ifaces); + + ev = s4_event_context_init(talloc_autofree_context()); + + while (poptPeekArg(pc)) { + const char *name = poptGetArg(pc); + + ret &= process_one(cmdline_lp_ctx, ev, ifaces, name, lp_nbt_port(cmdline_lp_ctx)); + } + + talloc_free(ev); + + talloc_free(ifaces); + + poptFreeContext(pc); + + if (!ret) { + return 1; + } + + return 0; +} diff --git a/source4/utils/config.mk b/source4/utils/config.mk index 37a19077f1..0b98dcfa85 100644 --- a/source4/utils/config.mk +++ b/source4/utils/config.mk @@ -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/nmblookup.c b/source4/utils/nmblookup.c deleted file mode 100644 index 0d98cb99de..0000000000 --- a/source4/utils/nmblookup.c +++ /dev/null @@ -1,381 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - NBT client - used to lookup netbios names - - Copyright (C) Andrew Tridgell 1994-2005 - Copyright (C) Jelmer Vernooij 2003 (Conversion to popt) - - 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 . - -*/ - -#include "includes.h" -#include "lib/cmdline/popt_common.h" -#include "lib/socket/socket.h" -#include "lib/events/events.h" -#include "system/network.h" -#include "system/locale.h" -#include "lib/socket/netif.h" -#include "librpc/gen_ndr/nbt.h" -#include "../libcli/nbt/libnbt.h" -#include "param/param.h" - -/* command line options */ -static struct { - const char *broadcast_address; - const char *unicast_address; - bool find_master; - bool wins_lookup; - bool node_status; - bool root_port; - bool lookup_by_ip; - bool case_sensitive; -} options; - -/* - clean any binary from a node name -*/ -static const char *clean_name(TALLOC_CTX *mem_ctx, const char *name) -{ - char *ret = talloc_strdup(mem_ctx, name); - int i; - for (i=0;ret[i];i++) { - if (!isprint((unsigned char)ret[i])) ret[i] = '.'; - } - return ret; -} - -/* - turn a node status flags field into a string -*/ -static char *node_status_flags(TALLOC_CTX *mem_ctx, uint16_t flags) -{ - char *ret; - const char *group = " "; - const char *type = "B"; - - if (flags & NBT_NM_GROUP) { - group = ""; - } - - switch (flags & NBT_NM_OWNER_TYPE) { - case NBT_NODE_B: - type = "B"; - break; - case NBT_NODE_P: - type = "P"; - break; - case NBT_NODE_M: - type = "M"; - break; - case NBT_NODE_H: - type = "H"; - break; - } - - ret = talloc_asprintf(mem_ctx, "%s %s", group, type); - - if (flags & NBT_NM_DEREGISTER) { - ret = talloc_asprintf_append_buffer(ret, " "); - } - if (flags & NBT_NM_CONFLICT) { - ret = talloc_asprintf_append_buffer(ret, " "); - } - if (flags & NBT_NM_ACTIVE) { - ret = talloc_asprintf_append_buffer(ret, " "); - } - if (flags & NBT_NM_PERMANENT) { - ret = talloc_asprintf_append_buffer(ret, " "); - } - - return ret; -} - -/* do a single node status */ -static bool do_node_status(struct nbt_name_socket *nbtsock, - const char *addr, uint16_t port) -{ - struct nbt_name_status io; - NTSTATUS status; - - io.in.name.name = "*"; - io.in.name.type = NBT_NAME_CLIENT; - io.in.name.scope = NULL; - io.in.dest_addr = addr; - io.in.dest_port = port; - io.in.timeout = 1; - io.in.retries = 2; - - status = nbt_name_status(nbtsock, nbtsock, &io); - if (NT_STATUS_IS_OK(status)) { - int i; - printf("Node status reply from %s\n", - io.out.reply_from); - for (i=0;i %s\n", - clean_name(nbtsock, io.out.status.names[i].name), - io.out.status.names[i].type, - node_status_flags(nbtsock, io.out.status.names[i].nb_flags)); - } - printf("\n\tMAC Address = %02X-%02X-%02X-%02X-%02X-%02X\n", - io.out.status.statistics.unit_id[0], - io.out.status.statistics.unit_id[1], - io.out.status.statistics.unit_id[2], - io.out.status.statistics.unit_id[3], - io.out.status.statistics.unit_id[4], - io.out.status.statistics.unit_id[5]); - return true; - } - - return false; -} - -/* do a single node query */ -static NTSTATUS do_node_query(struct nbt_name_socket *nbtsock, - const char *addr, - uint16_t port, - const char *node_name, - enum nbt_name_type node_type, - bool broadcast) -{ - struct nbt_name_query io; - NTSTATUS status; - int i; - - io.in.name.name = node_name; - io.in.name.type = node_type; - io.in.name.scope = NULL; - io.in.dest_addr = addr; - io.in.dest_port = port; - io.in.broadcast = broadcast; - io.in.wins_lookup = options.wins_lookup; - io.in.timeout = 1; - io.in.retries = 2; - - status = nbt_name_query(nbtsock, nbtsock, &io); - NT_STATUS_NOT_OK_RETURN(status); - - for (i=0;i\n", - io.out.reply_addrs[i], - io.out.name.name, - io.out.name.type); - } - if (options.node_status && io.out.num_addrs > 0) { - do_node_status(nbtsock, io.out.reply_addrs[0], port); - } - - return status; -} - - -static bool process_one(struct loadparm_context *lp_ctx, struct event_context *ev, - struct interface *ifaces, const char *name, int nbt_port) -{ - TALLOC_CTX *tmp_ctx = talloc_new(NULL); - enum nbt_name_type node_type = NBT_NAME_CLIENT; - char *node_name, *p; - struct socket_address *all_zero_addr; - struct nbt_name_socket *nbtsock; - NTSTATUS status = NT_STATUS_OK; - bool ret = true; - - if (!options.case_sensitive) { - name = strupper_talloc(tmp_ctx, name); - } - - if (options.find_master) { - node_type = NBT_NAME_MASTER; - if (*name == '-' || *name == '_') { - name = "\01\02__MSBROWSE__\02"; - node_type = NBT_NAME_MS; - } - } - - p = strchr(name, '#'); - if (p) { - node_name = talloc_strndup(tmp_ctx, name, PTR_DIFF(p,name)); - node_type = (enum nbt_name_type)strtol(p+1, NULL, 16); - } else { - node_name = talloc_strdup(tmp_ctx, name); - } - - nbtsock = nbt_name_socket_init(tmp_ctx, ev, lp_iconv_convenience(lp_ctx)); - - if (options.root_port) { - all_zero_addr = socket_address_from_strings(tmp_ctx, nbtsock->sock->backend_name, - "0.0.0.0", NBT_NAME_SERVICE_PORT); - - if (!all_zero_addr) { - talloc_free(tmp_ctx); - return false; - } - - status = socket_listen(nbtsock->sock, all_zero_addr, 0, 0); - if (!NT_STATUS_IS_OK(status)) { - printf("Failed to bind to local port 137 - %s\n", nt_errstr(status)); - talloc_free(tmp_ctx); - return false; - } - } - - if (options.lookup_by_ip) { - ret = do_node_status(nbtsock, name, nbt_port); - talloc_free(tmp_ctx); - return ret; - } - - if (options.broadcast_address) { - status = do_node_query(nbtsock, options.broadcast_address, nbt_port, - node_name, node_type, true); - } else if (options.unicast_address) { - status = do_node_query(nbtsock, options.unicast_address, - nbt_port, node_name, node_type, false); - } else { - int i, num_interfaces; - - num_interfaces = iface_count(ifaces); - for (i=0;i as an IP Address", NULL }, - - { "case-sensitive", 0, POPT_ARG_NONE, NULL, OPT_CASE_SENSITIVE, - "Don't uppercase the name before sending", NULL }, - - POPT_COMMON_SAMBA - { 0, 0, 0, 0 } - }; - - pc = poptGetContext("nmblookup", argc, argv, long_options, - POPT_CONTEXT_KEEP_FIRST); - - poptSetOtherOptionHelp(pc, " ..."); - - while ((opt = poptGetNextOpt(pc)) != -1) { - switch(opt) { - case OPT_BROADCAST_ADDRESS: - options.broadcast_address = poptGetOptArg(pc); - break; - case OPT_UNICAST_ADDRESS: - options.unicast_address = poptGetOptArg(pc); - break; - case OPT_FIND_MASTER: - options.find_master = true; - break; - case OPT_WINS_LOOKUP: - options.wins_lookup = true; - break; - case OPT_NODE_STATUS: - options.node_status = true; - break; - case OPT_ROOT_PORT: - options.root_port = true; - break; - case OPT_LOOKUP_BY_IP: - options.lookup_by_ip = true; - break; - case OPT_CASE_SENSITIVE: - options.case_sensitive = true; - break; - } - } - - /* swallow argv[0] */ - poptGetArg(pc); - - if(!poptPeekArg(pc)) { - poptPrintUsage(pc, stderr, 0); - exit(1); - } - - load_interfaces(NULL, lp_interfaces(cmdline_lp_ctx), &ifaces); - - ev = s4_event_context_init(talloc_autofree_context()); - - while (poptPeekArg(pc)) { - const char *name = poptGetArg(pc); - - ret &= process_one(cmdline_lp_ctx, ev, ifaces, name, lp_nbt_port(cmdline_lp_ctx)); - } - - talloc_free(ev); - - talloc_free(ifaces); - - poptFreeContext(pc); - - if (!ret) { - return 1; - } - - return 0; -} -- cgit From 08223692c69963bdb47b1687dc5be760e0c7ad7b Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 8 Oct 2008 12:03:45 +0200 Subject: fix libclinbtsrcdir variable. --- source3/samba4.mk | 2 +- source4/Makefile | 2 +- source4/libcli/config.mk | 12 ++++++------ 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/source3/samba4.mk b/source3/samba4.mk index 3abcbe121f..524fc9f64c 100644 --- a/source3/samba4.mk +++ b/source3/samba4.mk @@ -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/source4/Makefile b/source4/Makefile index 74383b1a59..cab82674d2 100644 --- a/source4/Makefile +++ b/source4/Makefile @@ -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 diff --git a/source4/libcli/config.mk b/source4/libcli/config.mk index 8e8587ffa4..8d9a1f5fa8 100644 --- a/source4/libcli/config.mk +++ b/source4/libcli/config.mk @@ -40,15 +40,15 @@ $(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 \ @@ -73,19 +73,19 @@ MANPAGES += $(libclinbtsrcdir)/man/nmblookup.1 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) + ../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) -- cgit From 71ef7ae824b1e8d411590a9a7dbd1f5b86b9df5e Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 8 Oct 2008 12:08:52 +0200 Subject: Remove duplicate copy of manual page. --- source4/utils/man/ndrdump.1.xml | 83 ----------------------------------------- 1 file changed, 83 deletions(-) delete mode 100644 source4/utils/man/ndrdump.1.xml diff --git a/source4/utils/man/ndrdump.1.xml b/source4/utils/man/ndrdump.1.xml deleted file mode 100644 index 9d66102682..0000000000 --- a/source4/utils/man/ndrdump.1.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - ndrdump - 1 - - - - - ndrdump - DCE/RPC Packet Parser and Dumper - - - - - ndrdump - -c context - pipe - function - in|out - filename - - - ndrdump - pipe - - - ndrdump - - - - - DESCRIPTION - - ndrdump tries to parse the specified filename - using Samba's parser for the specified pipe and function. The - third argument should be - either in or out, depending - on whether the data should be parsed as a request or a reply. - - Running ndrdump without arguments will list the pipes for which - parsers are available. - - Running ndrdump with one argument will list the functions that - Samba can parse for the specified pipe. - - The primary function of ndrdump is debugging Samba's internal - DCE/RPC parsing functions. The file being parsed is usually - one exported by wiresharks Export selected packet bytes - function. - - The context argument can be used to load context data from the request - packet when parsing reply packets (such as array lengths). - - - - - VERSION - - This man page is correct for version 4.0 of the Samba suite. - - - - SEE ALSO - - wireshark, pidl - - - - - AUTHOR - - This utility is part of the Samba suite, which is developed by the global Samba Team. - - ndrdump was written by Andrew Tridgell. - - This manpage was written by Jelmer Vernooij. - - - - -- cgit From be63f86ce7029b0a4efbe1478cc16189b5d26aec Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Wed, 8 Oct 2008 12:56:04 +0200 Subject: Remove unused CHECK_FSP macro --- source3/include/smb_macros.h | 16 ---------------- source3/smbd/reply.c | 5 ++--- 2 files changed, 2 insertions(+), 19 deletions(-) diff --git a/source3/include/smb_macros.h b/source3/include/smb_macros.h index 20e2a9a443..d2e0aa95ac 100644 --- a/source3/include/smb_macros.h +++ b/source3/include/smb_macros.h @@ -75,22 +75,6 @@ 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)))) diff --git a/source3/smbd/reply.c b/source3/smbd/reply.c index 0226d314f7..48403073f7 100644 --- a/source3/smbd/reply.c +++ b/source3/smbd/reply.c @@ -339,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, @@ -4272,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)) { -- cgit From 14f835ba4b7e553d0cd75f3b311378c5c875e87c Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Wed, 8 Oct 2008 11:39:32 -0700 Subject: Fix bug #5814 - Winbindd dumping core in a strange manner while doing "rescan_trusted_domain". From analysis by hargagan : "The winbindd_child_died() is also getting called from process_loop() in case of SIGCHLD signal. In this case it doesn't make the timeout_handler to NULL for the first request. It then initiate a new request using schedule_async_request() which installs a new timeout handler for the same request. In such a case, for a badly unresponsive system both the timeout handler can be called. For the first call the "private_data" will be cleared and for another call the timeout handler will be detecting the double free. So, for such a case as well, the winbindd_child_died() should make the timeout_handler to NULL." Jeremy. --- source3/winbindd/winbindd_dual.c | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/source3/winbindd/winbindd_dual.c b/source3/winbindd/winbindd_dual.c index f6a9c1f26d..aeb52d9b5a 100644 --- a/source3/winbindd/winbindd_dual.c +++ b/source3/winbindd/winbindd_dual.c @@ -300,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 . + * JRA. + */ + + TALLOC_FREE(request->reply_timeout_event); + if ((child->pid == 0) && (!fork_domain_child(child))) { /* fork_domain_child failed. Cancel all outstanding requests */ @@ -495,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); } -- cgit From 646df8bec618d78905f83779bf57d96141109d8f Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Wed, 8 Oct 2008 15:18:25 -0700 Subject: Deal with inheritance from parent directory when setting Windows ACLs. Jeremy. --- source3/include/proto.h | 3 +++ source3/modules/vfs_acl_xattr.c | 16 ++++++++++++++++ source3/smbd/posix_acls.c | 2 +- 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/source3/include/proto.h b/source3/include/proto.h index efa29be16d..535adf7e2f 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -9930,6 +9930,9 @@ NTSTATUS posix_fget_nt_acl(struct files_struct *fsp, uint32_t security_info, 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 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); diff --git a/source3/modules/vfs_acl_xattr.c b/source3/modules/vfs_acl_xattr.c index 4a8f6fec01..b641195fd7 100644 --- a/source3/modules/vfs_acl_xattr.c +++ b/source3/modules/vfs_acl_xattr.c @@ -317,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); diff --git a/source3/smbd/posix_acls.c b/source3/smbd/posix_acls.c index 48ea993e28..da17e53b2c 100644 --- a/source3/smbd/posix_acls.c +++ b/source3/smbd/posix_acls.c @@ -3227,7 +3227,7 @@ 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, +NTSTATUS append_parent_acl(files_struct *fsp, const SEC_DESC *pcsd, SEC_DESC **pp_new_sd) { -- cgit From 88a58ae0eeb553969c903a94e578375e109ad05a Mon Sep 17 00:00:00 2001 From: Tim Prouty Date: Tue, 7 Oct 2008 20:16:04 -0700 Subject: Fixed "might be uninitialized" warning --- source3/modules/vfs_acl_xattr.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source3/modules/vfs_acl_xattr.c b/source3/modules/vfs_acl_xattr.c index b641195fd7..241751c6a6 100644 --- a/source3/modules/vfs_acl_xattr.c +++ b/source3/modules/vfs_acl_xattr.c @@ -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); @@ -277,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)); -- cgit From 543c6a02ae1dcb903de800c88af1f9e221827d61 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Wed, 8 Oct 2008 18:06:58 -0700 Subject: For the vfs_acl_xattr.c module, make sure we map GENERIC file and directory bits to specific bits every time a security descriptor is set. The S4 torture suite proves that generic bits are not returned when querying an ACL set using them (ie. only the specific bits are stored on disk). Jeremy. --- source3/include/proto.h | 1 + source3/lib/util_seaccess.c | 18 ++++++++++++++++++ source3/rpc_server/srv_srvsvc_nt.c | 26 ++++++++++++++++++++++++-- source3/smbd/nttrans.c | 5 +++++ source3/smbd/open.c | 4 ++++ 5 files changed, 52 insertions(+), 2 deletions(-) diff --git a/source3/include/proto.h b/source3/include/proto.h index 535adf7e2f..b7e363253f 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -1431,6 +1431,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, diff --git a/source3/lib/util_seaccess.c b/source3/lib/util_seaccess.c index 87e70bb95b..cab4261adf 100644 --- a/source3/lib/util_seaccess.c +++ b/source3/lib/util_seaccess.c @@ -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 diff --git a/source3/rpc_server/srv_srvsvc_nt.c b/source3/rpc_server/srv_srvsvc_nt.c index fb7478653d..47688b114c 100644 --- a/source3/rpc_server/srv_srvsvc_nt.c +++ b/source3/rpc_server/srv_srvsvc_nt.c @@ -2150,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); @@ -2198,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 " diff --git a/source3/smbd/nttrans.c b/source3/smbd/nttrans.c index 584399c86c..061855876c 100644 --- a/source3/smbd/nttrans.c +++ b/source3/smbd/nttrans.c @@ -713,6 +713,7 @@ static void do_nt_transact_create_pipe(connection_struct *conn, static NTSTATUS set_sd(files_struct *fsp, uint8 *data, uint32 sd_len, uint32 security_info_sent) { + extern const struct generic_mapping file_generic_mapping; SEC_DESC *psd = NULL; NTSTATUS status; @@ -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); diff --git a/source3/smbd/open.c b/source3/smbd/open.c index ad024a58ef..8727e80d5f 100644 --- a/source3/smbd/open.c +++ b/source3/smbd/open.c @@ -2764,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; -- cgit From 298a918e953853d3b6fbb20e5984275db083bc9b Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sat, 27 Sep 2008 03:05:47 +0200 Subject: s3-winbindd: add dsgetdcname request and reply to winbind structure. Guenther --- source3/nsswitch/winbind_struct_protocol.h | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/source3/nsswitch/winbind_struct_protocol.h b/source3/nsswitch/winbind_struct_protocol.h index e81813c77b..ff52dbddaf 100644 --- a/source3/nsswitch/winbind_struct_protocol.h +++ b/source3/nsswitch/winbind_struct_protocol.h @@ -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 */ -- cgit From 4c68f3cd9b77414802bef08631ddb66325bfff4c Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Thu, 9 Oct 2008 11:45:03 +0200 Subject: build: add "make test_wbpad" for checking winbind 32/64bit structure padding. Guenther --- source3/Makefile.in | 4 +++ source3/script/tests/wb_pad.sh | 82 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100755 source3/script/tests/wb_pad.sh diff --git a/source3/Makefile.in b/source3/Makefile.in index eb6a05cba5..0ae32a0ef8 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -2769,6 +2769,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: diff --git a/source3/script/tests/wb_pad.sh b/source3/script/tests/wb_pad.sh new file mode 100755 index 0000000000..f1f5ca24c4 --- /dev/null +++ b/source3/script/tests/wb_pad.sh @@ -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 . + +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 -- cgit From 96a5d169dd3a8746270a9e086717ab6206ab02c6 Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Wed, 8 Oct 2008 17:24:24 +0200 Subject: Fix a typo --- source3/smbd/ipc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source3/smbd/ipc.c b/source3/smbd/ipc.c index f4c45999ba..0f2caad86f 100644 --- a/source3/smbd/ipc.c +++ b/source3/smbd/ipc.c @@ -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; -- cgit From 1d83fbffae23325961fd80873c93c06cae5f7a4e Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Wed, 8 Oct 2008 17:42:22 +0200 Subject: Remove a pointless level of indirection --- source3/include/proto.h | 1 - source3/smbd/fake_file.c | 8 -------- source3/smbd/files.c | 4 +--- 3 files changed, 1 insertion(+), 12 deletions(-) diff --git a/source3/include/proto.h b/source3/include/proto.h index b7e363253f..99557a25a1 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -9558,7 +9558,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 */ diff --git a/source3/smbd/fake_file.c b/source3/smbd/fake_file.c index 8dd9abee1a..1761cb66a8 100644 --- a/source3/smbd/fake_file.c +++ b/source3/smbd/fake_file.c @@ -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); diff --git a/source3/smbd/files.c b/source3/smbd/files.c index 8d06e20f81..519f4945f2 100644 --- a/source3/smbd/files.c +++ b/source3/smbd/files.c @@ -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); -- cgit From 76a8da6f711ce13de6c4e3e1af6714b0475b71f5 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sat, 27 Sep 2008 03:09:07 +0200 Subject: s3-winbindd: use new, richer structures in WINBINDD_DSGETDCNAME implementation. Guenther --- source3/winbindd/winbindd_locator.c | 61 ++++++++++++++++++++++++------------- 1 file changed, 40 insertions(+), 21 deletions(-) diff --git a/source3/winbindd/winbindd_locator.c b/source3/winbindd/winbindd_locator.c index b2a8bd7e30..b60d235f70 100644 --- a/source3/winbindd/winbindd_locator.c +++ b/source3/winbindd/winbindd_locator.c @@ -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; } -- cgit From 4e04c5ae1bb7ade41c0b28bbf9ec7cdb4930d9ae Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sat, 27 Sep 2008 03:11:33 +0200 Subject: wbinfo: fix dsgetdcname caller. Guenther --- source3/nsswitch/wbinfo.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/source3/nsswitch/wbinfo.c b/source3/nsswitch/wbinfo.c index 60524d1d1b..fc49be4314 100644 --- a/source3/nsswitch/wbinfo.c +++ b/source3/nsswitch/wbinfo.c @@ -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; } -- cgit From bf5c80c8eb3051ff2d04629b2b4a74b0c86d726d Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sat, 27 Sep 2008 03:11:59 +0200 Subject: krb5-locator: fix dsgetdcname caller. Guenther --- source3/nsswitch/winbind_krb5_locator.c | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/source3/nsswitch/winbind_krb5_locator.c b/source3/nsswitch/winbind_krb5_locator.c index 990c2cae50..7eecd13b70 100644 --- a/source3/nsswitch/winbind_krb5_locator.c +++ b/source3/nsswitch/winbind_krb5_locator.c @@ -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 @@ -247,18 +247,19 @@ static bool ask_winbind(const char *realm, char **dcname) NSS_STATUS status; struct winbindd_request request; struct winbindd_response response; + const char *dc = NULL; ZERO_STRUCT(request); ZERO_STRUCT(response); - request.flags = 0x40020600; + request.data.dsgetdcname.flags = 0x40020600; /* DS_KDC_REQUIRED | DS_IS_DNS_NAME | DS_RETURN_DNS_NAME | DS_IP_REQUIRED */ - strncpy(request.domain_name, realm, - sizeof(request.domain_name)-1); + strncpy(request.data.dsgetdcname.domain_name, realm, + sizeof(request.data.dsgetdcname.domain_name)-1); status = winbindd_request_response(WINBINDD_DSGETDCNAME, &request, &response); @@ -270,7 +271,23 @@ static bool ask_winbind(const char *realm, char **dcname) return false; } - *dcname = strdup(response.data.dc_name); + if (response.data.dsgetdcname.dc_address[0] != '\0') { + dc = response.data.dsgetdcname.dc_address; + if (dc[0] == '\\') dc++; + if (dc[0] == '\\') dc++; + } + + if (!dc && response.data.dsgetdcname.dc_unc[0] != '\0') { + dc = response.data.dsgetdcname.dc_unc; + if (dc[0] == '\\') dc++; + if (dc[0] == '\\') dc++; + } + + if (!dc) { + return false; + } + + *dcname = strdup(dc); if (!*dcname) { return false; } -- cgit From 5a61f30d13d55d10b74adf9fdb3a7e6731565682 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Thu, 2 Oct 2008 13:07:14 +0200 Subject: wbclient: add my copyright. Guenther --- source3/nsswitch/libwbclient/wbc_pam.c | 1 + 1 file changed, 1 insertion(+) diff --git a/source3/nsswitch/libwbclient/wbc_pam.c b/source3/nsswitch/libwbclient/wbc_pam.c index 20b42b6efb..70e2aa60a5 100644 --- a/source3/nsswitch/libwbclient/wbc_pam.c +++ b/source3/nsswitch/libwbclient/wbc_pam.c @@ -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 -- cgit From 8fcb81ee996312269b84ac9c7fb835b1048dc64b Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Thu, 2 Oct 2008 13:06:50 +0200 Subject: wbclient: add wbcGuid structure. Guenther --- source3/nsswitch/libwbclient/wbclient.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/source3/nsswitch/libwbclient/wbclient.h b/source3/nsswitch/libwbclient/wbclient.h index cae3feec5b..2fc7a9b7c1 100644 --- a/source3/nsswitch/libwbclient/wbclient.h +++ b/source3/nsswitch/libwbclient/wbclient.h @@ -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 **/ -- cgit From b28db15af8d9d163348e713c0adbb8ab7b955fb4 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Thu, 2 Oct 2008 13:11:31 +0200 Subject: wbclient: add wbcGuidToString and wbcStringToGuid helper functions. Guenther --- source3/Makefile.in | 1 + source3/nsswitch/libwbclient/wbc_guid.c | 118 ++++++++++++++++++++++++++++++++ source3/nsswitch/libwbclient/wbclient.h | 10 +++ 3 files changed, 129 insertions(+) create mode 100644 source3/nsswitch/libwbclient/wbc_guid.c diff --git a/source3/Makefile.in b/source3/Makefile.in index 0ae32a0ef8..18581badea 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -1718,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) \ diff --git a/source3/nsswitch/libwbclient/wbc_guid.c b/source3/nsswitch/libwbclient/wbc_guid.c new file mode 100644 index 0000000000..0cb33e9868 --- /dev/null +++ b/source3/nsswitch/libwbclient/wbc_guid.c @@ -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 . +*/ + +/* 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; +} diff --git a/source3/nsswitch/libwbclient/wbclient.h b/source3/nsswitch/libwbclient/wbclient.h index 2fc7a9b7c1..48b6115612 100644 --- a/source3/nsswitch/libwbclient/wbclient.h +++ b/source3/nsswitch/libwbclient/wbclient.h @@ -411,6 +411,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); -- cgit From eb78e5c46f2ceb1de9cdd459f024d0632ef90893 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Sat, 27 Sep 2008 03:29:01 +0200 Subject: wbclient: add wbcLookupDomainControllerEx call. Guenther --- source3/nsswitch/libwbclient/wbc_util.c | 139 ++++++++++++++++++++++++++++++++ source3/nsswitch/libwbclient/wbclient.h | 21 ++++- 2 files changed, 159 insertions(+), 1 deletion(-) diff --git a/source3/nsswitch/libwbclient/wbc_util.c b/source3/nsswitch/libwbclient/wbc_util.c index 8e01e6e719..5aea884272 100644 --- a/source3/nsswitch/libwbclient/wbc_util.c +++ b/source3/nsswitch/libwbclient/wbc_util.c @@ -550,3 +550,142 @@ 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; +} diff --git a/source3/nsswitch/libwbclient/wbclient.h b/source3/nsswitch/libwbclient/wbclient.h index 48b6115612..327dafdae4 100644 --- a/source3/nsswitch/libwbclient/wbclient.h +++ b/source3/nsswitch/libwbclient/wbclient.h @@ -392,7 +392,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 @@ -554,6 +567,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 */ -- cgit From dd9002cf498e177b769eabd2fed40213069cd239 Mon Sep 17 00:00:00 2001 From: Jeff Layton Date: Thu, 9 Oct 2008 09:58:39 -0400 Subject: mount.cifs: have uppercase_string return success on NULL pointer We currently don't attempt to uppercase the device portion of the mount string if there isn't a prefixpath. Fix that by making uppercase_string return success without doing anything on a NULL pointer. Signed-off-by: Jeff Layton --- source3/client/mount.cifs.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source3/client/mount.cifs.c b/source3/client/mount.cifs.c index b7a76c6102..0c30216cd4 100644 --- a/source3/client/mount.cifs.c +++ b/source3/client/mount.cifs.c @@ -996,12 +996,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 */ -- cgit From 2c9df6401c4b5cbd49c67c86c58f0515426846bb Mon Sep 17 00:00:00 2001 From: Jeff Layton Date: Thu, 9 Oct 2008 09:58:40 -0400 Subject: mount.cifs: make return codes match the return codes for /bin/mount (try #3) The manpage for /bin/mount specifies that the return code should be a positive integer (actually, it's a bitfield). Clean up the return codes from mount.cifs to make them match the expected return values from /bin/mount. This necessary for proper integration with autofs. This is the third attempt at this patch. The changes here are minor, just changing some return's from main() into exit() calls for consistency's sake. Signed-off-by: Jeff Layton --- source3/client/mount.cifs.c | 82 +++++++++++++++++++++++++-------------------- 1 file changed, 46 insertions(+), 36 deletions(-) diff --git a/source3/client/mount.cifs.c b/source3/client/mount.cifs.c index 0c30216cd4..fd8014cf9f 100644 --- a/source3/client/mount.cifs.c +++ b/source3/client/mount.cifs.c @@ -79,6 +79,15 @@ #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) { @@ -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); } -- cgit From 45b359a77f006a366837efa3ad51570942bc4faa Mon Sep 17 00:00:00 2001 From: Volker Lendecke Date: Thu, 9 Oct 2008 17:22:59 +0200 Subject: Make use of ZERO_STRUCT (the first memset was actually wrong) --- source3/modules/vfs_gpfs.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source3/modules/vfs_gpfs.c b/source3/modules/vfs_gpfs.c index 29ea7f0abe..fa0b4e97a5 100644 --- a/source3/modules/vfs_gpfs.c +++ b/source3/modules/vfs_gpfs.c @@ -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) { @@ -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 */ -- cgit From e5692d4cbe70dc4f2aba88db4fa3b68c572c6142 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Thu, 9 Oct 2008 09:49:03 -0700 Subject: Remove SEC_ACCESS. It's a uint32_t. Jeremy. --- source3/include/proto.h | 3 +-- source3/include/rpc_secdes.h | 3 --- source3/lib/display_sec.c | 2 +- source3/lib/secace.c | 2 +- source3/lib/secdesc.c | 13 +------------ source3/lib/sharesec.c | 8 ++++---- source3/lib/util_seaccess.c | 14 +++++++------- source3/libgpo/gpo_reg.c | 14 +++++++------- source3/libsmb/libsmb_xattr.c | 2 +- source3/modules/nfs4_acls.c | 4 ++-- source3/modules/vfs_afsacl.c | 6 ++---- source3/printing/nt_printing.c | 10 +++++----- source3/registry/reg_dispatcher.c | 10 +++------- source3/rpc_server/srv_lsa_nt.c | 10 +++------- source3/rpc_server/srv_samr_nt.c | 19 +++++++++---------- source3/rpc_server/srv_svcctl_nt.c | 9 ++++----- source3/services/services_db.c | 16 ++++++++-------- source3/smbd/posix_acls.c | 26 +++++++------------------- source3/utils/sharesec.c | 2 +- source3/utils/smbcacls.c | 2 +- 20 files changed, 68 insertions(+), 107 deletions(-) diff --git a/source3/include/proto.h b/source3/include/proto.h index 99557a25a1..b7a7ed5479 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -497,7 +497,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); @@ -776,7 +776,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 */ diff --git a/source3/include/rpc_secdes.h b/source3/include/rpc_secdes.h index 83103b7386..71fba41fe9 100644 --- a/source3/include/rpc_secdes.h +++ b/source3/include/rpc_secdes.h @@ -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)) diff --git a/source3/lib/display_sec.c b/source3/lib/display_sec.c index 67392e4568..5427a8173e 100644 --- a/source3/lib/display_sec.c +++ b/source3/lib/display_sec.c @@ -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 : ""); diff --git a/source3/lib/secace.c b/source3/lib/secace.c index 8760a6109a..9f5a0c02ba 100644 --- a/source3/lib/secace.c +++ b/source3/lib/secace.c @@ -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; diff --git a/source3/lib/secdesc.c b/source3/lib/secdesc.c index 4965200bc1..52ff067d6a 100644 --- a/source3/lib/secdesc.c +++ b/source3/lib/secdesc.c @@ -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; -} - - diff --git a/source3/lib/sharesec.c b/source3/lib/sharesec.c index 33f66ca47f..298655e181 100644 --- a/source3/lib/sharesec.c +++ b/source3/lib/sharesec.c @@ -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); } diff --git a/source3/lib/util_seaccess.c b/source3/lib/util_seaccess.c index cab4261adf..7e461556b3 100644 --- a/source3/lib/util_seaccess.c +++ b/source3/lib/util_seaccess.c @@ -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. @@ -346,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; @@ -357,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; diff --git a/source3/libgpo/gpo_reg.c b/source3/libgpo/gpo_reg.c index 920deeb189..d49315021e 100644 --- a/source3/libgpo/gpo_reg.c +++ b/source3/libgpo/gpo_reg.c @@ -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, diff --git a/source3/libsmb/libsmb_xattr.c b/source3/libsmb/libsmb_xattr.c index f1b3d1415e..ea2c46953c 100644 --- a/source3/libsmb/libsmb_xattr.c +++ b/source3/libsmb/libsmb_xattr.c @@ -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; diff --git a/source3/modules/nfs4_acls.c b/source3/modules/nfs4_acls.c index f1b8cfffce..f411176590 100644 --- a/source3/modules/nfs4_acls.c +++ b/source3/modules/nfs4_acls.c @@ -221,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; @@ -256,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); diff --git a/source3/modules/vfs_afsacl.c b/source3/modules/vfs_afsacl.c index c78369ac13..8c89d2fd9f 100644 --- a/source3/modules/vfs_afsacl.c +++ b/source3/modules/vfs_afsacl.c @@ -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; } diff --git a/source3/printing/nt_printing.c b/source3/printing/nt_printing.c index 19c44d1bbb..850375e82b 100644 --- a/source3/printing/nt_printing.c +++ b/source3/printing/nt_printing.c @@ -5493,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; @@ -5502,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); @@ -5514,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); @@ -5524,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); @@ -5534,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); diff --git a/source3/registry/reg_dispatcher.c b/source3/registry/reg_dispatcher.c index c68ecdedeb..d06410a1b3 100644 --- a/source3/registry/reg_dispatcher.c +++ b/source3/registry/reg_dispatcher.c @@ -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 */ diff --git a/source3/rpc_server/srv_lsa_nt.c b/source3/rpc_server/srv_lsa_nt.c index 94517f3478..0e9d121242 100644 --- a/source3/rpc_server/srv_lsa_nt.c +++ b/source3/rpc_server/srv_lsa_nt.c @@ -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; diff --git a/source3/rpc_server/srv_samr_nt.c b/source3/rpc_server/srv_samr_nt.c index 1b1e98c049..6455f02374 100644 --- a/source3/rpc_server/srv_samr_nt.c +++ b/source3/rpc_server/srv_samr_nt.c @@ -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 */ diff --git a/source3/rpc_server/srv_svcctl_nt.c b/source3/rpc_server/srv_svcctl_nt.c index 6bb538a311..a57d0ff4a4 100644 --- a/source3/rpc_server/srv_svcctl_nt.c +++ b/source3/rpc_server/srv_svcctl_nt.c @@ -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 */ diff --git a/source3/services/services_db.c b/source3/services/services_db.c index 8f58c2dbfa..0f5264bcd8 100644 --- a/source3/services/services_db.c +++ b/source3/services/services_db.c @@ -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 */ diff --git a/source3/smbd/posix_acls.c b/source3/smbd/posix_acls.c index da17e53b2c..4e35e9deaa 100644 --- a/source3/smbd/posix_acls.c +++ b/source3/smbd/posix_acls.c @@ -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; } /**************************************************************************** @@ -2962,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)); @@ -2979,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)); @@ -3009,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); } diff --git a/source3/utils/sharesec.c b/source3/utils/sharesec.c index 46f9ecdc7d..3ad949a6d3 100644 --- a/source3/utils/sharesec.c +++ b/source3/utils/sharesec.c @@ -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(); diff --git a/source3/utils/smbcacls.c b/source3/utils/smbcacls.c index d488ce2187..eda8732c89 100644 --- a/source3/utils/smbcacls.c +++ b/source3/utils/smbcacls.c @@ -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(); -- cgit From decd04d946287729866f6b43648d34650211b073 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Thu, 9 Oct 2008 15:40:00 -0700 Subject: Ensure we handle signals correctly during the async calls. Jeremy. --- source3/libsmb/async_smb.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source3/libsmb/async_smb.c b/source3/libsmb/async_smb.c index fb35ecbe1f..68495076b6 100644 --- a/source3/libsmb/async_smb.c +++ b/source3/libsmb/async_smb.c @@ -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) { -- cgit From 9b331df4124118f3957c281023fe8dd11edd44be Mon Sep 17 00:00:00 2001 From: Tim Prouty Date: Wed, 8 Oct 2008 11:48:01 -0700 Subject: Add support for autogen to take a --version-file argument --- source3/autogen.sh | 14 +++++++++++++- source4/autogen.sh | 14 +++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/source3/autogen.sh b/source3/autogen.sh index deed774b39..61316a8f70 100755 --- a/source3/autogen.sh +++ b/source3/autogen.sh @@ -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* diff --git a/source4/autogen.sh b/source4/autogen.sh index a56c5a2238..9984712caf 100755 --- a/source4/autogen.sh +++ b/source4/autogen.sh @@ -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* -- cgit From 10f65cc4ca5a48b6f4dc8c4de23e59628b6f95b2 Mon Sep 17 00:00:00 2001 From: Tim Prouty Date: Wed, 8 Oct 2008 11:06:18 -0700 Subject: remove common lib object files on make cleanlib from source3 source4 already cleans up the object files on make clean. This patch modifies source3 to also do this. --- source3/Makefile.in | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source3/Makefile.in b/source3/Makefile.in index 18581badea..175dcb36be 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -2660,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 -- cgit From 83f55e07557579cd0b9fe3972947fb2327990014 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 7 Oct 2008 18:54:08 +0200 Subject: krb5_locator: use wbcLookupDomainControllerEx() for query. Guenther --- source3/Makefile.in | 6 ++--- source3/nsswitch/winbind_krb5_locator.c | 39 +++++++++++++++------------------ 2 files changed, 21 insertions(+), 24 deletions(-) diff --git a/source3/Makefile.in b/source3/Makefile.in index 175dcb36be..3ef197bcf2 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -1078,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 @@ -2177,9 +2177,9 @@ 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) diff --git a/source3/nsswitch/winbind_krb5_locator.c b/source3/nsswitch/winbind_krb5_locator.c index 7eecd13b70..b9e35bdec5 100644 --- a/source3/nsswitch/winbind_krb5_locator.c +++ b/source3/nsswitch/winbind_krb5_locator.c @@ -18,6 +18,7 @@ */ #include "nsswitch/winbind_client.h" +#include "libwbclient/wbclient.h" #ifndef DEBUG_KRB5 #undef DEBUG_KRB5 @@ -244,54 +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.data.dsgetdcname.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.data.dsgetdcname.domain_name, realm, - sizeof(request.data.dsgetdcname.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; } - if (response.data.dsgetdcname.dc_address[0] != '\0') { - dc = response.data.dsgetdcname.dc_address; + if (dc_info->dc_address) { + dc = dc_info->dc_address; if (dc[0] == '\\') dc++; if (dc[0] == '\\') dc++; } - if (!dc && response.data.dsgetdcname.dc_unc[0] != '\0') { - dc = response.data.dsgetdcname.dc_unc; + 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; } -- cgit From aa22ab1404d6af50cd92c2ad9278c4b551497d24 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 8 Oct 2008 17:09:42 +0200 Subject: Fix executability of samba3-srv. --- pidl/TODO | 3 --- pidl/tests/samba3-srv.pl | 0 2 files changed, 3 deletions(-) mode change 100644 => 100755 pidl/tests/samba3-srv.pl diff --git a/pidl/TODO b/pidl/TODO index 8886441a75..87ae0c5fd3 100644 --- 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: diff --git a/pidl/tests/samba3-srv.pl b/pidl/tests/samba3-srv.pl old mode 100644 new mode 100755 -- cgit From 63291018df809296479147a91c055e296b9ce772 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 8 Oct 2008 17:19:46 +0200 Subject: Use const. --- source4/torture/raw/chkpath.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/source4/torture/raw/chkpath.c b/source4/torture/raw/chkpath.c index 2ed83d308c..68ef8e226d 100644 --- a/source4/torture/raw/chkpath.c +++ b/source4/torture/raw/chkpath.c @@ -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); -- cgit From 08d3918cf8773f1a3f67a82123ebe006ea581e4e Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Fri, 10 Oct 2008 15:13:14 +0200 Subject: libwbclient: fix wbcAuthenticateUserEx() to not ignore provided flags field. Guenther --- source3/nsswitch/libwbclient/wbc_pam.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/source3/nsswitch/libwbclient/wbc_pam.c b/source3/nsswitch/libwbclient/wbc_pam.c index 70e2aa60a5..91ea72f05f 100644 --- a/source3/nsswitch/libwbclient/wbc_pam.c +++ b/source3/nsswitch/libwbclient/wbc_pam.c @@ -332,6 +332,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); @@ -417,6 +418,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); -- cgit From 4464011ceaca803349052ed43217710fc3c33a9e Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Fri, 10 Oct 2008 10:54:06 +0200 Subject: libwbclient: add wbcBlob and wbcNamedBlob. Guenther --- source3/nsswitch/libwbclient/wbclient.h | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/source3/nsswitch/libwbclient/wbclient.h b/source3/nsswitch/libwbclient/wbclient.h index 327dafdae4..5f6e3be966 100644 --- a/source3/nsswitch/libwbclient/wbclient.h +++ b/source3/nsswitch/libwbclient/wbclient.h @@ -218,6 +218,25 @@ 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 ChangePassword Parameters **/ -- cgit From be6e21f9ead06da64f6f96c125612dd4854c0fc4 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Thu, 25 Sep 2008 01:31:12 +0200 Subject: libwbclient: add wbcAddNamedBlob. Guenther --- source3/nsswitch/libwbclient/wbc_util.c | 45 +++++++++++++++++++++++++++++++++ source3/nsswitch/libwbclient/wbclient.h | 10 +++++++- 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/source3/nsswitch/libwbclient/wbc_util.c b/source3/nsswitch/libwbclient/wbc_util.c index 5aea884272..b4868748ae 100644 --- a/source3/nsswitch/libwbclient/wbc_util.c +++ b/source3/nsswitch/libwbclient/wbc_util.c @@ -689,3 +689,48 @@ wbcErr wbcLookupDomainControllerEx(const char *domain, 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; +} diff --git a/source3/nsswitch/libwbclient/wbclient.h b/source3/nsswitch/libwbclient/wbclient.h index 5f6e3be966..5c184ebe46 100644 --- a/source3/nsswitch/libwbclient/wbclient.h +++ b/source3/nsswitch/libwbclient/wbclient.h @@ -627,6 +627,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 */ -- cgit From f33f888de708767b9682202701063fb86250a36e Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Fri, 15 Aug 2008 13:53:23 +0200 Subject: libwbclient: add wbcLogoffUserEx(). Guenther --- source3/nsswitch/libwbclient/wbc_pam.c | 95 +++++++++++++++++++++++++++++++++ source3/nsswitch/libwbclient/wbclient.h | 13 +++++ 2 files changed, 108 insertions(+) diff --git a/source3/nsswitch/libwbclient/wbc_pam.c b/source3/nsswitch/libwbclient/wbc_pam.c index 91ea72f05f..b59e3077bd 100644 --- a/source3/nsswitch/libwbclient/wbc_pam.c +++ b/source3/nsswitch/libwbclient/wbc_pam.c @@ -503,6 +503,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; inum_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 diff --git a/source3/nsswitch/libwbclient/wbclient.h b/source3/nsswitch/libwbclient/wbclient.h index 5c184ebe46..c8e62daf72 100644 --- a/source3/nsswitch/libwbclient/wbclient.h +++ b/source3/nsswitch/libwbclient/wbclient.h @@ -404,6 +404,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 */ @@ -607,6 +617,9 @@ 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); -- cgit From 65dc0c3e2fa2b557d1542a14641381a3d1973831 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Fri, 10 Oct 2008 15:18:02 +0200 Subject: libwbclient: add wbcLogonUser(). Guenther --- source3/nsswitch/libwbclient/wbc_pam.c | 200 ++++++++++++++++++++++++++++++++ source3/nsswitch/libwbclient/wbclient.h | 28 +++++ 2 files changed, 228 insertions(+) diff --git a/source3/nsswitch/libwbclient/wbc_pam.c b/source3/nsswitch/libwbclient/wbc_pam.c index b59e3077bd..713ba2e65b 100644 --- a/source3/nsswitch/libwbclient/wbc_pam.c +++ b/source3/nsswitch/libwbclient/wbc_pam.c @@ -261,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 @@ -895,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; inum_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; +} diff --git a/source3/nsswitch/libwbclient/wbclient.h b/source3/nsswitch/libwbclient/wbclient.h index c8e62daf72..00a3c98966 100644 --- a/source3/nsswitch/libwbclient/wbclient.h +++ b/source3/nsswitch/libwbclient/wbclient.h @@ -237,6 +237,17 @@ struct wbcNamedBlob { 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 **/ @@ -329,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 @@ -613,6 +636,11 @@ 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); -- cgit From 3bbffb96646bda732c21c7c418e80ddc63f16de4 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Thu, 14 Aug 2008 16:53:51 +0200 Subject: pam_winbind: convert to use talloc. Guenther --- source3/Makefile.in | 4 +- source3/nsswitch/pam_winbind.c | 107 +++++++++++++++++++---------------------- source3/nsswitch/pam_winbind.h | 6 +++ 3 files changed, 58 insertions(+), 59 deletions(-) diff --git a/source3/Makefile.in b/source3/Makefile.in index 3ef197bcf2..d3cb86e5d7 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -2182,10 +2182,10 @@ bin/winbind_krb5_locator.@SHLIBEXT@: $(BINARY_PREREQS) $(WINBIND_KRB5_LOCATOR_OB @$(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@ @echo "Linking shared library $@" @$(SHLD) $(LDSHFLAGS) -o $@ $(PAM_WINBIND_OBJ) -lpam @INIPARSERLIBS@ \ - $(PAM_WINBIND_EXTRA_LIBS) @SONAMEFLAG@`basename $@` + $(PAM_WINBIND_EXTRA_LIBS) $(LIBTALLOC_LIBS) @SONAMEFLAG@`basename $@` bin/builtin.@SHLIBEXT@: $(BINARY_PREREQS) $(AUTH_BUILTIN_OBJ) @echo "Building plugin $@" diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index beb0d47baa..cdb30edad4 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -452,13 +452,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 +473,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 +486,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 +506,7 @@ static void _pam_winbind_cleanup_func(pam_handle_t *pamh, "(error_status = %d)", pamh, data, error_status); } - SAFE_FREE(data); + TALLOC_FREE(data); } @@ -1104,14 +1108,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)); } - } /** @@ -1224,69 +1227,59 @@ static void _pam_warn_krb5_failure(struct pwb_context *ctx, * @return string (caller needs to free). */ -static char *_pam_compose_pwd_restriction_string(struct winbindd_response *response) +static char *_pam_compose_pwd_restriction_string(struct pwb_context *ctx, + struct winbindd_response *response) { char *str = NULL; - size_t offset = 0, ret = 0, str_size = 1024; - str = (char *)malloc(str_size); + str = talloc_asprintf(ctx, "Your password "); if (!str) { - return NULL; - } - - memset(str, '\0', str_size); - - offset = snprintf(str, str_size, "Your password "); - if (offset == -1) { goto failed; } if (response->data.auth.policy.min_length_password > 0) { - ret = snprintf(str+offset, str_size-offset, + str = talloc_asprintf_append(str, "must be at least %d characters; ", response->data.auth.policy.min_length_password); - if (ret == -1) { + if (!str) { goto failed; } - offset += ret; } if (response->data.auth.policy.password_history > 0) { - ret = snprintf(str+offset, str_size-offset, + str = talloc_asprintf_append(str, "cannot repeat any of your previous %d " "passwords; ", response->data.auth.policy.password_history); - if (ret == -1) { + if (!str) { goto failed; } - offset += ret; } if (response->data.auth.policy.password_properties & DOMAIN_PASSWORD_COMPLEX) { - ret = snprintf(str+offset, str_size-offset, + 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; } @@ -1590,11 +1583,11 @@ static int winbind_chauthtok_request(struct pwb_context *ctx, } pwd_restriction_string = - _pam_compose_pwd_restriction_string(&response); + _pam_compose_pwd_restriction_string(ctx, &response); if (pwd_restriction_string) { _make_remark(ctx, PAM_ERROR_MSG, pwd_restriction_string); - SAFE_FREE(pwd_restriction_string); + TALLOC_FREE(pwd_restriction_string); } } @@ -1846,12 +1839,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 +1887,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", @@ -1977,8 +1972,6 @@ static char* winbind_upn_to_username(struct pwb_context *ctx, struct winbindd_request req; struct winbindd_response resp; int retval; - char *account_name; - int account_name_len; char sep; /* This cannot work when the winbind separator = @ */ @@ -2014,11 +2007,9 @@ static char* winbind_upn_to_username(struct pwb_context *ctx, 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", + resp.data.name.dom_name, + resp.data.name.name); } PAM_EXTERN @@ -2087,7 +2078,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); } } @@ -2127,7 +2118,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 +2130,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 +2165,7 @@ out: _PAM_LOG_FUNCTION_LEAVE("pam_sm_authenticate", ctx, retval); - _pam_winbind_free_context(ctx); + TALLOC_FREE(ctx); return retval; } @@ -2220,7 +2213,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 +2314,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; } @@ -2345,7 +2338,7 @@ int pam_sm_open_session(pam_handle_t *pamh, int flags, out: _PAM_LOG_FUNCTION_LEAVE("pam_sm_open_session", ctx, ret); - _pam_winbind_free_context(ctx); + TALLOC_FREE(ctx); return ret; } @@ -2431,7 +2424,7 @@ out: _PAM_LOG_FUNCTION_LEAVE("pam_sm_close_session", ctx, retval); - _pam_winbind_free_context(ctx); + TALLOC_FREE(ctx); return retval; } @@ -2560,16 +2553,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 +2570,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"); @@ -2760,7 +2753,7 @@ out: _PAM_LOG_FUNCTION_LEAVE("pam_sm_chauthtok", ctx, ret); - _pam_winbind_free_context(ctx); + TALLOC_FREE(ctx); return ret; } diff --git a/source3/nsswitch/pam_winbind.h b/source3/nsswitch/pam_winbind.h index 6dba127cdc..425471d0d6 100644 --- a/source3/nsswitch/pam_winbind.h +++ b/source3/nsswitch/pam_winbind.h @@ -7,6 +7,7 @@ #include "../lib/replace/replace.h" #include "system/syslog.h" #include "system/time.h" +#include #define MODULE_NAME "pam_winbind" #define PAM_SM_AUTH @@ -209,3 +210,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) + -- cgit From 7817ad4ae0c462429f176ddf94bebcd44a3d6619 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Thu, 14 Aug 2008 18:15:00 +0200 Subject: pam_winbind: prepare to use libwbclient inside pam_winbind. Guenther --- source3/Makefile.in | 4 ++-- source3/nsswitch/pam_winbind.h | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/source3/Makefile.in b/source3/Makefile.in index d3cb86e5d7..8bee54d075 100644 --- a/source3/Makefile.in +++ b/source3/Makefile.in @@ -2182,10 +2182,10 @@ bin/winbind_krb5_locator.@SHLIBEXT@: $(BINARY_PREREQS) $(WINBIND_KRB5_LOCATOR_OB @$(SHLD) $(LDSHFLAGS) -o $@ $(WINBIND_KRB5_LOCATOR_OBJ) $(WINBIND_LIBS) \ @SONAMEFLAG@`basename $@` -bin/pam_winbind.@SHLIBEXT@: $(BINARY_PREREQS) $(PAM_WINBIND_OBJ) @LIBTALLOC_SHARED@ +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) $(LIBTALLOC_LIBS) @SONAMEFLAG@`basename $@` + $(PAM_WINBIND_EXTRA_LIBS) $(LIBTALLOC_LIBS) $(WINBIND_LIBS) @SONAMEFLAG@`basename $@` bin/builtin.@SHLIBEXT@: $(BINARY_PREREQS) $(AUTH_BUILTIN_OBJ) @echo "Building plugin $@" diff --git a/source3/nsswitch/pam_winbind.h b/source3/nsswitch/pam_winbind.h index 425471d0d6..ea7055ae19 100644 --- a/source3/nsswitch/pam_winbind.h +++ b/source3/nsswitch/pam_winbind.h @@ -8,6 +8,7 @@ #include "system/syslog.h" #include "system/time.h" #include +#include "libwbclient/wbclient.h" #define MODULE_NAME "pam_winbind" #define PAM_SM_AUTH -- cgit From 0532291fe9650f968aab0fb6b60e08f41b334c24 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Fri, 15 Aug 2008 03:13:18 +0200 Subject: pam_winbind: add wbc_error_to_pam_error(). Guenther --- source3/nsswitch/pam_winbind.c | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index cdb30edad4..e8f2459568 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -12,6 +12,42 @@ #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) { -- cgit From 0566164db03a19b98d4aec5cca63ece2a01acbec Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 19 Aug 2008 10:59:18 +0200 Subject: pam_winbind: add wbc_auth_error_to_pam_error(). Guenther --- source3/nsswitch/pam_winbind.c | 53 +++++++++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index e8f2459568..c840bba9d4 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -749,15 +749,9 @@ static int pam_winbind_request(struct pwb_context *ctx, } static int pam_winbind_request_log(struct pwb_context *ctx, - enum winbindd_cmd req_type, - struct winbindd_request *request, - struct winbindd_response *response, + int retval, const char *user) { - int retval; - - retval = pam_winbind_request(ctx, req_type, request, response); - switch (retval) { case PAM_AUTH_ERR: /* incorrect password */ @@ -789,6 +783,7 @@ static int pam_winbind_request_log(struct pwb_context *ctx, return retval; case PAM_SUCCESS: /* Otherwise, the authentication looked good */ +#if 0 switch (req_type) { case WINBINDD_INFO: break; @@ -805,7 +800,7 @@ static int pam_winbind_request_log(struct pwb_context *ctx, "user '%s' OK", user); break; } - +#endif return retval; default: /* we don't know anything about this return value */ @@ -816,6 +811,48 @@ static int pam_winbind_request_log(struct pwb_context *ctx, } } +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); + } + + 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); + } + + _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); + } + + ret = wbc_error_to_pam_error(status); + return pam_winbind_request_log(ctx, ret, username); +} + + /** * send a password expiry message if required * -- cgit From b1282d720cffeb4b89bc5276b827e60ccef3f110 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 19 Aug 2008 13:36:39 +0200 Subject: pam_winbind: add _pam_check_remark_auth_err(). Guenther --- source3/nsswitch/pam_winbind.c | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index c840bba9d4..41dacd7105 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -1292,6 +1292,47 @@ 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. * -- cgit From 377e4f929a4e0913fcc4b531437049db450659ea Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Thu, 14 Aug 2008 18:15:29 +0200 Subject: pam_winbind: use libwbclient for WINBINDD_GETPWNAM. Guenther --- source3/nsswitch/pam_winbind.c | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index 41dacd7105..4f4f043df4 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -718,7 +718,6 @@ static int pam_winbind_request(struct pwb_context *ctx, /* 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, @@ -1723,29 +1722,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; -- cgit From d397bafa0ac00df862d6c2b165df6b7cf9d2d4bd Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Thu, 14 Aug 2008 18:17:00 +0200 Subject: pam_winbind: use libwbclient for WINBINDD_INFO. Guenther --- source3/nsswitch/pam_winbind.c | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index 4f4f043df4..14eea9f0d6 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -784,8 +784,6 @@ static int pam_winbind_request_log(struct pwb_context *ctx, /* Otherwise, the authentication looked good */ #if 0 switch (req_type) { - case WINBINDD_INFO: - break; case WINBINDD_PAM_AUTH: _pam_log(ctx, LOG_NOTICE, "user '%s' granted access", user); @@ -2053,20 +2051,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. * -- cgit From ed2b94c1a29017013a8eb773755c051f4c2a2eb0 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Thu, 14 Aug 2008 23:33:12 +0200 Subject: pam_winbind: use libwbclient for WINBINDD_LOOKUPNAME/LOOKUPSID. Guenther --- source3/nsswitch/pam_winbind.c | 74 +++++++++++++----------------------------- 1 file changed, 23 insertions(+), 51 deletions(-) diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index 14eea9f0d6..9448890d28 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -715,22 +715,6 @@ static int pam_winbind_request(struct pwb_context *ctx, return PAM_SUCCESS; } - /* no need to check for pam_error codes for getpwnam() */ - switch (req_type) { - - 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, " @@ -1018,33 +1002,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, @@ -2082,10 +2066,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 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 = @ */ @@ -2096,33 +2082,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; } - return talloc_asprintf(ctx, "%s\\%s", - resp.data.name.dom_name, - resp.data.name.name); + return talloc_asprintf(ctx, "%s\\%s", domain, name); } PAM_EXTERN -- cgit From 3eae89dd7729c08a40d97dc1b095011bf2933dce Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Fri, 15 Aug 2008 02:34:22 +0200 Subject: pam_winbind: use libwbclient for WINBINDD_PAM_CHAUTHTOK. Guenther --- source3/nsswitch/pam_winbind.c | 144 ++++++++++++++++++++--------------------- source3/nsswitch/pam_winbind.h | 8 --- 2 files changed, 71 insertions(+), 81 deletions(-) diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index 9448890d28..4f9a27b721 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -772,10 +772,6 @@ static int pam_winbind_request_log(struct pwb_context *ctx, _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); @@ -1317,42 +1313,45 @@ static bool _pam_check_remark_auth_err(struct pwb_context *ctx, /** * 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 pwb_context *ctx, - struct winbindd_response *response) + struct wbcUserPasswordPolicyInfo *i) { char *str = NULL; + if (!i) { + goto failed; + } + str = talloc_asprintf(ctx, "Your password "); if (!str) { goto failed; } - if (response->data.auth.policy.min_length_password > 0) { + if (i->min_length_password > 0) { str = talloc_asprintf_append(str, "must be at least %d characters; ", - response->data.auth.policy.min_length_password); + i->min_length_password); if (!str) { goto failed; } } - if (response->data.auth.policy.password_history > 0) { + if (i->password_history > 0) { str = talloc_asprintf_append(str, "cannot repeat any of your previous %d " "passwords; ", - response->data.auth.policy.password_history); + i->password_history); if (!str) { goto failed; } } - if (response->data.auth.policy.password_properties & - DOMAIN_PASSWORD_COMPLEX) { + if (i->password_properties & WBC_DOMAIN_PASSWORD_COMPLEX) { str = talloc_asprintf_append(str, "must contain capitals, numerals " "or punctuation; " @@ -1572,99 +1571,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; - - ZERO_STRUCT(request); - ZERO_STRUCT(response); - - if (request.data.chauthtok.user == NULL) { - return -2; - } - - strncpy(request.data.chauthtok.user, user, - sizeof(request.data.chauthtok.user) - 1); + wbcErr wbc_status; + struct wbcChangePasswordParams params; + struct wbcAuthErrorInfo *error = NULL; + struct wbcUserPasswordPolicyInfo *policy = NULL; + enum wbcPasswordChangeRejectReason reject_reason = -1; + uint32_t flags = 0; - if (oldpass != NULL) { - strncpy(request.data.chauthtok.oldpass, oldpass, - sizeof(request.data.chauthtok.oldpass) - 1); - } else { - request.data.chauthtok.oldpass[0] = '\0'; - } + 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; - if (newpass != NULL) { - strncpy(request.data.chauthtok.newpass, newpass, - sizeof(request.data.chauthtok.newpass) - 1); - } else { - request.data.chauthtok.newpass[0] = '\0'; - } + ZERO_STRUCT(params); if (ctx->ctrl & WINBIND_KRB5_AUTH) { - request.flags = WBFLAG_PAM_KRB5 | - WBFLAG_PAM_CONTACT_TRUSTDOM; + flags |= WBFLAG_PAM_KRB5 | + WBFLAG_PAM_CONTACT_TRUSTDOM; } if (ctx->ctrl & WINBIND_CACHED_LOGIN) { - request.flags |= WBFLAG_PAM_CACHED_LOGIN; + flags |= WBFLAG_PAM_CACHED_LOGIN; } - ret = pam_winbind_request_log(ctx, WINBINDD_PAM_CHAUTHTOK, - &request, &response, user); - - if (ret == PAM_SUCCESS) { - return ret; - } + params.account_name = user; + params.level = WBC_AUTH_USER_LEVEL_PLAIN; + params.old_password.plaintext = oldpass; + params.new_password.plaintext = newpass; + params.flags = flags; - 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"); + wbc_status = wbcChangeUserPasswordEx(¶ms, &error, &reject_reason, &policy); + ret = wbc_auth_error_to_pam_error(ctx, error, wbc_status, + user, "wbcChangeUserPasswordEx"); - /* TODO: tell the min pwd length ? */ - PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response, - "NT_STATUS_PWD_TOO_SHORT"); + if (WBC_ERROR_IS_OK(wbc_status)) { + _pam_log(ctx, LOG_NOTICE, + "user '%s' password changed", user); + return PAM_SUCCESS; + } - /* TODO: tell the minage ? */ - PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response, - "NT_STATUS_PWD_TOO_RECENT"); + if (!error) { + wbcFreeMemory(policy); + return ret; + } - /* TODO: tell the history length ? */ - PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response, - "NT_STATUS_PWD_HISTORY_CONFLICT"); + for (i=0; int_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"); @@ -1678,13 +1673,16 @@ static int winbind_chauthtok_request(struct pwb_context *ctx, } pwd_restriction_string = - _pam_compose_pwd_restriction_string(ctx, &response); + _pam_compose_pwd_restriction_string(ctx, policy); if (pwd_restriction_string) { _make_remark(ctx, PAM_ERROR_MSG, pwd_restriction_string); TALLOC_FREE(pwd_restriction_string); } } + done: + wbcFreeMemory(error); + wbcFreeMemory(policy); return ret; } diff --git a/source3/nsswitch/pam_winbind.h b/source3/nsswitch/pam_winbind.h index ea7055ae19..f05f2d7018 100644 --- a/source3/nsswitch/pam_winbind.h +++ b/source3/nsswitch/pam_winbind.h @@ -182,14 +182,6 @@ do { \ };\ }; -/* 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 */ -- cgit From d3afd534291fc7bb9ed7326c7ecf22433441191d Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Fri, 15 Aug 2008 14:00:20 +0200 Subject: pam_winbind: use libwbclient for WINBINDD_PAM_LOGOFF. Guenther --- source3/nsswitch/pam_winbind.c | 75 +++++++++++++++++++++++++++++++----------- 1 file changed, 56 insertions(+), 19 deletions(-) diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index 4f9a27b721..defdbdbd2c 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -2432,6 +2432,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) { @@ -2448,15 +2449,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, @@ -2480,30 +2481,66 @@ 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; + + 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; + } - retval = pam_winbind_request_log(ctx, - WINBINDD_PAM_LOGOFF, - &request, &response, user); + 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); -- cgit From dde8046489cde714a42694d2979bfa44dac71cd6 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 19 Aug 2008 11:07:59 +0200 Subject: pam_winbind: use libwbclient for WINBINDD_PAM_AUTH. Guenther --- source3/nsswitch/pam_winbind.c | 367 ++++++++++++++++++++++++++++------------- 1 file changed, 251 insertions(+), 116 deletions(-) diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index defdbdbd2c..f343967b3f 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -902,29 +902,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) { + if (info->acct_flags & 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, @@ -935,12 +940,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, @@ -1109,15 +1113,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; } @@ -1137,6 +1154,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. * @@ -1178,16 +1230,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); } /** @@ -1384,37 +1436,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)) { @@ -1424,7 +1491,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) { @@ -1432,38 +1499,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); @@ -1471,60 +1534,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; } - if (p_response) { - /* We want to process the response in the caller. */ - *p_response = response; + 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; + } + + 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"); - } - - if (ret == PAM_SUCCESS) { + for (i=0; ipass_last_set_time; + _pam_log_debug(ctx, LOG_DEBUG, "Password has expired " "(Password was last set: %lld, " @@ -1532,33 +1635,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; @@ -2193,7 +2307,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 || @@ -2616,11 +2731,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; @@ -2700,7 +2813,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 && @@ -2809,6 +2923,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); @@ -2823,7 +2939,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); @@ -2831,19 +2948,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, @@ -2853,6 +2975,9 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags, username_ret); free(username_ret); } + + wbcFreeMemory(info); + wbcFreeMemory(policy); } goto out; @@ -2862,14 +2987,24 @@ 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 Date: Tue, 19 Aug 2008 14:48:23 +0200 Subject: pam_winbind: remove ACB_PWNOEXP. Guenther --- source3/nsswitch/pam_winbind.c | 4 ++-- source3/nsswitch/pam_winbind.h | 2 -- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index f343967b3f..43157b7727 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -918,8 +918,8 @@ static void _pam_warn_password_expiry(struct pwb_context *ctx, *already_expired = false; } - /* accounts with ACB_PWNOEXP set never receive a warning */ - if (info->acct_flags & ACB_PWNOEXP) { + /* accounts with WBC_ACB_PWNOEXP set never receive a warning */ + if (info->acct_flags & WBC_ACB_PWNOEXP) { return; } diff --git a/source3/nsswitch/pam_winbind.h b/source3/nsswitch/pam_winbind.h index f05f2d7018..1b1d646643 100644 --- a/source3/nsswitch/pam_winbind.h +++ b/source3/nsswitch/pam_winbind.h @@ -182,8 +182,6 @@ do { \ };\ }; -#define ACB_PWNOEXP 0x00000200 - /* from netlogon.idl */ #define NETLOGON_CACHED_ACCOUNT 0x00000004 #define NETLOGON_GRACE_LOGON 0x01000000 -- cgit From 9a0860f93f8260040ac458b06d7a8609b7b5beab Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 19 Aug 2008 14:51:31 +0200 Subject: pam_winbind: remove NETLOGON_CACHED_ACCOUNT and NETLOGON_GRACE_LOGON. Guenther --- source3/nsswitch/pam_winbind.h | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/source3/nsswitch/pam_winbind.h b/source3/nsswitch/pam_winbind.h index 1b1d646643..670120afde 100644 --- a/source3/nsswitch/pam_winbind.h +++ b/source3/nsswitch/pam_winbind.h @@ -182,16 +182,11 @@ do { \ };\ }; -/* 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; -- cgit From 9448520828bbd78f34d027fd1801467395449b7c Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Mon, 25 Aug 2008 14:35:42 +0200 Subject: pam_winbind: remove some unused macros. Guenther --- source3/nsswitch/pam_winbind.h | 47 ------------------------------------------ 1 file changed, 47 deletions(-) diff --git a/source3/nsswitch/pam_winbind.h b/source3/nsswitch/pam_winbind.h index 670120afde..e7c869c843 100644 --- a/source3/nsswitch/pam_winbind.h +++ b/source3/nsswitch/pam_winbind.h @@ -135,53 +135,6 @@ 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;\ - };\ -}; - #define LOGON_KRB5_FAIL_CLOCK_SKEW 0x02000000 #define PAM_WB_CACHED_LOGON(x) (x & WBC_AUTH_USER_INFO_CACHED_ACCOUNT) -- cgit From e8fe6661b4bbf338f46c52cb12c7bdb04037f297 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Tue, 19 Aug 2008 14:52:24 +0200 Subject: pam_winbind: fix wbc_auth_error_to_pam_error(). Guenther --- source3/nsswitch/pam_winbind.c | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index 43157b7727..cac8550e60 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -733,7 +733,8 @@ static int pam_winbind_request(struct pwb_context *ctx, static int pam_winbind_request_log(struct pwb_context *ctx, int retval, - const char *user) + const char *user, + const char *fn) { switch (retval) { case PAM_AUTH_ERR: @@ -766,24 +767,19 @@ static int pam_winbind_request_log(struct pwb_context *ctx, return retval; case PAM_SUCCESS: /* Otherwise, the authentication looked good */ -#if 0 - switch (req_type) { - case WINBINDD_PAM_AUTH: - _pam_log(ctx, LOG_NOTICE, - "user '%s' granted access", 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); } -#endif 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; } } @@ -800,7 +796,7 @@ static int wbc_auth_error_to_pam_error(struct pwb_context *ctx, _pam_log_debug(ctx, LOG_DEBUG, "request %s succeeded", fn); ret = PAM_SUCCESS; - return pam_winbind_request_log(ctx, ret, username); + return pam_winbind_request_log(ctx, ret, username, fn); } if (e) { @@ -816,17 +812,17 @@ static int wbc_auth_error_to_pam_error(struct pwb_context *ctx, e->nt_string, e->display_string); ret = e->pam_error; - return pam_winbind_request_log(ctx, ret, username); + 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); + return pam_winbind_request_log(ctx, ret, username, fn); } ret = wbc_error_to_pam_error(status); - return pam_winbind_request_log(ctx, ret, username); + return pam_winbind_request_log(ctx, ret, username, fn); } -- cgit From d9efd52fd09af752b3b7fae2a88a522e05e7f672 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Fri, 29 Aug 2008 16:12:04 +0200 Subject: pam_winbind: remove unused pam_winbind_request(). Guenther --- source3/nsswitch/pam_winbind.c | 47 ------------------------------------------ 1 file changed, 47 deletions(-) diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index cac8550e60..a9d6aa650a 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -684,53 +684,6 @@ 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; - } - - 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, int retval, const char *user, -- cgit From 042df7f0b78d60a721fa35c42e950774261cea1d Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Thu, 14 Aug 2008 14:39:52 +0200 Subject: pam_winbind: re-add mkhomedir option. Guenther --- examples/pam_winbind/pam_winbind.conf | 3 + source3/nsswitch/pam_winbind.c | 135 +++++++++++++++++++++++++++++++++- source3/nsswitch/pam_winbind.h | 1 + 3 files changed, 136 insertions(+), 3 deletions(-) diff --git a/examples/pam_winbind/pam_winbind.conf b/examples/pam_winbind/pam_winbind.conf index a9e02a833a..dd0b112f30 100644 --- a/examples/pam_winbind/pam_winbind.conf +++ b/examples/pam_winbind/pam_winbind.conf @@ -33,3 +33,6 @@ # omit pam conversations ;silent = no + +# create homedirectory on the fly +;mkhomedir = no diff --git a/source3/nsswitch/pam_winbind.c b/source3/nsswitch/pam_winbind.c index a9d6aa650a..8d8868d0ef 100644 --- a/source3/nsswitch/pam_winbind.c +++ b/source3/nsswitch/pam_winbind.c @@ -437,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) { @@ -469,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); @@ -1378,6 +1384,127 @@ static char *_pam_compose_pwd_restriction_string(struct pwb_context *ctx, 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, @@ -2470,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); @@ -2480,8 +2607,10 @@ 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); diff --git a/source3/nsswitch/pam_winbind.h b/source3/nsswitch/pam_winbind.h index e7c869c843..cb6f450ccb 100644 --- a/source3/nsswitch/pam_winbind.h +++ b/source3/nsswitch/pam_winbind.h @@ -99,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 -- cgit From 5b75aa34069d488d23e880393d4280cbe85cc5c6 Mon Sep 17 00:00:00 2001 From: Günther Deschner Date: Thu, 14 Aug 2008 14:41:50 +0200 Subject: pam_winbind: document mkhomedir option. Guenther --- docs-xml/manpages-3/pam_winbind.7.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs-xml/manpages-3/pam_winbind.7.xml b/docs-xml/manpages-3/pam_winbind.7.xml index cf7fd5a0f6..7f233c1386 100644 --- a/docs-xml/manpages-3/pam_winbind.7.xml +++ b/docs-xml/manpages-3/pam_winbind.7.xml @@ -134,6 +134,14 @@ + + mkhomedir + + Create homedirectory for a user on-the-fly, option is valid in + PAM session block. + + + -- cgit From eada8f8abe6e4b770b7a2e279fc897a4272b6fa5 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Fri, 10 Oct 2008 11:55:14 -0700 Subject: If you have a large number of cups printers, then scanning for print info can cause a client to timeout (it takes longer than 30 seconds to enumerate them). Make scanning for printers async with a callback from the main loop. This fixes a bug that was irritating *me* :-). Jeremy. --- source3/include/proto.h | 8 +- source3/include/smb.h | 1 + source3/param/loadparm.c | 2 +- source3/printing/load.c | 2 +- source3/printing/pcap.c | 77 +++++++++------ source3/printing/print_cups.c | 211 +++++++++++++++++++++++++++++++++++++++++- 6 files changed, 267 insertions(+), 34 deletions(-) diff --git a/source3/include/proto.h b/source3/include/proto.h index b7a7ed5479..fc497b6966 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -5995,7 +5995,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); @@ -6568,11 +6568,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 */ diff --git a/source3/include/smb.h b/source3/include/smb.h index c8c4f8c3cc..ef98b5e1b5 100644 --- a/source3/include/smb.h +++ b/source3/include/smb.h @@ -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; diff --git a/source3/param/loadparm.c b/source3/param/loadparm.c index 94660317f8..1191c3d3aa 100644 --- a/source3/param/loadparm.c +++ b/source3/param/loadparm.c @@ -7848,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; diff --git a/source3/printing/load.c b/source3/printing/load.c index 23144d5a95..fc21f271bd 100644 --- a/source3/printing/load.c +++ b/source3/printing/load.c @@ -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); } diff --git a/source3/printing/pcap.c b/source3/printing/pcap.c index 30cb254a29..10c1a2d608 100644 --- a/source3/printing/pcap.c +++ b/source3/printing/pcap.c @@ -63,41 +63,51 @@ #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); +} diff --git a/source3/printing/print_cups.c b/source3/printing/print_cups.c index b9bed7a138..6fe24e181e 100644 --- a/source3/printing/print_cups.c +++ b/source3/printing/print_cups.c @@ -106,9 +106,46 @@ static http_t *cups_connect(TALLOC_CTX *frame) 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 */ @@ -226,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; } } @@ -318,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; } } @@ -335,10 +372,178 @@ 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; + + 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. */ + 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)); + + TALLOC_FREE(cache_fd_event); + + while (1) { + char *name = NULL, *info = NULL; + size_t namelen = 0, infolen = 0; + + if (sys_read(fd, &namelen, sizeof(namelen)) != + sizeof(namelen)) { + DEBUG(10,("cups_async_callback: namelen read failed %d %s\n", + errno, strerror(errno))); + break; + } + if (sys_read(fd, &infolen, sizeof(infolen)) != + sizeof(infolen)) { + DEBUG(10,("cups_async_callback: infolen read failed %s\n", + strerror(errno))); + break; + } + if (namelen) { + name = TALLOC_ARRAY(frame, char, namelen); + if (!name) { + break; + } + if (sys_read(fd, name, namelen) != namelen) { + DEBUG(10,("cups_async_callback: name read failed %s\n", + strerror(errno))); + break; + } + } else { + name = NULL; + } + if (infolen) { + info = TALLOC_ARRAY(frame, char, infolen); + if (!info) { + break; + } + if (sys_read(fd, info, infolen) != infolen) { + DEBUG(10,("cups_async_callback: info read failed %s\n", + strerror(errno))); + break; + } + } 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); +} + +bool cups_cache_reload(void) +{ + int fd = -1; + + /* Set up an async refresh. */ + if (!cups_pcap_load_async(&fd)) { + return false; + } + if (!local_pcap_copy) { + /* We have no local cache, wait directly for + * async refresh to complete. + */ + cups_async_callback(smbd_event_context(), + NULL, + EVENT_FD_READ, + (void *)&fd); + if (!local_pcap_copy) { + return false; + } + } else { + /* Replace the system cache with our + * local copy. */ + pcap_cache_replace(local_pcap_copy); + + /* Trigger an event when the pipe can be read. */ + cache_fd_event = event_add_fd(smbd_event_context(), + NULL, fd, + EVENT_FD_READ, + cups_async_callback, + (void *)&fd); + if (!cache_fd_event) { + close(fd); + return false; + } + } + return true; +} /* * 'cups_job_delete()' - Delete a job. -- cgit From 430cc443901865a5c781ce4ac5cf65b450ccbe61 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Fri, 10 Oct 2008 15:55:49 -0700 Subject: Async is trickier than it looks :-). Don't use a stack variable for a private data ptr. Jeremy. --- source3/printing/print_cups.c | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/source3/printing/print_cups.c b/source3/printing/print_cups.c index 6fe24e181e..14119626e5 100644 --- a/source3/printing/print_cups.c +++ b/source3/printing/print_cups.c @@ -505,24 +505,32 @@ static void cups_async_callback(struct event_context *event_ctx, "printer list\n")); } close(fd); + TALLOC_FREE(p); } bool cups_cache_reload(void) { - int fd = -1; + int *p_pipe_fd = TALLOC_P(NULL, int); + + if (!p_pipe_fd) { + return false; + } /* Set up an async refresh. */ - if (!cups_pcap_load_async(&fd)) { + 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 *)&fd); + (void *)p_pipe_fd); if (!local_pcap_copy) { return false; } @@ -531,14 +539,18 @@ bool cups_cache_reload(void) * 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, fd, + NULL, *p_pipe_fd, EVENT_FD_READ, cups_async_callback, - (void *)&fd); + (void *)p_pipe_fd); if (!cache_fd_event) { - close(fd); + close(*p_pipe_fd); + TALLOC_FREE(p_pipe_fd); return false; } } -- cgit From 4cbb3b23a4e1d5e800b900fe91860eb0a9add12e Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Fri, 10 Oct 2008 16:29:14 -0700 Subject: Allow data flow to be debugged and only log on error. All seems ok now. Jeremy. --- source3/printing/print_cups.c | 48 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 8 deletions(-) diff --git a/source3/printing/print_cups.c b/source3/printing/print_cups.c index 14119626e5..6086bb858b 100644 --- a/source3/printing/print_cups.c +++ b/source3/printing/print_cups.c @@ -392,6 +392,8 @@ 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" )); @@ -441,34 +443,56 @@ static void cups_async_callback(struct event_context *event_ctx, DEBUG(5,("cups_async_callback: callback received for printer data. " "fd = %d\n", fd)); - TALLOC_FREE(cache_fd_event); - while (1) { char *name = NULL, *info = NULL; size_t namelen = 0, infolen = 0; + ssize_t ret = -1; - if (sys_read(fd, &namelen, sizeof(namelen)) != - sizeof(namelen)) { + 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; } - if (sys_read(fd, &infolen, sizeof(infolen)) != - sizeof(infolen)) { + + 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; } - if (sys_read(fd, name, namelen) != namelen) { + 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; } @@ -477,11 +501,18 @@ static void cups_async_callback(struct event_context *event_ctx, if (!info) { break; } - if (sys_read(fd, info, infolen) != infolen) { + 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; } @@ -506,6 +537,7 @@ static void cups_async_callback(struct event_context *event_ctx, } close(fd); TALLOC_FREE(p); + TALLOC_FREE(cache_fd_event); } bool cups_cache_reload(void) -- cgit From 1d151b3161b1bf82898baa9eb9dd1f212b79e2a1 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Fri, 10 Oct 2008 16:43:13 -0700 Subject: Ensure we do reinit_after_fork(). Jeremy. --- source3/printing/print_cups.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/source3/printing/print_cups.c b/source3/printing/print_cups.c index 6086bb858b..9326ac74a4 100644 --- a/source3/printing/print_cups.c +++ b/source3/printing/print_cups.c @@ -425,6 +425,11 @@ static bool cups_pcap_load_async(int *pfd) } /* 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]); -- cgit From 47f7ef8f39ba482a7d6578ab82c9e0670381c4f8 Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Fri, 10 Oct 2008 16:48:18 -0700 Subject: Initialize near creation of resource. Makes code clearer. Jeremy. --- source3/printing/print_cups.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source3/printing/print_cups.c b/source3/printing/print_cups.c index 9326ac74a4..ca3415ca5a 100644 --- a/source3/printing/print_cups.c +++ b/source3/printing/print_cups.c @@ -553,6 +553,8 @@ bool cups_cache_reload(void) return false; } + *p_pipe_fd = -1; + /* Set up an async refresh. */ if (!cups_pcap_load_async(p_pipe_fd)) { return false; -- cgit