Ignore:
Timestamp:
Nov 14, 2012, 12:59:34 PM (13 years ago)
Author:
Silvan Scherrer
Message:

Samba Server: update vendor to 3.6.0

Location:
vendor/current/source4/scripting
Files:
91 added
10 deleted
39 edited

Legend:

Unmodified
Added
Removed
  • vendor/current/source4/scripting/bin/autoidl

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22# -*- coding: utf-8 -*-
    33
  • vendor/current/source4/scripting/bin/fullschema

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22#
    33# Works out the full schema
     
    66import base64
    77import optparse
    8 import os
    98import sys
    109
     
    1413import samba
    1514from samba import getopt as options, Ldb
    16 from ldb import SCOPE_SUBTREE, SCOPE_BASE, LdbError
     15from ldb import SCOPE_SUBTREE, SCOPE_BASE
    1716import sys
    1817
  • vendor/current/source4/scripting/bin/get-descriptors

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22#
    33# Unix SMB/CIFS implementation.
     
    2828#
    2929
    30 import getopt
    3130import optparse
    3231import sys
    33 import os
    3432import base64
    35 import re
    3633
    3734sys.path.insert(0, "bin/python")
     
    4037from samba.auth import system_session
    4138import samba.getopt as options
    42 from samba import param
    4339from samba.ndr import ndr_pack, ndr_unpack
    4440from samba.dcerpc import security
    4541from samba import Ldb
    4642from samba.samdb import SamDB
    47 from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE, LdbError
     43from ldb import SCOPE_SUBTREE, SCOPE_BASE
    4844
    4945parser = optparse.OptionParser("get-descriptor [options]")
     
    6662
    6763class DescrGetter:
     64
    6865    def __init__(self, localdomain, remotedomain):
    6966        self.samdb = SamDB(session_info=system_session(), lp=lp, options=["modules:paged_searches"])
  • vendor/current/source4/scripting/bin/minschema

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22#
    33# Works out the minimal schema for a set of objectclasses
  • vendor/current/source4/scripting/bin/rebuildextendeddn

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22#
    33# Unix SMB/CIFS implementation.
     
    2424#
    2525
    26 import getopt
    2726import optparse
    2827import os
     
    3433from samba.credentials import DONT_USE_KERBEROS
    3534from samba.auth import system_session
    36 from samba import Ldb, substitute_var, valid_netbios_name, check_all_substituted
    37 from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE, LdbError, \
    38                         timestring, CHANGETYPE_MODIFY, CHANGETYPE_NONE
     35from samba import Ldb
     36from ldb import SCOPE_SUBTREE, SCOPE_BASE
    3937import ldb
    4038import samba.getopt as options
    41 from samba.samdb import SamDB
    4239from samba import param
    43 from samba.provision import ProvisionPaths, ProvisionNames,provision_paths_from_lp,get_dnsyntax_attributes,get_linked_attributes
     40from samba.provision import ProvisionNames, provision_paths_from_lp
     41from samba.schema import get_dnsyntax_attributes, get_linked_attributes
    4442
    4543parser = optparse.OptionParser("provision [options]")
  • vendor/current/source4/scripting/bin/rpcclient

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33import sys, os, string
  • vendor/current/source4/scripting/bin/samba3dump

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22#
    33#    Dump Samba3 data
  • vendor/current/source4/scripting/bin/setup_dns.sh

    r414 r740  
    1717}
    1818
    19 OBJECTGUID=$(bin/ldbsearch -H "$PRIVATEDIR/sam.ldb" -b "CN=NTDS Settings,CN=$HOSTNAME,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=$RSUFFIX" objectguid|grep ^objectGUID| cut -d: -f2)
     19OBJECTGUID=$(bin/ldbsearch -s base -H "$PRIVATEDIR/sam.ldb" -b "CN=NTDS Settings,CN=$HOSTNAME,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=$RSUFFIX" objectguid|grep ^objectGUID| cut -d: -f2)
    2020
    2121echo "Found objectGUID $OBJECTGUID"
     
    3434}
    3535echo "Checking"
     36rndc flush
    3637host $HOSTNAME.$DOMAIN
    3738host $OBJECTGUID._msdcs.$DOMAIN
  • vendor/current/source4/scripting/bin/smbstatus

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22# -*- coding: utf-8 -*-
    33#
  • vendor/current/source4/scripting/bin/subunitrun

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Simple subunit testrunner for python
     
    2222# Find right directory when running from source tree
    2323sys.path.insert(0, "bin/python")
    24 sys.path.insert(1, "../lib/subunit/python")
    2524
    26 from subunit import SubunitTestRunner
    27 from unittest import TestProgram
    2825import optparse
    29 import os
    30 from samba import param
     26import samba
     27samba.ensure_external_module("testtools", "testtools")
     28samba.ensure_external_module("subunit", "subunit/python")
     29from subunit.run import SubunitTestRunner
    3130import samba.getopt as options
    3231import samba.tests
     32
    3333
    3434parser = optparse.OptionParser("subunitrun [options] <tests>")
    3535credopts = options.CredentialsOptions(parser)
    3636parser.add_option_group(credopts)
    37 sambaopts = options.SambaOptions(parser)
    38 parser.add_option_group(sambaopts)
    39 parser.add_option_group(options.VersionOptions(parser))
     37try:
     38    from subunit.run import TestProgram
     39except ImportError:
     40    from unittest import TestProgram
     41else:
     42    parser.add_option('-l', '--list', dest='listtests', default=False,
     43                      help='List tests rather than running them.',
     44                      action="store_true")
    4045
    41 args = parser.parse_args()[1]
     46opts, args = parser.parse_args()
    4247
    43 samba.tests.cmdline_loadparm = sambaopts.get_loadparm()
    44 samba.tests.cmdline_credentials = credopts.get_credentials(samba.tests.cmdline_loadparm)
     48samba.tests.cmdline_credentials = credopts.get_credentials(samba.tests.env_loadparm())
     49if getattr(opts, "listtests", False):
     50    args.insert(0, "--list")
    4551
    4652runner = SubunitTestRunner()
  • vendor/current/source4/scripting/python/examples/netbios.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation.
  • vendor/current/source4/scripting/python/examples/samr.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22# -*- coding: utf-8 -*-
    33
  • vendor/current/source4/scripting/python/examples/winreg.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22#
    33#  tool to manipulate a remote registry
  • vendor/current/source4/scripting/python/modules.c

    r414 r740  
    1818*/
    1919
     20#include <Python.h>
    2021#include "includes.h"
    2122#include "scripting/python/modules.h"
    22 #include <Python.h>
     23#include "dynconfig/dynconfig.h"
    2324
    24 extern void init_ldb(void);
    25 extern void init_security(void);
    26 extern void init_registry(void);
    27 extern void init_param(void);
    28 extern void init_misc(void);
    29 extern void init_ldb(void);
    30 extern void init_auth(void);
    31 extern void init_credentials(void);
    32 extern void init_tdb(void);
    33 extern void init_dcerpc(void);
    34 extern void init_events(void);
    35 extern void inituuid(void);
    36 extern void init_net(void);
    37 extern void initecho(void);
    38 extern void initdfs(void);
    39 extern void initdrsuapi(void);
    40 extern void initwinreg(void);
    41 extern void initepmapper(void);
    42 extern void initinitshutdown(void);
    43 extern void initmgmt(void);
    44 extern void initnet(void);
    45 extern void initatsvc(void);
    46 extern void initsamr(void);
    47 extern void initlsa(void);
    48 extern void initsvcctl(void);
    49 extern void initwkssvc(void);
    50 extern void initunixinfo(void);
    51 extern void init_libcli_nbt(void);
    52 extern void init_libcli_smb(void);
     25static bool PySys_PathPrepend(PyObject *list, const char *path)
     26{
     27        PyObject *py_path = PyString_FromString(path);
     28        if (py_path == NULL)
     29                return false;
    5330
    54 static struct _inittab py_modules[] = { STATIC_LIBPYTHON_MODULES };
    55 
    56 void py_load_samba_modules(void)
    57 {
    58         int i;
    59         for (i = 0; i < ARRAY_SIZE(py_modules); i++) {
    60                 PyImport_ExtendInittab(&py_modules[i]);
    61         }
     31        return (PyList_Insert(list, 0, py_path) == 0);
    6232}
    6333
    64 void py_update_path(const char *bindir)
     34bool py_update_path(void)
    6535{
    66         char *newpath;
    67         asprintf(&newpath, "%s/python:%s/../scripting/python:%s", bindir, bindir, Py_GetPath());
    68         PySys_SetPath(newpath);
    69         free(newpath);
     36        PyObject *mod_sys, *py_path;
     37
     38        mod_sys = PyImport_ImportModule("sys");
     39        if (mod_sys == NULL) {
     40                return false;
     41        }
     42
     43        py_path = PyObject_GetAttrString(mod_sys, "path");
     44        if (py_path == NULL) {
     45                return false;
     46        }       
     47
     48        if (!PyList_Check(py_path)) {
     49                return false;
     50        }
     51
     52        if (!PySys_PathPrepend(py_path, dyn_PYTHONDIR)) {
     53                return false;
     54        }
     55
     56        if (strcmp(dyn_PYTHONARCHDIR, dyn_PYTHONDIR) != 0) {
     57                if (!PySys_PathPrepend(py_path, dyn_PYTHONARCHDIR)) {
     58                        return false;
     59                }
     60        }
     61
     62        return true;
    7063}
  • vendor/current/source4/scripting/python/modules.h

    r414 r740  
    2121#define __SAMBA_PYTHON_MODULES_H__
    2222
    23 void py_load_samba_modules(void);
    24 void py_update_path(const char *bindir);
    25 
    26 #define py_iconv_convenience(mem_ctx) smb_iconv_convenience_init(mem_ctx, "ASCII", PyUnicode_GetDefaultEncoding(), true)
     23bool py_update_path(void);
    2724
    2825#endif /* __SAMBA_PYTHON_MODULES_H__ */
  • vendor/current/source4/scripting/python/pyglue.c

    r414 r740  
    1818*/
    1919
     20#include <Python.h>
    2021#include "includes.h"
    21 #include "ldb.h"
    22 #include "ldb_errors.h"
    23 #include "ldb_wrap.h"
    24 #include "param/param.h"
    25 #include "auth/credentials/credentials.h"
    26 #include "dsdb/samdb/samdb.h"
    27 #include "lib/ldb-samba/ldif_handlers.h"
    28 #include "librpc/ndr/libndr.h"
    2922#include "version.h"
    30 #include <Python.h>
    31 #include "lib/ldb/pyldb.h"
    32 #include "libcli/util/pyerrors.h"
    33 #include "libcli/security/security.h"
    34 #include "auth/pyauth.h"
    3523#include "param/pyparam.h"
    36 #include "auth/credentials/pycredentials.h"
    37 
    38 #ifndef Py_RETURN_NONE
    39 #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
    40 #endif
    41 
    42 /* FIXME: These should be in a header file somewhere, once we finish moving
    43  * away from SWIG .. */
    44 #define PyErr_LDB_OR_RAISE(py_ldb, ldb) \
    45 /*      if (!PyLdb_Check(py_ldb)) { \
    46                 PyErr_SetString(py_ldb_get_exception(), "Ldb connection object required"); \
    47                 return NULL; \
    48         } */\
    49         ldb = PyLdb_AsLdbContext(py_ldb);
    50 
    51 static void PyErr_SetLdbError(PyObject *error, int ret, struct ldb_context *ldb_ctx)
    52 {
    53         if (ret == LDB_ERR_PYTHON_EXCEPTION)
    54                 return; /* Python exception should already be set, just keep that */
    55 
    56         PyErr_SetObject(error,
    57                                         Py_BuildValue(discard_const_p(char, "(i,s)"), ret,
    58                                   ldb_ctx == NULL?ldb_strerror(ret):ldb_errstring(ldb_ctx)));
    59 }
    60 
    61 static PyObject *py_ldb_get_exception(void)
    62 {
    63         PyObject *mod = PyImport_ImportModule("ldb");
    64         if (mod == NULL)
    65                 return NULL;
    66 
    67         return PyObject_GetAttrString(mod, "LdbError");
    68 }
     24#include "lib/socket/netif.h"
     25
     26void init_glue(void);
    6927
    7028static PyObject *py_generate_random_str(PyObject *self, PyObject *args)
     
    8240}
    8341
     42static PyObject *py_generate_random_password(PyObject *self, PyObject *args)
     43{
     44        int min, max;
     45        PyObject *ret;
     46        char *retstr;
     47        if (!PyArg_ParseTuple(args, "ii", &min, &max))
     48                return NULL;
     49
     50        retstr = generate_random_password(NULL, min, max);
     51        if (retstr == NULL) {
     52                return NULL;
     53        }
     54        ret = PyString_FromString(retstr);
     55        talloc_free(retstr);
     56        return ret;
     57}
     58
    8459static PyObject *py_unix2nttime(PyObject *self, PyObject *args)
    8560{
     
    9166        unix_to_nt_time(&nt, t);
    9267
    93         return PyInt_FromLong((uint64_t)nt);
     68        return PyLong_FromLongLong((uint64_t)nt);
     69}
     70
     71static PyObject *py_nttime2unix(PyObject *self, PyObject *args)
     72{
     73        time_t t;
     74        NTTIME nt;
     75        if (!PyArg_ParseTuple(args, "K", &nt))
     76                return NULL;
     77
     78        t = nt_time_to_unix(nt);
     79
     80        return PyInt_FromLong((uint64_t)t);
     81}
     82
     83static PyObject *py_nttime2string(PyObject *self, PyObject *args)
     84{
     85        PyObject *ret;
     86        NTTIME nt;
     87        TALLOC_CTX *tmp_ctx;
     88        const char *string;
     89        if (!PyArg_ParseTuple(args, "K", &nt))
     90                return NULL;
     91
     92        tmp_ctx = talloc_new(NULL);
     93        if (tmp_ctx == NULL) {
     94                PyErr_NoMemory();
     95                return NULL;
     96        }
     97
     98        string = nt_time_string(tmp_ctx, nt);
     99        ret =  PyString_FromString(string);
     100
     101        talloc_free(tmp_ctx);
     102
     103        return ret;
    94104}
    95105
     
    103113}
    104114
    105 static PyObject *py_ldb_set_credentials(PyObject *self, PyObject *args)
    106 {
    107         PyObject *py_creds, *py_ldb;
    108         struct cli_credentials *creds;
    109         struct ldb_context *ldb;
    110         if (!PyArg_ParseTuple(args, "OO", &py_ldb, &py_creds))
    111                 return NULL;
    112 
    113         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    114        
    115         creds = cli_credentials_from_py_object(py_creds);
    116         if (creds == NULL) {
    117                 PyErr_SetString(PyExc_TypeError, "Expected credentials object");
    118                 return NULL;
    119         }
    120 
    121         ldb_set_opaque(ldb, "credentials", creds);
    122 
    123         Py_RETURN_NONE;
    124 }
    125 
    126 static PyObject *py_ldb_set_loadparm(PyObject *self, PyObject *args)
    127 {
    128         PyObject *py_lp_ctx, *py_ldb;
     115static PyObject *py_get_debug_level(PyObject *self)
     116{
     117        return PyInt_FromLong(DEBUGLEVEL);
     118}
     119
     120/*
     121  return the list of interface IPs we have configured
     122  takes an loadparm context, returns a list of IPs in string form
     123
     124  Does not return addresses on 127.0.0.0/8
     125 */
     126static PyObject *py_interface_ips(PyObject *self, PyObject *args)
     127{
     128        PyObject *pylist;
     129        int count;
     130        TALLOC_CTX *tmp_ctx;
     131        PyObject *py_lp_ctx;
    129132        struct loadparm_context *lp_ctx;
    130         struct ldb_context *ldb;
    131         if (!PyArg_ParseTuple(args, "OO", &py_ldb, &py_lp_ctx))
    132                 return NULL;
    133 
    134         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    135 
    136         lp_ctx = lp_from_py_object(py_lp_ctx);
     133        struct interface *ifaces;
     134        int i, ifcount;
     135        int all_interfaces;
     136
     137        if (!PyArg_ParseTuple(args, "Oi", &py_lp_ctx, &all_interfaces))
     138                return NULL;
     139
     140        tmp_ctx = talloc_new(NULL);
     141        if (tmp_ctx == NULL) {
     142                PyErr_NoMemory();
     143                return NULL;
     144        }
     145
     146        lp_ctx = lpcfg_from_py_object(tmp_ctx, py_lp_ctx);
    137147        if (lp_ctx == NULL) {
    138                 PyErr_SetString(PyExc_TypeError, "Expected loadparm object");
    139                 return NULL;
    140         }
    141 
    142         ldb_set_opaque(ldb, "loadparm", lp_ctx);
    143 
    144         Py_RETURN_NONE;
    145 }
    146 
    147 
    148 static PyObject *py_ldb_set_session_info(PyObject *self, PyObject *args)
    149 {
    150         PyObject *py_session_info, *py_ldb;
    151         struct auth_session_info *info;
    152         struct ldb_context *ldb;
    153         if (!PyArg_ParseTuple(args, "OO", &py_ldb, &py_session_info))
    154                 return NULL;
    155 
    156         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    157         /*if (!PyAuthSession_Check(py_session_info)) {
    158                 PyErr_SetString(PyExc_TypeError, "Expected session info object");
    159                 return NULL;
    160         }*/
    161 
    162         info = PyAuthSession_AsSession(py_session_info);
    163 
    164         ldb_set_opaque(ldb, "sessionInfo", info);
    165 
    166         Py_RETURN_NONE;
    167 }
    168 
    169 static PyObject *py_ldb_set_utf8_casefold(PyObject *self, PyObject *args)
    170 {
    171         PyObject *py_ldb;
    172         struct ldb_context *ldb;
    173 
    174         if (!PyArg_ParseTuple(args, "O", &py_ldb))
    175                 return NULL;
    176 
    177         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    178 
    179         ldb_set_utf8_fns(ldb, NULL, wrap_casefold);
    180 
    181         Py_RETURN_NONE;
    182 }
    183 
    184 static PyObject *py_samdb_set_domain_sid(PyLdbObject *self, PyObject *args)
    185 {
    186         PyObject *py_ldb, *py_sid;
    187         struct ldb_context *ldb;
    188         struct dom_sid *sid;
    189         bool ret;
    190 
    191         if (!PyArg_ParseTuple(args, "OO", &py_ldb, &py_sid))
    192                 return NULL;
    193        
    194         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    195 
    196         sid = dom_sid_parse_talloc(NULL, PyString_AsString(py_sid));
    197 
    198         ret = samdb_set_domain_sid(ldb, sid);
    199         if (!ret) {
    200                 PyErr_SetString(PyExc_RuntimeError, "set_domain_sid failed");
    201                 return NULL;
    202         }
    203         Py_RETURN_NONE;
    204 }
    205 
    206 static PyObject *py_samdb_get_domain_sid(PyLdbObject *self, PyObject *args)
    207 {
    208         PyObject *py_ldb;
    209         struct ldb_context *ldb;
    210         const struct dom_sid *sid;
    211         PyObject *ret;
    212         char *retstr;
    213 
    214         if (!PyArg_ParseTuple(args, "O", &py_ldb))
    215                 return NULL;
    216        
    217         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    218 
    219         sid = samdb_domain_sid(ldb);
    220         if (!sid) {
    221                 PyErr_SetString(PyExc_RuntimeError, "samdb_domain_sid failed");
    222                 return NULL;
    223         }
    224         retstr = dom_sid_string(NULL, sid);
    225         ret = PyString_FromString(retstr);
    226         talloc_free(retstr);
    227         return ret;
    228 }
    229 
    230 static PyObject *py_ldb_register_samba_handlers(PyObject *self, PyObject *args)
    231 {
    232         PyObject *py_ldb;
    233         struct ldb_context *ldb;
    234         int ret;
    235 
    236         if (!PyArg_ParseTuple(args, "O", &py_ldb))
    237                 return NULL;
    238 
    239         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    240         ret = ldb_register_samba_handlers(ldb);
    241 
    242         PyErr_LDB_ERROR_IS_ERR_RAISE(py_ldb_get_exception(), ret, ldb);
    243         Py_RETURN_NONE;
    244 }
    245 
    246 static PyObject *py_dsdb_set_ntds_invocation_id(PyObject *self, PyObject *args)
    247 {
    248         PyObject *py_ldb, *py_guid;
    249         bool ret;
    250         struct GUID guid;
    251         struct ldb_context *ldb;
    252         if (!PyArg_ParseTuple(args, "OO", &py_ldb, &py_guid))
    253                 return NULL;
    254 
    255         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    256         GUID_from_string(PyString_AsString(py_guid), &guid);
    257 
    258         ret = samdb_set_ntds_invocation_id(ldb, &guid);
    259         if (!ret) {
    260                 PyErr_SetString(PyExc_RuntimeError, "set_ntds_invocation_id failed");
    261                 return NULL;
    262         }
    263         Py_RETURN_NONE;
    264 }
    265 
    266 static PyObject *py_dsdb_set_opaque_integer(PyObject *self, PyObject *args)
    267 {
    268         PyObject *py_ldb;
    269         int value;
    270         int *old_val, *new_val;
    271         char *py_opaque_name, *opaque_name_talloc;
    272         struct ldb_context *ldb;
    273         TALLOC_CTX *tmp_ctx;
    274 
    275         if (!PyArg_ParseTuple(args, "Osi", &py_ldb, &py_opaque_name, &value))
    276                 return NULL;
    277 
    278         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    279 
    280         /* see if we have a cached copy */
    281         old_val = (int *)ldb_get_opaque(ldb,
    282                                         py_opaque_name);
    283 
    284         if (old_val) {
    285                 *old_val = value;
    286                 Py_RETURN_NONE;
    287         }
    288 
    289         tmp_ctx = talloc_new(ldb);
    290         if (tmp_ctx == NULL) {
    291                 goto failed;
    292         }
    293        
    294         new_val = talloc(tmp_ctx, int);
    295         if (!new_val) {
    296                 goto failed;
    297         }
    298        
    299         opaque_name_talloc = talloc_strdup(tmp_ctx, py_opaque_name);
    300         if (!opaque_name_talloc) {
    301                 goto failed;
    302         }
    303        
    304         *new_val = value;
    305 
    306         /* cache the domain_sid in the ldb */
    307         if (ldb_set_opaque(ldb, opaque_name_talloc, new_val) != LDB_SUCCESS) {
    308                 goto failed;
    309         }
    310 
    311         talloc_steal(ldb, new_val);
    312         talloc_steal(ldb, opaque_name_talloc);
     148                talloc_free(tmp_ctx);
     149                return NULL;
     150        }
     151
     152        load_interfaces(tmp_ctx, lpcfg_interfaces(lp_ctx), &ifaces);
     153
     154        count = iface_count(ifaces);
     155
     156        /* first count how many are not loopback addresses */
     157        for (ifcount = i = 0; i<count; i++) {
     158                const char *ip = iface_n_ip(ifaces, i);
     159                if (!(!all_interfaces && iface_same_net(ip, "127.0.0.1", "255.0.0.0"))) {
     160                        ifcount++;
     161                }
     162        }
     163
     164        pylist = PyList_New(ifcount);
     165        for (ifcount = i = 0; i<count; i++) {
     166                const char *ip = iface_n_ip(ifaces, i);
     167                if (!(!all_interfaces && iface_same_net(ip, "127.0.0.1", "255.0.0.0"))) {
     168                        PyList_SetItem(pylist, ifcount, PyString_FromString(ip));
     169                        ifcount++;
     170                }
     171        }
    313172        talloc_free(tmp_ctx);
    314 
    315         Py_RETURN_NONE;
    316 
    317 failed:
    318         talloc_free(tmp_ctx);
    319         PyErr_SetString(PyExc_RuntimeError, "Failed to set opaque integer into the ldb!\n");
    320         return NULL;
    321 }
    322 
    323 static PyObject *py_dsdb_set_global_schema(PyObject *self, PyObject *args)
    324 {
    325         PyObject *py_ldb;
    326         struct ldb_context *ldb;
    327         int ret;
    328         if (!PyArg_ParseTuple(args, "O", &py_ldb))
    329                 return NULL;
    330 
    331         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    332 
    333         ret = dsdb_set_global_schema(ldb);
    334         PyErr_LDB_ERROR_IS_ERR_RAISE(py_ldb_get_exception(), ret, ldb);
    335 
    336         Py_RETURN_NONE;
    337 }
    338 
    339 static PyObject *py_dsdb_set_schema_from_ldif(PyObject *self, PyObject *args)
    340 {
    341         WERROR result;
    342         char *pf, *df;
    343         PyObject *py_ldb;
    344         struct ldb_context *ldb;
    345 
    346         if (!PyArg_ParseTuple(args, "Oss", &py_ldb, &pf, &df))
    347                 return NULL;
    348 
    349         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    350 
    351         result = dsdb_set_schema_from_ldif(ldb, pf, df);
    352         PyErr_WERROR_IS_ERR_RAISE(result);
    353 
    354         Py_RETURN_NONE;
    355 }
    356 
    357 static PyObject *py_dsdb_convert_schema_to_openldap(PyObject *self, PyObject *args)
    358 {
    359         char *target_str, *mapping;
    360         PyObject *py_ldb;
    361         struct ldb_context *ldb;
    362         PyObject *ret;
    363         char *retstr;
    364 
    365         if (!PyArg_ParseTuple(args, "Oss", &py_ldb, &target_str, &mapping))
    366                 return NULL;
    367 
    368         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    369 
    370         retstr = dsdb_convert_schema_to_openldap(ldb, target_str, mapping);
    371         if (!retstr) {
    372                 PyErr_SetString(PyExc_RuntimeError, "dsdb_convert_schema_to_openldap failed");
    373                 return NULL;
    374         }
    375         ret = PyString_FromString(retstr);
    376         talloc_free(retstr);
    377         return ret;
    378 }
    379 
    380 static PyObject *py_dsdb_write_prefixes_from_schema_to_ldb(PyObject *self, PyObject *args)
    381 {
    382         PyObject *py_ldb;
    383         struct ldb_context *ldb;
    384         WERROR result;
    385         struct dsdb_schema *schema;
    386 
    387         if (!PyArg_ParseTuple(args, "O", &py_ldb))
    388                 return NULL;
    389 
    390         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    391 
    392         schema = dsdb_get_schema(ldb);
    393         if (!schema) {
    394                 PyErr_SetString(PyExc_RuntimeError, "Failed to set find a schema on ldb!\n");
    395                 return NULL;
    396         }
    397 
    398         result = dsdb_write_prefixes_from_schema_to_ldb(NULL, ldb, schema);
    399         PyErr_WERROR_IS_ERR_RAISE(result);
    400 
    401         Py_RETURN_NONE;
    402 }
    403 
    404 static PyObject *py_dsdb_set_schema_from_ldb(PyObject *self, PyObject *args)
    405 {
    406         PyObject *py_ldb;
    407         struct ldb_context *ldb;
    408         PyObject *py_from_ldb;
    409         struct ldb_context *from_ldb;
    410         struct dsdb_schema *schema;
    411         int ret;
    412         if (!PyArg_ParseTuple(args, "OO", &py_ldb, &py_from_ldb))
    413                 return NULL;
    414 
    415         PyErr_LDB_OR_RAISE(py_ldb, ldb);
    416 
    417         PyErr_LDB_OR_RAISE(py_from_ldb, from_ldb);
    418 
    419         schema = dsdb_get_schema(from_ldb);
    420         if (!schema) {
    421                 PyErr_SetString(PyExc_RuntimeError, "Failed to set find a schema on 'from' ldb!\n");
    422                 return NULL;
    423         }
    424 
    425         ret = dsdb_reference_schema(ldb, schema, true);
    426         PyErr_LDB_ERROR_IS_ERR_RAISE(py_ldb_get_exception(), ret, ldb);
    427 
    428         Py_RETURN_NONE;
    429 }
    430 
    431 static PyObject *py_dom_sid_to_rid(PyLdbObject *self, PyObject *args)
    432 {
    433         PyObject *py_sid;
    434         struct dom_sid *sid;
    435         uint32_t rid;
    436         NTSTATUS status;
    437        
    438         if(!PyArg_ParseTuple(args, "O", &py_sid))
    439                 return NULL;
    440 
    441         sid = dom_sid_parse_talloc(NULL, PyString_AsString(py_sid));
    442 
    443         status = dom_sid_split_rid(NULL, sid, NULL, &rid);
    444         if (!NT_STATUS_IS_OK(status)) {
    445                 PyErr_SetString(PyExc_RuntimeError, "dom_sid_split_rid failed");
    446                 return NULL;
    447         }
    448 
    449         return PyInt_FromLong(rid);
     173        return pylist;
    450174}
    451175
    452176static PyMethodDef py_misc_methods[] = {
    453177        { "generate_random_str", (PyCFunction)py_generate_random_str, METH_VARARGS,
    454                 "random_password(len) -> string\n"
    455                 "Generate random password with specified length." },
     178                "generate_random_str(len) -> string\n"
     179                "Generate random string with specified length." },
     180        { "generate_random_password", (PyCFunction)py_generate_random_password,
     181                METH_VARARGS, "generate_random_password(min, max) -> string\n"
     182                "Generate random password with a length >= min and <= max." },
    456183        { "unix2nttime", (PyCFunction)py_unix2nttime, METH_VARARGS,
    457184                "unix2nttime(timestamp) -> nttime" },
    458         { "ldb_set_credentials", (PyCFunction)py_ldb_set_credentials, METH_VARARGS,
    459                 "ldb_set_credentials(ldb, credentials) -> None\n"
    460                 "Set credentials to use when connecting." },
    461         { "ldb_set_session_info", (PyCFunction)py_ldb_set_session_info, METH_VARARGS,
    462                 "ldb_set_session_info(ldb, session_info)\n"
    463                 "Set session info to use when connecting." },
    464         { "ldb_set_loadparm", (PyCFunction)py_ldb_set_loadparm, METH_VARARGS,
    465                 "ldb_set_loadparm(ldb, session_info)\n"
    466                 "Set loadparm context to use when connecting." },
    467         { "samdb_set_domain_sid", (PyCFunction)py_samdb_set_domain_sid, METH_VARARGS,
    468                 "samdb_set_domain_sid(samdb, sid)\n"
    469                 "Set SID of domain to use." },
    470         { "samdb_get_domain_sid", (PyCFunction)py_samdb_get_domain_sid, METH_VARARGS,
    471                 "samdb_get_domain_sid(samdb)\n"
    472                 "Get SID of domain in use." },
    473         { "ldb_register_samba_handlers", (PyCFunction)py_ldb_register_samba_handlers, METH_VARARGS,
    474                 "ldb_register_samba_handlers(ldb)\n"
    475                 "Register Samba-specific LDB modules and schemas." },
    476         { "ldb_set_utf8_casefold", (PyCFunction)py_ldb_set_utf8_casefold, METH_VARARGS,
    477                 "ldb_set_utf8_casefold(ldb)\n"
    478                 "Set the right Samba casefolding function for UTF8 charset." },
    479         { "dsdb_set_ntds_invocation_id", (PyCFunction)py_dsdb_set_ntds_invocation_id, METH_VARARGS,
    480                 NULL },
    481         { "dsdb_set_opaque_integer", (PyCFunction)py_dsdb_set_opaque_integer, METH_VARARGS,
    482                 NULL },
    483         { "dsdb_set_global_schema", (PyCFunction)py_dsdb_set_global_schema, METH_VARARGS,
    484                 NULL },
    485         { "dsdb_set_schema_from_ldif", (PyCFunction)py_dsdb_set_schema_from_ldif, METH_VARARGS,
    486                 NULL },
    487         { "dsdb_write_prefixes_from_schema_to_ldb", (PyCFunction)py_dsdb_write_prefixes_from_schema_to_ldb, METH_VARARGS,
    488                 NULL },
    489         { "dsdb_set_schema_from_ldb", (PyCFunction)py_dsdb_set_schema_from_ldb, METH_VARARGS,
    490                 NULL },
    491         { "dsdb_convert_schema_to_openldap", (PyCFunction)py_dsdb_convert_schema_to_openldap, METH_VARARGS,
    492                 NULL },
    493         { "dom_sid_to_rid", (PyCFunction)py_dom_sid_to_rid, METH_VARARGS,
    494                 NULL },
     185        { "nttime2unix", (PyCFunction)py_nttime2unix, METH_VARARGS,
     186                "nttime2unix(nttime) -> timestamp" },
     187        { "nttime2string", (PyCFunction)py_nttime2string, METH_VARARGS,
     188                "nttime2string(nttime) -> string" },
    495189        { "set_debug_level", (PyCFunction)py_set_debug_level, METH_VARARGS,
    496190                "set debug level" },
     191        { "get_debug_level", (PyCFunction)py_get_debug_level, METH_NOARGS,
     192                "get debug level" },
     193        { "interface_ips", (PyCFunction)py_interface_ips, METH_VARARGS,
     194                "get interface IP address list"},
    497195        { NULL }
    498196};
    499197
    500 void initglue(void)
     198void init_glue(void)
    501199{
    502200        PyObject *m;
    503201
    504         m = Py_InitModule3("glue", py_misc_methods,
     202        debug_setup_talloc_log();
     203
     204        m = Py_InitModule3("_glue", py_misc_methods,
    505205                           "Python bindings for miscellaneous Samba functions.");
    506206        if (m == NULL)
    507207                return;
    508208
    509         PyModule_AddObject(m, "version", PyString_FromString(SAMBA_VERSION_STRING));
    510 
    511         /* "userAccountControl" flags */
    512         PyModule_AddObject(m, "UF_NORMAL_ACCOUNT", PyInt_FromLong(UF_NORMAL_ACCOUNT));
    513         PyModule_AddObject(m, "UF_TEMP_DUPLICATE_ACCOUNT", PyInt_FromLong(UF_TEMP_DUPLICATE_ACCOUNT));
    514         PyModule_AddObject(m, "UF_SERVER_TRUST_ACCOUNT", PyInt_FromLong(UF_SERVER_TRUST_ACCOUNT));
    515         PyModule_AddObject(m, "UF_WORKSTATION_TRUST_ACCOUNT", PyInt_FromLong(UF_WORKSTATION_TRUST_ACCOUNT));
    516         PyModule_AddObject(m, "UF_INTERDOMAIN_TRUST_ACCOUNT", PyInt_FromLong(UF_INTERDOMAIN_TRUST_ACCOUNT));
    517         PyModule_AddObject(m, "UF_PASSWD_NOTREQD", PyInt_FromLong(UF_PASSWD_NOTREQD));
    518         PyModule_AddObject(m, "UF_ACCOUNTDISABLE", PyInt_FromLong(UF_ACCOUNTDISABLE));
    519 
    520         /* "groupType" flags */
    521         PyModule_AddObject(m, "GTYPE_SECURITY_BUILTIN_LOCAL_GROUP", PyInt_FromLong(GTYPE_SECURITY_BUILTIN_LOCAL_GROUP));
    522         PyModule_AddObject(m, "GTYPE_SECURITY_GLOBAL_GROUP", PyInt_FromLong(GTYPE_SECURITY_GLOBAL_GROUP));
    523         PyModule_AddObject(m, "GTYPE_SECURITY_DOMAIN_LOCAL_GROUP", PyInt_FromLong(GTYPE_SECURITY_DOMAIN_LOCAL_GROUP));
    524         PyModule_AddObject(m, "GTYPE_SECURITY_UNIVERSAL_GROUP", PyInt_FromLong(GTYPE_SECURITY_UNIVERSAL_GROUP));
    525         PyModule_AddObject(m, "GTYPE_DISTRIBUTION_GLOBAL_GROUP", PyInt_FromLong(GTYPE_DISTRIBUTION_GLOBAL_GROUP));
    526         PyModule_AddObject(m, "GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP", PyInt_FromLong(GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP));
    527         PyModule_AddObject(m, "GTYPE_DISTRIBUTION_UNIVERSAL_GROUP", PyInt_FromLong(GTYPE_DISTRIBUTION_UNIVERSAL_GROUP));
    528 
    529         /* "sAMAccountType" flags */
    530         PyModule_AddObject(m, "ATYPE_NORMAL_ACCOUNT", PyInt_FromLong(ATYPE_NORMAL_ACCOUNT));
    531         PyModule_AddObject(m, "ATYPE_WORKSTATION_TRUST", PyInt_FromLong(ATYPE_WORKSTATION_TRUST));
    532         PyModule_AddObject(m, "ATYPE_INTERDOMAIN_TRUST", PyInt_FromLong(ATYPE_INTERDOMAIN_TRUST));
    533         PyModule_AddObject(m, "ATYPE_SECURITY_GLOBAL_GROUP", PyInt_FromLong(ATYPE_SECURITY_GLOBAL_GROUP));
    534         PyModule_AddObject(m, "ATYPE_SECURITY_LOCAL_GROUP", PyInt_FromLong(ATYPE_SECURITY_LOCAL_GROUP));
    535         PyModule_AddObject(m, "ATYPE_SECURITY_UNIVERSAL_GROUP", PyInt_FromLong(ATYPE_SECURITY_UNIVERSAL_GROUP));
    536         PyModule_AddObject(m, "ATYPE_DISTRIBUTION_GLOBAL_GROUP", PyInt_FromLong(ATYPE_DISTRIBUTION_GLOBAL_GROUP));
    537         PyModule_AddObject(m, "ATYPE_DISTRIBUTION_LOCAL_GROUP", PyInt_FromLong(ATYPE_DISTRIBUTION_LOCAL_GROUP));
    538         PyModule_AddObject(m, "ATYPE_DISTRIBUTION_UNIVERSAL_GROUP", PyInt_FromLong(ATYPE_DISTRIBUTION_UNIVERSAL_GROUP));
    539 
    540         /* "domainFunctionality", "forestFunctionality" flags in the rootDSE */
    541         PyModule_AddObject(m, "DS_DOMAIN_FUNCTION_2000", PyInt_FromLong(DS_DOMAIN_FUNCTION_2000));
    542         PyModule_AddObject(m, "DS_DOMAIN_FUNCTION_2003_MIXED", PyInt_FromLong(DS_DOMAIN_FUNCTION_2003_MIXED));
    543         PyModule_AddObject(m, "DS_DOMAIN_FUNCTION_2003", PyInt_FromLong(DS_DOMAIN_FUNCTION_2003));
    544         PyModule_AddObject(m, "DS_DOMAIN_FUNCTION_2008", PyInt_FromLong(DS_DOMAIN_FUNCTION_2008));
    545         PyModule_AddObject(m, "DS_DOMAIN_FUNCTION_2008_R2", PyInt_FromLong(DS_DOMAIN_FUNCTION_2008_R2));
    546 
    547         /* "domainControllerFunctionality" flags in the rootDSE */
    548         PyModule_AddObject(m, "DS_DC_FUNCTION_2000", PyInt_FromLong(DS_DC_FUNCTION_2000));
    549         PyModule_AddObject(m, "DS_DC_FUNCTION_2003", PyInt_FromLong(DS_DC_FUNCTION_2003));
    550         PyModule_AddObject(m, "DS_DC_FUNCTION_2008", PyInt_FromLong(DS_DC_FUNCTION_2008));
    551         PyModule_AddObject(m, "DS_DC_FUNCTION_2008_R2", PyInt_FromLong(DS_DC_FUNCTION_2008_R2));
    552 }
    553 
     209        PyModule_AddObject(m, "version",
     210                                           PyString_FromString(SAMBA_VERSION_STRING));
     211
     212        /* one of the most annoying things about python scripts is
     213           that they don't die when you hit control-C. This fixes that
     214           sillyness. As we do all database operations using
     215           transactions, this is also safe.
     216        */
     217        signal(SIGINT, SIG_DFL);
     218}
     219
  • vendor/current/source4/scripting/python/samba/__init__.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation.
    44# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
    5 # 
     5#
    66# Based on the original in EJS:
    77# Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
    8 #   
     8#
    99# This program is free software; you can redistribute it and/or modify
    1010# it under the terms of the GNU General Public License as published by
    1111# the Free Software Foundation; either version 3 of the License, or
    1212# (at your option) any later version.
    13 #   
     13#
    1414# This program is distributed in the hope that it will be useful,
    1515# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1616# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1717# GNU General Public License for more details.
    18 #   
     18#
    1919# You should have received a copy of the GNU General Public License
    2020# along with this program.  If not, see <http://www.gnu.org/licenses/>.
     
    2626
    2727import os
    28 
    29 def _in_source_tree():
    30     """Check whether the script is being run from the source dir. """
    31     return os.path.exists("%s/../../../selftest/skip" % os.path.dirname(__file__))
    32 
    33 
    34 # When running, in-tree, make sure bin/python is in the PYTHONPATH
    35 if _in_source_tree():
    36     import sys
    37     srcdir = "%s/../../.." % os.path.dirname(__file__)
    38     sys.path.append("%s/bin/python" % srcdir)
    39     default_ldb_modules_dir = "%s/bin/modules/ldb" % srcdir
    40 else:
    41     default_ldb_modules_dir = None
     28import sys
     29
     30def source_tree_topdir():
     31    '''return the top level directory (the one containing the source4 directory)'''
     32    paths = [ "../../..", "../../../.." ]
     33    for p in paths:
     34        topdir = os.path.normpath(os.path.join(os.path.dirname(__file__), p))
     35        if os.path.exists(os.path.join(topdir, 'source4')):
     36            return topdir
     37    raise RuntimeError("unable to find top level source directory")
     38
     39def in_source_tree():
     40    '''return True if we are running from within the samba source tree'''
     41    try:
     42        topdir = source_tree_topdir()
     43    except RuntimeError:
     44        return False
     45    return True
     46
    4247
    4348
    4449import ldb
    45 import glue
    46 
    47 class Ldb(ldb.Ldb):
    48     """Simple Samba-specific LDB subclass that takes care 
     50from samba._ldb import Ldb as _Ldb
     51
     52class Ldb(_Ldb):
     53    """Simple Samba-specific LDB subclass that takes care
    4954    of setting up the modules dir, credentials pointers, etc.
    50    
    51     Please note that this is intended to be for all Samba LDB files, 
    52     not necessarily the Sam database. For Sam-specific helper 
     55
     56    Please note that this is intended to be for all Samba LDB files,
     57    not necessarily the Sam database. For Sam-specific helper
    5358    functions see samdb.py.
    5459    """
     60
    5561    def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
    5662                 credentials=None, flags=0, options=None):
     
    6672
    6773        This is different from a regular Ldb file in that the Samba-specific
    68         modules-dir is used by default and that credentials and session_info 
     74        modules-dir is used by default and that credentials and session_info
    6975        can be passed through (required by some modules).
    7076        """
     
    7278        if modules_dir is not None:
    7379            self.set_modules_dir(modules_dir)
    74         elif default_ldb_modules_dir is not None:
    75             self.set_modules_dir(default_ldb_modules_dir)
    7680        elif lp is not None:
    7781            self.set_modules_dir(os.path.join(lp.get("modules dir"), "ldb"))
     
    8993        # objectSid and objectGUID etc must take precedence over the 'binary
    9094        # attribute' declaration in the schema
    91         glue.ldb_register_samba_handlers(self)
     95        self.register_samba_handlers()
    9296
    9397        # TODO set debug
    94         def msg(l,text):
     98        def msg(l, text):
    9599            print text
    96100        #self.set_debug(msg)
    97101
    98         glue.ldb_set_utf8_casefold(self)
     102        self.set_utf8_casefold()
    99103
    100104        # Allow admins to force non-sync ldb for all databases
    101105        if lp is not None:
    102106            nosync_p = lp.get("nosync", "ldb")
    103             if nosync_p is not None and nosync_p == true:
    104                 flags |= FLG_NOSYNC
     107            if nosync_p is not None and nosync_p == True:
     108                flags |= ldb.FLG_NOSYNC
     109
     110        self.set_create_perms(0600)
    105111
    106112        if url is not None:
    107113            self.connect(url, flags, options)
    108114
    109     def set_credentials(self, credentials):
    110         glue.ldb_set_credentials(self, credentials)
    111 
    112     def set_session_info(self, session_info):
    113         glue.ldb_set_session_info(self, session_info)
    114 
    115     def set_loadparm(self, lp_ctx):
    116         glue.ldb_set_loadparm(self, lp_ctx)
    117 
    118     def searchone(self, attribute, basedn=None, expression=None,
     115    def searchone(self, attribute, basedn=None, expression=None,
    119116                  scope=ldb.SCOPE_BASE):
    120117        """Search for one attribute as a string.
    121        
     118
    122119        :param basedn: BaseDN for the search.
    123120        :param attribute: Name of the attribute
     
    134131
    135132    def erase_users_computers(self, dn):
    136         """Erases user and computer objects from our AD. This is needed since the 'samldb' module denies the deletion of primary groups. Therefore all groups shouldn't be primary somewhere anymore."""
     133        """Erases user and computer objects from our AD.
     134
     135        This is needed since the 'samldb' module denies the deletion of primary
     136        groups. Therefore all groups shouldn't be primary somewhere anymore.
     137        """
    137138
    138139        try:
    139140            res = self.search(base=dn, scope=ldb.SCOPE_SUBTREE, attrs=[],
    140141                      expression="(|(objectclass=user)(objectclass=computer))")
    141         except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
    142             # Ignore no such object errors
    143             return
    144             pass
     142        except ldb.LdbError, (errno, _):
     143            if errno == ldb.ERR_NO_SUCH_OBJECT:
     144                # Ignore no such object errors
     145                return
     146            else:
     147                raise
    145148
    146149        try:
    147150            for msg in res:
    148                 self.delete(msg.dn)
    149         except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
    150             # Ignore no such object errors
    151             return
     151                self.delete(msg.dn, ["relax:0"])
     152        except ldb.LdbError, (errno, _):
     153            if errno != ldb.ERR_NO_SUCH_OBJECT:
     154                # Ignore no such object errors
     155                raise
    152156
    153157    def erase_except_schema_controlled(self):
    154         """Erase this ldb, removing all records, except those that are controlled by Samba4's schema."""
     158        """Erase this ldb.
     159
     160        :note: Removes all records, except those that are controlled by
     161            Samba4's schema.
     162        """
    155163
    156164        basedn = ""
     
    160168
    161169        # Delete the 'visible' records, and the invisble 'deleted' records (if this DB supports it)
    162         for msg in self.search(basedn, ldb.SCOPE_SUBTREE, 
    163                                "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
    164                                [], controls=["show_deleted:0"]):
     170        for msg in self.search(basedn, ldb.SCOPE_SUBTREE,
     171                       "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
     172                       [], controls=["show_deleted:0", "show_recycled:0"]):
    165173            try:
    166                 self.delete(msg.dn)
    167             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
    168                 # Ignore no such object errors
    169                 pass
    170            
    171         res = self.search(basedn, ldb.SCOPE_SUBTREE,
    172                           "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
    173                           [], controls=["show_deleted:0"])
     174                self.delete(msg.dn, ["relax:0"])
     175            except ldb.LdbError, (errno, _):
     176                if errno != ldb.ERR_NO_SUCH_OBJECT:
     177                    # Ignore no such object errors
     178                    raise
     179
     180        res = self.search(basedn, ldb.SCOPE_SUBTREE,
     181            "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", [], controls=["show_deleted:0", "show_recycled:0"])
    174182        assert len(res) == 0
    175183
    176184        # delete the specials
    177         for attr in ["@SUBCLASSES", "@MODULES", 
     185        for attr in ["@SUBCLASSES", "@MODULES",
    178186                     "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
    179187            try:
    180                 self.delete(attr)
    181             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
    182                 # Ignore missing dn errors
    183                 pass
     188                self.delete(attr, ["relax:0"])
     189            except ldb.LdbError, (errno, _):
     190                if errno != ldb.ERR_NO_SUCH_OBJECT:
     191                    # Ignore missing dn errors
     192                    raise
    184193
    185194    def erase(self):
    186195        """Erase this ldb, removing all records."""
    187        
    188196        self.erase_except_schema_controlled()
    189197
     
    191199        for attr in ["@INDEXLIST", "@ATTRIBUTES"]:
    192200            try:
    193                 self.delete(attr)
    194             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
    195                 # Ignore missing dn errors
    196                 pass
    197 
    198     def erase_partitions(self):
    199         """Erase an ldb, removing all records."""
    200 
    201         def erase_recursive(self, dn):
    202             try:
    203                 res = self.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=[],
    204                                   controls=["show_deleted:0"])
    205             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
    206                 # Ignore no such object errors
    207                 return
    208                 pass
    209            
    210             for msg in res:
    211                 erase_recursive(self, msg.dn)
    212 
    213             try:
    214                 self.delete(dn)
    215             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
    216                 # Ignore no such object errors
    217                 pass
    218 
    219         res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)",
    220                          ["namingContexts"])
    221         assert len(res) == 1
    222         if not "namingContexts" in res[0]:
    223             return
    224         for basedn in res[0]["namingContexts"]:
    225             # Try to delete user/computer accounts to allow deletion of groups
    226             self.erase_users_computers(basedn)
    227             # Try and erase from the bottom-up in the tree
    228             erase_recursive(self, basedn)
     201                self.delete(attr, ["relax:0"])
     202            except ldb.LdbError, (errno, _):
     203                if errno != ldb.ERR_NO_SUCH_OBJECT:
     204                    # Ignore missing dn errors
     205                    raise
    229206
    230207    def load_ldif_file_add(self, ldif_path):
     
    235212        self.add_ldif(open(ldif_path, 'r').read())
    236213
    237     def add_ldif(self, ldif):
     214    def add_ldif(self, ldif, controls=None):
    238215        """Add data based on a LDIF string.
    239216
     
    242219        for changetype, msg in self.parse_ldif(ldif):
    243220            assert changetype == ldb.CHANGETYPE_NONE
    244             self.add(msg)
    245 
    246     def modify_ldif(self, ldif):
     221            self.add(msg, controls)
     222
     223    def modify_ldif(self, ldif, controls=None):
    247224        """Modify database based on a LDIF string.
    248225
     
    250227        """
    251228        for changetype, msg in self.parse_ldif(ldif):
    252             self.modify(msg)
    253 
    254     def set_domain_sid(self, sid):
    255         """Change the domain SID used by this LDB.
    256 
    257         :param sid: The new domain sid to use.
    258         """
    259         glue.samdb_set_domain_sid(self, sid)
    260 
    261     def domain_sid(self):
    262         """Read the domain SID used by this LDB.
    263 
    264         """
    265         glue.samdb_get_domain_sid(self)
    266 
    267     def set_schema_from_ldif(self, pf, df):
    268         glue.dsdb_set_schema_from_ldif(self, pf, df)
    269 
    270     def set_schema_from_ldb(self, ldb):
    271         glue.dsdb_set_schema_from_ldb(self, ldb)
    272 
    273     def write_prefixes_from_schema(self):
    274         glue.dsdb_write_prefixes_from_schema_to_ldb(self)
    275 
    276     def convert_schema_to_openldap(self, target, mapping):
    277         return glue.dsdb_convert_schema_to_openldap(self, target, mapping)
    278 
    279     def set_invocation_id(self, invocation_id):
    280         """Set the invocation id for this SamDB handle.
    281        
    282         :param invocation_id: GUID of the invocation id.
    283         """
    284         glue.dsdb_set_ntds_invocation_id(self, invocation_id)
    285 
    286     def set_opaque_integer(self, name, value):
    287         """Set an integer as an opaque (a flag or other value) value on the database
    288        
    289         :param name: The name for the opaque value
    290         :param value: The integer value
    291         """
    292         glue.dsdb_set_opaque_integer(self, name, value)
     229            if changetype == ldb.CHANGETYPE_ADD:
     230                self.add(msg, controls)
     231            else:
     232                self.modify(msg, controls)
    293233
    294234
    295235def substitute_var(text, values):
    296     """substitute strings of the form ${NAME} in str, replacing
    297     with substitutions from subobj.
    298    
     236    """Substitute strings of the form ${NAME} in str, replacing
     237    with substitutions from values.
     238
    299239    :param text: Text in which to subsitute.
    300240    :param values: Dictionary with keys and values.
     
    310250
    311251def check_all_substituted(text):
    312     """Make sure that all substitution variables in a string have been replaced.
     252    """Check that all substitution variables in a string have been replaced.
     253
    313254    If not, raise an exception.
    314    
     255
    315256    :param text: The text to search for substitution variables
    316257    """
    317258    if not "${" in text:
    318259        return
    319    
     260
    320261    var_start = text.find("${")
    321262    var_end = text.find("}", var_start)
    322    
    323     raise Exception("Not all variables substituted: %s" % text[var_start:var_end+1])
     263
     264    raise Exception("Not all variables substituted: %s" %
     265        text[var_start:var_end+1])
     266
     267
     268def read_and_sub_file(file_name, subst_vars):
     269    """Read a file and sub in variables found in it
     270
     271    :param file_name: File to be read (typically from setup directory)
     272     param subst_vars: Optional variables to subsitute in the file.
     273    """
     274    data = open(file_name, 'r').read()
     275    if subst_vars is not None:
     276        data = substitute_var(data, subst_vars)
     277        check_all_substituted(data)
     278    return data
     279
     280
     281def setup_file(template, fname, subst_vars=None):
     282    """Setup a file in the private dir.
     283
     284    :param template: Path of the template file.
     285    :param fname: Path of the file to create.
     286    :param subst_vars: Substitution variables.
     287    """
     288    if os.path.exists(fname):
     289        os.unlink(fname)
     290
     291    data = read_and_sub_file(template, subst_vars)
     292    f = open(fname, 'w')
     293    try:
     294        f.write(data)
     295    finally:
     296        f.close()
    324297
    325298
     
    335308
    336309
    337 def dom_sid_to_rid(sid_str):
    338     """Converts a domain SID to the relative RID.
    339 
    340     :param sid_str: The domain SID formatted as string
    341     """
    342 
    343     return glue.dom_sid_to_rid(sid_str)
    344 
    345 
    346 version = glue.version
    347 
    348 # "userAccountControl" flags
    349 UF_NORMAL_ACCOUNT = glue.UF_NORMAL_ACCOUNT
    350 UF_TEMP_DUPLICATE_ACCOUNT = glue.UF_TEMP_DUPLICATE_ACCOUNT
    351 UF_SERVER_TRUST_ACCOUNT = glue.UF_SERVER_TRUST_ACCOUNT
    352 UF_WORKSTATION_TRUST_ACCOUNT = glue.UF_WORKSTATION_TRUST_ACCOUNT
    353 UF_INTERDOMAIN_TRUST_ACCOUNT = glue.UF_INTERDOMAIN_TRUST_ACCOUNT
    354 UF_PASSWD_NOTREQD = glue.UF_PASSWD_NOTREQD
    355 UF_ACCOUNTDISABLE = glue.UF_ACCOUNTDISABLE
    356 
    357 # "groupType" flags
    358 GTYPE_SECURITY_BUILTIN_LOCAL_GROUP = glue.GTYPE_SECURITY_BUILTIN_LOCAL_GROUP
    359 GTYPE_SECURITY_GLOBAL_GROUP = glue.GTYPE_SECURITY_GLOBAL_GROUP
    360 GTYPE_SECURITY_DOMAIN_LOCAL_GROUP = glue.GTYPE_SECURITY_DOMAIN_LOCAL_GROUP
    361 GTYPE_SECURITY_UNIVERSAL_GROUP = glue.GTYPE_SECURITY_UNIVERSAL_GROUP
    362 GTYPE_DISTRIBUTION_GLOBAL_GROUP = glue.GTYPE_DISTRIBUTION_GLOBAL_GROUP
    363 GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP = glue.GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP
    364 GTYPE_DISTRIBUTION_UNIVERSAL_GROUP = glue.GTYPE_DISTRIBUTION_UNIVERSAL_GROUP
    365 
    366 # "sAMAccountType" flags
    367 ATYPE_NORMAL_ACCOUNT = glue.ATYPE_NORMAL_ACCOUNT
    368 ATYPE_WORKSTATION_TRUST = glue.ATYPE_WORKSTATION_TRUST
    369 ATYPE_INTERDOMAIN_TRUST = glue.ATYPE_INTERDOMAIN_TRUST
    370 ATYPE_SECURITY_GLOBAL_GROUP = glue.ATYPE_SECURITY_GLOBAL_GROUP
    371 ATYPE_SECURITY_LOCAL_GROUP = glue.ATYPE_SECURITY_LOCAL_GROUP
    372 ATYPE_SECURITY_UNIVERSAL_GROUP = glue.ATYPE_SECURITY_UNIVERSAL_GROUP
    373 ATYPE_DISTRIBUTION_GLOBAL_GROUP = glue.ATYPE_DISTRIBUTION_GLOBAL_GROUP
    374 ATYPE_DISTRIBUTION_LOCAL_GROUP = glue.ATYPE_DISTRIBUTION_LOCAL_GROUP
    375 ATYPE_DISTRIBUTION_UNIVERSAL_GROUP = glue.ATYPE_DISTRIBUTION_UNIVERSAL_GROUP
    376 
    377 # "domainFunctionality", "forestFunctionality" flags in the rootDSE */
    378 DS_DOMAIN_FUNCTION_2000 = glue.DS_DOMAIN_FUNCTION_2000
    379 DS_DOMAIN_FUNCTION_2003_MIXED = glue.DS_DOMAIN_FUNCTION_2003_MIXED
    380 DS_DOMAIN_FUNCTION_2003 = glue.DS_DOMAIN_FUNCTION_2003
    381 DS_DOMAIN_FUNCTION_2008 = glue.DS_DOMAIN_FUNCTION_2008
    382 DS_DOMAIN_FUNCTION_2008_R2 = glue.DS_DOMAIN_FUNCTION_2008_R2
    383 
    384 # "domainControllerFunctionality" flags in the rootDSE */
    385 DS_DC_FUNCTION_2000 = glue.DS_DC_FUNCTION_2000
    386 DS_DC_FUNCTION_2003 = glue.DS_DC_FUNCTION_2003
    387 DS_DC_FUNCTION_2008 = glue.DS_DC_FUNCTION_2008
    388 DS_DC_FUNCTION_2008_R2 = glue.DS_DC_FUNCTION_2008_R2
    389 
     310def import_bundled_package(modulename, location):
     311    """Import the bundled version of a package.
     312
     313    :note: This should only be called if the system version of the package
     314        is not adequate.
     315
     316    :param modulename: Module name to import
     317    :param location: Location to add to sys.path (can be relative to
     318        ${srcdir}/lib)
     319    """
     320    if in_source_tree():
     321        sys.path.insert(0, os.path.join(source_tree_topdir(), "lib", location))
     322        sys.modules[modulename] = __import__(modulename)
     323    else:
     324        sys.modules[modulename] = __import__(
     325            "samba.external.%s" % modulename, fromlist=["samba.external"])
     326
     327
     328def ensure_external_module(modulename, location):
     329    """Add a location to sys.path if an external dependency can't be found.
     330
     331    :param modulename: Module name to import
     332    :param location: Location to add to sys.path (can be relative to
     333        ${srcdir}/lib)
     334    """
     335    try:
     336        __import__(modulename)
     337    except ImportError:
     338        import_bundled_package(modulename, location)
     339
     340
     341from samba import _glue
     342version = _glue.version
     343interface_ips = _glue.interface_ips
     344set_debug_level = _glue.set_debug_level
     345get_debug_level = _glue.get_debug_level
     346unix2nttime = _glue.unix2nttime
     347nttime2string = _glue.nttime2string
     348nttime2unix = _glue.nttime2unix
     349unix2nttime = _glue.unix2nttime
     350generate_random_password = _glue.generate_random_password
  • vendor/current/source4/scripting/python/samba/getopt.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Samba-specific bits for optparse
    44# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
    5 #   
     5#
    66# This program is free software; you can redistribute it and/or modify
    77# it under the terms of the GNU General Public License as published by
    88# the Free Software Foundation; either version 3 of the License, or
    99# (at your option) any later version.
    10 #   
     10#
    1111# This program is distributed in the hope that it will be useful,
    1212# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1313# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1414# GNU General Public License for more details.
    15 #   
     15#
    1616# You should have received a copy of the GNU General Public License
    1717# along with this program.  If not, see <http://www.gnu.org/licenses/>.
     
    2020"""Support for parsing Samba-related command-line options."""
    2121
    22 import optparse
    23 from credentials import Credentials, DONT_USE_KERBEROS, MUST_USE_KERBEROS
    24 from hostconfig import Hostconfig
    25 
    2622__docformat__ = "restructuredText"
     23
     24import optparse, os
     25from samba.credentials import (
     26    Credentials,
     27    DONT_USE_KERBEROS,
     28    MUST_USE_KERBEROS,
     29    )
     30from samba.hostconfig import Hostconfig
     31import sys
     32
    2733
    2834class SambaOptions(optparse.OptionGroup):
    2935    """General Samba-related command line options."""
    30     def __init__(self, parser):
     36
     37    def __init__(self, parser):
     38        from samba.param import LoadParm
    3139        optparse.OptionGroup.__init__(self, parser, "Samba Common Options")
    3240        self.add_option("-s", "--configfile", action="callback",
    33                         type=str, metavar="FILE", help="Configuration file", 
     41                        type=str, metavar="FILE", help="Configuration file",
    3442                        callback=self._load_configfile)
     43        self.add_option("-d", "--debuglevel", action="callback",
     44                        type=int, metavar="DEBUGLEVEL", help="debug level",
     45                        callback=self._set_debuglevel)
     46        self.add_option("--option", action="callback",
     47                        type=str, metavar="OPTION", help="set smb.conf option from command line",
     48                        callback=self._set_option)
     49        self.add_option("--realm", action="callback",
     50                        type=str, metavar="REALM", help="set the realm name",
     51                        callback=self._set_realm)
    3552        self._configfile = None
     53        self._lp = LoadParm()
    3654
    3755    def get_loadparm_path(self):
     
    4260        self._configfile = arg
    4361
     62    def _set_debuglevel(self, option, opt_str, arg, parser):
     63        self._lp.set('debug level', str(arg))
     64
     65    def _set_realm(self, option, opt_str, arg, parser):
     66        self._lp.set('realm', arg)
     67
     68    def _set_option(self, option, opt_str, arg, parser):
     69        if arg.find('=') == -1:
     70            print("--option takes a 'a=b' argument")
     71            sys.exit(1)
     72        a = arg.split('=')
     73        self._lp.set(a[0], a[1])
     74
    4475    def get_loadparm(self):
    4576        """Return a loadparm object with data specified on the command line.  """
    46         import os, param
    47         lp = param.LoadParm()
    4877        if self._configfile is not None:
    49             lp.load(self._configfile)
     78            self._lp.load(self._configfile)
    5079        elif os.getenv("SMB_CONF_PATH") is not None:
    51             lp.load(os.getenv("SMB_CONF_PATH"))
     80            self._lp.load(os.getenv("SMB_CONF_PATH"))
    5281        else:
    53             lp.load_default()
    54         return lp
     82            self._lp.load_default()
     83        return self._lp
    5584
    5685    def get_hostconfig(self):
     
    6291    def __init__(self, parser):
    6392        optparse.OptionGroup.__init__(self, parser, "Version Options")
     93        self.add_option("--version", action="callback",
     94                callback=self._display_version,
     95                help="Display version number")
     96
     97    def _display_version(self, option, opt_str, arg, parser):
     98        import samba
     99        print samba.version
     100        sys.exit(0)
    64101
    65102
     
    67104    """Command line options for specifying credentials."""
    68105    def __init__(self, parser):
    69         self.no_pass = False
     106        self.no_pass = True
     107        self.ipaddress = None
    70108        optparse.OptionGroup.__init__(self, parser, "Credentials Options")
    71109        self.add_option("--simple-bind-dn", metavar="DN", action="callback",
     
    74112        self.add_option("--password", metavar="PASSWORD", action="callback",
    75113                        help="Password", type=str, callback=self._set_password)
    76         self.add_option("-U", "--username", metavar="USERNAME", 
     114        self.add_option("-U", "--username", metavar="USERNAME",
    77115                        action="callback", type=str,
    78116                        help="Username", callback=self._parse_username)
    79         self.add_option("-W", "--workgroup", metavar="WORKGROUP", 
     117        self.add_option("-W", "--workgroup", metavar="WORKGROUP",
    80118                        action="callback", type=str,
    81119                        help="Workgroup", callback=self._parse_workgroup)
    82120        self.add_option("-N", "--no-pass", action="store_true",
    83121                        help="Don't ask for a password")
    84         self.add_option("-k", "--kerberos", metavar="KERBEROS", 
     122        self.add_option("-k", "--kerberos", metavar="KERBEROS",
    85123                        action="callback", type=str,
    86124                        help="Use Kerberos", callback=self._set_kerberos)
     125        self.add_option("", "--ipaddress", metavar="IPADDRESS",
     126                        action="callback", type=str,
     127                        help="IP address of server", callback=self._set_ipaddress)
    87128        self.creds = Credentials()
    88129
     
    95136    def _set_password(self, option, opt_str, arg, parser):
    96137        self.creds.set_password(arg)
     138        self.no_pass = False
     139
     140    def _set_ipaddress(self, option, opt_str, arg, parser):
     141        self.ipaddress = arg
    97142
    98143    def _set_kerberos(self, option, opt_str, arg, parser):
    99         if bool(arg) or arg.lower() == "yes":
     144        if arg.lower() in ["yes", 'true', '1']:
    100145            self.creds.set_kerberos_state(MUST_USE_KERBEROS)
     146        elif arg.lower() in ["no", 'false', '0']:
     147            self.creds.set_kerberos_state(DONT_USE_KERBEROS)
    101148        else:
    102             self.creds.set_kerberos_state(DONT_USE_KERBEROS)
     149            raise optparse.BadOptionErr("invalid kerberos option: %s" % arg)
    103150
    104151    def _set_simple_bind_dn(self, option, opt_str, arg, parser):
    105152        self.creds.set_bind_dn(arg)
    106153
    107     def get_credentials(self, lp):
     154    def get_credentials(self, lp, fallback_machine=False):
    108155        """Obtain the credentials set on the command-line.
    109156
     
    112159        """
    113160        self.creds.guess(lp)
    114         if not self.no_pass:
     161        if self.no_pass:
    115162            self.creds.set_cmdline_callbacks()
     163
     164        # possibly fallback to using the machine account, if we have
     165        # access to the secrets db
     166        if fallback_machine and not self.creds.authentication_requested():
     167            try:
     168                self.creds.set_machine_account(lp)
     169            except Exception:
     170                pass
     171
    116172        return self.creds
     173
     174class CredentialsOptionsDouble(CredentialsOptions):
     175    """Command line options for specifying credentials of two servers."""
     176    def __init__(self, parser):
     177        CredentialsOptions.__init__(self, parser)
     178        self.no_pass2 = True
     179        self.add_option("--simple-bind-dn2", metavar="DN2", action="callback",
     180                        callback=self._set_simple_bind_dn2, type=str,
     181                        help="DN to use for a simple bind")
     182        self.add_option("--password2", metavar="PASSWORD2", action="callback",
     183                        help="Password", type=str, callback=self._set_password2)
     184        self.add_option("--username2", metavar="USERNAME2",
     185                        action="callback", type=str,
     186                        help="Username for second server", callback=self._parse_username2)
     187        self.add_option("--workgroup2", metavar="WORKGROUP2",
     188                        action="callback", type=str,
     189                        help="Workgroup for second server", callback=self._parse_workgroup2)
     190        self.add_option("--no-pass2", action="store_true",
     191                        help="Don't ask for a password for the second server")
     192        self.add_option("--kerberos2", metavar="KERBEROS2",
     193                        action="callback", type=str,
     194                        help="Use Kerberos", callback=self._set_kerberos2)
     195        self.creds2 = Credentials()
     196
     197    def _parse_username2(self, option, opt_str, arg, parser):
     198        self.creds2.parse_string(arg)
     199
     200    def _parse_workgroup2(self, option, opt_str, arg, parser):
     201        self.creds2.set_domain(arg)
     202
     203    def _set_password2(self, option, opt_str, arg, parser):
     204        self.creds2.set_password(arg)
     205        self.no_pass2 = False
     206
     207    def _set_kerberos2(self, option, opt_str, arg, parser):
     208        if bool(arg) or arg.lower() == "yes":
     209            self.creds2.set_kerberos_state(MUST_USE_KERBEROS)
     210        else:
     211            self.creds2.set_kerberos_state(DONT_USE_KERBEROS)
     212
     213    def _set_simple_bind_dn2(self, option, opt_str, arg, parser):
     214        self.creds2.set_bind_dn(arg)
     215
     216    def get_credentials2(self, lp, guess=True):
     217        """Obtain the credentials set on the command-line.
     218
     219        :param lp: Loadparm object to use.
     220        :param guess: Try guess Credentials from environment
     221        :return: Credentials object
     222        """
     223        if guess:
     224            self.creds2.guess(lp)
     225        elif not self.creds2.get_username():
     226                self.creds2.set_anonymous()
     227
     228        if self.no_pass2:
     229            self.creds2.set_cmdline_callbacks()
     230        return self.creds2
  • vendor/current/source4/scripting/python/samba/hostconfig.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation.
    44# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2008
    5 #   
     5#
    66# This program is free software; you can redistribute it and/or modify
    77# it under the terms of the GNU General Public License as published by
    88# the Free Software Foundation; either version 3 of the License, or
    99# (at your option) any later version.
    10 #   
     10#
    1111# This program is distributed in the hope that it will be useful,
    1212# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1313# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1414# GNU General Public License for more details.
    15 #   
     15#
    1616# You should have received a copy of the GNU General Public License
    1717# along with this program.  If not, see <http://www.gnu.org/licenses/>.
    1818#
    1919
     20"""Local host configuration."""
     21
    2022from samdb import SamDB
    2123
    2224class Hostconfig(object):
    23     """Aggregate object that contains all information about the configuration 
     25    """Aggregate object that contains all information about the configuration
    2426    of a Samba host."""
    2527
    26     def __init__(self, lp):       
     28    def __init__(self, lp):
    2729        self.lp = lp
    2830
     31    def get_shares(self):
     32        return SharesContainer(self.lp)
     33
    2934    def get_samdb(self, session_info, credentials):
    30         return SamDB(url=self.lp.get("sam database"),
    31                      session_info=session_info, credentials=credentials,
     35        """Access the SamDB host.
     36
     37        :param session_info: Session info to use
     38        :param credentials: Credentials to access the SamDB with
     39        """
     40        return SamDB(url=self.lp.get("sam database"),
     41                     session_info=session_info, credentials=credentials,
    3242                     lp=self.lp)
    3343
     44
     45# TODO: Rather than accessing Loadparm directly here, we should really
     46# have bindings to the param/shares.c and use those.
     47
     48
     49class SharesContainer(object):
     50    """A shares container."""
     51
     52    def __init__(self, lp):
     53        self._lp = lp
     54
     55    def __getitem__(self, name):
     56        if name == "global":
     57            # [global] is not a share
     58            raise KeyError
     59        return Share(self._lp[name])
     60
     61    def __len__(self):
     62        if "global" in self._lp.services():
     63            return len(self._lp)-1
     64        return len(self._lp)
     65
     66    def keys(self):
     67        return [name for name in self._lp.services() if name != "global"]
     68
     69    def __iter__(self):
     70        return iter(self.keys())
     71
     72
     73class Share(object):
     74    """A file share."""
     75
     76    def __init__(self, service):
     77        self._service = service
     78
     79    def __getitem__(self, name):
     80        return self._service[name]
     81
     82    def __setitem__(self, name, value):
     83        self._service[name] = value
  • vendor/current/source4/scripting/python/samba/idmap.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation.
     
    2323__docformat__ = "restructuredText"
    2424
     25import ldb
    2526import samba
    2627
     
    5152                options=options)
    5253
    53     def setup_name_mapping(self, sid, type, unixid):
     54
     55    def increment_xid(self):
     56        """Increment xidNumber, if not present it create and assign it to the lowerBound
     57
     58        :return xid can that be used for SID/unixid mapping
     59        """
     60        res = self.search(expression="dn=CN=CONFIG", base="",
     61                          scope=ldb.SCOPE_SUBTREE)
     62        id = res[0].get("xidNumber")
     63        flag = ldb.FLAG_MOD_REPLACE
     64        if id is None:
     65            id = res[0].get("lowerBound")
     66            flag = ldb.FLAG_MOD_ADD
     67        newid = int(str(id)) + 1
     68        msg = ldb.Message()
     69        msg.dn = ldb.Dn(self, "CN=CONFIG")
     70        msg["xidNumber"] = ldb.MessageElement(str(newid), flag, "xidNumber")
     71        self.modify(msg)
     72        return id
     73
     74    def setup_name_mapping(self, sid, type, unixid=None):
    5475        """Setup a mapping between a sam name and a unix name.
    5576
    5677        :param sid: SID of the NT-side of the mapping.
    57         :param unixname: Unix name to map to.
     78        :param unixname: Unix id to map to, if none supplied the next one will be selected
    5879        """
     80        if unixid is None:
     81            unixid = self.increment_xid()
    5982        type_string = ""
    6083        if type == self.TYPE_UID:
  • vendor/current/source4/scripting/python/samba/ms_display_specifiers.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22#
    33# Create DisplaySpecifiers LDIF (as a string) from the documents provided by
  • vendor/current/source4/scripting/python/samba/ms_schema.py

    r414 r740  
    1 #!/usr/bin/env python
    21#
    32# create schema.ldif (as a string) from WSPP documentation
     
    65#
    76
     7"""Generate LDIF from WSPP documentation."""
     8
    89import re
    910import base64
     11import uuid
    1012
    1113bitFields = {}
     
    3436# ADTS: 2.2.10
    3537bitFields["systemflags"] = {
    36     'FLAG_ATTR_NOT_REPLICATED': 31, 'FLAG_CR_NTDS_NC': 31,      # NR
    37     'FLAG_ATTR_REQ_PARTIAL_SET_MEMBER': 30, 'FLAG_CR_NTDS_DOMAIN': 30,  # PS
    38     'FLAG_ATTR_IS_CONSTRUCTED': 29, 'FLAG_CR_NTDS_NOT_GC_REPLICATED': 29,       # CS
    39     'FLAG_ATTR_IS_OPERATIONAL': 28,     # OP
    40     'FLAG_SCHEMA_BASE_OBJECT': 27,      # BS
    41     'FLAG_ATTR_IS_RDN': 26,     # RD
    42     'FLAG_DISALLOW_MOVE_ON_DELETE': 6,  # DE
    43     'FLAG_DOMAIN_DISALLOW_MOVE': 5,     # DM
    44     'FLAG_DOMAIN_DISALLOW_RENAME': 4,   # DR
    45     'FLAG_CONFIG_ALLOW_LIMITED_MOVE': 3,        # AL
    46     'FLAG_CONFIG_ALLOW_MOVE': 2,        # AM
    47     'FLAG_CONFIG_ALLOW_RENAME': 1,      # AR
    48     'FLAG_DISALLOW_DELETE': 0   # DD
     38    'FLAG_ATTR_NOT_REPLICATED': 31, 'FLAG_CR_NTDS_NC': 31,     # NR
     39    'FLAG_ATTR_REQ_PARTIAL_SET_MEMBER': 30, 'FLAG_CR_NTDS_DOMAIN': 30,     # PS
     40    'FLAG_ATTR_IS_CONSTRUCTED': 29, 'FLAG_CR_NTDS_NOT_GC_REPLICATED': 29,     # CS
     41    'FLAG_ATTR_IS_OPERATIONAL': 28,     # OP
     42    'FLAG_SCHEMA_BASE_OBJECT': 27,     # BS
     43    'FLAG_ATTR_IS_RDN': 26,     # RD
     44    'FLAG_DISALLOW_MOVE_ON_DELETE': 6,     # DE
     45    'FLAG_DOMAIN_DISALLOW_MOVE': 5,     # DM
     46    'FLAG_DOMAIN_DISALLOW_RENAME': 4,     # DR
     47    'FLAG_CONFIG_ALLOW_LIMITED_MOVE': 3,     # AL
     48    'FLAG_CONFIG_ALLOW_MOVE': 2,     # AM
     49    'FLAG_CONFIG_ALLOW_RENAME': 1,     # AR
     50    'FLAG_DISALLOW_DELETE': 0     # DD
    4951    }
    5052
     
    228230    entry.insert(1, ["objectClass", ["top", objectClass]])
    229231    entry.insert(2, ["cn", cn])
     232    entry.insert(2, ["objectGUID", str(uuid.uuid4())])
     233    entry.insert(2, ["adminDescription", cn])
     234    entry.insert(2, ["adminDisplayName", cn])
    230235   
    231236    for l in entry:
     
    273278       
    274279    print read_ms_schema(attr_file, classes_file)
    275 
    276        
  • vendor/current/source4/scripting/python/samba/ndr.py

    r414 r740  
    1 #!/usr/bin/python
    21# -*- coding: utf-8 -*-
    32
    43# Unix SMB/CIFS implementation.
    54# Copyright © Jelmer Vernooij <jelmer@samba.org> 2008
    6 #   
     5#
    76# This program is free software; you can redistribute it and/or modify
    87# it under the terms of the GNU General Public License as published by
    98# the Free Software Foundation; either version 3 of the License, or
    109# (at your option) any later version.
    11 #   
     10#
    1211# This program is distributed in the hope that it will be useful,
    1312# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1413# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1514# GNU General Public License for more details.
    16 #   
     15#
    1716# You should have received a copy of the GNU General Public License
    1817# along with this program.  If not, see <http://www.gnu.org/licenses/>.
    1918#
    2019
     20
     21"""Network Data Representation (NDR) marshalling and unmarshalling."""
     22
     23
    2124def ndr_pack(object):
    22     return object.__ndr_pack__()
     25    """Pack a NDR object.
     26   
     27    :param object: Object to pack
     28    :return: String object with marshalled object.
     29    """
     30    ndr_pack = getattr(object, "__ndr_pack__", None)
     31    if ndr_pack is None:
     32        raise TypeError("%r is not a NDR object" % object)
     33    return ndr_pack()
    2334
    2435
    2536def ndr_unpack(cls, data):
     37    """NDR unpack an object.
     38
     39    :param cls: Class of the object to unpack
     40    :param data: Buffer to unpack
     41    :return: Unpacked object
     42    """
    2643    object = cls()
    2744    object.__ndr_unpack__(data)
    2845    return object
     46
     47
     48def ndr_print(object):
     49    return object.__ndr_print__()
  • vendor/current/source4/scripting/python/samba/samba3.py

    r414 r740  
    1 #!/usr/bin/python
    2 
    31# Unix SMB/CIFS implementation.
    42# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
    5 #   
     3#
    64# This program is free software; you can redistribute it and/or modify
    75# it under the terms of the GNU General Public License as published by
    86# the Free Software Foundation; either version 3 of the License, or
    97# (at your option) any later version.
    10 #   
     8#
    119# This program is distributed in the hope that it will be useful,
    1210# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1311# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1412# GNU General Public License for more details.
    15 #   
     13#
    1614# You should have received a copy of the GNU General Public License
    1715# along with this program.  If not, see <http://www.gnu.org/licenses/>.
     
    6866class Registry(TdbDatabase):
    6967    """Simple read-only support for reading the Samba3 registry.
    70    
     68
    7169    :note: This object uses the same syntax for registry key paths as
    7270        Samba 3. This particular format uses forward slashes for key path
     
    684682        for i, l in enumerate(open(filename, 'r').xreadlines()):
    685683            l = l.strip()
    686             if not l:
     684            if not l or l[0] == '#' or l[0] == ';':
    687685                continue
    688686            if l[0] == "[" and l[-1] == "]":
     
    770768    def get_policy_db(self):
    771769        return PolicyDatabase(self.libdir_path("account_policy.tdb"))
    772    
     770
    773771    def get_registry(self):
    774772        return Registry(self.libdir_path("registry.tdb"))
  • vendor/current/source4/scripting/python/samba/samdb.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation.
    4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
     4# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2010
    55# Copyright (C) Matthias Dieter Wallnoefer 2009
    66#
    77# Based on the original in EJS:
    88# Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
    9 #   
     9#
    1010# This program is free software; you can redistribute it and/or modify
    1111# it under the terms of the GNU General Public License as published by
    1212# the Free Software Foundation; either version 3 of the License, or
    1313# (at your option) any later version.
    14 #   
     14#
    1515# This program is distributed in the hope that it will be useful,
    1616# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1717# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1818# GNU General Public License for more details.
    19 #   
     19#
    2020# You should have received a copy of the GNU General Public License
    2121# along with this program.  If not, see <http://www.gnu.org/licenses/>.
     
    2525
    2626import samba
    27 import glue
    2827import ldb
    29 from samba.idmap import IDmapDB
    30 import pwd
    3128import time
    3229import base64
     30from samba import dsdb
     31from samba.ndr import ndr_unpack, ndr_pack
     32from samba.dcerpc import drsblobs, misc
    3333
    3434__docformat__ = "restructuredText"
     35
    3536
    3637class SamDB(samba.Ldb):
    3738    """The SAM database."""
    3839
     40    hash_oid_name = {}
     41
    3942    def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
    40                  credentials=None, flags=0, options=None):
    41         """Opens the SAM Database
    42         For parameter meanings see the super class (samba.Ldb)
    43         """
    44 
     43                 credentials=None, flags=0, options=None, global_schema=True,
     44                 auto_connect=True, am_rodc=None):
    4545        self.lp = lp
    46         if url is None:
    47                 url = lp.get("sam database")
     46        if not auto_connect:
     47            url = None
     48        elif url is None and lp is not None:
     49            url = lp.get("sam database")
    4850
    4951        super(SamDB, self).__init__(url=url, lp=lp, modules_dir=modules_dir,
    50                 session_info=session_info, credentials=credentials, flags=flags,
     52            session_info=session_info, credentials=credentials, flags=flags,
     53            options=options)
     54
     55        if global_schema:
     56            dsdb._dsdb_set_global_schema(self)
     57
     58        if am_rodc is not None:
     59            dsdb._dsdb_set_am_rodc(self, am_rodc)
     60
     61    def connect(self, url=None, flags=0, options=None):
     62        if self.lp is not None:
     63            url = self.lp.private_path(url)
     64
     65        super(SamDB, self).connect(url=url, flags=flags,
    5166                options=options)
    5267
    53         glue.dsdb_set_global_schema(self)
    54 
    55     def connect(self, url=None, flags=0, options=None):
    56         super(SamDB, self).connect(url=self.lp.private_path(url), flags=flags,
    57                 options=options)
     68    def am_rodc(self):
     69        return dsdb._am_rodc(self)
    5870
    5971    def domain_dn(self):
    60         # find the DNs for the domain
    61         res = self.search(base="",
    62                           scope=ldb.SCOPE_BASE,
    63                           expression="(defaultNamingContext=*)",
    64                           attrs=["defaultNamingContext"])
    65         assert(len(res) == 1 and res[0]["defaultNamingContext"] is not None)
    66         return res[0]["defaultNamingContext"][0]
    67 
    68     def enable_account(self, filter):
     72        return str(self.get_default_basedn())
     73
     74    def enable_account(self, search_filter):
    6975        """Enables an account
    70        
    71         :param filter: LDAP filter to find the user (eg samccountname=name)
     76
     77        :param search_filter: LDAP filter to find the user (eg
     78            samccountname=name)
    7279        """
    7380        res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
    74                           expression=filter, attrs=["userAccountControl"])
     81                          expression=search_filter, attrs=["userAccountControl"])
    7582        assert(len(res) == 1)
    7683        user_dn = res[0].dn
    7784
    7885        userAccountControl = int(res[0]["userAccountControl"][0])
    79         if (userAccountControl & 0x2):
    80             userAccountControl = userAccountControl & ~0x2 # remove disabled bit
    81         if (userAccountControl & 0x20):
    82             userAccountControl = userAccountControl & ~0x20 # remove 'no password required' bit
     86        if userAccountControl & 0x2:
     87            # remove disabled bit
     88            userAccountControl = userAccountControl & ~0x2
     89        if userAccountControl & 0x20:
     90             # remove 'no password required' bit
     91            userAccountControl = userAccountControl & ~0x20
    8392
    8493        mod = """
     
    8998""" % (user_dn, userAccountControl)
    9099        self.modify_ldif(mod)
    91        
    92     def force_password_change_at_next_login(self, filter):
     100
     101    def force_password_change_at_next_login(self, search_filter):
    93102        """Forces a password change at next login
    94        
    95         :param filter: LDAP filter to find the user (eg samccountname=name)
     103
     104        :param search_filter: LDAP filter to find the user (eg
     105            samccountname=name)
    96106        """
    97107        res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
    98                           expression=filter, attrs=[])
     108                          expression=search_filter, attrs=[])
    99109        assert(len(res) == 1)
    100110        user_dn = res[0].dn
     
    108118        self.modify_ldif(mod)
    109119
    110     def newuser(self, username, unixname, password, force_password_change_at_next_login_req=False):
    111         """Adds a new user
    112 
    113         Note: This call adds also the ID mapping for winbind; therefore it works
    114         *only* on SAMBA 4.
    115        
     120    def newgroup(self, groupname, groupou=None, grouptype=None,
     121                 description=None, mailaddress=None, notes=None, sd=None):
     122        """Adds a new group with additional parameters
     123
     124        :param groupname: Name of the new group
     125        :param grouptype: Type of the new group
     126        :param description: Description of the new group
     127        :param mailaddress: Email address of the new group
     128        :param notes: Notes of the new group
     129        :param sd: security descriptor of the object
     130        """
     131
     132        group_dn = "CN=%s,%s,%s" % (groupname, (groupou or "CN=Users"), self.domain_dn())
     133
     134        # The new user record. Note the reliance on the SAMLDB module which
     135        # fills in the default informations
     136        ldbmessage = {"dn": group_dn,
     137            "sAMAccountName": groupname,
     138            "objectClass": "group"}
     139
     140        if grouptype is not None:
     141            ldbmessage["groupType"] = "%d" % grouptype
     142
     143        if description is not None:
     144            ldbmessage["description"] = description
     145
     146        if mailaddress is not None:
     147            ldbmessage["mail"] = mailaddress
     148
     149        if notes is not None:
     150            ldbmessage["info"] = notes
     151
     152        if sd is not None:
     153            ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd)
     154
     155        self.add(ldbmessage)
     156
     157    def deletegroup(self, groupname):
     158        """Deletes a group
     159
     160        :param groupname: Name of the target group
     161        """
     162
     163        groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (groupname, "CN=Group,CN=Schema,CN=Configuration", self.domain_dn())
     164        self.transaction_start()
     165        try:
     166            targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
     167                               expression=groupfilter, attrs=[])
     168            if len(targetgroup) == 0:
     169                raise Exception('Unable to find group "%s"' % groupname)
     170            assert(len(targetgroup) == 1)
     171            self.delete(targetgroup[0].dn)
     172        except Exception:
     173            self.transaction_cancel()
     174            raise
     175        else:
     176            self.transaction_commit()
     177
     178    def add_remove_group_members(self, groupname, listofmembers,
     179                                  add_members_operation=True):
     180        """Adds or removes group members
     181
     182        :param groupname: Name of the target group
     183        :param listofmembers: Comma-separated list of group members
     184        :param add_members_operation: Defines if its an add or remove
     185            operation
     186        """
     187
     188        groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (groupname, "CN=Group,CN=Schema,CN=Configuration", self.domain_dn())
     189        groupmembers = listofmembers.split(',')
     190
     191        self.transaction_start()
     192        try:
     193            targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
     194                               expression=groupfilter, attrs=['member'])
     195            if len(targetgroup) == 0:
     196                raise Exception('Unable to find group "%s"' % groupname)
     197            assert(len(targetgroup) == 1)
     198
     199            modified = False
     200
     201            addtargettogroup = """
     202dn: %s
     203changetype: modify
     204""" % (str(targetgroup[0].dn))
     205
     206            for member in groupmembers:
     207                targetmember = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
     208                                    expression="(|(sAMAccountName=%s)(CN=%s))" % (member, member), attrs=[])
     209
     210                if len(targetmember) != 1:
     211                    continue
     212
     213                if add_members_operation is True and (targetgroup[0].get('member') is None or str(targetmember[0].dn) not in targetgroup[0]['member']):
     214                    modified = True
     215                    addtargettogroup += """add: member
     216member: %s
     217""" % (str(targetmember[0].dn))
     218
     219                elif add_members_operation is False and (targetgroup[0].get('member') is not None and str(targetmember[0].dn) in targetgroup[0]['member']):
     220                    modified = True
     221                    addtargettogroup += """delete: member
     222member: %s
     223""" % (str(targetmember[0].dn))
     224
     225            if modified is True:
     226                self.modify_ldif(addtargettogroup)
     227
     228        except Exception:
     229            self.transaction_cancel()
     230            raise
     231        else:
     232            self.transaction_commit()
     233
     234    def newuser(self, username, password,
     235            force_password_change_at_next_login_req=False,
     236            useusernameascn=False, userou=None, surname=None, givenname=None,
     237            initials=None, profilepath=None, scriptpath=None, homedrive=None,
     238            homedirectory=None, jobtitle=None, department=None, company=None,
     239            description=None, mailaddress=None, internetaddress=None,
     240            telephonenumber=None, physicaldeliveryoffice=None, sd=None,
     241            setpassword=True):
     242        """Adds a new user with additional parameters
     243
    116244        :param username: Name of the new user
    117         :param unixname: Name of the unix user to map to
    118245        :param password: Password for the new user
    119246        :param force_password_change_at_next_login_req: Force password change
    120         """
     247        :param useusernameascn: Use username as cn rather that firstname +
     248            initials + lastname
     249        :param userou: Object container (without domainDN postfix) for new user
     250        :param surname: Surname of the new user
     251        :param givenname: First name of the new user
     252        :param initials: Initials of the new user
     253        :param profilepath: Profile path of the new user
     254        :param scriptpath: Logon script path of the new user
     255        :param homedrive: Home drive of the new user
     256        :param homedirectory: Home directory of the new user
     257        :param jobtitle: Job title of the new user
     258        :param department: Department of the new user
     259        :param company: Company of the new user
     260        :param description: of the new user
     261        :param mailaddress: Email address of the new user
     262        :param internetaddress: Home page of the new user
     263        :param telephonenumber: Phone number of the new user
     264        :param physicaldeliveryoffice: Office location of the new user
     265        :param sd: security descriptor of the object
     266        :param setpassword: optionally disable password reset
     267        """
     268
     269        displayname = ""
     270        if givenname is not None:
     271            displayname += givenname
     272
     273        if initials is not None:
     274            displayname += ' %s.' % initials
     275
     276        if surname is not None:
     277            displayname += ' %s' % surname
     278
     279        cn = username
     280        if useusernameascn is None and displayname is not "":
     281            cn = displayname
     282
     283        user_dn = "CN=%s,%s,%s" % (cn, (userou or "CN=Users"), self.domain_dn())
     284
     285        dnsdomain = ldb.Dn(self, self.domain_dn()).canonical_str().replace("/", "")
     286        user_principal_name = "%s@%s" % (username, dnsdomain)
     287        # The new user record. Note the reliance on the SAMLDB module which
     288        # fills in the default informations
     289        ldbmessage = {"dn": user_dn,
     290                      "sAMAccountName": username,
     291                      "userPrincipalName": user_principal_name,
     292                      "objectClass": "user"}
     293
     294        if surname is not None:
     295            ldbmessage["sn"] = surname
     296
     297        if givenname is not None:
     298            ldbmessage["givenName"] = givenname
     299
     300        if displayname is not "":
     301            ldbmessage["displayName"] = displayname
     302            ldbmessage["name"] = displayname
     303
     304        if initials is not None:
     305            ldbmessage["initials"] = '%s.' % initials
     306
     307        if profilepath is not None:
     308            ldbmessage["profilePath"] = profilepath
     309
     310        if scriptpath is not None:
     311            ldbmessage["scriptPath"] = scriptpath
     312
     313        if homedrive is not None:
     314            ldbmessage["homeDrive"] = homedrive
     315
     316        if homedirectory is not None:
     317            ldbmessage["homeDirectory"] = homedirectory
     318
     319        if jobtitle is not None:
     320            ldbmessage["title"] = jobtitle
     321
     322        if department is not None:
     323            ldbmessage["department"] = department
     324
     325        if company is not None:
     326            ldbmessage["company"] = company
     327
     328        if description is not None:
     329            ldbmessage["description"] = description
     330
     331        if mailaddress is not None:
     332            ldbmessage["mail"] = mailaddress
     333
     334        if internetaddress is not None:
     335            ldbmessage["wWWHomePage"] = internetaddress
     336
     337        if telephonenumber is not None:
     338            ldbmessage["telephoneNumber"] = telephonenumber
     339
     340        if physicaldeliveryoffice is not None:
     341            ldbmessage["physicalDeliveryOfficeName"] = physicaldeliveryoffice
     342
     343        if sd is not None:
     344            ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd)
     345
    121346        self.transaction_start()
    122347        try:
    123             user_dn = "CN=%s,CN=Users,%s" % (username, self.domain_dn())
    124 
    125             # The new user record. Note the reliance on the SAMLDB module which
    126             # fills in the default informations
    127             self.add({"dn": user_dn,
    128                 "sAMAccountName": username,
    129                 "objectClass": "user"})
     348            self.add(ldbmessage)
    130349
    131350            # Sets the password for it
    132             self.setpassword("(dn=" + user_dn + ")", password,
    133               force_password_change_at_next_login_req)
    134 
    135             # Gets the user SID (for the account mapping setup)
    136             res = self.search(user_dn, scope=ldb.SCOPE_BASE,
    137                               expression="objectclass=*",
    138                               attrs=["objectSid"])
    139             assert len(res) == 1
    140             user_sid = self.schema_format_value("objectSid", res[0]["objectSid"][0])
    141            
    142             try:
    143                 idmap = IDmapDB(lp=self.lp)
    144 
    145                 user = pwd.getpwnam(unixname)
    146 
    147                 # setup ID mapping for this UID
    148                 idmap.setup_name_mapping(user_sid, idmap.TYPE_UID, user[2])
    149 
    150             except KeyError:
    151                 pass
    152         except:
     351            if setpassword:
     352                self.setpassword("(samAccountName=%s)" % username, password,
     353                                 force_password_change_at_next_login_req)
     354        except Exception:
    153355            self.transaction_cancel()
    154356            raise
    155         self.transaction_commit()
    156 
    157     def setpassword(self, filter, password, force_password_change_at_next_login_req=False):
     357        else:
     358            self.transaction_commit()
     359
     360    def setpassword(self, search_filter, password,
     361            force_change_at_next_login=False, username=None):
    158362        """Sets the password for a user
    159        
    160         Note: This call uses the "userPassword" attribute to set the password.
    161         This works correctly on SAMBA 4 and on Windows DCs with
    162         "2003 Native" or higer domain function level.
    163 
    164         :param filter: LDAP filter to find the user (eg samccountname=name)
     363
     364        :param search_filter: LDAP filter to find the user (eg
     365            samccountname=name)
    165366        :param password: Password for the user
    166         :param force_password_change_at_next_login_req: Force password change
     367        :param force_change_at_next_login: Force password change
    167368        """
    168369        self.transaction_start()
    169370        try:
    170371            res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
    171                               expression=filter, attrs=[])
    172             assert(len(res) == 1)
     372                              expression=search_filter, attrs=[])
     373            if len(res) == 0:
     374                raise Exception('Unable to find user "%s"' % (username or search_filter))
     375            if len(res) > 1:
     376                raise Exception('Matched %u multiple users with filter "%s"' % (len(res), search_filter))
    173377            user_dn = res[0].dn
    174 
    175378            setpw = """
    176379dn: %s
    177380changetype: modify
    178 replace: userPassword
    179 userPassword:: %s
    180 """ % (user_dn, base64.b64encode(password))
     381replace: unicodePwd
     382unicodePwd:: %s
     383""" % (user_dn, base64.b64encode(("\"" + password + "\"").encode('utf-16-le')))
    181384
    182385            self.modify_ldif(setpw)
    183386
    184             if force_password_change_at_next_login_req:
     387            if force_change_at_next_login:
    185388                self.force_password_change_at_next_login(
    186389                  "(dn=" + str(user_dn) + ")")
    187390
    188391            #  modify the userAccountControl to remove the disabled bit
    189             self.enable_account(filter)
    190         except:
     392            self.enable_account(search_filter)
     393        except Exception:
    191394            self.transaction_cancel()
    192395            raise
    193         self.transaction_commit()
    194 
    195     def setexpiry(self, filter, expiry_seconds, no_expiry_req=False):
     396        else:
     397            self.transaction_commit()
     398
     399    def setexpiry(self, search_filter, expiry_seconds, no_expiry_req=False):
    196400        """Sets the account expiry for a user
    197        
    198         :param filter: LDAP filter to find the user (eg samccountname=name)
     401
     402        :param search_filter: LDAP filter to find the user (eg
     403            samaccountname=name)
    199404        :param expiry_seconds: expiry time from now in seconds
    200405        :param no_expiry_req: if set, then don't expire password
     
    203408        try:
    204409            res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
    205                           expression=filter,
     410                          expression=search_filter,
    206411                          attrs=["userAccountControl", "accountExpires"])
    207412            assert(len(res) == 1)
     
    215420            else:
    216421                userAccountControl = userAccountControl & ~0x10000
    217                 accountExpires = glue.unix2nttime(expiry_seconds + int(time.time()))
     422                accountExpires = samba.unix2nttime(expiry_seconds + int(time.time()))
    218423
    219424            setexp = """
     
    227432
    228433            self.modify_ldif(setexp)
    229         except:
     434        except Exception:
    230435            self.transaction_cancel()
    231436            raise
    232         self.transaction_commit();
    233 
     437        else:
     438            self.transaction_commit()
     439
     440    def set_domain_sid(self, sid):
     441        """Change the domain SID used by this LDB.
     442
     443        :param sid: The new domain sid to use.
     444        """
     445        dsdb._samdb_set_domain_sid(self, sid)
     446
     447    def get_domain_sid(self):
     448        """Read the domain SID used by this LDB. """
     449        return dsdb._samdb_get_domain_sid(self)
     450
     451    domain_sid = property(get_domain_sid, set_domain_sid,
     452        "SID for the domain")
     453
     454    def set_invocation_id(self, invocation_id):
     455        """Set the invocation id for this SamDB handle.
     456
     457        :param invocation_id: GUID of the invocation id.
     458        """
     459        dsdb._dsdb_set_ntds_invocation_id(self, invocation_id)
     460
     461    def get_invocation_id(self):
     462        """Get the invocation_id id"""
     463        return dsdb._samdb_ntds_invocation_id(self)
     464
     465    invocation_id = property(get_invocation_id, set_invocation_id,
     466        "Invocation ID GUID")
     467
     468    def get_oid_from_attid(self, attid):
     469        return dsdb._dsdb_get_oid_from_attid(self, attid)
     470
     471    def get_attid_from_lDAPDisplayName(self, ldap_display_name,
     472            is_schema_nc=False):
     473        return dsdb._dsdb_get_attid_from_lDAPDisplayName(self,
     474            ldap_display_name, is_schema_nc)
     475
     476    def set_ntds_settings_dn(self, ntds_settings_dn):
     477        """Set the NTDS Settings DN, as would be returned on the dsServiceName
     478        rootDSE attribute.
     479
     480        This allows the DN to be set before the database fully exists
     481
     482        :param ntds_settings_dn: The new DN to use
     483        """
     484        dsdb._samdb_set_ntds_settings_dn(self, ntds_settings_dn)
     485
     486    def get_ntds_GUID(self):
     487        """Get the NTDS objectGUID"""
     488        return dsdb._samdb_ntds_objectGUID(self)
     489
     490    def server_site_name(self):
     491        """Get the server site name"""
     492        return dsdb._samdb_server_site_name(self)
     493
     494    def load_partition_usn(self, base_dn):
     495        return dsdb._dsdb_load_partition_usn(self, base_dn)
     496
     497    def set_schema(self, schema):
     498        self.set_schema_from_ldb(schema.ldb)
     499
     500    def set_schema_from_ldb(self, ldb_conn):
     501        dsdb._dsdb_set_schema_from_ldb(self, ldb_conn)
     502
     503    def dsdb_DsReplicaAttribute(self, ldb, ldap_display_name, ldif_elements):
     504        return dsdb._dsdb_DsReplicaAttribute(ldb, ldap_display_name, ldif_elements)
     505
     506    def get_attribute_from_attid(self, attid):
     507        """ Get from an attid the associated attribute
     508
     509        :param attid: The attribute id for searched attribute
     510        :return: The name of the attribute associated with this id
     511        """
     512        if len(self.hash_oid_name.keys()) == 0:
     513            self._populate_oid_attid()
     514        if self.hash_oid_name.has_key(self.get_oid_from_attid(attid)):
     515            return self.hash_oid_name[self.get_oid_from_attid(attid)]
     516        else:
     517            return None
     518
     519    def _populate_oid_attid(self):
     520        """Populate the hash hash_oid_name.
     521
     522        This hash contains the oid of the attribute as a key and
     523        its display name as a value
     524        """
     525        self.hash_oid_name = {}
     526        res = self.search(expression="objectClass=attributeSchema",
     527                           controls=["search_options:1:2"],
     528                           attrs=["attributeID",
     529                           "lDAPDisplayName"])
     530        if len(res) > 0:
     531            for e in res:
     532                strDisplay = str(e.get("lDAPDisplayName"))
     533                self.hash_oid_name[str(e.get("attributeID"))] = strDisplay
     534
     535    def get_attribute_replmetadata_version(self, dn, att):
     536        """Get the version field trom the replPropertyMetaData for
     537        the given field
     538
     539        :param dn: The on which we want to get the version
     540        :param att: The name of the attribute
     541        :return: The value of the version field in the replPropertyMetaData
     542            for the given attribute. None if the attribute is not replicated
     543        """
     544
     545        res = self.search(expression="dn=%s" % dn,
     546                            scope=ldb.SCOPE_SUBTREE,
     547                            controls=["search_options:1:2"],
     548                            attrs=["replPropertyMetaData"])
     549        if len(res) == 0:
     550            return None
     551
     552        repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
     553                            str(res[0]["replPropertyMetaData"]))
     554        ctr = repl.ctr
     555        if len(self.hash_oid_name.keys()) == 0:
     556            self._populate_oid_attid()
     557        for o in ctr.array:
     558            # Search for Description
     559            att_oid = self.get_oid_from_attid(o.attid)
     560            if self.hash_oid_name.has_key(att_oid) and\
     561               att.lower() == self.hash_oid_name[att_oid].lower():
     562                return o.version
     563        return None
     564
     565    def set_attribute_replmetadata_version(self, dn, att, value,
     566            addifnotexist=False):
     567        res = self.search(expression="dn=%s" % dn,
     568                            scope=ldb.SCOPE_SUBTREE,
     569                            controls=["search_options:1:2"],
     570                            attrs=["replPropertyMetaData"])
     571        if len(res) == 0:
     572            return None
     573
     574        repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
     575                            str(res[0]["replPropertyMetaData"]))
     576        ctr = repl.ctr
     577        now = samba.unix2nttime(int(time.time()))
     578        found = False
     579        if len(self.hash_oid_name.keys()) == 0:
     580            self._populate_oid_attid()
     581        for o in ctr.array:
     582            # Search for Description
     583            att_oid = self.get_oid_from_attid(o.attid)
     584            if self.hash_oid_name.has_key(att_oid) and\
     585               att.lower() == self.hash_oid_name[att_oid].lower():
     586                found = True
     587                seq = self.sequence_number(ldb.SEQ_NEXT)
     588                o.version = value
     589                o.originating_change_time = now
     590                o.originating_invocation_id = misc.GUID(self.get_invocation_id())
     591                o.originating_usn = seq
     592                o.local_usn = seq
     593
     594        if not found and addifnotexist and len(ctr.array) >0:
     595            o2 = drsblobs.replPropertyMetaData1()
     596            o2.attid = 589914
     597            att_oid = self.get_oid_from_attid(o2.attid)
     598            seq = self.sequence_number(ldb.SEQ_NEXT)
     599            o2.version = value
     600            o2.originating_change_time = now
     601            o2.originating_invocation_id = misc.GUID(self.get_invocation_id())
     602            o2.originating_usn = seq
     603            o2.local_usn = seq
     604            found = True
     605            tab = ctr.array
     606            tab.append(o2)
     607            ctr.count = ctr.count + 1
     608            ctr.array = tab
     609
     610        if found :
     611            replBlob = ndr_pack(repl)
     612            msg = ldb.Message()
     613            msg.dn = res[0].dn
     614            msg["replPropertyMetaData"] = ldb.MessageElement(replBlob,
     615                                                ldb.FLAG_MOD_REPLACE,
     616                                                "replPropertyMetaData")
     617            self.modify(msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
     618
     619    def write_prefixes_from_schema(self):
     620        dsdb._dsdb_write_prefixes_from_schema_to_ldb(self)
     621
     622    def get_partitions_dn(self):
     623        return dsdb._dsdb_get_partitions_dn(self)
     624
     625    def set_minPwdAge(self, value):
     626        m = ldb.Message()
     627        m.dn = ldb.Dn(self, self.domain_dn())
     628        m["minPwdAge"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdAge")
     629        self.modify(m)
     630
     631    def get_minPwdAge(self):
     632        res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdAge"])
     633        if len(res) == 0:
     634            return None
     635        elif not "minPwdAge" in res[0]:
     636            return None
     637        else:
     638            return res[0]["minPwdAge"][0]
     639
     640    def set_minPwdLength(self, value):
     641        m = ldb.Message()
     642        m.dn = ldb.Dn(self, self.domain_dn())
     643        m["minPwdLength"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdLength")
     644        self.modify(m)
     645
     646    def get_minPwdLength(self):
     647        res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdLength"])
     648        if len(res) == 0:
     649            return None
     650        elif not "minPwdLength" in res[0]:
     651            return None
     652        else:
     653            return res[0]["minPwdLength"][0]
     654
     655    def set_pwdProperties(self, value):
     656        m = ldb.Message()
     657        m.dn = ldb.Dn(self, self.domain_dn())
     658        m["pwdProperties"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "pwdProperties")
     659        self.modify(m)
     660
     661    def get_pwdProperties(self):
     662        res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["pwdProperties"])
     663        if len(res) == 0:
     664            return None
     665        elif not "pwdProperties" in res[0]:
     666            return None
     667        else:
     668            return res[0]["pwdProperties"][0]
     669
     670    def set_dsheuristics(self, dsheuristics):
     671        m = ldb.Message()
     672        m.dn = ldb.Dn(self, "CN=Directory Service,CN=Windows NT,CN=Services,%s"
     673                      % self.get_config_basedn().get_linearized())
     674        if dsheuristics is not None:
     675            m["dSHeuristics"] = ldb.MessageElement(dsheuristics,
     676                ldb.FLAG_MOD_REPLACE, "dSHeuristics")
     677        else:
     678            m["dSHeuristics"] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE,
     679                "dSHeuristics")
     680        self.modify(m)
     681
     682    def get_dsheuristics(self):
     683        res = self.search("CN=Directory Service,CN=Windows NT,CN=Services,%s"
     684                          % self.get_config_basedn().get_linearized(),
     685                          scope=ldb.SCOPE_BASE, attrs=["dSHeuristics"])
     686        if len(res) == 0:
     687            dsheuristics = None
     688        elif "dSHeuristics" in res[0]:
     689            dsheuristics = res[0]["dSHeuristics"][0]
     690        else:
     691            dsheuristics = None
     692
     693        return dsheuristics
     694
     695    def create_ou(self, ou_dn, description=None, name=None, sd=None):
     696        """Creates an organizationalUnit object
     697        :param ou_dn: dn of the new object
     698        :param description: description attribute
     699        :param name: name atttribute
     700        :param sd: security descriptor of the object, can be
     701        an SDDL string or security.descriptor type
     702        """
     703        m = {"dn": ou_dn,
     704             "objectClass": "organizationalUnit"}
     705
     706        if description:
     707            m["description"] = description
     708        if name:
     709            m["name"] = name
     710
     711        if sd:
     712            m["nTSecurityDescriptor"] = ndr_pack(sd)
     713        self.add(m)
  • vendor/current/source4/scripting/python/samba/tests/__init__.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation.
    4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
    5 #   
     4# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2010
     5#
    66# This program is free software; you can redistribute it and/or modify
    77# it under the terms of the GNU General Public License as published by
    88# the Free Software Foundation; either version 3 of the License, or
    99# (at your option) any later version.
    10 #   
     10#
    1111# This program is distributed in the hope that it will be useful,
    1212# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1313# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1414# GNU General Public License for more details.
    15 #   
     15#
    1616# You should have received a copy of the GNU General Public License
    1717# along with this program.  If not, see <http://www.gnu.org/licenses/>.
     
    2323import ldb
    2424import samba
     25import samba.auth
     26from samba import param
     27from samba.samdb import SamDB
     28import subprocess
    2529import tempfile
    26 import unittest
    27 
    28 class LdbTestCase(unittest.TestCase):
    29 
     30
     31# Other modules import these two classes from here, for convenience:
     32from testtools.testcase import (
     33    TestCase as TesttoolsTestCase,
     34    TestSkipped,
     35    )
     36
     37
     38class TestCase(TesttoolsTestCase):
     39    """A Samba test case."""
     40
     41    def setUp(self):
     42        super(TestCase, self).setUp()
     43        test_debug_level = os.getenv("TEST_DEBUG_LEVEL")
     44        if test_debug_level is not None:
     45            test_debug_level = int(test_debug_level)
     46            self._old_debug_level = samba.get_debug_level()
     47            samba.set_debug_level(test_debug_level)
     48            self.addCleanup(samba.set_debug_level, test_debug_level)
     49
     50    def get_loadparm(self):
     51        return env_loadparm()
     52
     53    def get_credentials(self):
     54        return cmdline_credentials
     55
     56
     57class LdbTestCase(TesttoolsTestCase):
    3058    """Trivial test case for running tests against a LDB."""
     59
    3160    def setUp(self):
     61        super(LdbTestCase, self).setUp()
    3262        self.filename = os.tempnam()
    3363        self.ldb = samba.Ldb(self.filename)
     
    4272
    4373
    44 class TestCaseInTempDir(unittest.TestCase):
     74class TestCaseInTempDir(TestCase):
    4575
    4676    def setUp(self):
     
    5484
    5585
    56 class SubstituteVarTestCase(unittest.TestCase):
    57 
    58     def test_empty(self):
    59         self.assertEquals("", samba.substitute_var("", {}))
    60 
    61     def test_nothing(self):
    62         self.assertEquals("foo bar", samba.substitute_var("foo bar", {"bar": "bla"}))
    63 
    64     def test_replace(self):
    65         self.assertEquals("foo bla", samba.substitute_var("foo ${bar}", {"bar": "bla"}))
    66 
    67     def test_broken(self):
    68         self.assertEquals("foo ${bdkjfhsdkfh sdkfh ",
    69                 samba.substitute_var("foo ${bdkjfhsdkfh sdkfh ", {"bar": "bla"}))
    70 
    71     def test_unknown_var(self):
    72         self.assertEquals("foo ${bla} gsff",
    73                 samba.substitute_var("foo ${bla} gsff", {"bar": "bla"}))
    74                
    75     def test_check_all_substituted(self):
    76         samba.check_all_substituted("nothing to see here")
    77         self.assertRaises(Exception, samba.check_all_substituted, "Not subsituted: ${FOOBAR}")
    78 
    79 
    80 class LdbExtensionTests(TestCaseInTempDir):
    81 
    82     def test_searchone(self):
    83         path = self.tempdir + "/searchone.ldb"
    84         l = samba.Ldb(path)
    85         try:
    86             l.add({"dn": "foo=dc", "bar": "bla"})
    87             self.assertEquals("bla", l.searchone(basedn=ldb.Dn(l, "foo=dc"), attribute="bar"))
    88         finally:
    89             del l
    90             os.unlink(path)
    91 
    92 
    93 cmdline_loadparm = None
     86def env_loadparm():
     87    lp = param.LoadParm()
     88    try:
     89        lp.load(os.environ["SMB_CONF_PATH"])
     90    except KeyError:
     91        raise Exception("SMB_CONF_PATH not set")
     92    return lp
     93
     94
     95def env_get_var_value(var_name):
     96    """Returns value for variable in os.environ
     97
     98    Function throws AssertionError if variable is defined.
     99    Unit-test based python tests require certain input params
     100    to be set in environment, otherwise they can't be run
     101    """
     102    assert var_name in os.environ.keys(), "Please supply %s in environment" % var_name
     103    return os.environ[var_name]
     104
     105
    94106cmdline_credentials = None
    95107
    96 class RpcInterfaceTestCase(unittest.TestCase):
    97 
    98     def get_loadparm(self):
    99         assert cmdline_loadparm is not None
    100         return cmdline_loadparm
    101 
    102     def get_credentials(self):
    103         return cmdline_credentials
    104 
    105 
    106 class ValidNetbiosNameTests(unittest.TestCase):
     108class RpcInterfaceTestCase(TestCase):
     109    """DCE/RPC Test case."""
     110
     111
     112class ValidNetbiosNameTests(TestCase):
    107113
    108114    def test_valid(self):
     
    114120    def test_invalid_characters(self):
    115121        self.assertFalse(samba.valid_netbios_name("*BLA"))
     122
     123
     124class BlackboxProcessError(subprocess.CalledProcessError):
     125    """This exception is raised when a process run by check_output() returns
     126    a non-zero exit status. Exception instance should contain
     127    the exact exit code (S.returncode), command line (S.cmd),
     128    process output (S.stdout) and process error stream (S.stderr)"""
     129    def __init__(self, returncode, cmd, stdout, stderr):
     130        super(BlackboxProcessError, self).__init__(returncode, cmd)
     131        self.stdout = stdout
     132        self.stderr = stderr
     133    def __str__(self):
     134        return "Command '%s'; exit status %d; stdout: '%s'; stderr: '%s'" % (self.cmd, self.returncode,
     135                                                                             self.stdout, self.stderr)
     136
     137class BlackboxTestCase(TestCase):
     138    """Base test case for blackbox tests."""
     139
     140    def _make_cmdline(self, line):
     141        bindir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../bin"))
     142        parts = line.split(" ")
     143        if os.path.exists(os.path.join(bindir, parts[0])):
     144            parts[0] = os.path.join(bindir, parts[0])
     145        line = " ".join(parts)
     146        return line
     147
     148    def check_run(self, line):
     149        line = self._make_cmdline(line)
     150        subprocess.check_call(line, shell=True)
     151
     152    def check_output(self, line):
     153        line = self._make_cmdline(line)
     154        p = subprocess.Popen(line, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, close_fds=True)
     155        retcode = p.wait()
     156        if retcode:
     157            raise BlackboxProcessError(retcode, line, p.stdout.read(), p.stderr.read())
     158        return p.stdout.read()
     159
     160def connect_samdb(samdb_url, lp=None, session_info=None, credentials=None,
     161                  flags=0, ldb_options=None, ldap_only=False):
     162    """Create SamDB instance and connects to samdb_url database.
     163
     164    :param samdb_url: Url for database to connect to.
     165    :param lp: Optional loadparm object
     166    :param session_info: Optional session information
     167    :param credentials: Optional credentials, defaults to anonymous.
     168    :param flags: Optional LDB flags
     169    :param ldap_only: If set, only remote LDAP connection will be created.
     170
     171    Added value for tests is that we have a shorthand function
     172    to make proper URL for ldb.connect() while using default
     173    parameters for connection based on test environment
     174    """
     175    samdb_url = samdb_url.lower()
     176    if not "://" in samdb_url:
     177        if not ldap_only and os.path.isfile(samdb_url):
     178            samdb_url = "tdb://%s" % samdb_url
     179        else:
     180            samdb_url = "ldap://%s" % samdb_url
     181    # use 'paged_search' module when connecting remotely
     182    if samdb_url.startswith("ldap://"):
     183        ldb_options = ["modules:paged_searches"]
     184    elif ldap_only:
     185        raise AssertionError("Trying to connect to %s while remote "
     186                             "connection is required" % samdb_url)
     187
     188    # set defaults for test environment
     189    if lp is None:
     190        lp = env_loadparm()
     191    if session_info is None:
     192        session_info = samba.auth.system_session(lp)
     193    if credentials is None:
     194        credentials = cmdline_credentials
     195
     196    return SamDB(url=samdb_url,
     197                 lp=lp,
     198                 session_info=session_info,
     199                 credentials=credentials,
     200                 flags=flags,
     201                 options=ldb_options)
     202
     203
     204def connect_samdb_ex(samdb_url, lp=None, session_info=None, credentials=None,
     205                     flags=0, ldb_options=None, ldap_only=False):
     206    """Connects to samdb_url database
     207
     208    :param samdb_url: Url for database to connect to.
     209    :param lp: Optional loadparm object
     210    :param session_info: Optional session information
     211    :param credentials: Optional credentials, defaults to anonymous.
     212    :param flags: Optional LDB flags
     213    :param ldap_only: If set, only remote LDAP connection will be created.
     214    :return: (sam_db_connection, rootDse_record) tuple
     215    """
     216    sam_db = connect_samdb(samdb_url, lp, session_info, credentials,
     217                           flags, ldb_options, ldap_only)
     218    # fetch RootDse
     219    res = sam_db.search(base="", expression="", scope=ldb.SCOPE_BASE,
     220                        attrs=["*"])
     221    return (sam_db, res[0])
     222
     223
     224def delete_force(samdb, dn):
     225    try:
     226        samdb.delete(dn)
     227    except ldb.LdbError, (num, _):
     228        assert(num == ldb.ERR_NO_SUCH_OBJECT)
  • vendor/current/source4/scripting/python/samba/tests/dcerpc/__init__.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22# -*- coding: utf-8 -*-
    33
    44# Unix SMB/CIFS implementation.
    55# Copyright © Jelmer Vernooij <jelmer@samba.org> 2008
    6 #   
     6#
    77# This program is free software; you can redistribute it and/or modify
    88# it under the terms of the GNU General Public License as published by
    99# the Free Software Foundation; either version 3 of the License, or
    1010# (at your option) any later version.
    11 #   
     11#
    1212# This program is distributed in the hope that it will be useful,
    1313# but WITHOUT ANY WARRANTY; without even the implied warranty of
     
    1717# You should have received a copy of the GNU General Public License
    1818# along with this program.  If not, see <http://www.gnu.org/licenses/>.
    19 #
    2019
     20"""Tests for the DCE/RPC Python bindings."""
     21
  • vendor/current/source4/scripting/python/samba/tests/dcerpc/bare.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22# -*- coding: utf-8 -*-
    33
     
    1919#
    2020
     21"""Tests for samba.dcerpc.bare."""
     22
    2123from samba.dcerpc import ClientConnection
    22 from unittest import TestCase
    23 from samba.tests import cmdline_loadparm
     24import samba.tests
    2425
    25 
    26 class BareTestCase(TestCase):
     26class BareTestCase(samba.tests.TestCase):
    2727
    2828    def test_bare(self):
    2929        # Connect to the echo pipe
    3030        x = ClientConnection("ncalrpc:localhost[DEFAULT]",
    31                 ("60a15ec5-4de8-11d7-a637-005056a20182", 1), lp_ctx=cmdline_loadparm)
     31                ("60a15ec5-4de8-11d7-a637-005056a20182", 1),
     32                lp_ctx=samba.tests.env_loadparm())
    3233        self.assertEquals("\x01\x00\x00\x00", x.request(0, chr(0) * 4))
    3334
    3435    def test_alter_context(self):
    3536        x = ClientConnection("ncalrpc:localhost[DEFAULT]",
    36                 ("12345778-1234-abcd-ef00-0123456789ac", 1), lp_ctx=cmdline_loadparm)
     37                ("12345778-1234-abcd-ef00-0123456789ac", 1),
     38                lp_ctx=samba.tests.env_loadparm())
    3739        y = ClientConnection("ncalrpc:localhost",
    3840                ("60a15ec5-4de8-11d7-a637-005056a20182", 1),
    39                 basis_connection=x, lp_ctx=cmdline_loadparm)
     41                basis_connection=x, lp_ctx=samba.tests.env_loadparm())
    4042        x.alter_context(("60a15ec5-4de8-11d7-a637-005056a20182", 1))
    4143        # FIXME: self.assertEquals("\x01\x00\x00\x00", x.request(0, chr(0) * 4))
     
    4345    def test_two_connections(self):
    4446        x = ClientConnection("ncalrpc:localhost[DEFAULT]",
    45                 ("60a15ec5-4de8-11d7-a637-005056a20182", 1), lp_ctx=cmdline_loadparm)
     47                ("60a15ec5-4de8-11d7-a637-005056a20182", 1),
     48                lp_ctx=samba.tests.env_loadparm())
    4649        y = ClientConnection("ncalrpc:localhost",
    4750                ("60a15ec5-4de8-11d7-a637-005056a20182", 1),
    48                 basis_connection=x, lp_ctx=cmdline_loadparm)
     51                basis_connection=x, lp_ctx=samba.tests.env_loadparm())
    4952        self.assertEquals("\x01\x00\x00\x00", y.request(0, chr(0) * 4))
  • vendor/current/source4/scripting/python/samba/tests/dcerpc/misc.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation.
     
    1818#
    1919
    20 import unittest
     20"""Tests for samba.dcerpc.misc."""
     21
    2122from samba.dcerpc import misc
     23import samba.tests
    2224
    2325text1 = "76f53846-a7c2-476a-ae2c-20e2b80d7b34"
    2426text2 = "344edffa-330a-4b39-b96e-2c34da52e8b1"
    2527
    26 class GUIDTests(unittest.TestCase):
     28class GUIDTests(samba.tests.TestCase):
    2729
    2830    def test_str(self):
     
    4446        self.assertEquals(0, cmp(guid1, guid2))
    4547        self.assertEquals(guid1, guid2)
    46          
    47        
    48 class PolicyHandleTests(unittest.TestCase):
     48
     49
     50class PolicyHandleTests(samba.tests.TestCase):
    4951
    5052    def test_init(self):
  • vendor/current/source4/scripting/python/samba/tests/dcerpc/registry.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation.
     
    1818#
    1919
     20"""Tests for samba.dcerpc.registry."""
     21
    2022from samba.dcerpc import winreg
    2123from samba.tests import RpcInterfaceTestCase
     
    2527
    2628    def setUp(self):
     29        super(WinregTests, self).setUp()
    2730        self.conn = winreg.winreg("ncalrpc:", self.get_loadparm(),
    2831                                  self.get_credentials())
  • vendor/current/source4/scripting/python/samba/tests/dcerpc/rpcecho.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation.
     
    1818#
    1919
     20"""Tests for samba.dceprc.rpcecho."""
     21
    2022from samba.dcerpc import echo
    2123from samba.ndr import ndr_pack, ndr_unpack
    22 import unittest
    23 from samba.tests import RpcInterfaceTestCase
     24from samba.tests import RpcInterfaceTestCase, TestCase
    2425
    2526
     
    2728
    2829    def setUp(self):
     30        super(RpcEchoTests, self).setUp()
    2931        self.conn = echo.rpcecho("ncalrpc:", self.get_loadparm())
    3032
     
    3436
    3537    def test_abstract_syntax(self):
    36         self.assertEquals(("60a15ec5-4de8-11d7-a637-005056a20182", 1), 
     38        self.assertEquals(("60a15ec5-4de8-11d7-a637-005056a20182", 1),
    3739                          self.conn.abstract_syntax)
    3840
     
    6062
    6163
    62 class NdrEchoTests(unittest.TestCase):
     64class NdrEchoTests(TestCase):
    6365
    6466    def test_info1_push(self):
  • vendor/current/source4/scripting/python/samba/tests/dcerpc/sam.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22# -*- coding: utf-8 -*-
    33
     
    1919#
    2020
     21"""Tests for samba.dcerpc.sam."""
     22
    2123from samba.dcerpc import samr, security
    2224from samba.tests import RpcInterfaceTestCase
     
    3335
    3436    def setUp(self):
     37        super(SamrTests, self).setUp()
    3538        self.conn = samr.samr("ncalrpc:", self.get_loadparm())
    3639
     
    4043    def test_connect2(self):
    4144        handle = self.conn.Connect2(None, security.SEC_FLAG_MAXIMUM_ALLOWED)
     45        self.assertTrue(handle is not None)
    4246
    4347    def test_EnumDomains(self):
  • vendor/current/source4/scripting/python/samba/tests/dcerpc/unix.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation.
     
    1818#
    1919
     20"""Tests for samba.dcerpc.unixinfo."""
     21
     22
    2023from samba.dcerpc import unixinfo
    2124from samba.tests import RpcInterfaceTestCase
     
    2427
    2528    def setUp(self):
     29        super(UnixinfoTests, self).setUp()
    2630        self.conn = unixinfo.unixinfo("ncalrpc:", self.get_loadparm())
    2731
    28     def test_getpwuid(self):
     32    def test_getpwuid_int(self):
    2933        infos = self.conn.GetPWUid(range(512))
    3034        self.assertEquals(512, len(infos))
     
    3236        self.assertTrue(isinstance(infos[0].homedir, unicode))
    3337
     38    def test_getpwuid(self):
     39        infos = self.conn.GetPWUid(map(long, range(512)))
     40        self.assertEquals(512, len(infos))
     41        self.assertEquals("/bin/false", infos[0].shell)
     42        self.assertTrue(isinstance(infos[0].homedir, unicode))
     43
    3444    def test_gidtosid(self):
    35         self.conn.GidToSid(1000)
     45        self.conn.GidToSid(1000L)
    3646
    3747    def test_uidtosid(self):
    3848        self.conn.UidToSid(1000)
     49   
     50    def test_uidtosid_fail(self):
     51        self.assertRaises(TypeError, self.conn.UidToSid, "100")
  • vendor/current/source4/scripting/python/samba/tests/provision.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation.
     
    1818#
    1919
     20"""Tests for samba.provision."""
     21
    2022import os
    21 from samba.provision import setup_secretsdb, findnss
     23from samba.provision import setup_secretsdb, findnss, ProvisionPaths
    2224import samba.tests
    23 from ldb import Dn
    24 from samba import param
    25 import unittest
     25from samba.tests import env_loadparm, TestCase
    2626
    27 lp = samba.tests.cmdline_loadparm
     27def create_dummy_secretsdb(path, lp=None):
     28    """Create a dummy secrets database for use in tests.
    2829
    29 setup_dir = "setup"
    30 def setup_path(file):
    31     return os.path.join(setup_dir, file)
     30    :param path: Path to store the secrets db
     31    :param lp: Optional loadparm context. A simple one will
     32        be generated if not specified.
     33    """
     34    if lp is None:
     35        lp = env_loadparm()
     36    paths = ProvisionPaths()
     37    paths.secrets = path
     38    paths.private_dir = os.path.dirname(path)
     39    paths.keytab = "no.keytab"
     40    paths.dns_keytab = "no.dns.keytab"
     41    secrets_ldb = setup_secretsdb(paths, None, None, lp=lp)
     42    secrets_ldb.transaction_commit()
     43    return secrets_ldb
    3244
    3345
     
    3547    """Some simple tests for individual functions in the provisioning code.
    3648    """
     49
    3750    def test_setup_secretsdb(self):
    3851        path = os.path.join(self.tempdir, "secrets.ldb")
    39         ldb = setup_secretsdb(path, setup_path, None, None, lp=lp)
     52        paths = ProvisionPaths()
     53        paths.secrets = path
     54        paths.private_dir = os.path.dirname(path)
     55        paths.keytab = "no.keytab"
     56        paths.dns_keytab = "no.dns.keytab"
     57        ldb = setup_secretsdb(paths, None, None, lp=env_loadparm())
    4058        try:
    4159            self.assertEquals("LSA Secrets",
     
    4664           
    4765
    48 class FindNssTests(unittest.TestCase):
     66class FindNssTests(TestCase):
    4967    """Test findnss() function."""
     68
    5069    def test_nothing(self):
    5170        def x(y):
     
    6584
    6685class Disabled(object):
     86
    6787    def test_setup_templatesdb(self):
    6888        raise NotImplementedError(self.test_setup_templatesdb)
     
    95115        raise NotImplementedError(self.test_vampire)
    96116
    97     def test_erase_partitions(self):
    98         raise NotImplementedError(self.test_erase_partitions)
    99117
    100 
  • vendor/current/source4/scripting/python/samba/tests/samba3.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation.
     
    1818#
    1919
    20 import unittest
    21 from samba.samba3 import GroupMappingDatabase, Registry, PolicyDatabase, SecretsDatabase, TdbSam
    22 from samba.samba3 import WinsDatabase, SmbpasswdFile, ACB_NORMAL, IdmapDatabase, SAMUser, ParamFile
     20"""Tests for samba.samba3."""
     21
     22from samba.samba3 import (GroupMappingDatabase, Registry, PolicyDatabase,
     23        SecretsDatabase, TdbSam)
     24from samba.samba3 import (WinsDatabase, SmbpasswdFile, ACB_NORMAL,
     25        IdmapDatabase, SAMUser, ParamFile)
     26from samba.tests import TestCase
    2327import os
    2428
    25 DATADIR=os.path.join(os.path.dirname(__file__), "../../../../../testdata/samba3")
    26 print "Samba 3 data dir: %s" % DATADIR
    27 
    28 class RegistryTestCase(unittest.TestCase):
    29     def setUp(self):
     29for p in [ "../../../../../testdata/samba3", "../../../../testdata/samba3" ]:
     30    DATADIR = os.path.join(os.path.dirname(__file__), p)
     31    if os.path.exists(DATADIR):
     32        break
     33
     34
     35class RegistryTestCase(TestCase):
     36
     37    def setUp(self):
     38        super(RegistryTestCase, self).setUp()
    3039        self.registry = Registry(os.path.join(DATADIR, "registry.tdb"))
    3140
    3241    def tearDown(self):
    3342        self.registry.close()
     43        super(RegistryTestCase, self).tearDown()
    3444
    3545    def test_length(self):
     
    4858
    4959
    50 class PolicyTestCase(unittest.TestCase):
    51     def setUp(self):
     60class PolicyTestCase(TestCase):
     61
     62    def setUp(self):
     63        super(PolicyTestCase, self).setUp()
    5264        self.policy = PolicyDatabase(os.path.join(DATADIR, "account_policy.tdb"))
    5365
     
    6577
    6678
    67 class GroupsTestCase(unittest.TestCase):
    68     def setUp(self):
     79class GroupsTestCase(TestCase):
     80
     81    def setUp(self):
     82        super(GroupsTestCase, self).setUp()
    6983        self.groupdb = GroupMappingDatabase(os.path.join(DATADIR, "group_mapping.tdb"))
    7084
    7185    def tearDown(self):
    7286        self.groupdb.close()
     87        super(GroupsTestCase, self).tearDown()
    7388
    7489    def test_group_length(self):
     
    86101
    87102
    88 class SecretsDbTestCase(unittest.TestCase):
    89     def setUp(self):
     103class SecretsDbTestCase(TestCase):
     104
     105    def setUp(self):
     106        super(SecretsDbTestCase, self).setUp()
    90107        self.secretsdb = SecretsDatabase(os.path.join(DATADIR, "secrets.tdb"))
    91108
    92109    def tearDown(self):
    93110        self.secretsdb.close()
     111        super(SecretsDbTestCase, self).tearDown()
    94112
    95113    def test_get_sid(self):
     
    97115
    98116
    99 class TdbSamTestCase(unittest.TestCase):
    100     def setUp(self):
     117class TdbSamTestCase(TestCase):
     118
     119    def setUp(self):
     120        super(TdbSamTestCase, self).setUp()
    101121        self.samdb = TdbSam(os.path.join(DATADIR, "passdb.tdb"))
    102122
    103123    def tearDown(self):
    104124        self.samdb.close()
     125        super(TdbSamTestCase, self).tearDown()
    105126
    106127    def test_usernames(self):
     
    141162
    142163
    143 class WinsDatabaseTestCase(unittest.TestCase):
    144     def setUp(self):
     164class WinsDatabaseTestCase(TestCase):
     165
     166    def setUp(self):
     167        super(WinsDatabaseTestCase, self).setUp()
    145168        self.winsdb = WinsDatabase(os.path.join(DATADIR, "wins.dat"))
    146169
     
    153176    def tearDown(self):
    154177        self.winsdb.close()
    155 
    156 
    157 class SmbpasswdTestCase(unittest.TestCase):
    158     def setUp(self):
     178        super(WinsDatabaseTestCase, self).tearDown()
     179
     180
     181class SmbpasswdTestCase(TestCase):
     182
     183    def setUp(self):
     184        super(SmbpasswdTestCase, self).setUp()
    159185        self.samdb = SmbpasswdFile(os.path.join(DATADIR, "smbpasswd"))
    160186
     
    173199    def tearDown(self):
    174200        self.samdb.close()
    175 
    176 
    177 class IdmapDbTestCase(unittest.TestCase):
    178     def setUp(self):
    179         self.idmapdb = IdmapDatabase(os.path.join(DATADIR, "winbindd_idmap.tdb"))
     201        super(SmbpasswdTestCase, self).tearDown()
     202
     203
     204class IdmapDbTestCase(TestCase):
     205
     206    def setUp(self):
     207        super(IdmapDbTestCase, self).setUp()
     208        self.idmapdb = IdmapDatabase(os.path.join(DATADIR,
     209            "winbindd_idmap.tdb"))
    180210
    181211    def test_user_hwm(self):
     
    199229    def tearDown(self):
    200230        self.idmapdb.close()
    201 
    202 
    203 class ShareInfoTestCase(unittest.TestCase):
    204     def setUp(self):
    205         self.shareinfodb = ShareInfoDatabase(os.path.join(DATADIR, "share_info.tdb"))
    206 
    207     # FIXME: needs proper data so it can be tested
    208 
    209     def tearDown(self):
    210         self.shareinfodb.close()
    211 
    212 
    213 class ParamTestCase(unittest.TestCase):
     231        super(IdmapDbTestCase, self).tearDown()
     232
     233
     234class ParamTestCase(TestCase):
     235
    214236    def test_init(self):
    215237        file = ParamFile()
  • vendor/current/source4/scripting/python/samba/tests/samdb.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation. Tests for SamDB
    44# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2008
    5 #   
     5#
    66# This program is free software; you can redistribute it and/or modify
    77# it under the terms of the GNU General Public License as published by
    88# the Free Software Foundation; either version 3 of the License, or
    99# (at your option) any later version.
    10 #   
     10#
    1111# This program is distributed in the hope that it will be useful,
    1212# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1313# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1414# GNU General Public License for more details.
    15 #   
     15#
    1616# You should have received a copy of the GNU General Public License
    1717# along with this program.  If not, see <http://www.gnu.org/licenses/>.
    1818#
     19
     20"""Tests for samba.samdb."""
     21
     22import logging
     23import os
     24import uuid
     25
    1926from samba.auth import system_session
    20 from samba.credentials import Credentials
    21 import os
    22 from samba.provision import setup_samdb, guess_names, setup_templatesdb, make_smbconf, find_setup_dir
    23 from samba.samdb import SamDB
     27from samba.provision import (setup_samdb, guess_names, make_smbconf,
     28    provision_paths_from_lp)
     29from samba.provision import DEFAULT_POLICY_GUID, DEFAULT_DC_POLICY_GUID
     30from samba.provision.backend import ProvisionBackend
    2431from samba.tests import TestCaseInTempDir
    2532from samba.dcerpc import security
    26 from unittest import TestCase
    27 import uuid
     33from samba.schema import Schema
    2834from samba import param
    2935
     
    3137class SamDBTestCase(TestCaseInTempDir):
    3238    """Base-class for tests with a Sam Database.
    33    
     39
    3440    This is used by the Samba SamDB-tests, but e.g. also by the OpenChange
    3541    provisioning tests (which need a Sam).
    3642    """
    37 
    38     def setup_path(self, relpath):
    39         return os.path.join(find_setup_dir(), relpath)
    4043
    4144    def setUp(self):
     
    4750        schemadn = "CN=Schema," + configdn
    4851        domainguid = str(uuid.uuid4())
    49         policyguid = str(uuid.uuid4())
    50         creds = Credentials()
    51         creds.set_anonymous()
     52        policyguid = DEFAULT_POLICY_GUID
    5253        domainsid = security.random_sid()
    53         hostguid = str(uuid.uuid4())
    5454        path = os.path.join(self.tempdir, "samdb.ldb")
    5555        session_info = system_session()
     
    5959        dnsdomain="example.com"
    6060        serverrole="domain controller"
     61        policyguid_dc = DEFAULT_DC_POLICY_GUID
    6162
    6263        smbconf = os.path.join(self.tempdir, "smb.conf")
    63         make_smbconf(smbconf, self.setup_path, hostname, domain, dnsdomain,
     64        make_smbconf(smbconf, hostname, domain, dnsdomain,
    6465                     serverrole, self.tempdir)
    6566
     
    7273                            domaindn=self.domaindn, configdn=configdn,
    7374                            schemadn=schemadn)
    74         setup_templatesdb(os.path.join(self.tempdir, "templates.ldb"),
    75                           self.setup_path, session_info=session_info, lp=self.lp)
    76         self.samdb = setup_samdb(path, self.setup_path, session_info, creds,
    77                                  self.lp, names,
    78                                  lambda x: None, domainsid,
    79                                  domainguid,
    80                                  policyguid, False, "secret",
    81                                  "secret", "secret", invocationid,
    82                                  "secret", "domain controller")
     75
     76        paths = provision_paths_from_lp(self.lp, names.dnsdomain)
     77
     78        logger = logging.getLogger("provision")
     79
     80        provision_backend = ProvisionBackend("ldb", paths=paths,
     81                lp=self.lp, credentials=None,
     82                names=names, logger=logger)
     83
     84        schema = Schema(domainsid, invocationid=invocationid,
     85                schemadn=names.schemadn, serverdn=names.serverdn,
     86                am_rodc=False)
     87
     88        self.samdb = setup_samdb(path, session_info,
     89                provision_backend, self.lp, names, logger,
     90                domainsid, domainguid, policyguid, policyguid_dc, False,
     91                "secret", "secret", "secret", invocationid, "secret",
     92                None, "domain controller", schema=schema)
    8393
    8494    def tearDown(self):
    85         for f in ['templates.ldb', 'schema.ldb', 'configuration.ldb',
     95        for f in ['schema.ldb', 'configuration.ldb',
    8696                  'users.ldb', 'samdb.ldb', 'smb.conf']:
    8797            os.remove(os.path.join(self.tempdir, f))
    8898        super(SamDBTestCase, self).tearDown()
    89 
    90 
    91 # disable this test till andrew works it out ...
    92 class SamDBTests(SamDBTestCase):
    93     """Tests for the SamDB implementation."""
    94 
    95     print "samdb add_foreign disabled for now"
    96 #    def test_add_foreign(self):
  • vendor/current/source4/scripting/python/samba/tests/upgrade.py

    r414 r740  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22
    33# Unix SMB/CIFS implementation.
     
    1818#
    1919
    20 from samba import Ldb
     20"""Tests for samba.upgrade."""
     21
    2122from samba.upgrade import import_wins
    2223from samba.tests import LdbTestCase
    2324
    2425class WinsUpgradeTests(LdbTestCase):
     26
    2527    def test_upgrade(self):
    2628        winsdb = {
  • vendor/current/source4/scripting/python/samba/upgrade.py

    r414 r740  
    1 #!/usr/bin/python
     1# backend code for upgrading from Samba3
     2# Copyright Jelmer Vernooij 2005-2007
    23#
    3 #       backend code for upgrading from Samba3
    4 #       Copyright Jelmer Vernooij 2005-2007
    5 #       Released under the GNU GPL v3 or later
     4# This program is free software; you can redistribute it and/or modify
     5# it under the terms of the GNU General Public License as published by
     6# the Free Software Foundation; either version 3 of the License, or
     7# (at your option) any later version.
    68#
     9# This program is distributed in the hope that it will be useful,
     10# but WITHOUT ANY WARRANTY; without even the implied warranty of
     11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     12# GNU General Public License for more details.
     13#
     14# You should have received a copy of the GNU General Public License
     15# along with this program.  If not, see <http://www.gnu.org/licenses/>.
     16#
    717
    818"""Support code for upgrading from Samba 3 to Samba 4."""
     
    1020__docformat__ = "restructuredText"
    1121
    12 from provision import provision, FILL_DRS
    1322import grp
    1423import ldb
    1524import time
    1625import pwd
    17 import registry
    18 from samba import Ldb
     26
     27from samba import Ldb, registry
    1928from samba.param import LoadParm
     29from samba.provision import provision
    2030
    2131def import_sam_policy(samldb, policy, dn):
     
    3545samba3DisconnectTime: %d
    3646
    37 """ % (dn, policy.min_password_length, 
     47""" % (dn, policy.min_password_length,
    3848    policy.password_history, policy.minimum_password_age,
    3949    policy.maximum_password_age, policy.lockout_duration,
     
    4454def import_sam_account(samldb,acc,domaindn,domainsid):
    4555    """Import a Samba 3 SAM account.
    46    
     56
    4757    :param samldb: Samba 4 SAM Database handle
    4858    :param acc: Samba 3 account
     
    6070    if acc.fullname is None:
    6171        acc.fullname = acc.username
    62    
     72
    6373    assert acc.fullname is not None
    6474    assert acc.nt_username is not None
     
    7989        "samba3DirDrive": acc.dir_drive,
    8090        "samba3MungedDial": acc.munged_dial,
    81         "samba3Homedir": acc.homedir, 
    82         "samba3LogonScript": acc.logon_script, 
     91        "samba3Homedir": acc.homedir,
     92        "samba3LogonScript": acc.logon_script,
    8393        "samba3ProfilePath": acc.profile_path,
    8494        "samba3Workstations": acc.workstations,
     
    96106def import_sam_group(samldb, sid, gid, sid_name_use, nt_name, comment, domaindn):
    97107    """Upgrade a SAM group.
    98    
     108
    99109    :param samldb: SAM database.
    100110    :param gid: Group GID
     
    110120    if nt_name in ("Domain Guests", "Domain Users", "Domain Admins"):
    111121        return None
    112    
     122
    113123    if gid == -1:
    114124        gr = grp.getgrnam(nt_name)
     
    122132
    123133    assert unixname is not None
    124    
     134
    125135    samldb.add({
    126136        "dn": "cn=%s,%s" % (nt_name, domaindn),
    127137        "objectClass": ["top", "group"],
    128138        "description": comment,
    129         "cn": nt_name, 
     139        "cn": nt_name,
    130140        "objectSid": sid,
    131141        "unixName": unixname,
     
    161171def import_wins(samba4_winsdb, samba3_winsdb):
    162172    """Import settings from a Samba3 WINS database.
    163    
     173
    164174    :param samba4_winsdb: WINS database to import to
    165175    :param samba3_winsdb: WINS database to import from
     
    209219                       "maxVersion": str(version_id)})
    210220
    211 def upgrade_provision(samba3, setup_dir, message, credentials, session_info, smbconf, targetdir):
    212     oldconf = samba3.get_conf()
    213 
    214     if oldconf.get("domain logons") == "True":
    215         serverrole = "domain controller"
    216     else:
    217         if oldconf.get("security") == "user":
    218             serverrole = "standalone"
    219         else:
    220             serverrole = "member server"
    221 
    222     domainname = oldconf.get("workgroup")
    223     if domainname:
    224         domainname = str(domainname)
    225     realm = oldconf.get("realm")
    226     netbiosname = oldconf.get("netbios name")
    227 
    228     secrets_db = samba3.get_secrets_db()
    229    
    230     if domainname is None:
    231         domainname = secrets_db.domains()[0]
    232         message("No domain specified in smb.conf file, assuming '%s'" % domainname)
    233    
    234     if realm is None:
    235         realm = domainname.lower()
    236         message("No realm specified in smb.conf file, assuming '%s'\n" % realm)
    237 
    238     domainguid = secrets_db.get_domain_guid(domainname)
    239     domainsid = secrets_db.get_sid(domainname)
    240     if domainsid is None:
    241         message("Can't find domain secrets for '%s'; using random SID\n" % domainname)
    242    
    243     if netbiosname is not None:
    244         machinepass = secrets_db.get_machine_password(netbiosname)
    245     else:
    246         machinepass = None
    247    
    248     result = provision(setup_dir=setup_dir, message=message,
    249                        samdb_fill=FILL_DRS, smbconf=smbconf, session_info=session_info,
    250                        credentials=credentials, realm=realm,
    251                        domain=domainname, domainsid=domainsid, domainguid=domainguid,
    252                        machinepass=machinepass, serverrole=serverrole, targetdir=targetdir)
    253 
    254     import_wins(Ldb(result.paths.winsdb), samba3.get_wins_db())
    255 
    256     # FIXME: import_registry(registry.Registry(), samba3.get_registry())
    257 
    258     # FIXME: import_idmap(samdb,samba3.get_idmap_db(),domaindn)
    259    
    260     groupdb = samba3.get_groupmapping_db()
    261     for sid in groupdb.groupsids():
    262         (gid, sid_name_use, nt_name, comment) = groupdb.get_group(sid)
    263         # FIXME: import_sam_group(samdb, sid, gid, sid_name_use, nt_name, comment, domaindn)
    264 
    265     # FIXME: Aliases
    266 
    267     passdb = samba3.get_sam_db()
    268     for name in passdb:
    269         user = passdb[name]
    270         #FIXME: import_sam_account(result.samdb, user, domaindn, domainsid)
    271 
    272     if hasattr(passdb, 'ldap_url'):
    273         message("Enabling Samba3 LDAP mappings for SAM database")
    274 
    275         enable_samba3sam(result.samdb, passdb.ldap_url)
    276 
    277 
    278221def enable_samba3sam(samdb, ldapurl):
    279222    """Enable Samba 3 LDAP URL database.
     
    293236
    294237smbconf_keep = [
    295     "dos charset", 
     238    "dos charset",
    296239    "unix charset",
    297240    "display charset",
     
    390333
    391334    :param oldconf: Old configuration structure
    392     :param mark: Whether removed configuration variables should be 
     335    :param mark: Whether removed configuration variables should be
    393336        kept in the new configuration as "samba3:<name>"
    394337    """
     
    435378
    436379
     380def upgrade_provision(samba3, logger, credentials, session_info,
     381                      smbconf, targetdir):
     382    oldconf = samba3.get_conf()
     383
     384    if oldconf.get("domain logons") == "True":
     385        serverrole = "domain controller"
     386    else:
     387        if oldconf.get("security") == "user":
     388            serverrole = "standalone"
     389        else:
     390            serverrole = "member server"
     391
     392    domainname = oldconf.get("workgroup")
     393    realm = oldconf.get("realm")
     394    netbiosname = oldconf.get("netbios name")
     395
     396    secrets_db = samba3.get_secrets_db()
     397
     398    if domainname is None:
     399        domainname = secrets_db.domains()[0]
     400        logger.warning("No domain specified in smb.conf file, assuming '%s'",
     401                domainname)
     402
     403    if realm is None:
     404        if oldconf.get("domain logons") == "True":
     405            logger.warning("No realm specified in smb.conf file and being a DC. That upgrade path doesn't work! Please add a 'realm' directive to your old smb.conf to let us know which one you want to use (generally it's the upcased DNS domainname).")
     406            return
     407        else:
     408            realm = domainname.upper()
     409            logger.warning("No realm specified in smb.conf file, assuming '%s'",
     410                    realm)
     411
     412    domainguid = secrets_db.get_domain_guid(domainname)
     413    domainsid = secrets_db.get_sid(domainname)
     414    if domainsid is None:
     415        logger.warning("Can't find domain secrets for '%s'; using random SID",
     416            domainname)
     417
     418    if netbiosname is not None:
     419        machinepass = secrets_db.get_machine_password(netbiosname)
     420    else:
     421        machinepass = None
     422
     423    result = provision(logger=logger,
     424                       session_info=session_info, credentials=credentials,
     425                       targetdir=targetdir, realm=realm, domain=domainname,
     426                       domainguid=domainguid, domainsid=domainsid,
     427                       hostname=netbiosname, machinepass=machinepass,
     428                       serverrole=serverrole)
     429
     430    import_wins(Ldb(result.paths.winsdb), samba3.get_wins_db())
     431
     432    # FIXME: import_registry(registry.Registry(), samba3.get_registry())
     433
     434    # FIXME: import_idmap(samdb,samba3.get_idmap_db(),domaindn)
     435
     436    groupdb = samba3.get_groupmapping_db()
     437    for sid in groupdb.groupsids():
     438        (gid, sid_name_use, nt_name, comment) = groupdb.get_group(sid)
     439        # FIXME: import_sam_group(samdb, sid, gid, sid_name_use, nt_name, comment, domaindn)
     440
     441    # FIXME: Aliases
     442
     443    passdb = samba3.get_sam_db()
     444    for name in passdb:
     445        user = passdb[name]
     446        #FIXME: import_sam_account(result.samdb, user, domaindn, domainsid)
     447
     448    if hasattr(passdb, 'ldap_url'):
     449        logger.info("Enabling Samba3 LDAP mappings for SAM database")
     450
     451        enable_samba3sam(result.samdb, passdb.ldap_url)
     452
  • vendor/current/source4/scripting/python/uuidmodule.c

    r414 r740  
    1818*/
    1919
     20#include <Python.h>
    2021#include "includes.h"
    21 #include <Python.h>
    2222#include "librpc/ndr/libndr.h"
    2323
Note: See TracChangeset for help on using the changeset viewer.