diff options
author | Andrew Bartlett <abartlet@samba.org> | 2008-05-28 08:11:05 +1000 |
---|---|---|
committer | Andrew Bartlett <abartlet@samba.org> | 2008-05-28 08:11:05 +1000 |
commit | 51ae2302a68033b1b79a4ebc8d4cbab64adcf843 (patch) | |
tree | d8b1af54efe4ec70607ef2bcbd873c2cd667d894 /source4/scripting | |
parent | 5d0d239d1ab826c91839a603f93d2c0061658888 (diff) | |
parent | 52b230141b5ad9f317f97e7d257703614bab3985 (diff) | |
download | samba-51ae2302a68033b1b79a4ebc8d4cbab64adcf843.tar.gz samba-51ae2302a68033b1b79a4ebc8d4cbab64adcf843.tar.bz2 samba-51ae2302a68033b1b79a4ebc8d4cbab64adcf843.zip |
Merge branch 'v4-0-test' of ssh://git.samba.org/data/git/samba into 4-0-abartlet
It seems the format of main.mk changed in my sleep...
Conflicts:
source/main.mk
(This used to be commit 56f2288e4f4f1aa70d11fc5f118458baf5803627)
Diffstat (limited to 'source4/scripting')
52 files changed, 799 insertions, 5807 deletions
diff --git a/source4/scripting/bin/autoidl.py b/source4/scripting/bin/autoidl.py new file mode 100755 index 0000000000..eed4ba3a80 --- /dev/null +++ b/source4/scripting/bin/autoidl.py @@ -0,0 +1,161 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Unix SMB/CIFS implementation. +# Copyright © Jelmer Vernooij <jelmer@samba.org> 2008 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +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 <binding> <UUID> [<version>]" + 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/minschema.py b/source4/scripting/bin/minschema.py index 6dd5b42aff..111557126d 100755 --- a/source4/scripting/bin/minschema.py +++ b/source4/scripting/bin/minschema.py @@ -5,6 +5,8 @@ import optparse +import os, sys + # Find right directory when running from source tree sys.path.insert(0, "bin/python") diff --git a/source4/scripting/bin/samba3dump b/source4/scripting/bin/samba3dump index d89667233f..c11f8dbd0d 100755 --- a/source4/scripting/bin/samba3dump +++ b/source4/scripting/bin/samba3dump @@ -14,7 +14,7 @@ sys.path.insert(0, "bin/python") import samba import samba.samba3 -parser = optparse.OptionParser("provision <libdir> [<smb.conf>]") +parser = optparse.OptionParser("samba3dump <libdir> [<smb.conf>]") parser.add_option("--format", type="choice", metavar="FORMAT", choices=["full", "summary"]) @@ -96,7 +96,7 @@ def print_samba3_secrets(secrets): def print_samba3_regdb(regdb): print_header("Registry") - from registry import str_regtype + from samba.registry import str_regtype for k in regdb.keys(): print "[%s]" % k diff --git a/source4/scripting/bin/smbstatus b/source4/scripting/bin/smbstatus index 4dfc3365a1..bbd0e84826 100755 --- a/source4/scripting/bin/smbstatus +++ b/source4/scripting/bin/smbstatus @@ -1,96 +1,83 @@ -#!/bin/sh -exec smbscript "$0" ${1+"$@"} -/* - provide information on connected users and open files - Copyright Andrew Tridgell 2005 - Released under the GNU GPL version 3 or later -*/ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# provide information on connected users and open files +# Copyright ǒ Jelmer Vernooij 2008 +# +# Based on the original in EJS: +# Copyright Andrew Tridgell 2005 +# Released under the GNU GPL version 3 or later +# -libinclude("base.js"); -libinclude("management.js"); +import os, sys -var options = new Object(); +sys.path.insert(0, "bin/python") -options = GetOptions(ARGV, - "POPT_AUTOHELP", - "POPT_COMMON_SAMBA", - "POPT_COMMON_VERSION", - "nbt"); -if (options == undefined) { - println("Failed to parse options: " + options.ERROR); - return -1; -} +import optparse +import samba.getopt as options +from samba import irpc, messaging -/* - show open sessions -*/ -function show_sessions() -{ - var sessions = smbsrv_sessions(); - var i; - var sys = sys_init(); - if (sessions == undefined) { - println("No sessions open"); - return; - } - printf("User Client Connected at\n"); - printf("-------------------------------------------------------------------------------\n"); - for (i=0;i<sessions.length;i++) { - var info = sessions[i]; - var fulluser = sprintf("%s/%s", info.account_name, info.domain_name); - printf("%-30s %16s %s\n", - fulluser, info.client_ip, sys.httptime(info.connect_time)); - } - printf("\n"); -} +def show_sessions(conn): + """show open sessions""" -/* - show open tree connects -*/ -function show_tcons() -{ - var tcons = smbsrv_tcons(); - var sys = sys_init(); - if (tcons == undefined) { - println("No tree connects"); - return; - } - printf("Share Client Connected at\n"); - printf("-------------------------------------------------------------------------------\n"); - for (i=0;i<tcons.length;i++) { - var info = tcons[i]; - printf("%-30s %16s %s\n", - info.share_name, info.client_ip, sys.httptime(info.connect_time)); - } -} + sessions = conn.smbsrv_information(irpc.SMBSRV_INFO_SESSIONS).next() + print "User Client Connected at" + print "-------------------------------------------------------------------------------" + 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)) + print "" -/* - show nbtd information -*/ -function show_nbt() -{ - var stats = nbtd_statistics(); - if (stats == undefined) { - println("nbt server not running"); - return; - } - var r; - println("NBT server statistics:"); - for (r in stats) { - print("\t" + r + ":\t" + stats[r] + "\n"); - } - println(""); -} +def show_tcons(open_connection): + """show open tree connects""" + conn = open_connection("smb_server") + tcons = conn.smbsrv_information(irpc.SMBSRV_INFO_TCONS).next() + print "Share Client Connected at" + print "-------------------------------------------------------------------------------" + for tcon in tcons: + print "%-30s %16s %s" % (tcon.share_name, tcon.client_ip, sys.httptime(tcon.connect_time)) -var lp = loadparm_init(); -printf("%s\n\n", lp.get("server string")); +def show_nbt(open_connection): + """show nbtd information""" + conn = open_connection("nbt_server") + stats = conn.nbtd_information(irpc.NBTD_INFO_STATISTICS).next() + print "NBT server statistics:" + fields = [("total_received", "Total received"), + ("total_sent", "Total sent"), + ("query_count", "Query count"), + ("register_count", "Register count"), + ("release_count", "Release count")] + for (field, description) in fields: + print "\t%s:\t%s" % (description, getattr(stats, field)) + print -if (options['nbt'] != undefined) { - show_nbt(); -} else { - show_sessions(); - show_tcons(); -} +parser = optparse.OptionParser("%s [options]" % sys.argv[0]) +sambaopts = options.SambaOptions(parser) +parser.add_option_group(sambaopts) +parser.add_option("--messaging-path", type="string", metavar="PATH", + help="messaging path") +parser.add_option("--nbt", help="show NetBIOS status", action="store_true") -return 0; +opts, args = parser.parse_args() + +lp = sambaopts.get_loadparm() + +print "%s" % lp.get("server string") + +messaging_path = (opts.messaging_path or os.path.join(lp.get("private dir"), "smbd.tmp", "messaging")) + +def open_connection(name): + return messaging.ClientConnection(name, messaging_path=messaging_path) + +if opts.nbt: + show_nbt(open_connection) +else: + try: + conn = open_connection("smb_server") + except RuntimeError, (num, msg): + if msg == 'NT_STATUS_OBJECT_NAME_NOT_FOUND': + print "No active connections" + else: + show_sessions(conn) + show_tcons(conn) diff --git a/source4/scripting/bin/winreg b/source4/scripting/bin/winreg deleted file mode 100755 index 883c6d7ee3..0000000000 --- a/source4/scripting/bin/winreg +++ /dev/null @@ -1,107 +0,0 @@ -#!/bin/sh -exec smbscript "$0" ${1+"$@"} -/* - tool to manipulate a remote registry - Copyright Andrew Tridgell 2005 - Released under the GNU GPL version 3 or later -*/ - -var options = GetOptions(ARGV, - "POPT_AUTOHELP", - "POPT_COMMON_SAMBA", - "POPT_COMMON_CREDENTIALS", - "createkey=s"); -if (options == undefined) { - println("Failed to parse options"); - return -1; -} - -libinclude("base.js"); -libinclude("winreg.js"); - -if (options.ARGV.length < 1) { - println("Usage: winreg.js <BINDING> [path]"); - return -1; -} -var binding = options.ARGV[0]; -reg = winregObj(); - -print("Connecting to " + binding + "\n"); -status = reg.connect(binding); -if (status.is_ok != true) { - print("Failed to connect to " + binding + " - " + status.errstr + "\n"); - return -1; -} - -function list_values(path) { - var list = reg.enum_values(path); - var i; - if (list == undefined) { - return; - } - for (i=0;i<list.length;i++) { - var v = list[i]; - printf("\ttype=%-30s size=%4d '%s'\n", reg.typestring(v.type), v.size, v.name); - if (v.type == reg.REG_SZ || v.type == reg.REG_EXPAND_SZ) { - printf("\t\t'%s'\n", v.value); - } - if (v.type == reg.REG_MULTI_SZ) { - var j; - for (j in v.value) { - printf("\t\t'%s'\n", v.value[j]); - } - } - if (v.type == reg.REG_DWORD || v.type == reg.REG_DWORD_BIG_ENDIAN) { - printf("\t\t0x%08x (%d)\n", v.value, v.value); - } - if (v.type == reg.REG_QWORD) { - printf("\t\t0x%llx (%lld)\n", v.value, v.value); - } - } -} - -function list_path(path) { - var count = 0; - var list = reg.enum_path(path); - if (list == undefined) { - println("Unable to list " + path); - return 0; - } - var i; - list_values(path); - count = count + list.length; - for (i=0;i<list.length;i++) { - var npath; - if (path) { - npath = path + "\\" + list[i]; - } else { - npath = list[i]; - } - println(npath); - count = count + list_path(npath); - } - return count; -} - -var root; - -if (options.ARGV.length > 1) { - root = options.ARGV[1]; -} else { - root = ''; -} - -if (options.createkey) { - var ok = reg.create_key("HKLM\\SOFTWARE", options.createkey); - if (!ok) { - println("Failed to create key"); - } -} else { - printf("Listing registry tree '%s'\n", root); - var count = list_path(root); - if (count == 0) { - println("No entries found"); - return 1; - } -} -return 0; diff --git a/source4/scripting/ejs/config.mk b/source4/scripting/ejs/config.mk index c1a1ca1f0f..34c0a9678e 100644 --- a/source4/scripting/ejs/config.mk +++ b/source4/scripting/ejs/config.mk @@ -1,7 +1,3 @@ -[SUBSYSTEM::EJSRPC] - -EJSRPC_OBJ_FILES = $(ejsscriptsrcdir)/ejsrpc.o - [MODULE::smbcalls_config] OUTPUT_TYPE = MERGED_OBJ SUBSYSTEM = smbcalls @@ -17,43 +13,6 @@ PRIVATE_DEPENDENCIES = LIBLDB SAMDB LIBNDR smbcalls_ldb_OBJ_FILES = $(ejsscriptsrcdir)/smbcalls_ldb.o -[MODULE::smbcalls_reg] -SUBSYSTEM = smbcalls -OUTPUT_TYPE = MERGED_OBJ -INIT_FUNCTION = smb_setup_ejs_reg -PRIVATE_DEPENDENCIES = registry SAMDB LIBNDR - -smbcalls_reg_OBJ_FILES = $(ejsscriptsrcdir)/smbcalls_reg.o - -[MODULE::smbcalls_nbt] -SUBSYSTEM = smbcalls -OUTPUT_TYPE = MERGED_OBJ -INIT_FUNCTION = smb_setup_ejs_nbt - -smbcalls_nbt_OBJ_FILES = $(ejsscriptsrcdir)/smbcalls_nbt.o - -[MODULE::smbcalls_rand] -SUBSYSTEM = smbcalls -OUTPUT_TYPE = MERGED_OBJ -INIT_FUNCTION = smb_setup_ejs_random - -smbcalls_rand_OBJ_FILES = $(ejsscriptsrcdir)/smbcalls_rand.o - -[MODULE::smbcalls_nss] -SUBSYSTEM = smbcalls -OUTPUT_TYPE = MERGED_OBJ -INIT_FUNCTION = smb_setup_ejs_nss -PRIVATE_DEPENDENCIES = NSS_WRAPPER - -smbcalls_nss_OBJ_FILES = $(ejsscriptsrcdir)/smbcalls_nss.o - -[MODULE::smbcalls_data] -SUBSYSTEM = smbcalls -OUTPUT_TYPE = MERGED_OBJ -INIT_FUNCTION = smb_setup_ejs_datablob - -smbcalls_data_OBJ_FILES = $(ejsscriptsrcdir)/smbcalls_data.o - [MODULE::smbcalls_auth] OUTPUT_TYPE = MERGED_OBJ SUBSYSTEM = smbcalls @@ -78,26 +37,19 @@ INIT_FUNCTION = smb_setup_ejs_system smbcalls_sys_OBJ_FILES = $(ejsscriptsrcdir)/smbcalls_sys.o -mkinclude ejsnet/config.mk - [SUBSYSTEM::smbcalls] PRIVATE_DEPENDENCIES = \ EJS LIBSAMBA-UTIL \ - EJSRPC MESSAGING \ + MESSAGING \ LIBSAMBA-NET LIBCLI_SMB LIBPOPT \ CREDENTIALS POPT_CREDENTIALS POPT_SAMBA \ - dcerpc \ NDR_TABLE smbcalls_OBJ_FILES = $(addprefix $(ejsscriptsrcdir)/, \ smbcalls.o \ - smbcalls_cli.o \ - smbcalls_rpc.o \ smbcalls_options.o \ smbcalls_creds.o \ - smbcalls_param.o \ - mprutil.o \ - literal.o) + mprutil.o) $(eval $(call proto_header_template,$(ejsscriptsrcdir)/proto.h,$(smbcalls_OBJ_FILES:.o=.c))) diff --git a/source4/scripting/ejs/ejsnet/config.mk b/source4/scripting/ejs/ejsnet/config.mk deleted file mode 100644 index 710221e37d..0000000000 --- a/source4/scripting/ejs/ejsnet/config.mk +++ /dev/null @@ -1,13 +0,0 @@ -[MODULE::smbcalls_net] -SUBSYSTEM = smbcalls -INIT_FUNCTION = smb_setup_ejs_net -PRIVATE_DEPENDENCIES = LIBSAMBA-NET LIBCLI_SMB CREDENTIALS - -smbcalls_net_OBJ_FILES = $(addprefix $(ejsscriptsrcdir)/ejsnet/, \ - net_ctx.o \ - net_user.o \ - mpr_user.o \ - net_host.o \ - mpr_host.o) - -$(eval $(call proto_header_template,$(ejsscriptsrcdir)/ejsnet/proto.h,$(smbcalls_net_OBJ_FILES:.o=.c))) diff --git a/source4/scripting/ejs/ejsnet/mpr_host.c b/source4/scripting/ejs/ejsnet/mpr_host.c deleted file mode 100644 index 8258ea5256..0000000000 --- a/source4/scripting/ejs/ejsnet/mpr_host.c +++ /dev/null @@ -1,74 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provides interfaces to libnet calls from ejs scripts - - Copyright (C) Rafal Szczesniak 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 <http://www.gnu.org/licenses/>. -*/ - - -#include "includes.h" -#include "lib/appweb/ejs/ejs.h" -#include "libnet/libnet.h" -#include "scripting/ejs/smbcalls.h" -#include "events/events.h" -#include "auth/credentials/credentials.h" - - -/* - Properties: - DomainsList.Domains[0] - DomainsList.Status -*/ -struct MprVar mprDomainsList(TALLOC_CTX *mem_ctx, struct libnet_DomainList *list, NTSTATUS result) -{ - const char *name = "DomainsList"; - NTSTATUS status; - struct MprVar mprDomainList, mprDomains; - struct MprVar mprSid, mprDomainName; - struct MprVar mprDomain; - int i; - - if (list == NULL || mem_ctx == NULL) { - mprDomainList = mprCreateNullVar(); - goto done; - } - - mprDomains = mprArray("Domains"); - for (i = 0; i < list->out.count; i++) { - struct domainlist d = list->out.domains[i]; - - /* get domainlist fields */ - mprSid = mprString(d.sid); - mprDomainName = mprString(d.name); - - mprDomain = mprObject("Domain"); - mprSetVar(&mprDomain, "Name", mprDomainName); - mprSetVar(&mprDomain, "SID", mprSid); - - mprAddArray(&mprDomains, i, mprDomain); - } - - mprDomainList = mprObject(name); - status = mprSetVar(&mprDomainList, "Domains", mprDomains); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprDomainList, "Count", mprCreateIntegerVar(list->out.count)); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprDomainList, "Status", mprNTSTATUS(result)); - -done: - return mprDomainList; -} diff --git a/source4/scripting/ejs/ejsnet/mpr_user.c b/source4/scripting/ejs/ejsnet/mpr_user.c deleted file mode 100644 index 6691a0f955..0000000000 --- a/source4/scripting/ejs/ejsnet/mpr_user.c +++ /dev/null @@ -1,173 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provides interfaces to libnet calls from ejs scripts - - Copyright (C) Rafal Szczesniak 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 <http://www.gnu.org/licenses/>. -*/ - -#include "includes.h" -#include "lib/appweb/ejs/ejs.h" -#include "libnet/libnet.h" -#include "scripting/ejs/smbcalls.h" -#include "events/events.h" -#include "auth/credentials/credentials.h" - - -/* - Properties: - UserInfo.AccountName - UserInfo.FullName - UserInfo.Description - UserInfo.HomeDirectory - UserInfo.HomeDrive - UserInfo.Comment - UserInfo.LogonScript - UserInfo.AcctExpiry - UserInfo.AllowPasswordChange - UserInfo.ForcePasswordChange - */ -struct MprVar mprCreateUserInfo(TALLOC_CTX *mem_ctx, struct libnet_UserInfo *info) -{ - const char *name = "UserInfo"; - NTSTATUS status; - struct MprVar mprUserInfo; - struct MprVar mprAccountName, mprFullName, mprDescription; - struct MprVar mprHomeDir, mprHomeDrive, mprComment; - struct MprVar mprLogonScript; - struct MprVar mprAcctExpiry, mprAllowPassChange, mprForcePassChange; - - if (info == NULL || mem_ctx == NULL) { - mprUserInfo = mprCreateNullVar(); - goto done; - } - - mprUserInfo = mprObject(name); - - mprAccountName = mprString(info->out.account_name); - mprFullName = mprString(info->out.full_name); - mprDescription = mprString(info->out.description); - mprHomeDir = mprString(info->out.home_directory); - mprHomeDrive = mprString(info->out.home_drive); - mprComment = mprString(info->out.comment); - mprLogonScript = mprString(info->out.logon_script); - mprAcctExpiry = mprString(timestring(mem_ctx, info->out.acct_expiry->tv_sec)); - mprAllowPassChange = mprString(timestring(mem_ctx, info->out.allow_password_change->tv_sec)); - mprForcePassChange = mprString(timestring(mem_ctx, info->out.force_password_change->tv_sec)); - - status = mprSetVar(&mprUserInfo, "AccountName", mprAccountName); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprUserInfo, "FullName", mprFullName); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprUserInfo, "Description", mprDescription); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprUserInfo, "HomeDirectory", mprHomeDir); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprUserInfo, "HomeDrive", mprHomeDrive); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprUserInfo, "Comment", mprComment); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprUserInfo, "LogonScript", mprLogonScript); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprUserInfo, "AcctExpiry", mprAcctExpiry); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprUserInfo, "AllowPasswordChange", mprAllowPassChange); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprUserInfo, "ForcePasswordChange", mprForcePassChange); - if (!NT_STATUS_IS_OK(status)) goto done; - -done: - return mprUserInfo; -} - - -/* - Properties: - UserListCtx.Users[] - UserListCtx.ResumeIndex - UserListCtx.Count - UserListCtx.EndOfList - UserListCtx.Status - */ -struct MprVar mprUserListCtx(TALLOC_CTX *mem_ctx, struct libnet_UserList *list, NTSTATUS result) -{ - const char *name = "UserListCtx"; - NTSTATUS status; - bool endOfList; - struct MprVar mprListCtx, mprUserList; - struct MprVar mprUser, mprSid, mprUsername; - int i; - - if (list == NULL || mem_ctx == NULL) { - mprListCtx = mprCreateNullVar(); - goto done; - } - - endOfList = (NT_STATUS_EQUAL(result, NT_STATUS_NO_MORE_ENTRIES) || - NT_STATUS_IS_OK(result)); - - mprUserList = mprArray("Users"); - for (i = 0; i < list->out.count; i++) { - struct userlist u = list->out.users[i]; - - /* get userlist fields */ - mprSid = mprString(u.sid); - mprUsername = mprString(u.username); - - /* create userlist object */ - mprUser = mprObject("User"); - mprSetVar(&mprUser, "Username", mprUsername); - mprSetVar(&mprUser, "SID", mprSid); - - /* add the object to the array being constructed */ - mprAddArray(&mprUserList, i, mprUser); - } - - mprListCtx = mprObject(name); - status = mprSetVar(&mprListCtx, "Users", mprUserList); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprListCtx, "Count", mprCreateIntegerVar(list->out.count)); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprListCtx, "ResumeIndex", mprCreateIntegerVar((int)list->out.resume_index)); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprListCtx, "EndOfList", mprCreateBoolVar(endOfList)); - if (!NT_STATUS_IS_OK(status)) goto done; - status = mprSetVar(&mprListCtx, "Status", mprNTSTATUS(result)); - -done: - return mprListCtx; -} - - -/* - Returns UserListCtx.ResumeIndex out of passed UserListCtx - */ -unsigned int mprListGetResumeIndex(struct MprVar *listCtx) -{ - NTSTATUS status; - unsigned int resume = 0; - struct MprVar *mprResumeIndex; - if (listCtx == NULL) return 0; - - mprResumeIndex = listCtx; - status = mprGetVar(&mprResumeIndex, "ResumeIndex"); - if (!NT_STATUS_IS_OK(status)) goto done; - - resume = (unsigned int) mprVarToInteger(mprResumeIndex); - -done: - return resume; -} diff --git a/source4/scripting/ejs/ejsnet/net_ctx.c b/source4/scripting/ejs/ejsnet/net_ctx.c deleted file mode 100644 index cbe163552e..0000000000 --- a/source4/scripting/ejs/ejsnet/net_ctx.c +++ /dev/null @@ -1,230 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provides interfaces to libnet calls from ejs scripts - - Copyright (C) Rafal Szczesniak 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 <http://www.gnu.org/licenses/>. -*/ - -#include "includes.h" -#include "lib/appweb/ejs/ejs.h" -#include "scripting/ejs/smbcalls.h" -#include "libnet/libnet.h" -#include "events/events.h" -#include "auth/credentials/credentials.h" - - -int ejs_net_userman(MprVarHandle eid, int argc, struct MprVar** argv); -int ejs_net_hostman(MprVarHandle eid, int argc, struct MprVar** argv); - -static int ejs_net_join_domain(MprVarHandle eid, int argc, struct MprVar **argv); -static int ejs_net_samsync_ldb(MprVarHandle eid, int argc, struct MprVar **argv); - -/* - Usage: - net = NetContext(credentials); -*/ - -static int ejs_net_context(MprVarHandle eid, int argc, struct MprVar **argv) -{ - TALLOC_CTX *event_mem_ctx = talloc_new(mprMemCtx()); - struct cli_credentials *creds; - struct libnet_context *ctx; - struct MprVar obj, mprCreds; - struct event_context *ev; - - if (!event_mem_ctx) { - ejsSetErrorMsg(eid, "talloc_new() failed"); - return -1; - } - ev = mprEventCtx(); - - ctx = libnet_context_init(ev, mprLpCtx()); - /* IF we generated a new event context, it will be under here, - * and we need it to last as long as the libnet context, so - * make it a child */ - talloc_steal(ctx, event_mem_ctx); - - if (argc == 0 || (argc == 1 && argv[0]->type == MPR_TYPE_NULL)) { - /* - create the default credentials - */ - creds = cli_credentials_init(ctx); - if (creds == NULL) { - ejsSetErrorMsg(eid, "cli_credential_init() failed"); - talloc_free(ctx); - return -1; - } - cli_credentials_set_conf(creds, mprLpCtx()); - cli_credentials_set_anonymous(creds); - - mprCreds = mprCredentials(creds); - - } else if (argc == 1 && argv[0]->type == MPR_TYPE_OBJECT) { - /* - get credential values from credentials object - */ - mprCreds = *(argv[0]); - creds = (struct cli_credentials *)mprGetPtr(&mprCreds, "creds"); - if (creds == NULL) { - ejsSetErrorMsg(eid, "invalid credentials parameter"); - talloc_free(ctx); - return -1; - } - - } else { - ejsSetErrorMsg(eid, "NetContext invalid arguments, this function requires an object."); - talloc_free(ctx); - return -1; - } - - /* setup libnet_context credentials */ - ctx->cred = creds; - - /* create the NetContext object */ - obj = mprObject("NetContext"); - - /* add internal libnet_context pointer to the NetContext object */ - mprSetPtrChild(&obj, "ctx", ctx); - - /* add properties publicly available from js code */ - mprCreateProperty(&obj, "credentials", &mprCreds); - - /* add methods to the object */ - mprSetCFunction(&obj, "UserMgr", ejs_net_userman); - mprSetCFunction(&obj, "HostMgr", ejs_net_hostman); - mprSetCFunction(&obj, "JoinDomain", ejs_net_join_domain); - mprSetCFunction(&obj, "SamSyncLdb", ejs_net_samsync_ldb); - - /* return the object */ - mpr_Return(eid, obj); - - return 0; -} - - -static int ejs_net_join_domain(MprVarHandle eid, int argc, struct MprVar **argv) -{ - TALLOC_CTX *mem_ctx; - struct libnet_context *ctx; - struct libnet_Join *join; - NTSTATUS status; - ctx = (struct libnet_context *)mprGetThisPtr(eid, "ctx"); - mem_ctx = talloc_new(mprMemCtx()); - - join = talloc(mem_ctx, struct libnet_Join); - if (!join) { - talloc_free(mem_ctx); - return -1; - } - - /* prepare parameters for the join */ - join->in.netbios_name = NULL; - join->in.join_type = SEC_CHAN_WKSTA; - join->in.domain_name = cli_credentials_get_domain(ctx->cred); - join->in.level = LIBNET_JOIN_AUTOMATIC; - join->out.error_string = NULL; - - if (argc == 1 && argv[0]->type == MPR_TYPE_OBJECT) { - MprVar *netbios_name = mprGetProperty(argv[0], "netbios_name", NULL); - MprVar *domain_name = mprGetProperty(argv[0], "domain_name", NULL); - MprVar *join_type = mprGetProperty(argv[0], "join_type", NULL); - if (netbios_name) { - join->in.netbios_name = mprToString(netbios_name); - } - if (domain_name) { - join->in.domain_name = mprToString(domain_name); - } - if (join_type) { - join->in.join_type = mprToInt(join_type); - } - } - - if (!join->in.domain_name) { - ejsSetErrorMsg(eid, "a domain must be specified for to join"); - talloc_free(mem_ctx); - return -1; - } - - /* do the domain join */ - status = libnet_Join(ctx, join, join); - - if (!NT_STATUS_IS_OK(status)) { - MprVar error_string = mprString(join->out.error_string); - - mprSetPropertyValue(argv[0], "error_string", error_string); - mpr_Return(eid, mprCreateBoolVar(false)); - } else { - mpr_Return(eid, mprCreateBoolVar(true)); - } - talloc_free(mem_ctx); - return 0; -} - - -static int ejs_net_samsync_ldb(MprVarHandle eid, int argc, struct MprVar **argv) -{ - TALLOC_CTX *mem_ctx; - struct libnet_context *ctx; - struct libnet_samsync_ldb *samsync; - NTSTATUS status; - ctx = (struct libnet_context *)mprGetThisPtr(eid, "ctx"); - mem_ctx = talloc_new(mprMemCtx()); - - samsync = talloc(mem_ctx, struct libnet_samsync_ldb); - if (!samsync) { - talloc_free(mem_ctx); - return -1; - } - - /* prepare parameters for the samsync */ - samsync->in.machine_account = NULL; - samsync->in.session_info = NULL; - samsync->in.binding_string = NULL; - samsync->out.error_string = NULL; - - if (argc == 1 && argv[0]->type == MPR_TYPE_OBJECT) { - MprVar *credentials = mprGetProperty(argv[0], "machine_account", NULL); - MprVar *session_info = mprGetProperty(argv[0], "session_info", NULL); - if (credentials) { - samsync->in.machine_account = talloc_get_type(mprGetPtr(credentials, "creds"), struct cli_credentials); - } - if (session_info) { - samsync->in.session_info = talloc_get_type(mprGetPtr(session_info, "session_info"), struct auth_session_info); - } - } - - /* do the domain samsync */ - status = libnet_samsync_ldb(ctx, samsync, samsync); - - if (!NT_STATUS_IS_OK(status)) { - MprVar error_string = mprString(samsync->out.error_string); - - mprSetPropertyValue(argv[0], "error_string", error_string); - mpr_Return(eid, mprCreateBoolVar(false)); - } else { - mpr_Return(eid, mprCreateBoolVar(true)); - } - talloc_free(mem_ctx); - return 0; -} - - -NTSTATUS smb_setup_ejs_net(void) -{ - ejsDefineCFunction(-1, "NetContext", ejs_net_context, NULL, MPR_VAR_SCRIPT_HANDLE); - return NT_STATUS_OK; -} diff --git a/source4/scripting/ejs/ejsnet/net_host.c b/source4/scripting/ejs/ejsnet/net_host.c deleted file mode 100644 index 478da19db3..0000000000 --- a/source4/scripting/ejs/ejsnet/net_host.c +++ /dev/null @@ -1,124 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provides interfaces to libnet calls from ejs scripts - - Copyright (C) Rafal Szczesniak 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 <http://www.gnu.org/licenses/>. -*/ - - -#include "includes.h" -#include "lib/appweb/ejs/ejs.h" -#include "libnet/libnet.h" -#include "scripting/ejs/ejsnet/proto.h" -#include "scripting/ejs/smbcalls.h" -#include "events/events.h" -#include "auth/credentials/credentials.h" - - -static int ejs_net_domainlist(MprVarHandle eid, int argc, char **argv); - - -/* - Usage: - hostCtx = net.HostMgr(hostname = <default from credentials>) -*/ -int ejs_net_hostman(MprVarHandle eid, int argc, struct MprVar** argv) -{ - struct libnet_context *ctx; - const char *hostname; - struct MprVar obj; - - /* libnet context */ - ctx = mprGetThisPtr(eid, "ctx"); - if (ctx == NULL) { - ejsSetErrorMsg(eid, "ctx property returns null pointer"); - return 0; - } - - /* fetch the arguments: host name */ - if (argc == 0) { - /* default host (machine) name is supplied in credentials */ - hostname = cli_credentials_get_workstation(ctx->cred); - - } else if (argc == 1 && mprVarIsString(argv[0]->type)) { - /* host name has been specified */ - hostname = mprToString(argv[0]); - - } else { - ejsSetErrorMsg(eid, "too many arguments"); - return 0; - } - - /* create the NetHostCtx object */ - obj = mprObject("NetHostCtx"); - - /* create a copy of the string for the object */ - hostname = talloc_strdup(ctx, hostname); - - /* add internal libnet_context pointer to the NetHostCtx object */ - mprSetPtrChild(&obj, "ctx", ctx); - mprSetPtrChild(&obj, "hostname", hostname); - - /* add methods to the object */ - mprSetStringCFunction(&obj, "DomainList", ejs_net_domainlist); - - /* set the object returned by this function */ - mpr_Return(eid, obj); - - return 0; -} - - -static int ejs_net_domainlist(MprVarHandle eid, int argc, char **argv) -{ - NTSTATUS status; - TALLOC_CTX *mem_ctx; - const char* hostname; - struct libnet_context *ctx; - struct libnet_DomainList req; - struct MprVar mprDomains; - - mem_ctx = talloc_new(mprMemCtx()); - if (mem_ctx == NULL) { - ejsSetErrorMsg(eid, "could not create memory context - out of memory"); - goto done; - } - - /* libnet context */ - ctx = mprGetThisPtr(eid, "ctx"); - if (ctx == NULL) { - ejsSetErrorMsg(eid, "ctx property returns null pointer"); - goto done; - } - - hostname = mprGetThisPtr(eid, "hostname"); - if (hostname == NULL) { - ejsSetErrorMsg(eid, "hostname property returns null pointer"); - goto done; - } - - /* call the libnet function */ - req.in.hostname = hostname; - - status = libnet_DomainList(ctx, mem_ctx, &req); - mprDomains = mprDomainsList(mem_ctx, &req, status); - -done: - talloc_free(mem_ctx); - mpr_Return(eid, mprDomains); - return 0; -} diff --git a/source4/scripting/ejs/ejsnet/net_user.c b/source4/scripting/ejs/ejsnet/net_user.c deleted file mode 100644 index 0c32035c6c..0000000000 --- a/source4/scripting/ejs/ejsnet/net_user.c +++ /dev/null @@ -1,359 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provides interfaces to libnet calls from ejs scripts - - Copyright (C) Rafal Szczesniak 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 <http://www.gnu.org/licenses/>. -*/ - -#include "includes.h" -#include "lib/appweb/ejs/ejs.h" -#include "libnet/libnet.h" -#include "scripting/ejs/ejsnet/proto.h" -#include "scripting/ejs/smbcalls.h" -#include "events/events.h" -#include "auth/credentials/credentials.h" - - -static int ejs_net_createuser(MprVarHandle eid, int argc, char **argv); -static int ejs_net_deleteuser(MprVarHandle eid, int argc, char **argv); -static int ejs_net_userinfo(MprVarHandle eid, int argc, char **argv); -static int ejs_net_userlist(MprVarHandle eid, int argc, struct MprVar **argv); - - -/* - Usage: - usrCtx = net.UserMgr(domain = <default from credentials>); -*/ -int ejs_net_userman(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct libnet_context *ctx; - const char *userman_domain = NULL; - struct MprVar obj; - - /* libnet context */ - ctx = (struct libnet_context *)mprGetThisPtr(eid, "ctx"); - if (ctx == NULL) { - ejsSetErrorMsg(eid, "ctx property returns null pointer"); - return 0; - } - - /* fetch the arguments: domain name */ - if (argc == 0) { - /* default domain name is supplied in credentials */ - userman_domain = cli_credentials_get_domain(ctx->cred); - - } else if (argc == 1 && mprVarIsString(argv[0]->type)) { - /* domain name can also be specified explicitly - (e.g. to connect BUILTIN domain) */ - userman_domain = mprToString(argv[0]); - - } else { - ejsSetErrorMsg(eid, "too many arguments"); - return 0; - } - - /* any domain name must be specified anyway */ - if (userman_domain == NULL) { - ejsSetErrorMsg(eid, "a domain must be specified for user management"); - return 0; - } - - /* create 'net user' subcontext */ - obj = mprObject("NetUsrCtx"); - - /* we need to make a copy of the string for this object */ - userman_domain = talloc_strdup(ctx, userman_domain); - - /* add properties */ - mprSetPtrChild(&obj, "ctx", ctx); - mprSetPtrChild(&obj, "domain", userman_domain); - - /* add methods */ - mprSetStringCFunction(&obj, "Create", ejs_net_createuser); - mprSetStringCFunction(&obj, "Delete", ejs_net_deleteuser); - mprSetStringCFunction(&obj, "Info", ejs_net_userinfo); - mprSetCFunction(&obj, "List", ejs_net_userlist); - - /* set the object returned by this function */ - mpr_Return(eid, obj); - - return 0; -} - - -/* - Usage: - NTSTATUS = NetUsrCtx.Create(Username) -*/ -static int ejs_net_createuser(MprVarHandle eid, int argc, char **argv) -{ - NTSTATUS status = NT_STATUS_UNSUCCESSFUL; - TALLOC_CTX *mem_ctx; - struct libnet_context *ctx; - const char *userman_domain = NULL; - const char *username = NULL; - struct libnet_CreateUser req; - - mem_ctx = talloc_new(mprMemCtx()); - if (mem_ctx == NULL) { - ejsSetErrorMsg(eid, "could not create memory context - out of memory"); - goto done; - } - - /* fetch the arguments: username */ - if (argc == 0) { - ejsSetErrorMsg(eid, "too little arguments"); - goto done; - - } else if (argc == 1) { - username = argv[0]; - - } else { - ejsSetErrorMsg(eid, "too many arguments"); - goto done; - } - - /* libnet context */ - ctx = (struct libnet_context *)mprGetThisPtr(eid, "ctx"); - if (ctx == NULL) { - ejsSetErrorMsg(eid, "ctx property returns null pointer"); - goto done; - } - - /* domain where the account is to be created */ - userman_domain = (const char *)mprGetThisPtr(eid, "domain"); - if (userman_domain == NULL) { - ejsSetErrorMsg(eid, "domain property returns null pointer"); - goto done; - } - - /* call the libnet function */ - req.in.domain_name = userman_domain; - req.in.user_name = argv[0]; - - status = libnet_CreateUser(ctx, mem_ctx, &req); - if (!NT_STATUS_IS_OK(status)) { - ejsSetErrorMsg(eid, "%s", req.out.error_string); - } - -done: - talloc_free(mem_ctx); - mpr_Return(eid, mprNTSTATUS(status)); - return 0; -} - - -/* - Usage: - NTSTATUS = NetUsrCtx.Delete(Username) -*/ -static int ejs_net_deleteuser(MprVarHandle eid, int argc, char **argv) -{ - NTSTATUS status = NT_STATUS_UNSUCCESSFUL; - TALLOC_CTX *mem_ctx; - struct libnet_context *ctx; - const char *userman_domain = NULL; - const char *username = NULL; - struct libnet_DeleteUser req; - - mem_ctx = talloc_new(mprMemCtx()); - if (mem_ctx == NULL) { - ejsSetErrorMsg(eid, "could not create memory context - out of memory"); - goto done; - } - - /* fetch the arguments: username */ - if (argc == 0) { - ejsSetErrorMsg(eid, "too little arguments"); - goto done; - - } else if (argc == 1) { - username = argv[0]; - - } else { - ejsSetErrorMsg(eid, "too many arguments"); - goto done; - } - - /* libnet context */ - ctx = mprGetThisPtr(eid, "ctx"); - if (ctx == NULL) { - ejsSetErrorMsg(eid, "ctx property returns null pointer"); - goto done; - } - - /* domain where the account is to be deleted */ - userman_domain = mprGetThisPtr(eid, "domain"); - if (!userman_domain) { - ejsSetErrorMsg(eid, "domain property returns null pointer"); - goto done; - } - - /* call the libnet function */ - req.in.domain_name = userman_domain; - req.in.user_name = username; - - status = libnet_DeleteUser(ctx, mem_ctx, &req); - if (!NT_STATUS_IS_OK(status)) { - ejsSetErrorMsg(eid, "%s", req.out.error_string); - } - -done: - talloc_free(mem_ctx); - mpr_Return(eid, mprNTSTATUS(status)); - return 0; -} - - -/* - Usage: - UserInfo = NetUsrCtx.Info(Username) -*/ -static int ejs_net_userinfo(MprVarHandle eid, int argc, char **argv) -{ - NTSTATUS status = NT_STATUS_UNSUCCESSFUL; - TALLOC_CTX *mem_ctx; - struct libnet_context *ctx; - const char *userman_domain = NULL; - const char *username = NULL; - struct libnet_UserInfo req; - struct MprVar mprUserInfo; - - mem_ctx = talloc_new(mprMemCtx()); - if (mem_ctx == NULL) { - ejsSetErrorMsg(eid, "could not create memory context - out of memory"); - goto done; - } - - /* fetch the arguments: username */ - if (argc == 0) { - ejsSetErrorMsg(eid, "too little arguments"); - goto done; - - } else if (argc == 1) { - username = argv[0]; - - } else { - ejsSetErrorMsg(eid, "too many arguments"); - goto done; - } - - /* libnet context */ - ctx = (struct libnet_context *)mprGetThisPtr(eid, "ctx"); - if (ctx == NULL) { - ejsSetErrorMsg(eid, "ctx property returns null pointer"); - goto done; - } - - /* domain where the user account is to be queried */ - userman_domain = mprGetThisPtr(eid, "domain"); - if (userman_domain == NULL) { - ejsSetErrorMsg(eid, "domain property returns null pointer"); - return -1; - } - - /* call the libnet function */ - req.in.domain_name = userman_domain; - req.in.data.user_name = username; - req.in.level = USER_INFO_BY_NAME; - - status = libnet_UserInfo(ctx, mem_ctx, &req); - if (!NT_STATUS_IS_OK(status)) { - ejsSetErrorMsg(eid, "%s", req.out.error_string); - - /* create null object to return */ - mprUserInfo = mprCreateNullVar(); - goto done; - } - - /* create UserInfo object */ - mprUserInfo = mprCreateUserInfo(ctx, &req); - -done: - talloc_free(mem_ctx); - mpr_Return(eid, mprUserInfo); - return 0; -} - - -/* - Usage: - UserListCtx = NetUsrCtx.List(UserListCtx) -*/ -static int ejs_net_userlist(MprVarHandle eid, int argc, struct MprVar **argv) -{ - TALLOC_CTX *mem_ctx; - NTSTATUS status; - struct libnet_context *ctx; - const char *userlist_domain; - int page_size = 512; /* TODO: this should be specified in a nicer way */ - struct libnet_UserList req; - struct MprVar mprListCtx, *mprInListCtx; - - mem_ctx = talloc_new(mprMemCtx()); - if (mem_ctx == NULL) { - ejsSetErrorMsg(eid, "could not create memory context - out of memory"); - goto done; - } - - /* fetch the arguments */ - if (argc == 0) { - ejsSetErrorMsg(eid, "too little arguments"); - goto done; - - } else if (argc == 1) { - if (mprVarIsObject(argv[0]->type)) { - /* this is a continuation call */ - mprInListCtx = argv[0]; - req.in.resume_index = mprListGetResumeIndex(mprInListCtx); - - } else { - /* this is a first call */ - req.in.resume_index = 0; - } - - } else { - ejsSetErrorMsg(eid, "too many arguments"); - goto done; - } - - /* libnet context */ - ctx = (struct libnet_context *)mprGetThisPtr(eid, "ctx"); - if (ctx == NULL) { - ejsSetErrorMsg(eid, "ctx property returns null pointer"); - goto done; - } - - /* domain where user accounts are to be enumerated */ - userlist_domain = mprGetThisPtr(eid, "domain"); - if (userlist_domain == NULL) { - ejsSetErrorMsg(eid, "domain property returns null pointer"); - goto done; - } - - /* call the libnet function */ - req.in.domain_name = userlist_domain; - req.in.page_size = page_size; - - status = libnet_UserList(ctx, mem_ctx, &req); - mprListCtx = mprUserListCtx(mem_ctx, &req, status); - -done: - talloc_free(mem_ctx); - mpr_Return(eid, mprListCtx); - return 0; -} diff --git a/source4/scripting/ejs/ejsrpc.c b/source4/scripting/ejs/ejsrpc.c deleted file mode 100644 index c7c02dbd64..0000000000 --- a/source4/scripting/ejs/ejsrpc.c +++ /dev/null @@ -1,424 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide interfaces to rpc 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 <http://www.gnu.org/licenses/>. -*/ - -#include "includes.h" -#include "lib/appweb/ejs/ejs.h" -#include "scripting/ejs/smbcalls.h" -#include "librpc/gen_ndr/lsa.h" -#include "librpc/gen_ndr/winreg.h" -#include "scripting/ejs/ejsrpc.h" -#include "libcli/security/security.h" - -/* - set the switch var to be used by the next union switch -*/ -void ejs_set_switch(struct ejs_rpc *ejs, uint32_t switch_var) -{ - ejs->switch_var = switch_var; -} - -/* - panic in the ejs wrapper code - */ -NTSTATUS ejs_panic(struct ejs_rpc *ejs, const char *why) -{ - ejsSetErrorMsg(ejs->eid, "rpc_call '%s' failed - %s", ejs->callname, why); - return NT_STATUS_INTERNAL_ERROR; -} - -/* - start the ejs pull process for a structure -*/ -NTSTATUS ejs_pull_struct_start(struct ejs_rpc *ejs, struct MprVar **v, const char *name) -{ - return mprGetVar(v, name); -} - - -/* - start the ejs push process for a structure -*/ -NTSTATUS ejs_push_struct_start(struct ejs_rpc *ejs, struct MprVar **v, const char *name) -{ - EJS_CHECK(mprSetVar(*v, name, mprObject(name))); - return mprGetVar(v, name); -} - -/* - pull a uint8 from a mpr variable to a C element -*/ -NTSTATUS ejs_pull_uint8(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, uint8_t *r) -{ - EJS_CHECK(mprGetVar(&v, name)); - *r = mprVarToInteger(v); - return NT_STATUS_OK; - -} - -NTSTATUS ejs_push_uint8(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const uint8_t *r) -{ - return mprSetVar(v, name, mprCreateIntegerVar(*r)); -} - -/* - pull a uint16 from a mpr variable to a C element -*/ -NTSTATUS ejs_pull_uint16(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, uint16_t *r) -{ - EJS_CHECK(mprGetVar(&v, name)); - *r = mprVarToInteger(v); - return NT_STATUS_OK; - -} - -NTSTATUS ejs_push_uint16(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const uint16_t *r) -{ - return mprSetVar(v, name, mprCreateIntegerVar(*r)); -} - -/* - pull a uint32 from a mpr variable to a C element -*/ -NTSTATUS ejs_pull_uint32(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, uint32_t *r) -{ - EJS_CHECK(mprGetVar(&v, name)); - *r = mprVarToInteger(v); - return NT_STATUS_OK; -} - -NTSTATUS ejs_push_uint32(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const uint32_t *r) -{ - return mprSetVar(v, name, mprCreateIntegerVar(*r)); -} - -/* - pull a int32 from a mpr variable to a C element -*/ -NTSTATUS ejs_pull_int32(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, int32_t *r) -{ - EJS_CHECK(mprGetVar(&v, name)); - *r = mprVarToInteger(v); - return NT_STATUS_OK; -} - -NTSTATUS ejs_push_int32(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const int32_t *r) -{ - return mprSetVar(v, name, mprCreateIntegerVar(*r)); -} - -/* - pull a uint32 from a mpr variable to a C element -*/ -NTSTATUS ejs_pull_time_t(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, time_t *r) -{ - EJS_CHECK(mprGetVar(&v, name)); - *r = mprVarToInteger(v); - return NT_STATUS_OK; -} - -NTSTATUS ejs_push_time_t(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const time_t *r) -{ - return mprSetVar(v, name, mprCreateIntegerVar(*r)); -} - -NTSTATUS ejs_pull_hyper(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, uint64_t *r) -{ - EJS_CHECK(mprGetVar(&v, name)); - *r = mprVarToNumber(v); - return NT_STATUS_OK; -} - -NTSTATUS ejs_push_hyper(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const uint64_t *r) -{ - return mprSetVar(v, name, mprCreateNumberVar(*r)); -} - -NTSTATUS ejs_pull_dlong(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, int64_t *r) -{ - return ejs_pull_hyper(ejs, v, name, (uint64_t *)r); -} - -NTSTATUS ejs_push_dlong(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const int64_t *r) -{ - return ejs_push_hyper(ejs, v, name, (const uint64_t *)r); -} - -NTSTATUS ejs_pull_udlong(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, uint64_t *r) -{ - return ejs_pull_hyper(ejs, v, name, r); -} - -NTSTATUS ejs_push_udlong(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const uint64_t *r) -{ - return ejs_push_hyper(ejs, v, name, r); -} - -NTSTATUS ejs_pull_NTTIME(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, uint64_t *r) -{ - return ejs_pull_hyper(ejs, v, name, r); -} - -NTSTATUS ejs_push_NTTIME(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const uint64_t *r) -{ - return ejs_push_hyper(ejs, v, name, r); -} - -NTSTATUS ejs_push_WERROR(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const WERROR *r) -{ - return ejs_push_string(ejs, v, name, win_errstr(*r)); -} - -NTSTATUS ejs_push_NTSTATUS(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const NTSTATUS *r) -{ - return ejs_push_string(ejs, v, name, nt_errstr(*r)); -} - - -/* - pull a enum from a mpr variable to a C element - a enum is just treating as an unsigned integer at this level -*/ -NTSTATUS ejs_pull_enum(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, unsigned *r) -{ - EJS_CHECK(mprGetVar(&v, name)); - *r = mprVarToInteger(v); - return NT_STATUS_OK; - -} - -NTSTATUS ejs_push_enum(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const unsigned *r) -{ - return mprSetVar(v, name, mprCreateIntegerVar(*r)); -} - - -/* - pull a string -*/ -NTSTATUS ejs_pull_string(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const char **s) -{ - EJS_CHECK(mprGetVar(&v, name)); - *s = mprToString(v); - return NT_STATUS_OK; -} - -/* - push a string -*/ -NTSTATUS ejs_push_string(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const char *s) -{ - return mprSetVar(v, name, mprString(s)); -} - - -/* - pull a ipv4address (internally a string) -*/ -NTSTATUS ejs_pull_ipv4address(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const char **s) -{ - return ejs_pull_string(ejs, v, name, s); -} - -/* - push a ipv4address (internally a string) -*/ -NTSTATUS ejs_push_ipv4address(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const char *s) -{ - return ejs_push_string(ejs, v, name, s); -} - - -NTSTATUS ejs_pull_dom_sid(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, struct dom_sid *r) -{ - struct dom_sid *sid; - EJS_CHECK(mprGetVar(&v, name)); - sid = dom_sid_parse_talloc(ejs, mprToString(v)); - NT_STATUS_HAVE_NO_MEMORY(sid); - *r = *sid; - return NT_STATUS_OK; -} - -NTSTATUS ejs_push_dom_sid(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const struct dom_sid *r) -{ - char *sidstr = dom_sid_string(ejs, r); - NT_STATUS_HAVE_NO_MEMORY(sidstr); - return mprSetVar(v, name, mprString(sidstr)); -} - -NTSTATUS ejs_pull_GUID(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, struct GUID *r) -{ - EJS_CHECK(mprGetVar(&v, name)); - return GUID_from_string(mprToString(v), r); -} - -NTSTATUS ejs_push_GUID(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const struct GUID *r) -{ - char *guid = GUID_string(ejs, r); - NT_STATUS_HAVE_NO_MEMORY(guid); - return mprSetVar(v, name, mprString(guid)); -} - -NTSTATUS ejs_push_null(struct ejs_rpc *ejs, struct MprVar *v, const char *name) -{ - return mprSetVar(v, name, mprCreatePtrVar(NULL)); -} - -bool ejs_pull_null(struct ejs_rpc *ejs, struct MprVar *v, const char *name) -{ - NTSTATUS status = mprGetVar(&v, name); - if (!NT_STATUS_IS_OK(status)) { - return false; - } - if (v->type == MPR_TYPE_PTR && v->ptr == NULL) { - return true; - } - return false; -} - -/* - pull a lsa_String -*/ -NTSTATUS ejs_pull_lsa_String(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, struct lsa_String *r) -{ - return ejs_pull_string(ejs, v, name, &r->string); -} - -/* - push a lsa_String -*/ -NTSTATUS ejs_push_lsa_String(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const struct lsa_String *r) -{ - return ejs_push_string(ejs, v, name, r->string); -} - -/* - pull a winreg_String -*/ -NTSTATUS ejs_pull_winreg_String(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, struct winreg_String *r) -{ - return ejs_pull_string(ejs, v, name, &r->name); -} - -/* - push a winreg_String -*/ -NTSTATUS ejs_push_winreg_String(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const struct winreg_String *r) -{ - return ejs_push_string(ejs, v, name, r->name); -} - -NTSTATUS ejs_pull_DATA_BLOB(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, DATA_BLOB *r) -{ - return NT_STATUS_NOT_IMPLEMENTED; -} - -NTSTATUS ejs_push_DATA_BLOB(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, - const DATA_BLOB *r) -{ - return NT_STATUS_NOT_IMPLEMENTED; -} - -NTSTATUS ejs_pull_bool(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, bool *r) -{ - EJS_CHECK(mprGetVar(&v, name)); - *r = mprVarToBool(v); - return NT_STATUS_OK; -} - -NTSTATUS ejs_push_bool(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const bool *r) -{ - return mprSetVar(v, name, mprCreateBoolVar(*r)); -} - - -/* - pull a uint8 array from a mpr variable to a C element - treating as a data blob -*/ -NTSTATUS ejs_pull_array_uint8(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, - uint8_t *r, uint32_t length) -{ - NTSTATUS status; - DATA_BLOB *blob; - - status = mprGetVar(&v, name); - NT_STATUS_NOT_OK_RETURN(status); - - blob = mprToDataBlob(v); - if (blob == NULL) { - return NT_STATUS_OBJECT_NAME_INVALID; - } - if (blob->length != length) { - return NT_STATUS_INFO_LENGTH_MISMATCH; - } - memcpy(r, blob->data, length); - return NT_STATUS_OK; - -} - -NTSTATUS ejs_push_array_uint8(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, - const uint8_t *r, uint32_t length) -{ - DATA_BLOB blob; - blob.data = (uint8_t *)discard_const(r); - blob.length = length; - mprSetVar(v, name, mprDataBlob(blob)); - return NT_STATUS_OK; -} diff --git a/source4/scripting/ejs/ejsrpc.h b/source4/scripting/ejs/ejsrpc.h deleted file mode 100644 index cc22a26700..0000000000 --- a/source4/scripting/ejs/ejsrpc.h +++ /dev/null @@ -1,172 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - ejs <-> rpc interface definitions - - 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 <http://www.gnu.org/licenses/>. -*/ - -#include "librpc/gen_ndr/security.h" -#include "librpc/rpc/dcerpc.h" - -struct ejs_rpc { - int eid; - const char *callname; - /* as ejs does only one pass, we can use a single var for switch - handling */ - uint32_t switch_var; -}; - -typedef NTSTATUS (*ejs_pull_t)(struct ejs_rpc *, struct MprVar *, const char *, void *); -typedef NTSTATUS (*ejs_push_t)(struct ejs_rpc *, struct MprVar *, const char *, const void *); -typedef NTSTATUS (*ejs_pull_function_t)(struct ejs_rpc *, struct MprVar *, void *); -typedef NTSTATUS (*ejs_push_function_t)(struct ejs_rpc *, struct MprVar *, const void *); - -NTSTATUS ejs_panic(struct ejs_rpc *ejs, const char *why); -void ejs_set_switch(struct ejs_rpc *ejs, uint32_t switch_var); - -NTSTATUS smbcalls_register_ejs(const char *name, MprCFunction fn); - - -int ejs_rpc_call(int eid, int argc, struct MprVar **argv, - const struct ndr_interface_table *iface, int callnum, - ejs_pull_function_t ejs_pull, ejs_push_function_t ejs_push); - -NTSTATUS ejs_pull_struct_start(struct ejs_rpc *ejs, struct MprVar **v, const char *name); -NTSTATUS ejs_push_struct_start(struct ejs_rpc *ejs, struct MprVar **v, const char *name); - -NTSTATUS ejs_pull_uint8(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, uint8_t *r); -NTSTATUS ejs_push_uint8(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const uint8_t *r); -NTSTATUS ejs_pull_uint16(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, uint16_t *r); -NTSTATUS ejs_push_uint16(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const uint16_t *r); -NTSTATUS ejs_pull_uint32(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, uint32_t *r); -NTSTATUS ejs_push_int32(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const int32_t *r); -NTSTATUS ejs_pull_int32(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, int32_t *r); -NTSTATUS ejs_push_uint32(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const uint32_t *r); -NTSTATUS ejs_pull_hyper(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, uint64_t *r); -NTSTATUS ejs_push_hyper(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const uint64_t *r); -NTSTATUS ejs_pull_dlong(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, int64_t *r); -NTSTATUS ejs_push_dlong(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const int64_t *r); -NTSTATUS ejs_pull_udlong(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, uint64_t *r); -NTSTATUS ejs_push_udlong(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const uint64_t *r); -NTSTATUS ejs_pull_NTTIME(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, uint64_t *r); -NTSTATUS ejs_push_NTTIME(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const uint64_t *r); -NTSTATUS ejs_pull_time_t(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, time_t *r); -NTSTATUS ejs_push_time_t(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const time_t *r); -NTSTATUS ejs_pull_enum(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, unsigned *r); -NTSTATUS ejs_push_enum(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const unsigned *r); -NTSTATUS ejs_pull_string(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const char **s); -NTSTATUS ejs_push_string(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const char *s); -NTSTATUS ejs_pull_ipv4address(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const char **s); -NTSTATUS ejs_push_ipv4address(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const char *s); -void ejs_set_constant_int(int eid, const char *name, int value); -void ejs_set_constant_string(int eid, const char *name, const char *value); - -NTSTATUS ejs_pull_dom_sid(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, struct dom_sid *r); -NTSTATUS ejs_push_dom_sid(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const struct dom_sid *r); -NTSTATUS ejs_push_null(struct ejs_rpc *ejs, struct MprVar *v, const char *name); -bool ejs_pull_null(struct ejs_rpc *ejs, struct MprVar *v, const char *name); -NTSTATUS ejs_push_WERROR(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const WERROR *r); -NTSTATUS ejs_push_NTSTATUS(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const NTSTATUS *r); -NTSTATUS ejs_pull_DATA_BLOB(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, DATA_BLOB *r); -NTSTATUS ejs_push_DATA_BLOB(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const DATA_BLOB *r); -NTSTATUS ejs_pull_bool(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, bool *r); -NTSTATUS ejs_push_bool(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const bool *r); - -NTSTATUS ejs_pull_array_uint8(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, - uint8_t *r, uint32_t length); -NTSTATUS ejs_push_array_uint8(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, - const uint8_t *r, uint32_t length); - -NTSTATUS ejs_pull_GUID(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, struct GUID *r); -NTSTATUS ejs_push_GUID(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const struct GUID *r); - -struct lsa_String; -NTSTATUS ejs_pull_lsa_String(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, struct lsa_String *r); -NTSTATUS ejs_push_lsa_String(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const struct lsa_String *r); - -struct winreg_String; -NTSTATUS ejs_pull_winreg_String(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, struct winreg_String *r); -NTSTATUS ejs_push_winreg_String(struct ejs_rpc *ejs, - struct MprVar *v, const char *name, const struct winreg_String *r); - -#define EJS_ALLOC(ejs, s) do { \ - (s) = talloc_ptrtype(ejs, (s)); \ - if (!(s)) return ejs_panic(ejs, "out of memory"); \ -} while (0) - -#define EJS_ALLOC_N(ejs, s, n) do { \ - (s) = talloc_array_ptrtype(ejs, (s), n); \ - if (!(s)) return ejs_panic(ejs, "out of memory"); \ -} while (0) - -#define EJS_CHECK(cmd) do { \ - NTSTATUS _status; \ - _status = cmd; \ - if (!NT_STATUS_IS_OK(_status)) { \ - return _status; \ - } \ -} while (0) - -/* some types are equivalent for ejs */ -#define ejs_pull_dom_sid2 ejs_pull_dom_sid -#define ejs_push_dom_sid2 ejs_push_dom_sid -#define ejs_pull_dom_sid28 ejs_pull_dom_sid -#define ejs_push_dom_sid28 ejs_push_dom_sid -#define ejs_pull_NTTIME_hyper ejs_pull_NTTIME -#define ejs_push_NTTIME_hyper ejs_push_NTTIME -#define ejs_pull_NTTIME_1sec ejs_pull_NTTIME -#define ejs_push_NTTIME_1sec ejs_push_NTTIME - diff --git a/source4/scripting/ejs/literal.c b/source4/scripting/ejs/literal.c deleted file mode 100644 index 8307c211d3..0000000000 --- a/source4/scripting/ejs/literal.c +++ /dev/null @@ -1,797 +0,0 @@ -/* - * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd. - * Michael Clark <michael@metaparadigm.com> - * Copyright (c) 2006 Derrell Lipman - * - * This library is free software; you can redistribute it and/or modify - * it under the terms of the MIT license. See COPYING for details. - * - * Derrell Lipman: - * This version is modified from the original. It has been modified to - * natively use EJS variables rather than the original C object interface, and - * to use the talloc() family of functions for memory allocation. - */ - -#include "includes.h" -#include "scripting/ejs/smbcalls.h" - -enum json_tokener_error { - json_tokener_success, - json_tokener_error_oom, /* out of memory */ - json_tokener_error_parse_unexpected, - json_tokener_error_parse_null, - json_tokener_error_parse_date, - json_tokener_error_parse_boolean, - json_tokener_error_parse_number, - json_tokener_error_parse_array, - json_tokener_error_parse_object, - json_tokener_error_parse_string, - json_tokener_error_parse_comment, - json_tokener_error_parse_eof -}; - -enum json_tokener_state { - json_tokener_state_eatws, - json_tokener_state_start, - json_tokener_state_finish, - json_tokener_state_null, - json_tokener_state_date, - json_tokener_state_comment_start, - json_tokener_state_comment, - json_tokener_state_comment_eol, - json_tokener_state_comment_end, - json_tokener_state_string, - json_tokener_state_string_escape, - json_tokener_state_escape_unicode, - json_tokener_state_boolean, - json_tokener_state_number, - json_tokener_state_array, - json_tokener_state_datelist, - json_tokener_state_array_sep, - json_tokener_state_datelist_sep, - json_tokener_state_object, - json_tokener_state_object_field_start, - json_tokener_state_object_field, - json_tokener_state_object_field_end, - json_tokener_state_object_value, - json_tokener_state_object_sep -}; - -enum date_field { - date_field_year, - date_field_month, - date_field_day, - date_field_hour, - date_field_minute, - date_field_second, - date_field_millisecond -}; - -struct json_tokener -{ - char *source; - int pos; - void *ctx; - void *pb; -}; - -static const char *json_number_chars = "0123456789.+-e"; -static const char *json_hex_chars = "0123456789abcdef"; - -#define hexdigit(x) (((x) <= '9') ? (x) - '0' : ((x) & 7) + 9) - -extern struct MprVar json_tokener_parse(char *s); -static struct MprVar json_tokener_do_parse(struct json_tokener *this, - enum json_tokener_error *err_p); - -/* - * literal_to_var() parses a string into an ejs variable. The ejs - * variable is returned. Upon error, the javascript variable will be - * `undefined`. This was created for parsing JSON, but is generally useful - * for parsing the literal forms of objects and arrays, since ejs doesn't - * procide that functionality. - */ -int literal_to_var(int eid, int argc, char **argv) -{ - struct json_tokener tok; - struct MprVar obj; - enum json_tokener_error err = json_tokener_success; - - if (argc != 1) { - ejsSetErrorMsg(eid, - "literal_to_var() requires one parameter: " - "the string to be parsed."); - return -1; - } - - tok.source = argv[0]; - tok.pos = 0; - tok.ctx = talloc_new(mprMemCtx()); - if (tok.ctx == NULL) { - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; - } - tok.pb = talloc_zero_size(tok.ctx, 1); - if (tok.pb == NULL) { - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; - } - obj = json_tokener_do_parse(&tok, &err); - talloc_free(tok.pb); - if (err != json_tokener_success) { - mprDestroyVar(&obj); - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; - } - mpr_Return(eid, obj); - return 0; -} - -static void *append_string(void *ctx, - char *orig, - char *append, - int size) -{ - if (!orig) { - return talloc_strndup(ctx, append, size); - } - - return talloc_strndup_append(orig, append, size); -} - - -static struct MprVar json_tokener_do_parse(struct json_tokener *this, - enum json_tokener_error *err_p) -{ - enum json_tokener_state state; - enum json_tokener_state saved_state; - enum date_field date_field; - struct MprVar current = mprCreateUndefinedVar(); - struct MprVar tempObj; - struct MprVar obj; - enum json_tokener_error err = json_tokener_success; - char date_script[] = "JSON_Date.create(0);"; - char *obj_field_name = NULL; - char *emsg = NULL; - char quote_char; - int deemed_double; - int start_offset; - char c; - - state = json_tokener_state_eatws; - saved_state = json_tokener_state_start; - - - do { - c = this->source[this->pos]; - switch(state) { - - case json_tokener_state_eatws: - if(isspace(c)) { - this->pos++; - } else if(c == '/') { - state = json_tokener_state_comment_start; - start_offset = this->pos++; - } else { - state = saved_state; - } - break; - - case json_tokener_state_start: - switch(c) { - case '{': - state = json_tokener_state_eatws; - saved_state = json_tokener_state_object; - current = mprObject(NULL); - this->pos++; - break; - case '[': - state = json_tokener_state_eatws; - saved_state = json_tokener_state_array; - current = mprArray(NULL); - this->pos++; - break; - case 'N': - case 'n': - start_offset = this->pos++; - if (this->source[this->pos] == 'e') { - state = json_tokener_state_date; - } else { - state = json_tokener_state_null; - } - break; - case '"': - case '\'': - quote_char = c; - talloc_free(this->pb); - this->pb = talloc_zero_size(this->ctx, 1); - if (this->pb == NULL) { - *err_p = json_tokener_error_oom; - goto out; - } - state = json_tokener_state_string; - start_offset = ++this->pos; - break; - case 'T': - case 't': - case 'F': - case 'f': - state = json_tokener_state_boolean; - start_offset = this->pos++; - break; -#if defined(__GNUC__) - case '0' ... '9': -#else - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': -#endif - case '-': - deemed_double = 0; - state = json_tokener_state_number; - start_offset = this->pos++; - break; - default: - err = json_tokener_error_parse_unexpected; - goto out; - } - break; - - case json_tokener_state_finish: - goto out; - - case json_tokener_state_null: - if(strncasecmp("null", - this->source + start_offset, - this->pos - start_offset)) { - *err_p = json_tokener_error_parse_null; - mprDestroyVar(¤t); - return mprCreateUndefinedVar(); - } - - if(this->pos - start_offset == 4) { - mprDestroyVar(¤t); - current = mprCreateNullVar(); - saved_state = json_tokener_state_finish; - state = json_tokener_state_eatws; - } else { - this->pos++; - } - break; - - case json_tokener_state_date: - if (this->pos - start_offset <= 18) { - if (strncasecmp("new Date(Date.UTC(", - this->source + start_offset, - this->pos - start_offset)) { - *err_p = json_tokener_error_parse_date; - mprDestroyVar(¤t); - return mprCreateUndefinedVar(); - } else { - this->pos++; - break; - } - } - - this->pos--; /* we went one too far */ - state = json_tokener_state_eatws; - saved_state = json_tokener_state_datelist; - - /* Create a JsonDate object */ - if (ejsEvalScript(0, - date_script, - &tempObj, - &emsg) != 0) { - *err_p = json_tokener_error_parse_date; - mprDestroyVar(¤t); - return mprCreateUndefinedVar(); - } - mprDestroyVar(¤t); - mprCopyVar(¤t, &tempObj, MPR_DEEP_COPY); - date_field = date_field_year; - break; - - case json_tokener_state_comment_start: - if(c == '*') { - state = json_tokener_state_comment; - } else if(c == '/') { - state = json_tokener_state_comment_eol; - } else { - err = json_tokener_error_parse_comment; - goto out; - } - this->pos++; - break; - - case json_tokener_state_comment: - if(c == '*') state = json_tokener_state_comment_end; - this->pos++; - break; - - case json_tokener_state_comment_eol: - if(c == '\n') { - state = json_tokener_state_eatws; - } - this->pos++; - break; - - case json_tokener_state_comment_end: - if(c == '/') { - state = json_tokener_state_eatws; - } else { - state = json_tokener_state_comment; - } - this->pos++; - break; - - case json_tokener_state_string: - if(c == quote_char) { - this->pb = append_string( - this->ctx, - this->pb, - this->source + start_offset, - this->pos - start_offset); - if (this->pb == NULL) { - err = json_tokener_error_oom; - goto out; - } - current = mprString(this->pb); - saved_state = json_tokener_state_finish; - state = json_tokener_state_eatws; - } else if(c == '\\') { - saved_state = json_tokener_state_string; - state = json_tokener_state_string_escape; - } - this->pos++; - break; - - case json_tokener_state_string_escape: - switch(c) { - case '"': - case '\\': - this->pb = append_string( - this->ctx, - this->pb, - this->source + start_offset, - this->pos - start_offset - 1); - if (this->pb == NULL) { - err = json_tokener_error_oom; - goto out; - } - start_offset = this->pos++; - state = saved_state; - break; - case 'b': - case 'n': - case 'r': - case 't': - this->pb = append_string( - this->ctx, - this->pb, - this->source + start_offset, - this->pos - start_offset - 1); - if (this->pb == NULL) { - err = json_tokener_error_oom; - goto out; - } - if (c == 'b') { - /* - * second param to append_string() - * gets temporarily modified; can't - * pass string constant. - */ - char buf[] = "\b"; - this->pb = append_string(this->ctx, - this->pb, - buf, - 1); - if (this->pb == NULL) { - err = json_tokener_error_oom; - goto out; - } - } else if (c == 'n') { - char buf[] = "\n"; - this->pb = append_string(this->ctx, - this->pb, - buf, - 1); - if (this->pb == NULL) { - err = json_tokener_error_oom; - goto out; - } - } else if (c == 'r') { - char buf[] = "\r"; - this->pb = append_string(this->ctx, - this->pb, - buf, - 1); - if (this->pb == NULL) { - err = json_tokener_error_oom; - goto out; - } - } else if (c == 't') { - char buf[] = "\t"; - this->pb = append_string(this->ctx, - this->pb, - buf, - 1); - if (this->pb == NULL) { - err = json_tokener_error_oom; - goto out; - } - } - start_offset = ++this->pos; - state = saved_state; - break; - case 'u': - this->pb = append_string( - this->ctx, - this->pb, - this->source + start_offset, - this->pos - start_offset - 1); - if (this->pb == NULL) { - err = json_tokener_error_oom; - goto out; - } - start_offset = ++this->pos; - state = json_tokener_state_escape_unicode; - break; - default: - err = json_tokener_error_parse_string; - goto out; - } - break; - - case json_tokener_state_escape_unicode: - if(strchr(json_hex_chars, c)) { - this->pos++; - if(this->pos - start_offset == 4) { - unsigned char utf_out[3]; - unsigned int ucs_char = - (hexdigit(*(this->source + start_offset)) << 12) + - (hexdigit(*(this->source + start_offset + 1)) << 8) + - (hexdigit(*(this->source + start_offset + 2)) << 4) + - hexdigit(*(this->source + start_offset + 3)); - if (ucs_char < 0x80) { - utf_out[0] = ucs_char; - this->pb = append_string( - this->ctx, - this->pb, - (char *) utf_out, - 1); - if (this->pb == NULL) { - err = json_tokener_error_oom; - goto out; - } - } else if (ucs_char < 0x800) { - utf_out[0] = 0xc0 | (ucs_char >> 6); - utf_out[1] = 0x80 | (ucs_char & 0x3f); - this->pb = append_string( - this->ctx, - this->pb, - (char *) utf_out, - 2); - if (this->pb == NULL) { - err = json_tokener_error_oom; - goto out; - } - } else { - utf_out[0] = 0xe0 | (ucs_char >> 12); - utf_out[1] = 0x80 | ((ucs_char >> 6) & 0x3f); - utf_out[2] = 0x80 | (ucs_char & 0x3f); - this->pb = append_string( - this->ctx, - this->pb, - (char *) utf_out, - 3); - if (this->pb == NULL) { - err = json_tokener_error_oom; - goto out; - } - } - start_offset = this->pos; - state = saved_state; - } - } else { - err = json_tokener_error_parse_string; - goto out; - } - break; - - case json_tokener_state_boolean: - if(strncasecmp("true", this->source + start_offset, - this->pos - start_offset) == 0) { - if(this->pos - start_offset == 4) { - current = mprCreateBoolVar(1); - saved_state = json_tokener_state_finish; - state = json_tokener_state_eatws; - } else { - this->pos++; - } - } else if(strncasecmp("false", this->source + start_offset, - this->pos - start_offset) == 0) { - if(this->pos - start_offset == 5) { - current = mprCreateBoolVar(0); - saved_state = json_tokener_state_finish; - state = json_tokener_state_eatws; - } else { - this->pos++; - } - } else { - err = json_tokener_error_parse_boolean; - goto out; - } - break; - - case json_tokener_state_number: - if(!c || !strchr(json_number_chars, c)) { - int numi; - double numd; - char *tmp = talloc_strndup( - this->ctx, - this->source + start_offset, - this->pos - start_offset); - if (tmp == NULL) { - err = json_tokener_error_oom; - goto out; - } - if(!deemed_double && sscanf(tmp, "%d", &numi) == 1) { - current = mprCreateIntegerVar(numi); - } else if(deemed_double && sscanf(tmp, "%lf", &numd) == 1) { - current = mprCreateFloatVar(numd); - } else { - talloc_free(tmp); - err = json_tokener_error_parse_number; - goto out; - } - talloc_free(tmp); - saved_state = json_tokener_state_finish; - state = json_tokener_state_eatws; - } else { - if(c == '.' || c == 'e') deemed_double = 1; - this->pos++; - } - break; - - case json_tokener_state_array: - if(c == ']') { - this->pos++; - saved_state = json_tokener_state_finish; - state = json_tokener_state_eatws; - } else { - int oldlen; - char idx[16]; - - obj = json_tokener_do_parse(this, &err); - if (err != json_tokener_success) { - goto out; - } - oldlen = mprToInt(mprGetProperty(¤t, - "length", - NULL)); - mprItoa(oldlen, idx, sizeof(idx)); - mprSetVar(¤t, idx, obj); - saved_state = json_tokener_state_array_sep; - state = json_tokener_state_eatws; - } - break; - - case json_tokener_state_datelist: - if(c == ')') { - if (this->source[this->pos+1] == ')') { - this->pos += 2; - saved_state = json_tokener_state_finish; - state = json_tokener_state_eatws; - } else { - err = json_tokener_error_parse_date; - goto out; - } - } else { - obj = json_tokener_do_parse(this, &err); - if (err != json_tokener_success) { - goto out; - } - - /* date list items must be integers */ - if (obj.type != MPR_TYPE_INT) { - err = json_tokener_error_parse_date; - goto out; - } - - switch(date_field) { - case date_field_year: - mprSetVar(¤t, "year", obj); - break; - case date_field_month: - mprSetVar(¤t, "month", obj); - break; - case date_field_day: - mprSetVar(¤t, "day", obj); - break; - case date_field_hour: - mprSetVar(¤t, "hour", obj); - break; - case date_field_minute: - mprSetVar(¤t, "minute", obj); - break; - case date_field_second: - mprSetVar(¤t, "second", obj); - break; - case date_field_millisecond: - mprSetVar(¤t, "millisecond", obj); - break; - default: - err = json_tokener_error_parse_date; - goto out; - } - - /* advance to the next date field */ - date_field++; - - saved_state = json_tokener_state_datelist_sep; - state = json_tokener_state_eatws; - } - break; - - case json_tokener_state_array_sep: - if(c == ']') { - this->pos++; - saved_state = json_tokener_state_finish; - state = json_tokener_state_eatws; - } else if(c == ',') { - this->pos++; - saved_state = json_tokener_state_array; - state = json_tokener_state_eatws; - } else { - *err_p = json_tokener_error_parse_array; - mprDestroyVar(¤t); - return mprCreateUndefinedVar(); - } - break; - - case json_tokener_state_datelist_sep: - if(c == ')') { - if (this->source[this->pos+1] == ')') { - this->pos += 2; - saved_state = json_tokener_state_finish; - state = json_tokener_state_eatws; - } else { - err = json_tokener_error_parse_date; - goto out; - } - } else if(c == ',') { - this->pos++; - saved_state = json_tokener_state_datelist; - state = json_tokener_state_eatws; - } else { - *err_p = json_tokener_error_parse_date; - mprDestroyVar(¤t); - return mprCreateUndefinedVar(); - } - break; - - case json_tokener_state_object: - state = json_tokener_state_object_field_start; - start_offset = this->pos; - break; - - case json_tokener_state_object_field_start: - if(c == '}') { - this->pos++; - saved_state = json_tokener_state_finish; - state = json_tokener_state_eatws; - } else if (c == '"' || c == '\'') { - quote_char = c; - talloc_free(this->pb); - this->pb = talloc_zero_size(this->ctx, 1); - if (this->pb == NULL) { - *err_p = json_tokener_error_oom; - goto out; - } - state = json_tokener_state_object_field; - start_offset = ++this->pos; - } else { - err = json_tokener_error_parse_object; - goto out; - } - break; - - case json_tokener_state_object_field: - if(c == quote_char) { - this->pb = append_string( - this->ctx, - this->pb, - this->source + start_offset, - this->pos - start_offset); - if (this->pb == NULL) { - err = json_tokener_error_oom; - goto out; - } - obj_field_name = talloc_strdup(this->ctx, - this->pb); - if (obj_field_name == NULL) { - err = json_tokener_error_oom; - goto out; - } - saved_state = json_tokener_state_object_field_end; - state = json_tokener_state_eatws; - } else if(c == '\\') { - saved_state = json_tokener_state_object_field; - state = json_tokener_state_string_escape; - } - this->pos++; - break; - - case json_tokener_state_object_field_end: - if(c == ':') { - this->pos++; - saved_state = json_tokener_state_object_value; - state = json_tokener_state_eatws; - } else { - *err_p = json_tokener_error_parse_object; - mprDestroyVar(¤t); - return mprCreateUndefinedVar(); - } - break; - - case json_tokener_state_object_value: - obj = json_tokener_do_parse(this, &err); - if (err != json_tokener_success) { - goto out; - } - mprSetVar(¤t, obj_field_name, obj); - talloc_free(obj_field_name); - obj_field_name = NULL; - saved_state = json_tokener_state_object_sep; - state = json_tokener_state_eatws; - break; - - case json_tokener_state_object_sep: - if(c == '}') { - this->pos++; - saved_state = json_tokener_state_finish; - state = json_tokener_state_eatws; - } else if(c == ',') { - this->pos++; - saved_state = json_tokener_state_object; - state = json_tokener_state_eatws; - } else { - err = json_tokener_error_parse_object; - goto out; - } - break; - - } - } while(c); - - if(state != json_tokener_state_finish && - saved_state != json_tokener_state_finish) - err = json_tokener_error_parse_eof; - -out: - talloc_free(obj_field_name); - if(err == json_tokener_success) { - return current; - } else { - mprDestroyVar(¤t); - *err_p = err; - return mprCreateUndefinedVar(); - } -} - - -void smb_setup_ejs_literal(void) -{ - ejsDefineStringCFunction(-1, - "literal_to_var", - literal_to_var, - NULL, - MPR_VAR_SCRIPT_HANDLE); -} diff --git a/source4/scripting/ejs/smbcalls.c b/source4/scripting/ejs/smbcalls.c index 98d6be07bf..4314b51455 100644 --- a/source4/scripting/ejs/smbcalls.c +++ b/source4/scripting/ejs/smbcalls.c @@ -191,7 +191,6 @@ void smb_setup_ejs_functions(void (*exception_handler)(const char *)) 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_nbt(void); extern NTSTATUS smb_setup_ejs_net(void); extern NTSTATUS ejs_init_srvsvc(void); extern NTSTATUS ejs_init_netlogon(void); @@ -203,11 +202,8 @@ void smb_setup_ejs_functions(void (*exception_handler)(const char *)) ejs_exception_handler = exception_handler; - smb_setup_ejs_cli(); smb_setup_ejs_options(); smb_setup_ejs_credentials(); - smb_setup_ejs_param(); - smb_setup_ejs_literal(); shared_init = load_samba_modules(NULL, mprLpCtx(), "smbcalls"); diff --git a/source4/scripting/ejs/smbcalls_cli.c b/source4/scripting/ejs/smbcalls_cli.c deleted file mode 100644 index dbb36312da..0000000000 --- a/source4/scripting/ejs/smbcalls_cli.c +++ /dev/null @@ -1,722 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide hooks into smbd C calls from ejs scripts - - 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 <http://www.gnu.org/licenses/>. -*/ - -#include "includes.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/appweb/ejs/ejs.h" -#include "libcli/raw/libcliraw.h" -#include "libcli/composite/composite.h" -#include "libcli/smb_composite/smb_composite.h" -#include "libcli/libcli.h" -#include "libcli/resolve/resolve.h" -#include "auth/credentials/credentials.h" -#include "param/param.h" - -#if 0 - -#include "librpc/gen_ndr/ndr_nbt.h" - -/* Connect to a server */ - -static int ejs_cli_connect(MprVarHandle eid, int argc, char **argv) -{ - struct smbcli_socket *sock; - struct smbcli_transport *transport; - struct nbt_name calling, called; - NTSTATUS result; - - if (argc != 1) { - ejsSetErrorMsg(eid, "connect invalid arguments"); - return -1; - } - - /* Socket connect */ - - sock = smbcli_sock_init(NULL, NULL); - - if (!sock) { - ejsSetErrorMsg(eid, "socket initialisation failed"); - return -1; - } - - if (!smbcli_sock_connect_byname(sock, argv[0], 0)) { - ejsSetErrorMsg(eid, "socket connect failed"); - return -1; - } - - transport = smbcli_transport_init(sock, sock, false); - - if (!transport) { - ejsSetErrorMsg(eid, "transport init failed"); - return -1; - } - - /* Send a netbios session request */ - - make_nbt_name_client(&calling, lp_netbios_name()); - - nbt_choose_called_name(NULL, &called, argv[0], NBT_NAME_SERVER); - - if (!smbcli_transport_connect(transport, &calling, &called)) { - ejsSetErrorMsg(eid, "transport establishment failed"); - return -1; - } - - result = smb_raw_negotiate(transport, lp_maxprotocol()); - - if (!NT_STATUS_IS_OK(result)) { - mpr_Return(eid, mprNTSTATUS(result)); - return 0; - } - - /* Return a socket object */ - - mpr_Return(eid, mprCreatePtrVar(transport)); - - return 0; -} - -/* Perform a session setup: - - session_setup(conn, "DOMAIN\\USERNAME%PASSWORD"); - session_setup(conn, USERNAME, PASSWORD); - session_setup(conn, DOMAIN, USERNAME, PASSWORD); - session_setup(conn); // anonymous - - */ - -static int ejs_cli_ssetup(MprVarHandle eid, int argc, MprVar **argv) -{ - struct smbcli_transport *transport; - struct smbcli_session *session; - struct smb_composite_sesssetup setup; - struct cli_credentials *creds; - NTSTATUS status; - int result = -1; - - /* Argument parsing */ - - if (argc < 1 || argc > 4) { - ejsSetErrorMsg(eid, "session_setup invalid arguments"); - return -1; - } - - if (!mprVarIsPtr(argv[0]->type)) { - ejsSetErrorMsg(eid, "first arg is not a connect handle"); - return -1; - } - - transport = argv[0]->ptr; - creds = cli_credentials_init(transport); - cli_credentials_set_conf(creds); - - if (argc == 4) { - - /* DOMAIN, USERNAME, PASSWORD form */ - - if (!mprVarIsString(argv[1]->type)) { - ejsSetErrorMsg(eid, "arg 1 must be a string"); - goto done; - } - - cli_credentials_set_domain(creds, argv[1]->string, - CRED_SPECIFIED); - - if (!mprVarIsString(argv[2]->type)) { - ejsSetErrorMsg(eid, "arg 2 must be a string"); - goto done; - } - - cli_credentials_set_username(creds, argv[2]->string, - CRED_SPECIFIED); - - if (!mprVarIsString(argv[3]->type)) { - ejsSetErrorMsg(eid, "arg 3 must be a string"); - goto done; - } - - cli_credentials_set_password(creds, argv[3]->string, - CRED_SPECIFIED); - - } else if (argc == 3) { - - /* USERNAME, PASSWORD form */ - - if (!mprVarIsString(argv[1]->type)) { - ejsSetErrorMsg(eid, "arg1 must be a string"); - goto done; - } - - cli_credentials_set_username(creds, argv[1]->string, - CRED_SPECIFIED); - - if (!mprVarIsString(argv[2]->type)) { - - ejsSetErrorMsg(eid, "arg2 must be a string"); - goto done; - } - - cli_credentials_set_password(creds, argv[2]->string, - CRED_SPECIFIED); - - } else if (argc == 2) { - - /* DOMAIN/USERNAME%PASSWORD form */ - - cli_credentials_parse_string(creds, argv[1]->string, - CRED_SPECIFIED); - - } else { - - /* Anonymous connection */ - - cli_credentials_set_anonymous(creds); - } - - /* Do session setup */ - - session = smbcli_session_init(transport, transport, false); - - if (!session) { - ejsSetErrorMsg(eid, "session init failed"); - return -1; - } - - setup.in.sesskey = transport->negotiate.sesskey; - setup.in.capabilities = transport->negotiate.capabilities; - setup.in.credentials = creds; - setup.in.workgroup = lp_workgroup(); - - status = smb_composite_sesssetup(session, &setup); - - if (!NT_STATUS_IS_OK(status)) { - ejsSetErrorMsg(eid, "session_setup: %s", nt_errstr(status)); - return -1; - } - - session->vuid = setup.out.vuid; - - /* Return a session object */ - - mpr_Return(eid, mprCreatePtrVar(session)); - - result = 0; - - done: - talloc_free(creds); - return result; -} - -/* Perform a tree connect - - tree_connect(session, SHARE); - - */ - -static int ejs_cli_tree_connect(MprVarHandle eid, int argc, MprVar **argv) -{ - struct smbcli_session *session; - struct smbcli_tree *tree; - union smb_tcon tcon; - TALLOC_CTX *mem_ctx; - NTSTATUS status; - const char *password = ""; - - /* Argument parsing */ - - if (argc != 2) { - ejsSetErrorMsg(eid, "tree_connect invalid arguments"); - return -1; - } - - if (!mprVarIsPtr(argv[0]->type)) { - ejsSetErrorMsg(eid, "first arg is not a session handle"); - return -1; - } - - session = argv[0]->ptr; - tree = smbcli_tree_init(session, session, false); - - if (!tree) { - ejsSetErrorMsg(eid, "tree init failed"); - return -1; - } - - mem_ctx = talloc_init("tcon"); - if (!mem_ctx) { - ejsSetErrorMsg(eid, "talloc_init failed"); - return -1; - } - - /* Do tree connect */ - - tcon.generic.level = RAW_TCON_TCONX; - tcon.tconx.in.flags = 0; - - if (session->transport->negotiate.sec_mode & NEGOTIATE_SECURITY_USER_LEVEL) { - tcon.tconx.in.password = data_blob(NULL, 0); - } else if (session->transport->negotiate.sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) { - tcon.tconx.in.password = data_blob_talloc(mem_ctx, NULL, 24); - if (session->transport->negotiate.secblob.length < 8) { - ejsSetErrorMsg(eid, "invalid security blob"); - return -1; - } - SMBencrypt(password, session->transport->negotiate.secblob.data, tcon.tconx.in.password.data); - } else { - tcon.tconx.in.password = data_blob_talloc(mem_ctx, password, strlen(password)+1); - } - - tcon.tconx.in.path = argv[1]->string; - tcon.tconx.in.device = "?????"; - - status = smb_tree_connect(tree, mem_ctx, &tcon); - - if (!NT_STATUS_IS_OK(status)) { - ejsSetErrorMsg(eid, "tree_connect: %s", nt_errstr(status)); - return -1; - } - - tree->tid = tcon.tconx.out.tid; - - talloc_free(mem_ctx); - - mpr_Return(eid, mprCreatePtrVar(tree)); - - return 0; -} - -/* Perform a tree disconnect - - tree_disconnect(tree); - - */ -static int ejs_cli_tree_disconnect(MprVarHandle eid, int argc, MprVar **argv) -{ - struct smbcli_tree *tree; - NTSTATUS status; - - /* Argument parsing */ - - if (argc != 1) { - ejsSetErrorMsg(eid, "tree_disconnect invalid arguments"); - return -1; - } - - if (!mprVarIsPtr(argv[0]->type)) { - ejsSetErrorMsg(eid, "first arg is not a tree handle"); - return -1; - } - - tree = argv[0]->ptr; - - status = smb_tree_disconnect(tree); - - if (!NT_STATUS_IS_OK(status)) { - ejsSetErrorMsg(eid, "tree_disconnect: %s", nt_errstr(status)); - return -1; - } - - talloc_free(tree); - - return 0; -} - -/* Perform a ulogoff - - session_logoff(session); - - */ -static int ejs_cli_session_logoff(MprVarHandle eid, int argc, MprVar **argv) -{ - struct smbcli_session *session; - NTSTATUS status; - - /* Argument parsing */ - - if (argc != 1) { - ejsSetErrorMsg(eid, "session_logoff invalid arguments"); - return -1; - } - - if (!mprVarIsPtr(argv[0]->type)) { - ejsSetErrorMsg(eid, "first arg is not a session handle"); - return -1; - } - - session = argv[0]->ptr; - - status = smb_raw_ulogoff(session); - - if (!NT_STATUS_IS_OK(status)) { - ejsSetErrorMsg(eid, "session_logoff: %s", nt_errstr(status)); - return -1; - } - - talloc_free(session); - - return 0; -} - -/* Perform a connection close - - disconnect(conn); - - */ -static int ejs_cli_disconnect(MprVarHandle eid, int argc, MprVar **argv) -{ - struct smbcli_sock *sock; - - /* Argument parsing */ - - if (argc != 1) { - ejsSetErrorMsg(eid, "disconnect invalid arguments"); - return -1; - } - - if (!mprVarIsPtr(argv[0]->type)) { - ejsSetErrorMsg(eid, "first arg is not a connect handle"); - return -1; - } - - sock = argv[0]->ptr; - - talloc_free(sock); - - return 0; -} - -#endif - -/* Perform a tree connect: - - tree_handle = tree_connect("\\\\frogurt\\homes", "user%pass"); - */ - -static int ejs_tree_connect(MprVarHandle eid, int argc, char **argv) -{ - struct cli_credentials *creds; - struct smb_composite_connect io; - struct smbcli_tree *tree; - char *hostname, *sharename; - NTSTATUS result; - TALLOC_CTX *mem_ctx; - - if (argc != 2) { - ejsSetErrorMsg(eid, "tree_connect(): invalid number of args"); - return -1; - } - - /* Set up host, share destination */ - - mem_ctx = talloc_new(mprMemCtx()); - smbcli_parse_unc(argv[0], mem_ctx, &hostname, &sharename); - - /* Set up credentials */ - - creds = cli_credentials_init(NULL); - cli_credentials_set_conf(creds, mprLpCtx()); - cli_credentials_parse_string(creds, argv[1], CRED_SPECIFIED); - - /* Do connect */ - - io.in.dest_host = hostname; - io.in.dest_ports = lp_smb_ports(mprLpCtx()); - io.in.called_name = strupper_talloc(mem_ctx, hostname); - io.in.service = sharename; - io.in.service_type = "?????"; - io.in.credentials = creds; - io.in.fallback_to_anonymous = false; - io.in.workgroup = lp_workgroup(mprLpCtx()); - lp_smbcli_options(mprLpCtx(), &io.in.options); - - result = smb_composite_connect(&io, mem_ctx, - lp_resolve_context(mprLpCtx()), - NULL); - tree = io.out.tree; - - talloc_free(mem_ctx); - - if (!NT_STATUS_IS_OK(result)) { - mpr_Return(eid, mprNTSTATUS(result)); - return 0; - } - - mpr_Return(eid, mprCreatePtrVar(tree)); - - return 0; -} - -#define IS_TREE_HANDLE(x) (mprVarIsPtr((x)->type) && \ - talloc_check_name((x)->ptr, "struct smbcli_tree")) - -/* Perform a tree disconnect: - - tree_disconnect(tree_handle); - */ - -static int ejs_tree_disconnect(MprVarHandle eid, int argc, MprVar **argv) -{ - struct smbcli_tree *tree; - NTSTATUS result; - - if (argc != 1) { - ejsSetErrorMsg(eid, - "tree_disconnect(): invalid number of args"); - return -1; - } - - if (!IS_TREE_HANDLE(argv[0])) { - ejsSetErrorMsg(eid, "first arg is not a tree handle"); - return -1; - } - - tree = talloc_get_type(argv[0]->ptr, struct smbcli_tree); - - result = smb_tree_disconnect(tree); - - mpr_Return(eid, mprNTSTATUS(result)); - - return 0; -} - -/* Create a directory: - - result = mkdir(tree_handle, DIRNAME); - */ - -static int ejs_mkdir(MprVarHandle eid, int argc, MprVar **argv) -{ - struct smbcli_tree *tree; - NTSTATUS result; - - if (argc != 2) { - ejsSetErrorMsg(eid, "mkdir(): invalid number of args"); - return -1; - } - - if (!IS_TREE_HANDLE(argv[0])) { - ejsSetErrorMsg(eid, "first arg is not a tree handle"); - return -1; - } - - tree = (struct smbcli_tree *)argv[0]->ptr; - - if (!mprVarIsString(argv[1]->type)) { - ejsSetErrorMsg(eid, "arg 2 must be a string"); - return -1; - } - - result = smbcli_mkdir(tree, argv[1]->string); - - mpr_Return(eid, mprNTSTATUS(result)); - - return 0; -} - -/* Remove a directory: - - result = rmdir(tree_handle, DIRNAME); - */ - -static int ejs_rmdir(MprVarHandle eid, int argc, MprVar **argv) -{ - struct smbcli_tree *tree; - NTSTATUS result; - - if (argc != 2) { - ejsSetErrorMsg(eid, "rmdir(): invalid number of args"); - return -1; - } - - if (!IS_TREE_HANDLE(argv[0])) { - ejsSetErrorMsg(eid, "first arg is not a tree handle"); - return -1; - } - - tree = (struct smbcli_tree *)argv[0]->ptr; - - if (!mprVarIsString(argv[1]->type)) { - ejsSetErrorMsg(eid, "arg 2 must be a string"); - return -1; - } - - result = smbcli_rmdir(tree, argv[1]->string); - - mpr_Return(eid, mprNTSTATUS(result)); - - return 0; -} - -/* Rename a file or directory: - - result = rename(tree_handle, SRCFILE, DESTFILE); - */ - -static int ejs_rename(MprVarHandle eid, int argc, MprVar **argv) -{ - struct smbcli_tree *tree; - NTSTATUS result; - - if (argc != 3) { - ejsSetErrorMsg(eid, "rename(): invalid number of args"); - return -1; - } - - if (!IS_TREE_HANDLE(argv[0])) { - ejsSetErrorMsg(eid, "first arg is not a tree handle"); - return -1; - } - - tree = (struct smbcli_tree *)argv[0]->ptr; - - if (!mprVarIsString(argv[1]->type)) { - ejsSetErrorMsg(eid, "arg 2 must be a string"); - return -1; - } - - if (!mprVarIsString(argv[2]->type)) { - ejsSetErrorMsg(eid, "arg 3 must be a string"); - return -1; - } - - result = smbcli_rename(tree, argv[1]->string, argv[2]->string); - - mpr_Return(eid, mprNTSTATUS(result)); - - return 0; -} - -/* Unlink a file or directory: - - result = unlink(tree_handle, FILENAME); - */ - -static int ejs_unlink(MprVarHandle eid, int argc, MprVar **argv) -{ - struct smbcli_tree *tree; - NTSTATUS result; - - if (argc != 2) { - ejsSetErrorMsg(eid, "unlink(): invalid number of args"); - return -1; - } - - if (!IS_TREE_HANDLE(argv[0])) { - ejsSetErrorMsg(eid, "first arg is not a tree handle"); - return -1; - } - - tree = (struct smbcli_tree *)argv[0]->ptr; - - if (!mprVarIsString(argv[1]->type)) { - ejsSetErrorMsg(eid, "arg 2 must be a string"); - return -1; - } - - result = smbcli_unlink(tree, argv[1]->string); - - mpr_Return(eid, mprNTSTATUS(result)); - - return 0; -} - -/* List directory contents - - result = list(tree_handle, ARG1, ...); - */ - -static void ejs_list_helper(struct clilist_file_info *info, const char *mask, - void *state) - -{ - MprVar *result = (MprVar *)state; - char idx[16]; - - mprItoa(result->properties->numDataItems, idx, sizeof(idx)); - mprSetVar(result, idx, mprString(info->name)); -} - -static int ejs_list(MprVarHandle eid, int argc, MprVar **argv) -{ - struct smbcli_tree *tree; - char *mask; - uint16_t attribute; - MprVar result; - - if (argc != 3) { - ejsSetErrorMsg(eid, "list(): invalid number of args"); - return -1; - } - - if (!IS_TREE_HANDLE(argv[0])) { - ejsSetErrorMsg(eid, "first arg is not a tree handle"); - return -1; - } - - tree = (struct smbcli_tree *)argv[0]->ptr; - - if (!mprVarIsString(argv[1]->type)) { - ejsSetErrorMsg(eid, "arg 2 must be a string"); - return -1; - } - - mask = argv[1]->string; - - if (!mprVarIsNumber(argv[2]->type)) { - ejsSetErrorMsg(eid, "arg 3 must be a number"); - return -1; - } - - attribute = mprVarToInteger(argv[2]); - - result = mprObject("list"); - - smbcli_list(tree, mask, attribute, ejs_list_helper, &result); - - mpr_Return(eid, result); - - return 0; -} - -/* - setup C functions that be called from ejs -*/ -void smb_setup_ejs_cli(void) -{ - ejsDefineStringCFunction(-1, "tree_connect", ejs_tree_connect, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineCFunction(-1, "tree_disconnect", ejs_tree_disconnect, NULL, MPR_VAR_SCRIPT_HANDLE); - - ejsDefineCFunction(-1, "mkdir", ejs_mkdir, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineCFunction(-1, "rmdir", ejs_rmdir, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineCFunction(-1, "rename", ejs_rename, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineCFunction(-1, "unlink", ejs_unlink, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineCFunction(-1, "list", ejs_list, NULL, MPR_VAR_SCRIPT_HANDLE); - - -#if 0 - ejsDefineStringCFunction(-1, "connect", ejs_cli_connect, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineCFunction(-1, "session_setup", ejs_cli_ssetup, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineCFunction(-1, "tree_connect", ejs_cli_tree_connect, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineCFunction(-1, "tree_disconnect", ejs_cli_tree_disconnect, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineCFunction(-1, "session_logoff", ejs_cli_session_logoff, NULL, MPR_VAR_SCRIPT_HANDLE); - ejsDefineCFunction(-1, "disconnect", ejs_cli_disconnect, NULL, MPR_VAR_SCRIPT_HANDLE); -#endif -} diff --git a/source4/scripting/ejs/smbcalls_data.c b/source4/scripting/ejs/smbcalls_data.c deleted file mode 100644 index 19e1e173d6..0000000000 --- a/source4/scripting/ejs/smbcalls_data.c +++ /dev/null @@ -1,284 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide access to data blobs - - 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 <http://www.gnu.org/licenses/>. -*/ - -#include "includes.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/appweb/ejs/ejs.h" -#include "librpc/gen_ndr/winreg.h" - -/* - create a data blob object from a ejs array of integers -*/ -static int ejs_blobFromArray(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct MprVar *array, *v; - unsigned length, i; - DATA_BLOB blob; - - if (argc != 1) { - ejsSetErrorMsg(eid, "blobFromArray invalid arguments"); - return -1; - } - array = argv[0]; - - v = mprGetProperty(array, "length", NULL); - if (v == NULL) { - goto failed; - } - length = mprToInt(v); - - blob = data_blob_talloc(mprMemCtx(), NULL, length); - if (length != 0 && blob.data == NULL) { - goto failed; - } - - for (i=0;i<length;i++) { - struct MprVar *vs; - char idx[16]; - mprItoa(i, idx, sizeof(idx)); - vs = mprGetProperty(array, idx, NULL); - if (vs == NULL) { - goto failed; - } - blob.data[i] = mprVarToNumber(vs); - } - - mpr_Return(eid, mprDataBlob(blob)); - return 0; - -failed: - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; -} - -/* - create a ejs array of integers from a data blob -*/ -static int ejs_blobToArray(MprVarHandle eid, int argc, struct MprVar **argv) -{ - DATA_BLOB *blob; - struct MprVar array; - int i; - - if (argc != 1) { - ejsSetErrorMsg(eid, "blobToArray invalid arguments"); - return -1; - } - blob = mprToDataBlob(argv[0]); - if (blob == NULL) { - goto failed; - } - - array = mprArray("array"); - - for (i=0;i<blob->length;i++) { - mprAddArray(&array, i, mprCreateNumberVar(blob->data[i])); - } - mpr_Return(eid, array); - return 0; - -failed: - mpr_Return(eid, mprCreateUndefinedVar()); - return 0; -} - - -/* - compare two data blobs -*/ -static int ejs_blobCompare(MprVarHandle eid, int argc, struct MprVar **argv) -{ - DATA_BLOB *blob1, *blob2; - bool ret = false; - - if (argc != 2) { - ejsSetErrorMsg(eid, "blobCompare invalid arguments"); - return -1; - } - - blob1 = mprToDataBlob(argv[0]); - blob2 = mprToDataBlob(argv[1]); - - if (blob1 == blob2) { - ret = true; - goto done; - } - if (blob1 == NULL || blob2 == NULL) { - ret = false; - goto done; - } - - if (blob1->length != blob2->length) { - ret = false; - goto done; - } - - if (memcmp(blob1->data, blob2->data, blob1->length) != 0) { - ret = false; - goto done; - } - ret = true; - -done: - mpr_Return(eid, mprCreateBoolVar(ret)); - return 0; -} - - -/* - convert a blob in winreg format to a mpr variable - - usage: - v = data.regToVar(blob, type); -*/ -static int ejs_regToVar(MprVarHandle eid, int argc, struct MprVar **argv) -{ - DATA_BLOB *blob; - enum winreg_Type type; - struct MprVar v; - - if (argc != 2) { - ejsSetErrorMsg(eid, "regToVar invalid arguments"); - return -1; - } - - blob = mprToDataBlob(argv[0]); - type = mprToInt(argv[1]); - - if (blob == NULL) { - ejsSetErrorMsg(eid, "regToVar null data"); - return -1; - } - - switch (type) { - case REG_NONE: - v = mprCreateUndefinedVar(); - break; - - case REG_SZ: - case REG_EXPAND_SZ: { - char *s; - ssize_t len; - len = convert_string_talloc(mprMemCtx(), lp_iconv_convenience(mprLpCtx()), CH_UTF16, CH_UNIX, - blob->data, blob->length, (void **)&s); - if (len == -1) { - ejsSetErrorMsg(eid, "regToVar invalid REG_SZ string"); - return -1; - } - v = mprString(s); - talloc_free(s); - break; - } - - case REG_DWORD: { - if (blob->length != 4) { - ejsSetErrorMsg(eid, "regToVar invalid REG_DWORD length %ld", (long)blob->length); - return -1; - } - v = mprCreateNumberVar(IVAL(blob->data, 0)); - break; - } - - case REG_DWORD_BIG_ENDIAN: { - if (blob->length != 4) { - ejsSetErrorMsg(eid, "regToVar invalid REG_DWORD_BIG_ENDIAN length %ld", (long)blob->length); - return -1; - } - v = mprCreateNumberVar(RIVAL(blob->data, 0)); - break; - } - - case REG_QWORD: { - if (blob->length != 8) { - ejsSetErrorMsg(eid, "regToVar invalid REG_QWORD length %ld", (long)blob->length); - return -1; - } - v = mprCreateNumberVar(BVAL(blob->data, 0)); - break; - } - - case REG_MULTI_SZ: { - DATA_BLOB b = *blob; - const char **list = NULL; - while (b.length > 0) { - char *s; - ssize_t len; - size_t slen = utf16_len_n(b.data, b.length); - if (slen == 2 && b.length == 2 && SVAL(b.data, 0) == 0) { - break; - } - len = convert_string_talloc(mprMemCtx(), lp_iconv_convenience(mprLpCtx()), CH_UTF16, CH_UNIX, - b.data, slen, (void **)&s); - if (len == -1) { - ejsSetErrorMsg(eid, "regToVar invalid REG_MULTI_SZ string"); - return -1; - } - list = str_list_add(list, s); - talloc_free(s); - talloc_steal(mprMemCtx(), list); - b.data += slen; - b.length -= slen; - } - v = mprList("REG_MULTI_SZ", list); - talloc_free(list); - break; - } - - - case REG_FULL_RESOURCE_DESCRIPTOR: - case REG_RESOURCE_LIST: - case REG_BINARY: - case REG_RESOURCE_REQUIREMENTS_LIST: - case REG_LINK: - return ejs_blobToArray(eid, 1, argv); - - default: - ejsSetErrorMsg(eid, "regToVar invalid type %d", type); - return -1; - } - - mpr_Return(eid, v); - return 0; -} - -/* - initialise datablob ejs subsystem -*/ -static int ejs_datablob_init(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct MprVar *obj = mprInitObject(eid, "datablob", argc, argv); - - mprSetCFunction(obj, "blobFromArray", ejs_blobFromArray); - mprSetCFunction(obj, "blobToArray", ejs_blobToArray); - mprSetCFunction(obj, "blobCompare", ejs_blobCompare); - mprSetCFunction(obj, "regToVar", ejs_regToVar); - - return 0; -} - -/* - setup C functions that be called from ejs -*/ -NTSTATUS smb_setup_ejs_datablob(void) -{ - ejsDefineCFunction(-1, "datablob_init", ejs_datablob_init, NULL, MPR_VAR_SCRIPT_HANDLE); - return NT_STATUS_OK; -} diff --git a/source4/scripting/ejs/smbcalls_nbt.c b/source4/scripting/ejs/smbcalls_nbt.c deleted file mode 100644 index 8c555bf821..0000000000 --- a/source4/scripting/ejs/smbcalls_nbt.c +++ /dev/null @@ -1,93 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide hooks into smbd C calls from ejs scripts - - 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 <http://www.gnu.org/licenses/>. -*/ - -#include "includes.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/appweb/ejs/ejs.h" -#include "librpc/gen_ndr/nbt.h" -#include "lib/events/events.h" -#include "libcli/resolve/resolve.h" - -/* - look up a netbios name - - syntax: - resolveName(result, "frogurt"); - resolveName(result, "frogurt", 0x1c); -*/ - -static int ejs_resolve_name(MprVarHandle eid, int argc, struct MprVar **argv) -{ - int result = -1; - struct nbt_name name; - TALLOC_CTX *tmp_ctx = talloc_new(mprMemCtx()); - NTSTATUS nt_status; - const char *reply_addr; - - /* validate arguments */ - if (argc < 2 || argc > 3) { - ejsSetErrorMsg(eid, "resolveName invalid arguments"); - goto done; - } - - if (argv[0]->type != MPR_TYPE_OBJECT) { - ejsSetErrorMsg(eid, "resolvename invalid arguments"); - goto done; - } - - if (argv[1]->type != MPR_TYPE_STRING) { - ejsSetErrorMsg(eid, "resolveName invalid arguments"); - goto done; - } - - if (argc == 2) { - make_nbt_name_client(&name, mprToString(argv[1])); - } else { - if (!mprVarIsNumber(argv[1]->type)) { - ejsSetErrorMsg(eid, "resolveName invalid arguments"); - goto done; - } - make_nbt_name(&name, mprToString(argv[1]), mprToInt(argv[2])); - } - - result = 0; - - nt_status = resolve_name(lp_resolve_context(mprLpCtx()), &name, tmp_ctx, &reply_addr, mprEventCtx()); - - if (NT_STATUS_IS_OK(nt_status)) { - mprSetPropertyValue(argv[0], "value", mprString(reply_addr)); - } - - mpr_Return(eid, mprNTSTATUS(nt_status)); - - done: - talloc_free(tmp_ctx); - return result; -} - -/* - setup C functions that be called from ejs -*/ -NTSTATUS smb_setup_ejs_nbt(void) -{ - ejsDefineCFunction(-1, "resolveName", ejs_resolve_name, NULL, MPR_VAR_SCRIPT_HANDLE); - return NT_STATUS_OK; -} diff --git a/source4/scripting/ejs/smbcalls_nss.c b/source4/scripting/ejs/smbcalls_nss.c deleted file mode 100644 index 58f86d3b6c..0000000000 --- a/source4/scripting/ejs/smbcalls_nss.c +++ /dev/null @@ -1,160 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide access to getpwnam() and related 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 <http://www.gnu.org/licenses/>. -*/ - -#include "includes.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/appweb/ejs/ejs.h" -#include "system/passwd.h" - - -/* - return a struct passwd as an object -*/ -static struct MprVar mpr_passwd(struct passwd *pwd) -{ - struct MprVar ret; - if (pwd == NULL) { - return mprCreateUndefinedVar(); - } - ret = mprObject("passwd"); - - mprSetVar(&ret, "pw_name", mprString(pwd->pw_name)); - mprSetVar(&ret, "pw_passwd", mprString(pwd->pw_passwd)); - mprSetVar(&ret, "pw_uid", mprCreateIntegerVar(pwd->pw_uid)); - mprSetVar(&ret, "pw_gid", mprCreateIntegerVar(pwd->pw_gid)); - mprSetVar(&ret, "pw_gecos", mprString(pwd->pw_gecos)); - mprSetVar(&ret, "pw_dir", mprString(pwd->pw_dir)); - mprSetVar(&ret, "pw_shell", mprString(pwd->pw_shell)); - return ret; -} - -/* - return a struct passwd as an object -*/ -static struct MprVar mpr_group(struct group *grp) -{ - struct MprVar ret; - if (grp == NULL) { - return mprCreateUndefinedVar(); - } - ret = mprObject("group"); - - mprSetVar(&ret, "gr_name", mprString(grp->gr_name)); - mprSetVar(&ret, "gr_passwd", mprString(grp->gr_passwd)); - mprSetVar(&ret, "gr_gid", mprCreateIntegerVar(grp->gr_gid)); - mprSetVar(&ret, "gr_mem", mprList("gr_mem", (const char **)grp->gr_mem)); - return ret; -} - - -/* - usage: - var pw = nss.getpwnam("root"); - - returns an object containing struct passwd entries -*/ -static int ejs_getpwnam(MprVarHandle eid, int argc, struct MprVar **argv) -{ - /* validate arguments */ - if (argc != 1 || argv[0]->type != MPR_TYPE_STRING) { - ejsSetErrorMsg(eid, "getpwnam invalid arguments"); - return -1; - } - - mpr_Return(eid, mpr_passwd(getpwnam(mprToString(argv[0])))); - return 0; -} - -/* - usage: - var pw = nss.getpwuid(0); - - returns an object containing struct passwd entries -*/ -static int ejs_getpwuid(MprVarHandle eid, int argc, struct MprVar **argv) -{ - /* validate arguments */ - if (argc != 1 || !mprVarIsNumber(argv[0]->type)) { - ejsSetErrorMsg(eid, "getpwuid invalid arguments"); - return -1; - } - mpr_Return(eid, mpr_passwd(getpwuid(mprToInt(argv[0])))); - return 0; -} - -/* - usage: - var pw = nss.getgrnam("users"); - - returns an object containing struct group entries -*/ -static int ejs_getgrnam(MprVarHandle eid, int argc, struct MprVar **argv) -{ - /* validate arguments */ - if (argc != 1 || argv[0]->type != MPR_TYPE_STRING) { - ejsSetErrorMsg(eid, "getgrnam invalid arguments"); - return -1; - } - mpr_Return(eid, mpr_group(getgrnam(mprToString(argv[0])))); - return 0; -} - -/* - usage: - var pw = nss.getgrgid(0); - - returns an object containing struct group entries -*/ -static int ejs_getgrgid(MprVarHandle eid, int argc, struct MprVar **argv) -{ - /* validate arguments */ - if (argc != 1 || argv[0]->type != MPR_TYPE_STRING) { - ejsSetErrorMsg(eid, "getgrgid invalid arguments"); - return -1; - } - mpr_Return(eid, mpr_group(getgrgid(mprToInt(argv[0])))); - return 0; -} - - -/* - initialise nss ejs subsystem -*/ -static int ejs_nss_init(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct MprVar *nss = mprInitObject(eid, "nss", argc, argv); - - mprSetCFunction(nss, "getpwnam", ejs_getpwnam); - mprSetCFunction(nss, "getpwuid", ejs_getpwuid); - mprSetCFunction(nss, "getgrnam", ejs_getgrnam); - mprSetCFunction(nss, "getgrgid", ejs_getgrgid); - - return 0; -} - -/* - setup C functions that be called from ejs -*/ -NTSTATUS smb_setup_ejs_nss(void) -{ - ejsDefineCFunction(-1, "nss_init", ejs_nss_init, NULL, MPR_VAR_SCRIPT_HANDLE); - return NT_STATUS_OK; -} diff --git a/source4/scripting/ejs/smbcalls_param.c b/source4/scripting/ejs/smbcalls_param.c deleted file mode 100644 index 5fbb0bb017..0000000000 --- a/source4/scripting/ejs/smbcalls_param.c +++ /dev/null @@ -1,259 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide hooks into smbd C calls from ejs scripts - - 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 <http://www.gnu.org/licenses/>. -*/ - -#include "includes.h" -#include "param/param.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/appweb/ejs/ejs.h" - -/* - get parameter - - value = param.get("name"); - value = param.get("section", "name"); -*/ -static int ejs_param_get(MprVarHandle eid, int argc, char **argv) -{ - struct param_context *ctx; - const char *ret; - if (argc != 1 && argc != 2) { - ejsSetErrorMsg(eid, "param.get invalid argument count"); - return -1; - } - - ctx = (struct param_context *)mprGetThisPtr(eid, "param"); - mprAssert(ctx); - - if (argc == 2) { - ret = param_get_string(ctx, argv[0], argv[1]); - } else { - ret = param_get_string(ctx, argv[0], NULL); - } - - if (ret) { - mpr_Return(eid, mprString(ret)); - } else { - mpr_Return(eid, mprCreateUndefinedVar()); - } - return 0; -} - -/* - get list parameter - - ok = param.get_list("name"); - ok = param.get_list("section", "name"); -*/ -static int ejs_param_get_list(MprVarHandle eid, int argc, char **argv) -{ - struct param_context *ctx; - const char **ret; - - if (argc != 1 && argc != 2) { - ejsSetErrorMsg(eid, "param.get_list invalid argument count"); - return -1; - } - - ctx = (struct param_context *)mprGetThisPtr(eid, "param"); - mprAssert(ctx); - - if (argc == 2) { - ret = param_get_string_list(ctx, argv[0], argv[1], NULL); - } else { - ret = param_get_string_list(ctx, argv[0], NULL, NULL); - } - - if (ret != NULL) { - mpr_Return(eid, mprList("array", ret)); - } else { - mpr_Return(eid, mprCreateUndefinedVar()); - } - return 0; -} - -/* - set parameter - - ok = param.set("name", "value"); - ok = param.set("section", "name", "value"); -*/ -static int ejs_param_set(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct param_context *ctx; - const char **list; - const char *section, *paramname; - struct MprVar *value; - bool ret; - if (argc != 2 && argc != 3) { - ejsSetErrorMsg(eid, "param.set invalid argument count"); - return -1; - } - - ctx = (struct param_context *)mprGetThisPtr(eid, "param"); - mprAssert(ctx); - - - if (argc == 3) { - section = mprToString(argv[0]); - paramname = mprToString(argv[1]); - value = argv[2]; - } else { - section = NULL; - paramname = mprToString(argv[0]); - value = argv[1]; - } - - list = mprToList(mprMemCtx(), value); - if (list) { - ret = param_set_string_list(ctx, paramname, list, section); - } else { - ret = param_set_string(ctx, paramname, mprToString(value), section); - } - - mpr_Return(eid, mprCreateBoolVar(ret)); - return 0; -} - -/* - param data as a two-level array - - data = param.data; - */ -static int ejs_param_data(MprVarHandle eid, int argc, char **argv) -{ - struct param_context *ctx; - struct MprVar ret; - struct param_section *sec; - - if (argc != 0) { - ejsSetErrorMsg(eid, "param.data does not take arguments"); - return -1; - } - - ctx = (struct param_context *)mprGetThisPtr(eid, "param"); - mprAssert(ctx); - - ret = mprObject("array"); - - for (sec = ctx->sections; sec; sec = sec->next) { - struct MprVar ps = mprObject("array"); - struct param_opt *p; - - for (p = sec->parameters; p; p = p->next) { - mprSetVar(&ps, p->key, mprString(p->value)); - } - - mprSetVar(&ret, sec->name, ps); - } - - mpr_Return(eid, ret); - - return 0; -} - -/* - load file - - ok = param.load(file); -*/ -static int ejs_param_load(MprVarHandle eid, int argc, char **argv) -{ - struct param_context *ctx; - bool ret; - - if (argc != 1) { - ejsSetErrorMsg(eid, "param.load invalid argument count"); - return -1; - } - - ctx = (struct param_context *)mprGetThisPtr(eid, "param"); - mprAssert(ctx); - - ret = param_read(ctx, argv[0]); - - mpr_Return(eid, mprCreateBoolVar(ret)); - return 0; -} - - -/* - save file - - ok = param.save(file); -*/ -static int ejs_param_save(MprVarHandle eid, int argc, char **argv) -{ - struct param_context *ctx; - bool ret; - - if (argc != 1) { - ejsSetErrorMsg(eid, "param.save invalid argument count"); - return -1; - } - - ctx = (struct param_context *)mprGetThisPtr(eid, "param"); - mprAssert(ctx); - - ret = param_write(ctx, argv[0]); - - mpr_Return(eid, mprCreateBoolVar(ret)); - return 0; -} - -static void param_add_members(struct MprVar *obj) -{ - mprSetStringCFunction(obj, "get", ejs_param_get); - mprSetStringCFunction(obj, "get_list", ejs_param_get_list); - mprSetCFunction(obj, "set", ejs_param_set); - mprSetStringCFunction(obj, "load", ejs_param_load); - mprSetStringCFunction(obj, "save", ejs_param_save); - mprSetStringCFunction(obj, "data", ejs_param_data); -} - -/* - initialise param ejs subsystem -*/ -static int ejs_param_init(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct MprVar *obj = mprInitObject(eid, "param", argc, argv); - - mprSetPtrChild(obj, "param", param_init(mprMemCtx())); - - param_add_members(obj); - - return 0; -} - -struct MprVar mprParam(struct param_context *ctx) -{ - struct MprVar mpv = mprObject("param"); - mprSetPtrChild(&mpv, "param", ctx); - param_add_members(&mpv); - return mpv; -} - -/* - setup C functions that be called from ejs -*/ -void smb_setup_ejs_param(void) -{ - ejsDefineCFunction(-1, "param_init", ejs_param_init, NULL, MPR_VAR_SCRIPT_HANDLE); -} diff --git a/source4/scripting/ejs/smbcalls_rand.c b/source4/scripting/ejs/smbcalls_rand.c deleted file mode 100644 index 58e0fa1fd1..0000000000 --- a/source4/scripting/ejs/smbcalls_rand.c +++ /dev/null @@ -1,104 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide access to randomisation functions - - 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 <http://www.gnu.org/licenses/>. -*/ - -#include "includes.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/appweb/ejs/ejs.h" -#include "librpc/gen_ndr/ndr_misc.h" -#include "librpc/ndr/libndr.h" - -/* - usage: - var i = random(); -*/ -static int ejs_random(MprVarHandle eid, int argc, struct MprVar **argv) -{ - mpr_Return(eid, mprCreateIntegerVar(generate_random())); - return 0; -} - -/* - usage: - var s = randpass(len); -*/ -static int ejs_randpass(MprVarHandle eid, int argc, struct MprVar **argv) -{ - char *s; - if (argc != 1 || !mprVarIsNumber(argv[0]->type)) { - ejsSetErrorMsg(eid, "randpass invalid arguments"); - return -1; - } - s = generate_random_str(mprMemCtx(), mprToInt(argv[0])); - mpr_Return(eid, mprString(s)); - talloc_free(s); - return 0; -} - -/* - usage: - var guid = randguid(); -*/ -static int ejs_randguid(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct GUID guid = GUID_random(); - char *s = GUID_string(mprMemCtx(), &guid); - mpr_Return(eid, mprString(s)); - talloc_free(s); - return 0; -} - -/* - usage: - var sid = randsid(); -*/ -static int ejs_randsid(MprVarHandle eid, int argc, struct MprVar **argv) -{ - char *s = talloc_asprintf(mprMemCtx(), "S-1-5-21-%u-%u-%u", - (unsigned)generate_random(), - (unsigned)generate_random(), - (unsigned)generate_random()); - mpr_Return(eid, mprString(s)); - talloc_free(s); - return 0; -} - -/* - initialise random ejs subsystem -*/ -static int ejs_random_init(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct MprVar *obj = mprInitObject(eid, "random", argc, argv); - - mprSetCFunction(obj, "random", ejs_random); - mprSetCFunction(obj, "randpass", ejs_randpass); - mprSetCFunction(obj, "randguid", ejs_randguid); - mprSetCFunction(obj, "randsid", ejs_randsid); - return 0; -} - -/* - setup C functions that be called from ejs -*/ -NTSTATUS smb_setup_ejs_random(void) -{ - ejsDefineCFunction(-1, "random_init", ejs_random_init, NULL, MPR_VAR_SCRIPT_HANDLE); - return NT_STATUS_OK; -} diff --git a/source4/scripting/ejs/smbcalls_reg.c b/source4/scripting/ejs/smbcalls_reg.c deleted file mode 100644 index ed8653d3a7..0000000000 --- a/source4/scripting/ejs/smbcalls_reg.c +++ /dev/null @@ -1,90 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide hooks into smbd C calls from ejs scripts - - Copyright (C) Jelmer Vernooij 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 <http://www.gnu.org/licenses/>. -*/ - -#include "includes.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/appweb/ejs/ejs.h" -#include "dsdb/samdb/samdb.h" -#include "librpc/ndr/libndr.h" -#include "lib/registry/registry.h" - -/* - get the connected db - */ -static struct registry_context *ejs_get_reg_context(int eid) -{ - struct registry_context *rctx = (struct registry_context *)mprGetThisPtr(eid, "registry"); - if (rctx == NULL) { - ejsSetErrorMsg(eid, "unable to find registry"); - } - return rctx; -} - -static int ejs_apply_patchfile(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct registry_context *rctx; - WERROR error; - - /* validate arguments */ - if (argc != 1) { - ejsSetErrorMsg(eid, "reg.apply_patchfile invalid number of arguments"); - return -1; - } - - rctx = ejs_get_reg_context(eid); - if (rctx == NULL) { - return -1; - } - - error = reg_diff_apply(rctx, mprToString(argv[0])); - - mpr_Return(eid, mprWERROR(error)); - - return 0; -} - -/* - initialise registry ejs subsystem -*/ -static int ejs_reg_open(MprVarHandle eid, int argc, struct MprVar **argv) -{ - struct MprVar *reg = mprInitObject(eid, "registry", argc, argv); - struct registry_context *rctx; - WERROR error; - - error = reg_open_samba(mprMemCtx(), &rctx, mprEventCtx(), mprLpCtx(), NULL, NULL); - SMB_ASSERT(W_ERROR_IS_OK(error)); - - mprSetPtrChild(reg, "registry", rctx); - mprSetCFunction(reg, "apply_patchfile", ejs_apply_patchfile); - - return 0; -} - - -/* - setup C functions that be called from ejs -*/ -NTSTATUS smb_setup_ejs_reg(void) -{ - ejsDefineCFunction(-1, "reg_open", ejs_reg_open, NULL, MPR_VAR_SCRIPT_HANDLE); - return NT_STATUS_OK; -} diff --git a/source4/scripting/ejs/smbcalls_rpc.c b/source4/scripting/ejs/smbcalls_rpc.c deleted file mode 100644 index 94774d708b..0000000000 --- a/source4/scripting/ejs/smbcalls_rpc.c +++ /dev/null @@ -1,385 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - provide interfaces to rpc 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 <http://www.gnu.org/licenses/>. -*/ - -#include "includes.h" -#include "scripting/ejs/smbcalls.h" -#include "lib/appweb/ejs/ejs.h" -#include "librpc/gen_ndr/echo.h" -#include "lib/cmdline/popt_common.h" -#include "lib/messaging/irpc.h" -#include "scripting/ejs/ejsrpc.h" -#include "lib/util/dlinklist.h" -#include "lib/events/events.h" -#include "librpc/ndr/ndr_table.h" -#include "auth/credentials/credentials.h" -#include "librpc/rpc/dcerpc.h" -#include "cluster/cluster.h" - -/* - state of a irpc 'connection' -*/ -struct ejs_irpc_connection { - const char *server_name; - struct server_id *dest_ids; - struct messaging_context *msg_ctx; -}; - -/* - messaging clients need server IDs as well ... - */ -#define EJS_ID_BASE 0x30000000 - -/* - setup a context for talking to a irpc server - example: - status = irpc.connect("smb_server"); -*/ -static int ejs_irpc_connect(MprVarHandle eid, int argc, char **argv) -{ - NTSTATUS status; - int i; - struct event_context *ev; - struct ejs_irpc_connection *p; - struct MprVar *this = mprGetProperty(ejsGetLocalObject(eid), "this", 0); - - /* validate arguments */ - if (argc != 1) { - ejsSetErrorMsg(eid, "rpc_connect invalid arguments"); - return -1; - } - - p = talloc(this, struct ejs_irpc_connection); - if (p == NULL) { - return -1; - } - - p->server_name = argv[0]; - - ev = mprEventCtx(); - - /* create a messaging context, looping as we have no way to - allocate temporary server ids automatically */ - for (i=0;i<10000;i++) { - p->msg_ctx = messaging_init(p, - lp_messaging_path(p, mprLpCtx()), - cluster_id(EJS_ID_BASE, i), - lp_iconv_convenience(mprLpCtx()), - ev); - if (p->msg_ctx) break; - } - if (p->msg_ctx == NULL) { - ejsSetErrorMsg(eid, "irpc_connect unable to create a messaging context"); - talloc_free(p); - return -1; - } - - p->dest_ids = irpc_servers_byname(p->msg_ctx, p, p->server_name); - if (p->dest_ids == NULL || p->dest_ids[0].id == 0) { - talloc_free(p); - status = NT_STATUS_OBJECT_NAME_NOT_FOUND; - } else { - mprSetPtrChild(this, "irpc", p); - status = NT_STATUS_OK; - } - - mpr_Return(eid, mprNTSTATUS(status)); - return 0; -} - - -/* - connect to an rpc server - examples: - status = rpc.connect("ncacn_ip_tcp:localhost"); - status = rpc.connect("ncacn_ip_tcp:localhost", "pipe_name"); -*/ -static int ejs_rpc_connect(MprVarHandle eid, int argc, char **argv) -{ - const char *binding, *pipe_name; - const struct ndr_interface_table *iface; - NTSTATUS status; - struct dcerpc_pipe *p; - struct cli_credentials *creds; - struct event_context *ev; - struct MprVar *this = mprGetProperty(ejsGetLocalObject(eid), "this", 0); - struct MprVar *credentials; - - /* validate arguments */ - if (argc < 1) { - ejsSetErrorMsg(eid, "rpc_connect invalid arguments"); - return -1; - } - - binding = argv[0]; - if (strchr(binding, ':') == NULL) { - /* its an irpc connect */ - return ejs_irpc_connect(eid, argc, argv); - } - - if (argc > 1) { - pipe_name = argv[1]; - } else { - pipe_name = mprToString(mprGetProperty(this, "pipe_name", NULL)); - } - - iface = ndr_table_by_name(pipe_name); - if (iface == NULL) { - status = NT_STATUS_OBJECT_NAME_INVALID; - goto done; - } - - credentials = mprGetProperty(this, "credentials", NULL); - if (credentials) { - creds = (struct cli_credentials *) - mprGetPtr(credentials, "creds"); - } else { - creds = cmdline_credentials; - } - if (creds == NULL) { - creds = cli_credentials_init(mprMemCtx()); - cli_credentials_set_anonymous(creds); - } - - ev = mprEventCtx(); - - status = dcerpc_pipe_connect(this, &p, binding, iface, creds, ev, - mprLpCtx()); - if (!NT_STATUS_IS_OK(status)) goto done; - - /* callers don't allocate ref vars in the ejs interface */ - p->conn->flags |= DCERPC_NDR_REF_ALLOC; - - /* by making the pipe a child of the connection variable, it will - auto close when it goes out of scope in the script */ - mprSetPtrChild(this, "pipe", p); - -done: - mpr_Return(eid, mprNTSTATUS(status)); - return 0; -} - - -/* - make an irpc call - called via the same interface as rpc -*/ -static int ejs_irpc_call(int eid, struct MprVar *io, - const struct ndr_interface_table *iface, int callnum, - ejs_pull_function_t ejs_pull, ejs_push_function_t ejs_push) -{ - NTSTATUS status; - void *ptr; - struct ejs_rpc *ejs; - const struct ndr_interface_call *call; - struct ejs_irpc_connection *p; - struct irpc_request **reqs; - int i, count; - struct MprVar *results; - - p = (struct ejs_irpc_connection *)mprGetThisPtr(eid, "irpc"); - - ejs = talloc(mprMemCtx(), struct ejs_rpc); - if (ejs == NULL) { - status = NT_STATUS_NO_MEMORY; - goto done; - } - - call = &iface->calls[callnum]; - - ejs->eid = eid; - ejs->callname = call->name; - - /* allocate the C structure */ - ptr = talloc_zero_size(ejs, call->struct_size); - if (ptr == NULL) { - status = NT_STATUS_NO_MEMORY; - goto done; - } - - /* convert the mpr object into a C structure */ - status = ejs_pull(ejs, io, ptr); - if (!NT_STATUS_IS_OK(status)) { - goto done; - } - - for (count=0;p->dest_ids[count].id;count++) /* noop */ ; - - /* we need to make a call per server */ - reqs = talloc_array(ejs, struct irpc_request *, count); - if (reqs == NULL) { - status = NT_STATUS_NO_MEMORY; - goto done; - } - - /* make the actual calls */ - for (i=0;i<count;i++) { - reqs[i] = irpc_call_send(p->msg_ctx, p->dest_ids[i], - iface, callnum, ptr, ptr); - if (reqs[i] == NULL) { - status = NT_STATUS_NO_MEMORY; - goto done; - } - talloc_steal(reqs, reqs[i]); - } - - mprSetVar(io, "results", mprObject("results")); - results = mprGetProperty(io, "results", NULL); - - /* and receive the results, placing them in io.results[i] */ - for (i=0;i<count;i++) { - struct MprVar *output; - - status = irpc_call_recv(reqs[i]); - if (!NT_STATUS_IS_OK(status)) { - goto done; - } - status = ejs_push(ejs, io, ptr); - if (!NT_STATUS_IS_OK(status)) { - goto done; - } - - /* add to the results array */ - output = mprGetProperty(io, "output", NULL); - if (output) { - char idx[16]; - mprItoa(i, idx, sizeof(idx)); - mprSetProperty(results, idx, output); - mprDeleteProperty(io, "output"); - } - } - mprSetVar(results, "length", mprCreateIntegerVar(i)); - -done: - talloc_free(ejs); - mpr_Return(eid, mprNTSTATUS(status)); - if (NT_STATUS_EQUAL(status, NT_STATUS_INTERNAL_ERROR)) { - return -1; - } - return 0; -} - - -/* - backend code for making an rpc call - this is called from the pidl generated ejs - code -*/ - int ejs_rpc_call(int eid, int argc, struct MprVar **argv, - const struct ndr_interface_table *iface, int callnum, - ejs_pull_function_t ejs_pull, ejs_push_function_t ejs_push) -{ - struct MprVar *io; - struct dcerpc_pipe *p; - NTSTATUS status; - void *ptr; - struct rpc_request *req; - struct ejs_rpc *ejs; - const struct ndr_interface_call *call; - - if (argc != 1 || argv[0]->type != MPR_TYPE_OBJECT) { - ejsSetErrorMsg(eid, "rpc_call invalid arguments"); - return -1; - } - - io = argv[0]; - - if (mprGetThisPtr(eid, "irpc")) { - /* its an irpc call */ - return ejs_irpc_call(eid, io, iface, callnum, ejs_pull, ejs_push); - } - - /* get the pipe info */ - p = mprGetThisPtr(eid, "pipe"); - if (p == NULL) { - ejsSetErrorMsg(eid, "rpc_call invalid pipe"); - return -1; - } - - ejs = talloc(mprMemCtx(), struct ejs_rpc); - if (ejs == NULL) { - status = NT_STATUS_NO_MEMORY; - goto done; - } - - call = &iface->calls[callnum]; - - ejs->eid = eid; - ejs->callname = call->name; - - /* allocate the C structure */ - ptr = talloc_zero_size(ejs, call->struct_size); - if (ptr == NULL) { - status = NT_STATUS_NO_MEMORY; - goto done; - } - - /* convert the mpr object into a C structure */ - status = ejs_pull(ejs, io, ptr); - if (!NT_STATUS_IS_OK(status)) { - goto done; - } - - /* make the actual call */ - req = dcerpc_ndr_request_send(p, NULL, iface, callnum, ptr, ptr); - - /* if requested, print the structure */ - if (p->conn->flags & DCERPC_DEBUG_PRINT_IN) { - ndr_print_function_debug(call->ndr_print, call->name, NDR_IN, ptr); - } - - if (req == NULL) { - status = NT_STATUS_NO_MEMORY; - goto done; - } - - status = dcerpc_ndr_request_recv(req); - if (!NT_STATUS_IS_OK(status)) { - goto done; - } - - /* print the 'out' structure, if needed */ - if (p->conn->flags & DCERPC_DEBUG_PRINT_OUT) { - ndr_print_function_debug(call->ndr_print, call->name, NDR_OUT, ptr); - } - - status = ejs_push(ejs, io, ptr); - -done: - talloc_free(ejs); - mpr_Return(eid, mprNTSTATUS(status)); - if (NT_STATUS_EQUAL(status, NT_STATUS_INTERNAL_ERROR)) { - return -1; - } - return 0; -} - -/* - hook called by generated RPC interfaces at the end of their init routines - used to add generic operations on the pipe -*/ -int ejs_rpc_init(struct MprVar *obj, const char *name) -{ - ndr_table_init(); - - mprSetStringCFunction(obj, "connect", ejs_rpc_connect); - if (mprGetProperty(obj, "pipe_name", NULL) == NULL) { - mprSetVar(obj, "pipe_name", mprString(name)); - } - return 0; -} diff --git a/source4/scripting/ejs/smbscript.c b/source4/scripting/ejs/smbscript.c index 9ed4aa490f..db9fc9affa 100644 --- a/source4/scripting/ejs/smbscript.c +++ b/source4/scripting/ejs/smbscript.c @@ -26,7 +26,7 @@ #include "scripting/ejs/smbcalls.h" #include "auth/gensec/gensec.h" #include "ldb/include/ldb.h" -#include "dynconfig.h" +#include "dynconfig/dynconfig.h" static EjsId eid; diff --git a/source4/scripting/libjs/auth.js b/source4/scripting/libjs/auth.js deleted file mode 100644 index 3fe81d0ea7..0000000000 --- a/source4/scripting/libjs/auth.js +++ /dev/null @@ -1,18 +0,0 @@ -/* - auth js library functions - Copyright Andrew Tridgell 2005 - released under the GNU GPL version 3 or later -*/ - - -/* - get a list of domains for SWAT authentication -*/ -function getDomainList() -{ - var ret = new Array(2); - var lp = loadparm_init(); - ret[0] = "System User"; - ret[1] = lp.get("workgroup"); - return ret; -} diff --git a/source4/scripting/libjs/base.js b/source4/scripting/libjs/base.js index d861073a07..790dfeb3e0 100644 --- a/source4/scripting/libjs/base.js +++ b/source4/scripting/libjs/base.js @@ -21,48 +21,6 @@ function printf() } /* - helper function to setup a rpc io object, ready for input -*/ -function irpcObj() -{ - var o = new Object(); - o.input = new Object(); - return o; -} - -/* - check that a status result is OK -*/ -function check_status_ok(status) -{ - if (status.is_ok != true) { - printVars(status); - } - assert(status.is_ok == true); -} - -/* - check that two arrays are equal -*/ -function check_array_equal(a1, a2) -{ - assert(a1.length == a2.length); - for (i=0; i<a1.length; i++) { - assert(a1[i] == a2[i]); - } -} - -/* - check that an array is all zeros -*/ -function check_array_zero(a) -{ - for (i=0; i<a.length; i++) { - assert(a[i] == 0); - } -} - -/* substitute strings of the form ${NAME} in str, replacing with substitutions from subobj */ @@ -90,14 +48,3 @@ function substitute_var(str, subobj) } return join("", list); } - -/* - return "s" if a number should be shown as plural -*/ -function plural(n) -{ - if (n == 1) { - return ""; - } - return "s"; -} diff --git a/source4/scripting/libjs/encoder.js b/source4/scripting/libjs/encoder.js deleted file mode 100644 index 6cb780c00d..0000000000 --- a/source4/scripting/libjs/encoder.js +++ /dev/null @@ -1,116 +0,0 @@ -/* - server side js functions for encoding/decoding objects into linear strings - - Copyright Andrew Tridgell 2005 - released under the GNU GPL Version 3 or later -*/ -/* - usage: - - enc = encodeObject(obj); - obj = decodeObject(enc); - - The encoded format of the object is a string that is safe to - use in URLs - - Note that only data elements are encoded, not functions -*/ - -function __count_members(o) { - var i, count = 0; - for (i in o) { - count++; - } - if (o.length != undefined) { - count++; - } - return count; -} - -function __replace(str, old, rep) { - var s = string_init(); - var a = s.split(old, str); - var j = s.join(rep, a); - return s.join(rep, a); -} - -function encodeElement(e, name) { - var t = typeof(e); - var r; - var s = string_init(); - if (t == 'object' && e == null) { - t = 'null'; - } - if (t == 'object') { - r = s.sprintf("%s:%s:%s", name, t, encodeObject(e)); - } else if (t == "string") { - var enc = s.encodeURIComponent(e); - var rep = __replace(enc, '%', '#'); - r = s.sprintf("%s:%s:%s:", - name, t, __replace(s.encodeURIComponent(e),'%','#')); - } else if (t == "boolean" || t == "number") { - r = s.sprintf("%s:%s:%s:", name, t, "" + e); - } else if (t == "undefined" || t == "null") { - r = s.sprintf("%s:%s:", name, t); - } else if (t == "pointer") { - r = s.sprintf("%s:string:(POINTER):", name); - } else { - println("Unable to linearise type " + t); - r = ""; - } - return r; -} - -function encodeObject(o) { - var s = string_init(); - var i, r = s.sprintf("%u:", __count_members(o)); - for (i in o) { - r = r + encodeElement(o[i], i); - } - if (o.length != undefined) { - r = r + encodeElement(o.length, 'length'); - } - return r; -} - -function decodeObjectArray(a) { - var s = string_init(); - var o = new Object(); - var i, count = a[a.i]; a.i++; - for (i=0;i<count;i++) { - var name = a[a.i]; a.i++; - var type = a[a.i]; a.i++; - var value; - if (type == 'object') { - o[name] = decodeObjectArray(a); - } else if (type == "string") { - value = s.decodeURIComponent(__replace(a[a.i],'#','%')); a.i++; - o[name] = value; - } else if (type == "boolean") { - value = a[a.i]; a.i++; - if (value == 'true') { - o[name] = true; - } else { - o[name] = false; - } - } else if (type == "undefined") { - o[name] = undefined; - } else if (type == "null") { - o[name] = null; - } else if (type == "number") { - value = a[a.i]; a.i++; - o[name] = value + 0; - } else { - println("Unable to delinearise type " + t); - assert(t == "supported type"); - } - } - return o; -} - -function decodeObject(str) { - var s = string_init(); - var a = s.split(':', str); - a.i = 0; - return decodeObjectArray(a); -} diff --git a/source4/scripting/libjs/management.js b/source4/scripting/libjs/management.js deleted file mode 100644 index 4a43275156..0000000000 --- a/source4/scripting/libjs/management.js +++ /dev/null @@ -1,157 +0,0 @@ -/* - backend code for Samba4 management - Copyright Andrew Tridgell 2005 - Released under the GNU GPL version 3 or later -*/ - - -/* - return a list of current sessions -*/ -function smbsrv_sessions() -{ - var irpc = irpc_init(); - status = irpc.connect("smb_server"); - if (status.is_ok != true) { - return undefined; - } - - var io = irpcObj(); - io.input.level = irpc.SMBSRV_INFO_SESSIONS; - status = irpc.smbsrv_information(io); - if (status.is_ok != true) { - return undefined; - } - - /* gather the results into a single array */ - var i, count=0, ret = new Array(0); - for (i=0;i<io.results.length;i++) { - var sessions = io.results[i].info.sessions.sessions; - var j; - for (j=0;j<sessions.length;j++) { - ret[count] = sessions[j]; - count++; - } - } - return ret; -} - -/* - return a list of current tree connects -*/ -function smbsrv_tcons() -{ - var irpc = irpc_init(); - status = irpc.connect("smb_server"); - if (status.is_ok != true) { - return undefined; - } - - var io = irpcObj(); - io.input.level = irpc.SMBSRV_INFO_TCONS; - status = irpc.smbsrv_information(io); - if (status.is_ok != true) { - return undefined; - } - - /* gather the results into a single array */ - var i, count=0, ret = new Object(); - for (i=0;i<io.results.length;i++) { - var tcons = io.results[i].info.tcons.tcons; - var j; - for (j=0;j<tcons.length;j++) { - ret[count] = tcons[j]; - count++; - } - } - ret.length = count; - return ret; -} - -/* - return nbtd statistics -*/ -function nbtd_statistics() -{ - var irpc = irpc_init(); - status = irpc.connect("nbt_server"); - if (status.is_ok != true) { - return undefined; - } - - var io = irpcObj(); - io.input.level = irpc.NBTD_INFO_STATISTICS; - status = irpc.nbtd_information(io); - if (status.is_ok != true) { - return undefined; - } - return io.results[0].info.stats; -} - -/* - see if a service is enabled -*/ -function service_enabled(name) -{ - var lp = loadparm_init(); - var services = lp.get("server services"); - var i; - for (i=0;i<services.length;i++) { - if (services[i] == name) { - return true; - } - } - return false; -} - -/* - show status of a server -*/ -function server_status(name) -{ - var i; - var io; - var irpc = irpc_init(); - - if (!service_enabled(name)) { - return "DISABLED"; - } - - status = irpc.connect(name + "_server"); - if (status.is_ok != true) { - return "DOWN"; - } - - var io = irpcObj(); - status = irpc.irpc_uptime(io); - if (status.is_ok != true) { - return "NOT RESPONDING"; - } - - return "RUNNING"; -} - -/* - show status of a stream server -*/ -function stream_server_status(name) -{ - var irpc = irpc_init(); - - if (!service_enabled(name)) { - return "DISABLED"; - } - status = irpc.connect(name + "_server"); - if (status.is_ok != true) { - return "0 connections"; - } - - var io = irpcObj(); - status = irpc.irpc_uptime(io); - if (status.is_ok != true) { - return "NOT RESPONDING"; - } - - var n = io.results.length; - return sprintf("%u connection%s", n, plural(n)); -} diff --git a/source4/scripting/libjs/samr.js b/source4/scripting/libjs/samr.js deleted file mode 100644 index 6e8c70af3c..0000000000 --- a/source4/scripting/libjs/samr.js +++ /dev/null @@ -1,170 +0,0 @@ -/* - samr rpc utility functions - Copyright Andrew Tridgell 2005 - released under the GNU GPL version 3 or later -*/ - -if (global["HAVE_SAMR_JS"] != undefined) { - return; -} -HAVE_SAMR_JS=1 - -/* - return a list of names and indexes from a samArray -*/ -function samArray(output) -{ - var list = new Array(output.num_entries); - if (output.sam == NULL) { - return list; - } - var i, entries = output.sam.entries; - for (i=0;i<output.num_entries;i++) { - list[i] = new Object(); - list[i].name = entries[i].name; - list[i].idx = entries[i].idx; - } - return list; -} - -/* - connect to the sam database -*/ -function samrConnect(conn) -{ - security_init(conn); - var io = irpcObj(); - io.input.system_name = NULL; - io.input.access_mask = conn.SEC_FLAG_MAXIMUM_ALLOWED; - var status = conn.samr_Connect2(io); - check_status_ok(status); - return io.output.connect_handle; -} - -/* - close a handle -*/ -function samrClose(conn, handle) -{ - var io = irpcObj(); - io.input.handle = handle; - var status = conn.samr_Close(io); - check_status_ok(status); -} - -/* - get the sid for a domain -*/ -function samrLookupDomain(conn, handle, domain) -{ - var io = irpcObj(); - io.input.connect_handle = handle; - io.input.domain_name = domain; - var status = conn.samr_LookupDomain(io); - check_status_ok(status); - return io.output.sid; -} - -/* - open a domain by sid -*/ -function samrOpenDomain(conn, handle, sid) -{ - var io = irpcObj(); - io.input.connect_handle = handle; - io.input.access_mask = conn.SEC_FLAG_MAXIMUM_ALLOWED; - io.input.sid = sid; - var status = conn.samr_OpenDomain(io); - check_status_ok(status); - return io.output.domain_handle; -} - -/* - open a user by rid -*/ -function samrOpenUser(conn, handle, rid) -{ - var io = irpcObj(); - io.input.domain_handle = handle; - io.input.access_mask = conn.SEC_FLAG_MAXIMUM_ALLOWED; - io.input.rid = rid; - var status = conn.samr_OpenUser(io); - check_status_ok(status); - return io.output.user_handle; -} - -/* - return a list of all users -*/ -function samrEnumDomainUsers(conn, dom_handle) -{ - var io = irpcObj(); - io.input.domain_handle = dom_handle; - io.input.resume_handle = 0; - io.input.acct_flags = 0; - io.input.max_size = -1; - var status = conn.samr_EnumDomainUsers(io); - check_status_ok(status); - return samArray(io.output); -} - -/* - return a list of all groups -*/ -function samrEnumDomainGroups(conn, dom_handle) -{ - var io = irpcObj(); - io.input.domain_handle = dom_handle; - io.input.resume_handle = 0; - io.input.acct_flags = 0; - io.input.max_size = -1; - var status = conn.samr_EnumDomainGroups(io); - check_status_ok(status); - return samArray(io.output); -} - -/* - return a list of domains -*/ -function samrEnumDomains(conn, handle) -{ - var io = irpcObj(); - io.input.connect_handle = handle; - io.input.resume_handle = 0; - io.input.buf_size = -1; - var status = conn.samr_EnumDomains(io); - check_status_ok(status); - return samArray(io.output); -} - -/* - return information about a user -*/ -function samrQueryUserInfo(conn, user_handle, level) -{ - var r, io = irpcObj(); - io.input.user_handle = user_handle; - io.input.level = level; - var status = conn.samr_QueryUserInfo(io); - check_status_ok(status); - return io.output.info.info3; -} - - -/* - fill a user array with user information from samrQueryUserInfo -*/ -function samrFillUserInfo(conn, dom_handle, users, level) -{ - var i; - for (i=0;i<users.length;i++) { - var r, user_handle, info; - user_handle = samrOpenUser(conn, dom_handle, users[i].idx); - info = samrQueryUserInfo(conn, user_handle, level); - info.name = users[i].name; - info.idx = users[i].idx; - users[i] = info; - samrClose(conn, user_handle); - } -} - diff --git a/source4/scripting/libjs/server_call.js b/source4/scripting/libjs/server_call.js deleted file mode 100644 index 46414a90dd..0000000000 --- a/source4/scripting/libjs/server_call.js +++ /dev/null @@ -1,83 +0,0 @@ -/* - server side js functions for handling async calls from js clients - - Copyright Andrew Tridgell 2005 - released under the GNU GPL Version 3 or later -*/ - -libinclude("encoder.js"); - -/* - register a new call -*/ -function __register_call(name, func) -{ - var c = this; - c.calls[name] = func; -} - -/* - run a call sent from the client, and output the returned object (if any) -*/ -function __run_call() { - var c = this; - var name = form['ajaj_func']; - if (name == undefined) { - /* no function to run */ - return; - } - var args = form['ajaj_args']; - if (args == undefined) { - println("no function arguments given in run_call"); - exit(0); - } - args = decodeObject(args); - if (c.calls[name] == undefined) { - println("undefined remote call " + name); - exit(0); - } - var f = c.calls[name]; - var res; - /* oh what a hack - should write a varargs ejs helper */ - if (args.length == 0) { - res = f(); - } else if (args.length == 1) { - res = f(args[0]); - } else if (args.length == 2) { - res = f(args[0], args[1]); - } else if (args.length == 3) { - res = f(args[0], args[1], args[2]); - } else if (args.length == 4) { - res = f(args[0], args[1], args[2], args[3]); - } else if (args.length == 5) { - res = f(args[0], args[1], args[2], args[3], args[4]); - } else if (args.length == 6) { - res = f(args[0], args[1], args[2], args[3], args[4], args[5]); - } else if (args.length == 7) { - res = f(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - } else if (args.length == 8) { - res = f(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); - } else { - println("too many arguments for remote call: " + name); - exit(0); - } - var repobj = new Object(); - repobj.res = res; - write(encodeObject(repobj)); - exit(0); -} - - - -/* - initialise a server call object -*/ -function servCallObj() -{ - var c = new Object(); - c.add = __register_call; - c.run = __run_call; - c.calls = new Object(); - return c; -} - diff --git a/source4/scripting/libjs/winreg.js b/source4/scripting/libjs/winreg.js deleted file mode 100644 index 9db415694d..0000000000 --- a/source4/scripting/libjs/winreg.js +++ /dev/null @@ -1,291 +0,0 @@ -/* - winreg rpc utility functions - Copyright Andrew Tridgell 2005 - released under the GNU GPL version 3 or later -*/ - -libinclude("base.js"); - -/* - close a handle -*/ -function __winreg_close(handle) -{ - var io = irpcObj(); - io.input.handle = handle; - this.winreg_CloseKey(io); -} - - -/* - open a hive -*/ -function __winreg_open_hive(hive) -{ - var io = irpcObj(); - io.input.system_name = NULL; - io.input.access_mask = this.SEC_FLAG_MAXIMUM_ALLOWED; - var status; - if (hive == "HKLM") { - status = this.winreg_OpenHKLM(io); - } else if (hive == "HKCR") { - status = this.winreg_OpenHKCR(io); - } else if (hive == "HKPD") { - status = this.winreg_OpenHKPD(io); - } else if (hive == "HKU") { - status = this.winreg_OpenHKU(io); - } else { - this._last_error = "Unknown hive " + hive; - return undefined; - } - if (!status.is_ok) { - return undefined; - } - return io.output.handle; -} - -/* - open a handle to a path -*/ -function __winreg_open_path(path) -{ - var s = string_init(); - var i, components = s.split('\\', path); - - /* cope with a leading slash */ - if (components[0] == '') { - for (i=0;i<(components.length-1);i++) { - components[i] = components[i+1]; - } - delete(components[i]); - } - - if (components.length == 0) { - return undefined; - } - - var handle = this.open_hive(components[0]); - if (handle == undefined) { - return undefined; - } - - if (components.length == 1) { - return handle; - } - - var hpath = components[1]; - - for (i=2;i<components.length;i++) { - hpath = hpath + "\\" + components[i]; - } - - io = irpcObj(); - io.input.parent_handle = handle; - io.input.keyname = hpath; - io.input.unknown = 0; - io.input.access_mask = this.SEC_FLAG_MAXIMUM_ALLOWED; - var status = this.winreg_OpenKey(io); - - this.close(handle); - - if (!status.is_ok) { - return undefined; - } - if (io.output.result != "WERR_OK") { - return undefined; - } - - return io.output.handle; -} - -/* - return a list of keys for a winreg server given a path - usage: - list = reg.enum_path(path); -*/ -function __winreg_enum_path(path) -{ - var list = new Array(0); - - if (path == null || path == "\\" || path == "") { - return new Array("HKLM", "HKU"); - } - - var handle = this.open_path(path); - if (handle == undefined) { - return undefined; - } - - var io = irpcObj(); - io.input.handle = handle; - io.input.name = new Object(); - io.input.name.length = 0; - io.input.name.size = 32; - io.input.name.name = NULL; - io.input.keyclass = new Object(); - io.input.keyclass.length = 0; - io.input.keyclass.size = 1024; - io.input.keyclass.name = NULL; - io.input.last_changed_time = 0; - - var idx = 0; - for (idx=0;idx >= 0;idx++) { - io.input.enum_index = idx; - var status = this.winreg_EnumKey(io); - if (!status.is_ok) { - this.close(handle); - return list; - } - var out = io.output; - if (out.result == "WERR_MORE_DATA") { - io.input.name.size = io.input.name.size * 2; - idx--; - if (io.input.name.size > 32000) { - this.close(handle); - return list; - } - continue; - } - if (out.result != "WERR_OK") { - this.close(handle); - return list; - } - list[list.length] = out.name.name; - } - - this.close(handle); - return list; -} - - -/* - return a list of values for a winreg server given a path - usage: - list = reg.enum_values(path); - - each returned list element is an object containing a name, a - type and a value -*/ -function __winreg_enum_values(path) -{ - var data = datablob_init(); - var list = new Array(0); - - var handle = this.open_path(path); - if (handle == undefined) { - return undefined; - } - - var io = irpcObj(); - io.input.handle = handle; - io.input.name = new Object(); - io.input.name.length = 0; - io.input.name.size = 128; - io.input.name.name = ""; - io.input.type = 0; - io.input.value = new Array(0); - io.input.size = 1024; - io.input.length = 0; - - var idx; - for (idx=0;idx >= 0;idx++) { - io.input.enum_index = idx; - var status = this.winreg_EnumValue(io); - if (!status.is_ok) { - this.close(handle); - return list; - } - var out = io.output; - if (out.result == "WERR_MORE_DATA") { - io.input.size = io.input.size * 2; - io.input.name.size = io.input.name.size * 2; - idx--; - /* limit blobs to 1M */ - if (io.input.size > 1000000) { - this.close(handle); - return list; - } - continue; - } - if (out.result != "WERR_OK") { - this.close(handle); - return list; - } - var el = new Object(); - el.name = out.name.name; - el.type = out.type; - el.rawvalue = out.value; - el.value = data.regToVar(el.rawvalue, el.type); - el.size = out.size; - list[list.length] = el; - } - - this.close(handle); - return list; -} - - -/* - create a new key - ok = reg.create_key(path, key); -*/ -function __winreg_create_key(path, key) -{ - var handle = this.open_path(path); - if (handle == undefined) { - return undefined; - } - - var io = irpcObj(); - io.input.handle = handle; - io.input.name = key; - io.input.keyclass = NULL; - io.input.options = 0; - io.input.access_mask = this.SEC_FLAG_MAXIMUM_ALLOWED; - io.input.secdesc = NULL; - io.input.action_taken = 0; - - var status = this.winreg_CreateKey(io); - this.close(handle); - if (!status.is_ok) { - return false; - } - if (io.output.result != "WERR_OK") { - return false; - } - this.close(io.output.new_handle); - return true; -} - - -/* - return a string for a winreg type -*/ -function __winreg_typestring(type) -{ - return this.typenames[type]; -} - -/* - initialise the winreg lib, returning an object -*/ -function winregObj() -{ - var reg = winreg_init(); - security_init(reg); - - reg.typenames = new Array("REG_NONE", "REG_SZ", "REG_EXPAND_SZ", "REG_BINARY", - "REG_DWORD", "REG_DWORD_BIG_ENDIAN", "REG_LINK", "REG_MULTI_SZ", - "REG_RESOURCE_LIST", "REG_FULL_RESOURCE_DESCRIPTOR", - "REG_RESOURCE_REQUIREMENTS_LIST", "REG_QWORD"); - - reg.close = __winreg_close; - reg.open_hive = __winreg_open_hive; - reg.open_path = __winreg_open_path; - reg.enum_path = __winreg_enum_path; - reg.enum_values = __winreg_enum_values; - reg.create_key = __winreg_create_key; - reg.typestring = __winreg_typestring; - - return reg; -} diff --git a/source4/scripting/python/config.m4 b/source4/scripting/python/config.m4 index 1a86951bfb..b599aaefb0 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.31) +AC_PROG_SWIG(1.3.35) AC_PATH_PROG([PYTHON],[python[$PYTHON_VERSION]]) if test -z "$PYTHON"; then diff --git a/source4/scripting/python/config.mk b/source4/scripting/python/config.mk index 73607eb76c..b494ee6e8d 100644 --- a/source4/scripting/python/config.mk +++ b/source4/scripting/python/config.mk @@ -29,7 +29,9 @@ $(foreach pyfile, $(_PY_FILES),$(eval $(call python_py_module_template,$(patsubs $(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 --no-private samba dcerpc tdb ldb subunit + PYTHONPATH=$(pythonbuilddir) epydoc $(EPYDOC_OPTIONS) samba tdb ldb subunit install:: installpython diff --git a/source4/scripting/python/examples/samr.py b/source4/scripting/python/examples/samr.py new file mode 100755 index 0000000000..1f2afbe688 --- /dev/null +++ b/source4/scripting/python/examples/samr.py @@ -0,0 +1,114 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Unix SMB/CIFS implementation. +# Copyright © Jelmer Vernooij <jelmer@samba.org> 2008 +# +# Based on samr.js © Andrew Tridgell <tridge@samba.org> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +import sys + +sys.path.insert(0, "bin/python") + +from samba.dcerpc import samr, security, lsa + +def FillUserInfo(samr, dom_handle, users, level): + """fill a user array with user information from samrQueryUserInfo""" + for i in range(len(users)): + user_handle = samr.OpenUser(handle, security.SEC_FLAG_MAXIMUM_ALLOWED, users[i].idx) + info = samr.QueryUserInfo(user_handle, level) + info.name = users[i].name + info.idx = users[i].idx + users[i] = info + samr.Close(user_handle) + +def toArray((handle, array, num_entries)): + ret = [] + for x in range(num_entries): + ret.append((array.entries[x].idx, array.entries[x].name)) + return ret + + +def test_Connect(samr): + """test the samr_Connect interface""" + print "Testing samr_Connect" + return samr.Connect2(None, security.SEC_FLAG_MAXIMUM_ALLOWED) + +def test_LookupDomain(samr, handle, domain): + """test the samr_LookupDomain interface""" + print "Testing samr_LookupDomain" + return samr.LookupDomain(handle, domain) + +def test_OpenDomain(samr, handle, sid): + """test the samr_OpenDomain interface""" + print "Testing samr_OpenDomain" + return samr.OpenDomain(handle, security.SEC_FLAG_MAXIMUM_ALLOWED, sid) + +def test_EnumDomainUsers(samr, dom_handle): + """test the samr_EnumDomainUsers interface""" + print "Testing samr_EnumDomainUsers" + users = toArray(samr.EnumDomainUsers(dom_handle, 0, 0, -1)) + print "Found %d users" % len(users) + for idx, user in users: + print "\t%s\t(%d)" % (user, idx) + +def test_EnumDomainGroups(samr, dom_handle): + """test the samr_EnumDomainGroups interface""" + print "Testing samr_EnumDomainGroups" + groups = toArray(samr.EnumDomainGroups(dom_handle, 0, 0)) + print "Found %d groups" % len(groups) + for idx, group in groups: + print "\t%s\t(%d)" % (group, idx) + +def test_domain_ops(samr, dom_handle): + """test domain specific ops""" + test_EnumDomainUsers(samr, dom_handle) + test_EnumDomainGroups(samr, dom_handle) + +def test_EnumDomains(samr, handle): + """test the samr_EnumDomains interface""" + print "Testing samr_EnumDomains" + + domains = toArray(samr.EnumDomains(handle, 0, -1)) + print "Found %d domains" % len(domains) + for idx, domain in domains: + print "\t%s (%d)" % (domain, idx) + for idx, domain in domains: + print "Testing domain %s" % domain + sid = samr.LookupDomain(handle, domain) + dom_handle = test_OpenDomain(samr, handle, sid) + test_domain_ops(samr, dom_handle) + samr.Close(dom_handle) + +if len(sys.argv) != 2: + print "Usage: samr.js <BINDING>" + sys.exit(1) + +binding = sys.argv[1] + +print "Connecting to %s" % binding +try: + samr = samr.samr(binding) +except Exception, e: + print "Failed to connect to %s: %s" % (binding, e.message) + sys.exit(1) + +handle = test_Connect(samr) +test_EnumDomains(samr, handle) +samr.Close(handle) + +print "All OK" diff --git a/source4/scripting/bin/winreg.py b/source4/scripting/python/examples/winreg.py index 19d39e56ab..80b48ecfd7 100755 --- a/source4/scripting/bin/winreg.py +++ b/source4/scripting/python/examples/winreg.py @@ -11,7 +11,7 @@ import sys # Find right directory when running from source tree sys.path.insert(0, "bin/python") -import winreg +from samba.dcerpc import winreg import optparse import samba.getopt as options diff --git a/source4/scripting/python/misc.i b/source4/scripting/python/misc.i index 6fa3bc93e3..1d331215b5 100644 --- a/source4/scripting/python/misc.i +++ b/source4/scripting/python/misc.i @@ -16,7 +16,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. */ -%module(package="samba.misc") misc +%module(docstring="Python bindings for miscellaneous Samba functions.",package="samba.misc") misc %{ #include "includes.h" @@ -35,11 +35,23 @@ %import "../../auth/credentials/credentials.i" %import "../../param/param.i" %import "../../libcli/security/security.i" -%import "../../libcli/util/errors.i" +%include "../../libcli/util/errors.i" + +%feature("docstring") generate_random_str "S.random_password(len) -> string\n" \ + "Generate random password with specified length."; %rename(random_password) generate_random_str; char *generate_random_str(TALLOC_CTX *mem_ctx, size_t len); +%feature("docstring") ldb_set_credentials "S.set_credentials(credentials)\n" + "Set credentials to use when connecting."; + +%feature("docstring") ldb_set_session_info "S.set_session_info(session_info)\n" + "Set session info to use when connecting."; + +%feature("docstring") ldb_set_loadparm "S.set_loadparm(session_info)\n" + "Set loadparm context to use when connecting."; + %inline %{ void ldb_set_credentials(struct ldb_context *ldb, struct cli_credentials *creds) { @@ -58,14 +70,20 @@ void ldb_set_loadparm(struct ldb_context *ldb, struct loadparm_context *lp_ctx) %} +%feature("docstring") samdb_set_domain_sid "S.set_domain_sid(sid)\n" + "Set SID of domain to use."; bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in); WERROR dsdb_attach_schema_from_ldif_file(struct ldb_context *ldb, const char *pf, const char *df); +%feature("docstring") samba_version_string "version()\n" + "Obtain the Samba version."; %rename(version) samba_version_string; const char *samba_version_string(void); int dsdb_set_global_schema(struct ldb_context *ldb); +%feature("docstring") ldb_register_samba_handlers "register_samba_handlers()\n" + "Register Samba-specific LDB modules and schemas."; int ldb_register_samba_handlers(struct ldb_context *ldb); %inline %{ @@ -79,7 +97,6 @@ bool dsdb_set_ntds_invocation_id(struct ldb_context *ldb, const char *guid) } %} -char *private_path(TALLOC_CTX* mem_ctx, - struct loadparm_context *lp_ctx, - const char *name); +char *private_path(TALLOC_CTX* mem_ctx, struct loadparm_context *lp_ctx, + const char *name); diff --git a/source4/scripting/python/misc.py b/source4/scripting/python/misc.py index f1da4c687a..0c14944001 100644 --- a/source4/scripting/python/misc.py +++ b/source4/scripting/python/misc.py @@ -1,8 +1,12 @@ # This file was automatically generated by SWIG (http://www.swig.org). -# Version 1.3.33 +# Version 1.3.35 # # Don't modify this file, modify the SWIG interface instead. +""" +Python bindings for miscellaneous Samba functions. +""" + import _misc import new new_instancemethod = new.instancemethod @@ -61,15 +65,57 @@ import ldb import credentials import param import security -random_password = _misc.random_password -ldb_set_credentials = _misc.ldb_set_credentials -ldb_set_session_info = _misc.ldb_set_session_info -ldb_set_loadparm = _misc.ldb_set_loadparm -samdb_set_domain_sid = _misc.samdb_set_domain_sid + +def random_password(*args, **kwargs): + """ + S.random_password(len) -> string + Generate random password with specified length. + """ + return _misc.random_password(*args, **kwargs) + +def ldb_set_credentials(*args, **kwargs): + """ + S.set_credentials(credentials) + Set credentials to use when connecting. + """ + return _misc.ldb_set_credentials(*args, **kwargs) + +def ldb_set_session_info(*args, **kwargs): + """ + S.set_session_info(session_info) + Set session info to use when connecting. + """ + return _misc.ldb_set_session_info(*args, **kwargs) + +def ldb_set_loadparm(*args, **kwargs): + """ + S.set_loadparm(session_info) + Set loadparm context to use when connecting. + """ + return _misc.ldb_set_loadparm(*args, **kwargs) + +def samdb_set_domain_sid(*args, **kwargs): + """ + S.set_domain_sid(sid) + Set SID of domain to use. + """ + return _misc.samdb_set_domain_sid(*args, **kwargs) dsdb_attach_schema_from_ldif_file = _misc.dsdb_attach_schema_from_ldif_file -version = _misc.version + +def version(*args): + """ + version() + Obtain the Samba version. + """ + return _misc.version(*args) dsdb_set_global_schema = _misc.dsdb_set_global_schema -ldb_register_samba_handlers = _misc.ldb_register_samba_handlers + +def ldb_register_samba_handlers(*args, **kwargs): + """ + register_samba_handlers() + Register Samba-specific LDB modules and schemas. + """ + return _misc.ldb_register_samba_handlers(*args, **kwargs) dsdb_set_ntds_invocation_id = _misc.dsdb_set_ntds_invocation_id private_path = _misc.private_path diff --git a/source4/scripting/python/misc_wrap.c b/source4/scripting/python/misc_wrap.c index 4944515d15..888918ef53 100644 --- a/source4/scripting/python/misc_wrap.c +++ b/source4/scripting/python/misc_wrap.c @@ -1,6 +1,6 @@ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). - * Version 1.3.33 + * Version 1.3.35 * * 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 @@ -126,7 +126,7 @@ /* This should only be incremented when either the layout of swig_type_info changes, or for whatever reason, the runtime changes incompatibly */ -#define SWIG_RUNTIME_VERSION "3" +#define SWIG_RUNTIME_VERSION "4" /* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ #ifdef SWIG_TYPE_TABLE @@ -161,6 +161,7 @@ /* Flags for pointer conversions */ #define SWIG_POINTER_DISOWN 0x1 +#define SWIG_CAST_NEW_MEMORY 0x2 /* Flags for new pointer objects */ #define SWIG_POINTER_OWN 0x1 @@ -301,10 +302,10 @@ SWIGINTERNINLINE int SWIG_CheckState(int r) { extern "C" { #endif -typedef void *(*swig_converter_func)(void *); +typedef void *(*swig_converter_func)(void *, int *); typedef struct swig_type_info *(*swig_dycast_func)(void **); -/* Structure to store inforomation on one type */ +/* Structure to store information on one type */ typedef struct swig_type_info { const char *name; /* mangled name of this type */ const char *str; /* human readable name of this type */ @@ -431,8 +432,8 @@ SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) { Cast a pointer up an inheritance hierarchy */ SWIGRUNTIMEINLINE void * -SWIG_TypeCast(swig_cast_info *ty, void *ptr) { - return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr); +SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { + return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* @@ -856,7 +857,7 @@ SWIG_Python_AddErrorMsg(const char* mesg) Py_DECREF(old_str); Py_DECREF(value); } else { - PyErr_Format(PyExc_RuntimeError, mesg); + PyErr_SetString(PyExc_RuntimeError, mesg); } } @@ -1416,7 +1417,7 @@ PySwigObject_dealloc(PyObject *v) { PySwigObject *sobj = (PySwigObject *) v; PyObject *next = sobj->next; - if (sobj->own) { + if (sobj->own == SWIG_POINTER_OWN) { swig_type_info *ty = sobj->ty; PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0; PyObject *destroy = data ? data->destroy : 0; @@ -1434,12 +1435,13 @@ PySwigObject_dealloc(PyObject *v) res = ((*meth)(mself, v)); } Py_XDECREF(res); - } else { - const char *name = SWIG_TypePrettyName(ty); + } #if !defined(SWIG_PYTHON_SILENT_MEMLEAK) - printf("swig/python detected a memory leak of type '%s', no destructor found.\n", name); -#endif + else { + const char *name = SWIG_TypePrettyName(ty); + printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); } +#endif } Py_XDECREF(next); PyObject_DEL(v); @@ -1944,7 +1946,7 @@ SWIG_Python_GetSwigThis(PyObject *pyobj) SWIGRUNTIME int SWIG_Python_AcquirePtr(PyObject *obj, int own) { - if (own) { + if (own == SWIG_POINTER_OWN) { PySwigObject *sobj = SWIG_Python_GetSwigThis(obj); if (sobj) { int oldown = sobj->own; @@ -1965,6 +1967,8 @@ SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int return SWIG_OK; } else { PySwigObject *sobj = SWIG_Python_GetSwigThis(obj); + if (own) + *own = 0; while (sobj) { void *vptr = sobj->ptr; if (ty) { @@ -1978,7 +1982,15 @@ SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int if (!tc) { sobj = (PySwigObject *)sobj->next; } else { - if (ptr) *ptr = SWIG_TypeCast(tc,vptr); + if (ptr) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&newmemory); + if (newmemory == SWIG_CAST_NEW_MEMORY) { + assert(own); + if (own) + *own = *own | SWIG_CAST_NEW_MEMORY; + } + } break; } } @@ -1988,7 +2000,8 @@ SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int } } if (sobj) { - if (own) *own = sobj->own; + if (own) + *own = *own | sobj->own; if (flags & SWIG_POINTER_DISOWN) { sobj->own = 0; } @@ -2053,8 +2066,13 @@ SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { } if (ty) { swig_cast_info *tc = SWIG_TypeCheck(desc,ty); - if (!tc) return SWIG_ERROR; - *ptr = SWIG_TypeCast(tc,vptr); + if (tc) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + } else { + return SWIG_ERROR; + } } else { *ptr = vptr; } @@ -2519,7 +2537,7 @@ static swig_module_info swig_module = {swig_types, 27, 0, 0, 0, 0}; #define SWIG_name "_misc" -#define SWIGVERSION 0x010333 +#define SWIGVERSION 0x010335 #define SWIG_VERSION SWIGVERSION @@ -2536,6 +2554,9 @@ static swig_module_info swig_module = {swig_types, 27, 0, 0, 0, 0}; #include "librpc/ndr/libndr.h" +#include "libcli/util/pyerrors.h" + + SWIGINTERN int SWIG_AsVal_double (PyObject *obj, double *val) { @@ -3028,8 +3049,7 @@ SWIGINTERN PyObject *_wrap_dsdb_attach_schema_from_ldif_file(PyObject *SWIGUNUSE "ldb context must be non-NULL"); result = dsdb_attach_schema_from_ldif_file(arg1,(char const *)arg2,(char const *)arg3); if (!W_ERROR_IS_OK(result)) { - PyObject *obj = Py_BuildValue((char *)"(i,s)", W_ERROR_V(result), win_errstr(result)); - PyErr_SetObject(PyExc_RuntimeError, obj); + PyErr_SetWERROR(result); SWIG_fail; } else if (resultobj == NULL) { resultobj = Py_None; @@ -3198,15 +3218,36 @@ fail: static PyMethodDef SwigMethods[] = { - { (char *)"random_password", (PyCFunction) _wrap_random_password, METH_VARARGS | METH_KEYWORDS, NULL}, - { (char *)"ldb_set_credentials", (PyCFunction) _wrap_ldb_set_credentials, METH_VARARGS | METH_KEYWORDS, NULL}, - { (char *)"ldb_set_session_info", (PyCFunction) _wrap_ldb_set_session_info, METH_VARARGS | METH_KEYWORDS, NULL}, - { (char *)"ldb_set_loadparm", (PyCFunction) _wrap_ldb_set_loadparm, METH_VARARGS | METH_KEYWORDS, NULL}, - { (char *)"samdb_set_domain_sid", (PyCFunction) _wrap_samdb_set_domain_sid, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"random_password", (PyCFunction) _wrap_random_password, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.random_password(len) -> string\n" + "Generate random password with specified length.\n" + ""}, + { (char *)"ldb_set_credentials", (PyCFunction) _wrap_ldb_set_credentials, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.set_credentials(credentials)\n" + "Set credentials to use when connecting.\n" + ""}, + { (char *)"ldb_set_session_info", (PyCFunction) _wrap_ldb_set_session_info, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.set_session_info(session_info)\n" + "Set session info to use when connecting.\n" + ""}, + { (char *)"ldb_set_loadparm", (PyCFunction) _wrap_ldb_set_loadparm, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.set_loadparm(session_info)\n" + "Set loadparm context to use when connecting.\n" + ""}, + { (char *)"samdb_set_domain_sid", (PyCFunction) _wrap_samdb_set_domain_sid, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.set_domain_sid(sid)\n" + "Set SID of domain to use.\n" + ""}, { (char *)"dsdb_attach_schema_from_ldif_file", (PyCFunction) _wrap_dsdb_attach_schema_from_ldif_file, METH_VARARGS | METH_KEYWORDS, NULL}, - { (char *)"version", (PyCFunction)_wrap_version, METH_NOARGS, NULL}, + { (char *)"version", (PyCFunction)_wrap_version, METH_NOARGS, (char *)"\n" + "version()\n" + "Obtain the Samba version.\n" + ""}, { (char *)"dsdb_set_global_schema", (PyCFunction) _wrap_dsdb_set_global_schema, METH_VARARGS | METH_KEYWORDS, NULL}, - { (char *)"ldb_register_samba_handlers", (PyCFunction) _wrap_ldb_register_samba_handlers, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"ldb_register_samba_handlers", (PyCFunction) _wrap_ldb_register_samba_handlers, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "register_samba_handlers()\n" + "Register Samba-specific LDB modules and schemas.\n" + ""}, { (char *)"dsdb_set_ntds_invocation_id", (PyCFunction) _wrap_dsdb_set_ntds_invocation_id, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"private_path", (PyCFunction) _wrap_private_path, METH_VARARGS | METH_KEYWORDS, NULL}, { NULL, NULL, 0, NULL } @@ -3225,7 +3266,7 @@ static swig_type_info _swigt__p_ldb_context = {"_p_ldb_context", "struct ldb_con static swig_type_info _swigt__p_ldb_dn = {"_p_ldb_dn", "struct ldb_dn *|ldb_dn *", 0, 0, (void*)0, 0}; 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_msg_element *", 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_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}; @@ -3397,7 +3438,7 @@ SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) { size_t i; swig_module_info *module_head, *iter; - int found; + int found, init; clientdata = clientdata; @@ -3407,6 +3448,9 @@ SWIG_InitializeModule(void *clientdata) { swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; + init = 1; + } else { + init = 0; } /* Try and load any already created modules */ @@ -3435,6 +3479,12 @@ SWIG_InitializeModule(void *clientdata) { module_head->next = &swig_module; } + /* When multiple interpeters are used, a module could have already been initialized in + a different interpreter, but not yet have a pointer in this interpreter. + In this case, we do not want to continue adding types... everything should be + set up already */ + if (init == 0) return; + /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); diff --git a/source4/scripting/python/pyrpc.h b/source4/scripting/python/pyrpc.h deleted file mode 100644 index 93d583c10a..0000000000 --- a/source4/scripting/python/pyrpc.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - Unix SMB/CIFS implementation. - Samba utility functions - Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2008 - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. -*/ - -#ifndef _PYRPC_H_ -#define _PYRPC_H_ - -#define PY_CHECK_TYPE(type, var, fail) \ - if (!type ## _Check(var)) {\ - PyErr_Format(PyExc_TypeError, "Expected type %s", type ## _Type.tp_name); \ - fail; \ - } - -#define dom_sid2_Type dom_sid_Type -#define dom_sid28_Type dom_sid_Type -#define dom_sid2_Check dom_sid_Check -#define dom_sid28_Check dom_sid_Check - -/* This macro is only provided by Python >= 2.3 */ -#ifndef PyAPI_DATA -# define PyAPI_DATA(RTYPE) extern RTYPE -#endif - -#endif /* _PYRPC_H_ */ diff --git a/source4/scripting/python/pytalloc.c b/source4/scripting/python/pytalloc.c index aa0ae9bf90..ca476e9604 100644 --- a/source4/scripting/python/pytalloc.c +++ b/source4/scripting/python/pytalloc.c @@ -24,6 +24,7 @@ void py_talloc_dealloc(PyObject* self) { py_talloc_Object *obj = (py_talloc_Object *)self; talloc_free(obj->talloc_ctx); + obj->talloc_ctx = NULL; PyObject_Del(self); } @@ -31,7 +32,13 @@ PyObject *py_talloc_import_ex(PyTypeObject *py_type, TALLOC_CTX *mem_ctx, void *ptr) { py_talloc_Object *ret = PyObject_New(py_talloc_Object, py_type); - ret->talloc_ctx = talloc_reference(NULL, mem_ctx); + ret->talloc_ctx = talloc_new(NULL); + if (ret->talloc_ctx == NULL) { + return NULL; + } + if (talloc_reference(ret->talloc_ctx, mem_ctx) == NULL) { + return NULL; + } ret->ptr = ptr; return (PyObject *)ret; } @@ -41,5 +48,5 @@ PyObject *py_talloc_default_repr(PyObject *py_obj) py_talloc_Object *obj = (py_talloc_Object *)py_obj; PyTypeObject *type = (PyTypeObject*)PyObject_Type((PyObject *)obj); - return PyString_FromFormat("<%s>", type->tp_name); + return PyString_FromFormat("<%s talloc object at 0x%x>", type->tp_name, (intptr_t)py_obj); } diff --git a/source4/scripting/python/samba/__init__.py b/source4/scripting/python/samba/__init__.py index 29afdb931d..e191227108 100644 --- a/source4/scripting/python/samba/__init__.py +++ b/source4/scripting/python/samba/__init__.py @@ -20,6 +20,10 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # +"""Samba 4.""" + +__docformat__ = "restructuredText" + import os def _in_source_tree(): @@ -71,15 +75,15 @@ class Ldb(ldb.Ldb): self.set_modules_dir(default_ldb_modules_dir) if credentials is not None: - self.set_credentials(self, credentials) + self.set_credentials(credentials) if session_info is not None: - self.set_session_info(self, session_info) + self.set_session_info(session_info) assert misc.ldb_register_samba_handlers(self) == 0 if lp is not None: - self.set_loadparm(self, lp) + self.set_loadparm(lp) def msg(l,text): print text diff --git a/source4/scripting/python/samba/getopt.py b/source4/scripting/python/samba/getopt.py index 7ec684a9d6..9ecb66e21c 100644 --- a/source4/scripting/python/samba/getopt.py +++ b/source4/scripting/python/samba/getopt.py @@ -17,10 +17,15 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # +"""Support for parsing Samba-related command-line options.""" + import optparse from credentials import Credentials, AUTO_USE_KERBEROS, DONT_USE_KERBEROS, MUST_USE_KERBEROS +__docformat__ = "restructuredText" + class SambaOptions(optparse.OptionGroup): + """General Samba-related command line options.""" def __init__(self, parser): optparse.OptionGroup.__init__(self, parser, "Samba Common Options") self.add_option("-s", "--configfile", action="callback", @@ -29,12 +34,14 @@ class SambaOptions(optparse.OptionGroup): self._configfile = None def get_loadparm_path(self): + """Return the path to the smb.conf file specified on the command line. """ return self._configfile def _load_configfile(self, option, opt_str, arg, parser): self._configfile = arg def get_loadparm(self): + """Return a loadparm object with data specified on the command line. """ import os, param lp = param.LoadParm() if self._configfile is not None: @@ -45,12 +52,15 @@ class SambaOptions(optparse.OptionGroup): lp.load_default() return lp + class VersionOptions(optparse.OptionGroup): + """Command line option for printing Samba version.""" def __init__(self, parser): optparse.OptionGroup.__init__(self, parser, "Version Options") class CredentialsOptions(optparse.OptionGroup): + """Command line options for specifying credentials.""" def __init__(self, parser): self.no_pass = False optparse.OptionGroup.__init__(self, parser, "Credentials Options") @@ -91,6 +101,11 @@ class CredentialsOptions(optparse.OptionGroup): self.creds.set_bind_dn(arg) def get_credentials(self, lp): + """Obtain the credentials set on the command-line. + + :param lp: Loadparm object to use. + :return: Credentials object + """ self.creds.guess(lp) if not self.no_pass: self.creds.set_cmdline_callbacks() diff --git a/source4/scripting/python/samba/idmap.py b/source4/scripting/python/samba/idmap.py index 16efcd0470..755ec52c7b 100644 --- a/source4/scripting/python/samba/idmap.py +++ b/source4/scripting/python/samba/idmap.py @@ -20,6 +20,8 @@ """Convenience functions for using the idmap database.""" +__docformat__ = "restructuredText" + import samba import misc import ldb diff --git a/source4/scripting/python/samba/ndr.py b/source4/scripting/python/samba/ndr.py new file mode 100644 index 0000000000..e718ff3422 --- /dev/null +++ b/source4/scripting/python/samba/ndr.py @@ -0,0 +1,28 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Unix SMB/CIFS implementation. +# Copyright © Jelmer Vernooij <jelmer@samba.org> 2008 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +def ndr_pack(object): + return object.__ndr_pack__() + + +def ndr_unpack(cls, data): + object = cls() + object.__ndr_unpack__(data) + return object diff --git a/source4/scripting/python/samba/provision.py b/source4/scripting/python/samba/provision.py index 69c7e8846d..3914fa8376 100644 --- a/source4/scripting/python/samba/provision.py +++ b/source4/scripting/python/samba/provision.py @@ -22,6 +22,8 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # +"""Functions for setting up a Samba configuration.""" + from base64 import b64encode import os import pwd @@ -41,11 +43,12 @@ import urllib from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE, LdbError, \ LDB_ERR_NO_SUCH_OBJECT, timestring, CHANGETYPE_MODIFY, CHANGETYPE_NONE -"""Functions for setting up a Samba configuration.""" +__docformat__ = "restructuredText" DEFAULTSITE = "Default-First-Site-Name" class InvalidNetbiosName(Exception): + """A specified name was not a valid NetBIOS name.""" def __init__(self, name): super(InvalidNetbiosName, self).__init__("The name '%r' is not a valid NetBIOS name" % name) @@ -104,7 +107,7 @@ def check_install(lp, session_info, credentials): :param credentials: Credentials """ if lp.get("realm") == "": - raise Error("Realm empty") + raise Exception("Realm empty") ldb = Ldb(lp.get("sam database"), session_info=session_info, credentials=credentials, lp=lp) if len(ldb.search("(cn=Administrator)")) != 1: @@ -126,6 +129,10 @@ def findnss(nssfn, names): raise KeyError("Unable to find user/group %r" % names) +findnss_uid = lambda names: findnss(pwd.getpwnam, names)[2] +findnss_gid = lambda names: findnss(grp.getgrnam, names)[2] + + def open_ldb(session_info, credentials, lp, dbname): """Open a LDB, thrashing it if it is corrupt. @@ -299,13 +306,13 @@ def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None, serverrole= dnsdomain = dnsdomain.lower() - if (serverrole == "domain controller"): + if serverrole == "domain controller": if domain is None: domain = lp.get("workgroup") if domaindn is None: domaindn = "DC=" + dnsdomain.replace(".", ",DC=") if lp.get("workgroup").upper() != domain.upper(): - raise Error("workgroup '%s' in smb.conf must match chosen domain '%s'", + raise Exception("workgroup '%s' in smb.conf must match chosen domain '%s'", lp.get("workgroup"), domain) else: domain = netbiosname @@ -345,67 +352,53 @@ def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None, serverrole= return names -def load_or_make_smbconf(smbconf, setup_path, hostname, domain, realm, serverrole, targetdir): - if targetdir is not None: - if not os.path.exists(targetdir): - os.mkdir(targetdir) - if not os.path.exists(os.path.join(targetdir, "etc")): - os.mkdir(os.path.join(targetdir, "etc")) +def make_smbconf(smbconf, setup_path, hostname, domain, realm, serverrole, + targetdir): + if hostname is None: + hostname = socket.gethostname().split(".")[0].lower() - smbconf = os.path.join(targetdir, "etc", "smb.conf") + if serverrole is None: + serverrole = "standalone" - # only install a new smb.conf if there isn't one there already + assert serverrole in ("domain controller", "member server", "standalone") + if serverrole == "domain controller": + smbconfsuffix = "dc" + elif serverrole == "member server": + smbconfsuffix = "member" + elif serverrole == "standalone": + smbconfsuffix = "standalone" - if not os.path.exists(smbconf): - if hostname is None: - hostname = socket.gethostname().split(".")[0].lower() + assert domain is not None + assert realm is not None - if serverrole is None: - serverrole = "standalone" + default_lp = param.LoadParm() + #Load non-existant file + default_lp.load(smbconf) + + if targetdir is not None: + privatedir_line = "private dir = " + os.path.abspath(os.path.join(targetdir, "private")) + lockdir_line = "lock dir = " + os.path.abspath(targetdir) - assert serverrole in ("domain controller", "member server", "standalone") - if serverrole == "domain controller": - smbconfsuffix = "dc" - elif serverrole == "member server": - smbconfsuffix = "member" - elif serverrole == "standalone": - smbconfsuffix = "standalone" - - assert domain is not None - assert realm is not None - - default_lp = param.LoadParm() - #Load non-existant file - default_lp.load(smbconf) - - if targetdir is not None: - privatedir_line = "private dir = " + os.path.abspath(os.path.join(targetdir, "private")) - lockdir_line = "lock dir = " + os.path.abspath(targetdir) + default_lp.set("lock dir", os.path.abspath(targetdir)) + else: + privatedir_line = "" + lockdir_line = "" - default_lp.set("lock dir", os.path.abspath(targetdir)) - else: - privatedir_line = "" - lockdir_line = "" - - sysvol = os.path.join(default_lp.get("lock dir"), "sysvol") - netlogon = os.path.join(sysvol, realm.lower(), "scripts") - - setup_file(setup_path("provision.smb.conf.%s" % smbconfsuffix), - smbconf, { - "HOSTNAME": hostname, - "DOMAIN": domain, - "REALM": realm, - "SERVERROLE": serverrole, - "NETLOGONPATH": netlogon, - "SYSVOLPATH": sysvol, - "PRIVATEDIR_LINE": privatedir_line, - "LOCKDIR_LINE": lockdir_line - }) + sysvol = os.path.join(default_lp.get("lock dir"), "sysvol") + netlogon = os.path.join(sysvol, realm.lower(), "scripts") - lp = param.LoadParm() - lp.load(smbconf) + setup_file(setup_path("provision.smb.conf.%s" % smbconfsuffix), + smbconf, { + "HOSTNAME": hostname, + "DOMAIN": domain, + "REALM": realm, + "SERVERROLE": serverrole, + "NETLOGONPATH": netlogon, + "SYSVOLPATH": sysvol, + "PRIVATEDIR_LINE": privatedir_line, + "LOCKDIR_LINE": lockdir_line + }) - return lp def setup_name_mappings(samdb, idmap, sid, domaindn, root_uid, nobody_uid, @@ -500,8 +493,8 @@ def setup_samdb_partitions(samdb_path, setup_path, message, lp, session_info, schemadn_ldb = "schema.ldb" if ldap_backend is not None: schema_ldb = ldap_backend - schemadn_ldb = ldap_backend - + schemadn_ldb = ldap_backend + if ldap_backend_type == "fedora-ds": backend_modules = ["nsuniqueid", "paged_searches"] # We can handle linked attributes here, as we don't have directory-side subtree operations @@ -748,7 +741,8 @@ def setup_samdb(path, setup_path, session_info, credentials, lp, if serverrole == "domain controller": samdb.set_invocation_id(invocationid) - load_schema(setup_path, samdb, names.schemadn, names.netbiosname, names.configdn, names.sitename) + load_schema(setup_path, samdb, names.schemadn, names.netbiosname, + names.configdn, names.sitename) samdb.transaction_start() @@ -922,26 +916,27 @@ def provision(setup_dir, message, session_info, machinepass = misc.random_password(12) if dnspass is None: dnspass = misc.random_password(12) - if root is None: - root_uid = findnss(pwd.getpwnam, ["root"])[2] - else: - root_uid = findnss(pwd.getpwnam, [root])[2] - if nobody is None: - nobody_uid = findnss(pwd.getpwnam, ["nobody"])[2] - else: - nobody_uid = findnss(pwd.getpwnam, [nobody])[2] - if users is None: - users_gid = findnss(grp.getgrnam, ["users"])[2] - else: - users_gid = findnss(grp.getgrnam, [users])[2] + root_uid = findnss_uid([root or "root"]) + nobody_uid = findnss_uid([nobody or "nobody"]) + users_gid = findnss_gid([users or "users"]) if wheel is None: - wheel_gid = findnss(grp.getgrnam, ["wheel", "adm"])[2] + wheel_gid = findnss_gid(["wheel", "adm"]) else: - wheel_gid = findnss(grp.getgrnam, [wheel])[2] + wheel_gid = findnss_gid([wheel]) if aci is None: aci = "# no aci for local ldb" - lp = load_or_make_smbconf(smbconf, setup_path, hostname, domain, realm, serverrole, targetdir) + if smbconf is None: + os.makedirs(os.path.join(targetdir, "etc")) + smbconf = os.path.join(targetdir, "etc", "smb.conf") + + # only install a new smb.conf if there isn't one there already + if not os.path.exists(smbconf): + make_smbconf(smbconf, setup_path, hostname, domain, realm, serverrole, + targetdir) + + lp = param.LoadParm() + lp.load(smbconf) names = guess_names(lp=lp, hostname=hostname, domain=domain, dnsdomain=realm, serverrole=serverrole, sitename=sitename, @@ -956,7 +951,8 @@ def provision(setup_dir, message, session_info, if hostip6 is None: try: hostip6 = socket.getaddrinfo(names.hostname, None, socket.AF_INET6, socket.AI_CANONNAME, socket.IPPROTO_IP)[0][-1][0] - except socket.gaierror: pass + except socket.gaierror: + pass if serverrole is None: serverrole = lp.get("server role") @@ -1110,13 +1106,13 @@ def provision_become_dc(setup_dir=None, ldap_backend=None, ldap_backend_type=None, sitename=None): def message(text): - """print a message if quiet is not set.""" + """print a message if quiet is not set.""" print text return provision(setup_dir, message, system_session(), None, smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS, realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn, configdn=configdn, serverdn=serverdn, - domain=domain, hostname=hostname, hostip="127.0.0.1", domainsid=domainsid, machinepass=machinepass, serverrole="domain controller", sitename=sitename); + domain=domain, hostname=hostname, hostip="127.0.0.1", domainsid=domainsid, machinepass=machinepass, serverrole="domain controller", sitename=sitename) def setup_db_config(setup_path, dbdir): @@ -1125,9 +1121,9 @@ def setup_db_config(setup_path, dbdir): :param setup_path: Setup path function. :param dbdir: Database directory.""" if not os.path.isdir(os.path.join(dbdir, "bdb-logs")): - os.makedirs(os.path.join(dbdir, "bdb-logs"), 0700); + os.makedirs(os.path.join(dbdir, "bdb-logs"), 0700) if not os.path.isdir(os.path.join(dbdir, "tmp")): - os.makedirs(os.path.join(dbdir, "tmp"), 0700); + os.makedirs(os.path.join(dbdir, "tmp"), 0700) setup_file(setup_path("DB_CONFIG"), os.path.join(dbdir, "DB_CONFIG"), {"LDAPDBDIR": dbdir}) @@ -1149,11 +1145,23 @@ def provision_backend(setup_dir=None, message=None, if root is None: root = findnss(pwd.getpwnam, ["root"])[0] - lp = load_or_make_smbconf(smbconf, setup_path, hostname, domain, realm, serverrole, targetdir) + if smbconf is None: + etcdir = os.path.join(targetdir, "etc") + os.makedirs(etcdir) + smbconf = os.path.join(etcdir, "smb.conf") + + # only install a new smb.conf if there isn't one there already + if not os.path.exists(smbconf): + make_smbconf(smbconf, setup_path, hostname, domain, realm, + serverrole, targetdir) + + lp = param.LoadParm() + lp.load(smbconf) names = guess_names(lp=lp, hostname=hostname, domain=domain, dnsdomain=realm, serverrole=serverrole, - rootdn=rootdn, domaindn=domaindn, configdn=configdn, schemadn=schemadn) + rootdn=rootdn, domaindn=domaindn, configdn=configdn, + schemadn=schemadn) paths = provision_paths_from_lp(lp, names.dnsdomain) @@ -1214,21 +1222,19 @@ def provision_backend(setup_dir=None, message=None, elif ldap_backend_type == "openldap": attrs = ["linkID", "lDAPDisplayName"] - res = schemadb.search(expression="(&(&(linkID=*)(!(linkID:1.2.840.113556.1.4.803:=1)))(objectclass=attributeSchema))", base=names.schemadn, scope=SCOPE_SUBTREE, attrs=attrs); - - memberof_config = "# Generated from schema in " + schemadb_path + "\n"; - refint_attributes = ""; - for i in range (0, len(res)): - linkid = res[i]["linkID"][0] - linkid = str(int(linkid) + 1) - expression = "(&(objectclass=attributeSchema)(linkID=" + (linkid) + "))" + res = schemadb.search(expression="(&(&(linkID=*)(!(linkID:1.2.840.113556.1.4.803:=1)))(objectclass=attributeSchema))", base=names.schemadn, scope=SCOPE_SUBTREE, attrs=attrs) + + memberof_config = "# Generated from schema in %s\n" % schemadb_path + refint_attributes = "" + for i in range (0, len(res)): + expression = "(&(objectclass=attributeSchema)(linkID=%d))" % (int(res[i]["linkID"][0])+1) target = schemadb.searchone(basedn=names.schemadn, expression=expression, attribute="lDAPDisplayName", - scope=SCOPE_SUBTREE); + scope=SCOPE_SUBTREE) if target is not None: - refint_attributes = refint_attributes + " " + target + " " + res[i]["lDAPDisplayName"][0]; - memberof_config = memberof_config + """overlay memberof + refint_attributes = refint_attributes + " " + target + " " + res[i]["lDAPDisplayName"][0] + memberof_config += """overlay memberof memberof-dangling error memberof-refint TRUE memberof-group-oc top @@ -1236,13 +1242,13 @@ memberof-member-ad """ + res[i]["lDAPDisplayName"][0] + """ memberof-memberof-ad """ + target + """ memberof-dangling-error 32 -"""; +""" - memberof_config = memberof_config + """ + memberof_config += """ overlay refint -refint_attributes""" + refint_attributes + "\n"; - - setup_file(setup_path("slapd.conf"), paths.slapdconf, +refint_attributes""" + refint_attributes + "\n" + + setup_file(setup_path("slapd.conf"), paths.slapdconf, {"DNSDOMAIN": names.dnsdomain, "LDAPDIR": paths.ldapdir, "DOMAINDN": names.domaindn, @@ -1251,28 +1257,28 @@ refint_attributes""" + refint_attributes + "\n"; "LDAPMANAGERDN": names.ldapmanagerdn, "LDAPMANAGERPASS": adminpass, "MEMBEROF_CONFIG": memberof_config}) - setup_file(setup_path("modules.conf"), paths.modulesconf, + setup_file(setup_path("modules.conf"), paths.modulesconf, {"REALM": names.realm}) - setup_db_config(setup_path, os.path.join(paths.ldapdir, os.path.join("db", "user"))) - setup_db_config(setup_path, os.path.join(paths.ldapdir, os.path.join("db", "config"))) - setup_db_config(setup_path, os.path.join(paths.ldapdir, os.path.join("db", "schema"))) - mapping = "schema-map-openldap-2.3" - backend_schema = "backend-schema.schema" - - ldapi_uri = "ldapi://" + urllib.quote(os.path.join(paths.private_dir, "ldap", "ldapi"), safe="") - if ldap_backend_port is not None: - server_port_string = " -h ldap://0.0.0.0:%d" % ldap_backend_port - else: - server_port_string = "" - slapdcommand="Start slapd with: slapd -f " + paths.ldapdir + "/slapd.conf -h " + ldapi_uri + server_port_string + setup_db_config(setup_path, os.path.join(paths.ldapdir, os.path.join("db", "user"))) + setup_db_config(setup_path, os.path.join(paths.ldapdir, os.path.join("db", "config"))) + setup_db_config(setup_path, os.path.join(paths.ldapdir, os.path.join("db", "schema"))) + mapping = "schema-map-openldap-2.3" + backend_schema = "backend-schema.schema" + + ldapi_uri = "ldapi://" + urllib.quote(os.path.join(paths.private_dir, "ldap", "ldapi"), safe="") + if ldap_backend_port is not None: + server_port_string = " -h ldap://0.0.0.0:%d" % ldap_backend_port + else: + server_port_string = "" + slapdcommand="Start slapd with: slapd -f " + paths.ldapdir + "/slapd.conf -h " + ldapi_uri + server_port_string - schema_command = "bin/ad2oLschema --option=convert:target=" + ldap_backend_type + " -I " + setup_path(mapping) + " -H tdb://" + schemadb_path + " -O " + os.path.join(paths.ldapdir, backend_schema); + schema_command = "bin/ad2oLschema --option=convert:target=" + ldap_backend_type + " -I " + setup_path(mapping) + " -H tdb://" + schemadb_path + " -O " + os.path.join(paths.ldapdir, backend_schema) os.system(schema_command) - message("Your %s Backend for Samba4 is now configured, and is ready to be started" % ( ldap_backend_type) ) + message("Your %s Backend for Samba4 is now configured, and is ready to be started" % ldap_backend_type) message("Server Role: %s" % serverrole) message("Hostname: %s" % names.hostname) message("DNS Domain: %s" % names.dnsdomain) @@ -1314,8 +1320,8 @@ def create_zone_file(path, setup_path, dnsdomain, domaindn, hostip6_host_line = "" if hostip6 is not None: - hostip6_base_line = " IN AAAA " + hostip6 - hostip6_host_line = hostname + " IN AAAA " + hostip6 + hostip6_base_line = " IN AAAA " + hostip6 + hostip6_host_line = hostname + " IN AAAA " + hostip6 setup_file(setup_path("provision.zone"), path, { "DNSPASS_B64": b64encode(dnspass), @@ -1331,6 +1337,7 @@ def create_zone_file(path, setup_path, dnsdomain, domaindn, "HOSTIP6_HOST_LINE": hostip6_host_line, }) + def create_named_conf(path, setup_path, realm, dnsdomain, private_dir, keytab_name): """Write out a file containing zone statements suitable for inclusion in a @@ -1369,6 +1376,7 @@ def create_krb5_conf(path, setup_path, dnsdomain, hostname, realm): "REALM": realm, }) + def load_schema(setup_path, samdb, schemadn, netbiosname, configdn, sitename): """Load schema for the SamDB. diff --git a/source4/scripting/python/samba/samba3.py b/source4/scripting/python/samba/samba3.py index cffedb54af..c1340b7760 100644 --- a/source4/scripting/python/samba/samba3.py +++ b/source4/scripting/python/samba/samba3.py @@ -19,6 +19,8 @@ """Support for reading Samba 3 data files.""" +__docformat__ = "restructuredText" + REGISTRY_VALUE_PREFIX = "SAMBA_REGVAL" REGISTRY_DB_VERSION = 1 @@ -307,6 +309,7 @@ class ShareInfoDatabase(TdbDatabase): class Shares: + """Container for share objects.""" def __init__(self, lp, shareinfo): self.lp = lp self.shareinfo = shareinfo @@ -492,6 +495,7 @@ class TdbSam(TdbDatabase): assert self.version in (0, 1, 2) def usernames(self): + """Iterate over the usernames in this Tdb database.""" for k in self.tdb.keys(): if k.startswith(TDBSAM_USER_PREFIX): yield k[len(TDBSAM_USER_PREFIX):].rstrip("\0") @@ -633,6 +637,7 @@ class WinsDatabase: return iter(self.entries) def items(self): + """Return the entries in this WINS database.""" return self.entries.items() def close(self): # for consistency diff --git a/source4/scripting/python/samba/samdb.py b/source4/scripting/python/samba/samdb.py index 198d1e9f5c..6465f49519 100644 --- a/source4/scripting/python/samba/samdb.py +++ b/source4/scripting/python/samba/samdb.py @@ -28,6 +28,8 @@ import ldb from samba.idmap import IDmapDB import pwd +__docformat__ = "restructuredText" + class SamDB(samba.Ldb): """The SAM database.""" diff --git a/source4/scripting/python/samba/tests/dcerpc/bare.py b/source4/scripting/python/samba/tests/dcerpc/bare.py new file mode 100644 index 0000000000..d75ffc381e --- /dev/null +++ b/source4/scripting/python/samba/tests/dcerpc/bare.py @@ -0,0 +1,46 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Unix SMB/CIFS implementation. +# Copyright © Jelmer Vernooij <jelmer@samba.org> 2008 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +from samba.dcerpc import ClientConnection +from unittest import TestCase + +class BareTestCase(TestCase): + def test_bare(self): + # Connect to the echo pipe + x = ClientConnection("ncalrpc:localhost[DEFAULT]", + ("60a15ec5-4de8-11d7-a637-005056a20182", 1)) + self.assertEquals("\x01\x00\x00\x00", x.request(0, chr(0) * 4)) + + def test_alter_context(self): + x = ClientConnection("ncalrpc:localhost[DEFAULT]", + ("12345778-1234-abcd-ef00-0123456789ac", 1)) + y = ClientConnection("ncalrpc:localhost", + ("60a15ec5-4de8-11d7-a637-005056a20182", 1), + basis_connection=x) + x.alter_context(("60a15ec5-4de8-11d7-a637-005056a20182", 1)) + # FIXME: self.assertEquals("\x01\x00\x00\x00", x.request(0, chr(0) * 4)) + + def test_two_connections(self): + x = ClientConnection("ncalrpc:localhost[DEFAULT]", + ("60a15ec5-4de8-11d7-a637-005056a20182", 1)) + y = ClientConnection("ncalrpc:localhost", + ("60a15ec5-4de8-11d7-a637-005056a20182", 1), + basis_connection=x) + self.assertEquals("\x01\x00\x00\x00", y.request(0, chr(0) * 4)) diff --git a/source4/scripting/python/samba/tests/dcerpc/rpcecho.py b/source4/scripting/python/samba/tests/dcerpc/rpcecho.py index 3b37f8a9bc..bbbd0d76ec 100644 --- a/source4/scripting/python/samba/tests/dcerpc/rpcecho.py +++ b/source4/scripting/python/samba/tests/dcerpc/rpcecho.py @@ -18,6 +18,7 @@ # from samba.dcerpc import echo +from samba.ndr import ndr_pack, ndr_unpack import unittest from samba.tests import RpcInterfaceTestCase @@ -25,6 +26,14 @@ class RpcEchoTests(RpcInterfaceTestCase): def setUp(self): self.conn = echo.rpcecho("ncalrpc:", self.get_loadparm()) + def test_two_contexts(self): + self.conn2 = echo.rpcecho("ncalrpc:", basis_connection=self.conn) + self.assertEquals(3, self.conn2.AddOne(2)) + + def test_abstract_syntax(self): + self.assertEquals(("60a15ec5-4de8-11d7-a637-005056a20182", 1), + self.conn.abstract_syntax) + def test_addone(self): self.assertEquals(2, self.conn.AddOne(1)) @@ -40,3 +49,19 @@ class RpcEchoTests(RpcInterfaceTestCase): surrounding_struct.surrounding = [1,2,3,4] y = self.conn.TestSurrounding(surrounding_struct) self.assertEquals(8 * [0], y.surrounding) + + def test_manual_request(self): + self.assertEquals("\x01\x00\x00\x00", self.conn.request(0, chr(0) * 4)) + + def test_server_name(self): + self.assertEquals(None, self.conn.server_name) + +class NdrEchoTests(unittest.TestCase): + def test_info1_push(self): + x = echo.info1() + x.v = 42 + self.assertEquals("\x2a", ndr_pack(x)) + + def test_info1_pull(self): + x = ndr_unpack(echo.info1, "\x42") + self.assertEquals(x.v, 66) diff --git a/source4/scripting/python/samba/tests/dcerpc/sam.py b/source4/scripting/python/samba/tests/dcerpc/sam.py index a6816153c0..50e00a3f9e 100644 --- a/source4/scripting/python/samba/tests/dcerpc/sam.py +++ b/source4/scripting/python/samba/tests/dcerpc/sam.py @@ -1,7 +1,8 @@ #!/usr/bin/python +# -*- coding: utf-8 -*- # Unix SMB/CIFS implementation. -# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2008 +# Copyright © Jelmer Vernooij <jelmer@samba.org> 2008 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -17,12 +18,29 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # -from samba.dcerpc import samr +from samba.dcerpc import samr, security from samba.tests import RpcInterfaceTestCase +# FIXME: Pidl should be doing this for us +def toArray((handle, array, num_entries)): + ret = [] + for x in range(num_entries): + ret.append((array.entries[x].idx, array.entries[x].name)) + return ret + + class SamrTests(RpcInterfaceTestCase): def setUp(self): self.conn = samr.samr("ncalrpc:", self.get_loadparm()) def test_connect5(self): (level, info, handle) = self.conn.Connect5(None, 0, 1, samr.ConnectInfo1()) + + def test_connect2(self): + handle = self.conn.Connect2(None, security.SEC_FLAG_MAXIMUM_ALLOWED) + + def test_EnumDomains(self): + handle = self.conn.Connect2(None, security.SEC_FLAG_MAXIMUM_ALLOWED) + domains = toArray(self.conn.EnumDomains(handle, 0, -1)) + self.conn.Close(handle) + diff --git a/source4/scripting/python/samba/upgrade.py b/source4/scripting/python/samba/upgrade.py index f40f2cffe7..0c83604e82 100644 --- a/source4/scripting/python/samba/upgrade.py +++ b/source4/scripting/python/samba/upgrade.py @@ -7,6 +7,8 @@ """Support code for upgrading from Samba 3 to Samba 4.""" +__docformat__ = "restructuredText" + from provision import findnss, provision, FILL_DRS import grp import ldb |