Ignore:
Timestamp:
Nov 24, 2016, 1:14:11 PM (9 years ago)
Author:
Silvan Scherrer
Message:

Samba Server: update vendor to version 4.4.3

Location:
vendor/current/source3/utils
Files:
24 added
3 deleted
65 edited

Legend:

Unmodified
Added
Removed
  • vendor/current/source3/utils/dbwrap_tool.c

    r740 r988  
    55
    66   Copyright (C) 2009 Michael Adam <obnox@samba.org>
     7   Copyright (C) 2011 Bjoern Baumbach <bb@sernet.de>
    78
    89   This program is free software; you can redistribute it and/or modify
     
    2223#include "includes.h"
    2324#include "system/filesys.h"
    24 #include "dbwrap.h"
     25#include "popt_common.h"
     26#include "dbwrap/dbwrap.h"
     27#include "dbwrap/dbwrap_open.h"
     28#include "dbwrap/dbwrap_watch.h"
    2529#include "messages.h"
    26 
    27 typedef enum { OP_FETCH, OP_STORE, OP_DELETE, OP_ERASE, OP_LISTKEYS } dbwrap_op;
    28 
    29 typedef enum { TYPE_INT32, TYPE_UINT32 } dbwrap_type;
     30#include "util_tdb.h"
     31
     32enum dbwrap_op { OP_FETCH, OP_STORE, OP_DELETE, OP_ERASE, OP_LISTKEYS,
     33                 OP_LISTWATCHERS, OP_EXISTS };
     34
     35enum dbwrap_type { TYPE_INT32, TYPE_UINT32, TYPE_STRING, TYPE_HEX, TYPE_NONE };
    3036
    3137static int dbwrap_tool_fetch_int32(struct db_context *db,
    3238                                   const char *keyname,
    33                                    void *data)
     39                                   const char *data)
    3440{
    3541        int32_t value;
    36 
    37         value = dbwrap_fetch_int32(db, keyname);
     42        NTSTATUS status;
     43
     44        status = dbwrap_fetch_int32_bystring(db, keyname, &value);
     45        if (!NT_STATUS_IS_OK(status)) {
     46                d_printf("Error fetching int32 from key '%s': %s\n",
     47                         keyname, nt_errstr(status));
     48                return -1;
     49        }
    3850        d_printf("%d\n", value);
    3951
     
    4355static int dbwrap_tool_fetch_uint32(struct db_context *db,
    4456                                    const char *keyname,
    45                                     void *data)
     57                                    const char *data)
    4658{
    4759        uint32_t value;
    48         bool ret;
    49 
    50         ret = dbwrap_fetch_uint32(db, keyname, &value);
    51         if (ret) {
     60        NTSTATUS ret;
     61
     62        ret = dbwrap_fetch_uint32_bystring(db, keyname, &value);
     63        if (NT_STATUS_IS_OK(ret)) {
    5264                d_printf("%u\n", value);
    5365                return 0;
    5466        } else {
    55                 d_fprintf(stderr, "ERROR: could not fetch uint32 key '%s'\n",
    56                           keyname);
    57                 return -1;
    58         }
     67                d_fprintf(stderr, "ERROR: could not fetch uint32 key '%s': "
     68                          "%s\n", nt_errstr(ret), keyname);
     69                return -1;
     70        }
     71}
     72
     73static int dbwrap_tool_fetch_string(struct db_context *db,
     74                                    const char *keyname,
     75                                    const char *data)
     76{
     77        TDB_DATA tdbdata;
     78        NTSTATUS status;
     79        TALLOC_CTX *tmp_ctx = talloc_stackframe();
     80        int ret;
     81
     82        status = dbwrap_fetch_bystring(db, tmp_ctx, keyname, &tdbdata);
     83        if (NT_STATUS_IS_OK(status)) {
     84                d_printf("%-*.*s\n", (int)tdbdata.dsize, (int)tdbdata.dsize,
     85                         tdbdata.dptr);
     86                ret = 0;
     87        } else {
     88                d_fprintf(stderr, "ERROR: could not fetch string key '%s': "
     89                          "%s\n", nt_errstr(status), keyname);
     90                ret = -1;
     91        }
     92
     93        talloc_free(tmp_ctx);
     94        return ret;
     95}
     96
     97static int dbwrap_tool_fetch_hex(struct db_context *db,
     98                                 const char *keyname,
     99                                 const char *data)
     100{
     101        TDB_DATA tdbdata;
     102        DATA_BLOB datablob;
     103        NTSTATUS status;
     104        TALLOC_CTX *tmp_ctx = talloc_stackframe();
     105        char *hex_string;
     106        int ret;
     107
     108        status = dbwrap_fetch_bystring(db, tmp_ctx, keyname, &tdbdata);
     109        if (NT_STATUS_IS_OK(status)) {
     110                datablob.data = tdbdata.dptr;
     111                datablob.length = tdbdata.dsize;
     112
     113                hex_string = data_blob_hex_string_upper(tmp_ctx, &datablob);
     114                if (hex_string == NULL) {
     115                        d_fprintf(stderr, "ERROR: could not get hex string "
     116                                  "from data blob\n");
     117                        ret = -1;
     118                } else {
     119                        d_printf("%s\n", hex_string);
     120                        ret =  0;
     121                }
     122        } else {
     123                d_fprintf(stderr, "ERROR: could not fetch hex key '%s': "
     124                          "%s\n", nt_errstr(status), keyname);
     125                ret = -1;
     126        }
     127
     128        talloc_free(tmp_ctx);
     129        return ret;
    59130}
    60131
    61132static int dbwrap_tool_store_int32(struct db_context *db,
    62133                                   const char *keyname,
    63                                    void *data)
    64 {
    65         NTSTATUS status;
    66         int32_t value = *((int32_t *)data);
    67 
    68         status = dbwrap_trans_store_int32(db, keyname, value);
    69 
     134                                   const char *data)
     135{
     136        NTSTATUS status;
     137        int32_t value = (int32_t)strtol(data, NULL, 10);
     138
     139        if (dbwrap_is_persistent(db)) {
     140                status = dbwrap_trans_store_int32_bystring(db, keyname, value);
     141        } else {
     142                status = dbwrap_store_int32_bystring(db, keyname, value);
     143        }
    70144        if (!NT_STATUS_IS_OK(status)) {
    71145                d_fprintf(stderr, "ERROR: could not store int32 key '%s': %s\n",
     
    79153static int dbwrap_tool_store_uint32(struct db_context *db,
    80154                                    const char *keyname,
    81                                     void *data)
    82 {
    83         NTSTATUS status;
    84         uint32_t value = *((uint32_t *)data);
    85 
    86         status = dbwrap_trans_store_uint32(db, keyname, value);
    87 
     155                                    const char *data)
     156{
     157        NTSTATUS status;
     158        uint32_t value = (uint32_t)strtol(data, NULL, 10);
     159
     160        if (dbwrap_is_persistent(db)) {
     161                status = dbwrap_trans_store_uint32_bystring(db, keyname, value);
     162        } else {
     163                status = dbwrap_store_uint32_bystring(db, keyname, value);
     164        }
    88165        if (!NT_STATUS_IS_OK(status)) {
    89166                d_fprintf(stderr,
     
    96173}
    97174
     175static int dbwrap_tool_store_string(struct db_context *db,
     176                                    const char *keyname,
     177                                    const char *data)
     178{
     179        NTSTATUS status;
     180        TDB_DATA tdbdata;
     181
     182        tdbdata = string_term_tdb_data(data);
     183
     184        if (dbwrap_is_persistent(db)) {
     185                status = dbwrap_trans_store_bystring(db, keyname,
     186                                                     tdbdata,
     187                                                     TDB_REPLACE);
     188        } else {
     189                status = dbwrap_store_bystring(db, keyname,
     190                                              tdbdata,
     191                                              TDB_REPLACE);
     192        }
     193        if (!NT_STATUS_IS_OK(status)) {
     194                d_fprintf(stderr,
     195                          "ERROR: could not store string key '%s': %s\n",
     196                          keyname, nt_errstr(status));
     197                return -1;
     198        }
     199
     200        return 0;
     201}
     202
     203static int dbwrap_tool_store_hex(struct db_context *db,
     204                                    const char *keyname,
     205                                    const char *data)
     206{
     207        NTSTATUS status;
     208        DATA_BLOB datablob;
     209        TDB_DATA tdbdata;
     210        TALLOC_CTX *tmp_ctx = talloc_stackframe();
     211
     212        datablob = strhex_to_data_blob(tmp_ctx, data);
     213        if(strlen(data) > 0 && datablob.length == 0) {
     214                d_fprintf(stderr,
     215                          "ERROR: could not convert hex string to data blob\n"
     216                          "       Not a valid hex string?\n");
     217                talloc_free(tmp_ctx);
     218                return -1;
     219        }
     220
     221        tdbdata.dptr = (unsigned char *)datablob.data;
     222        tdbdata.dsize = datablob.length;
     223
     224        if (dbwrap_is_persistent(db)) {
     225                status = dbwrap_trans_store_bystring(db, keyname,
     226                                                     tdbdata,
     227                                                     TDB_REPLACE);
     228        } else {
     229                status = dbwrap_store_bystring(db, keyname,
     230                                               tdbdata,
     231                                               TDB_REPLACE);
     232        }
     233        if (!NT_STATUS_IS_OK(status)) {
     234                d_fprintf(stderr,
     235                          "ERROR: could not store string key '%s': %s\n",
     236                          keyname, nt_errstr(status));
     237                talloc_free(tmp_ctx);
     238                return -1;
     239        }
     240
     241        talloc_free(tmp_ctx);
     242        return 0;
     243}
     244
    98245static int dbwrap_tool_delete(struct db_context *db,
    99246                              const char *keyname,
    100                               void *data)
    101 {
    102         NTSTATUS status;
    103 
    104         status = dbwrap_trans_delete_bystring(db, keyname);
     247                              const char *data)
     248{
     249        NTSTATUS status;
     250
     251        if (dbwrap_is_persistent(db)) {
     252                status = dbwrap_trans_delete_bystring(db, keyname);
     253        } else {
     254                status = dbwrap_delete_bystring(db, keyname);
     255        }
    105256
    106257        if (!NT_STATUS_IS_OK(status)) {
     
    113264}
    114265
     266static int dbwrap_tool_exists(struct db_context *db,
     267                              const char *keyname,
     268                              const char *data)
     269{
     270        bool result;
     271
     272        result = dbwrap_exists(db, string_term_tdb_data(keyname));
     273
     274        if (result) {
     275                d_fprintf(stdout, "Key %s exists\n", keyname);
     276        } else {
     277                d_fprintf(stdout, "Key %s does not exist\n", keyname);
     278        }
     279
     280        return (result)?0:1;
     281}
     282
     283
    115284static int delete_fn(struct db_record *rec, void *priv)
    116285{
    117         rec->delete_rec(rec);
     286        dbwrap_record_delete(rec);
    118287        return 0;
    119288}
     
    125294static int dbwrap_tool_erase(struct db_context *db,
    126295                             const char *keyname,
    127                              void *data)
    128 {
    129         int ret;
    130 
    131         ret = db->traverse(db, delete_fn, NULL);
    132 
    133         if (ret < 0) {
     296                             const char *data)
     297{
     298        NTSTATUS status;
     299
     300        status = dbwrap_traverse(db, delete_fn, NULL, NULL);
     301
     302        if (!NT_STATUS_IS_OK(status)) {
    134303                d_fprintf(stderr, "ERROR erasing the database\n");
    135304                return -1;
     
    141310static int listkey_fn(struct db_record *rec, void *private_data)
    142311{
    143         int length = rec->key.dsize;
    144         unsigned char *p = (unsigned char *)rec->key.dptr;
     312        int length = dbwrap_record_get_key(rec).dsize;
     313        unsigned char *p = (unsigned char *)dbwrap_record_get_key(rec).dptr;
    145314
    146315        while (length--) {
     
    160329static int dbwrap_tool_listkeys(struct db_context *db,
    161330                                const char *keyname,
    162                                 void *data)
    163 {
    164         int ret;
    165 
    166         ret = db->traverse_read(db, listkey_fn, NULL);
    167 
    168         if (ret < 0) {
     331                                const char *data)
     332{
     333        NTSTATUS status;
     334
     335        status = dbwrap_traverse_read(db, listkey_fn, NULL, NULL);
     336
     337        if (!NT_STATUS_IS_OK(status)) {
    169338                d_fprintf(stderr, "ERROR listing db keys\n");
    170339                return -1;
     
    174343}
    175344
     345static int dbwrap_tool_listwatchers_cb(const uint8_t *db_id, size_t db_id_len,
     346                                       const TDB_DATA key,
     347                                       const struct server_id *watchers,
     348                                       size_t num_watchers,
     349                                       void *private_data)
     350{
     351        uint32_t i;
     352        dump_data_file(db_id, db_id_len, false, stdout);
     353        dump_data_file(key.dptr, key.dsize, false, stdout);
     354
     355        for (i=0; i<num_watchers; i++) {
     356                struct server_id_buf idbuf;
     357                printf("%s\n", server_id_str_buf(watchers[i], &idbuf));
     358        }
     359        printf("\n");
     360        return 0;
     361}
     362
     363
     364static int dbwrap_tool_listwatchers(struct db_context *db,
     365                                    const char *keyname,
     366                                    const char *data)
     367{
     368        dbwrap_watchers_traverse_read(dbwrap_tool_listwatchers_cb, NULL);
     369        return 0;
     370}
     371
    176372struct dbwrap_op_dispatch_table {
    177         dbwrap_op op;
    178         dbwrap_type type;
     373        enum dbwrap_op op;
     374        enum dbwrap_type type;
    179375        int (*cmd)(struct db_context *db,
    180376                   const char *keyname,
    181                    void *data);
     377                   const char *data);
    182378};
    183379
     
    185381        { OP_FETCH,  TYPE_INT32,  dbwrap_tool_fetch_int32 },
    186382        { OP_FETCH,  TYPE_UINT32, dbwrap_tool_fetch_uint32 },
     383        { OP_FETCH,  TYPE_STRING, dbwrap_tool_fetch_string },
     384        { OP_FETCH,  TYPE_HEX,    dbwrap_tool_fetch_hex },
    187385        { OP_STORE,  TYPE_INT32,  dbwrap_tool_store_int32 },
    188386        { OP_STORE,  TYPE_UINT32, dbwrap_tool_store_uint32 },
     387        { OP_STORE,  TYPE_STRING, dbwrap_tool_store_string },
     388        { OP_STORE,  TYPE_HEX,    dbwrap_tool_store_hex },
    189389        { OP_DELETE, TYPE_INT32,  dbwrap_tool_delete },
    190390        { OP_ERASE,  TYPE_INT32,  dbwrap_tool_erase },
    191391        { OP_LISTKEYS, TYPE_INT32, dbwrap_tool_listkeys },
     392        { OP_LISTWATCHERS, TYPE_NONE, dbwrap_tool_listwatchers },
     393        { OP_EXISTS, TYPE_STRING, dbwrap_tool_exists },
    192394        { 0, 0, NULL },
    193395};
     
    203405        const char *dbname;
    204406        const char *opname;
    205         dbwrap_op op;
     407        enum dbwrap_op op;
    206408        const char *keyname = "";
    207409        const char *keytype = "int32";
    208         dbwrap_type type;
     410        enum dbwrap_type type;
    209411        const char *valuestr = "0";
    210         int32_t value = 0;
     412        int persistent = 0;
     413        int non_persistent = 0;
     414        int tdb_flags = TDB_DEFAULT;
    211415
    212416        TALLOC_CTX *mem_ctx = talloc_stackframe();
     
    214418        int ret = 1;
    215419
    216         load_case_tables();
     420        struct poptOption popt_options[] = {
     421                POPT_AUTOHELP
     422                POPT_COMMON_SAMBA
     423                { "non-persistent", 0, POPT_ARG_NONE, &non_persistent, 0,
     424                  "treat the database as non-persistent "
     425                  "(CAVEAT: This mode might wipe your database!)",
     426                  NULL },
     427                { "persistent", 0, POPT_ARG_NONE, &persistent, 0,
     428                  "treat the database as persistent",
     429                  NULL },
     430                POPT_TABLEEND
     431        };
     432        int opt;
     433        const char **extra_argv;
     434        int extra_argc = 0;
     435        poptContext pc;
     436
     437        smb_init_locale();
    217438        lp_set_cmdline("log level", "0");
    218439        setup_logging(argv[0], DEBUG_STDERR);
    219         lp_load(get_dyn_CONFIGFILE(), true, false, false, true);
    220 
    221         if ((argc < 3) || (argc > 6)) {
     440
     441        pc = poptGetContext(argv[0], argc, argv, popt_options, POPT_CONTEXT_KEEP_FIRST);
     442
     443        while ((opt = poptGetNextOpt(pc)) != -1) {
     444                switch (opt) {
     445                default:
     446                        fprintf(stderr, "Invalid option %s: %s\n",
     447                                poptBadOption(pc, 0), poptStrerror(opt));
     448                        goto done;
     449                }
     450        }
     451
     452        /* setup the remaining options for the main program to use */
     453        extra_argv = poptGetArgs(pc);
     454        if (extra_argv) {
     455                extra_argv++;
     456                while (extra_argv[extra_argc]) extra_argc++;
     457        }
     458
     459        lp_load_global(get_dyn_CONFIGFILE());
     460
     461        if ((extra_argc < 2) || (extra_argc > 5)) {
    222462                d_fprintf(stderr,
    223                           "USAGE: %s <database> <op> [<key> [<type> [<value>]]]\n"
    224                           "       ops: fetch, store, delete, erase, listkeys\n"
    225                           "       types: int32, uint32\n",
     463                          "USAGE: %s [options] <database> <op> [<key> [<type> "
     464                          "[<value>]]]\n"
     465                          "       ops: fetch, store, delete, exists, "
     466                          "erase, listkeys, listwatchers\n"
     467                          "       types: int32, uint32, string, hex\n",
    226468                         argv[0]);
    227469                goto done;
    228470        }
    229471
    230         dbname = argv[1];
    231         opname = argv[2];
     472        if ((persistent == 0 && non_persistent == 0) ||
     473            (persistent == 1 && non_persistent == 1))
     474        {
     475                d_fprintf(stderr, "ERROR: you must specify exactly one "
     476                          "of --persistent and --non-persistent\n");
     477                goto done;
     478        } else if (non_persistent == 1) {
     479                tdb_flags |= TDB_CLEAR_IF_FIRST;
     480        }
     481
     482        dbname = extra_argv[0];
     483        opname = extra_argv[1];
    232484
    233485        if (strcmp(opname, "store") == 0) {
    234                 if (argc != 6) {
     486                if (extra_argc != 5) {
    235487                        d_fprintf(stderr, "ERROR: operation 'store' requires "
    236488                                  "value argument\n");
    237489                        goto done;
    238490                }
    239                 valuestr = argv[5];
    240                 keytype = argv[4];
    241                 keyname = argv[3];
     491                valuestr = extra_argv[4];
     492                keytype = extra_argv[3];
     493                keyname = extra_argv[2];
    242494                op = OP_STORE;
    243495        } else if (strcmp(opname, "fetch") == 0) {
    244                 if (argc != 5) {
     496                if (extra_argc != 4) {
    245497                        d_fprintf(stderr, "ERROR: operation 'fetch' requires "
    246498                                  "type but not value argument\n");
     
    248500                }
    249501                op = OP_FETCH;
    250                 keytype = argv[4];
    251                 keyname = argv[3];
     502                keytype = extra_argv[3];
     503                keyname = extra_argv[2];
    252504        } else if (strcmp(opname, "delete") == 0) {
    253                 if (argc != 4) {
     505                if (extra_argc != 3) {
    254506                        d_fprintf(stderr, "ERROR: operation 'delete' does "
    255507                                  "not allow type nor value argument\n");
    256508                        goto done;
    257509                }
    258                 keyname = argv[3];
     510                keyname = extra_argv[2];
    259511                op = OP_DELETE;
    260512        } else if (strcmp(opname, "erase") == 0) {
    261                 if (argc != 3) {
     513                if (extra_argc != 2) {
    262514                        d_fprintf(stderr, "ERROR: operation 'erase' does "
    263515                                  "not take a key argument\n");
     
    266518                op = OP_ERASE;
    267519        } else if (strcmp(opname, "listkeys") == 0) {
    268                 if (argc != 3) {
     520                if (extra_argc != 2) {
    269521                        d_fprintf(stderr, "ERROR: operation 'listkeys' does "
    270522                                  "not take a key argument\n");
     
    272524                }
    273525                op = OP_LISTKEYS;
     526        } else if (strcmp(opname, "listwatchers") == 0) {
     527                if (extra_argc != 2) {
     528                        d_fprintf(stderr, "ERROR: operation 'listwatchers' "
     529                                  "does not take an argument\n");
     530                        goto done;
     531                }
     532                op = OP_LISTWATCHERS;
     533                keytype = "none";
     534        } else if (strcmp(opname, "exists") == 0) {
     535                if (extra_argc != 3) {
     536                        d_fprintf(stderr, "ERROR: operation 'exists' does "
     537                                  "not allow type nor value argument\n");
     538                        goto done;
     539                }
     540                keyname = extra_argv[2];
     541                op = OP_EXISTS;
     542                keytype = "string";
    274543        } else {
    275544                d_fprintf(stderr,
    276545                          "ERROR: invalid op '%s' specified\n"
    277                           "       supported ops: fetch, store, delete\n",
     546                          "       supported ops: fetch, store, delete, exists, "
     547                          "erase, listkeys, listwatchers\n",
    278548                          opname);
    279549                goto done;
     
    282552        if (strcmp(keytype, "int32") == 0) {
    283553                type = TYPE_INT32;
    284                 value = (int32_t)strtol(valuestr, NULL, 10);
    285554        } else if (strcmp(keytype, "uint32") == 0) {
    286555                type = TYPE_UINT32;
    287                 value = (int32_t)strtoul(valuestr, NULL, 10);
     556        } else if (strcmp(keytype, "string") == 0) {
     557                type = TYPE_STRING;
     558        } else if (strcmp(keytype, "hex") == 0) {
     559                type = TYPE_HEX;
     560        } else if (strcmp(keytype, "none") == 0) {
     561                type = TYPE_NONE;
    288562        } else {
    289563                d_fprintf(stderr, "ERROR: invalid type '%s' specified.\n"
    290                                   "       supported types: int32, uint32\n",
     564                                  "       supported types: int32, uint32, "
     565                                  "string, hex, none\n",
    291566                                  keytype);
    292567                goto done;
    293568        }
    294569
    295         evt_ctx = tevent_context_init(mem_ctx);
     570        evt_ctx = samba_tevent_context_init(mem_ctx);
    296571        if (evt_ctx == NULL) {
    297572                d_fprintf(stderr, "ERROR: could not init event context\n");
     
    299574        }
    300575
    301         msg_ctx = messaging_init(mem_ctx, procid_self(), evt_ctx);
     576        msg_ctx = messaging_init(mem_ctx, evt_ctx);
    302577        if (msg_ctx == NULL) {
    303578                d_fprintf(stderr, "ERROR: could not init messaging context\n");
     
    305580        }
    306581
    307         db = db_open(mem_ctx, dbname, 0, TDB_DEFAULT, O_RDWR | O_CREAT, 0644);
    308         if (db == NULL) {
    309                 d_fprintf(stderr, "ERROR: could not open dbname\n");
    310                 goto done;
     582        switch (op) {
     583        case OP_FETCH:
     584        case OP_STORE:
     585        case OP_DELETE:
     586        case OP_ERASE:
     587        case OP_LISTKEYS:
     588        case OP_EXISTS:
     589                db = db_open(mem_ctx, dbname, 0, tdb_flags, O_RDWR | O_CREAT,
     590                             0644, DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
     591                if (db == NULL) {
     592                        d_fprintf(stderr, "ERROR: could not open dbname\n");
     593                        goto done;
     594                }
     595                break;
     596        default:
     597                db = NULL;
     598                break;
    311599        }
    312600
     
    315603                    (type == dispatch_table[count].type))
    316604                {
    317                         ret = dispatch_table[count].cmd(db, keyname, &value);
     605                        ret = dispatch_table[count].cmd(db, keyname, valuestr);
    318606                        break;
    319607                }
  • vendor/current/source3/utils/dbwrap_torture.c

    r740 r988  
    2323#include "system/filesys.h"
    2424#include "popt_common.h"
    25 #include "dbwrap.h"
     25#include "dbwrap/dbwrap.h"
     26#include "dbwrap/dbwrap_open.h"
    2627#include "messages.h"
     28#include "lib/util/util_tdb.h"
    2729
    2830#if 0
     
    4244static int verbose = 0;
    4345static int no_trans = 0;
    44 static char *db_name = (char *)discard_const(DEFAULT_DB_NAME);
     46static const char *db_name = DEFAULT_DB_NAME;
    4547
    4648
     
    5658        uint32_t *old_counters;
    5759
    58         printf("[%4u] Counters: ", getpid());
     60        printf("[%4u] Counters: ", (unsigned int)getpid());
    5961        old_counters = (uint32_t *)old_data.dptr;
    6062        for (i=0; i < old_data.dsize/sizeof(uint32_t); i++) {
     
    8890                if (counters[i] < old_counters[i]) {
    8991                        printf("[%4u] ERROR: counters has decreased for node %u  From %u to %u\n",
    90                                getpid(), i, old_counters[i], counters[i]);
     92                               (unsigned int)getpid(), i, old_counters[i], counters[i]);
    9193                        success = false;
    9294                        return false;
     
    129131        struct timeval start;
    130132
    131         key.dptr = (unsigned char *)discard_const("testkey");
    132         key.dsize = strlen((const char *)key.dptr)+1;
     133        key = string_term_tdb_data("testkey");
    133134
    134135        start = timeval_current();
     
    136137                struct db_record *rec;
    137138                TDB_DATA data;
     139                TDB_DATA value;
    138140                int ret;
    139141                NTSTATUS status;
     
    141143                if (!no_trans) {
    142144                        if (verbose) DEBUG(1, ("starting transaction\n"));
    143                         ret = db->transaction_start(db);
     145                        ret = dbwrap_transaction_start(db);
    144146                        if (ret != 0) {
    145147                                DEBUG(0, ("Failed to start transaction on node "
     
    152154
    153155                if (verbose) DEBUG(1, ("calling fetch_lock\n"));
    154                 rec = db->fetch_locked(db, tmp_ctx, key);
     156                rec = dbwrap_fetch_locked(db, tmp_ctx, key);
    155157                if (rec == NULL) {
    156158                        DEBUG(0, ("Failed to fetch record\n"));
     
    159161                if (verbose) DEBUG(1, ("fetched record ok\n"));
    160162                do_sleep(torture_delay);
    161 
    162                 data.dsize = MAX(rec->value.dsize, sizeof(uint32_t) * (pnn+1));
     163                value = dbwrap_record_get_value(rec);
     164
     165                data.dsize = MAX(value.dsize, sizeof(uint32_t) * (pnn+1));
    163166                data.dptr = (unsigned char *)talloc_zero_size(tmp_ctx,
    164167                                                              data.dsize);
     
    167170                        goto fail;
    168171                }
    169                 memcpy(data.dptr, rec->value.dptr,rec->value.dsize);
     172                memcpy(data.dptr, value.dptr, value.dsize);
    170173
    171174                counters = (uint32_t *)data.dptr;
     
    175178
    176179                if (verbose) DEBUG(1, ("storing data\n"));
    177                 status = rec->store(rec, data, TDB_REPLACE);
     180                status = dbwrap_record_store(rec, data, TDB_REPLACE);
    178181                if (!NT_STATUS_IS_OK(status)) {
    179182                        DEBUG(0, ("Failed to store record\n"));
    180183                        if (!no_trans) {
    181                                 ret = db->transaction_cancel(db);
     184                                ret = dbwrap_transaction_cancel(db);
    182185                                if (ret != 0) {
    183186                                        DEBUG(0, ("Error cancelling transaction.\n"));
     
    192195                if (!no_trans) {
    193196                        if (verbose) DEBUG(1, ("calling transaction_commit\n"));
    194                         ret = db->transaction_commit(db);
     197                        ret = dbwrap_transaction_commit(db);
    195198                        if (ret != 0) {
    196199                                DEBUG(0, ("Failed to commit transaction\n"));
     
    259262        }
    260263
    261         load_case_tables();
     264        smb_init_locale();
    262265
    263266        setup_logging(argv[0], DEBUG_STDERR);
     
    282285        }
    283286
    284         lp_load(get_dyn_CONFIGFILE(), true, false, false, true);
    285 
    286         ev_ctx = tevent_context_init(mem_ctx);
     287        lp_load_global(get_dyn_CONFIGFILE());
     288
     289        ev_ctx = samba_tevent_context_init(mem_ctx);
    287290        if (ev_ctx == NULL) {
    288291                d_fprintf(stderr, "ERROR: could not init event context\n");
     
    290293        }
    291294
    292         msg_ctx = messaging_init(mem_ctx, procid_self(), ev_ctx);
     295        msg_ctx = messaging_init(mem_ctx, ev_ctx);
    293296        if (msg_ctx == NULL) {
    294297                d_fprintf(stderr, "ERROR: could not init messaging context\n");
     
    306309        }
    307310
    308         db = db_open(mem_ctx, db_name, 0, tdb_flags,  O_RDWR | O_CREAT, 0644);
     311        db = db_open(mem_ctx, db_name, 0, tdb_flags,  O_RDWR | O_CREAT, 0644,
     312                     DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
    309313
    310314        if (db == NULL) {
  • vendor/current/source3/utils/eventlogadm.c

    r740 r988  
    2626#include "lib/eventlog/eventlog.h"
    2727#include "registry.h"
     28#include "registry/reg_api.h"
     29#include "registry/reg_init_basic.h"
     30#include "registry/reg_util_token.h"
    2831#include "registry/reg_backend_db.h"
    29 #include "registry/reg_objects.h"
    3032#include "../libcli/registry/util_reg.h"
    3133
     
    7981        const char **wrklist, **wp;
    8082        char *evtlogpath = NULL;
    81         struct regsubkey_ctr *subkeys;
    82         struct regval_ctr *values;
    83         struct regval_blob *rval;
    8483        int ii = 0;
    8584        bool already_in;
    8685        int i;
    8786        int numsources = 0;
    88         TALLOC_CTX *ctx = talloc_tos();
     87        TALLOC_CTX *ctx = talloc_stackframe();
    8988        WERROR werr;
    90         DATA_BLOB blob;
     89        struct registry_key *key_hive, *key_eventlog, *key_source;
     90        struct security_token *token = NULL;
     91        const char *hive_name, *relpath;
     92        enum winreg_CreateAction action;
     93        struct registry_value *value;
     94        static const uint32_t ACCESS = REG_KEY_READ | REG_KEY_WRITE;
     95        bool ret = false;
    9196
    9297        if (!elogs) {
    93                 return False;
     98                d_printf("No Eventlogs configured\n");
     99                goto done;
    94100        }
    95101
     
    102108                d_printf("Eventlog [%s] not found in list of valid event logs\n",
    103109                         eventlog);
    104                 return false;   /* invalid named passed in */
     110                goto done;
    105111        }
    106112
     
    110116        /* todo add to Sources */
    111117
    112         werr = regval_ctr_init(ctx, &values);
    113         if(!W_ERROR_IS_OK(werr)) {
    114                 d_printf("talloc() failure!\n");
    115                 return false;
    116         }
    117 
    118118        evtlogpath = talloc_asprintf(ctx, "%s\\%s", KEY_EVENTLOG, eventlog);
    119119        if (!evtlogpath) {
    120                 TALLOC_FREE(values);
    121                 return false;
    122         }
    123 
    124         regdb_fetch_values( evtlogpath, values );
    125 
    126 
    127         if ( !( rval = regval_ctr_getvalue( values, "Sources" ) ) ) {
    128                 d_printf("No Sources value for [%s]!\n", eventlog);
    129                 return False;
     120                d_printf("Out of memory\n");
     121                goto done;
     122        }
     123
     124        relpath = evtlogpath + sizeof(KEY_EVENTLOG);
     125        hive_name = talloc_strndup(ctx, evtlogpath, relpath - evtlogpath);
     126        if (!hive_name) {
     127                d_printf("Out of memory\n");
     128                goto done;
     129        }
     130        relpath++;
     131
     132        werr = ntstatus_to_werror(registry_create_admin_token(ctx, &token));
     133        if (!W_ERROR_IS_OK(werr)) {
     134                d_printf("Failed to create admin token: %s\n", win_errstr(werr));
     135                goto done;
     136        }
     137
     138        werr = reg_openhive(ctx, hive_name, ACCESS, token, &key_hive);
     139        if (!W_ERROR_IS_OK(werr)) {
     140                d_printf("Failed to open hive [%s]: %s\n", hive_name, win_errstr(werr));
     141                goto done;
     142        }
     143
     144        werr = reg_openkey(ctx, key_hive, relpath, ACCESS, &key_eventlog);
     145        if (!W_ERROR_IS_OK(werr)) {
     146                d_printf("Failed to open key [%s]: %s\n", evtlogpath, win_errstr(werr));
     147                goto done;
     148        }
     149
     150        werr = reg_queryvalue(ctx, key_eventlog, "Sources", &value);
     151        if (!W_ERROR_IS_OK(werr)) {
     152                d_printf("Failed to get value \"Sources\" for [%s]: %s\n", evtlogpath, win_errstr(werr));
     153                goto done;
    130154        }
    131155        /* perhaps this adding a new string to a multi_sz should be a fn? */
    132156        /* check to see if it's there already */
    133157
    134         if ( regval_type(rval) != REG_MULTI_SZ ) {
    135                 d_printf("Wrong type for Sources, should be REG_MULTI_SZ\n");
    136                 return False;
     158        if ( value->type != REG_MULTI_SZ ) {
     159                d_printf("Wrong type for \"Sources\", should be REG_MULTI_SZ\n");
     160                goto done;
    137161        }
    138162        /* convert to a 'regulah' chars to do some comparisons */
    139163
    140         already_in = False;
     164        already_in = false;
    141165        wrklist = NULL;
    142         dump_data(1, regval_data_p(rval), regval_size(rval));
    143 
    144         blob = data_blob_const(regval_data_p(rval), regval_size(rval));
    145         if (!pull_reg_multi_sz(talloc_tos(), &blob, &wrklist)) {
    146                 return false;
     166        dump_data(1, value->data.data, value->data.length);
     167
     168        if (!pull_reg_multi_sz(ctx, &value->data, &wrklist)) {
     169                d_printf("Failed to pull REG_MULTI_SZ from \"Sources\"\n");
     170                goto done;
    147171        }
    148172
     
    159183                                d_printf("Source name [%s] already in list for [%s] \n",
    160184                                         sourcename, eventlog);
    161                                 already_in = True;
     185                                already_in = true;
    162186                                break;
    163187                        }
     
    168192        }
    169193
    170         wp = wrklist;
    171 
    172194        if ( !already_in ) {
    173195                /* make a new list with an additional entry; copy values, add another */
    174                 wp = TALLOC_ARRAY(ctx, const char *, numsources + 2 );
    175 
     196                wp = talloc_realloc(ctx, wrklist, const char *, numsources + 2 );
    176197                if ( !wp ) {
    177                         d_printf("talloc() failed \n");
    178                         return False;
    179                 }
    180                 memcpy( wp, wrklist, sizeof( char * ) * numsources );
    181                 *( wp + numsources ) = ( char * ) sourcename;
    182                 *( wp + numsources + 1 ) = NULL;
    183                 if (!push_reg_multi_sz(ctx, &blob, wp)) {
    184                         return false;
    185                 }
    186                 dump_data( 1, blob.data, blob.length);
    187                 regval_ctr_addvalue( values, "Sources", REG_MULTI_SZ,
    188                                      blob.data, blob.length);
    189                 regdb_store_values( evtlogpath, values );
    190                 data_blob_free(&blob);
     198                        d_printf("Out of memory\n");
     199                        goto done;
     200                }
     201
     202                wp[numsources] = sourcename;
     203                wp[numsources+1] = NULL;
     204                if (!push_reg_multi_sz(ctx, &value->data, wp)) {
     205                        d_printf("Failed to push Sources\n");
     206                        goto done;
     207                }
     208                dump_data( 1, value->data.data, value->data.length);
     209                werr = reg_setvalue(key_eventlog,  "Sources", value);
     210                if (!W_ERROR_IS_OK(werr)) {
     211                        d_printf("Failed to set value Sources:  %s\n", win_errstr(werr));
     212                        goto done;
     213                }
    191214        } else {
    192215                d_printf("Source name [%s] found in existing list of sources\n",
    193216                         sourcename);
    194217        }
    195         TALLOC_FREE(values);
    196         TALLOC_FREE(wrklist);   /*  */
    197 
    198         werr = regsubkey_ctr_init(ctx, &subkeys);
    199         if (!W_ERROR_IS_OK(werr)) {
    200                 d_printf("talloc() failure!\n");
    201                 return False;
    202         }
    203         TALLOC_FREE(evtlogpath);
    204         evtlogpath = talloc_asprintf(ctx, "%s\\%s", KEY_EVENTLOG, eventlog );
    205         if (!evtlogpath) {
    206                 TALLOC_FREE(subkeys);
    207                 return false;
    208         }
    209 
    210         regdb_fetch_keys( evtlogpath, subkeys );
    211 
    212         if ( !regsubkey_ctr_key_exists( subkeys, sourcename ) ) {
     218
     219        werr = reg_createkey(ctx, key_eventlog, sourcename, ACCESS, &key_source, &action);
     220        if (!W_ERROR_IS_OK(werr)) {
     221                d_printf("Failed to create subkey \"%s\" of \"%s\": %s\n", sourcename, evtlogpath, win_errstr(werr));
     222                goto done;
     223        }
     224
     225        if (action == REG_CREATED_NEW_KEY) {
    213226                d_printf(" Source name [%s] for eventlog [%s] didn't exist, adding \n",
    214227                         sourcename, eventlog);
    215                 regsubkey_ctr_addkey( subkeys, sourcename );
    216                 if ( !regdb_store_keys( evtlogpath, subkeys ) )
    217                         return False;
    218         }
    219         TALLOC_FREE(subkeys);
     228        }
    220229
    221230        /* at this point KEY_EVENTLOG/<eventlog>/<sourcename> key is in there. Now need to add EventMessageFile */
    222231
    223         /* now allocate room for the source's subkeys */
    224 
    225         werr = regsubkey_ctr_init(ctx, &subkeys);
    226         if (!W_ERROR_IS_OK(werr)) {
    227                 d_printf("talloc() failure!\n");
    228                 return False;
    229         }
    230         TALLOC_FREE(evtlogpath);
    231         evtlogpath = talloc_asprintf(ctx, "%s\\%s\\%s",
    232                   KEY_EVENTLOG, eventlog, sourcename);
    233         if (!evtlogpath) {
    234                 TALLOC_FREE(subkeys);
    235                 return false;
    236         }
    237 
    238         regdb_fetch_keys( evtlogpath, subkeys );
    239 
    240232        /* now add the values to the KEY_EVENTLOG/Application form key */
    241         werr = regval_ctr_init(ctx, &values);
    242         if (!W_ERROR_IS_OK(werr)) {
    243                 d_printf("talloc() failure!\n");
    244                 return False;
    245         }
    246233        d_printf("Storing EventMessageFile [%s] to eventlog path of [%s]\n",
    247234                 messagefile, evtlogpath);
    248235
    249         regdb_fetch_values( evtlogpath, values );
    250 
    251         regval_ctr_addvalue_sz(values, "EventMessageFile", messagefile);
    252         regdb_store_values( evtlogpath, values );
    253 
    254         TALLOC_FREE(values);
    255 
    256         return True;
     236        if (!push_reg_sz(ctx, &value->data, messagefile)) {
     237                d_printf("Failed to push \"EventMessageFile\"\n");
     238                goto done;
     239        }
     240        value->type = REG_SZ;
     241
     242        werr = reg_setvalue(key_source, "EventMessageFile", value);
     243        if (!W_ERROR_IS_OK(werr)) {
     244                d_printf("Failed to set value \"EventMessageFile\":  %s\n", win_errstr(werr));
     245                return false;
     246        }
     247        ret = true;
     248done:
     249        talloc_free(ctx);
     250        return ret;
    257251}
    258252
    259253static int DoAddSourceCommand( int argc, char **argv, bool debugflag, char *exename )
    260254{
     255        WERROR werr;
    261256
    262257        if ( argc < 3 ) {
     
    265260                return -1;
    266261        }
     262
    267263        /* must open the registry before we access it */
    268         if (!W_ERROR_IS_OK(regdb_init())) {
    269                 printf( "Can't open the registry.\n" );
    270                 return -1;
    271         }
    272 
    273         if ( !eventlog_add_source( argv[0], argv[1], argv[2] ) )
     264        werr = registry_init_common();
     265        if (!W_ERROR_IS_OK(werr)) {
     266                printf("Can't open the registry: %s.\n", win_errstr(werr));
     267                return -1;
     268        }
     269        werr = regdb_transaction_start();
     270        if (!W_ERROR_IS_OK(werr)) {
     271                printf("Can't start transaction on registry: %s.\n", win_errstr(werr));
     272                return -1;
     273        }
     274
     275        if ( !eventlog_add_source( argv[0], argv[1], argv[2] ) ) {
     276                regdb_transaction_cancel();
    274277                return -2;
     278        }
     279        werr = regdb_transaction_commit();
     280        if (!W_ERROR_IS_OK(werr)) {
     281                printf("Failed to commit transaction on registry: %s.\n", win_errstr(werr));
     282                return -1;
     283        }
    275284        return 0;
    276285}
     
    366375        ELOG_TDB *etdb;
    367376        TALLOC_CTX *mem_ctx = talloc_tos();
    368         const char *tdb_filename;
    369377        uint32_t count = 1;
    370378
     
    372380                return -1;
    373381        }
    374 
    375         tdb_filename = argv[0];
    376382
    377383        if (argc > 1) {
     
    422428        fstring opname;
    423429
    424         load_case_tables();
     430        smb_init_locale();
    425431
    426432        opt_debug = 0;          /* todo set this from getopts */
     
    468474
    469475        if ( configfile == NULL ) {
    470                 lp_load(get_dyn_CONFIGFILE(), True, False, False, True);
    471         } else if (!lp_load(configfile, True, False, False, True)) {
     476                lp_load_global(get_dyn_CONFIGFILE());
     477        } else if (!lp_load_global(configfile)) {
    472478                printf("Unable to parse configfile '%s'\n",configfile);
    473479                exit( 1 );
     
    476482        /*  note that the separate command types should call usage if they need to... */
    477483        while ( 1 ) {
    478                 if ( !StrCaseCmp( opname, "addsource" ) ) {
     484                if ( !strcasecmp_m( opname, "addsource" ) ) {
    479485                        rc = DoAddSourceCommand( argc, argv, opt_debug,
    480486                                                 exename );
    481487                        break;
    482488                }
    483                 if ( !StrCaseCmp( opname, "write" ) ) {
     489                if ( !strcasecmp_m( opname, "write" ) ) {
    484490                        rc = DoWriteCommand( argc, argv, opt_debug, exename );
    485491                        break;
    486492                }
    487                 if ( !StrCaseCmp( opname, "dump" ) ) {
     493                if ( !strcasecmp_m( opname, "dump" ) ) {
    488494                        rc = DoDumpCommand( argc, argv, opt_debug, exename );
    489495                        break;
  • vendor/current/source3/utils/log2pcaphex.c

    r740 r988  
    1 /* 
     1/*
    22   Unix SMB/CIFS implementation.
    33   Utility to extract pcap files from samba (log level 10) log files
     
    7575/* tcpdump file format */
    7676struct tcpdump_file_header {
    77         uint32 magic;
    78         uint16 major;
    79         uint16 minor;
    80         int32 zone;
    81         uint32 sigfigs;
    82         uint32 snaplen;
    83         uint32 linktype;
     77        uint32_t magic;
     78        uint16_t major;
     79        uint16_t minor;
     80        int32_t zone;
     81        uint32_t sigfigs;
     82        uint32_t snaplen;
     83        uint32_t linktype;
    8484};
    8585
    8686struct tcpdump_packet {
    8787        struct timeval ts;
    88         uint32 caplen;
    89         uint32 len;
     88        uint32_t caplen;
     89        uint32_t len;
    9090};
    9191
    9292typedef struct {
    93     uint8  ver_hdrlen;
    94     uint8  dscp;
    95     uint16 packet_length;
    96     uint16 identification;
    97     uint8  flags;
    98     uint8  fragment;
    99     uint8  ttl;
    100     uint8  protocol;
    101     uint16 hdr_checksum;
    102     uint32 src_addr;
    103     uint32 dest_addr;
     93    uint8_t  ver_hdrlen;
     94    uint8_t  dscp;
     95    uint16_t packet_length;
     96    uint16_t identification;
     97    uint8_t  flags;
     98    uint8_t  fragment;
     99    uint8_t  ttl;
     100    uint8_t  protocol;
     101    uint16_t hdr_checksum;
     102    uint32_t src_addr;
     103    uint32_t dest_addr;
    104104} hdr_ip_t;
    105105
     
    107107
    108108typedef struct {
    109     uint16 source_port;
    110     uint16 dest_port;
    111     uint32 seq_num;
    112     uint32 ack_num;
    113     uint8  hdr_length;
    114     uint8  flags;
    115     uint16 window;
    116     uint16 checksum;
    117     uint16 urg;
     109    uint16_t source_port;
     110    uint16_t dest_port;
     111    uint32_t seq_num;
     112    uint32_t ack_num;
     113    uint8_t  hdr_length;
     114    uint8_t  flags;
     115    uint16_t window;
     116    uint16_t checksum;
     117    uint16_t urg;
    118118} hdr_tcp_t;
    119119
     
    155155                        fprintf(out, "%02x ", data[i]);
    156156                }
    157        
    158157                cur = i;
    159158                fprintf(out, "\n");
     
    163162static void print_netbios_packet(FILE *out, unsigned char *data, long length,
    164163                                 long actual_length)
    165 {       
     164{
    166165        unsigned char *newdata; long offset = 0;
    167166        long newlen;
    168        
     167
    169168        newlen = length+sizeof(HDR_IP)+sizeof(HDR_TCP);
    170169        newdata = (unsigned char *)malloc(newlen);
     
    177176        memcpy(newdata+offset, &HDR_TCP, sizeof(HDR_TCP));offset+=sizeof(HDR_TCP);
    178177        memcpy(newdata+offset,data,length);
    179        
     178
    180179        print_pcap_packet(out, newdata, newlen, actual_length+offset);
    181180        free(newdata);
     
    297296}
    298297
    299 int main (int argc, char **argv)
     298int main(int argc, const char **argv)
    300299{
    301300        const char *infile, *outfile;
     
    313312                POPT_TABLEEND
    314313        };
    315        
    316         pc = poptGetContext(NULL, argc, (const char **) argv, long_options,
     314
     315        pc = poptGetContext(NULL, argc, argv, long_options,
    317316                            POPT_CONTEXT_KEEP_FIRST);
    318317        poptSetOtherOptionHelp(pc, "[<infile> [<outfile>]]");
    319        
    320        
     318
     319
    321320        while((opt = poptGetNextOpt(pc)) != -1) {
    322321                switch (opt) {
     
    335334                }
    336335        } else in = stdin;
    337        
     336
    338337        outfile = poptGetArg(pc);
    339338
    340339        if(outfile) {
    341340                out = fopen(outfile, "w+");
    342                 if(!out) { 
    343                         perror("fopen"); 
     341                if(!out) {
     342                        perror("fopen");
    344343                        fprintf(stderr, "Can't find %s, using stdout...\n", outfile);
    345344                        return 1;
     
    360359                        } else if(in_packet && strstr(buffer, "dump_data")) {
    361360                                data_bytes_read = read_log_data(in, curpacket+data_offset, data_length);
    362                         }  else { 
    363                                 if(in_packet){ 
    364                                         if(hexformat) print_hex_packet(out, curpacket, curpacket_len); 
     361                        }  else {
     362                                if(in_packet){
     363                                        if(hexformat) print_hex_packet(out, curpacket, curpacket_len);
    365364                                        else print_netbios_packet(out, curpacket, curpacket_len, data_bytes_read+data_offset);
    366                                         free(curpacket); 
     365                                        free(curpacket);
    367366                                }
    368367                                in_packet = 0;
    369368                        }
    370                 } 
     369                }
    371370        }
    372371
  • vendor/current/source3/utils/net.c

    r740 r988  
    106106
    107107                trust_pw = get_pass(_("Enter machine password: "), c->opt_stdin);
     108                if (trust_pw == NULL) {
     109                            d_fprintf(stderr,
     110                                      _("Error in reading machine password\n"));
     111                            return 1;
     112                }
    108113
    109114                if (!secrets_store_machine_password(trust_pw, lp_workgroup(), sec_channel_type)) {
     
    244249        }
    245250        else {
    246                 name = global_myname();
     251                name = lp_netbios_name();
    247252        }
    248253
    249254        if(!initialize_password_db(false, NULL)) {
    250                 DEBUG(0, ("WARNING: Could not open passdb - local sid may not reflect passdb\n"
    251                           "backend knowledge (such as the sid stored in LDAP)\n"));
     255                d_fprintf(stderr, _("WARNING: Could not open passdb\n"));
     256                return 1;
    252257        }
    253258
     
    287292        }
    288293
    289         if (!secrets_store_domain_sid(global_myname(), &sid)) {
     294        if (!secrets_store_domain_sid(lp_netbios_name(), &sid)) {
    290295                DEBUG(0,("Can't store domain SID as a pdc/bdc.\n"));
    291296                return 1;
     
    328333
    329334        if(!initialize_password_db(false, NULL)) {
    330                 DEBUG(0, ("WARNING: Could not open passdb - domain SID may "
    331                           "not reflect passdb\n"
    332                           "backend knowledge (such as the SID stored in "
    333                           "LDAP)\n"));
     335                d_fprintf(stderr, _("WARNING: Could not open passdb\n"));
     336                return 1;
    334337        }
    335338
     
    347350        get_global_sam_sid();
    348351
    349         if (!secrets_fetch_domain_sid(global_myname(), &domain_sid)) {
    350                 d_fprintf(stderr, _("Could not fetch local SID\n"));
    351                 return 1;
    352         }
    353         sid_to_fstring(sid_str, &domain_sid);
    354         d_printf(_("SID for local machine %s is: %s\n"),
    355                  global_myname(), sid_str);
    356 
     352        if (!IS_DC) {
     353                if (!secrets_fetch_domain_sid(lp_netbios_name(), &domain_sid)) {
     354                        d_fprintf(stderr, _("Could not fetch local SID\n"));
     355                        return 1;
     356                }
     357                sid_to_fstring(sid_str, &domain_sid);
     358                d_printf(_("SID for local machine %s is: %s\n"),
     359                         lp_netbios_name(), sid_str);
     360        }
    357361        if (!secrets_fetch_domain_sid(c->opt_workgroup, &domain_sid)) {
    358362                d_fprintf(stderr, _("Could not fetch domain SID\n"));
     
    367371
    368372static bool search_maxrid(struct pdb_search *search, const char *type,
    369                           uint32 *max_rid)
     373                          uint32_t *max_rid)
    370374{
    371375        struct samr_displayentry *entries;
    372         uint32 i, num_entries;
     376        uint32_t i, num_entries;
    373377
    374378        if (search == NULL) {
     
    384388}
    385389
    386 static uint32 get_maxrid(void)
    387 {
    388         uint32 max_rid = 0;
     390static uint32_t get_maxrid(void)
     391{
     392        uint32_t max_rid = 0;
    389393
    390394        if (!search_maxrid(pdb_search_users(talloc_tos(), 0), "users", &max_rid))
     
    404408static int net_maxrid(struct net_context *c, int argc, const char **argv)
    405409{
    406         uint32 rid;
     410        uint32_t rid;
    407411
    408412        if (argc != 0) {
     
    740744        },
    741745
     746        {       "notify",
     747                net_notify,
     748                NET_TRANSPORT_LOCAL,
     749                N_("notifyd client code"),
     750                N_("  Use 'net help notify' to get more information about "
     751                   "'net notify' commands.")
     752        },
     753
    742754#ifdef WITH_FAKE_KASERVER
    743755        {       "afs",
     
    764776  main program
    765777****************************************************************************/
    766  int main(int argc, const char **argv)
     778 int main(int argc, char **argv)
    767779{
    768780        int opt,i;
     
    771783        int argc_new = 0;
    772784        const char ** argv_new;
     785        const char **argv_const = discard_const_p(const char *, argv);
    773786        poptContext pc;
    774787        TALLOC_CTX *frame = talloc_stackframe();
     
    783796                {"myname",      'n', POPT_ARG_STRING, &c->opt_requester_name},
    784797                {"server",      'S', POPT_ARG_STRING, &c->opt_host},
    785                 {"encrypt",     'e', POPT_ARG_NONE,   NULL, 'e', N_("Encrypt SMB transport (UNIX extended servers only)") },
     798                {"encrypt",     'e', POPT_ARG_NONE,   NULL, 'e', N_("Encrypt SMB transport") },
    786799                {"container",   'c', POPT_ARG_STRING, &c->opt_container},
    787800                {"comment",     'C', POPT_ARG_STRING, &c->opt_comment},
     
    821834                {"auto", 'a', POPT_ARG_NONE,   &c->opt_auto},
    822835                {"repair", 0, POPT_ARG_NONE,   &c->opt_repair},
     836                /* Options for 'net registry check'*/
     837                {"reg-version", 0, POPT_ARG_INT, &c->opt_reg_version},
     838                {"output", 'o', POPT_ARG_STRING, &c->opt_output},
     839                {"wipe", 0, POPT_ARG_NONE, &c->opt_wipe},
     840                /* Options for 'net registry import' */
     841                {"precheck", 0, POPT_ARG_STRING, &c->opt_precheck},
     842                /* Options for 'net ads join' */
     843                {"no-dns-updates", 0, POPT_ARG_NONE, &c->opt_no_dns_updates},
    823844                POPT_COMMON_SAMBA
    824845                { 0, 0, 0, 0}
     
    829850        setup_logging(argv[0], DEBUG_STDERR);
    830851
    831         load_case_tables();
     852        smb_init_locale();
    832853
    833854        setlocale(LC_ALL, "");
     
    843864        c->private_data = net_func;
    844865
    845         pc = poptGetContext(NULL, argc, (const char **) argv, long_options,
     866        pc = poptGetContext(NULL, argc, argv_const, long_options,
    846867                            POPT_CONTEXT_KEEP_FIRST);
    847868
     
    864885                case 'U':
    865886                        c->opt_user_specified = true;
    866                         c->opt_user_name = SMB_STRDUP(c->opt_user_name);
     887                        c->opt_user_name = talloc_strdup(c, c->opt_user_name);
    867888                        p = strchr(c->opt_user_name,'%');
    868889                        if (p) {
     
    874895                        d_fprintf(stderr, _("\nInvalid option %s: %s\n"),
    875896                                 poptBadOption(pc, 0), poptStrerror(opt));
    876                         net_help(c, argc, argv);
     897                        net_help(c, argc, argv_const);
    877898                        exit(1);
    878899                }
    879900        }
    880901
    881         lp_load(get_dyn_CONFIGFILE(), true, false, false, true);
     902        if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
     903                d_fprintf(stderr, "Can't load %s - run testparm to debug it\n",
     904                          get_dyn_CONFIGFILE());
     905                exit(1);
     906        }
     907
     908        /*
     909         * Failing to init the msg_ctx isn't a fatal error. Only root-level
     910         * things (joining/leaving domains etc.) will be denied.
     911         */
     912        c->msg_ctx = messaging_init(c, samba_tevent_context_init(c));
     913
     914        if (!lp_load_global(get_dyn_CONFIGFILE())) {
     915                d_fprintf(stderr, "Can't load %s - run testparm to debug it\n",
     916                          get_dyn_CONFIGFILE());
     917                exit(1);
     918        }
     919
     920#if defined(HAVE_BIND_TEXTDOMAIN_CODESET)
     921        /* Bind our gettext results to 'unix charset'
     922           
     923           This ensures that the translations and any embedded strings are in the
     924           same charset.  It won't be the one from the user's locale (we no
     925           longer auto-detect that), but it will be self-consistent.
     926        */
     927        bind_textdomain_codeset(MODULE_NAME, lp_unix_charset());
     928#endif
    882929
    883930        argv_new = (const char **)poptGetArgs(pc);
     
    896943
    897944        if (c->opt_requester_name) {
    898                 set_global_myname(c->opt_requester_name);
     945                lp_set_cmdline("netbios name", c->opt_requester_name);
    899946        }
    900947
     
    904951
    905952        if (!c->opt_workgroup) {
    906                 c->opt_workgroup = smb_xstrdup(lp_workgroup());
     953                c->opt_workgroup = talloc_strdup(c, lp_workgroup());
    907954        }
    908955
    909956        if (!c->opt_target_workgroup) {
    910                 c->opt_target_workgroup = smb_xstrdup(lp_workgroup());
     957                c->opt_target_workgroup = talloc_strdup(c, lp_workgroup());
    911958        }
    912959
     
    931978        }
    932979
    933         /* Failing to init the msg_ctx isn't a fatal error. Only
    934            root-level things (joining/leaving domains etc.) will be denied. */
    935 
    936         c->msg_ctx = messaging_init(c, procid_self(),
    937                                     event_context_init(c));
     980        popt_burn_cmdline_password(argc, argv);
    938981
    939982        rc = net_run_function(c, argc_new-1, argv_new+1, "net", net_func);
  • vendor/current/source3/utils/net.h

    r740 r988  
    8181        int opt_auto;
    8282        int opt_repair;
     83        int opt_reg_version;
     84        const char *opt_output;
     85        int opt_wipe;
     86        const char *opt_precheck;
     87        int opt_no_dns_updates;
    8388
    8489        int opt_have_ip;
     
    8792        struct libnetapi_ctx *netapi_ctx;
    8893        struct messaging_context *msg_ctx;
     94        struct netlogon_creds_cli_context *netlogon_creds;
    8995
    9096        bool display_usage;
     
    129135        struct cli_state *cli_share_dst;
    130136        char *cwd;
    131         uint16 attribute;
     137        uint16_t attribute;
    132138        struct net_context *c;
    133139}copy_clistate;
     
    150156                                  TALLOC_CTX *mem_ctx,
    151157                                  struct rpc_sh_ctx *ctx);
    152         const struct ndr_syntax_id *interface;
     158        const struct ndr_interface_table *table;
    153159        NTSTATUS (*fn)(struct net_context *c, TALLOC_CTX *mem_ctx,
    154160                       struct rpc_sh_ctx *ctx,
     
    179185#define NET_FLAGS_SEAL                          0x00000080      /* seal RPC connection */
    180186#define NET_FLAGS_TCP                           0x00000100      /* use ncacn_ip_tcp */
     187#define NET_FLAGS_EXPECT_FALLBACK               0x00000200      /* the caller will fallback */
    181188
    182189/* net share operation modes */
  • vendor/current/source3/utils/net_ads.c

    r860 r988  
    2929#include "ads.h"
    3030#include "libads/cldap.h"
    31 #include "libads/dns.h"
     31#include "../lib/addns/dnsquery.h"
    3232#include "../libds/common/flags.h"
    3333#include "librpc/gen_ndr/libnet_join.h"
     
    3838#include "../libcli/security/security.h"
    3939#include "libsmb/libsmb.h"
     40#include "lib/param/loadparm.h"
    4041#include "utils/net_dns.h"
    4142
     
    6364
    6465        print_sockaddr(addr, sizeof(addr), &ads->ldap.ss);
    65         if ( !ads_cldap_netlogon_5(talloc_tos(), addr, ads->server.realm, &reply ) ) {
     66
     67        if ( !ads_cldap_netlogon_5(talloc_tos(), &ads->ldap.ss, ads->server.realm, &reply ) ) {
    6668                d_fprintf(stderr, _("CLDAP query failed!\n"));
    6769                return -1;
     
    98100                   "\tIs a non-domain NC serviced by LDAP server: %s\n"
    99101                   "\tIs NT6 DC that has some secrets:            %s\n"
    100                    "\tIs NT6 DC that has all secrets:             %s\n"),
     102                   "\tIs NT6 DC that has all secrets:             %s\n"
     103                   "\tRuns Active Directory Web Services:         %s\n"
     104                   "\tRuns on Windows 2012 or later:              %s\n"),
    101105                   (reply.server_type & NBT_SERVER_PDC) ? _("yes") : _("no"),
    102106                   (reply.server_type & NBT_SERVER_GC) ? _("yes") : _("no"),
     
    110114                   (reply.server_type & NBT_SERVER_NDNC) ? _("yes") : _("no"),
    111115                   (reply.server_type & NBT_SERVER_SELECT_SECRET_DOMAIN_6) ? _("yes") : _("no"),
    112                    (reply.server_type & NBT_SERVER_FULL_SECRET_DOMAIN_6) ? _("yes") : _("no"));
     116                   (reply.server_type & NBT_SERVER_FULL_SECRET_DOMAIN_6) ? _("yes") : _("no"),
     117                   (reply.server_type & NBT_SERVER_ADS_WEB_SERVICE) ? _("yes") : _("no"),
     118                   (reply.server_type & NBT_SERVER_DS_8) ? _("yes") : _("no"));
    113119
    114120
     
    157163
    158164        if (!ads->config.realm) {
    159                 ads->config.realm = CONST_DISCARD(char *, c->opt_target_workgroup);
     165                ads->config.realm = discard_const_p(char, c->opt_target_workgroup);
    160166                ads->ldap.port = 389;
    161167        }
     
    172178        ADS_STRUCT *ads;
    173179        char addr[INET6_ADDRSTRLEN];
     180        time_t pass_time;
    174181
    175182        if (c->display_usage) {
     
    201208        }
    202209
     210        pass_time = secrets_fetch_pass_last_set_time(ads->server.workgroup);
     211
    203212        print_sockaddr(addr, sizeof(addr), &ads->ldap.ss);
    204213
     
    214223        d_printf(_("Server time offset: %d\n"), ads->auth.time_offset );
    215224
     225        d_printf(_("Last machine account password change: %s\n"),
     226                 http_timestring(talloc_tos(), pass_time));
     227
    216228        ads_destroy(&ads);
    217229        return 0;
     
    225237
    226238static ADS_STATUS ads_startup_int(struct net_context *c, bool only_own_domain,
    227                                   uint32 auth_flags, ADS_STRUCT **ads_ret)
     239                                  uint32_t auth_flags, ADS_STRUCT **ads_ret)
    228240{
    229241        ADS_STRUCT *ads = NULL;
     
    287299                SAFE_FREE(ads->auth.realm);
    288300                ads->auth.realm = smb_xstrdup(cp);
    289                 strupper_m(ads->auth.realm);
     301                if (!strupper_m(ads->auth.realm)) {
     302                        ads_destroy(&ads);
     303                        return ADS_ERROR(LDAP_NO_MEMORY);
     304                }
    290305       }
    291306
     
    386401{
    387402        ADS_STRUCT *ads;
    388         char addr[INET6_ADDRSTRLEN];
    389403        struct NETLOGON_SAM_LOGON_RESPONSE_EX reply;
    390404
     
    404418
    405419        if (!ads->config.realm) {
    406                 ads->config.realm = CONST_DISCARD(char *, c->opt_target_workgroup);
     420                ads->config.realm = discard_const_p(char, c->opt_target_workgroup);
    407421                ads->ldap.port = 389;
    408422        }
    409423
    410         print_sockaddr(addr, sizeof(addr), &ads->ldap.ss);
    411         if ( !ads_cldap_netlogon_5(talloc_tos(), addr, ads->server.realm, &reply ) ) {
     424        if ( !ads_cldap_netlogon_5(talloc_tos(), &ads->ldap.ss, ads->server.realm, &reply ) ) {
    412425                d_fprintf(stderr, _("CLDAP query failed!\n"));
    413426                ads_destroy(&ads);
     
    444457        if (!values) /* must be new field, indicate string field */
    445458                return true;
    446         if (StrCaseCmp(field, "sAMAccountName") == 0) {
     459        if (strcasecmp_m(field, "sAMAccountName") == 0) {
    447460                disp_fields[0] = SMB_STRDUP((char *) values[0]);
    448461        }
    449         if (StrCaseCmp(field, "description") == 0)
     462        if (strcasecmp_m(field, "description") == 0)
    450463                disp_fields[1] = SMB_STRDUP((char *) values[0]);
    451464        return true;
     
    918931        }
    919932
    920         rc = ads_find_machine_acct(ads, &res, global_myname());
     933        rc = ads_find_machine_acct(ads, &res, lp_netbios_name());
    921934        if (!ADS_ERR_OK(rc)) {
    922935                d_fprintf(stderr, _("ads_find_machine_acct: %s\n"), ads_errstr(rc));
     
    926939
    927940        if (ads_count_replies(ads, res) == 0) {
    928                 d_fprintf(stderr, _("No machine account for '%s' found\n"), global_myname());
     941                d_fprintf(stderr, _("No machine account for '%s' found\n"), lp_netbios_name());
    929942                ads_destroy(&ads);
    930943                return -1;
     
    10211034        }
    10221035
    1023         /* Based on what we requseted, we shouldn't get here, but if
     1036        /* Based on what we requested, we shouldn't get here, but if
    10241037           we did, it means the secrets were removed, and therefore
    10251038           we have left the domain */
     
    11031116        }
    11041117
    1105         if (strlen(global_myname()) > 15) {
     1118        if (strlen(lp_netbios_name()) > 15) {
    11061119                d_printf(_("Our netbios name can be at most 15 chars long, "
    1107                            "\"%s\" is %u chars long\n"), global_myname(),
    1108                          (unsigned int)strlen(global_myname()));
     1120                           "\"%s\" is %u chars long\n"), lp_netbios_name(),
     1121                         (unsigned int)strlen(lp_netbios_name()));
    11091122                return WERR_INVALID_COMPUTERNAME;
    11101123        }
     
    11481161        dnsdomain++;
    11491162
    1150         status = ads_dns_lookup_ns( ctx, dnsdomain, &nameservers, &ns_count );
     1163        status = ads_dns_lookup_ns(ctx,
     1164                                   dnsdomain,
     1165                                   &nameservers,
     1166                                   &ns_count);
    11511167        if ( !NT_STATUS_IS_OK(status) || (ns_count == 0)) {
    11521168                /* Child domains often do not have NS records.  Look
     
    11861202                /* try again for NS servers */
    11871203
    1188                 status = ads_dns_lookup_ns( ctx, root_domain, &nameservers, &ns_count );
     1204                status = ads_dns_lookup_ns(ctx,
     1205                                           root_domain,
     1206                                           &nameservers,
     1207                                           &ns_count);
    11891208
    11901209                if ( !NT_STATUS_IS_OK(status) || (ns_count == 0)) {
     
    12581277                fstrcpy(machine_name, hostname);
    12591278        } else {
    1260                 name_to_fqdn( machine_name, global_myname() );
    1261         }
    1262         strlower_m( machine_name );
     1279                name_to_fqdn( machine_name, lp_netbios_name() );
     1280        }
     1281        if (!strlower_m( machine_name )) {
     1282                return NT_STATUS_INVALID_PARAMETER;
     1283        }
    12631284
    12641285        if (num_addrs == 0 || iplist == NULL) {
     
    12981319static int net_ads_join_usage(struct net_context *c, int argc, const char **argv)
    12991320{
    1300         d_printf(_("net ads join [options]\n"
     1321        d_printf(_("net ads join [--no-dns-updates] [options]\n"
    13011322                   "Valid options:\n"));
    1302         d_printf(_("   createupn[=UPN]    Set the userPrincipalName attribute during the join.\n"
    1303                    "                      The deault UPN is in the form host/netbiosname@REALM.\n"));
    1304         d_printf(_("   createcomputer=OU  Precreate the computer account in a specific OU.\n"
    1305                    "                      The OU string read from top to bottom without RDNs and delimited by a '/'.\n"
    1306                    "                      E.g. \"createcomputer=Computers/Servers/Unix\"\n"
    1307                    "                      NB: A backslash '\\' is used as escape at multiple levels and may\n"
    1308                    "                          need to be doubled or even quadrupled.  It is not used as a separator.\n"));
    1309         d_printf(_("   osName=string      Set the operatingSystem attribute during the join.\n"));
    1310         d_printf(_("   osVer=string       Set the operatingSystemVersion attribute during the join.\n"
    1311                    "                      NB: osName and osVer must be specified together for either to take effect.\n"
    1312                    "                          Also, the operatingSystemService attribute is also set when along with\n"
    1313                    "                          the two other attributes.\n"));
    1314 
     1323        d_printf(_("   createupn[=UPN]       Set the userPrincipalName attribute during the join.\n"
     1324                   "                         The default UPN is in the form host/netbiosname@REALM.\n"));
     1325        d_printf(_("   createcomputer=OU     Precreate the computer account in a specific OU.\n"
     1326                   "                         The OU string read from top to bottom without RDNs\n"
     1327                   "                         and delimited by a '/'.\n"
     1328                   "                         E.g. \"createcomputer=Computers/Servers/Unix\"\n"
     1329                   "                         NB: A backslash '\\' is used as escape at multiple\n"
     1330                   "                             levels and may need to be doubled or even\n"
     1331                   "                             quadrupled. It is not used as a separator.\n"));
     1332        d_printf(_("   machinepass=PASS      Set the machine password to a specific value during\n"
     1333                   "                         the join. The default password is random.\n"));
     1334        d_printf(_("   osName=string         Set the operatingSystem attribute during the join.\n"));
     1335        d_printf(_("   osVer=string          Set the operatingSystemVersion attribute during join.\n"
     1336                   "                         NB: osName and osVer must be specified together for\n"
     1337                   "                             either to take effect. The operatingSystemService\n"
     1338                   "                             attribute is then also set along with the two\n"
     1339                   "                             other attributes.\n"));
     1340        d_printf(_("   osServicePack=string  Set the operatingSystemServicePack attribute\n"
     1341                   "                         during the join.\n"
     1342                   "                         NB: If not specified then by default the samba\n"
     1343                   "                             version string is used instead.\n"));
    13151344        return -1;
    13161345}
    13171346
    1318 /*******************************************************************
    1319  ********************************************************************/
    1320 
    1321 int net_ads_join(struct net_context *c, int argc, const char **argv)
    1322 {
    1323         TALLOC_CTX *ctx = NULL;
    1324         struct libnet_JoinCtx *r = NULL;
    1325         const char *domain = lp_realm();
    1326         WERROR werr = WERR_SETUP_NOT_JOINED;
    1327         bool createupn = false;
    1328         const char *machineupn = NULL;
    1329         const char *create_in_ou = NULL;
    1330         int i;
    1331         const char *os_name = NULL;
    1332         const char *os_version = NULL;
    1333         bool modify_config = lp_config_backend_is_registry();
    1334 
    1335         if (c->display_usage)
    1336                 return net_ads_join_usage(c, argc, argv);
    1337 
    1338         if (!modify_config) {
    1339 
    1340                 werr = check_ads_config();
    1341                 if (!W_ERROR_IS_OK(werr)) {
    1342                         d_fprintf(stderr, _("Invalid configuration.  Exiting....\n"));
    1343                         goto fail;
    1344                 }
    1345         }
    1346 
    1347         if (!(ctx = talloc_init("net_ads_join"))) {
    1348                 d_fprintf(stderr, _("Could not initialise talloc context.\n"));
    1349                 werr = WERR_NOMEM;
    1350                 goto fail;
    1351         }
    1352 
    1353         if (!c->opt_kerberos) {
    1354                 use_in_memory_ccache();
    1355         }
    1356 
    1357         werr = libnet_init_JoinCtx(ctx, &r);
    1358         if (!W_ERROR_IS_OK(werr)) {
    1359                 goto fail;
    1360         }
    1361 
    1362         /* process additional command line args */
    1363 
    1364         for ( i=0; i<argc; i++ ) {
    1365                 if ( !StrnCaseCmp(argv[i], "createupn", strlen("createupn")) ) {
    1366                         createupn = true;
    1367                         machineupn = get_string_param(argv[i]);
    1368                 }
    1369                 else if ( !StrnCaseCmp(argv[i], "createcomputer", strlen("createcomputer")) ) {
    1370                         if ( (create_in_ou = get_string_param(argv[i])) == NULL ) {
    1371                                 d_fprintf(stderr, _("Please supply a valid OU path.\n"));
    1372                                 werr = WERR_INVALID_PARAM;
    1373                                 goto fail;
    1374                         }
    1375                 }
    1376                 else if ( !StrnCaseCmp(argv[i], "osName", strlen("osName")) ) {
    1377                         if ( (os_name = get_string_param(argv[i])) == NULL ) {
    1378                                 d_fprintf(stderr, _("Please supply a operating system name.\n"));
    1379                                 werr = WERR_INVALID_PARAM;
    1380                                 goto fail;
    1381                         }
    1382                 }
    1383                 else if ( !StrnCaseCmp(argv[i], "osVer", strlen("osVer")) ) {
    1384                         if ( (os_version = get_string_param(argv[i])) == NULL ) {
    1385                                 d_fprintf(stderr, _("Please supply a valid operating system version.\n"));
    1386                                 werr = WERR_INVALID_PARAM;
    1387                                 goto fail;
    1388                         }
    1389                 }
    1390                 else {
    1391                         domain = argv[i];
    1392                 }
    1393         }
    1394 
    1395         if (!*domain) {
    1396                 d_fprintf(stderr, _("Please supply a valid domain name\n"));
    1397                 werr = WERR_INVALID_PARAM;
    1398                 goto fail;
    1399         }
    1400 
    1401         if (!c->msg_ctx) {
    1402                 d_fprintf(stderr, _("Could not initialise message context. "
    1403                         "Try running as root\n"));
    1404                 werr = WERR_ACCESS_DENIED;
    1405                 goto fail;
    1406         }
    1407 
    1408         /* Do the domain join here */
    1409 
    1410         r->in.domain_name       = domain;
    1411         r->in.create_upn        = createupn;
    1412         r->in.upn               = machineupn;
    1413         r->in.account_ou        = create_in_ou;
    1414         r->in.os_name           = os_name;
    1415         r->in.os_version        = os_version;
    1416         r->in.dc_name           = c->opt_host;
    1417         r->in.admin_account     = c->opt_user_name;
    1418         r->in.admin_password    = net_prompt_pass(c, c->opt_user_name);
    1419         r->in.debug             = true;
    1420         r->in.use_kerberos      = c->opt_kerberos;
    1421         r->in.modify_config     = modify_config;
    1422         r->in.join_flags        = WKSSVC_JOIN_FLAGS_JOIN_TYPE |
    1423                                   WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE |
    1424                                   WKSSVC_JOIN_FLAGS_DOMAIN_JOIN_IF_JOINED;
    1425         r->in.msg_ctx           = c->msg_ctx;
    1426 
    1427         werr = libnet_Join(ctx, r);
    1428         if (W_ERROR_EQUAL(werr, WERR_DCNOTFOUND) &&
    1429             strequal(domain, lp_realm())) {
    1430                 r->in.domain_name = lp_workgroup();
    1431                 werr = libnet_Join(ctx, r);
    1432         }
    1433         if (!W_ERROR_IS_OK(werr)) {
    1434                 goto fail;
    1435         }
    1436 
    1437         /* Check the short name of the domain */
    1438 
    1439         if (!modify_config && !strequal(lp_workgroup(), r->out.netbios_domain_name)) {
    1440                 d_printf(_("The workgroup in %s does not match the short\n"
    1441                            "domain name obtained from the server.\n"
    1442                            "Using the name [%s] from the server.\n"
    1443                            "You should set \"workgroup = %s\" in %s.\n"),
    1444                          get_dyn_CONFIGFILE(), r->out.netbios_domain_name,
    1445                          r->out.netbios_domain_name, get_dyn_CONFIGFILE());
    1446         }
    1447 
    1448         d_printf(_("Using short domain name -- %s\n"), r->out.netbios_domain_name);
    1449 
    1450         if (r->out.dns_domain_name) {
    1451                 d_printf(_("Joined '%s' to dns domain '%s'\n"), r->in.machine_name,
    1452                         r->out.dns_domain_name);
    1453         } else {
    1454                 d_printf(_("Joined '%s' to domain '%s'\n"), r->in.machine_name,
    1455                         r->out.netbios_domain_name);
    1456         }
    1457 
     1347
     1348static void _net_ads_join_dns_updates(struct net_context *c, TALLOC_CTX *ctx, struct libnet_JoinCtx *r)
     1349{
    14581350#if defined(WITH_DNS_UPDATES)
     1351        ADS_STRUCT *ads_dns = NULL;
     1352        int ret;
     1353        NTSTATUS status;
     1354
    14591355        /*
    14601356         * In a clustered environment, don't do dynamic dns updates:
     
    14691365         */
    14701366        if (lp_clustering()) {
    1471                 d_fprintf(stderr, _("Not doing automatic DNS update in a"
     1367                d_fprintf(stderr, _("Not doing automatic DNS update in a "
    14721368                                    "clustered setup.\n"));
    1473                 goto done;
    1474         }
    1475 
    1476         if (r->out.domain_is_ad) {
    1477                 /* We enter this block with user creds */
    1478                 ADS_STRUCT *ads_dns = NULL;
    1479 
    1480                 if ( (ads_dns = ads_init( lp_realm(), NULL, NULL )) != NULL ) {
    1481                         /* kinit with the machine password */
    1482 
    1483                         use_in_memory_ccache();
    1484                         if (asprintf( &ads_dns->auth.user_name, "%s$", global_myname()) == -1) {
     1369                return;
     1370        }
     1371
     1372        if (!r->out.domain_is_ad) {
     1373                return;
     1374        }
     1375
     1376        /*
     1377         * We enter this block with user creds.
     1378         * kinit with the machine password to do dns update.
     1379         */
     1380
     1381        ads_dns = ads_init(lp_realm(), NULL, r->in.dc_name);
     1382
     1383        if (ads_dns == NULL) {
     1384                d_fprintf(stderr, _("DNS update failed: out of memory!\n"));
     1385                goto done;
     1386        }
     1387
     1388        use_in_memory_ccache();
     1389
     1390        ret = asprintf(&ads_dns->auth.user_name, "%s$", lp_netbios_name());
     1391        if (ret == -1) {
     1392                d_fprintf(stderr, _("DNS update failed: out of memory\n"));
     1393                goto done;
     1394        }
     1395
     1396        ads_dns->auth.password = secrets_fetch_machine_password(
     1397                r->out.netbios_domain_name, NULL, NULL);
     1398        if (ads_dns->auth.password == NULL) {
     1399                d_fprintf(stderr, _("DNS update failed: out of memory\n"));
     1400                goto done;
     1401        }
     1402
     1403        ads_dns->auth.realm = SMB_STRDUP(r->out.dns_domain_name);
     1404        if (ads_dns->auth.realm == NULL) {
     1405                d_fprintf(stderr, _("DNS update failed: out of memory\n"));
     1406                goto done;
     1407        }
     1408
     1409        if (!strupper_m(ads_dns->auth.realm)) {
     1410                d_fprintf(stderr, _("strupper_m %s failed\n"), ads_dns->auth.realm);
     1411                goto done;
     1412        }
     1413
     1414        ret = ads_kinit_password(ads_dns);
     1415        if (ret != 0) {
     1416                d_fprintf(stderr,
     1417                          _("DNS update failed: kinit failed: %s\n"),
     1418                          error_message(ret));
     1419                goto done;
     1420        }
     1421
     1422        status = net_update_dns(c, ctx, ads_dns, NULL);
     1423        if (!NT_STATUS_IS_OK(status)) {
     1424                d_fprintf( stderr, _("DNS update failed: %s\n"),
     1425                          nt_errstr(status));
     1426        }
     1427
     1428done:
     1429        ads_destroy(&ads_dns);
     1430#endif
     1431
     1432        return;
     1433}
     1434
     1435
     1436int net_ads_join(struct net_context *c, int argc, const char **argv)
     1437{
     1438        TALLOC_CTX *ctx = NULL;
     1439        struct libnet_JoinCtx *r = NULL;
     1440        const char *domain = lp_realm();
     1441        WERROR werr = WERR_SETUP_NOT_JOINED;
     1442        bool createupn = false;
     1443        const char *machineupn = NULL;
     1444        const char *machine_password = NULL;
     1445        const char *create_in_ou = NULL;
     1446        int i;
     1447        const char *os_name = NULL;
     1448        const char *os_version = NULL;
     1449        const char *os_servicepack = NULL;
     1450        bool modify_config = lp_config_backend_is_registry();
     1451        enum libnetjoin_JoinDomNameType domain_name_type = JoinDomNameTypeDNS;
     1452
     1453        if (c->display_usage)
     1454                return net_ads_join_usage(c, argc, argv);
     1455
     1456        if (!modify_config) {
     1457
     1458                werr = check_ads_config();
     1459                if (!W_ERROR_IS_OK(werr)) {
     1460                        d_fprintf(stderr, _("Invalid configuration.  Exiting....\n"));
     1461                        goto fail;
     1462                }
     1463        }
     1464
     1465        if (!(ctx = talloc_init("net_ads_join"))) {
     1466                d_fprintf(stderr, _("Could not initialise talloc context.\n"));
     1467                werr = WERR_NOMEM;
     1468                goto fail;
     1469        }
     1470
     1471        if (!c->opt_kerberos) {
     1472                use_in_memory_ccache();
     1473        }
     1474
     1475        werr = libnet_init_JoinCtx(ctx, &r);
     1476        if (!W_ERROR_IS_OK(werr)) {
     1477                goto fail;
     1478        }
     1479
     1480        /* process additional command line args */
     1481
     1482        for ( i=0; i<argc; i++ ) {
     1483                if ( !strncasecmp_m(argv[i], "createupn", strlen("createupn")) ) {
     1484                        createupn = true;
     1485                        machineupn = get_string_param(argv[i]);
     1486                }
     1487                else if ( !strncasecmp_m(argv[i], "createcomputer", strlen("createcomputer")) ) {
     1488                        if ( (create_in_ou = get_string_param(argv[i])) == NULL ) {
     1489                                d_fprintf(stderr, _("Please supply a valid OU path.\n"));
     1490                                werr = WERR_INVALID_PARAM;
    14851491                                goto fail;
    14861492                        }
    1487                         ads_dns->auth.password = secrets_fetch_machine_password(
    1488                                 r->out.netbios_domain_name, NULL, NULL );
    1489                         ads_dns->auth.realm = SMB_STRDUP( r->out.dns_domain_name );
    1490                         strupper_m(ads_dns->auth.realm );
    1491                         ads_kinit_password( ads_dns );
    1492                 }
    1493 
    1494                 if ( !ads_dns || !NT_STATUS_IS_OK(net_update_dns(c, ctx, ads_dns, NULL)) ) {
    1495                         d_fprintf( stderr, _("DNS update failed!\n") );
    1496                 }
    1497 
    1498                 /* exit from this block using machine creds */
    1499                 ads_destroy(&ads_dns);
    1500         }
    1501 
    1502 done:
    1503 #endif
     1493                }
     1494                else if ( !strncasecmp_m(argv[i], "osName", strlen("osName")) ) {
     1495                        if ( (os_name = get_string_param(argv[i])) == NULL ) {
     1496                                d_fprintf(stderr, _("Please supply a operating system name.\n"));
     1497                                werr = WERR_INVALID_PARAM;
     1498                                goto fail;
     1499                        }
     1500                }
     1501                else if ( !strncasecmp_m(argv[i], "osVer", strlen("osVer")) ) {
     1502                        if ( (os_version = get_string_param(argv[i])) == NULL ) {
     1503                                d_fprintf(stderr, _("Please supply a valid operating system version.\n"));
     1504                                werr = WERR_INVALID_PARAM;
     1505                                goto fail;
     1506                        }
     1507                }
     1508                else if ( !strncasecmp_m(argv[i], "osServicePack", strlen("osServicePack")) ) {
     1509                        if ( (os_servicepack = get_string_param(argv[i])) == NULL ) {
     1510                                d_fprintf(stderr, _("Please supply a valid servicepack identifier.\n"));
     1511                                werr = WERR_INVALID_PARAM;
     1512                                goto fail;
     1513                        }
     1514                }
     1515                else if ( !strncasecmp_m(argv[i], "machinepass", strlen("machinepass")) ) {
     1516                        if ( (machine_password = get_string_param(argv[i])) == NULL ) {
     1517                                d_fprintf(stderr, _("Please supply a valid password to set as trust account password.\n"));
     1518                                werr = WERR_INVALID_PARAM;
     1519                                goto fail;
     1520                        }
     1521                }
     1522                else {
     1523                        domain = argv[i];
     1524                        if (strchr(domain, '.') == NULL) {
     1525                                domain_name_type = JoinDomNameTypeUnknown;
     1526                        } else {
     1527                                domain_name_type = JoinDomNameTypeDNS;
     1528                        }
     1529                }
     1530        }
     1531
     1532        if (!*domain) {
     1533                d_fprintf(stderr, _("Please supply a valid domain name\n"));
     1534                werr = WERR_INVALID_PARAM;
     1535                goto fail;
     1536        }
     1537
     1538        if (!c->msg_ctx) {
     1539                d_fprintf(stderr, _("Could not initialise message context. "
     1540                        "Try running as root\n"));
     1541                werr = WERR_ACCESS_DENIED;
     1542                goto fail;
     1543        }
     1544
     1545        /* Do the domain join here */
     1546
     1547        r->in.domain_name       = domain;
     1548        r->in.domain_name_type  = domain_name_type;
     1549        r->in.create_upn        = createupn;
     1550        r->in.upn               = machineupn;
     1551        r->in.account_ou        = create_in_ou;
     1552        r->in.os_name           = os_name;
     1553        r->in.os_version        = os_version;
     1554        r->in.os_servicepack    = os_servicepack;
     1555        r->in.dc_name           = c->opt_host;
     1556        r->in.admin_account     = c->opt_user_name;
     1557        r->in.admin_password    = net_prompt_pass(c, c->opt_user_name);
     1558        r->in.machine_password  = machine_password;
     1559        r->in.debug             = true;
     1560        r->in.use_kerberos      = c->opt_kerberos;
     1561        r->in.modify_config     = modify_config;
     1562        r->in.join_flags        = WKSSVC_JOIN_FLAGS_JOIN_TYPE |
     1563                                  WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE |
     1564                                  WKSSVC_JOIN_FLAGS_DOMAIN_JOIN_IF_JOINED;
     1565        r->in.msg_ctx           = c->msg_ctx;
     1566
     1567        werr = libnet_Join(ctx, r);
     1568        if (W_ERROR_EQUAL(werr, WERR_DCNOTFOUND) &&
     1569            strequal(domain, lp_realm())) {
     1570                r->in.domain_name = lp_workgroup();
     1571                r->in.domain_name_type = JoinDomNameTypeNBT;
     1572                werr = libnet_Join(ctx, r);
     1573        }
     1574        if (!W_ERROR_IS_OK(werr)) {
     1575                goto fail;
     1576        }
     1577
     1578        /* Check the short name of the domain */
     1579
     1580        if (!modify_config && !strequal(lp_workgroup(), r->out.netbios_domain_name)) {
     1581                d_printf(_("The workgroup in %s does not match the short\n"
     1582                           "domain name obtained from the server.\n"
     1583                           "Using the name [%s] from the server.\n"
     1584                           "You should set \"workgroup = %s\" in %s.\n"),
     1585                         get_dyn_CONFIGFILE(), r->out.netbios_domain_name,
     1586                         r->out.netbios_domain_name, get_dyn_CONFIGFILE());
     1587        }
     1588
     1589        d_printf(_("Using short domain name -- %s\n"), r->out.netbios_domain_name);
     1590
     1591        if (r->out.dns_domain_name) {
     1592                d_printf(_("Joined '%s' to dns domain '%s'\n"), r->in.machine_name,
     1593                        r->out.dns_domain_name);
     1594        } else {
     1595                d_printf(_("Joined '%s' to domain '%s'\n"), r->in.machine_name,
     1596                        r->out.netbios_domain_name);
     1597        }
     1598
     1599        /*
     1600         * We try doing the dns update (if it was compiled in
     1601         * and if it was not disabled on the command line).
     1602         * If the dns update fails, we still consider the join
     1603         * operation as succeeded if we came this far.
     1604         */
     1605        if (!c->opt_no_dns_updates) {
     1606                _net_ads_join_dns_updates(c, ctx, r);
     1607        }
    15041608
    15051609        TALLOC_FREE(r);
     
    17661870                servername =  argv[1];
    17671871        } else {
    1768                 servername = global_myname();
     1872                servername = lp_netbios_name();
    17691873        }
    17701874
     
    18071911        char *srv_cn_escaped = NULL, *printername_escaped = NULL;
    18081912        LDAPMessage *res = NULL;
     1913        bool ok;
    18091914
    18101915        if (argc < 1 || c->display_usage) {
     
    18291934                servername = argv[1];
    18301935        } else {
    1831                 servername = global_myname();
     1936                servername = lp_netbios_name();
    18321937        }
    18331938
    18341939        /* Get printer data from SPOOLSS */
    18351940
    1836         resolve_name(servername, &server_ss, 0x20, false);
    1837 
    1838         nt_status = cli_full_connection(&cli, global_myname(), servername,
     1941        ok = resolve_name(servername, &server_ss, 0x20, false);
     1942        if (!ok) {
     1943                d_fprintf(stderr, _("Could not find server %s\n"),
     1944                          servername);
     1945                ads_destroy(&ads);
     1946                talloc_destroy(mem_ctx);
     1947                return -1;
     1948        }
     1949
     1950        nt_status = cli_full_connection(&cli, lp_netbios_name(), servername,
    18391951                                        &server_ss, 0,
    18401952                                        "IPC$", "IPC",
     
    18421954                                        c->opt_password ? c->opt_password : "",
    18431955                                        CLI_FULL_CONNECTION_USE_KERBEROS,
    1844                                         Undefined);
     1956                                        SMB_SIGNING_IPC_DEFAULT);
    18451957
    18461958        if (NT_STATUS_IS_ERR(nt_status)) {
     
    18922004        SAFE_FREE(printername_escaped);
    18932005
    1894         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_spoolss.syntax_id, &pipe_hnd);
     2006        nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_spoolss, &pipe_hnd);
    18952007        if (!NT_STATUS_IS_OK(nt_status)) {
    18962008                d_fprintf(stderr, _("Unable to open a connection to the spoolss pipe on %s\n"),
     
    19522064                servername = argv[1];
    19532065        } else {
    1954                 servername = global_myname();
     2066                servername = lp_netbios_name();
    19552067        }
    19562068
     
    20332145        const char *auth_principal = c->opt_user_name;
    20342146        const char *auth_password = c->opt_password;
    2035         char *realm = NULL;
    2036         char *new_password = NULL;
     2147        const char *realm = NULL;
     2148        const char *new_password = NULL;
    20372149        char *chr, *prompt;
    20382150        const char *user;
     2151        char pwd[256] = {0};
    20392152        ADS_STATUS ret;
    20402153
     
    20932206
    20942207        if (argv[1]) {
    2095                 new_password = (char *)argv[1];
     2208                new_password = (const char *)argv[1];
    20962209        } else {
     2210                int rc;
     2211
    20972212                if (asprintf(&prompt, _("Enter new password for %s:"), user) == -1) {
    20982213                        return -1;
    20992214                }
    2100                 new_password = getpass(prompt);
     2215                rc = samba_getpass(prompt, pwd, sizeof(pwd), false, true);
     2216                if (rc < 0) {
     2217                        return -1;
     2218                }
     2219                new_password = pwd;
    21012220                free(prompt);
    21022221        }
     
    21042223        ret = kerberos_set_password(ads->auth.kdc_server, auth_principal,
    21052224                                auth_password, user, new_password, ads->auth.time_offset);
     2225        memset(pwd, '\0', sizeof(pwd));
    21062226        if (!ADS_ERR_OK(ret)) {
    21072227                d_fprintf(stderr, _("Password change failed: %s\n"), ads_errstr(ret));
     
    21452265        }
    21462266
    2147         fstrcpy(my_name, global_myname());
    2148         strlower_m(my_name);
     2267        fstrcpy(my_name, lp_netbios_name());
     2268        if (!strlower_m(my_name)) {
     2269                ads_destroy(&ads);
     2270                return -1;
     2271        }
     2272
    21492273        if (asprintf(&host_principal, "%s$@%s", my_name, ads->config.realm) == -1) {
    21502274                ads_destroy(&ads);
     
    25202644}
    25212645
    2522 static int net_ads_kerberos_pac(struct net_context *c, int argc, const char **argv)
    2523 {
    2524         struct PAC_LOGON_INFO *info = NULL;
    2525         TALLOC_CTX *mem_ctx = NULL;
     2646static int net_ads_kerberos_pac_common(struct net_context *c, int argc, const char **argv,
     2647                                       struct PAC_DATA_CTR **pac_data_ctr)
     2648{
    25262649        NTSTATUS status;
    25272650        int ret = -1;
    25282651        const char *impersonate_princ_s = NULL;
    2529 
    2530         if (c->display_usage) {
    2531                 d_printf(  "%s\n"
    2532                            "net ads kerberos pac\n"
    2533                            "    %s\n",
    2534                          _("Usage:"),
    2535                          _("Dump the Kerberos PAC"));
    2536                 return 0;
    2537         }
    2538 
    2539         mem_ctx = talloc_init("net_ads_kerberos_pac");
    2540         if (!mem_ctx) {
    2541                 goto out;
    2542         }
    2543 
    2544         if (argc > 0) {
    2545                 impersonate_princ_s = argv[0];
     2652        const char *local_service = NULL;
     2653        int i;
     2654
     2655        for (i=0; i<argc; i++) {
     2656                if (strnequal(argv[i], "impersonate", strlen("impersonate"))) {
     2657                        impersonate_princ_s = get_string_param(argv[i]);
     2658                        if (impersonate_princ_s == NULL) {
     2659                                return -1;
     2660                        }
     2661                }
     2662                if (strnequal(argv[i], "local_service", strlen("local_service"))) {
     2663                        local_service = get_string_param(argv[i]);
     2664                        if (local_service == NULL) {
     2665                                return -1;
     2666                        }
     2667                }
     2668        }
     2669
     2670        if (local_service == NULL) {
     2671                local_service = talloc_asprintf(c, "%s$@%s",
     2672                                                lp_netbios_name(), lp_realm());
     2673                if (local_service == NULL) {
     2674                        goto out;
     2675                }
    25462676        }
    25472677
    25482678        c->opt_password = net_prompt_pass(c, c->opt_user_name);
    25492679
    2550         status = kerberos_return_pac(mem_ctx,
     2680        status = kerberos_return_pac(c,
    25512681                                     c->opt_user_name,
    25522682                                     c->opt_password,
     
    25592689                                     2592000, /* one month */
    25602690                                     impersonate_princ_s,
    2561                                      &info);
     2691                                     local_service,
     2692                                     pac_data_ctr);
    25622693        if (!NT_STATUS_IS_OK(status)) {
    25632694                d_printf(_("failed to query kerberos PAC: %s\n"),
     
    25662697        }
    25672698
    2568         if (info) {
    2569                 const char *s;
    2570                 s = NDR_PRINT_STRUCT_STRING(mem_ctx, PAC_LOGON_INFO, info);
    2571                 d_printf(_("The Pac: %s\n"), s);
    2572         }
    2573 
    25742699        ret = 0;
    25752700 out:
    2576         TALLOC_FREE(mem_ctx);
    25772701        return ret;
     2702}
     2703
     2704static int net_ads_kerberos_pac_dump(struct net_context *c, int argc, const char **argv)
     2705{
     2706        struct PAC_DATA_CTR *pac_data_ctr = NULL;
     2707        int i;
     2708        int ret = -1;
     2709        enum PAC_TYPE type = 0;
     2710
     2711        if (c->display_usage) {
     2712                d_printf(  "%s\n"
     2713                           "net ads kerberos pac dump [impersonate=string] [local_service=string] [pac_buffer_type=int]\n"
     2714                           "    %s\n",
     2715                         _("Usage:"),
     2716                         _("Dump the Kerberos PAC"));
     2717                return -1;
     2718        }
     2719
     2720        for (i=0; i<argc; i++) {
     2721                if (strnequal(argv[i], "pac_buffer_type", strlen("pac_buffer_type"))) {
     2722                        type = get_int_param(argv[i]);
     2723                }
     2724        }
     2725
     2726        ret = net_ads_kerberos_pac_common(c, argc, argv, &pac_data_ctr);
     2727        if (ret) {
     2728                return ret;
     2729        }
     2730
     2731        if (type == 0) {
     2732
     2733                char *s = NULL;
     2734
     2735                s = NDR_PRINT_STRUCT_STRING(c, PAC_DATA,
     2736                        pac_data_ctr->pac_data);
     2737                if (s != NULL) {
     2738                        d_printf(_("The Pac: %s\n"), s);
     2739                        talloc_free(s);
     2740                }
     2741
     2742                return 0;
     2743        }
     2744
     2745        for (i=0; i < pac_data_ctr->pac_data->num_buffers; i++) {
     2746
     2747                char *s = NULL;
     2748
     2749                if (pac_data_ctr->pac_data->buffers[i].type != type) {
     2750                        continue;
     2751                }
     2752
     2753                s = NDR_PRINT_UNION_STRING(c, PAC_INFO, type,
     2754                                pac_data_ctr->pac_data->buffers[i].info);
     2755                if (s != NULL) {
     2756                        d_printf(_("The Pac: %s\n"), s);
     2757                        talloc_free(s);
     2758                }
     2759                break;
     2760        }
     2761
     2762        return 0;
     2763}
     2764
     2765static int net_ads_kerberos_pac_save(struct net_context *c, int argc, const char **argv)
     2766{
     2767        struct PAC_DATA_CTR *pac_data_ctr = NULL;
     2768        char *filename = NULL;
     2769        int ret = -1;
     2770        int i;
     2771
     2772        if (c->display_usage) {
     2773                d_printf(  "%s\n"
     2774                           "net ads kerberos pac save [impersonate=string] [local_service=string] [filename=string]\n"
     2775                           "    %s\n",
     2776                         _("Usage:"),
     2777                         _("Save the Kerberos PAC"));
     2778                return -1;
     2779        }
     2780
     2781        for (i=0; i<argc; i++) {
     2782                if (strnequal(argv[i], "filename", strlen("filename"))) {
     2783                        filename = get_string_param(argv[i]);
     2784                        if (filename == NULL) {
     2785                                return -1;
     2786                        }
     2787                }
     2788        }
     2789
     2790        ret = net_ads_kerberos_pac_common(c, argc, argv, &pac_data_ctr);
     2791        if (ret) {
     2792                return ret;
     2793        }
     2794
     2795        if (filename == NULL) {
     2796                d_printf(_("please define \"filename=<filename>\" to save the PAC\n"));
     2797                return -1;
     2798        }
     2799
     2800        /* save the raw format */
     2801        if (!file_save(filename, pac_data_ctr->pac_blob.data, pac_data_ctr->pac_blob.length)) {
     2802                d_printf(_("failed to save PAC in %s\n"), filename);
     2803                return -1;
     2804        }
     2805
     2806        return 0;
     2807}
     2808
     2809static int net_ads_kerberos_pac(struct net_context *c, int argc, const char **argv)
     2810{
     2811        struct functable func[] = {
     2812                {
     2813                        "dump",
     2814                        net_ads_kerberos_pac_dump,
     2815                        NET_TRANSPORT_ADS,
     2816                        N_("Dump Kerberos PAC"),
     2817                        N_("net ads kerberos pac dump\n"
     2818                           "    Dump a Kerberos PAC to stdout")
     2819                },
     2820                {
     2821                        "save",
     2822                        net_ads_kerberos_pac_save,
     2823                        NET_TRANSPORT_ADS,
     2824                        N_("Save Kerberos PAC"),
     2825                        N_("net ads kerberos pac save\n"
     2826                           "    Save a Kerberos PAC in a file")
     2827                },
     2828
     2829                {NULL, NULL, 0, NULL, NULL}
     2830        };
     2831
     2832        return net_run_function(c, argc, argv, "net ads kerberos pac", func);
    25782833}
    25792834
     
    26522907}
    26532908
     2909static int net_ads_enctype_lookup_account(struct net_context *c,
     2910                                          ADS_STRUCT *ads,
     2911                                          const char *account,
     2912                                          LDAPMessage **res,
     2913                                          const char **enctype_str)
     2914{
     2915        const char *filter;
     2916        const char *attrs[] = {
     2917                "msDS-SupportedEncryptionTypes",
     2918                NULL
     2919        };
     2920        int count;
     2921        int ret = -1;
     2922        ADS_STATUS status;
     2923
     2924        filter = talloc_asprintf(c, "(&(objectclass=user)(sAMAccountName=%s))",
     2925                                 account);
     2926        if (filter == NULL) {
     2927                goto done;
     2928        }
     2929
     2930        status = ads_search(ads, res, filter, attrs);
     2931        if (!ADS_ERR_OK(status)) {
     2932                d_printf(_("no account found with filter: %s\n"), filter);
     2933                goto done;
     2934        }
     2935
     2936        count = ads_count_replies(ads, *res);
     2937        switch (count) {
     2938        case 1:
     2939                break;
     2940        case 0:
     2941                d_printf(_("no account found with filter: %s\n"), filter);
     2942                goto done;
     2943        default:
     2944                d_printf(_("multiple accounts found with filter: %s\n"), filter);
     2945                goto done;
     2946        }
     2947
     2948        if (enctype_str) {
     2949                *enctype_str = ads_pull_string(ads, c, *res,
     2950                                               "msDS-SupportedEncryptionTypes");
     2951                if (*enctype_str == NULL) {
     2952                        d_printf(_("no msDS-SupportedEncryptionTypes attribute found\n"));
     2953                        goto done;
     2954                }
     2955        }
     2956
     2957        ret = 0;
     2958 done:
     2959        return ret;
     2960}
     2961
     2962static void net_ads_enctype_dump_enctypes(const char *username,
     2963                                          const char *enctype_str)
     2964{
     2965        int enctypes = atoi(enctype_str);
     2966
     2967        d_printf(_("'%s' uses \"msDS-SupportedEncryptionTypes\": %d (0x%08x)\n"),
     2968                username, enctypes, enctypes);
     2969
     2970        printf("[%s] 0x%08x DES-CBC-CRC\n",
     2971                enctypes & ENC_CRC32 ? "X" : " ",
     2972                ENC_CRC32);
     2973        printf("[%s] 0x%08x DES-CBC-MD5\n",
     2974                enctypes & ENC_RSA_MD5 ? "X" : " ",
     2975                ENC_RSA_MD5);
     2976        printf("[%s] 0x%08x RC4-HMAC\n",
     2977                enctypes & ENC_RC4_HMAC_MD5 ? "X" : " ",
     2978                ENC_RC4_HMAC_MD5);
     2979        printf("[%s] 0x%08x AES128-CTS-HMAC-SHA1-96\n",
     2980                enctypes & ENC_HMAC_SHA1_96_AES128 ? "X" : " ",
     2981                ENC_HMAC_SHA1_96_AES128);
     2982        printf("[%s] 0x%08x AES256-CTS-HMAC-SHA1-96\n",
     2983                enctypes & ENC_HMAC_SHA1_96_AES256 ? "X" : " ",
     2984                ENC_HMAC_SHA1_96_AES256);
     2985}
     2986
     2987static int net_ads_enctypes_list(struct net_context *c, int argc, const char **argv)
     2988{
     2989        int ret = -1;
     2990        ADS_STATUS status;
     2991        ADS_STRUCT *ads = NULL;
     2992        LDAPMessage *res = NULL;
     2993        const char *str = NULL;
     2994
     2995        if (c->display_usage || (argc < 1)) {
     2996                d_printf(  "%s\n"
     2997                           "net ads enctypes list\n"
     2998                           "    %s\n",
     2999                         _("Usage:"),
     3000                         _("List supported enctypes"));
     3001                return 0;
     3002        }
     3003
     3004        status = ads_startup(c, false, &ads);
     3005        if (!ADS_ERR_OK(status)) {
     3006                printf("startup failed\n");
     3007                return ret;
     3008        }
     3009
     3010        ret = net_ads_enctype_lookup_account(c, ads, argv[0], &res, &str);
     3011        if (ret) {
     3012                goto done;
     3013        }
     3014
     3015        net_ads_enctype_dump_enctypes(argv[0], str);
     3016
     3017        ret = 0;
     3018 done:
     3019        ads_msgfree(ads, res);
     3020        ads_destroy(&ads);
     3021
     3022        return ret;
     3023}
     3024
     3025static int net_ads_enctypes_set(struct net_context *c, int argc, const char **argv)
     3026{
     3027        int ret = -1;
     3028        ADS_STATUS status;
     3029        ADS_STRUCT *ads;
     3030        LDAPMessage *res = NULL;
     3031        const char *etype_list_str;
     3032        const char *dn;
     3033        ADS_MODLIST mods;
     3034        uint32_t etype_list;
     3035        const char *str;
     3036
     3037        if (c->display_usage || argc < 1) {
     3038                d_printf(  "%s\n"
     3039                           "net ads enctypes set <sAMAccountName> [enctypes]\n"
     3040                           "    %s\n",
     3041                         _("Usage:"),
     3042                         _("Set supported enctypes"));
     3043                return 0;
     3044        }
     3045
     3046        status = ads_startup(c, false, &ads);
     3047        if (!ADS_ERR_OK(status)) {
     3048                printf("startup failed\n");
     3049                return ret;
     3050        }
     3051
     3052        ret = net_ads_enctype_lookup_account(c, ads, argv[0], &res, NULL);
     3053        if (ret) {
     3054                goto done;
     3055        }
     3056
     3057        dn = ads_get_dn(ads, c, res);
     3058        if (dn == NULL) {
     3059                goto done;
     3060        }
     3061
     3062        etype_list = ENC_CRC32 | ENC_RSA_MD5 | ENC_RC4_HMAC_MD5;
     3063#ifdef HAVE_ENCTYPE_AES128_CTS_HMAC_SHA1_96
     3064        etype_list |= ENC_HMAC_SHA1_96_AES128;
     3065#endif
     3066#ifdef HAVE_ENCTYPE_AES256_CTS_HMAC_SHA1_96
     3067        etype_list |= ENC_HMAC_SHA1_96_AES256;
     3068#endif
     3069
     3070        if (argv[1] != NULL) {
     3071                sscanf(argv[1], "%i", &etype_list);
     3072        }
     3073
     3074        etype_list_str = talloc_asprintf(c, "%d", etype_list);
     3075        if (!etype_list_str) {
     3076                goto done;
     3077        }
     3078
     3079        mods = ads_init_mods(c);
     3080        if (!mods) {
     3081                goto done;
     3082        }
     3083
     3084        status = ads_mod_str(c, &mods, "msDS-SupportedEncryptionTypes",
     3085                             etype_list_str);
     3086        if (!ADS_ERR_OK(status)) {
     3087                goto done;
     3088        }
     3089
     3090        status = ads_gen_mod(ads, dn, mods);
     3091        if (!ADS_ERR_OK(status)) {
     3092                d_printf(_("failed to add msDS-SupportedEncryptionTypes: %s\n"),
     3093                        ads_errstr(status));
     3094                goto done;
     3095        }
     3096
     3097        ads_msgfree(ads, res);
     3098
     3099        ret = net_ads_enctype_lookup_account(c, ads, argv[0], &res, &str);
     3100        if (ret) {
     3101                goto done;
     3102        }
     3103
     3104        net_ads_enctype_dump_enctypes(argv[0], str);
     3105
     3106        ret = 0;
     3107 done:
     3108        ads_msgfree(ads, res);
     3109        ads_destroy(&ads);
     3110
     3111        return ret;
     3112}
     3113
     3114static int net_ads_enctypes_delete(struct net_context *c, int argc, const char **argv)
     3115{
     3116        int ret = -1;
     3117        ADS_STATUS status;
     3118        ADS_STRUCT *ads;
     3119        LDAPMessage *res = NULL;
     3120        const char *dn;
     3121        ADS_MODLIST mods;
     3122
     3123        if (c->display_usage || argc < 1) {
     3124                d_printf(  "%s\n"
     3125                           "net ads enctypes delete <sAMAccountName>\n"
     3126                           "    %s\n",
     3127                         _("Usage:"),
     3128                         _("Delete supported enctypes"));
     3129                return 0;
     3130        }
     3131
     3132        status = ads_startup(c, false, &ads);
     3133        if (!ADS_ERR_OK(status)) {
     3134                printf("startup failed\n");
     3135                return ret;
     3136        }
     3137
     3138        ret = net_ads_enctype_lookup_account(c, ads, argv[0], &res, NULL);
     3139        if (ret) {
     3140                goto done;
     3141        }
     3142
     3143        dn = ads_get_dn(ads, c, res);
     3144        if (dn == NULL) {
     3145                goto done;
     3146        }
     3147
     3148        mods = ads_init_mods(c);
     3149        if (!mods) {
     3150                goto done;
     3151        }
     3152
     3153        status = ads_mod_str(c, &mods, "msDS-SupportedEncryptionTypes", NULL);
     3154        if (!ADS_ERR_OK(status)) {
     3155                goto done;
     3156        }
     3157
     3158        status = ads_gen_mod(ads, dn, mods);
     3159        if (!ADS_ERR_OK(status)) {
     3160                d_printf(_("failed to remove msDS-SupportedEncryptionTypes: %s\n"),
     3161                        ads_errstr(status));
     3162                goto done;
     3163        }
     3164
     3165        ret = 0;
     3166
     3167 done:
     3168        ads_msgfree(ads, res);
     3169        ads_destroy(&ads);
     3170        return ret;
     3171}
     3172
     3173static int net_ads_enctypes(struct net_context *c, int argc, const char **argv)
     3174{
     3175        struct functable func[] = {
     3176                {
     3177                        "list",
     3178                        net_ads_enctypes_list,
     3179                        NET_TRANSPORT_ADS,
     3180                        N_("List the supported encryption types"),
     3181                        N_("net ads enctypes list\n"
     3182                           "    List the supported encryption types")
     3183                },
     3184                {
     3185                        "set",
     3186                        net_ads_enctypes_set,
     3187                        NET_TRANSPORT_ADS,
     3188                        N_("Set the supported encryption types"),
     3189                        N_("net ads enctypes set\n"
     3190                           "    Set the supported encryption types")
     3191                },
     3192                {
     3193                        "delete",
     3194                        net_ads_enctypes_delete,
     3195                        NET_TRANSPORT_ADS,
     3196                        N_("Delete the supported encryption types"),
     3197                        N_("net ads enctypes delete\n"
     3198                           "    Delete the supported encryption types")
     3199                },
     3200
     3201                {NULL, NULL, 0, NULL, NULL}
     3202        };
     3203
     3204        return net_run_function(c, argc, argv, "net ads enctypes", func);
     3205}
     3206
     3207
    26543208int net_ads(struct net_context *c, int argc, const char **argv)
    26553209{
     
    28073361                           "    Manage kerberos keytab")
    28083362                },
     3363                {
     3364                        "enctypes",
     3365                        net_ads_enctypes,
     3366                        NET_TRANSPORT_ADS,
     3367                        N_("List/modify supported encryption types"),
     3368                        N_("net ads enctypes\n"
     3369                           "    List/modify enctypes")
     3370                },
    28093371                {NULL, NULL, 0, NULL, NULL}
    28103372        };
     
    28723434}
    28733435
    2874 #endif  /* WITH_ADS */
     3436#endif  /* HAVE_ADS */
  • vendor/current/source3/utils/net_ads_gpo.c

    r740 r988  
    3535        struct GROUP_POLICY_OBJECT *gpo_list = NULL;
    3636        struct GROUP_POLICY_OBJECT *read_list = NULL;
    37         uint32 uac = 0;
    38         uint32 flags = 0;
     37        uint32_t uac = 0;
     38        uint32_t flags = 0;
    3939        struct GROUP_POLICY_OBJECT *gpo;
    4040        NTSTATUS result;
    4141        struct security_token *token = NULL;
     42        char *gpo_cache_path;
    4243
    4344        if (argc < 1 || c->display_usage) {
     
    7980        d_printf(_("* fetching token "));
    8081        if (uac & UF_WORKSTATION_TRUST_ACCOUNT) {
    81                 status = gp_get_machine_token(ads, mem_ctx, NULL, dn, &token);
     82                status = gp_get_machine_token(ads, mem_ctx, dn, &token);
    8283        } else {
    8384                status = ads_get_sid_token(ads, mem_ctx, dn, &token);
     
    100101
    101102        d_printf(_("* Refreshing Group Policy Data "));
    102         if (!NT_STATUS_IS_OK(result = check_refresh_gpo_list(ads, mem_ctx,
    103                                                              cache_path(GPO_CACHE_DIR),
    104                                                              NULL,
    105                                                              flags,
    106                                                              gpo_list))) {
     103        gpo_cache_path = cache_path(GPO_CACHE_DIR);
     104        if (gpo_cache_path == NULL) {
     105                d_printf(_("failed: %s\n"), nt_errstr(NT_STATUS_NO_MEMORY));
     106                goto out;
     107        }
     108        result = check_refresh_gpo_list(ads, mem_ctx,
     109                                        gpo_cache_path,
     110                                        flags,
     111                                        gpo_list);
     112        TALLOC_FREE(gpo_cache_path);
     113        if (!NT_STATUS_IS_OK(result)) {
    107114                d_printf(_("failed: %s\n"), nt_errstr(result));
    108115                goto out;
     
    129136                for (gpo = gpo_list; gpo; gpo = gpo->next) {
    130137
    131                         dump_gpo(ads, mem_ctx, gpo, 0);
     138                        dump_gpo(gpo, 0);
    132139#if 0
    133140                char *server, *share, *nt_path, *unix_path;
     
    174181                for (gpo = read_list; gpo; gpo = gpo->next) {
    175182
    176                         dump_gpo(ads, mem_ctx, gpo, 0);
     183                        dump_gpo(gpo, 0);
    177184
    178185#if 0
     
    280287                }
    281288
    282                 dump_gpo(ads, mem_ctx, &gpo, 0);
     289                dump_gpo(&gpo, 0);
    283290        }
    284291
     
    299306        TALLOC_CTX *mem_ctx;
    300307        const char *dn = NULL;
    301         uint32 uac = 0;
    302         uint32 flags = 0;
     308        uint32_t uac = 0;
     309        uint32_t flags = 0;
    303310        struct GROUP_POLICY_OBJECT *gpo_list;
    304311        struct security_token *token = NULL;
     
    338345
    339346        if (uac & UF_WORKSTATION_TRUST_ACCOUNT) {
    340                 status = gp_get_machine_token(ads, mem_ctx, NULL, dn, &token);
     347                status = gp_get_machine_token(ads, mem_ctx, dn, &token);
    341348        } else {
    342349                status = ads_get_sid_token(ads, mem_ctx, dn, &token);
     
    352359        }
    353360
    354         dump_gpo_list(ads, mem_ctx, gpo_list, 0);
     361        dump_gpo_list(gpo_list, 0);
    355362
    356363out:
     
    370377        const char *dn = NULL;
    371378        struct GROUP_POLICY_OBJECT *gpo_list;
    372         uint32 uac = 0;
    373         uint32 flags = 0;
     379        uint32_t uac = 0;
     380        uint32_t flags = 0;
    374381        struct security_token *token = NULL;
    375382        const char *filter = NULL;
     
    421428
    422429        if (uac & UF_WORKSTATION_TRUST_ACCOUNT) {
    423                 status = gp_get_machine_token(ads, mem_ctx, NULL, dn, &token);
     430                status = gp_get_machine_token(ads, mem_ctx, dn, &token);
    424431        } else {
    425432                status = ads_get_sid_token(ads, mem_ctx, dn, &token);
     
    435442        }
    436443
    437         status = gpo_process_gpo_list(ads, mem_ctx, token, gpo_list,
    438                                       filter, flags);
     444        status = ADS_ERROR_NT(gpo_process_gpo_list(mem_ctx, token, NULL, gpo_list,
     445                                                   filter, flags));
    439446        if (!ADS_ERR_OK(status)) {
    440447                d_printf("failed to process gpo list: %s\n",
     
    482489        }
    483490
    484         dump_gplink(ads, mem_ctx, &gp_link);
     491        dump_gplink(&gp_link);
    485492
    486493out:
     
    495502        ADS_STRUCT *ads;
    496503        ADS_STATUS status;
    497         uint32 gpo_opt = 0;
     504        uint32_t gpo_opt = 0;
    498505        TALLOC_CTX *mem_ctx;
    499506
     
    590597                         _("Usage:"),
    591598                         _("net ads gpo getgpo <gpo>"),
    592                          _("  List speciefied GPO\n"
     599                         _("  List specified GPO\n"
    593600                           "    gpo\t\tGPO to list\n"));
    594601                return -1;
     
    617624        }
    618625
    619         dump_gpo(ads, mem_ctx, &gpo, 1);
     626        dump_gpo(&gpo, 1);
    620627
    621628out:
  • vendor/current/source3/utils/net_afs.c

    r740 r988  
    2020#include "includes.h"
    2121#include "utils/net.h"
     22#include "utils/net_afs.h"
    2223#include "secrets.h"
    2324#include "system/filesys.h"
     25#include "lib/afs/afs_funcs.h"
     26#include "lib/afs/afs_settoken.h"
     27
     28#ifdef WITH_FAKE_KASERVER
    2429
    2530int net_afs_usage(struct net_context *c, int argc, const char **argv)
     
    118123}
    119124
     125#endif /* WITH_FAKE_KASERVER */
  • vendor/current/source3/utils/net_cache.c

    r740 r988  
    243243        }
    244244
    245         if (gencache_get_data_blob(keystr, &value, &timeout, NULL)) {
     245        if (gencache_get_data_blob(keystr, NULL, &value, &timeout, NULL)) {
    246246                print_cache_entry(keystr, value, timeout, NULL);
    247247                data_blob_free(&value);
  • vendor/current/source3/utils/net_conf.c

    r740 r988  
    3131#include "system/filesys.h"
    3232#include "utils/net.h"
     33#include "utils/net_conf_util.h"
    3334#include "lib/smbconf/smbconf.h"
    3435#include "lib/smbconf/smbconf_init.h"
    3536#include "lib/smbconf/smbconf_reg.h"
     37#include "lib/param/loadparm.h"
    3638
    3739/**********************************************************************
     
    9193                 _("Usage:"),
    9294                 _(" net conf addshare <sharename> <path> "
    93                    "[writeable={y|N} [guest_ok={y|N} [<comment>]]\n"
     95                   "[writeable={y|N} [guest_ok={y|N} [<comment>]]]\n"
    9496                   "\t<sharename>      the new share name.\n"
    9597                   "\t<path>           the path on the filesystem to export.\n"
     
    179181                                     struct smbconf_service *service)
    180182{
    181         uint32_t idx;
    182183        sbcErr err = SBC_ERR_OK;
    183         uint32_t num_includes = 0;
    184         char **includes = NULL;
    185         TALLOC_CTX *mem_ctx = talloc_stackframe();
    186184
    187185        if (c->opt_testmode) {
     186                uint32_t idx;
    188187                const char *indent = "";
    189188                if (service->name != NULL) {
     
    206205                }
    207206        }
    208         err = smbconf_create_share(conf_ctx, service->name);
    209         if (!SBC_ERROR_IS_OK(err)) {
    210                 goto done;
    211         }
    212 
    213         for (idx = 0; idx < service->num_params; idx ++) {
    214                 if (strequal(service->param_names[idx], "include")) {
    215                         includes = TALLOC_REALLOC_ARRAY(mem_ctx,
    216                                                         includes,
    217                                                         char *,
    218                                                         num_includes+1);
    219                         if (includes == NULL) {
    220                                 err = SBC_ERR_NOMEM;
    221                                 goto done;
    222                         }
    223                         includes[num_includes] = talloc_strdup(includes,
    224                                                 service->param_values[idx]);
    225                         if (includes[num_includes] == NULL) {
    226                                 err = SBC_ERR_NOMEM;
    227                                 goto done;
    228                         }
    229                         num_includes++;
    230                 } else {
    231                         err = smbconf_set_parameter(conf_ctx,
    232                                                      service->name,
    233                                                      service->param_names[idx],
    234                                                      service->param_values[idx]);
    235                         if (!SBC_ERROR_IS_OK(err)) {
    236                                 d_fprintf(stderr,
    237                                           _("Error in section [%s], parameter \"%s\": %s\n"),
    238                                           service->name, service->param_names[idx],
    239                                           sbcErrorString(err));
    240                                 goto done;
    241                         }
    242                 }
    243         }
    244 
    245         err = smbconf_set_includes(conf_ctx, service->name, num_includes,
    246                                    (const char **)includes);
    247         if (!SBC_ERROR_IS_OK(err)) {
    248                 goto done;
    249         }
    250 
    251         err = SBC_ERR_OK;
    252 done:
    253         TALLOC_FREE(mem_ctx);
     207
     208        err = smbconf_create_set_share(conf_ctx, service);
     209
     210done:
    254211        return err;
    255212}
     
    383340                err = import_process_service(c, conf_ctx, service);
    384341                if (!SBC_ERROR_IS_OK(err)) {
     342                        d_printf(_("error importing service %s: %s\n"),
     343                                 servicename, sbcErrorString(err));
    385344                        goto cancel;
    386345                }
     
    420379                                                     services[sidx]);
    421380                        if (!SBC_ERROR_IS_OK(err)) {
     381                                d_printf(_("error importing service %s: %s\n"),
     382                                         services[sidx]->name,
     383                                         sbcErrorString(err));
    422384                                goto cancel;
    423385                        }
     
    833795        value_str = argv[2];
    834796
     797        if (!net_conf_param_valid(service,param, value_str)) {
     798                goto done;
     799        }
     800
    835801        err = smbconf_transaction_start(conf_ctx);
    836802        if (!SBC_ERROR_IS_OK(err)) {
     
    11311097        err = smbconf_init(mem_ctx, &conf_ctx, "registry:");
    11321098        if (!SBC_ERROR_IS_OK(err)) {
     1099                talloc_free(mem_ctx);
    11331100                return -1;
    11341101        }
     
    11381105        smbconf_shutdown(conf_ctx);
    11391106
     1107        talloc_free(mem_ctx);
    11401108        return ret;
    11411109}
     
    11671135        if (argc != 0) {
    11681136                for (i=0; table[i].funcname; i++) {
    1169                         if (StrCaseCmp(argv[0], table[i].funcname) == 0)
     1137                        if (strcasecmp_m(argv[0], table[i].funcname) == 0)
    11701138                                return net_conf_wrap_function(c, table[i].fn,
    11711139                                                              argc-1,
     
    13001268                        NET_TRANSPORT_LOCAL,
    13011269                        N_("Delete includes from a share definition."),
    1302                         N_("net conf setincludes\n"
     1270                        N_("net conf delincludes\n"
    13031271                           "    Delete includes from a share definition.")
    13041272                },
  • vendor/current/source3/utils/net_dns.c

    r860 r988  
    193193
    194194                /* Don't register loopback addresses */
    195                 if (is_loopback_addr((struct sockaddr *)nic_sa_storage)) {
     195                if (is_loopback_addr((const struct sockaddr *)nic_sa_storage)) {
     196                        continue;
     197                }
     198
     199                /* Don't register link-local addresses */
     200                if (is_linklocal_addr(nic_sa_storage)) {
    196201                        continue;
    197202                }
     
    206211DNS_ERROR do_gethostbyname(const char *server, const char *host)
    207212{
    208         struct dns_connection *conn;
     213        struct dns_connection *conn = NULL;
    209214        struct dns_request *req, *resp;
    210215        DNS_ERROR err;
  • vendor/current/source3/utils/net_dom.c

    r740 r988  
    112112
    113113                ret = run_rpc_command(c, cli,
    114                                       &ndr_table_initshutdown.syntax_id,
     114                                      &ndr_table_initshutdown,
    115115                                      0, rpc_init_shutdown_internals,
    116116                                      argc, argv);
     
    119119                }
    120120
    121                 ret = run_rpc_command(c, cli, &ndr_table_winreg.syntax_id, 0,
     121                ret = run_rpc_command(c, cli, &ndr_table_winreg, 0,
    122122                                      rpc_reg_shutdown_internals,
    123123                                      argc, argv);
     
    218218                c->opt_timeout = 30;
    219219
    220                 ret = run_rpc_command(c, cli, &ndr_table_initshutdown.syntax_id, 0,
     220                ret = run_rpc_command(c, cli, &ndr_table_initshutdown, 0,
    221221                                      rpc_init_shutdown_internals,
    222222                                      argc, argv);
     
    225225                }
    226226
    227                 ret = run_rpc_command(c, cli, &ndr_table_winreg.syntax_id, 0,
     227                ret = run_rpc_command(c, cli, &ndr_table_winreg, 0,
    228228                                      rpc_reg_shutdown_internals,
    229229                                      argc, argv);
     
    315315
    316316                ret = run_rpc_command(c, cli,
    317                                       &ndr_table_initshutdown.syntax_id,
     317                                      &ndr_table_initshutdown,
    318318                                      0, rpc_init_shutdown_internals,
    319319                                      argc, argv);
     
    322322                }
    323323
    324                 ret = run_rpc_command(c, cli, &ndr_table_winreg.syntax_id, 0,
     324                ret = run_rpc_command(c, cli, &ndr_table_winreg, 0,
    325325                                      rpc_reg_shutdown_internals,
    326326                                      argc, argv);
  • vendor/current/source3/utils/net_file.c

    r414 r988  
    4545                return net_file_usage(c, argc, argv);
    4646
    47         if (StrCaseCmp(argv[0], "HELP") == 0) {
     47        if (strcasecmp_m(argv[0], "HELP") == 0) {
    4848                net_file_usage(c, argc, argv);
    4949                return 0;
  • vendor/current/source3/utils/net_g_lock.c

    r740 r988  
    3232        struct g_lock_ctx *g_ctx = NULL;
    3333
    34         ev = tevent_context_init(mem_ctx);
     34        ev = samba_tevent_context_init(mem_ctx);
    3535        if (ev == NULL) {
    3636                d_fprintf(stderr, "ERROR: could not init event context\n");
    3737                goto fail;
    3838        }
    39         msg = messaging_init(mem_ctx, procid_self(), ev);
     39        msg = messaging_init(mem_ctx, ev);
    4040        if (msg == NULL) {
    4141                d_fprintf(stderr, "ERROR: could not init messaging context\n");
     
    9292        status = g_lock_do(name, G_LOCK_WRITE,
    9393                           timeval_set(timeout / 1000, timeout % 1000),
    94                            procid_self(), net_g_lock_do_fn, &state);
     94                           net_g_lock_do_fn, &state);
    9595        if (!NT_STATUS_IS_OK(status)) {
    9696                d_fprintf(stderr, "ERROR: g_lock_do failed: %s\n",
     
    112112                              void *private_data)
    113113{
    114         char *pidstr;
    115 
    116         pidstr = procid_str(talloc_tos(), &pid);
    117         d_printf("%s: %s (%s)\n", pidstr,
    118                  (lock_type & 1) ? "WRITE" : "READ",
    119                  (lock_type & G_LOCK_PENDING) ? "pending" : "holder");
    120         TALLOC_FREE(pidstr);
     114        struct server_id_buf idbuf;
     115        d_printf("%s: %s\n", server_id_str_buf(pid, &idbuf),
     116                 (lock_type & 1) ? "WRITE" : "READ");
    121117        return 0;
    122118}
     
    127123        struct messaging_context *msg = NULL;
    128124        struct g_lock_ctx *g_ctx = NULL;
    129         NTSTATUS status;
    130125        int ret = -1;
    131126
     
    139134        }
    140135
    141         status = g_lock_dump(g_ctx, argv[0], net_g_lock_dump_fn, NULL);
     136        (void)g_lock_dump(g_ctx, argv[0], net_g_lock_dump_fn, NULL);
    142137
    143138        ret = 0;
     
    176171        TALLOC_FREE(msg);
    177172        TALLOC_FREE(ev);
    178         return ret;
     173        return ret < 0 ? -1 : ret;
    179174}
    180175
  • vendor/current/source3/utils/net_group.c

    r740 r988  
    5656                return net_group_usage(c, argc, argv);
    5757
    58         if (StrCaseCmp(argv[0], "HELP") == 0) {
     58        if (strcasecmp_m(argv[0], "HELP") == 0) {
    5959                net_group_usage(c, argc, argv);
    6060                return 0;
  • vendor/current/source3/utils/net_groupmap.c

    r746 r988  
    3434static bool get_sid_from_input(struct dom_sid *sid, char *input)
    3535{
    36         GROUP_MAP map;
    37 
    38         if (StrnCaseCmp( input, "S-", 2)) {
     36        GROUP_MAP *map;
     37
     38        map = talloc_zero(NULL, GROUP_MAP);
     39        if (!map) {
     40                return false;
     41        }
     42
     43        if (strncasecmp_m( input, "S-", 2)) {
    3944                /* Perhaps its the NT group name? */
    40                 if (!pdb_getgrnam(&map, input)) {
     45                if (!pdb_getgrnam(map, input)) {
    4146                        printf(_("NT Group %s doesn't exist in mapping DB\n"),
    4247                               input);
     48                        TALLOC_FREE(map);
    4349                        return false;
    4450                } else {
    45                         *sid = map.sid;
     51                        *sid = map->sid;
    4652                }
    4753        } else {
     
    4955                        printf(_("converting sid %s from a string failed!\n"),
    5056                               input);
     57                        TALLOC_FREE(map);
    5158                        return false;
    5259                }
    5360        }
     61        TALLOC_FREE(map);
    5462        return true;
    5563}
     
    5967**********************************************************/
    6068
    61 static void print_map_entry ( GROUP_MAP map, bool long_list )
     69static void print_map_entry (const GROUP_MAP *map, bool long_list)
    6270{
    6371        if (!long_list)
    64                 d_printf("%s (%s) -> %s\n", map.nt_name,
    65                          sid_string_tos(&map.sid), gidtoname(map.gid));
     72                d_printf("%s (%s) -> %s\n", map->nt_name,
     73                         sid_string_tos(&map->sid), gidtoname(map->gid));
    6674        else {
    67                 d_printf("%s\n", map.nt_name);
    68                 d_printf(_("\tSID       : %s\n"), sid_string_tos(&map.sid));
    69                 d_printf(_("\tUnix gid  : %u\n"), (unsigned int)map.gid);
    70                 d_printf(_("\tUnix group: %s\n"), gidtoname(map.gid));
     75                d_printf("%s\n", map->nt_name);
     76                d_printf(_("\tSID       : %s\n"), sid_string_tos(&map->sid));
     77                d_printf(_("\tUnix gid  : %u\n"), (unsigned int)map->gid);
     78                d_printf(_("\tUnix group: %s\n"), gidtoname(map->gid));
    7179                d_printf(_("\tGroup type: %s\n"),
    72                          sid_type_lookup(map.sid_name_use));
    73                 d_printf(_("\tComment   : %s\n"), map.comment);
     80                         sid_type_lookup(map->sid_name_use));
     81                d_printf(_("\tComment   : %s\n"), map->comment);
    7482        }
    7583
     
    101109        /* get the options */
    102110        for ( i=0; i<argc; i++ ) {
    103                 if ( !StrCaseCmp(argv[i], "verbose")) {
     111                if ( !strcasecmp_m(argv[i], "verbose")) {
    104112                        long_list = true;
    105113                }
    106                 else if ( !StrnCaseCmp(argv[i], "ntgroup", strlen("ntgroup")) ) {
     114                else if ( !strncasecmp_m(argv[i], "ntgroup", strlen("ntgroup")) ) {
    107115                        fstrcpy( ntgroup, get_string_param( argv[i] ) );
    108116                        if ( !ntgroup[0] ) {
     
    111119                        }
    112120                }
    113                 else if ( !StrnCaseCmp(argv[i], "sid", strlen("sid")) ) {
     121                else if ( !strncasecmp_m(argv[i], "sid", strlen("sid")) ) {
    114122                        fstrcpy( sid_string, get_string_param( argv[i] ) );
    115123                        if ( !sid_string[0] ) {
     
    128136        if ( ntgroup[0] || sid_string[0] ) {
    129137                struct dom_sid sid;
    130                 GROUP_MAP map;
     138                GROUP_MAP *map;
    131139
    132140                if ( sid_string[0] )
    133                         fstrcpy( ntgroup, sid_string);
     141                        strlcpy(ntgroup, sid_string, sizeof(ntgroup));
    134142
    135143                if (!get_sid_from_input(&sid, ntgroup)) {
     
    137145                }
    138146
     147                map = talloc_zero(NULL, GROUP_MAP);
     148                if (!map) {
     149                        return -1;
     150                }
     151
    139152                /* Get the current mapping from the database */
    140                 if(!pdb_getgrsid(&map, sid)) {
     153                if(!pdb_getgrsid(map, sid)) {
    141154                        d_fprintf(stderr,
    142155                                  _("Failure to local group SID in the "
    143156                                    "database\n"));
    144                         return -1;
    145                 }
    146 
    147                 print_map_entry( map, long_list );
     157                        TALLOC_FREE(map);
     158                        return -1;
     159                }
     160
     161                print_map_entry(map, long_list );
     162                TALLOC_FREE(map);
    148163        }
    149164        else {
    150                 GROUP_MAP *map=NULL;
     165                GROUP_MAP **maps = NULL;
     166                bool ok = false;
    151167                /* enumerate all group mappings */
    152                 if (!pdb_enum_group_mapping(NULL, SID_NAME_UNKNOWN, &map, &entries, ENUM_ALL_MAPPED))
    153                         return -1;
     168                ok = pdb_enum_group_mapping(NULL, SID_NAME_UNKNOWN,
     169                                            &maps, &entries,
     170                                            ENUM_ALL_MAPPED);
     171                if (!ok) {
     172                        return -1;
     173                }
    154174
    155175                for (i=0; i<entries; i++) {
    156                         print_map_entry( map[i], long_list );
    157                 }
    158 
    159                 SAFE_FREE(map);
     176                        print_map_entry(maps[i], long_list);
     177                }
     178
     179                TALLOC_FREE(maps);
    160180        }
    161181
     
    176196        fstring ntcomment = "";
    177197        enum lsa_SidType sid_type = SID_NAME_DOM_GRP;
    178         uint32 rid = 0;
     198        uint32_t rid = 0;
    179199        gid_t gid;
    180200        int i;
    181         GROUP_MAP map;
     201        GROUP_MAP *map;
    182202
    183203        const char *name_type;
     
    189209                                        "[comment=<string>]");
    190210
    191         ZERO_STRUCT(map);
    192 
    193         /* Default is domain group. */
    194         map.sid_name_use = SID_NAME_DOM_GRP;
    195211        name_type = "domain group";
    196212
     
    202218        /* get the options */
    203219        for ( i=0; i<argc; i++ ) {
    204                 if ( !StrnCaseCmp(argv[i], "rid", strlen("rid")) ) {
     220                if ( !strncasecmp_m(argv[i], "rid", strlen("rid")) ) {
    205221                        rid = get_int_param(argv[i]);
    206222                        if ( rid < DOMAIN_RID_ADMINS ) {
    207223                                d_fprintf(stderr,
    208224                                          _("RID must be greater than %d\n"),
    209                                           (uint32)DOMAIN_RID_ADMINS-1);
    210                                 return -1;
    211                         }
    212                 }
    213                 else if ( !StrnCaseCmp(argv[i], "unixgroup", strlen("unixgroup")) ) {
     225                                          (uint32_t)DOMAIN_RID_ADMINS-1);
     226                                return -1;
     227                        }
     228                }
     229                else if ( !strncasecmp_m(argv[i], "unixgroup", strlen("unixgroup")) ) {
    214230                        fstrcpy( unixgrp, get_string_param( argv[i] ) );
    215231                        if ( !unixgrp[0] ) {
     
    218234                        }
    219235                }
    220                 else if ( !StrnCaseCmp(argv[i], "ntgroup", strlen("ntgroup")) ) {
     236                else if ( !strncasecmp_m(argv[i], "ntgroup", strlen("ntgroup")) ) {
    221237                        fstrcpy( ntgroup, get_string_param( argv[i] ) );
    222238                        if ( !ntgroup[0] ) {
     
    225241                        }
    226242                }
    227                 else if ( !StrnCaseCmp(argv[i], "sid", strlen("sid")) ) {
     243                else if ( !strncasecmp_m(argv[i], "sid", strlen("sid")) ) {
    228244                        fstrcpy( string_sid, get_string_param( argv[i] ) );
    229245                        if ( !string_sid[0] ) {
     
    232248                        }
    233249                }
    234                 else if ( !StrnCaseCmp(argv[i], "comment", strlen("comment")) ) {
     250                else if ( !strncasecmp_m(argv[i], "comment", strlen("comment")) ) {
    235251                        fstrcpy( ntcomment, get_string_param( argv[i] ) );
    236252                        if ( !ntcomment[0] ) {
     
    240256                        }
    241257                }
    242                 else if ( !StrnCaseCmp(argv[i], "type", strlen("type")) )  {
     258                else if ( !strncasecmp_m(argv[i], "type", strlen("type")) )  {
    243259                        fstrcpy( type, get_string_param( argv[i] ) );
    244260                        switch ( type[0] ) {
     
    281297        }
    282298
    283         {
    284                 if (pdb_getgrgid(&map, gid)) {
    285                         d_printf(_("Unix group %s already mapped to SID %s\n"),
    286                                  unixgrp, sid_string_tos(&map.sid));
    287                         return -1;
    288                 }
    289         }
     299        map = talloc_zero(NULL, GROUP_MAP);
     300        if (!map) {
     301                return -1;
     302        }
     303        /* Default is domain group. */
     304        map->sid_name_use = SID_NAME_DOM_GRP;
     305        if (pdb_getgrgid(map, gid)) {
     306                d_printf(_("Unix group %s already mapped to SID %s\n"),
     307                         unixgrp, sid_string_tos(&map->sid));
     308                TALLOC_FREE(map);
     309                return -1;
     310        }
     311        TALLOC_FREE(map);
    290312
    291313        if ( (rid == 0) && (string_sid[0] == '\0') ) {
     
    325347
    326348        if (!ntgroup[0] )
    327                 fstrcpy( ntgroup, unixgrp );
     349                strlcpy(ntgroup, unixgrp, sizeof(ntgroup));
    328350
    329351        if (!NT_STATUS_IS_OK(add_initial_entry(gid, string_sid, sid_type, ntgroup, ntcomment))) {
     
    340362{
    341363        struct dom_sid sid;
    342         GROUP_MAP map;
     364        GROUP_MAP *map = NULL;
    343365        fstring ntcomment = "";
    344366        fstring type = "";
     
    362384        /* get the options */
    363385        for ( i=0; i<argc; i++ ) {
    364                 if ( !StrnCaseCmp(argv[i], "ntgroup", strlen("ntgroup")) ) {
     386                if ( !strncasecmp_m(argv[i], "ntgroup", strlen("ntgroup")) ) {
    365387                        fstrcpy( ntgroup, get_string_param( argv[i] ) );
    366388                        if ( !ntgroup[0] ) {
     
    369391                        }
    370392                }
    371                 else if ( !StrnCaseCmp(argv[i], "sid", strlen("sid")) ) {
     393                else if ( !strncasecmp_m(argv[i], "sid", strlen("sid")) ) {
    372394                        fstrcpy( sid_string, get_string_param( argv[i] ) );
    373395                        if ( !sid_string[0] ) {
     
    376398                        }
    377399                }
    378                 else if ( !StrnCaseCmp(argv[i], "comment", strlen("comment")) ) {
     400                else if ( !strncasecmp_m(argv[i], "comment", strlen("comment")) ) {
    379401                        fstrcpy( ntcomment, get_string_param( argv[i] ) );
    380402                        if ( !ntcomment[0] ) {
     
    384406                        }
    385407                }
    386                 else if ( !StrnCaseCmp(argv[i], "unixgroup", strlen("unixgroup")) ) {
     408                else if ( !strncasecmp_m(argv[i], "unixgroup", strlen("unixgroup")) ) {
    387409                        fstrcpy( unixgrp, get_string_param( argv[i] ) );
    388410                        if ( !unixgrp[0] ) {
     
    392414                        }
    393415                }
    394                 else if ( !StrnCaseCmp(argv[i], "type", strlen("type")) )  {
     416                else if ( !strncasecmp_m(argv[i], "type", strlen("type")) )  {
    395417                        fstrcpy( type, get_string_param( argv[i] ) );
    396418                        switch ( type[0] ) {
     
    431453        }
    432454
     455        map = talloc_zero(NULL, GROUP_MAP);
     456        if (!map) {
     457                return -1;
     458        }
     459
    433460        /* Get the current mapping from the database */
    434         if(!pdb_getgrsid(&map, sid)) {
     461        if(!pdb_getgrsid(map, sid)) {
    435462                d_fprintf(stderr,
    436463                         _("Failed to find local group SID in the database\n"));
     464                TALLOC_FREE(map);
    437465                return -1;
    438466        }
     
    444472        if (sid_type == SID_NAME_UNKNOWN) {
    445473                d_fprintf(stderr, _("Can't map to an unknown group type.\n"));
     474                TALLOC_FREE(map);
    446475                return -1;
    447476        }
    448477
    449         if (map.sid_name_use == SID_NAME_WKN_GRP) {
     478        if (map->sid_name_use == SID_NAME_WKN_GRP) {
    450479                d_fprintf(stderr,
    451480                          _("You can only change between domain and local "
    452481                            "groups.\n"));
    453                 return -1;
    454         }
    455 
    456         map.sid_name_use=sid_type;
     482                TALLOC_FREE(map);
     483                return -1;
     484        }
     485
     486        map->sid_name_use = sid_type;
    457487
    458488        /* Change comment if new one */
    459         if ( ntcomment[0] )
    460                 fstrcpy( map.comment, ntcomment );
    461 
    462         if ( ntgroup[0] )
    463                 fstrcpy( map.nt_name, ntgroup );
     489        if (ntcomment[0]) {
     490                map->comment = talloc_strdup(map, ntcomment);
     491                if (!map->comment) {
     492                        d_fprintf(stderr, _("Out of memory!\n"));
     493                        return -1;
     494                }
     495        }
     496
     497        if (ntgroup[0]) {
     498                map->nt_name = talloc_strdup(map, ntgroup);
     499                if (!map->nt_name) {
     500                        d_fprintf(stderr, _("Out of memory!\n"));
     501                        return -1;
     502                }
     503        }
    464504
    465505        if ( unixgrp[0] ) {
     
    469509                                            "Make sure the group exists.\n"),
    470510                                unixgrp);
    471                         return -1;
    472                 }
    473 
    474                 map.gid = gid;
    475         }
    476 
    477         if ( !NT_STATUS_IS_OK(pdb_update_group_mapping_entry(&map)) ) {
     511                        TALLOC_FREE(map);
     512                        return -1;
     513                }
     514
     515                map->gid = gid;
     516        }
     517
     518        if (!NT_STATUS_IS_OK(pdb_update_group_mapping_entry(map))) {
    478519                d_fprintf(stderr, _("Could not update group database\n"));
    479                 return -1;
    480         }
    481 
    482         d_printf(_("Updated mapping entry for %s\n"), map.nt_name);
    483 
     520                TALLOC_FREE(map);
     521                return -1;
     522        }
     523
     524        d_printf(_("Updated mapping entry for %s\n"), map->nt_name);
     525
     526        TALLOC_FREE(map);
    484527        return 0;
    485528}
     
    501544        /* get the options */
    502545        for ( i=0; i<argc; i++ ) {
    503                 if ( !StrnCaseCmp(argv[i], "ntgroup", strlen("ntgroup")) ) {
     546                if ( !strncasecmp_m(argv[i], "ntgroup", strlen("ntgroup")) ) {
    504547                        fstrcpy( ntgroup, get_string_param( argv[i] ) );
    505548                        if ( !ntgroup[0] ) {
     
    508551                        }
    509552                }
    510                 else if ( !StrnCaseCmp(argv[i], "sid", strlen("sid")) ) {
     553                else if ( !strncasecmp_m(argv[i], "sid", strlen("sid")) ) {
    511554                        fstrcpy( sid_string, get_string_param( argv[i] ) );
    512555                        if ( !sid_string[0] ) {
     
    529572
    530573        if ( sid_string[0] )
    531                 fstrcpy( ntgroup, sid_string );
     574                strlcpy(ntgroup, sid_string, sizeof(ntgroup));
    532575
    533576        if ( !get_sid_from_input(&sid, ntgroup) ) {
     
    544587        }
    545588
    546         d_printf(_("Sucessfully removed %s from the mapping db\n"), ntgroup);
     589        d_printf(_("Successfully removed %s from the mapping db\n"), ntgroup);
    547590
    548591        return 0;
     
    553596        const char *ntgroup = NULL;
    554597        struct group *grp = NULL;
    555         GROUP_MAP map;
     598        GROUP_MAP *map;
    556599        bool have_map = false;
    557600
     
    581624        }
    582625
    583         have_map = pdb_getgrnam(&map, ntgroup);
     626        map = talloc_zero(NULL, GROUP_MAP);
     627        if (!map) {
     628                d_printf(_("Out of memory!\n"));
     629                return -1;
     630        }
     631
     632        have_map = pdb_getgrnam(map, ntgroup);
    584633
    585634        if (!have_map) {
     
    587636                have_map = ( (strncmp(ntgroup, "S-", 2) == 0) &&
    588637                             string_to_sid(&sid, ntgroup) &&
    589                              pdb_getgrsid(&map, sid) );
     638                             pdb_getgrsid(map, sid) );
    590639        }
    591640
     
    598647                                  _("Could not find group mapping for %s\n"),
    599648                                  ntgroup);
    600                         return -1;
    601                 }
    602 
    603                 map.gid = grp->gr_gid;
     649                        TALLOC_FREE(map);
     650                        return -1;
     651                }
     652
     653                map->gid = grp->gr_gid;
    604654
    605655                if (c->opt_rid == 0) {
    606656                        if ( pdb_capabilities() & PDB_CAP_STORE_RIDS ) {
    607                                 if ( !pdb_new_rid((uint32*)&c->opt_rid) ) {
     657                                if ( !pdb_new_rid((uint32_t *)&c->opt_rid) ) {
    608658                                        d_fprintf( stderr,
    609659                                            _("Could not allocate new RID\n"));
     660                                        TALLOC_FREE(map);
    610661                                        return -1;
    611662                                }
    612663                        } else {
    613                                 c->opt_rid = algorithmic_pdb_gid_to_group_rid(map.gid);
    614                         }
    615                 }
    616 
    617                 sid_compose(&map.sid, get_global_sam_sid(), c->opt_rid);
    618 
    619                 map.sid_name_use = SID_NAME_DOM_GRP;
    620                 fstrcpy(map.nt_name, ntgroup);
    621                 fstrcpy(map.comment, "");
    622 
    623                 if (!NT_STATUS_IS_OK(pdb_add_group_mapping_entry(&map))) {
     664                                c->opt_rid = algorithmic_pdb_gid_to_group_rid(map->gid);
     665                        }
     666                }
     667
     668                sid_compose(&map->sid, get_global_sam_sid(), c->opt_rid);
     669
     670                map->sid_name_use = SID_NAME_DOM_GRP;
     671                map->nt_name = talloc_strdup(map, ntgroup);
     672                map->comment = talloc_strdup(map, "");
     673                if (!map->nt_name || !map->comment) {
     674                        d_printf(_("Out of memory!\n"));
     675                        TALLOC_FREE(map);
     676                        return -1;
     677                }
     678
     679                if (!NT_STATUS_IS_OK(pdb_add_group_mapping_entry(map))) {
    624680                        d_fprintf(stderr,
    625681                                  _("Could not add mapping entry for %s\n"),
    626682                                  ntgroup);
     683                        TALLOC_FREE(map);
    627684                        return -1;
    628685                }
     
    632689
    633690        if ( c->opt_localgroup || c->opt_domaingroup ) {
    634                 if (map.sid_name_use == SID_NAME_WKN_GRP) {
     691                if (map->sid_name_use == SID_NAME_WKN_GRP) {
    635692                        d_fprintf(stderr,
    636693                                  _("Can't change type of the BUILTIN "
    637694                                    "group %s\n"),
    638                                   map.nt_name);
     695                                  map->nt_name);
     696                        TALLOC_FREE(map);
    639697                        return -1;
    640698                }
     
    642700
    643701        if (c->opt_localgroup)
    644                 map.sid_name_use = SID_NAME_ALIAS;
     702                map->sid_name_use = SID_NAME_ALIAS;
    645703
    646704        if (c->opt_domaingroup)
    647                 map.sid_name_use = SID_NAME_DOM_GRP;
     705                map->sid_name_use = SID_NAME_DOM_GRP;
    648706
    649707        /* The case (opt_domaingroup && opt_localgroup) was tested for above */
    650708
    651709        if ((c->opt_comment != NULL) && (strlen(c->opt_comment) > 0)) {
    652                 fstrcpy(map.comment, c->opt_comment);
     710                map->comment = talloc_strdup(map, c->opt_comment);
     711                if (!map->comment) {
     712                        d_printf(_("Out of memory!\n"));
     713                        TALLOC_FREE(map);
     714                        return -1;
     715                }
    653716        }
    654717
    655718        if ((c->opt_newntname != NULL) && (strlen(c->opt_newntname) > 0)) {
    656                 fstrcpy(map.nt_name, c->opt_newntname);
     719                map->nt_name = talloc_strdup(map, c->opt_newntname);
     720                if (!map->nt_name) {
     721                        d_printf(_("Out of memory!\n"));
     722                        TALLOC_FREE(map);
     723                        return -1;
     724                }
    657725        }
    658726
    659727        if (grp != NULL)
    660                 map.gid = grp->gr_gid;
    661 
    662         if (!NT_STATUS_IS_OK(pdb_update_group_mapping_entry(&map))) {
     728                map->gid = grp->gr_gid;
     729
     730        if (!NT_STATUS_IS_OK(pdb_update_group_mapping_entry(map))) {
    663731                d_fprintf(stderr, _("Could not update group mapping for %s\n"),
    664732                          ntgroup);
    665                 return -1;
    666         }
    667 
     733                TALLOC_FREE(map);
     734                return -1;
     735        }
     736
     737        TALLOC_FREE(map);
    668738        return 0;
    669739}
     
    671741static int net_groupmap_cleanup(struct net_context *c, int argc, const char **argv)
    672742{
    673         GROUP_MAP *map = NULL;
     743        GROUP_MAP **maps = NULL;
    674744        size_t i, entries;
    675745
     
    683753        }
    684754
    685         if (!pdb_enum_group_mapping(NULL, SID_NAME_UNKNOWN, &map, &entries,
     755        if (!pdb_enum_group_mapping(NULL, SID_NAME_UNKNOWN, &maps, &entries,
    686756                                    ENUM_ALL_MAPPED)) {
    687757                d_fprintf(stderr, _("Could not list group mappings\n"));
     
    691761        for (i=0; i<entries; i++) {
    692762
    693                 if (map[i].gid == -1)
    694                         printf(_("Group %s is not mapped\n"), map[i].nt_name);
    695 
    696                 if (!sid_check_is_in_our_domain(&map[i].sid)) {
     763                if (maps[i]->gid == -1)
     764                        printf(_("Group %s is not mapped\n"),
     765                                maps[i]->nt_name);
     766
     767                if (!sid_check_is_in_our_sam(&maps[i]->sid)) {
    697768                        printf(_("Deleting mapping for NT Group %s, sid %s\n"),
    698                                map[i].nt_name,
    699                                sid_string_tos(&map[i].sid));
    700                         pdb_delete_group_mapping_entry(map[i].sid);
    701                 }
    702         }
    703 
    704         SAFE_FREE(map);
    705 
     769                                maps[i]->nt_name,
     770                                sid_string_tos(&maps[i]->sid));
     771                        pdb_delete_group_mapping_entry(maps[i]->sid);
     772                }
     773        }
     774
     775        TALLOC_FREE(maps);
    706776        return 0;
    707777}
     
    791861                                    const struct dom_sid *member)
    792862{
    793         uint32 *alias_rids;
     863        uint32_t *alias_rids;
    794864        size_t i, num_alias_rids;
    795865
  • vendor/current/source3/utils/net_help.c

    r414 r988  
    6161        }
    6262
    63         if (StrCaseCmp(argv[0], "help") == 0) {
     63        if (strcasecmp_m(argv[0], "help") == 0) {
    6464                return net_help_usage(c, argc, argv);
    6565        }
  • vendor/current/source3/utils/net_idmap.c

    r740 r988  
    2323#include "secrets.h"
    2424#include "idmap.h"
    25 #include "dbwrap.h"
     25#include "dbwrap/dbwrap.h"
     26#include "dbwrap/dbwrap_open.h"
    2627#include "../libcli/security/security.h"
    2728#include "net_idmap_check.h"
    2829#include "util_tdb.h"
     30#include "idmap_autorid_tdb.h"
    2931
    3032#define ALLOC_CHECK(mem) do { \
     
    3537        } } while(0)
    3638
     39enum idmap_dump_backend {
     40        TDB,
     41        AUTORID
     42};
     43
     44struct net_idmap_ctx {
     45        enum idmap_dump_backend backend;
     46};
     47
     48static int net_idmap_dump_one_autorid_entry(struct db_record *rec,
     49                                            void *unused)
     50{
     51        TDB_DATA key;
     52        TDB_DATA value;
     53
     54        key = dbwrap_record_get_key(rec);
     55        value = dbwrap_record_get_value(rec);
     56
     57        if (strncmp((char *)key.dptr, "CONFIG", 6) == 0) {
     58                char *config = talloc_array(talloc_tos(), char, value.dsize+1);
     59                memcpy(config, value.dptr, value.dsize);
     60                config[value.dsize] = '\0';
     61                printf("CONFIG: %s\n", config);
     62                talloc_free(config);
     63                return 0;
     64        }
     65
     66        if (strncmp((char *)key.dptr, "NEXT RANGE", 10) == 0) {
     67                printf("RANGE HWM: %"PRIu32"\n", IVAL(value.dptr, 0));
     68                return 0;
     69        }
     70
     71        if (strncmp((char *)key.dptr, "NEXT ALLOC UID", 14) == 0) {
     72                printf("UID HWM: %"PRIu32"\n", IVAL(value.dptr, 0));
     73                return 0;
     74        }
     75
     76        if (strncmp((char *)key.dptr, "NEXT ALLOC GID", 14) == 0) {
     77                printf("GID HWM: %"PRIu32"\n", IVAL(value.dptr, 0));
     78                return 0;
     79        }
     80
     81        if (strncmp((char *)key.dptr, "UID", 3) == 0 ||
     82            strncmp((char *)key.dptr, "GID", 3) == 0)
     83        {
     84                /* mapped entry from allocation pool */
     85                printf("%s %s\n", value.dptr, key.dptr);
     86                return 0;
     87        }
     88
     89        if ((strncmp((char *)key.dptr, "S-1-5-", 6) == 0 ||
     90             strncmp((char *)key.dptr, "ALLOC", 5) == 0) &&
     91            value.dsize == sizeof(uint32_t))
     92        {
     93                /* this is a domain range assignment */
     94                uint32_t range = IVAL(value.dptr, 0);
     95                printf("RANGE %"PRIu32": %s\n", range, key.dptr);
     96                return 0;
     97        }
     98
     99        return 0;
     100}
     101
    37102/***********************************************************
    38103 Helper function for net_idmap_dump. Dump one entry.
    39104 **********************************************************/
    40 static int net_idmap_dump_one_entry(struct db_record *rec,
    41                                     void *unused)
    42 {
    43         if (strcmp((char *)rec->key.dptr, "USER HWM") == 0) {
    44                 printf(_("USER HWM %d\n"), IVAL(rec->value.dptr,0));
     105static int net_idmap_dump_one_tdb_entry(struct db_record *rec,
     106                                        void *unused)
     107{
     108        TDB_DATA key;
     109        TDB_DATA value;
     110
     111        key = dbwrap_record_get_key(rec);
     112        value = dbwrap_record_get_value(rec);
     113
     114        if (strcmp((char *)key.dptr, "USER HWM") == 0) {
     115                printf(_("USER HWM %d\n"), IVAL(value.dptr,0));
    45116                return 0;
    46117        }
    47118
    48         if (strcmp((char *)rec->key.dptr, "GROUP HWM") == 0) {
    49                 printf(_("GROUP HWM %d\n"), IVAL(rec->value.dptr,0));
     119        if (strcmp((char *)key.dptr, "GROUP HWM") == 0) {
     120                printf(_("GROUP HWM %d\n"), IVAL(value.dptr,0));
    50121                return 0;
    51122        }
    52123
    53         if (strncmp((char *)rec->key.dptr, "S-", 2) != 0)
     124        if (strncmp((char *)key.dptr, "S-", 2) != 0) {
    54125                return 0;
    55 
    56         printf("%s %s\n", rec->value.dptr, rec->key.dptr);
     126        }
     127
     128        printf("%s %s\n", value.dptr, key.dptr);
    57129        return 0;
    58130}
    59131
    60 static const char* net_idmap_dbfile(struct net_context *c)
    61 {
    62         const char* dbfile = NULL;
     132/* returns db path for idmap backend alloced on talloc_tos */
     133static char *net_idmap_dbfile(struct net_context *c,
     134                              struct net_idmap_ctx *ctx)
     135{
     136        char *dbfile = NULL;
     137        const char *backend = NULL;
     138
     139        backend = lp_idmap_default_backend();
     140        if (!backend) {
     141                d_printf(_("Internal error: 'idmap config * : backend' is not set!\n"));
     142                return NULL;
     143        }
    63144
    64145        if (c->opt_db != NULL) {
     
    67148                        d_fprintf(stderr, _("Out of memory!\n"));
    68149                }
    69         } else if (strequal(lp_idmap_backend(), "tdb")) {
     150        } else if (strequal(backend, "tdb")) {
    70151                dbfile = state_path("winbindd_idmap.tdb");
    71152                if (dbfile == NULL) {
    72153                        d_fprintf(stderr, _("Out of memory!\n"));
    73154                }
    74         } else if (strequal(lp_idmap_backend(), "tdb2")) {
    75                 dbfile = lp_parm_talloc_string(-1, "tdb", "idmap2.tdb", NULL);
    76                 if (dbfile == NULL) {
    77                         dbfile = talloc_asprintf(talloc_tos(), "%s/idmap2.tdb",
    78                                                  lp_private_dir());
    79                 }
     155                ctx->backend = TDB;
     156        } else if (strequal(backend, "tdb2")) {
     157                dbfile = talloc_asprintf(talloc_tos(), "%s/idmap2.tdb",
     158                                         lp_private_dir());
    80159                if (dbfile == NULL) {
    81160                        d_fprintf(stderr, _("Out of memory!\n"));
    82161                }
     162                ctx->backend = TDB;
     163        } else if (strequal(backend, "autorid")) {
     164                dbfile = state_path("autorid.tdb");
     165                if (dbfile == NULL) {
     166                        d_fprintf(stderr, _("Out of memory!\n"));
     167                }
     168                ctx->backend = AUTORID;
    83169        } else {
    84                 char* backend = talloc_strdup(talloc_tos(), lp_idmap_backend());
    85                 char* args = strchr(backend, ':');
     170                char *_backend = talloc_strdup(talloc_tos(), backend);
     171                char* args = strchr(_backend, ':');
    86172                if (args != NULL) {
    87173                        *args = '\0';
     
    89175
    90176                d_printf(_("Sorry, 'idmap backend = %s' is currently not supported\n"),
    91                          backend);
    92 
    93                 talloc_free(backend);
     177                           _backend);
     178
     179                talloc_free(_backend);
    94180        }
    95181
    96182        return dbfile;
    97183}
     184
     185static bool net_idmap_opendb_autorid(TALLOC_CTX *mem_ctx,
     186                                     struct net_context *c,
     187                                     bool readonly,
     188                                     struct db_context **db)
     189{
     190        bool ret = false;
     191        char *dbfile = NULL;
     192        struct net_idmap_ctx ctx = { .backend = AUTORID };
     193
     194        if (c == NULL) {
     195                goto done;
     196        }
     197
     198        dbfile = net_idmap_dbfile(c, &ctx);
     199        if (dbfile == NULL) {
     200                goto done;
     201        }
     202
     203        if (ctx.backend != AUTORID) {
     204                d_fprintf(stderr, _("Unsupported backend\n"));
     205                goto done;
     206        }
     207
     208        if (readonly) {
     209                *db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDONLY, 0,
     210                             DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
     211                if (*db == NULL) {
     212                        d_fprintf(stderr,
     213                                  _("Could not open autorid db (%s): %s\n"),
     214                                 dbfile, strerror(errno));
     215                        goto done;
     216                }
     217        } else {
     218                NTSTATUS status;
     219                status = idmap_autorid_db_init(dbfile, mem_ctx, db);
     220                if (!NT_STATUS_IS_OK(status)) {
     221                        d_fprintf(stderr,
     222                                _("Error calling idmap_autorid_db_init: %s\n"),
     223                                nt_errstr(status));
     224                        goto done;
     225                }
     226        }
     227
     228        ret = true;
     229
     230done:
     231        talloc_free(dbfile);
     232        return ret;
     233}
     234
    98235
    99236/***********************************************************
     
    105242        TALLOC_CTX *mem_ctx;
    106243        const char* dbfile;
     244        NTSTATUS status;
    107245        int ret = -1;
     246        struct net_idmap_ctx ctx = { .backend = TDB };
    108247
    109248        if ( argc > 1  || c->display_usage) {
     
    118257        mem_ctx = talloc_stackframe();
    119258
    120         dbfile = (argc > 0) ? argv[0] : net_idmap_dbfile(c);
     259        dbfile = (argc > 0) ? argv[0] : net_idmap_dbfile(c, &ctx);
    121260        if (dbfile == NULL) {
    122261                goto done;
     
    124263        d_fprintf(stderr, _("dumping id mapping from %s\n"), dbfile);
    125264
    126         db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDONLY, 0);
     265        db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDONLY, 0,
     266                     DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
    127267        if (db == NULL) {
    128268                d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
     
    131271        }
    132272
    133         db->traverse_read(db, net_idmap_dump_one_entry, NULL);
     273        if (ctx.backend == AUTORID) {
     274                status = dbwrap_traverse_read(db,
     275                                              net_idmap_dump_one_autorid_entry,
     276                                              NULL, NULL);
     277        } else {
     278                status = dbwrap_traverse_read(db,
     279                                              net_idmap_dump_one_tdb_entry,
     280                                              NULL, NULL);
     281        }
     282        if (!NT_STATUS_IS_OK(status)) {
     283                d_fprintf(stderr, _("error traversing the database\n"));
     284                ret = -1;
     285                goto done;
     286        }
     287
    134288        ret = 0;
    135289
     
    192346        const char *dbfile = NULL;
    193347        int ret = 0;
     348        struct net_idmap_ctx ctx = { .backend = TDB };
    194349
    195350        if (c->display_usage) {
     
    206361        mem_ctx = talloc_stackframe();
    207362
    208         dbfile = net_idmap_dbfile(c);
     363        dbfile = net_idmap_dbfile(c, &ctx);
    209364
    210365        if (dbfile == NULL) {
     366                ret = -1;
     367                goto done;
     368        }
     369
     370        if (ctx.backend != TDB) {
     371                d_fprintf(stderr, _("Sorry, restoring of non-TDB databases is "
     372                                    "currently not supported\n"));
    211373                ret = -1;
    212374                goto done;
     
    227389        }
    228390
    229         db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0644);
     391        db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0644,
     392                     DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
    230393        if (db == NULL) {
    231394                d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
     
    235398        }
    236399
    237         if (db->transaction_start(db) != 0) {
     400        if (dbwrap_transaction_start(db) != 0) {
    238401                d_fprintf(stderr, _("Failed to start transaction.\n"));
    239402                ret = -1;
     
    245408                int len;
    246409                unsigned long idval;
     410                NTSTATUS status;
    247411
    248412                if (fgets(line, 127, input) == NULL)
     
    269433                        }
    270434                } else if (sscanf(line, "USER HWM %lu", &idval) == 1) {
    271                         ret = dbwrap_store_int32(db, "USER HWM", idval);
    272                         if (ret != 0) {
    273                                 d_fprintf(stderr, _("Could not store USER HWM.\n"));
     435                        status = dbwrap_store_int32_bystring(
     436                                db, "USER HWM", idval);
     437                        if (!NT_STATUS_IS_OK(status)) {
     438                                d_fprintf(stderr,
     439                                          _("Could not store USER HWM: %s\n"),
     440                                          nt_errstr(status));
    274441                                break;
    275442                        }
    276443                } else if (sscanf(line, "GROUP HWM %lu", &idval) == 1) {
    277                         ret = dbwrap_store_int32(db, "GROUP HWM", idval);
    278                         if (ret != 0) {
     444                        status = dbwrap_store_int32_bystring(
     445                                db, "GROUP HWM", idval);
     446                        if (!NT_STATUS_IS_OK(status)) {
    279447                                d_fprintf(stderr,
    280                                           _("Could not store GROUP HWM.\n"));
     448                                          _("Could not store GROUP HWM: %s\n"),
     449                                          nt_errstr(status));
    281450                                break;
    282451                        }
     
    289458
    290459        if (ret == 0) {
    291                 if(db->transaction_commit(db) != 0) {
     460                if(dbwrap_transaction_commit(db) != 0) {
    292461                        d_fprintf(stderr, _("Failed to commit transaction.\n"));
    293462                        ret = -1;
    294463                }
    295464        } else {
    296                 if (db->transaction_cancel(db) != 0) {
     465                if (dbwrap_transaction_cancel(db) != 0) {
    297466                        d_fprintf(stderr, _("Failed to cancel transaction.\n"));
    298467                }
     
    311480NTSTATUS dbwrap_delete_mapping(struct db_context *db, TDB_DATA key1, bool force)
    312481{
    313         TALLOC_CTX* mem_ctx = talloc_tos();
    314         struct db_record *rec1=NULL, *rec2=NULL;
    315         TDB_DATA key2;
     482        TALLOC_CTX *mem_ctx = talloc_stackframe();
    316483        bool is_valid_mapping;
    317484        NTSTATUS status = NT_STATUS_OK;
    318 
    319         rec1 = db->fetch_locked(db, mem_ctx, key1);
    320         if (rec1 == NULL) {
     485        TDB_DATA val1, val2;
     486
     487        ZERO_STRUCT(val1);
     488        ZERO_STRUCT(val2);
     489
     490        status = dbwrap_fetch(db, mem_ctx, key1, &val1);
     491        if (!NT_STATUS_IS_OK(status)) {
    321492                DEBUG(1, ("failed to fetch: %.*s\n", (int)key1.dsize, key1.dptr));
    322                 status = NT_STATUS_NO_MEMORY;
    323                 goto done;
    324         }
    325         key2 = rec1->value;
    326         if (key2.dptr == NULL) {
    327                 DEBUG(1, ("could not find %.*s\n", (int)key1.dsize, key1.dptr));
    328                 status = NT_STATUS_NOT_FOUND;
     493                goto done;
     494        }
     495
     496        if (val1.dptr == NULL) {
     497                DEBUG(1, ("invalid mapping: %.*s -> empty value\n",
     498                          (int)key1.dsize, key1.dptr));
     499                status = NT_STATUS_FILE_INVALID;
    329500                goto done;
    330501        }
    331502
    332503        DEBUG(2, ("mapping: %.*s -> %.*s\n",
    333                   (int)key1.dsize, key1.dptr, (int)key2.dsize, key2.dptr));
    334 
    335         rec2 = db->fetch_locked(db, mem_ctx, key2);
    336         if (rec2 == NULL) {
    337                 DEBUG(1, ("failed to fetch: %.*s\n", (int)key2.dsize, key2.dptr));
    338                 status = NT_STATUS_NO_MEMORY;
    339                 goto done;
    340         }
    341 
    342         is_valid_mapping = tdb_data_equal(key1, rec2->value);
     504                  (int)key1.dsize, key1.dptr, (int)val1.dsize, val1.dptr));
     505
     506        status = dbwrap_fetch(db, mem_ctx, val1, &val2);
     507        if (!NT_STATUS_IS_OK(status)) {
     508                DEBUG(1, ("failed to fetch: %.*s\n", (int)val1.dsize, val1.dptr));
     509                goto done;
     510        }
     511
     512        is_valid_mapping = tdb_data_equal(key1, val2);
    343513
    344514        if (!is_valid_mapping) {
    345515                DEBUG(1, ("invalid mapping: %.*s -> %.*s -> %.*s\n",
    346                           (int)key1.dsize, key1.dptr, (int)key2.dsize, key2.dptr,
    347                           (int)rec2->value.dsize, rec2->value.dptr ));
     516                          (int)key1.dsize, key1.dptr,
     517                          (int)val1.dsize, val1.dptr,
     518                          (int)val2.dsize, val2.dptr));
    348519                if ( !force ) {
    349520                        status = NT_STATUS_FILE_INVALID;
     
    352523        }
    353524
    354         status = rec1->delete_rec(rec1);
     525        status = dbwrap_delete(db, key1);
    355526        if (!NT_STATUS_IS_OK(status)) {
    356527                DEBUG(1, ("failed to delete: %.*s\n", (int)key1.dsize, key1.dptr));
     
    358529        }
    359530
    360         if (is_valid_mapping) {
    361                 status = rec2->delete_rec(rec2);
    362                 if (!NT_STATUS_IS_OK(status)) {
    363                         DEBUG(1, ("failed to delete: %.*s\n", (int)key2.dsize, key2.dptr));
    364                 }
    365         }
     531        if (!is_valid_mapping) {
     532                goto done;
     533        }
     534
     535        status = dbwrap_delete(db, val1);
     536        if (!NT_STATUS_IS_OK(status)) {
     537                DEBUG(1, ("failed to delete: %.*s\n", (int)val1.dsize, val1.dptr));
     538        }
     539
    366540done:
    367         TALLOC_FREE(rec1);
    368         TALLOC_FREE(rec2);
     541        talloc_free(mem_ctx);
    369542        return status;
    370543}
     
    397570}
    398571
    399 static int net_idmap_delete(struct net_context *c, int argc, const char **argv)
     572static int net_idmap_delete_mapping(struct net_context *c, int argc,
     573                                    const char **argv)
    400574{
    401575        int ret = -1;
     
    405579        NTSTATUS status;
    406580        const char* dbfile;
     581        struct net_idmap_ctx ctx = { .backend = TDB };
    407582
    408583        if ( !delete_args_ok(argc,argv) || c->display_usage) {
    409584                d_printf("%s\n%s",
    410585                         _("Usage:"),
    411                          _("net idmap delete [-f] [--db=<TDB>] <ID>\n"
     586                         _("net idmap delete mapping [-f] [--db=<TDB>] <ID>\n"
    412587                           "  Delete mapping of ID from TDB.\n"
    413588                           "    -f\tforce\n"
     
    419594        mem_ctx = talloc_stackframe();
    420595
    421         dbfile = net_idmap_dbfile(c);
     596        dbfile = net_idmap_dbfile(c, &ctx);
    422597        if (dbfile == NULL) {
    423598                goto done;
     
    425600        d_fprintf(stderr, _("deleting id mapping from %s\n"), dbfile);
    426601
    427         db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDWR, 0);
     602        db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDWR, 0,
     603                     DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
    428604        if (db == NULL) {
    429605                d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
     
    449625}
    450626
    451 static int net_idmap_set(struct net_context *c, int argc, const char **argv)
     627static bool parse_uint32(const char *str, uint32_t *result)
     628{
     629        unsigned long val;
     630        char *endptr;
     631
     632        val = strtoul(str, &endptr, 10);
     633
     634        if (str == endptr) {
     635                return false;
     636        }
     637        if (*endptr != '\0') {
     638                return false;
     639        }
     640        if ((val == ULONG_MAX) && (errno == ERANGE)) {
     641                return false;
     642        }
     643        if ((val & UINT32_MAX) != val) {
     644                /* overflow */
     645                return false;
     646        }
     647        *result = val;          /* Potential crop */
     648        return true;
     649}
     650
     651static void net_idmap_autorid_delete_range_usage(void)
     652{
     653        d_printf("%s\n%s",
     654                 _("Usage:"),
     655                 _("net idmap delete range [-f] [--db=<TDB>] <RANGE>|(<SID>[ <INDEX>])\n"
     656                   "  Delete a domain range mapping from the database.\n"
     657                   "    -f\tforce\n"
     658                   "    TDB\tidmap database\n"
     659                   "    RANGE\tthe range number to delete\n"
     660                   "    SID\t\tSID of the domain\n"
     661                   "    INDEX\trange index number do delete for the domain\n"));
     662}
     663
     664static int net_idmap_autorid_delete_range(struct net_context *c, int argc,
     665                                          const char **argv)
     666{
     667        int ret = -1;
     668        struct db_context *db = NULL;
     669        NTSTATUS status;
     670        uint32_t rangenum;
     671        uint32_t range_index;
     672        const char *domsid;
     673        TALLOC_CTX *mem_ctx = NULL;
     674        bool ok;
     675        bool force = (c->opt_force != 0);
     676
     677        if (c->display_usage) {
     678                net_idmap_autorid_delete_range_usage();
     679                return 0;
     680        }
     681
     682        if (argc < 1 || argc > 2) {
     683                net_idmap_autorid_delete_range_usage();
     684                return -1;
     685        }
     686
     687        mem_ctx = talloc_stackframe();
     688        if (!net_idmap_opendb_autorid(mem_ctx, c, false, &db)) {
     689                goto done;
     690        }
     691
     692        ok = parse_uint32(argv[0], &rangenum);
     693        if (ok) {
     694                d_printf("%s: %"PRIu32"\n", _("Deleting range number"),
     695                         rangenum);
     696
     697                status = idmap_autorid_delete_range_by_num(db, rangenum,
     698                                                           force);
     699                if (!NT_STATUS_IS_OK(status)) {
     700                        d_fprintf(stderr, "%s: %s\n",
     701                                  _("Failed to delete domain range mapping"),
     702                                  nt_errstr(status));
     703                } else {
     704                        ret = 0;
     705                }
     706
     707                goto done;
     708        }
     709
     710        domsid = argv[0];
     711        range_index = 0;
     712
     713        if (argc == 2) {
     714                ok = parse_uint32(argv[1], &range_index);
     715                if (!ok) {
     716                        d_printf("%s: %s\n",
     717                                 _("Invalid index specification"), argv[1]);
     718                        net_idmap_autorid_delete_range_usage();
     719                        goto done;
     720                }
     721        }
     722
     723        status = idmap_autorid_delete_range_by_sid(db, domsid, range_index,
     724                                                   force);
     725        if (!NT_STATUS_IS_OK(status)) {
     726                d_fprintf(stderr, "%s: %s\n",
     727                          _("Failed to delete domain range mapping"),
     728                          nt_errstr(status));
     729                goto done;
     730        }
     731
     732        ret = 0;
     733
     734done:
     735        talloc_free(mem_ctx);
     736        return ret;
     737}
     738
     739static void net_idmap_autorid_delete_ranges_usage(void)
     740{
     741        d_printf("%s\n%s",
     742                 _("Usage:"),
     743                 _("net idmap delete ranges [-f] [--db=<TDB>] <SID>\n"
     744                   "  Delete all domain range mappings for a given domain.\n"
     745                   "    -f\tforce\n"
     746                   "    TDB\tidmap database\n"
     747                   "    SID\t\tSID of the domain\n"));
     748}
     749
     750static int net_idmap_autorid_delete_ranges(struct net_context *c, int argc,
     751                                           const char **argv)
     752{
     753        int ret = -1;
     754        struct db_context *db = NULL;
     755        NTSTATUS status;
     756        const char *domsid;
     757        TALLOC_CTX *mem_ctx = NULL;
     758        bool force = (c->opt_force != 0);
     759        int count = 0;
     760
     761        if (c->display_usage) {
     762                net_idmap_autorid_delete_ranges_usage();
     763                return 0;
     764        }
     765
     766        if (argc != 1) {
     767                net_idmap_autorid_delete_ranges_usage();
     768                return -1;
     769        }
     770
     771        domsid = argv[0];
     772
     773        mem_ctx = talloc_stackframe();
     774        if (!net_idmap_opendb_autorid(mem_ctx, c, false, &db)) {
     775                goto done;
     776        }
     777
     778        status = idmap_autorid_delete_domain_ranges(db, domsid, force, &count);
     779        if (!NT_STATUS_IS_OK(status)) {
     780                d_fprintf(stderr, "%s %s: %s\n",
     781                          _("Failed to delete domain range mappings for "
     782                            "domain"),
     783                          domsid,
     784                          nt_errstr(status));
     785                goto done;
     786        }
     787
     788        d_printf(_("deleted %d domain mappings\n"), count);
     789
     790        ret = 0;
     791
     792done:
     793        talloc_free(mem_ctx);
     794        return ret;
     795}
     796
     797static int net_idmap_delete(struct net_context *c, int argc, const char **argv)
     798{
     799        struct functable func[] = {
     800                {
     801                        "mapping",
     802                        net_idmap_delete_mapping,
     803                        NET_TRANSPORT_LOCAL,
     804                        N_("Delete ID mapping"),
     805                        N_("net idmap delete mapping <ID>\n"
     806                           "  Delete ID mapping")
     807                },
     808                {
     809                        "range",
     810                        net_idmap_autorid_delete_range,
     811                        NET_TRANSPORT_LOCAL,
     812                        N_("Delete a domain range mapping"),
     813                        N_("net idmap delete range <RANGE>|(<SID>[ <INDEX>])\n"
     814                           "  Delete a domain range mapping")
     815                },
     816                {
     817                        "ranges",
     818                        net_idmap_autorid_delete_ranges,
     819                        NET_TRANSPORT_LOCAL,
     820                        N_("Delete all domain range mappings for a given "
     821                           "domain"),
     822                        N_("net idmap delete ranges <SID>\n"
     823                           "  Delete a domain range mapping")
     824                },
     825                {NULL, NULL, 0, NULL, NULL}
     826        };
     827
     828        return net_run_function(c, argc, argv, "net idmap delete", func);
     829}
     830
     831
     832static int net_idmap_set_mapping(struct net_context *c,
     833                                 int argc, const char **argv)
    452834{
    453835        d_printf("%s\n", _("Not implemented yet"));
    454836        return -1;
    455837}
     838
     839static void net_idmap_autorid_set_range_usage(void)
     840{
     841        d_printf("%s\n%s",
     842                 _("Usage:"),
     843                 _("net idmap set range"
     844                   " <range> <SID> [<index>] [--db=<inputfile>]\n"
     845                   "  Store a domain-range mapping for a given domain.\n"
     846                   "    range\tRange number to be set for the domain\n"
     847                   "    SID\t\tSID of the domain\n"
     848                   "    index\trange-index number to be set for the domain\n"
     849                   "    inputfile\tTDB file to add mapping to.\n"));
     850}
     851
     852static int net_idmap_autorid_set_range(struct net_context *c,
     853                                       int argc, const char **argv)
     854{
     855        int ret = -1;
     856        TALLOC_CTX *mem_ctx;
     857        struct db_context *db = NULL;
     858        const char *domsid;
     859        uint32_t rangenum;
     860        uint32_t range_index = 0;
     861        NTSTATUS status;
     862        bool ok;
     863
     864        if (c->display_usage) {
     865                net_idmap_autorid_set_range_usage();
     866                return 0;
     867        }
     868
     869        if (argc < 2  || argc > 3) {
     870                net_idmap_autorid_set_range_usage();
     871                return -1;
     872        }
     873
     874        ok = parse_uint32(argv[0], &rangenum);
     875        if (!ok) {
     876                d_printf("%s: %s\n", _("Invalid range specification"),
     877                         argv[0]);
     878                net_idmap_autorid_set_range_usage();
     879                return -1;
     880        }
     881
     882        domsid = argv[1];
     883
     884        if (argc == 3) {
     885                ok = parse_uint32(argv[2], &range_index);
     886                if (!ok) {
     887                        d_printf("%s: %s\n",
     888                                 _("Invalid index specification"), argv[2]);
     889                        net_idmap_autorid_set_range_usage();
     890                        return -1;
     891                }
     892        }
     893
     894        mem_ctx = talloc_stackframe();
     895        if (!net_idmap_opendb_autorid(mem_ctx, c, false, &db)) {
     896                goto done;
     897        }
     898
     899        status = idmap_autorid_setrange(db, domsid, range_index, rangenum);
     900        if (!NT_STATUS_IS_OK(status)) {
     901                d_fprintf(stderr, "%s: %s\n",
     902                          _("Failed to save domain mapping"),
     903                          nt_errstr(status));
     904                goto done;
     905        }
     906
     907        ret = 0;
     908
     909done:
     910        TALLOC_FREE(mem_ctx);
     911        return ret;
     912}
     913
    456914static bool idmap_store_secret(const char *backend,
    457915                               const char *domain,
     
    467925        if (r < 0) return false;
    468926
    469         strupper_m(tmp); /* make sure the key is case insensitive */
     927        /* make sure the key is case insensitive */
     928        if (!strupper_m(tmp)) {
     929                free(tmp);
     930                return false;
     931        }
    470932        ret = secrets_store_generic(tmp, identity, secret);
    471933
     
    488950                d_printf("%s\n%s",
    489951                         _("Usage:\n"),
    490                          _("net idmap secret <DOMAIN> <secret>\n"
     952                         _("net idmap set secret <DOMAIN> <secret>\n"
    491953                           "  Set the secret for the specified domain\n"
    492954                           "    DOMAIN\tDomain to set secret for.\n"
     
    509971        ALLOC_CHECK(backend);
    510972
    511         if ( ( ! backend) || ( ! strequal(backend, "ldap"))) {
     973        if ((!backend) || (!strequal(backend, "ldap") &&
     974                           !strequal(backend, "rfc2307"))) {
    512975                d_fprintf(stderr,
    513                           _("The only currently supported backend is LDAP\n"));
     976                          _("The only currently supported backend are LDAP "
     977                            "and rfc2307\n"));
    514978                talloc_free(ctx);
    515979                return -1;
     
    5371001}
    5381002
     1003static int net_idmap_autorid_set_config(struct net_context *c,
     1004                                        int argc, const char **argv)
     1005{
     1006        int ret = -1;
     1007        NTSTATUS status;
     1008        TALLOC_CTX *mem_ctx;
     1009        struct db_context *db = NULL;
     1010
     1011        if (argc != 1 || c->display_usage) {
     1012                d_printf("%s\n%s",
     1013                         _("Usage:"),
     1014                         _("net idmap set config <config>"
     1015                           " [--db=<inputfile>]\n"
     1016                           " Update CONFIG entry in autorid.\n"
     1017                           "    config\tConfig string to be stored\n"
     1018                           "    inputfile\tTDB file to update config.\n"));
     1019                return c->display_usage ? 0 : -1;
     1020        }
     1021
     1022        mem_ctx = talloc_stackframe();
     1023
     1024        if (!net_idmap_opendb_autorid(mem_ctx, c, false, &db)) {
     1025                goto done;
     1026        }
     1027
     1028        status = idmap_autorid_saveconfigstr(db, argv[0]);
     1029        if (!NT_STATUS_IS_OK(status)) {
     1030                printf("Error storing the config in the database: %s\n",
     1031                       nt_errstr(status));
     1032                goto done;
     1033        }
     1034
     1035        ret = 0;
     1036
     1037done:
     1038        TALLOC_FREE(mem_ctx);
     1039        return ret;
     1040}
     1041
     1042static int net_idmap_set(struct net_context *c, int argc, const char **argv)
     1043{
     1044        struct functable func[] = {
     1045                {
     1046                        "mapping",
     1047                        net_idmap_set_mapping,
     1048                        NET_TRANSPORT_LOCAL,
     1049                        N_("Not implemented yet"),
     1050                        N_("net idmap set mapping\n"
     1051                           "  Not implemented yet")
     1052                },
     1053                {
     1054                        "range",
     1055                        net_idmap_autorid_set_range,
     1056                        NET_TRANSPORT_LOCAL,
     1057                        N_("Store a domain-range mapping"),
     1058                        N_("net idmap set range\n"
     1059                           "  Store a domain-range mapping")
     1060                },
     1061                {
     1062                        "config",
     1063                        net_idmap_autorid_set_config,
     1064                        NET_TRANSPORT_LOCAL,
     1065                        N_("Save the global configuration in the autorid database"),
     1066                        N_("net idmap set config \n"
     1067                           "  Save the global configuration in the autorid database ")
     1068                },
     1069                {
     1070                        "secret",
     1071                        net_idmap_secret,
     1072                        NET_TRANSPORT_LOCAL,
     1073                        N_("Set secret for specified domain"),
     1074                        N_("net idmap set secret <DOMAIN> <secret>\n"
     1075                           "  Set secret for specified domain")
     1076                },
     1077                {NULL, NULL, 0, NULL, NULL}
     1078        };
     1079
     1080        return net_run_function(c, argc, argv, "net idmap set", func);
     1081}
     1082
     1083static void net_idmap_autorid_get_range_usage(void)
     1084{
     1085        d_printf("%s\n%s",
     1086                 _("Usage:"),
     1087                 _("net idmap get range <SID> [<index>] [--db=<inputfile>]\n"
     1088                   "  Get the range for a given domain and index.\n"
     1089                   "    SID\t\tSID of the domain\n"
     1090                   "    index\trange-index number to be retrieved\n"
     1091                   "    inputfile\tTDB file to add mapping to.\n"));
     1092}
     1093
     1094
     1095static int net_idmap_autorid_get_range(struct net_context *c, int argc,
     1096                                       const char **argv)
     1097{
     1098        int ret = -1;
     1099        TALLOC_CTX *mem_ctx;
     1100        struct db_context *db = NULL;
     1101        const char *domsid;
     1102        uint32_t rangenum;
     1103        uint32_t range_index = 0;
     1104        uint32_t low_id;
     1105        NTSTATUS status;
     1106        char *keystr;
     1107        bool ok;
     1108
     1109        if (c->display_usage) {
     1110                net_idmap_autorid_get_range_usage();
     1111                return 0;
     1112        }
     1113
     1114        if (argc < 1  || argc > 2) {
     1115                net_idmap_autorid_get_range_usage();
     1116                return -1;
     1117        }
     1118
     1119        domsid = argv[0];
     1120
     1121        if (argc == 2) {
     1122                ok = parse_uint32(argv[1], &range_index);
     1123                if (!ok) {
     1124                        d_printf("%s: %s\n",
     1125                                 _("Invalid index specification"), argv[1]);
     1126                        net_idmap_autorid_get_range_usage();
     1127                        return -1;
     1128                }
     1129        }
     1130
     1131        mem_ctx = talloc_stackframe();
     1132        if (!net_idmap_opendb_autorid(mem_ctx, c, true, &db)) {
     1133                goto done;
     1134        }
     1135
     1136        status = idmap_autorid_getrange(db, domsid, range_index, &rangenum,
     1137                                        &low_id);
     1138        if (!NT_STATUS_IS_OK(status)) {
     1139                d_fprintf(stderr, "%s: %s\n",
     1140                          _("Failed to load domain range"), nt_errstr(status));
     1141                goto done;
     1142        }
     1143
     1144        if (range_index == 0) {
     1145                keystr = talloc_strdup(mem_ctx, domsid);
     1146        } else {
     1147                keystr = talloc_asprintf(mem_ctx, "%s#%"PRIu32, domsid,
     1148                                         range_index);
     1149        }
     1150
     1151        printf("RANGE %"PRIu32": %s (low id: %"PRIu32")\n",
     1152               rangenum, keystr, low_id);
     1153
     1154        ret = 0;
     1155
     1156done:
     1157        TALLOC_FREE(mem_ctx);
     1158        return ret;
     1159}
     1160
     1161static NTSTATUS net_idmap_autorid_print_range(struct db_context *db,
     1162                                              const char *domsid,
     1163                                              uint32_t range_index,
     1164                                              uint32_t rangenum,
     1165                                              void *private_data)
     1166{
     1167        if (range_index == 0) {
     1168                printf("RANGE %"PRIu32": %s\n", rangenum, domsid);
     1169        } else {
     1170                printf("RANGE %"PRIu32": %s#%"PRIu32"\n", rangenum, domsid,
     1171                       range_index);
     1172        }
     1173
     1174        return NT_STATUS_OK;
     1175}
     1176
     1177static void net_idmap_autorid_get_ranges_usage(void)
     1178{
     1179        d_printf("%s\n%s",
     1180                 _("Usage:"),
     1181                 _("net idmap get ranges [<SID>] [--db=<inputfile>]\n"
     1182                   "  Get all ranges for a given domain.\n"
     1183                   "    SID\t\tSID of the domain - list all ranges if omitted\n"
     1184                   "    inputfile\tTDB file to add mapping to.\n"));
     1185}
     1186
     1187static int net_idmap_autorid_get_ranges(struct net_context *c, int argc,
     1188                                        const char **argv)
     1189{
     1190        int ret = -1;
     1191        TALLOC_CTX *mem_ctx;
     1192        struct db_context *db = NULL;
     1193        const char *domsid;
     1194        NTSTATUS status;
     1195
     1196        if (c->display_usage) {
     1197                net_idmap_autorid_get_ranges_usage();
     1198                return 0;
     1199        }
     1200
     1201        if (argc == 0) {
     1202                domsid = NULL;
     1203        } else if (argc == 1) {
     1204                domsid = argv[0];
     1205        } else {
     1206                net_idmap_autorid_get_ranges_usage();
     1207                return -1;
     1208        }
     1209
     1210        mem_ctx = talloc_stackframe();
     1211        if (!net_idmap_opendb_autorid(mem_ctx, c, true, &db)) {
     1212                goto done;
     1213        }
     1214
     1215        status = idmap_autorid_iterate_domain_ranges_read(db,
     1216                                                domsid,
     1217                                                net_idmap_autorid_print_range,
     1218                                                NULL, /* private_data */
     1219                                                NULL  /* count */);
     1220        if (!NT_STATUS_IS_OK(status)) {
     1221                d_fprintf(stderr, "%s: %s\n",
     1222                          _("Error getting domain ranges"), nt_errstr(status));
     1223                goto done;
     1224        }
     1225
     1226        ret = 0;
     1227
     1228done:
     1229        talloc_free(mem_ctx);
     1230        return ret;
     1231}
     1232
     1233static int net_idmap_autorid_get_config(struct net_context *c, int argc,
     1234                                        const char **argv)
     1235{
     1236        int ret = -1;
     1237        char *config;
     1238        TALLOC_CTX *mem_ctx;
     1239        NTSTATUS status;
     1240        struct db_context *db = NULL;
     1241
     1242        if (argc > 0 || c->display_usage) {
     1243                d_printf("%s\n%s",
     1244                         _("Usage:"),
     1245                         _("net idmap get config"
     1246                           " [--db=<inputfile>]\n"
     1247                           " Get CONFIG entry from autorid database\n"
     1248                           "    inputfile\tTDB file to read config from.\n"));
     1249                return c->display_usage ? 0 : -1;
     1250        }
     1251
     1252        mem_ctx = talloc_stackframe();
     1253
     1254        if (!net_idmap_opendb_autorid(mem_ctx, c, true, &db)) {
     1255                goto done;
     1256        }
     1257
     1258        status = idmap_autorid_getconfigstr(db, mem_ctx, &config);
     1259        if (!NT_STATUS_IS_OK(status)) {
     1260                d_fprintf(stderr, "%s: %s\n",
     1261                          _("Error: unable to read config entry"),
     1262                          nt_errstr(status));
     1263                goto done;
     1264        }
     1265
     1266        printf("CONFIG: %s\n", config);
     1267        ret = 0;
     1268
     1269done:
     1270        TALLOC_FREE(mem_ctx);
     1271        return ret;
     1272}
     1273
     1274
     1275static int net_idmap_get(struct net_context *c, int argc, const char **argv)
     1276{
     1277        struct functable func[] = {
     1278                {
     1279                        "range",
     1280                        net_idmap_autorid_get_range,
     1281                        NET_TRANSPORT_LOCAL,
     1282                        N_("Get the range for a domain and range-index"),
     1283                        N_("net idmap get range\n"
     1284                           "  Get the range for a domain and range-index")
     1285                },
     1286                {
     1287                        "ranges",
     1288                        net_idmap_autorid_get_ranges,
     1289                        NET_TRANSPORT_LOCAL,
     1290                        N_("Get all ranges for a domain"),
     1291                        N_("net idmap get ranges <SID>\n"
     1292                           "  Get all ranges for a domain")
     1293                },
     1294                {
     1295                        "config",
     1296                        net_idmap_autorid_get_config,
     1297                        NET_TRANSPORT_LOCAL,
     1298                        N_("Get the global configuration from the autorid database"),
     1299                        N_("net idmap get config \n"
     1300                           "  Get the global configuration from the autorid database ")
     1301                },
     1302                {NULL, NULL, 0, NULL, NULL}
     1303        };
     1304
     1305        return net_run_function(c, argc, argv, "net idmap get", func);
     1306}
     1307
    5391308static int net_idmap_check(struct net_context *c, int argc, const char **argv)
    5401309{
    541         const char* dbfile;
     1310        char *dbfile;
    5421311        struct check_options opts;
     1312        struct net_idmap_ctx ctx = { .backend = TDB };
     1313        int ret;
    5431314
    5441315        if ( argc > 1 || c->display_usage) {
     
    5571328        }
    5581329
    559         dbfile = (argc > 0) ? argv[0] : net_idmap_dbfile(c);
     1330        if (argc > 0) {
     1331                dbfile = talloc_strdup(talloc_tos(), argv[0]);
     1332        } else {
     1333                dbfile = net_idmap_dbfile(c, &ctx);
     1334        }
    5601335        if (dbfile == NULL) {
    5611336                return -1;
    5621337        }
     1338
     1339        if (ctx.backend != TDB) {
     1340                d_fprintf(stderr, _("Sorry, checking of non-TDB databases is "
     1341                                    "currently not supported\n"));
     1342                talloc_free(dbfile);
     1343                return -1;
     1344        }
     1345
    5631346        d_fprintf(stderr, _("check database: %s\n"), dbfile);
    5641347
     
    5721355        };
    5731356
    574         return net_idmap_check_db(dbfile, &opts);
    575 }
    576 
    577 static int net_idmap_aclmapset(struct net_context *c, int argc, const char **argv)
    578 {
    579         TALLOC_CTX *mem_ctx;
    580         int result = -1;
    581         struct dom_sid src_sid, dst_sid;
    582         char *src, *dst;
    583         struct db_context *db;
    584         struct db_record *rec;
    585         NTSTATUS status;
    586 
    587         if (argc != 3 || c->display_usage) {
    588                 d_fprintf(stderr, "%s net idmap aclmapset <tdb> "
    589                           "<src-sid> <dst-sid>\n", _("Usage:"));
    590                 return -1;
    591         }
    592 
    593         if (!(mem_ctx = talloc_init("net idmap aclmapset"))) {
    594                 d_fprintf(stderr, _("talloc_init failed\n"));
    595                 return -1;
    596         }
    597 
    598         if (!(db = db_open(mem_ctx, argv[0], 0, TDB_DEFAULT,
    599                            O_RDWR|O_CREAT, 0600))) {
    600                 d_fprintf(stderr, _("db_open failed: %s\n"), strerror(errno));
    601                 goto fail;
    602         }
    603 
    604         if (!string_to_sid(&src_sid, argv[1])) {
    605                 d_fprintf(stderr, _("%s is not a valid sid\n"), argv[1]);
    606                 goto fail;
    607         }
    608 
    609         if (!string_to_sid(&dst_sid, argv[2])) {
    610                 d_fprintf(stderr, _("%s is not a valid sid\n"), argv[2]);
    611                 goto fail;
    612         }
    613 
    614         if (!(src = sid_string_talloc(mem_ctx, &src_sid))
    615             || !(dst = sid_string_talloc(mem_ctx, &dst_sid))) {
    616                 d_fprintf(stderr, _("talloc_strdup failed\n"));
    617                 goto fail;
    618         }
    619 
    620         if (!(rec = db->fetch_locked(
    621                       db, mem_ctx, string_term_tdb_data(src)))) {
    622                 d_fprintf(stderr, _("could not fetch db record\n"));
    623                 goto fail;
    624         }
    625 
    626         status = rec->store(rec, string_term_tdb_data(dst), 0);
    627         TALLOC_FREE(rec);
    628 
    629         if (!NT_STATUS_IS_OK(status)) {
    630                 d_fprintf(stderr, _("could not store record: %s\n"),
    631                           nt_errstr(status));
    632                 goto fail;
    633         }
    634 
    635         result = 0;
    636 fail:
    637         TALLOC_FREE(mem_ctx);
    638         return result;
     1357        ret = net_idmap_check_db(dbfile, &opts);
     1358        talloc_free(dbfile);
     1359        return ret;
    6391360}
    6401361
     
    6491370                        net_idmap_dump,
    6501371                        NET_TRANSPORT_LOCAL,
    651                         N_("Dump the current ID mappings"),
     1372                        N_("Dump the current ID mapping database"),
    6521373                        N_("net idmap dump\n"
    6531374                           "  Dump the current ID mappings")
     
    6571378                        net_idmap_restore,
    6581379                        NET_TRANSPORT_LOCAL,
    659                         N_("Restore entries from stdin"),
     1380                        N_("Restore entries from a file or stdin"),
    6601381                        N_("net idmap restore\n"
    6611382                           "  Restore entries from stdin")
    6621383                },
    6631384                {
    664                         "setmap",
     1385                        "get",
     1386                        net_idmap_get,
     1387                        NET_TRANSPORT_LOCAL,
     1388                        N_("Read data from the ID mapping database"),
     1389                        N_("net idmap get\n"
     1390                           "  Read data from the ID mapping database")
     1391                },
     1392                {
     1393                        "set",
    6651394                        net_idmap_set,
    6661395                        NET_TRANSPORT_LOCAL,
    667                         N_("Not implemented yet"),
    668                         N_("net idmap setmap\n"
    669                            "  Not implemented yet")
     1396                        N_("Write data to the ID mapping database"),
     1397                        N_("net idmap set\n"
     1398                           "  Write data to the ID mapping database")
    6701399                },
    6711400                {
     
    6731402                        net_idmap_delete,
    6741403                        NET_TRANSPORT_LOCAL,
    675                         N_("Delete ID mapping"),
    676                         N_("net idmap delete <ID>\n"
    677                            "  Delete ID mapping")
    678                 },
    679                 {
    680                         "secret",
    681                         net_idmap_secret,
    682                         NET_TRANSPORT_LOCAL,
    683                         N_("Set secret for specified domain"),
    684                         N_("net idmap secret <DOMAIN> <secret>\n"
    685                            "  Set secret for specified domain")
    686                 },
    687                 {
    688                         "aclmapset",
    689                         net_idmap_aclmapset,
    690                         NET_TRANSPORT_LOCAL,
    691                         N_("Set acl map"),
    692                         N_("net idmap aclmapset\n"
    693                            "  Set acl map")
     1404                        N_("Delete entries from the ID mapping database"),
     1405                        N_("net idmap delete\n"
     1406                           "  Delete entries from the ID mapping database")
    6941407                },
    6951408                {
  • vendor/current/source3/utils/net_idmap_check.c

    r746 r988  
    2727#include "includes.h"
    2828#include "system/filesys.h"
    29 #include "dbwrap.h"
     29#include "dbwrap/dbwrap.h"
     30#include "dbwrap/dbwrap_open.h"
     31#include "dbwrap/dbwrap_rbt.h"
    3032#include "net.h"
    3133#include "../libcli/security/dom_sid.h"
    3234#include "cbuf.h"
    3335#include "srprs.h"
    34 #include <termios.h>
    3536#include "util_tdb.h"
     37#include "interact.h"
    3638
    3739static int traverse_commit(struct db_record *diff_rec, void* data);
    3840static int traverse_check(struct db_record *rec, void* data);
    39 
    40 static char* interact_edit(TALLOC_CTX* mem_ctx, const char* str);
    41 static int interact_prompt(const char* msg, const char* accept, char def);
    4241
    4342/* TDB_DATA *******************************************************************/
    4443static char*    print_data(TALLOC_CTX* mem_ctx, TDB_DATA d);
    4544static TDB_DATA parse_data(TALLOC_CTX* mem_ctx, const char** ptr);
    46 static TDB_DATA talloc_copy(TALLOC_CTX* mem_ctx, TDB_DATA data);
    47 static bool is_empty(TDB_DATA data) {
    48         return (data.dsize == 0) || (data.dptr == NULL);
    49 }
    5045
    5146/* record *********************************************************************/
     
    7974
    8075typedef struct check_action {
    81         const char* fmt;
     76        void (*fmt)(struct check_action *a,
     77                    struct record *r,
     78                    TDB_DATA *v);
    8279        const char* name;
    8380        const char* prompt;
     
    103100};
    104101
     102static void invalid_mapping_fmt(struct check_action *a,
     103                                struct record *r,
     104                                TDB_DATA *v)
     105{
     106        d_printf("%1$s: %2$s -> %3$s\n(%4$s <- %3$s)\n",
     107                 a->name,
     108                 print_data(r, r->key),
     109                 print_data(r, r->val),
     110                 (v ? print_data(r, *v) : ""));
     111}
     112
     113static void record_exists_fmt(struct check_action *a,
     114                              struct record *r,
     115                              TDB_DATA *v)
     116{
     117        d_printf("%1$s: %2$s\n-%4$s\n+%3$s\n",
     118                 a->name,
     119                 print_data(r, r->key),
     120                 print_data(r, r->val),
     121                 (v ? print_data(r, *v) : ""));
     122}
     123
     124static void valid_mapping_fmt(struct check_action *a,
     125                              struct record *r,
     126                              TDB_DATA *v)
     127{
     128        d_printf("%1$s: %2$s <-> %3$s\n",
     129                 a->name,
     130                 print_data(r, r->key),
     131                 print_data(r, r->val));
     132}
     133
    105134static struct check_actions
    106135check_actions_init(const struct check_options* opts) {
     
    123152                },
    124153                .invalid_mapping = (check_action) {
    125                         .fmt = "%1$s: %2$s -> %3$s\n(%4$s <- %3$s)\n",
     154                        .fmt = invalid_mapping_fmt,
    126155                        .name = "Invalid mapping",
    127156                        .prompt = "[e]dit/[d]elete/[D]elete all"
     
    140169                },
    141170                .record_exists = (check_action) {
    142                         .fmt = "%1$s: %2$s\n-%4$s\n+%3$s\n",
     171                        .fmt = record_exists_fmt,
    143172                        .name = "Record exists",
    144173                        .prompt = "[o]verwrite/[O]verwrite all/[e]dit"
     
    170199                },
    171200                .valid_mapping = (check_action) {
    172                         .fmt = "%1$s: %2$s <-> %3$s\n",
     201                        .fmt = valid_mapping_fmt,
    173202                        .name = "Mapping",
    174203                        .auto_action = 's',
     
    236265                        }
    237266                } else {
    238                         d_printf(a->fmt, a->name,
    239                                  print_data(r, r->key),
    240                                  print_data(r, r->val),
    241                                  (v ? print_data(r, *v) : ""));
     267                        a->fmt(a, r, v);
    242268                }
    243269        }
     
    277303#define DEBUG_DIFF(LEV,MEM,MSG,KEY,OLD,NEW)                     \
    278304        DEBUG(LEV, ("%s: %s\n", MSG, print_data(MEM, KEY)));    \
    279         if (!is_empty(OLD)) {                                   \
     305        if (!tdb_data_is_empty(OLD)) {                          \
    280306                DEBUGADD(LEV, ("-%s\n", print_data(MEM, OLD))); \
    281307        }                                                       \
    282         if (!is_empty(NEW)) {                                   \
     308        if (!tdb_data_is_empty(NEW)) {                          \
    283309                DEBUGADD(LEV, ("+%s\n", print_data(MEM, NEW))); \
    284310        }
     
    312338        TDB_DATA_diff diff;
    313339        TALLOC_CTX* mem = talloc_new(ctx->diff);
    314         struct db_record* rec = ctx->diff->fetch_locked(ctx->diff, mem, key);
     340        TDB_DATA recvalue;
     341        struct db_record *rec = dbwrap_fetch_locked(ctx->diff, mem, key);
     342
    315343        if (rec == NULL) {
    316344                return -1;
    317         };
    318         if (rec->value.dptr == 0) { /* first entry */
    319                 diff.oval = dbwrap_fetch(ctx->db, ctx->diff, key);
     345        }
     346
     347        recvalue = dbwrap_record_get_value(rec);
     348
     349        if (recvalue.dptr == 0) { /* first entry */
     350                status = dbwrap_fetch(ctx->db, ctx->diff, key, &diff.oval);
     351                if (!NT_STATUS_IS_OK(status)) {
     352                        diff.oval = tdb_null;
     353                }
    320354        } else {
    321                 diff = unpack_diff(rec->value);
     355                diff = unpack_diff(recvalue);
    322356                talloc_free(diff.nval.dptr);
    323357        }
    324         diff.nval = talloc_copy(ctx->diff, value);
     358        diff.nval = tdb_data_talloc_copy(ctx->diff, value);
    325359
    326360        DEBUG_DIFF(2, mem, "TDB DIFF", key, diff.oval, diff.nval);
    327361
    328         status = rec->store(rec, pack_diff(&diff), 0);
     362        status = dbwrap_record_store(rec, pack_diff(&diff), 0);
    329363
    330364        talloc_free(mem);
     
    346380{
    347381        TDB_DATA tmp;
    348 
    349         if (ctx->diff->fetch(ctx->diff, mem_ctx, key, &tmp) == -1) {
    350                 DEBUG(0, ("Out of memory!\n"));
    351                 return tdb_null;
    352         }
    353         if (tmp.dptr != NULL) {
     382        NTSTATUS status;
     383
     384        status = dbwrap_fetch(ctx->diff, mem_ctx, key, &tmp);
     385
     386        if (NT_STATUS_IS_OK(status)) {
    354387                TDB_DATA_diff diff = unpack_diff(tmp);
    355                 TDB_DATA ret = talloc_copy(mem_ctx, diff.nval);
     388                TDB_DATA ret = tdb_data_talloc_copy(mem_ctx, diff.nval);
    356389                talloc_free(tmp.dptr);
    357390                return ret;
    358391        }
    359392
    360         if (ctx->db->fetch(ctx->db, mem_ctx, key, &tmp) == -1) {
    361                 DEBUG(0, ("Out of memory!\n"));
     393        status = dbwrap_fetch(ctx->db, mem_ctx, key, &tmp);
     394        if (!NT_STATUS_IS_OK(status)) {
    362395                return tdb_null;
    363396        }
     
    388421        static const char* key = "IDMAP_VERSION";
    389422        uint32_t version;
    390         bool no_version = !dbwrap_fetch_uint32(ctx->db, key, &version);
     423        NTSTATUS status;
    391424        char action = 's';
    392425        struct check_actions* act = &ctx->action;
    393         if (no_version) {
     426
     427        status = dbwrap_fetch_uint32_bystring(ctx->db, key, &version);
     428        if (!NT_STATUS_IS_OK(status)) {
    394429                d_printf("No version number, assume 2\n");
    395430                action = get_action(&act->no_version, NULL, NULL);
     
    417452        uint32_t hwm;
    418453        char action = 's';
    419         bool found = dbwrap_fetch_uint32(ctx->db, key, &hwm);
     454        NTSTATUS status;
    420455        struct check_actions* act = &ctx->action;
    421         if (!found) {
     456
     457        status = dbwrap_fetch_uint32_bystring(ctx->db, key, &hwm);
     458        if (!NT_STATUS_IS_OK(status)) {
    422459                d_printf("No %s should be %d\n", key, target);
    423460                action = get_action(&act->invalid_hwm, NULL, NULL);
     
    437474        struct check_actions* act = &ctx->action;
    438475        TALLOC_CTX* mem = talloc_new(ctx->diff);
    439         struct record* r = parse_record(mem, rec->key, rec->value);
     476        TDB_DATA key;
     477        TDB_DATA value;
     478        struct record *r;
    440479        char action = 's';
     480
     481        key = dbwrap_record_get_key(rec);
     482        value = dbwrap_record_get_value(rec);
     483
     484        r = parse_record(mem, key, value);
    441485
    442486        if (is_invalid(r)) {
     
    471515                        break;
    472516                case 'd': /* delete */
    473                         del_record(ctx, rec->key);
     517                        del_record(ctx, key);
    474518                        break;
    475519                case 'f': /* add reverse mapping */
    476                         add_record(ctx, rec->value, rec->key);
     520                        add_record(ctx, value, key);
    477521                        break;
    478522                case 'e': /* edit */
     
    483527                                continue;
    484528                        }
    485                         if (!tdb_data_equal(rec->key, r->key)) {
     529                        if (!tdb_data_equal(key, r->key)) {
    486530                                TDB_DATA oval = fetch_record(ctx, mem, r->key);
    487                                 if (!is_empty(oval) &&
     531                                if (!tdb_data_is_empty(oval) &&
    488532                                    !tdb_data_equal(oval, r->val))
    489533                                {
     
    497541                        if (is_map(r)) {
    498542                                TDB_DATA okey = fetch_record(ctx, mem, r->val);
    499                                 if (!is_empty(okey) &&
     543                                if (!tdb_data_is_empty(okey) &&
    500544                                    !tdb_data_equal(okey, r->key))
    501545                                {
     
    508552                case 'o': /* overwrite */
    509553                        adjust_hwm(ctx, r);
    510                         if (!tdb_data_equal(rec->key, r->key)) {
    511                                 del_record(ctx, rec->key);
     554                        if (!tdb_data_equal(key, r->key)) {
     555                                del_record(ctx, key);
    512556                        }
    513557                        add_record(ctx, r->key, r->val);
     
    535579}
    536580
    537 TDB_DATA talloc_copy(TALLOC_CTX* mem_ctx, TDB_DATA data) {
    538         TDB_DATA ret = {
    539                 .dptr  = (uint8_t *)talloc_size(mem_ctx, data.dsize+1),
    540                 .dsize = data.dsize
    541         };
    542         if (ret.dptr == NULL) {
    543                 ret.dsize = 0;
    544         } else {
    545                 memcpy(ret.dptr, data.dptr, data.dsize);
    546                 ret.dptr[ret.dsize] = '\0';
    547         }
    548         return ret;
    549 }
    550 
    551581static bool is_cstr(TDB_DATA str) {
    552         return !is_empty(str) && str.dptr[str.dsize-1] == '\0';
     582        return !tdb_data_is_empty(str) && str.dptr[str.dsize-1] == '\0';
    553583}
    554584
     
    590620                return NULL;
    591621        }
    592         ret->key = talloc_copy(ret, key);
    593         ret->val = talloc_copy(ret, val);
     622        ret->key = tdb_data_talloc_copy(ret, key);
     623        ret->val = tdb_data_talloc_copy(ret, val);
    594624        if ((ret->key.dptr == NULL && key.dptr != NULL) ||
    595625            (ret->val.dptr == NULL && val.dptr != NULL))
     
    647677/******************************************************************************/
    648678
    649 int interact_prompt(const char* msg, const char* acc, char def) {
    650         struct termios old_tio, new_tio;
    651         int c;
    652 
    653         tcgetattr(STDIN_FILENO, &old_tio);
    654         new_tio=old_tio;
    655         new_tio.c_lflag &=(~ICANON & ~ECHO);
    656         tcsetattr(STDIN_FILENO, TCSANOW, &new_tio);
    657 
    658         do {
    659                 d_printf("%s? [%c]\n", msg, def);
    660                 fflush(stdout);
    661                 c = getchar();
    662                 if (c == '\n') {
    663                         c = def;
    664                         break;
    665                 }
    666                 else if (strchr(acc, tolower(c)) != NULL) {
    667                         break;
    668                 }
    669                 d_printf("Invalid input '%c'\n", c);
    670         } while(c != EOF);
    671         tcsetattr(STDIN_FILENO, TCSANOW, &old_tio);
    672         return c;
    673 }
    674679
    675680char* print_data(TALLOC_CTX* mem_ctx, TDB_DATA d)
    676681{
    677         if (!is_empty(d)) {
     682        if (!tdb_data_is_empty(d)) {
    678683                char* ret = NULL;
    679684                cbuf* ost = cbuf_new(mem_ctx);
     
    702707}
    703708
    704 static const char* get_editor(void) {
    705         static const char* editor = NULL;
    706         if (editor == NULL) {
    707                 editor = getenv("VISUAL");
    708                 if (editor == NULL) {
    709                         editor = getenv("EDITOR");
    710                 }
    711                 if (editor == NULL) {
    712                         editor = "vi";
    713                 }
    714         }
    715         return editor;
    716 }
    717 
    718 char* interact_edit(TALLOC_CTX* mem_ctx, const char* str) {
    719         char fname[] = "/tmp/net_idmap_check.XXXXXX";
    720         char buf[128];
    721         char* ret = NULL;
    722         FILE* file;
    723 
    724         int fd = mkstemp(fname);
    725         if (fd == -1) {
    726                 DEBUG(0, ("failed to mkstemp %s: %s\n", fname,
    727                           strerror(errno)));
    728                 return NULL;
    729         }
    730 
    731         file  = fdopen(fd, "w");
    732         if (!file) {
    733                 DEBUG(0, ("failed to open %s for writing: %s\n", fname,
    734                           strerror(errno)));
    735                 close(fd);
    736                 unlink(fname);
    737                 return NULL;
    738         }
    739 
    740         fprintf(file, "%s", str);
    741         fclose(file);
    742 
    743         snprintf(buf, sizeof(buf), "%s %s\n", get_editor(), fname);
    744         if (system(buf) != 0) {
    745                 DEBUG(0, ("failed to start editor %s: %s\n", buf,
    746                           strerror(errno)));
    747                 unlink(fname);
    748                 return NULL;
    749         }
    750 
    751         file = fopen(fname, "r");
    752         if (!file) {
    753                 DEBUG(0, ("failed to open %s for reading: %s\n", fname,
    754                           strerror(errno)));
    755                 unlink(fname);
    756                 return NULL;
    757         }
    758         while ( fgets(buf, sizeof(buf), file) ) {
    759                 ret = talloc_strdup_append(ret, buf);
    760         }
    761         fclose(file);
    762         unlink(fname);
    763 
    764         return talloc_steal(mem_ctx, ret);
    765 }
    766 
    767 
    768709static int traverse_print_diff(struct db_record *rec, void* data) {
    769710        struct check_ctx* ctx = (struct check_ctx*)data;
    770         TDB_DATA key = rec->key;
    771         TDB_DATA_diff diff = unpack_diff(rec->value);
     711        TDB_DATA key;
     712        TDB_DATA value;
     713        TDB_DATA_diff diff;
    772714        TALLOC_CTX* mem = talloc_new(ctx->diff);
     715
     716        key = dbwrap_record_get_key(rec);
     717        value = dbwrap_record_get_value(rec);
     718        diff = unpack_diff(value);
    773719
    774720        DEBUG_DIFF(0, mem, "DIFF", key, diff.oval, diff.nval);
     
    781727static int traverse_commit(struct db_record *diff_rec, void* data) {
    782728        struct check_ctx* ctx = (struct check_ctx*)data;
    783         TDB_DATA_diff diff = unpack_diff(diff_rec->value);
    784         TDB_DATA key = diff_rec->key;
     729        TDB_DATA key;
     730        TDB_DATA diff_value;
     731        TDB_DATA_diff diff;
     732        TDB_DATA value;
    785733        TALLOC_CTX* mem = talloc_new(ctx->diff);
    786734        int ret = -1;
    787735        NTSTATUS status;
    788736        struct check_actions* act = &ctx->action;
    789 
    790         struct db_record* rec = ctx->db->fetch_locked(ctx->db, mem, key);
     737        struct db_record* rec;
     738
     739        key = dbwrap_record_get_key(diff_rec);
     740        diff_value = dbwrap_record_get_value(diff_rec);
     741        diff = unpack_diff(diff_value);
     742
     743        rec = dbwrap_fetch_locked(ctx->db, mem, key);
    791744        if (rec == NULL) {
    792745                goto done;
    793         };
    794 
    795         if (!tdb_data_equal(rec->value, diff.oval)) {
     746        }
     747
     748        value = dbwrap_record_get_value(rec);
     749
     750        if (!tdb_data_equal(value, diff.oval)) {
    796751                char action;
    797752
     
    799754                         "expected: %s got %s\n", print_data(mem, key),
    800755                         print_data(mem, diff.oval),
    801                          print_data(mem, rec->value));
     756                         print_data(mem, value));
    802757
    803758                action = get_action(&act->invalid_diff, NULL, NULL);
     
    812767        DEBUG_DIFF(0, mem, "Commit", key, diff.oval, diff.nval);
    813768
    814         if (is_empty(diff.nval)) {
    815                 status = rec->delete_rec(rec);
     769        if (tdb_data_is_empty(diff.nval)) {
     770                status = dbwrap_record_delete(rec);
    816771        } else {
    817                 status = rec->store(rec, diff.nval, 0);
     772                status = dbwrap_record_store(rec, diff.nval, 0);
    818773        }
    819774
     
    866821        }
    867822
    868         ctx->db = db_open(ctx, name, 0, TDB_DEFAULT, oflags, 0);
     823        ctx->db = db_open(ctx, name, 0, TDB_DEFAULT, oflags, 0,
     824                          DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
    869825        if (ctx->db == NULL) {
    870826                d_fprintf(stderr,
     
    915871
    916872static bool check_transaction_start(struct check_ctx* ctx) {
    917         return (ctx->db->transaction_start(ctx->db) == 0);
     873        return (dbwrap_transaction_start(ctx->db) == 0);
    918874}
    919875
    920876static bool check_transaction_commit(struct check_ctx* ctx) {
    921         return (ctx->db->transaction_commit(ctx->db) == 0);
     877        return (dbwrap_transaction_commit(ctx->db) == 0);
    922878}
    923879
    924880static bool check_transaction_cancel(struct check_ctx* ctx) {
    925         return (ctx->db->transaction_cancel(ctx->db) == 0);
     881        return (dbwrap_transaction_cancel(ctx->db) == 0);
    926882}
    927883
     
    970926                return false;
    971927        }
    972         if (ctx->opts.test) { //get_action?
     928        if (ctx->opts.test) { /*get_action? */
    973929                return check_transaction_cancel(ctx);
    974930        } else {
  • vendor/current/source3/utils/net_join.c

    r414 r988  
    3535int net_join(struct net_context *c, int argc, const char **argv)
    3636{
    37         if ((argc > 0) && (StrCaseCmp(argv[0], "HELP") == 0)) {
     37        if ((argc > 0) && (strcasecmp_m(argv[0], "HELP") == 0)) {
    3838                net_join_usage(c, argc, argv);
    3939                return 0;
  • vendor/current/source3/utils/net_lookup.c

    r746 r988  
    2020#include "utils/net.h"
    2121#include "libads/sitename_cache.h"
    22 #include "libads/dns.h"
     22#include "../lib/addns/dnsquery.h"
    2323#include "../librpc/gen_ndr/ndr_netlogon.h"
    2424#include "smb_krb5.h"
     
    113113                domain = c->opt_target_workgroup;
    114114
    115         sitename = sitename_fetch(domain);
    116 
    117115        if ( (ctx = talloc_init("net_lookup_ldap")) == NULL ) {
    118116                d_fprintf(stderr,"net_lookup_ldap: talloc_init() %s!\n",
    119117                          _("failed"));
    120                 SAFE_FREE(sitename);
    121                 return -1;
    122         }
     118                return -1;
     119        }
     120
     121        sitename = sitename_fetch(ctx, domain);
    123122
    124123        DEBUG(9, ("Lookup up ldap for domain %s\n", domain));
    125124
    126         status = ads_dns_query_dcs( ctx, domain, sitename, &dcs, &numdcs );
     125        status = ads_dns_query_dcs(ctx,
     126                                   domain,
     127                                   sitename,
     128                                   &dcs,
     129                                   &numdcs);
    127130        if ( NT_STATUS_IS_OK(status) && numdcs ) {
    128131                print_ldap_srvlist(dcs, numdcs);
    129132                TALLOC_FREE( ctx );
    130                 SAFE_FREE(sitename);
    131133                return 0;
    132134        }
     
    135137        if (!get_pdc_ip(domain, &ss)) {
    136138                TALLOC_FREE( ctx );
    137                 SAFE_FREE(sitename);
    138139                return -1;
    139140        }
     
    147148        if (ret) {
    148149                TALLOC_FREE( ctx );
    149                 SAFE_FREE(sitename);
    150150                return -1;
    151151        }
     
    155155        if (!domain) {
    156156                TALLOC_FREE( ctx );
    157                 SAFE_FREE(sitename);
    158157                return -1;
    159158        }
     
    162161        DEBUG(9, ("Looking up ldap for domain %s\n", domain));
    163162
    164         status = ads_dns_query_dcs( ctx, domain, sitename, &dcs, &numdcs );
     163        status = ads_dns_query_dcs(ctx,
     164                                   domain,
     165                                   sitename,
     166                                   &dcs,
     167                                   &numdcs);
    165168        if ( NT_STATUS_IS_OK(status) && numdcs ) {
    166169                print_ldap_srvlist(dcs, numdcs);
    167170                TALLOC_FREE( ctx );
    168                 SAFE_FREE(sitename);
    169171                return 0;
    170172        }
    171173
    172174        TALLOC_FREE( ctx );
    173         SAFE_FREE(sitename);
    174175
    175176        return -1;
     
    209210        d_printf("%s\n", pdc_str);
    210211
    211         sitename = sitename_fetch(domain);
     212        sitename = sitename_fetch(talloc_tos(), domain);
    212213        if (!NT_STATUS_IS_OK(get_sorted_dc_list(domain, sitename,
    213214                                        &ip_list, &count, sec_ads))) {
    214215                SAFE_FREE(pdc_str);
    215                 SAFE_FREE(sitename);
     216                TALLOC_FREE(sitename);
    216217                return 0;
    217218        }
    218         SAFE_FREE(sitename);
     219        TALLOC_FREE(sitename);
    219220        for (i=0;i<count;i++) {
    220221                print_sockaddr(addr, sizeof(addr), &ip_list[i].ss);
     
    292293
    293294        if (argc > 0) {
    294                 realm = argv[0];
     295                realm = argv[0];
    295296        } else if (lp_realm() && *lp_realm()) {
    296297                realm = lp_realm();
     
    318319                print_sockaddr(addr, sizeof(addr), &kdcs[i].ss);
    319320
    320                 d_printf("%s:%hd\n", addr, kdcs[i].port);
     321                d_printf("%s:%u\n", addr, kdcs[i].port);
    321322        }
    322323
     
    462463        }
    463464        for (i=0; table[i].funcname; i++) {
    464                 if (StrCaseCmp(argv[0], table[i].funcname) == 0)
     465                if (strcasecmp_m(argv[0], table[i].funcname) == 0)
    465466                        return table[i].fn(c, argc-1, argv+1);
    466467        }
  • vendor/current/source3/utils/net_printing.c

    r860 r988  
    440440        return run_rpc_command(c,
    441441                               NULL,
    442                                &ndr_table_winreg.syntax_id,
     442                               &ndr_table_winreg,
    443443                               0,
    444444                               printing_migrate_internal,
  • vendor/current/source3/utils/net_proto.h

    r740 r988  
    140140int run_rpc_command(struct net_context *c,
    141141                        struct cli_state *cli_arg,
    142                         const struct ndr_syntax_id *interface,
     142                        const struct ndr_interface_table *table,
    143143                        int conn_flags,
    144144                        rpc_command_fn fn,
     
    146146                        const char **argv);
    147147int net_rpc_changetrustpw(struct net_context *c, int argc, const char **argv);
     148int net_rpc_testjoin(struct net_context *c, int argc, const char **argv);
    148149int net_rpc_join(struct net_context *c, int argc, const char **argv);
    149150NTSTATUS rpc_info_internals(struct net_context *c,
     
    200201int net_rpc_audit(struct net_context *c, int argc, const char **argv);
    201202
    202 /* The following definitions come from utils/net_rpc_join.c  */
    203 
    204 NTSTATUS net_rpc_join_ok(struct net_context *c, const char *domain,
    205                          const char *server, struct sockaddr_storage *pss);
    206 int net_rpc_join_newstyle(struct net_context *c, int argc, const char **argv);
    207 int net_rpc_testjoin(struct net_context *c, int argc, const char **argv);
    208 
    209203/* The following definitions come from utils/net_rpc_printer.c  */
    210204
     
    339333/* The following definitions come from utils/net_rpc_service.c  */
    340334
    341 const char *svc_status_string( uint32 state );
     335const char *svc_status_string( uint32_t state );
    342336int net_rpc_service(struct net_context *c, int argc, const char **argv);
    343337
     
    401395                             enum lsa_SidType *ret_type);
    402396NTSTATUS connect_to_service(struct net_context *c,
    403                                         struct cli_state **cli_ctx,
    404                                         struct sockaddr_storage *server_ss,
    405                                         const char *server_name,
    406                                         const char *service_name,
    407                                         const char *service_type);
     397                            struct cli_state **cli_ctx,
     398                            const struct sockaddr_storage *server_ss,
     399                            const char *server_name,
     400                            const char *service_name,
     401                            const char *service_type);
    408402NTSTATUS connect_to_ipc(struct net_context *c,
    409403                        struct cli_state **cli_ctx,
    410                         struct sockaddr_storage *server_ss,
     404                        const struct sockaddr_storage *server_ss,
    411405                        const char *server_name);
    412406NTSTATUS connect_to_ipc_anonymous(struct net_context *c,
    413407                                struct cli_state **cli_ctx,
    414                                 struct sockaddr_storage *server_ss,
     408                                const struct sockaddr_storage *server_ss,
    415409                                const char *server_name);
    416 NTSTATUS connect_to_ipc_krb5(struct net_context *c,
    417                         struct cli_state **cli_ctx,
    418                         struct sockaddr_storage *server_ss,
    419                         const char *server_name);
    420410NTSTATUS connect_dst_pipe(struct net_context *c, struct cli_state **cli_dst,
    421411                          struct rpc_pipe_client **pp_pipe_hnd,
    422                           const struct ndr_syntax_id *interface);
     412                          const struct ndr_interface_table *table);
    423413int net_use_krb_machine_account(struct net_context *c);
    424414int net_use_machine_account(struct net_context *c);
     
    435425NTSTATUS net_make_ipc_connection_ex(struct net_context *c ,const char *domain,
    436426                                    const char *server,
    437                                     struct sockaddr_storage *pss,
     427                                    const struct sockaddr_storage *pss,
    438428                                    unsigned flags, struct cli_state **pcli);
    439429const char *net_prompt_pass(struct net_context *c, const char *user);
     
    469459int net_rpc_trust(struct net_context *c, int argc, const char **argv);
    470460
     461/* The following definitions come from utils/net_rpc_conf.c */
     462int net_rpc_conf(struct net_context *c, int argc, const char **argv);
     463
     464int net_notify(struct net_context *c, int argc, const char **argv);
    471465#endif /*  _NET_PROTO_H_  */
  • vendor/current/source3/utils/net_rap.c

    r740 r988  
    2929#include "libsmb/libsmb.h"
    3030#include "libsmb/clirap.h"
     31#include "../libcli/smb/smbXcli_base.h"
    3132
    3233/* The following messages were for error checking that is not properly
     
    5354  list info on an open file
    5455***************************************************************************/
    55 static void file_fn(const char * pPath, const char * pUser, uint16 perms,
    56                     uint16 locks, uint32 id)
     56static void file_fn(const char * pPath, const char * pUser, uint16_t perms,
     57                    uint16_t locks, uint32_t id)
    5758{
    5859        d_printf("%-7.1d %-20.20s 0x%-4.2x %-6.1d %s\n",
     
    6061}
    6162
    62 static void one_file_fn(const char *pPath, const char *pUser, uint16 perms,
    63                         uint16 locks, uint32 id)
     63static void one_file_fn(const char *pPath, const char *pUser, uint16_t perms,
     64                        uint16_t locks, uint32_t id)
    6465{
    6566        d_printf(_("File ID          %d\n"
     
    196197}
    197198
    198 static void long_share_fn(const char *share_name, uint32 type,
     199static void long_share_fn(const char *share_name, uint32_t type,
    199200                          const char *comment, void *state)
    200201{
     
    203204}
    204205
    205 static void share_fn(const char *share_name, uint32 type,
     206static void share_fn(const char *share_name, uint32_t type,
    206207                     const char *comment, void *state)
    207208{
     
    348349}
    349350
    350 static void list_sessions_func(char *wsname, char *username, uint16 conns,
    351                         uint16 opens, uint16 users, uint32 sess_time,
    352                         uint32 idle_time, uint32 user_flags, char *clitype)
     351static void list_sessions_func(char *wsname, char *username, uint16_t conns,
     352                        uint16_t opens, uint16_t users, uint32_t sess_time,
     353                        uint32_t idle_time, uint32_t user_flags, char *clitype)
    353354{
    354355        int hrs = idle_time / 3600;
     
    361362
    362363static void display_session_func(const char *wsname, const char *username,
    363                                  uint16 conns, uint16 opens, uint16 users,
    364                                  uint32 sess_time, uint32 idle_time,
    365                                  uint32 user_flags, const char *clitype)
     364                                 uint16_t conns, uint16_t opens, uint16_t users,
     365                                 uint32_t sess_time, uint32_t idle_time,
     366                                 uint32_t user_flags, const char *clitype)
    366367{
    367368        int ihrs = idle_time / 3600;
     
    382383}
    383384
    384 static void display_conns_func(uint16 conn_id, uint16 conn_type, uint16 opens,
    385                                uint16 users, uint32 conn_time,
     385static void display_conns_func(uint16_t conn_id, uint16_t conn_type, uint16_t opens,
     386                               uint16_t users, uint32_t conn_time,
    386387                               const char *username, const char *netname)
    387388{
     
    496497list a server name
    497498****************************************************************************/
    498 static void display_server_func(const char *name, uint32 m,
     499static void display_server_func(const char *name, uint32_t m,
    499500                                const char *comment, void * reserved)
    500501{
     
    634635}
    635636
    636 static void enum_queue(const char *queuename, uint16 pri, uint16 start,
    637                        uint16 until, const char *sep, const char *pproc,
     637static void enum_queue(const char *queuename, uint16_t pri, uint16_t start,
     638                       uint16_t until, const char *sep, const char *pproc,
    638639                       const char *dest, const char *qparms,
    639                        const char *qcomment, uint16 status, uint16 jobcount)
     640                       const char *qcomment, uint16_t status, uint16_t jobcount)
    640641{
    641642        d_printf(_("%-17.17s Queue %5d jobs                      "),
     
    660661}
    661662
    662 static void enum_jobs(uint16 jobid, const char *ownername,
     663static void enum_jobs(uint16_t jobid, const char *ownername,
    663664                      const char *notifyname, const char *datatype,
    664                       const char *jparms, uint16 pos, uint16 status,
     665                      const char *jparms, uint16_t pos, uint16_t status,
    665666                      const char *jstatus, unsigned int submitted, unsigned int jobsize,
    666667                      const char *comment)
     
    703704                return -1;
    704705
    705         d_printf(PRINTQ_ENUM_DISPLAY, cli->desthost); /* list header */
     706        d_printf(PRINTQ_ENUM_DISPLAY, smbXcli_conn_remote_name(cli->conn)); /* list header */
    706707        ret = cli_NetPrintQGetInfo(cli, argv[0], enum_queue, enum_jobs);
    707708        cli_shutdown(cli);
     
    764765                        return -1;
    765766
    766                 d_printf(PRINTQ_ENUM_DISPLAY, cli->desthost); /* list header */
     767                d_printf(PRINTQ_ENUM_DISPLAY, smbXcli_conn_remote_name(cli->conn)); /* list header */
    767768                ret = cli_NetPrintQEnum(cli, enum_queue, enum_jobs);
    768769                cli_shutdown(cli);
     
    826827                return -1;
    827828
    828         safe_strcpy((char *)userinfo.user_name, argv[0], sizeof(userinfo.user_name)-1);
     829        strlcpy((char *)userinfo.user_name, argv[0], sizeof(userinfo.user_name));
    829830        if (c->opt_flags == 0)
    830831                c->opt_flags = 0x21;
     
    971972
    972973        /* BB check for length 21 or smaller explicitly ? BB */
    973         safe_strcpy((char *)grinfo.group_name, argv[0], sizeof(grinfo.group_name)-1);
     974        strlcpy((char *)grinfo.group_name, argv[0], sizeof(grinfo.group_name));
    974975        grinfo.reserved1 = '\0';
    975976        grinfo.comment = smb_xstrdup(c->opt_comment ? c->opt_comment : "");
  • vendor/current/source3/utils/net_registry.c

    r740 r988  
    3131#include "registry/reg_import.h"
    3232#include "registry/reg_format.h"
     33#include "registry/reg_api_util.h"
    3334#include <assert.h>
    3435#include "../libcli/security/display_sec.h"
     
    3637#include "../libcli/registry/util_reg.h"
    3738#include "passdb/machine_sid.h"
     39#include "net_registry_check.h"
    3840
    3941/*
     
    4749 */
    4850static WERROR open_hive(TALLOC_CTX *ctx, const char *path,
    49                         uint32 desired_access,
     51                        uint32_t desired_access,
    5052                        struct registry_key **hive,
    5153                        char **subkeyname)
     
    9092
    9193static WERROR open_key(TALLOC_CTX *ctx, const char *path,
    92                        uint32 desired_access,
     94                       uint32_t desired_access,
    9395                       struct registry_key **key)
    9496{
     
    123125}
    124126
    125 static WERROR registry_enumkey(struct registry_key* parent, const char* keyname, bool recursive)
     127static WERROR registry_enumkey(struct registry_key *parent, const char *keyname,
     128                               bool recursive)
    126129{
    127130        WERROR werr;
    128131        TALLOC_CTX *ctx = talloc_stackframe();
    129         charsubkey_name;
     132        char *subkey_name;
    130133        NTTIME modtime;
    131134        uint32_t count;
    132         char* valname = NULL;
     135        char *valname = NULL;
    133136        struct registry_value *valvalue = NULL;
    134         struct registry_key* key = NULL;
     137        struct registry_key *key = NULL;
    135138
    136139        werr = reg_openkey(ctx, parent, keyname, REG_KEY_READ, &key);
     
    203206        WERROR werr;
    204207        struct registry_key *key = NULL;
    205         char* name = NULL;
     208        char *name = NULL;
    206209        TALLOC_CTX *ctx = talloc_stackframe();
    207210        int ret = -1;
     
    237240        WERROR werr;
    238241        struct registry_key *key = NULL;
    239         char* name = NULL;
     242        char *name = NULL;
    240243        TALLOC_CTX *ctx = talloc_stackframe();
    241244        int ret = -1;
     
    272275        WERROR werr;
    273276        enum winreg_CreateAction action;
    274         char *subkeyname;
     277        char *subkeyname = NULL;
    275278        struct registry_key *hivekey = NULL;
    276279        struct registry_key *subkey = NULL;
     
    331334{
    332335        WERROR werr;
    333         char *subkeyname;
     336        char *subkeyname = NULL;
    334337        struct registry_key *hivekey = NULL;
    335338        TALLOC_CTX *ctx = talloc_stackframe();
     
    642645
    643646        status = g_lock_do("registry_increment_lock", G_LOCK_WRITE,
    644                            timeval_set(600, 0), procid_self(),
     647                           timeval_set(600, 0),
    645648                           net_registry_increment_fn, &state);
    646649        if (!NT_STATUS_IS_OK(status)) {
     
    909912
    910913
    911 static WERROR import_create_key(struct import_ctx* ctx,
    912                                 struct registry_key* parent,
    913                                 const char* name, void** pkey, bool* existing)
    914 {
    915         WERROR werr;
    916         void* mem_ctx = talloc_new(ctx->mem_ctx);
    917 
    918         struct registry_key* key = NULL;
     914static WERROR import_create_key(struct import_ctx *ctx,
     915                                struct registry_key *parent,
     916                                const char *name, void **pkey, bool *existing)
     917{
     918        WERROR werr;
     919        TALLOC_CTX *mem_ctx = talloc_new(ctx->mem_ctx);
     920
     921        struct registry_key *key = NULL;
    919922        enum winreg_CreateAction action;
    920923
    921924        if (parent == NULL) {
    922                 char* subkeyname = NULL;
     925                char *subkeyname = NULL;
    923926                werr = open_hive(mem_ctx, name, REG_KEY_WRITE,
    924927                         &parent, &subkeyname);
     
    959962}
    960963
    961 static WERROR import_close_key(struct import_ctx* ctx,
    962                                struct registry_key* key)
     964static WERROR import_close_key(struct import_ctx *ctx,
     965                               struct registry_key *key)
    963966{
    964967        return WERR_OK;
    965968}
    966969
    967 static WERROR import_delete_key(struct import_ctx* ctx,
    968                                 struct registry_key* parent, const char* name)
    969 {
    970         WERROR werr;
    971         void* mem_ctx = talloc_new(talloc_tos());
     970static WERROR import_delete_key(struct import_ctx *ctx,
     971                                struct registry_key *parent, const char *name)
     972{
     973        WERROR werr;
     974        TALLOC_CTX *mem_ctx = talloc_new(talloc_tos());
    972975
    973976        if (parent == NULL) {
    974                 char* subkeyname = NULL;
     977                char *subkeyname = NULL;
    975978                werr = open_hive(mem_ctx, name, REG_KEY_WRITE,
    976979                         &parent, &subkeyname);
     
    985988        werr = reg_deletekey_recursive(parent, name);
    986989        if (!W_ERROR_IS_OK(werr)) {
    987                 d_fprintf(stderr, "reg_deletekey_recursive %s: %s\n", _("failed"),
    988                           win_errstr(werr));
     990                d_fprintf(stderr, "reg_deletekey_recursive %s: %s\n",
     991                          _("failed"), win_errstr(werr));
    989992                goto done;
    990993        }
     
    995998}
    996999
    997 static WERROR import_create_val (struct import_ctx* ctx,
    998                                  struct registry_key* parent, const char* name,
    999                                  const struct registry_value* value)
     1000static WERROR import_create_val (struct import_ctx *ctx,
     1001                                 struct registry_key *parent, const char *name,
     1002                                 const struct registry_value *value)
    10001003{
    10011004        WERROR werr;
     
    10131016}
    10141017
    1015 static WERROR import_delete_val (struct import_ctx* ctx, struct registry_key* parent, const char* name) {
     1018static WERROR import_delete_val (struct import_ctx *ctx,
     1019                                 struct registry_key *parent, const char *name)
     1020{
    10161021        WERROR werr;
    10171022
     
    10291034}
    10301035
    1031 
    1032 static int net_registry_import(struct net_context *c, int argc,
    1033                                const char **argv)
    1034 {
    1035         struct import_ctx import_ctx;
     1036struct precheck_ctx {
     1037        TALLOC_CTX *mem_ctx;
     1038        bool failed;
     1039};
     1040
     1041static WERROR precheck_create_key(struct precheck_ctx *ctx,
     1042                                  struct registry_key *parent,
     1043                                  const char *name, void **pkey, bool *existing)
     1044{
     1045        WERROR werr;
     1046        TALLOC_CTX *frame = talloc_stackframe();
     1047        struct registry_key *key = NULL;
     1048
     1049        if (parent == NULL) {
     1050                char *subkeyname = NULL;
     1051                werr = open_hive(frame, name, REG_KEY_READ,
     1052                                 &parent, &subkeyname);
     1053                if (!W_ERROR_IS_OK(werr)) {
     1054                        d_printf("Precheck: open_hive of [%s] failed: %s\n",
     1055                                 name, win_errstr(werr));
     1056                        goto done;
     1057                }
     1058                name = subkeyname;
     1059        }
     1060
     1061        werr = reg_openkey(frame, parent, name, 0, &key);
     1062        if (!W_ERROR_IS_OK(werr)) {
     1063                d_printf("Precheck: openkey [%s] failed: %s\n",
     1064                         name, win_errstr(werr));
     1065                goto done;
     1066        }
     1067
     1068        if (existing != NULL) {
     1069                *existing = true;
     1070        }
     1071
     1072        if (pkey != NULL) {
     1073                *pkey = talloc_steal(ctx->mem_ctx, key);
     1074        }
     1075
     1076done:
     1077        talloc_free(frame);
     1078        ctx->failed = !W_ERROR_IS_OK(werr);
     1079        return werr;
     1080}
     1081
     1082static WERROR precheck_close_key(struct precheck_ctx *ctx,
     1083                                 struct registry_key *key)
     1084{
     1085        talloc_free(key);
     1086        return WERR_OK;
     1087}
     1088
     1089static WERROR precheck_delete_key(struct precheck_ctx *ctx,
     1090                                  struct registry_key *parent, const char *name)
     1091{
     1092        WERROR werr;
     1093        TALLOC_CTX *frame = talloc_stackframe();
     1094        struct registry_key *key;
     1095
     1096        if (parent == NULL) {
     1097                char *subkeyname = NULL;
     1098                werr = open_hive(frame, name, REG_KEY_READ,
     1099                                 &parent, &subkeyname);
     1100                if (!W_ERROR_IS_OK(werr)) {
     1101                        d_printf("Precheck: open_hive of [%s] failed: %s\n",
     1102                                 name, win_errstr(werr));
     1103                        goto done;
     1104                }
     1105                name = subkeyname;
     1106        }
     1107
     1108        werr = reg_openkey(ctx->mem_ctx, parent, name, 0, &key);
     1109        if (W_ERROR_IS_OK(werr)) {
     1110                d_printf("Precheck: key [%s\\%s] should not exist\n",
     1111                         parent->key->name, name);
     1112                werr = WERR_FILE_EXISTS;
     1113        } else if (W_ERROR_EQUAL(werr, WERR_BADFILE)) {
     1114                werr = WERR_OK;
     1115        } else {
     1116                d_printf("Precheck: openkey [%s\\%s] failed: %s\n",
     1117                         parent->key->name, name, win_errstr(werr));
     1118        }
     1119
     1120done:
     1121        talloc_free(frame);
     1122        ctx->failed = !W_ERROR_IS_OK(werr);
     1123        return werr;
     1124}
     1125
     1126static WERROR precheck_create_val(struct precheck_ctx *ctx,
     1127                                  struct registry_key *parent,
     1128                                  const char *name,
     1129                                  const struct registry_value *value)
     1130{
     1131        TALLOC_CTX *frame = talloc_stackframe();
     1132        struct registry_value *old;
     1133        WERROR werr;
     1134
     1135        SMB_ASSERT(parent);
     1136
     1137        werr = reg_queryvalue(frame, parent, name, &old);
     1138        if (!W_ERROR_IS_OK(werr)) {
     1139                d_printf("Precheck: queryvalue \"%s\" of [%s] failed: %s\n",
     1140                         name, parent->key->name, win_errstr(werr));
     1141                goto done;
     1142        }
     1143        if (registry_value_cmp(value, old) != 0) {
     1144                d_printf("Precheck: unexpected value \"%s\" of key [%s]\n",
     1145                         name, parent->key->name);
     1146                ctx->failed = true;
     1147        }
     1148done:
     1149        talloc_free(frame);
     1150        return werr;
     1151}
     1152
     1153static WERROR precheck_delete_val(struct precheck_ctx *ctx,
     1154                                  struct registry_key *parent,
     1155                                  const char *name)
     1156{
     1157        TALLOC_CTX *frame = talloc_stackframe();
     1158        struct registry_value *old;
     1159        WERROR werr;
     1160
     1161        SMB_ASSERT(parent);
     1162
     1163        werr = reg_queryvalue(frame, parent, name, &old);
     1164        if (W_ERROR_IS_OK(werr)) {
     1165                d_printf("Precheck: value \"%s\" of key [%s] should not exist\n",
     1166                         name, parent->key->name);
     1167                werr = WERR_FILE_EXISTS;
     1168        } else if (W_ERROR_EQUAL(werr, WERR_BADFILE)) {
     1169                werr = WERR_OK;
     1170        } else {
     1171                printf("Precheck: queryvalue \"%s\" of key [%s] failed: %s\n",
     1172                       name, parent->key->name, win_errstr(werr));
     1173        }
     1174
     1175        talloc_free(frame);
     1176        ctx->failed = !W_ERROR_IS_OK(werr);
     1177        return werr;
     1178}
     1179
     1180static bool import_precheck(const char *fname, const char *parse_options)
     1181{
     1182        TALLOC_CTX *mem_ctx = talloc_tos();
     1183        struct precheck_ctx precheck_ctx = {
     1184                .mem_ctx = mem_ctx,
     1185                .failed = false,
     1186        };
     1187        struct reg_import_callback precheck_callback = {
     1188                .openkey     = NULL,
     1189                .closekey    = (reg_import_callback_closekey_t)&precheck_close_key,
     1190                .createkey   = (reg_import_callback_createkey_t)&precheck_create_key,
     1191                .deletekey   = (reg_import_callback_deletekey_t)&precheck_delete_key,
     1192                .deleteval   = (reg_import_callback_deleteval_t)&precheck_delete_val,
     1193                .setval      = {
     1194                        .registry_value = (reg_import_callback_setval_registry_value_t)
     1195                                          &precheck_create_val,
     1196                },
     1197                .setval_type = REGISTRY_VALUE,
     1198                .data        = &precheck_ctx
     1199        };
     1200        struct reg_parse_callback *parse_callback;
     1201        int ret;
     1202
     1203        if (!fname) {
     1204                return true;
     1205        }
     1206
     1207        parse_callback = reg_import_adapter(mem_ctx, precheck_callback);
     1208        if (parse_callback == NULL) {
     1209                d_printf("talloc failed\n");
     1210                return false;
     1211        }
     1212
     1213        ret = reg_parse_file(fname, parse_callback, parse_options);
     1214
     1215        if (ret < 0 || precheck_ctx.failed) {
     1216                d_printf("Precheck failed\n");
     1217                return false;
     1218        }
     1219        return true;
     1220}
     1221
     1222static int import_with_precheck_action(const char *import_fname,
     1223                                       const char *precheck_fname,
     1224                                       const char *parse_options)
     1225{
     1226        TALLOC_CTX *frame = talloc_stackframe();
     1227        struct import_ctx import_ctx = {
     1228                .mem_ctx = frame,
     1229        };
    10361230        struct reg_import_callback import_callback = {
    10371231                .openkey     = NULL,
     
    10471241                .data        = &import_ctx
    10481242        };
    1049 
    1050         int ret;
     1243        struct reg_parse_callback *parse_callback;
     1244        int ret = -1;
     1245        bool precheck_ok;
     1246
     1247        precheck_ok = import_precheck(precheck_fname, parse_options);
     1248        if (!precheck_ok) {
     1249                goto done;
     1250        }
     1251
     1252        parse_callback = reg_import_adapter(frame, import_callback);
     1253        if (parse_callback == NULL) {
     1254                d_printf("talloc failed\n");
     1255                goto done;
     1256        }
     1257
     1258        ret = reg_parse_file(import_fname, parse_callback, parse_options);
     1259
     1260done:
     1261        talloc_free(frame);
     1262        return ret;
     1263}
     1264
     1265static int net_registry_import(struct net_context *c, int argc,
     1266                               const char **argv)
     1267{
     1268        const char *parse_options =  (argc > 1) ? argv[1] : NULL;
     1269        int ret = -1;
     1270        WERROR werr;
    10511271
    10521272        if (argc < 1 || argc > 2 || c->display_usage) {
     
    10601280        }
    10611281
    1062         ZERO_STRUCT(import_ctx);
    1063         import_ctx.mem_ctx = talloc_stackframe();
    1064 
    1065         regdb_open();
    1066         regdb_transaction_start();
    1067 
    1068         ret = reg_parse_file(argv[0],
    1069                              reg_import_adapter(import_ctx.mem_ctx,
    1070                                                 import_callback),
    1071                              (argc > 1) ? argv[1] : NULL
    1072                 );
     1282        werr = regdb_open();
     1283        if (!W_ERROR_IS_OK(werr)) {
     1284                d_printf("Failed to open regdb: %s\n", win_errstr(werr));
     1285                return -1;
     1286        }
     1287
     1288        werr = regdb_transaction_start();
     1289        if (!W_ERROR_IS_OK(werr)) {
     1290                d_printf("Failed to start transaction on regdb: %s\n",
     1291                         win_errstr(werr));
     1292                goto done;
     1293        }
     1294
     1295        ret = import_with_precheck_action(argv[0], c->opt_precheck,
     1296                                          parse_options);
     1297
    10731298        if (ret < 0) {
    1074                 d_printf("reg_parse_file failed: transaction canceled\n");
     1299                d_printf("Transaction canceled!\n");
    10751300                regdb_transaction_cancel();
    1076         } else{
    1077                 regdb_transaction_commit();
    1078         }
    1079 
     1301                goto done;
     1302        }
     1303
     1304        SMB_ASSERT(ret == 0);
     1305
     1306        if (c->opt_testmode) {
     1307                d_printf("Testmode: not committing changes.\n");
     1308                regdb_transaction_cancel();
     1309                goto done;
     1310        }
     1311
     1312        werr = regdb_transaction_commit();
     1313        if (!W_ERROR_IS_OK(werr)) {
     1314                d_printf("Failed to commit transaction on regdb: %s\n",
     1315                         win_errstr(werr));
     1316                ret = -1;
     1317        }
     1318
     1319done:
    10801320        regdb_close();
    1081         talloc_free(import_ctx.mem_ctx);
    1082 
    10831321        return ret;
    10841322}
     
    10931331 */
    10941332
    1095 static int registry_export(TALLOC_CTX *ctx, /*const*/ struct registry_key* key,
    1096                            struct reg_format* f)
     1333static int registry_export(TALLOC_CTX *ctx, /*const*/ struct registry_key *key,
     1334                           struct reg_format *f)
    10971335{
    10981336        int ret=-1;
     
    11031341        char *valname = NULL;
    11041342
    1105         struct registry_key* subkey = NULL;
    11061343        char *subkey_name = NULL;
    11071344        NTTIME modtime = 0;
     
    11291366             count++)
    11301367        {
     1368                struct registry_key *subkey = NULL;
     1369
    11311370                werr = reg_openkey(ctx, key, subkey_name, REG_KEY_READ,
    11321371                                   &subkey);
     
    11381377
    11391378                registry_export(ctx, subkey, f);
     1379                TALLOC_FREE(subkey);
    11401380        }
    11411381        if (!W_ERROR_EQUAL(WERR_NO_MORE_ITEMS, werr)) {
     
    11561396        struct registry_key *key = NULL;
    11571397        TALLOC_CTX *ctx = talloc_stackframe();
    1158         struct reg_format* f=NULL;
     1398        struct reg_format *f=NULL;
    11591399
    11601400        if (argc < 2 || argc > 3 || c->display_usage) {
     
    12001440{
    12011441        int ret;
    1202         void* mem_ctx;
    1203         const char* in_opt  = NULL;
    1204         const char* out_opt = NULL;
     1442        TALLOC_CTX *mem_ctx;
     1443        const char *in_opt  = NULL;
     1444        const char *out_opt = NULL;
    12051445
    12061446        if (argc < 2 || argc > 4|| c->display_usage) {
     
    12421482/**@}*/
    12431483
     1484static int net_registry_check(struct net_context *c, int argc,
     1485                              const char **argv)
     1486{
     1487        char *dbfile;
     1488        struct check_options opts;
     1489        int ret;
     1490
     1491        if (argc > 1|| c->display_usage) {
     1492                d_printf("%s\n%s",
     1493                         _("Usage:"),
     1494                         _("net registry check  [-vraTfl] [-o <ODB>] [--wipe] [<TDB>]\n"
     1495                           "  Check a registry database.\n"
     1496                           "    -v|--verbose\t be verbose\n"
     1497                           "    -r|--repair\t\t interactive repair mode\n"
     1498                           "    -a|--auto\t\t noninteractive repair mode\n"
     1499                           "    -T|--test\t\t dry run\n"
     1500                           "    -f|--force\t\t force\n"
     1501                           "    -l|--lock\t\t lock <TDB> while doing the check\n"
     1502                           "    -o|--output=<ODB>\t output database\n"
     1503                           "    --reg-version=n\t assume database format version {n|1,2,3}\n"
     1504                           "    --wipe\t\t create a new database from scratch\n"
     1505                           "    --db=<TDB>\t\t registry database to open\n"));
     1506                return c->display_usage ? 0 : -1;
     1507        }
     1508
     1509        if (c->opt_db != NULL) {
     1510                dbfile = talloc_strdup(talloc_tos(), c->opt_db);
     1511        } else if (argc > 0) {
     1512                dbfile = talloc_strdup(talloc_tos(), argv[0]);
     1513        } else {
     1514                dbfile = state_path("registry.tdb");
     1515        }
     1516        if (dbfile == NULL) {
     1517                return -1;
     1518        }
     1519
     1520        opts = (struct check_options) {
     1521                .lock = c->opt_lock || c->opt_long_list_entries,
     1522                .test = c->opt_testmode,
     1523                .automatic = c->opt_auto,
     1524                .verbose = c->opt_verbose,
     1525                .force = c->opt_force,
     1526                .repair = c->opt_repair || c->opt_reboot,
     1527                .version = c->opt_reg_version,
     1528                .output  = c->opt_output,
     1529                .wipe = c->opt_wipe,
     1530                .implicit_db = (c->opt_db == NULL) && (argc == 0),
     1531        };
     1532
     1533        ret = net_registry_check_db(dbfile, &opts);
     1534        talloc_free(dbfile);
     1535        return ret;
     1536}
     1537
     1538
    12441539/******************************************************************************/
    12451540
     
    13851680                           "    Convert .reg file")
    13861681                },
     1682                {
     1683                        "check",
     1684                        net_registry_check,
     1685                        NET_TRANSPORT_LOCAL,
     1686                        N_("Check a registry database"),
     1687                        N_("net registry check\n"
     1688                           "    Check a registry database")
     1689                },
    13871690        { NULL, NULL, 0, NULL, NULL }
    13881691        };
    13891692
    1390         if (!W_ERROR_IS_OK(registry_init_basic())) {
    1391                 return -1;
     1693        if (!c->display_usage
     1694            && argc > 0
     1695            && (strcasecmp_m(argv[0], "convert") != 0)
     1696            && (strcasecmp_m(argv[0], "check") != 0))
     1697        {
     1698                if (!W_ERROR_IS_OK(registry_init_basic())) {
     1699                        return -1;
     1700                }
    13921701        }
    13931702
  • vendor/current/source3/utils/net_registry_util.c

    r740 r988  
    2828void print_registry_key(const char *keyname, NTTIME *modtime)
    2929{
     30        const char *ts = _("None");
     31        char *freeme = NULL;
     32
     33        if (modtime != 0) {
     34                freeme = http_timestring(talloc_tos(),
     35                                         nt_time_to_unix(*modtime));
     36                ts = freeme;
     37        }
     38
    3039        d_printf(_("Keyname   = %s\n"), keyname);
    31         d_printf(_("Modtime   = %s\n"),
    32                  modtime
    33                  ? http_timestring(talloc_tos(), nt_time_to_unix(*modtime))
    34                  : _("None"));
     40        d_printf(_("Modtime   = %s\n"), ts);
    3541        d_printf("\n");
     42
     43        TALLOC_FREE(freeme);
    3644}
    3745
     
    5159                        d_printf(_("Value      = "));
    5260                }
    53                 d_printf("%d\n", v);
     61                d_printf("%u\n", v);
    5462                break;
    5563        }
     
    7280        }
    7381        case REG_MULTI_SZ: {
    74                 uint32 j;
     82                uint32_t j;
    7583                const char **a;
    7684
  • vendor/current/source3/utils/net_rpc.c

    r860 r988  
    3838#include "lib/netapi/netapi.h"
    3939#include "lib/netapi/netapi_net.h"
     40#include "librpc/gen_ndr/libnet_join.h"
     41#include "libnet/libnet_join.h"
    4042#include "rpc_client/init_lsa.h"
    4143#include "../libcli/security/security.h"
     
    4446#include "nsswitch/libwbclient/wbclient.h"
    4547#include "passdb.h"
     48#include "../libcli/smb/smbXcli_base.h"
    4649
    4750static int net_mode_share;
     
    8285        struct dcerpc_binding_handle *b;
    8386
    84         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
     87        status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
    8588                                          &lsa_pipe);
    8689        if (!NT_STATUS_IS_OK(status)) {
     
    142145int run_rpc_command(struct net_context *c,
    143146                        struct cli_state *cli_arg,
    144                         const struct ndr_syntax_id *interface,
     147                        const struct ndr_interface_table *table,
    145148                        int conn_flags,
    146149                        rpc_command_fn fn,
     
    187190        if (!(conn_flags & NET_FLAGS_NO_PIPE)) {
    188191                if (lp_client_schannel()
    189                     && (ndr_syntax_id_equal(interface,
     192                    && (ndr_syntax_id_equal(&table->syntax_id,
    190193                                            &ndr_table_netlogon.syntax_id))) {
    191194                        /* Always try and create an schannel netlogon pipe. */
     195                        TALLOC_FREE(c->netlogon_creds);
    192196                        nt_status = cli_rpc_pipe_open_schannel(
    193                                 cli, interface, NCACN_NP,
    194                                 DCERPC_AUTH_LEVEL_PRIVACY, domain_name,
    195                                 &pipe_hnd);
     197                                cli, c->msg_ctx, table, NCACN_NP,
     198                                domain_name,
     199                                &pipe_hnd, c, &c->netlogon_creds);
    196200                        if (!NT_STATUS_IS_OK(nt_status)) {
    197201                                DEBUG(0, ("Could not initialise schannel netlogon pipe. Error was %s\n",
     
    201205                } else {
    202206                        if (conn_flags & NET_FLAGS_SEAL) {
    203                                 nt_status = cli_rpc_pipe_open_ntlmssp(
    204                                         cli, interface,
     207                                nt_status = cli_rpc_pipe_open_generic_auth(
     208                                        cli, table,
    205209                                        (conn_flags & NET_FLAGS_TCP) ?
    206210                                        NCACN_IP_TCP : NCACN_NP,
     211                                        CRED_DONT_USE_KERBEROS,
     212                                        DCERPC_AUTH_TYPE_NTLMSSP,
    207213                                        DCERPC_AUTH_LEVEL_PRIVACY,
     214                                        smbXcli_conn_remote_name(cli->conn),
    208215                                        lp_workgroup(), c->opt_user_name,
    209216                                        c->opt_password, &pipe_hnd);
    210217                        } else {
    211218                                nt_status = cli_rpc_pipe_open_noauth(
    212                                         cli, interface,
     219                                        cli, table,
    213220                                        &pipe_hnd);
    214221                        }
    215222                        if (!NT_STATUS_IS_OK(nt_status)) {
    216223                                DEBUG(0, ("Could not initialise pipe %s. Error was %s\n",
    217                                           get_pipe_name_from_syntax(
    218                                                   talloc_tos(), interface),
     224                                          table->name,
    219225                                        nt_errstr(nt_status) ));
    220226                                goto fail;
     
    275281        NTSTATUS status;
    276282
    277         status = trust_pw_find_change_and_store_it(pipe_hnd, mem_ctx, c->opt_target_workgroup);
     283        status = trust_pw_change(c->netlogon_creds,
     284                                 c->msg_ctx,
     285                                 pipe_hnd->binding_handle,
     286                                 c->opt_target_workgroup,
     287                                 true); /* force */
    278288        if (!NT_STATUS_IS_OK(status)) {
    279289                d_fprintf(stderr, _("Failed to change machine account password: %s\n"),
     
    306316        }
    307317
    308         return run_rpc_command(c, NULL, &ndr_table_netlogon.syntax_id,
     318        return run_rpc_command(c, NULL, &ndr_table_netlogon,
    309319                               NET_FLAGS_ANONYMOUS | NET_FLAGS_PDC,
    310320                               rpc_changetrustpw_internals,
     
    313323
    314324/**
    315  * Join a domain, the old way.
     325 * Join a domain, the old way.  This function exists to allow
     326 * the message to be displayed when oldjoin was explicitly
     327 * requested, but not when it was implied by "net rpc join".
    316328 *
    317329 * This uses 'machinename' as the inital password, and changes it.
     
    319331 * The password should be created with 'server manager' or equiv first.
    320332 *
    321  * All parameters are provided by the run_rpc_command function, except for
    322  * argc, argv which are passed through.
    323  *
    324  * @param domain_sid The domain sid acquired from the remote server.
    325  * @param cli A cli_state connected to the server.
    326  * @param mem_ctx Talloc context, destroyed on completion of the function.
    327333 * @param argc  Standard main() style argc.
    328334 * @param argv  Standard main() style argv. Initial components are already
    329335 *              stripped.
    330336 *
    331  * @return Normal NTSTATUS return.
     337 * @return A shell status integer (0 for success).
    332338 **/
    333339
    334 static NTSTATUS rpc_oldjoin_internals(struct net_context *c,
    335                                         const struct dom_sid *domain_sid,
    336                                         const char *domain_name,
    337                                         struct cli_state *cli,
    338                                         struct rpc_pipe_client *pipe_hnd,
    339                                         TALLOC_CTX *mem_ctx,
    340                                         int argc,
    341                                         const char **argv)
    342 {
    343 
    344         fstring trust_passwd;
    345         unsigned char orig_trust_passwd_hash[16];
    346         NTSTATUS result;
    347         enum netr_SchannelType sec_channel_type;
    348 
    349         result = cli_rpc_pipe_open_noauth(cli, &ndr_table_netlogon.syntax_id,
    350                                           &pipe_hnd);
    351         if (!NT_STATUS_IS_OK(result)) {
    352                 DEBUG(0,("rpc_oldjoin_internals: netlogon pipe open to machine %s failed. "
    353                         "error was %s\n",
    354                         cli->desthost,
    355                         nt_errstr(result) ));
    356                 return result;
     340static int net_rpc_oldjoin(struct net_context *c, int argc, const char **argv)
     341{
     342        struct libnet_JoinCtx *r = NULL;
     343        TALLOC_CTX *mem_ctx;
     344        WERROR werr;
     345        const char *domain = lp_workgroup(); /* FIXME */
     346        bool modify_config = lp_config_backend_is_registry();
     347        enum netr_SchannelType sec_chan_type;
     348        char *pw = NULL;
     349
     350        if (c->display_usage) {
     351                d_printf("Usage:\n"
     352                         "net rpc oldjoin\n"
     353                         "    Join a domain the old way\n");
     354                return 0;
     355        }
     356
     357        mem_ctx = talloc_init("net_rpc_oldjoin");
     358        if (!mem_ctx) {
     359                return -1;
     360        }
     361
     362        werr = libnet_init_JoinCtx(mem_ctx, &r);
     363        if (!W_ERROR_IS_OK(werr)) {
     364                goto fail;
    357365        }
    358366
     
    362370        */
    363371        if (argc >= 0) {
    364                 sec_channel_type = get_sec_channel_type(argv[0]);
     372                sec_chan_type = get_sec_channel_type(argv[0]);
    365373        } else {
    366                 sec_channel_type = get_sec_channel_type(NULL);
    367         }
    368 
    369         fstrcpy(trust_passwd, global_myname());
    370         strlower_m(trust_passwd);
     374                sec_chan_type = get_sec_channel_type(NULL);
     375        }
     376
     377        if (!c->msg_ctx) {
     378                d_fprintf(stderr, _("Could not initialise message context. "
     379                        "Try running as root\n"));
     380                werr = WERR_ACCESS_DENIED;
     381                goto fail;
     382        }
     383
     384        pw = talloc_strndup(r, lp_netbios_name(), 14);
     385        if (pw == NULL) {
     386                werr = WERR_NOMEM;
     387                goto fail;
     388        }
     389
     390        r->in.msg_ctx                   = c->msg_ctx;
     391        r->in.domain_name               = domain;
     392        r->in.secure_channel_type       = sec_chan_type;
     393        r->in.dc_name                   = c->opt_host;
     394        r->in.admin_account             = "";
     395        r->in.admin_password            = strlower_talloc(r, pw);
     396        if (r->in.admin_password == NULL) {
     397                werr = WERR_NOMEM;
     398                goto fail;
     399        }
     400        r->in.debug                     = true;
     401        r->in.modify_config             = modify_config;
     402        r->in.join_flags                = WKSSVC_JOIN_FLAGS_JOIN_TYPE |
     403                                          WKSSVC_JOIN_FLAGS_JOIN_UNSECURE |
     404                                          WKSSVC_JOIN_FLAGS_MACHINE_PWD_PASSED;
     405
     406        werr = libnet_Join(mem_ctx, r);
     407        if (!W_ERROR_IS_OK(werr)) {
     408                goto fail;
     409        }
     410
     411        /* Check the short name of the domain */
     412
     413        if (!modify_config && !strequal(lp_workgroup(), r->out.netbios_domain_name)) {
     414                d_printf("The workgroup in %s does not match the short\n", get_dyn_CONFIGFILE());
     415                d_printf("domain name obtained from the server.\n");
     416                d_printf("Using the name [%s] from the server.\n", r->out.netbios_domain_name);
     417                d_printf("You should set \"workgroup = %s\" in %s.\n",
     418                         r->out.netbios_domain_name, get_dyn_CONFIGFILE());
     419        }
     420
     421        d_printf("Using short domain name -- %s\n", r->out.netbios_domain_name);
     422
     423        if (r->out.dns_domain_name) {
     424                d_printf("Joined '%s' to realm '%s'\n", r->in.machine_name,
     425                        r->out.dns_domain_name);
     426        } else {
     427                d_printf("Joined '%s' to domain '%s'\n", r->in.machine_name,
     428                        r->out.netbios_domain_name);
     429        }
     430
     431        TALLOC_FREE(mem_ctx);
     432
     433        return 0;
     434
     435fail:
     436        if (c->opt_flags & NET_FLAGS_EXPECT_FALLBACK) {
     437                goto cleanup;
     438        }
     439
     440        /* issue an overall failure message at the end. */
     441        d_fprintf(stderr, _("Failed to join domain: %s\n"),
     442                r && r->out.error_string ? r->out.error_string :
     443                get_friendly_werror_msg(werr));
     444
     445cleanup:
     446        TALLOC_FREE(mem_ctx);
     447
     448        return -1;
     449}
     450
     451/**
     452 * check that a join is OK
     453 *
     454 * @return A shell status integer (0 for success)
     455 *
     456 **/
     457int net_rpc_testjoin(struct net_context *c, int argc, const char **argv)
     458{
     459        NTSTATUS status;
     460        TALLOC_CTX *mem_ctx;
     461        const char *domain = c->opt_target_workgroup;
     462        const char *dc = c->opt_host;
     463
     464        if (c->display_usage) {
     465                d_printf("Usage\n"
     466                         "net rpc testjoin\n"
     467                         "    Test if a join is OK\n");
     468                return 0;
     469        }
     470
     471        mem_ctx = talloc_init("net_rpc_testjoin");
     472        if (!mem_ctx) {
     473                return -1;
     474        }
     475
     476        if (!dc) {
     477                struct netr_DsRGetDCNameInfo *info;
     478
     479                if (!c->msg_ctx) {
     480                        d_fprintf(stderr, _("Could not initialise message context. "
     481                                "Try running as root\n"));
     482                        talloc_destroy(mem_ctx);
     483                        return -1;
     484                }
     485
     486                status = dsgetdcname(mem_ctx,
     487                                     c->msg_ctx,
     488                                     domain,
     489                                     NULL,
     490                                     NULL,
     491                                     DS_RETURN_DNS_NAME,
     492                                     &info);
     493                if (!NT_STATUS_IS_OK(status)) {
     494                        talloc_destroy(mem_ctx);
     495                        return -1;
     496                }
     497
     498                dc = strip_hostname(info->dc_unc);
     499        }
     500
     501        /* Display success or failure */
     502        status = libnet_join_ok(c->msg_ctx,
     503                                c->opt_workgroup,
     504                                dc,
     505                                c->opt_kerberos);
     506        if (!NT_STATUS_IS_OK(status)) {
     507                fprintf(stderr,"Join to domain '%s' is not valid: %s\n",
     508                        domain, nt_errstr(status));
     509                talloc_destroy(mem_ctx);
     510                return -1;
     511        }
     512
     513        printf("Join to '%s' is OK\n",domain);
     514        talloc_destroy(mem_ctx);
     515
     516        return 0;
     517}
     518
     519/**
     520 * Join a domain using the administrator username and password
     521 *
     522 * @param argc  Standard main() style argc
     523 * @param argc  Standard main() style argv.  Initial components are already
     524 *              stripped.  Currently not used.
     525 * @return A shell status integer (0 for success)
     526 *
     527 **/
     528
     529static int net_rpc_join_newstyle(struct net_context *c, int argc, const char **argv)
     530{
     531        struct libnet_JoinCtx *r = NULL;
     532        TALLOC_CTX *mem_ctx;
     533        WERROR werr;
     534        const char *domain = lp_workgroup(); /* FIXME */
     535        bool modify_config = lp_config_backend_is_registry();
     536        enum netr_SchannelType sec_chan_type;
     537
     538        if (c->display_usage) {
     539                d_printf("Usage:\n"
     540                         "net rpc join\n"
     541                         "    Join a domain the new way\n");
     542                return 0;
     543        }
     544
     545        mem_ctx = talloc_init("net_rpc_join_newstyle");
     546        if (!mem_ctx) {
     547                return -1;
     548        }
     549
     550        werr = libnet_init_JoinCtx(mem_ctx, &r);
     551        if (!W_ERROR_IS_OK(werr)) {
     552                goto fail;
     553        }
    371554
    372555        /*
    373          * Machine names can be 15 characters, but the max length on
    374          * a password is 14.  --jerry
    375          */
    376 
    377         trust_passwd[14] = '\0';
    378 
    379         E_md4hash(trust_passwd, orig_trust_passwd_hash);
    380 
    381         result = trust_pw_change_and_store_it(pipe_hnd, mem_ctx, c->opt_target_workgroup,
    382                                               global_myname(),
    383                                               orig_trust_passwd_hash,
    384                                               sec_channel_type);
    385 
    386         if (NT_STATUS_IS_OK(result))
    387                 printf(_("Joined domain %s.\n"), c->opt_target_workgroup);
    388 
    389 
    390         if (!secrets_store_domain_sid(c->opt_target_workgroup, domain_sid)) {
    391                 DEBUG(0, ("error storing domain sid for %s\n", c->opt_target_workgroup));
    392                 result = NT_STATUS_UNSUCCESSFUL;
    393         }
    394 
    395         return result;
    396 }
    397 
    398 /**
    399  * Join a domain, the old way.
    400  *
    401  * @param argc  Standard main() style argc.
    402  * @param argv  Standard main() style argv. Initial components are already
    403  *              stripped.
    404  *
    405  * @return A shell status integer (0 for success).
    406  **/
    407 
    408 static int net_rpc_perform_oldjoin(struct net_context *c, int argc, const char **argv)
    409 {
    410         return run_rpc_command(c, NULL, &ndr_table_netlogon.syntax_id,
    411                                NET_FLAGS_NO_PIPE | NET_FLAGS_ANONYMOUS | NET_FLAGS_PDC,
    412                                rpc_oldjoin_internals,
    413                                argc, argv);
    414 }
    415 
    416 /**
    417  * Join a domain, the old way.  This function exists to allow
    418  * the message to be displayed when oldjoin was explicitly
    419  * requested, but not when it was implied by "net rpc join".
    420  *
    421  * @param argc  Standard main() style argc.
    422  * @param argv  Standard main() style argv. Initial components are already
    423  *              stripped.
    424  *
    425  * @return A shell status integer (0 for success).
    426  **/
    427 
    428 static int net_rpc_oldjoin(struct net_context *c, int argc, const char **argv)
    429 {
    430         int rc = -1;
    431 
    432         if (c->display_usage) {
    433                 d_printf(  "%s\n"
    434                            "net rpc oldjoin\n"
    435                            "    %s\n",
    436                          _("Usage:"),
    437                          _("Join a domain the old way"));
    438                 return 0;
    439         }
    440 
    441         rc = net_rpc_perform_oldjoin(c, argc, argv);
    442 
    443         if (rc) {
    444                 d_fprintf(stderr, _("Failed to join domain\n"));
    445         }
    446 
    447         return rc;
     556           check what type of join - if the user want's to join as
     557           a BDC, the server must agree that we are a BDC.
     558        */
     559        if (argc >= 0) {
     560                sec_chan_type = get_sec_channel_type(argv[0]);
     561        } else {
     562                sec_chan_type = get_sec_channel_type(NULL);
     563        }
     564
     565        if (!c->msg_ctx) {
     566                d_fprintf(stderr, _("Could not initialise message context. "
     567                        "Try running as root\n"));
     568                werr = WERR_ACCESS_DENIED;
     569                goto fail;
     570        }
     571
     572        r->in.msg_ctx                   = c->msg_ctx;
     573        r->in.domain_name               = domain;
     574        r->in.secure_channel_type       = sec_chan_type;
     575        r->in.dc_name                   = c->opt_host;
     576        r->in.admin_account             = c->opt_user_name;
     577        r->in.admin_password            = net_prompt_pass(c, c->opt_user_name);
     578        r->in.debug                     = true;
     579        r->in.use_kerberos              = c->opt_kerberos;
     580        r->in.modify_config             = modify_config;
     581        r->in.join_flags                = WKSSVC_JOIN_FLAGS_JOIN_TYPE |
     582                                          WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE |
     583                                          WKSSVC_JOIN_FLAGS_DOMAIN_JOIN_IF_JOINED;
     584
     585        werr = libnet_Join(mem_ctx, r);
     586        if (!W_ERROR_IS_OK(werr)) {
     587                goto fail;
     588        }
     589
     590        /* Check the short name of the domain */
     591
     592        if (!modify_config && !strequal(lp_workgroup(), r->out.netbios_domain_name)) {
     593                d_printf("The workgroup in %s does not match the short\n", get_dyn_CONFIGFILE());
     594                d_printf("domain name obtained from the server.\n");
     595                d_printf("Using the name [%s] from the server.\n", r->out.netbios_domain_name);
     596                d_printf("You should set \"workgroup = %s\" in %s.\n",
     597                         r->out.netbios_domain_name, get_dyn_CONFIGFILE());
     598        }
     599
     600        d_printf("Using short domain name -- %s\n", r->out.netbios_domain_name);
     601
     602        if (r->out.dns_domain_name) {
     603                d_printf("Joined '%s' to realm '%s'\n", r->in.machine_name,
     604                        r->out.dns_domain_name);
     605        } else {
     606                d_printf("Joined '%s' to domain '%s'\n", r->in.machine_name,
     607                        r->out.netbios_domain_name);
     608        }
     609
     610        TALLOC_FREE(mem_ctx);
     611
     612        return 0;
     613
     614fail:
     615        /* issue an overall failure message at the end. */
     616        d_printf("Failed to join domain: %s\n",
     617                r && r->out.error_string ? r->out.error_string :
     618                get_friendly_werror_msg(werr));
     619
     620        TALLOC_FREE(mem_ctx);
     621
     622        return -1;
    448623}
    449624
     
    462637int net_rpc_join(struct net_context *c, int argc, const char **argv)
    463638{
     639        int ret;
     640
    464641        if (c->display_usage) {
    465642                d_printf("%s\n%s",
     
    482659        }
    483660
    484         if (strlen(global_myname()) > 15) {
     661        if (strlen(lp_netbios_name()) > 15) {
    485662                d_printf(_("Our netbios name can be at most 15 chars long, "
    486663                           "\"%s\" is %u chars long\n"),
    487                          global_myname(), (unsigned int)strlen(global_myname()));
     664                         lp_netbios_name(), (unsigned int)strlen(lp_netbios_name()));
    488665                return -1;
    489666        }
    490667
    491         if ((net_rpc_perform_oldjoin(c, argc, argv) == 0))
     668        c->opt_flags |= NET_FLAGS_EXPECT_FALLBACK;
     669        ret = net_rpc_oldjoin(c, argc, argv);
     670        c->opt_flags &= ~NET_FLAGS_EXPECT_FALLBACK;
     671        if (ret == 0) {
    492672                return 0;
     673        }
    493674
    494675        return net_rpc_join_newstyle(c, argc, argv);
     
    551732                                        &connect_pol,
    552733                                        MAXIMUM_ALLOWED_ACCESS,
    553                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
     734                                        discard_const_p(struct dom_sid2, domain_sid),
    554735                                        &domain_pol,
    555736                                        &result);
     
    608789        }
    609790
    610         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id,
     791        return run_rpc_command(c, NULL, &ndr_table_samr,
    611792                               NET_FLAGS_PDC, rpc_info_internals,
    612793                               argc, argv);
     
    676857        }
    677858
    678         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id,
     859        return run_rpc_command(c, NULL, &ndr_table_samr,
    679860                               conn_flags,
    680861                               rpc_getsid_internals,
     
    8851066                u1003.usri1003_password = argv[1];
    8861067        } else {
     1068                char pwd[256] = {0};
    8871069                ret = asprintf(&prompt, _("Enter new password for %s:"),
    8881070                               argv[0]);
     
    8901072                        return -1;
    8911073                }
    892                 u1003.usri1003_password = talloc_strdup(c, getpass(prompt));
     1074
     1075                ret = samba_getpass(prompt, pwd, sizeof(pwd), false, false);
    8931076                SAFE_FREE(prompt);
     1077                if (ret < 0) {
     1078                        return -1;
     1079                }
     1080
     1081                u1003.usri1003_password = talloc_strdup(c, pwd);
    8941082                if (u1003.usri1003_password == NULL) {
    8951083                        return -1;
     
    11491337        NTSTATUS status, result;
    11501338        struct dom_sid sid;
    1151         uint32 rid;
     1339        uint32_t rid;
    11521340        enum lsa_SidType type;
    11531341        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
     
    11631351        ZERO_STRUCT(user_pol);
    11641352
    1165         status = net_rpc_lookup_name(c, mem_ctx, rpc_pipe_np_smb_conn(pipe_hnd),
     1353        status = net_rpc_lookup_name(c, mem_ctx, ctx->cli,
    11661354                                     argv[0], NULL, NULL, &sid, &type);
    11671355        if (!NT_STATUS_IS_OK(status)) {
     
    14031591        const char *username;
    14041592        const char *oldval = "unknown";
    1405         uint32 oldflags, newflags;
     1593        uint32_t oldflags, newflags;
    14061594        bool newval;
    14071595        union samr_UserInfo *info = NULL;
     
    14871675        static struct rpc_sh_cmd cmds[] = {
    14881676
    1489                 { "fullname", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_str_edit,
     1677                { "fullname", NULL, &ndr_table_samr, rpc_sh_user_str_edit,
    14901678                  N_("Show/Set a user's full name") },
    14911679
    1492                 { "homedir", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_str_edit,
     1680                { "homedir", NULL, &ndr_table_samr, rpc_sh_user_str_edit,
    14931681                  N_("Show/Set a user's home directory") },
    14941682
    1495                 { "homedrive", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_str_edit,
     1683                { "homedrive", NULL, &ndr_table_samr, rpc_sh_user_str_edit,
    14961684                  N_("Show/Set a user's home drive") },
    14971685
    1498                 { "logonscript", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_str_edit,
     1686                { "logonscript", NULL, &ndr_table_samr, rpc_sh_user_str_edit,
    14991687                  N_("Show/Set a user's logon script") },
    15001688
    1501                 { "profilepath", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_str_edit,
     1689                { "profilepath", NULL, &ndr_table_samr, rpc_sh_user_str_edit,
    15021690                  N_("Show/Set a user's profile path") },
    15031691
    1504                 { "description", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_str_edit,
     1692                { "description", NULL, &ndr_table_samr, rpc_sh_user_str_edit,
    15051693                  N_("Show/Set a user's description") },
    15061694
    1507                 { "disabled", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_flag_edit,
     1695                { "disabled", NULL, &ndr_table_samr, rpc_sh_user_flag_edit,
    15081696                  N_("Show/Set whether a user is disabled") },
    15091697
    1510                 { "autolock", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_flag_edit,
     1698                { "autolock", NULL, &ndr_table_samr, rpc_sh_user_flag_edit,
    15111699                  N_("Show/Set whether a user locked out") },
    15121700
    1513                 { "pwnotreq", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_flag_edit,
     1701                { "pwnotreq", NULL, &ndr_table_samr, rpc_sh_user_flag_edit,
    15141702                  N_("Show/Set whether a user does not need a password") },
    15151703
    1516                 { "pwnoexp", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_flag_edit,
     1704                { "pwnoexp", NULL, &ndr_table_samr, rpc_sh_user_flag_edit,
    15171705                  N_("Show/Set whether a user's password does not expire") },
    15181706
     
    15291717        static struct rpc_sh_cmd cmds[] = {
    15301718
    1531                 { "list", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_list,
     1719                { "list", NULL, &ndr_table_samr, rpc_sh_user_list,
    15321720                  N_("List available users") },
    15331721
    1534                 { "info", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_info,
     1722                { "info", NULL, &ndr_table_samr, rpc_sh_user_info,
    15351723                  N_("List the domain groups a user is member of") },
    15361724
    1537                 { "show", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_show,
     1725                { "show", NULL, &ndr_table_samr, rpc_sh_user_show,
    15381726                  N_("Show info about a user") },
    15391727
     
    16241812                                        &connect_pol,
    16251813                                        MAXIMUM_ALLOWED_ACCESS,
    1626                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
     1814                                        discard_const_p(struct dom_sid2, domain_sid),
    16271815                                        &domain_pol,
    16281816                                        &result);
     
    18652053static int rpc_group_delete(struct net_context *c, int argc, const char **argv)
    18662054{
    1867         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
     2055        return run_rpc_command(c, NULL, &ndr_table_samr, 0,
    18682056                               rpc_group_delete_internals, argc,argv);
    18692057}
     
    19562144        struct dcerpc_binding_handle *b;
    19572145
    1958         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
     2146        status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
    19592147                                          &pipe_hnd);
    19602148        if (!NT_STATUS_IS_OK(status)) {
     
    19862174        }
    19872175
    1988         if (!NT_STATUS_IS_OK(status) && (StrnCaseCmp(name, "S-", 2) == 0)) {
     2176        if (!NT_STATUS_IS_OK(status) && (strncasecmp_m(name, "S-", 2) == 0)) {
    19892177
    19902178                /* Try as S-1-5-whatever */
     
    20092197        struct policy_handle connect_pol, domain_pol;
    20102198        NTSTATUS status, result;
    2011         uint32 group_rid;
     2199        uint32_t group_rid;
    20122200        struct policy_handle group_pol;
    20132201        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
     
    21132301
    21142302static NTSTATUS rpc_add_aliasmem(struct rpc_pipe_client *pipe_hnd,
    2115                                 TALLOC_CTX *mem_ctx,
    2116                                 const struct dom_sid *alias_sid,
    2117                                 const char *member)
     2303                                 struct cli_state *cli,
     2304                                 TALLOC_CTX *mem_ctx,
     2305                                 const struct dom_sid *alias_sid,
     2306                                 const char *member)
    21182307{
    21192308        struct policy_handle connect_pol, domain_pol;
    21202309        NTSTATUS status, result;
    2121         uint32 alias_rid;
     2310        uint32_t alias_rid;
    21222311        struct policy_handle alias_pol;
    21232312        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
     
    21342323        }
    21352324
    2136         result = get_sid_from_name(rpc_pipe_np_smb_conn(pipe_hnd), mem_ctx,
     2325        result = get_sid_from_name(cli, mem_ctx,
    21372326                                   member, &member_sid, &member_type);
    21382327
     
    22412430
    22422431        if (group_type == SID_NAME_ALIAS) {
    2243                 NTSTATUS result = rpc_add_aliasmem(pipe_hnd, mem_ctx,
     2432                NTSTATUS result = rpc_add_aliasmem(pipe_hnd, cli, mem_ctx,
    22442433                                                   &group_sid, argv[1]);
    22452434
     
    22592448static int rpc_group_addmem(struct net_context *c, int argc, const char **argv)
    22602449{
    2261         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
     2450        return run_rpc_command(c, NULL, &ndr_table_samr, 0,
    22622451                               rpc_group_addmem_internals,
    22632452                               argc, argv);
     
    22722461        struct policy_handle connect_pol, domain_pol;
    22732462        NTSTATUS status, result;
    2274         uint32 group_rid;
     2463        uint32_t group_rid;
    22752464        struct policy_handle group_pol;
    22762465        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
     
    23732562
    23742563static NTSTATUS rpc_del_aliasmem(struct rpc_pipe_client *pipe_hnd,
    2375                                 TALLOC_CTX *mem_ctx,
    2376                                 const struct dom_sid *alias_sid,
    2377                                 const char *member)
     2564                                 struct cli_state *cli,
     2565                                 TALLOC_CTX *mem_ctx,
     2566                                 const struct dom_sid *alias_sid,
     2567                                 const char *member)
    23782568{
    23792569        struct policy_handle connect_pol, domain_pol;
    23802570        NTSTATUS status, result;
    2381         uint32 alias_rid;
     2571        uint32_t alias_rid;
    23822572        struct policy_handle alias_pol;
    23832573        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
     
    23932583                return NT_STATUS_UNSUCCESSFUL;
    23942584
    2395         result = get_sid_from_name(rpc_pipe_np_smb_conn(pipe_hnd), mem_ctx,
     2585        result = get_sid_from_name(cli, mem_ctx,
    23962586                                   member, &member_sid, &member_type);
    23972587
     
    25022692
    25032693        if (group_type == SID_NAME_ALIAS) {
    2504                 NTSTATUS result = rpc_del_aliasmem(pipe_hnd, mem_ctx,
     2694                NTSTATUS result = rpc_del_aliasmem(pipe_hnd, cli, mem_ctx,
    25052695                                                   &group_sid, argv[1]);
    25062696
     
    25202710static int rpc_group_delmem(struct net_context *c, int argc, const char **argv)
    25212711{
    2522         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
     2712        return run_rpc_command(c, NULL, &ndr_table_samr, 0,
    25232713                               rpc_group_delmem_internals,
    25242714                               argc, argv);
     
    25522742        struct policy_handle connect_pol, domain_pol;
    25532743        NTSTATUS status, result;
    2554         uint32 start_idx=0, max_entries=250, num_entries, i, loop_count = 0;
     2744        uint32_t start_idx=0, max_entries=250, num_entries, i, loop_count = 0;
    25552745        struct samr_SamArray *groups = NULL;
    25562746        bool global = false;
     
    26102800                                        &connect_pol,
    26112801                                        MAXIMUM_ALLOWED_ACCESS,
    2612                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
     2802                                        discard_const_p(struct dom_sid2, domain_sid),
    26132803                                        &domain_pol,
    26142804                                        &result);
     
    27362926                                        &connect_pol,
    27372927                                        MAXIMUM_ALLOWED_ACCESS,
    2738                                         CONST_DISCARD(struct dom_sid2 *, &global_sid_Builtin),
     2928                                        discard_const_p(struct dom_sid2, &global_sid_Builtin),
    27392929                                        &domain_pol,
    27402930                                        &result);
     
    28193009static int rpc_group_list(struct net_context *c, int argc, const char **argv)
    28203010{
    2821         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
     3011        return run_rpc_command(c, NULL, &ndr_table_samr, 0,
    28223012                               rpc_group_list_internals,
    28233013                               argc, argv);
     
    28303020                                        const struct dom_sid *domain_sid,
    28313021                                        struct policy_handle *domain_pol,
    2832                                         uint32 rid)
     3022                                        uint32_t rid)
    28333023{
    28343024        NTSTATUS result, status;
    28353025        struct policy_handle group_pol;
    2836         uint32 num_members, *group_rids;
     3026        uint32_t num_members, *group_rids;
    28373027        int i;
    28383028        struct samr_RidAttrArray *rids = NULL;
     
    29203110
    29213111static NTSTATUS rpc_list_alias_members(struct net_context *c,
    2922                                         struct rpc_pipe_client *pipe_hnd,
    2923                                         TALLOC_CTX *mem_ctx,
    2924                                         struct policy_handle *domain_pol,
    2925                                         uint32 rid)
     3112                                       struct rpc_pipe_client *pipe_hnd,
     3113                                       struct cli_state *cli,
     3114                                       TALLOC_CTX *mem_ctx,
     3115                                       struct policy_handle *domain_pol,
     3116                                       uint32_t rid)
    29263117{
    29273118        NTSTATUS result, status;
    29283119        struct rpc_pipe_client *lsa_pipe;
    29293120        struct policy_handle alias_pol, lsa_pol;
    2930         uint32 num_members;
     3121        uint32_t num_members;
    29313122        struct dom_sid *alias_sids;
    29323123        char **domains;
     
    29693160        }
    29703161
    2971         result = cli_rpc_pipe_open_noauth(rpc_pipe_np_smb_conn(pipe_hnd),
    2972                                           &ndr_table_lsarpc.syntax_id,
     3162        result = cli_rpc_pipe_open_noauth(cli,
     3163                                          &ndr_table_lsarpc,
    29733164                                          &lsa_pipe);
    29743165        if (!NT_STATUS_IS_OK(result)) {
     
    29873178        }
    29883179
    2989         alias_sids = TALLOC_ZERO_ARRAY(mem_ctx, struct dom_sid, num_members);
     3180        alias_sids = talloc_zero_array(mem_ctx, struct dom_sid, num_members);
    29903181        if (!alias_sids) {
    29913182                d_fprintf(stderr, _("Out of memory\n"));
     
    30633254                                        &connect_pol,
    30643255                                        MAXIMUM_ALLOWED_ACCESS,
    3065                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
     3256                                        discard_const_p(struct dom_sid2, domain_sid),
    30663257                                        &domain_pol,
    30673258                                        &result);
     
    31473338
    31483339        if (rid_types.ids[0] == SID_NAME_ALIAS) {
    3149                 return rpc_list_alias_members(c, pipe_hnd, mem_ctx, &domain_pol,
     3340                return rpc_list_alias_members(c, pipe_hnd, cli, mem_ctx, &domain_pol,
    31503341                                              rids.ids[0]);
    31513342        }
     
    31603351        }
    31613352
    3162         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
     3353        return run_rpc_command(c, NULL, &ndr_table_samr, 0,
    31633354                               rpc_group_members_internals,
    31643355                               argc, argv);
     
    32953486                }
    32963487
    3297                 return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
     3488                return run_rpc_command(c, NULL, &ndr_table_samr, 0,
    32983489                                       rpc_group_list_internals,
    32993490                                       argc, argv);
     
    33253516        char *sharename;
    33263517        char *path;
    3327         uint32 type = STYPE_DISKTREE; /* only allow disk shares to be added */
    3328         uint32 num_users=0, perms=0;
     3518        uint32_t type = STYPE_DISKTREE; /* only allow disk shares to be added */
     3519        uint32_t num_users=0, perms=0;
    33293520        char *password=NULL; /* don't allow a share password */
    33303521        struct SHARE_INFO_2 i2;
     
    34083599                             struct rpc_pipe_client *pipe_hnd,
    34093600                             TALLOC_CTX *mem_ctx,
    3410                              uint32 level,
     3601                             uint32_t level,
    34113602                             int argc,
    34123603                             const char **argv,
     
    34673658                struct srvsvc_NetShareCtr1 *ctr1;
    34683659
    3469                 ctr1 = TALLOC_ZERO_P(mem_ctx, struct srvsvc_NetShareCtr1);
     3660                ctr1 = talloc_zero(mem_ctx, struct srvsvc_NetShareCtr1);
    34703661                W_ERROR_HAVE_NO_MEMORY(ctr1);
    34713662
     
    34813672                struct srvsvc_NetShareCtr2 *ctr2;
    34823673
    3483                 ctr2 = TALLOC_ZERO_P(mem_ctx, struct srvsvc_NetShareCtr2);
     3674                ctr2 = talloc_zero(mem_ctx, struct srvsvc_NetShareCtr2);
    34843675                W_ERROR_HAVE_NO_MEMORY(ctr2);
    34853676
     
    34953686                struct srvsvc_NetShareCtr502 *ctr502;
    34963687
    3497                 ctr502 = TALLOC_ZERO_P(mem_ctx, struct srvsvc_NetShareCtr502);
     3688                ctr502 = talloc_zero(mem_ctx, struct srvsvc_NetShareCtr502);
    34983689                W_ERROR_HAVE_NO_MEMORY(ctr502);
    34993690
     
    35633754        NTSTATUS status;
    35643755
    3565         status = cli_tcon_andx(cli, netname, "A:", "", 0);
     3756        status = cli_tree_connect(cli, netname, "A:", "", 0);
    35663757        if (!NT_STATUS_IS_OK(status)) {
    35673758                d_printf(_("skipping   [%s]: not a file share.\n"), netname);
     
    35793770
    35803771static bool check_share_sanity(struct net_context *c, struct cli_state *cli,
    3581                                const char *netname, uint32 type)
     3772                               const char *netname, uint32_t type)
    35823773{
    35833774        /* only support disk shares */
     
    36303821        NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
    36313822        struct srvsvc_NetShareInfoCtr ctr_src;
    3632         uint32 i;
     3823        uint32_t i;
    36333824        struct rpc_pipe_client *srvsvc_pipe = NULL;
    36343825        struct cli_state *cli_dst = NULL;
    3635         uint32 level = 502; /* includes secdesc */
     3826        uint32_t level = 502; /* includes secdesc */
    36363827        uint32_t parm_error = 0;
    36373828        struct dcerpc_binding_handle *b;
     
    36443835        /* connect destination PI_SRVSVC */
    36453836        nt_status = connect_dst_pipe(c, &cli_dst, &srvsvc_pipe,
    3646                                      &ndr_table_srvsvc.syntax_id);
     3837                                     &ndr_table_srvsvc);
    36473838        if (!NT_STATUS_IS_OK(nt_status))
    36483839                return nt_status;
     
    37333924        }
    37343925
    3735         return run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
     3926        return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
    37363927                               rpc_share_migrate_shares_internals,
    37373928                               argc, argv);
     
    38003991
    38013992                /* search below that directory */
    3802                 fstrcpy(new_mask, dir);
    3803                 fstrcat(new_mask, "\\*");
     3993                if (strlcpy(new_mask, dir, sizeof(new_mask)) >= sizeof(new_mask)) {
     3994                        return NT_STATUS_NO_MEMORY;
     3995                }
     3996                if (strlcat(new_mask, "\\*", sizeof(new_mask)) >= sizeof(new_mask)) {
     3997                        return NT_STATUS_NO_MEMORY;
     3998                }
    38043999
    38054000                old_dir = local_state->cwd;
     
    38634058        DEBUG(3,("calling cli_list with mask: %s\n", mask));
    38644059
    3865         if ( !cli_resolve_path(talloc_tos(), "", NULL, cp_clistate->cli_share_src,
    3866                                 mask, &targetcli, &targetpath ) ) {
     4060        status = cli_resolve_path(talloc_tos(), "", NULL,
     4061                                  cp_clistate->cli_share_src,
     4062                                  mask, &targetcli, &targetpath);
     4063        if (!NT_STATUS_IS_OK(status)) {
    38674064                d_fprintf(stderr, _("cli_resolve_path %s failed with error: "
    38684065                                    "%s\n"),
    3869                         mask, cli_errstr(cp_clistate->cli_share_src));
    3870                 return cli_nt_error(cp_clistate->cli_share_src);
     4066                        mask, nt_errstr(status));
     4067                return status;
    38714068        }
    38724069
     
    39494146        NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
    39504147        struct srvsvc_NetShareInfoCtr ctr_src;
    3951         uint32 i;
    3952         uint32 level = 502;
     4148        uint32_t i;
     4149        uint32_t level = 502;
    39534150        struct copy_clistate cp_clistate;
    39544151        bool got_src_share = false;
     
    40104207                /* open share source */
    40114208                nt_status = connect_to_service(c, &cp_clistate.cli_share_src,
    4012                                                &cli->dest_ss, cli->desthost,
     4209                                               smbXcli_conn_remote_sockaddr(cli->conn),
     4210                                               smbXcli_conn_remote_name(cli->conn),
    40134211                                               info502.name, "A:");
    40144212                if (!NT_STATUS_IS_OK(nt_status))
     
    40744272        }
    40754273
    4076         return run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
     4274        return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
    40774275                               rpc_share_migrate_files_internals,
    40784276                               argc, argv);
     
    41084306        struct srvsvc_NetShareInfoCtr ctr_src;
    41094307        union srvsvc_NetShareInfo info;
    4110         uint32 i;
     4308        uint32_t i;
    41114309        struct rpc_pipe_client *srvsvc_pipe = NULL;
    41124310        struct cli_state *cli_dst = NULL;
    4113         uint32 level = 502; /* includes secdesc */
     4311        uint32_t level = 502; /* includes secdesc */
    41144312        uint32_t parm_error = 0;
    41154313        struct dcerpc_binding_handle *b;
     
    41234321        /* connect destination PI_SRVSVC */
    41244322        nt_status = connect_dst_pipe(c, &cli_dst, &srvsvc_pipe,
    4125                                      &ndr_table_srvsvc.syntax_id);
     4323                                     &ndr_table_srvsvc);
    41264324        if (!NT_STATUS_IS_OK(nt_status))
    41274325                return nt_status;
     
    42094407        }
    42104408
    4211         return run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
     4409        return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
    42124410                               rpc_share_migrate_security_internals,
    42134411                               argc, argv);
     
    42474445         * before copying files - gd */
    42484446
    4249         ret = run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
     4447        ret = run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
    42504448                              rpc_share_migrate_shares_internals, argc, argv);
    42514449        if (ret)
    42524450                return ret;
    42534451
    4254         ret = run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
     4452        ret = run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
    42554453                              rpc_share_migrate_files_internals, argc, argv);
    42564454        if (ret)
    42574455                return ret;
    42584456
    4259         return run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
     4457        return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
    42604458                               rpc_share_migrate_security_internals, argc,
    42614459                               argv);
     
    43154513struct full_alias {
    43164514        struct dom_sid sid;
    4317         uint32 num_members;
     4515        uint32_t num_members;
    43184516        struct dom_sid *members;
    43194517};
     
    43254523 * Add an alias to the static list.
    43264524 */
    4327 static void push_alias(TALLOC_CTX *mem_ctx, struct full_alias *alias)
    4328 {
    4329         if (server_aliases == NULL)
    4330                 server_aliases = SMB_MALLOC_ARRAY(struct full_alias, 100);
     4525static void push_alias(struct full_alias *alias)
     4526{
     4527        size_t array_size;
     4528
     4529        if (server_aliases == NULL) {
     4530                server_aliases = talloc_array(NULL, struct full_alias, 100);
     4531                if (server_aliases == NULL) {
     4532                        smb_panic("talloc_array failed");
     4533                }
     4534        }
     4535
     4536        array_size = talloc_array_length(server_aliases);
     4537        if (array_size == num_server_aliases) {
     4538                server_aliases = talloc_realloc(NULL, server_aliases,
     4539                                                struct full_alias, array_size + 100);
     4540                if (server_aliases == NULL) {
     4541                        smb_panic("talloc_realloc failed");
     4542                }
     4543        }
    43314544
    43324545        server_aliases[num_server_aliases] = *alias;
     
    43444557                                        const struct dom_sid *domain_sid)
    43454558{
    4346         uint32 start_idx, max_entries, num_entries, i;
     4559        uint32_t start_idx, max_entries, num_entries, i;
    43474560        struct samr_SamArray *groups = NULL;
    43484561        NTSTATUS result, status;
     
    43554568                                        connect_pol,
    43564569                                        MAXIMUM_ALLOWED_ACCESS,
    4357                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
     4570                                        discard_const_p(struct dom_sid2, domain_sid),
    43584571                                        &domain_pol,
    43594572                                        &result);
     
    44374650                                    groups->entries[i].idx);
    44384651
    4439                         push_alias(mem_ctx, &alias);
     4652                        push_alias(&alias);
    44404653                }
    44414654        } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
     
    45054718                for (j=0; j<alias->num_members; j++)
    45064719                        DEBUG(1, ("%s\\%s (%d); ",
    4507                                   domains[j] ? domains[j] : "*unknown*", 
     4720                                  domains[j] ? domains[j] : "*unknown*",
    45084721                                  names[j] ? names[j] : "*unknown*",types[j]));
    45094722                DEBUG(1, ("\n"));
     
    47024915                gid_t gid = groups[i];
    47034916                struct dom_sid sid;
     4917                bool ok;
    47044918
    47054919                wbc_status = wbcGidToSid(gid, &wsid);
     
    47154929                DEBUG(3, (" %s\n", sid_str));
    47164930
    4717                 string_to_sid(&sid, sid_str);
     4931                ok = string_to_sid(&sid, sid_str);
     4932                if (!ok) {
     4933                        DEBUG(1, ("Failed to convert string to SID\n"));
     4934                        wbcFreeMemory(groups);
     4935                        return false;
     4936                }
    47184937                add_sid_to_token(token, &sid);
    47194938        }
     
    47774996                        *p++ = '\0';
    47784997                        fstrcpy(domain, users[i]);
    4779                         strupper_m(domain);
     4998                        if (!strupper_m(domain)) {
     4999                                DEBUG(1, ("strupper_m %s failed\n", domain));
     5000                                wbcFreeMemory(users);
     5001                                return false;
     5002                        }
    47805003                        fstrcpy(user, p);
    47815004                }
     
    48395062                token = &((*tokens)[*num_tokens-1]);
    48405063
    4841                 fstrcpy(token->name, line);
     5064                if (strlcpy(token->name, line, sizeof(token->name)) >= sizeof(token->name)) {
     5065                        return false;
     5066                }
    48425067                token->token.num_sids = 0;
    48435068                token->token.sids = NULL;
    48445069                continue;
    48455070        }
    4846        
     5071
    48475072        return false;
    48485073}
     
    48545079
    48555080static void show_userlist(struct rpc_pipe_client *pipe_hnd,
    4856                         TALLOC_CTX *mem_ctx,
    4857                         const char *netname,
    4858                         int num_tokens,
    4859                         struct user_token *tokens)
     5081                          struct cli_state *cli,
     5082                          TALLOC_CTX *mem_ctx,
     5083                          const char *netname,
     5084                          int num_tokens,
     5085                          struct user_token *tokens)
    48605086{
    48615087        uint16_t fnum;
    48625088        struct security_descriptor *share_sd = NULL;
    48635089        struct security_descriptor *root_sd = NULL;
    4864         struct cli_state *cli = rpc_pipe_np_smb_conn(pipe_hnd);
    48655090        int i;
    48665091        union srvsvc_NetShareInfo info;
    48675092        WERROR result;
    48685093        NTSTATUS status;
    4869         uint16 cnum;
     5094        uint16_t cnum;
    48705095        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
    48715096
     
    48895114        }
    48905115
    4891         cnum = cli->cnum;
    4892 
    4893         if (!NT_STATUS_IS_OK(cli_tcon_andx(cli, netname, "A:", "", 0))) {
     5116        cnum = cli_state_get_tid(cli);
     5117
     5118        if (!NT_STATUS_IS_OK(cli_tree_connect(cli, netname, "A:", "", 0))) {
    48945119                return;
    48955120        }
    48965121
    48975122        if (!NT_STATUS_IS_OK(cli_ntcreate(cli, "\\", 0, READ_CONTROL_ACCESS, 0,
    4898                         FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN, 0x0, 0x0, &fnum))) {
    4899                 root_sd = cli_query_secdesc(cli, fnum, mem_ctx);
     5123                        FILE_SHARE_READ|FILE_SHARE_WRITE,
     5124                        FILE_OPEN, 0x0, 0x0, &fnum, NULL))) {
     5125                cli_query_secdesc(cli, fnum, mem_ctx, &root_sd);
    49005126        }
    49015127
    49025128        for (i=0; i<num_tokens; i++) {
    4903                 uint32 acc_granted;
     5129                uint32_t acc_granted;
    49045130
    49055131                if (share_sd != NULL) {
     
    49335159                cli_close(cli, fnum);
    49345160        cli_tdis(cli);
    4935         cli->cnum = cnum;
    4936        
     5161        cli_state_set_tid(cli, cnum);
     5162
    49375163        return;
    49385164}
     
    50465272                d_printf("%s\n", netname);
    50475273
    5048                 show_userlist(pipe_hnd, mem_ctx, netname,
     5274                show_userlist(pipe_hnd, cli, mem_ctx, netname,
    50495275                              num_tokens, tokens);
    50505276        }
     
    50545280        }
    50555281        SAFE_FREE(tokens);
     5282        TALLOC_FREE(server_aliases);
    50565283
    50575284        return nt_status;
     
    50725299        }
    50735300
    5074         result = run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
     5301        result = run_rpc_command(c, NULL, &ndr_table_samr, 0,
    50755302                                 rpc_aliaslist_internals,
    50765303                                 argc, argv);
     
    50785305                return result;
    50795306
    5080         result = run_rpc_command(c, NULL, &ndr_table_lsarpc.syntax_id, 0,
     5307        result = run_rpc_command(c, NULL, &ndr_table_lsarpc, 0,
    50815308                                 rpc_aliaslist_dump,
    50825309                                 argc, argv);
     
    50845311                return result;
    50855312
    5086         return run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
     5313        return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
    50875314                               rpc_share_allowedusers_internals,
    50885315                               argc, argv);
     
    51025329        if (!get_user_tokens(c, &num_tokens, &tokens)) {
    51035330                DEBUG(0, ("Could not get the user/sid list\n"));
    5104                 return 0;
     5331                return -1;
    51055332        }
    51065333
     
    51115338
    51125339        SAFE_FREE(tokens);
    5113         return 1;
     5340        return 0;
    51145341}
    51155342
     
    53085535        static struct rpc_sh_cmd cmds[] = {
    53095536
    5310         { "list", NULL, &ndr_table_srvsvc.syntax_id, rpc_sh_share_list,
     5537        { "list", NULL, &ndr_table_srvsvc, rpc_sh_share_list,
    53115538          N_("List available shares") },
    53125539
    5313         { "add", NULL, &ndr_table_srvsvc.syntax_id, rpc_sh_share_add,
     5540        { "add", NULL, &ndr_table_srvsvc, rpc_sh_share_add,
    53145541          N_("Add a share") },
    53155542
    5316         { "delete", NULL, &ndr_table_srvsvc.syntax_id, rpc_sh_share_delete,
     5543        { "delete", NULL, &ndr_table_srvsvc, rpc_sh_share_delete,
    53175544          N_("Delete a share") },
    53185545
    5319         { "info", NULL, &ndr_table_srvsvc.syntax_id, rpc_sh_share_info,
     5546        { "info", NULL, &ndr_table_srvsvc, rpc_sh_share_info,
    53205547          N_("Get information about a share") },
    53215548
     
    53775604{
    53785605        NET_API_STATUS status;
    5379         uint32 preferred_len = 0xffffffff, i;
    5380         const char *username=NULL;
     5606        uint32_t preferred_len = 0xffffffff, i;
     5607        char *username=NULL;
    53815608        uint32_t total_entries = 0;
    53825609        uint32_t entries_read = 0;
     
    54175644        }
    54185645 done:
     5646        SAFE_FREE(username);
    54195647        return status;
    54205648}
     
    55985826        }
    55995827
    5600         rc = run_rpc_command(c, NULL, &ndr_table_initshutdown.syntax_id, 0,
     5828        rc = run_rpc_command(c, NULL, &ndr_table_initshutdown, 0,
    56015829                             rpc_shutdown_abort_internals, argc, argv);
    56025830
     
    56065834        DEBUG(1, ("initshutdown pipe didn't work, trying winreg pipe\n"));
    56075835
    5608         return run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
     5836        return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
    56095837                               rpc_reg_shutdown_abort_internals,
    56105838                               argc, argv);
     
    56405868        WERROR result;
    56415869        const char *msg = N_("This machine will be shutdown shortly");
    5642         uint32 timeout = 20;
     5870        uint32_t timeout = 20;
    56435871        struct lsa_StringLarge msg_string;
    56445872        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
     
    56965924{
    56975925        const char *msg = N_("This machine will be shutdown shortly");
    5698         uint32 timeout = 20;
     5926        uint32_t timeout = 20;
    56995927        struct lsa_StringLarge msg_string;
    57005928        NTSTATUS result;
     
    57565984        }
    57575985
    5758         rc = run_rpc_command(c, NULL, &ndr_table_initshutdown.syntax_id, 0,
     5986        rc = run_rpc_command(c, NULL, &ndr_table_initshutdown, 0,
    57595987                             rpc_init_shutdown_internals, argc, argv);
    57605988
    57615989        if (rc) {
    57625990                DEBUG(1, ("initshutdown pipe failed, trying winreg pipe\n"));
    5763                 rc = run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
     5991                rc = run_rpc_command(c, NULL, &ndr_table_winreg, 0,
    57645992                                     rpc_reg_shutdown_internals, argc, argv);
    57655993        }
     
    58016029        char *acct_name;
    58026030        struct lsa_String lsa_acct_name;
    5803         uint32 acb_info;
    5804         uint32 acct_flags=0;
    5805         uint32 user_rid;
     6031        uint32_t acb_info;
     6032        uint32_t acct_flags=0;
     6033        uint32_t user_rid;
    58066034        uint32_t access_granted = 0;
    58076035        union samr_UserInfo info;
    58086036        unsigned int orig_timeout;
    58096037        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
     6038        DATA_BLOB session_key = data_blob_null;
    58106039
    58116040        if (argc != 2) {
     
    58256054        }
    58266055
    5827         strupper_m(acct_name);
     6056        if (!strupper_m(acct_name)) {
     6057                SAFE_FREE(acct_name);
     6058                return NT_STATUS_INVALID_PARAMETER;
     6059        }
    58286060
    58296061        init_lsa_String(&lsa_acct_name, acct_name);
     6062
     6063        status = cli_get_session_key(mem_ctx, pipe_hnd, &session_key);
     6064        if (!NT_STATUS_IS_OK(status)) {
     6065                DEBUG(0,("Error getting session_key of SAM pipe. Error was %s\n",
     6066                        nt_errstr(status)));
     6067                goto done;
     6068        }
    58306069
    58316070        /* Get samr policy handle */
     
    58476086                                        &connect_pol,
    58486087                                        MAXIMUM_ALLOWED_ACCESS,
    5849                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
     6088                                        discard_const_p(struct dom_sid2, domain_sid),
    58506089                                        &domain_pol,
    58516090                                        &result);
     
    58996138
    59006139                init_samr_CryptPassword(argv[1],
    5901                                         &cli->user_session_key,
     6140                                        &session_key,
    59026141                                        &crypt_pwd);
    59036142
     
    59266165 done:
    59276166        SAFE_FREE(acct_name);
     6167        data_blob_clear_free(&session_key);
    59286168        return status;
    59296169}
     
    59416181{
    59426182        if (argc > 0 && !c->display_usage) {
    5943                 return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
     6183                return run_rpc_command(c, NULL, &ndr_table_samr, 0,
    59446184                                       rpc_trustdom_add_internals, argc, argv);
    59456185        } else {
     
    60016241                return NT_STATUS_NO_MEMORY;
    60026242
    6003         strupper_m(acct_name);
     6243        if (!strupper_m(acct_name)) {
     6244                TALLOC_FREE(acct_name);
     6245                return NT_STATUS_INVALID_PARAMETER;
     6246        }
    60046247
    60056248        /* Get samr policy handle */
     
    60216264                                        &connect_pol,
    60226265                                        MAXIMUM_ALLOWED_ACCESS,
    6023                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
     6266                                        discard_const_p(struct dom_sid2, domain_sid),
    60246267                                        &domain_pol,
    60256268                                        &result);
     
    61526395{
    61536396        if (argc > 0 && !c->display_usage) {
    6154                 return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
     6397                return run_rpc_command(c, NULL, &ndr_table_samr, 0,
    61556398                                       rpc_trustdom_del_internals, argc, argv);
    61566399        } else {
     
    61866429        /* Try netr_GetDcName */
    61876430
    6188         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_netlogon.syntax_id,
     6431        status = cli_rpc_pipe_open_noauth(cli, &ndr_table_netlogon,
    61896432                                          &netr);
    61906433        if (!NT_STATUS_IS_OK(status)) {
     
    61956438
    61966439        status = dcerpc_netr_GetDcName(b, mem_ctx,
    6197                                        cli->desthost,
     6440                                       netr->desthost,
    61986441                                       domain_name,
    61996442                                       &buffer,
     
    62556498
    62566499        domain_name = smb_xstrdup(argv[0]);
    6257         strupper_m(domain_name);
     6500        if (!strupper_m(domain_name)) {
     6501                SAFE_FREE(domain_name);
     6502                return -1;
     6503        }
    62586504
    62596505        /* account name used at first is our domain's name with '$' */
     
    62616507                return -1;
    62626508        }
    6263         strupper_m(acct_name);
     6509        if (!strupper_m(acct_name)) {
     6510                SAFE_FREE(domain_name);
     6511                SAFE_FREE(acct_name);
     6512                return -1;
     6513        }
    62646514
    62656515        /*
     
    63266576         */
    63276577
    6328         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
     6578        nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
    63296579                                             &pipe_hnd);
    63306580        if (!NT_STATUS_IS_OK(nt_status)) {
     
    64336683        /* generate upper cased domain name */
    64346684        domain_name = smb_xstrdup(argv[0]);
    6435         strupper_m(domain_name);
     6685        if (!strupper_m(domain_name)) {
     6686                SAFE_FREE(domain_name);
     6687                return -1;
     6688        }
    64366689
    64376690        /* delete password of the trust */
     
    64846737        union lsa_TrustedDomainInfo *info = NULL;
    64856738        char *cleartextpwd = NULL;
    6486         uint8_t session_key[16];
    6487         DATA_BLOB session_key_blob;
     6739        DATA_BLOB session_key;
    64886740        DATA_BLOB data = data_blob_null;
    64896741        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
     
    65106762                         info->password.password->length);
    65116763
    6512         if (!rpccli_get_pwd_hash(pipe_hnd, session_key)) {
    6513                 DEBUG(0, ("Could not retrieve password hash\n"));
    6514                 goto done;
    6515         }
    6516 
    6517         session_key_blob = data_blob_const(session_key, sizeof(session_key));
    6518         cleartextpwd = sess_decrypt_string(mem_ctx, &data, &session_key_blob);
     6764        nt_status = cli_get_session_key(mem_ctx, pipe_hnd, &session_key);
     6765        if (!NT_STATUS_IS_OK(nt_status)) {
     6766                DEBUG(0, ("Could not retrieve session key: %s\n", nt_errstr(nt_status)));
     6767                goto done;
     6768        }
     6769
     6770        cleartextpwd = sess_decrypt_string(mem_ctx, &data, &session_key);
     6771        data_blob_free(&session_key);
    65196772
    65206773        if (cleartextpwd == NULL) {
     
    65526805        NTSTATUS nt_status, result;
    65536806        const char *domain_name = NULL;
    6554         struct dom_sid *queried_dom_sid;
    65556807        struct policy_handle connect_hnd;
    65566808        union lsa_PolicyInformation *info = NULL;
     
    65836835         */
    65846836
    6585         if (StrCaseCmp(c->opt_workgroup, lp_workgroup())) {
     6837        if (strcasecmp_m(c->opt_workgroup, lp_workgroup())) {
    65866838                domain_name = c->opt_workgroup;
    65876839                c->opt_target_workgroup = c->opt_workgroup;
    65886840        } else {
    6589                 fstrcpy(pdc_name, global_myname());
     6841                fstrcpy(pdc_name, lp_netbios_name());
    65906842                domain_name = talloc_strdup(mem_ctx, lp_workgroup());
    65916843                c->opt_target_workgroup = domain_name;
     
    66016853        };
    66026854
    6603         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
     6855        nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
    66046856                                             &pipe_hnd);
    66056857        if (!NT_STATUS_IS_OK(nt_status)) {
     
    66446896                return -1;
    66456897        }
    6646 
    6647         queried_dom_sid = info->account_domain.sid;
    66486898
    66496899        /*
     
    66836933                                             dom_list.domains[i].name.string);
    66846934
    6685                         nt_status = vampire_trusted_domain(pipe_hnd, mem_ctx, &connect_hnd, 
     6935                        nt_status = vampire_trusted_domain(pipe_hnd, mem_ctx, &connect_hnd,
    66866936                                                           *dom_list.domains[i].sid,
    66876937                                                           dom_list.domains[i].name.string);
     
    67637013         */
    67647014
    6765         if (StrCaseCmp(c->opt_workgroup, lp_workgroup())) {
     7015        if (strcasecmp_m(c->opt_workgroup, lp_workgroup())) {
    67667016                domain_name = c->opt_workgroup;
    67677017                c->opt_target_workgroup = c->opt_workgroup;
    67687018        } else {
    6769                 fstrcpy(pdc_name, global_myname());
     7019                fstrcpy(pdc_name, lp_netbios_name());
    67707020                domain_name = talloc_strdup(mem_ctx, lp_workgroup());
    67717021                c->opt_target_workgroup = domain_name;
     
    67817031        };
    67827032
    6783         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
     7033        nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
    67847034                                             &pipe_hnd);
    67857035        if (!NT_STATUS_IS_OK(nt_status)) {
     
    68027052                return -1;
    68037053        };
    6804        
     7054
    68057055        /* query info level 5 to obtain sid of a domain being queried */
    68067056        nt_status = dcerpc_lsa_QueryInfoPolicy(b, mem_ctx,
     
    68857135                return -1;
    68867136        };
    6887        
     7137
    68887138        TALLOC_FREE(pipe_hnd);
    68897139
     
    68917141         * Listing trusting domains (stored in passdb backend, if local)
    68927142         */
    6893        
     7143
    68947144        d_printf(_("\nTrusting domains list:\n\n"));
    68957145
     
    68977147         * Open \PIPE\samr and get needed policy handles
    68987148         */
    6899         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr.syntax_id,
     7149        nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr,
    69007150                                             &pipe_hnd);
    69017151        if (!NT_STATUS_IS_OK(nt_status)) {
     
    69897239                for (i = 0; i < num_domains; i++) {
    69907240
    6991                         char *str = CONST_DISCARD(char *, trusts->entries[i].name.string);
     7241                        char *str = discard_const_p(char, trusts->entries[i].name.string);
    69927242
    69937243                        found_domain = true;
     
    70057255
    70067256                        /* set opt_* variables to remote domain */
    7007                         strupper_m(str);
     7257                        if (!strupper_m(str)) {
     7258                                cli_shutdown(cli);
     7259                                talloc_destroy(mem_ctx);
     7260                                return -1;
     7261                        }
    70087262                        c->opt_workgroup = talloc_strdup(mem_ctx, str);
    70097263                        c->opt_target_workgroup = c->opt_workgroup;
     
    70197273                                if (run_rpc_command(
    70207274                                            c, remote_cli,
    7021                                             &ndr_table_lsarpc.syntax_id, 0,
     7275                                            &ndr_table_lsarpc, 0,
    70227276                                            rpc_query_domain_sid, argc,
    70237277                                            argv))
     
    71427396                return false;
    71437397
    7144         if ((cli = cli_initialise()) == NULL) {
     7398        status = cli_connect_nb(server_name, &server_ss, 0, 0x20,
     7399                                lp_netbios_name(), SMB_SIGNING_IPC_DEFAULT,
     7400                                0, &cli);
     7401        if (!NT_STATUS_IS_OK(status)) {
    71457402                return false;
    71467403        }
    7147 
    7148         status = cli_connect(cli, server_name, &server_ss);
     7404        status = smbXcli_negprot(cli->conn, cli->timeout, PROTOCOL_CORE,
     7405                                 PROTOCOL_NT1);
    71497406        if (!NT_STATUS_IS_OK(status))
    71507407                goto done;
    7151         if (!attempt_netbios_session_request(&cli, global_myname(),
    7152                                              server_name, &server_ss))
    7153                 goto done;
    7154         status = cli_negprot(cli);
    7155         if (!NT_STATUS_IS_OK(status))
    7156                 goto done;
    7157         if (cli->protocol < PROTOCOL_NT1)
     7408        if (smbXcli_conn_protocol(cli->conn) < PROTOCOL_NT1)
    71587409                goto done;
    71597410
     
    71757426        }
    71767427
    7177         return run_rpc_command(c, NULL, &ndr_table_netlogon.syntax_id,
     7428        return run_rpc_command(c, NULL, &ndr_table_netlogon,
    71787429                               NET_FLAGS_ANONYMOUS,
    71797430                               rpc_samdump_internals, argc, argv);
     
    72647515        }
    72657516
    7266         ret = run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7517        ret = run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    72677518                              rpc_printer_migrate_printers_internals, argc,
    72687519                              argv);
     
    72707521                return ret;
    72717522
    7272         ret = run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7523        ret = run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    72737524                              rpc_printer_migrate_drivers_internals, argc,
    72747525                              argv);
     
    72767527                return ret;
    72777528
    7278         ret = run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7529        ret = run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    72797530                              rpc_printer_migrate_forms_internals, argc, argv);
    72807531        if (ret)
    72817532                return ret;
    72827533
    7283         ret = run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7534        ret = run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    72847535                              rpc_printer_migrate_settings_internals, argc,
    72857536                              argv);
     
    72877538                return ret;
    72887539
    7289         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7540        return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    72907541                               rpc_printer_migrate_security_internals, argc,
    72917542                               argv);
     
    73207571        }
    73217572
    7322         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7573        return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    73237574                               rpc_printer_migrate_drivers_internals,
    73247575                               argc, argv);
     
    73527603        }
    73537604
    7354         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7605        return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    73557606                               rpc_printer_migrate_forms_internals,
    73567607                               argc, argv);
     
    73847635        }
    73857636
    7386         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7637        return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    73877638                               rpc_printer_migrate_printers_internals,
    73887639                               argc, argv);
     
    74167667        }
    74177668
    7418         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7669        return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    74197670                               rpc_printer_migrate_security_internals,
    74207671                               argc, argv);
     
    74497700        }
    74507701
    7451         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7702        return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    74527703                               rpc_printer_migrate_settings_internals,
    74537704                               argc, argv);
     
    75477798        }
    75487799
    7549         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7800        return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    75507801                               rpc_printer_list_internals,
    75517802                               argc, argv);
     
    75747825        }
    75757826
    7576         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7827        return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    75777828                               rpc_printer_driver_list_internals,
    75787829                               argc, argv);
     
    76017852        }
    76027853
    7603         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7854        return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    76047855                               rpc_printer_publish_publish_internals,
    76057856                               argc, argv);
     
    76277878        }
    76287879
    7629         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7880        return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    76307881                               rpc_printer_publish_update_internals,
    76317882                               argc, argv);
     
    76547905        }
    76557906
    7656         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7907        return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    76577908                               rpc_printer_publish_unpublish_internals,
    76587909                               argc, argv);
     
    76817932        }
    76827933
    7683         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     7934        return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    76847935                               rpc_printer_publish_list_internals,
    76857936                               argc, argv);
     
    77477998                        return 0;
    77487999                }
    7749                 return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     8000                return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    77508001                               rpc_printer_publish_list_internals,
    77518002                               argc, argv);
     
    78508101                        return 0;
    78518102                }
    7852                 return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
     8103                return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
    78538104                               rpc_printer_list_internals,
    78548105                               argc, argv);
     
    80578308                           "    Manage trusts")
    80588309                },
     8310                {
     8311                        "conf",
     8312                        net_rpc_conf,
     8313                        NET_TRANSPORT_RPC,
     8314                        N_("Configure a remote samba server"),
     8315                        N_("net rpc conf\n"
     8316                           "    Configure a remote samba server")
     8317                },
    80598318                {NULL, NULL, 0, NULL, NULL}
    80608319        };
  • vendor/current/source3/utils/net_rpc_audit.c

    r740 r988  
    412412        }
    413413
    414         return run_rpc_command(c, NULL, &ndr_table_lsarpc.syntax_id, 0,
     414        return run_rpc_command(c, NULL, &ndr_table_lsarpc, 0,
    415415                rpc_audit_get_internal, argc, argv);
    416416}
     
    430430        }
    431431
    432         return run_rpc_command(c, NULL, &ndr_table_lsarpc.syntax_id, 0,
     432        return run_rpc_command(c, NULL, &ndr_table_lsarpc, 0,
    433433                rpc_audit_set_internal, argc, argv);
    434434}
     
    448448        }
    449449
    450         return run_rpc_command(c, NULL, &ndr_table_lsarpc.syntax_id, 0,
     450        return run_rpc_command(c, NULL, &ndr_table_lsarpc, 0,
    451451                rpc_audit_enable_internal, argc, argv);
    452452}
     
    466466        }
    467467
    468         return run_rpc_command(c, NULL, &ndr_table_lsarpc.syntax_id, 0,
     468        return run_rpc_command(c, NULL, &ndr_table_lsarpc, 0,
    469469                rpc_audit_disable_internal, argc, argv);
    470470}
     
    484484        }
    485485
    486         return run_rpc_command(c, NULL, &ndr_table_lsarpc.syntax_id, 0,
     486        return run_rpc_command(c, NULL, &ndr_table_lsarpc, 0,
    487487                rpc_audit_list_internal, argc, argv);
    488488}
  • vendor/current/source3/utils/net_rpc_printer.c

    r740 r988  
    2525#include "rpc_client/init_spoolss.h"
    2626#include "nt_printing.h"
    27 #include "registry/reg_objects.h"
     27#include "registry.h"
    2828#include "../libcli/security/security.h"
    2929#include "../libcli/registry/util_reg.h"
    3030#include "libsmb/libsmb.h"
     31#include "../libcli/smb/smbXcli_base.h"
     32#include "auth/gensec/gensec.h"
     33#include "auth/credentials/credentials.h"
    3134
    3235/* support itanium as well */
     
    8184}
    8285
    83 static void display_reg_value(const char *subkey, struct regval_blob *value)
     86static void display_reg_value(const char *subkey, const char *name, struct registry_value *value)
    8487{
    8588        const char *text;
    86         DATA_BLOB blob;
    87 
    88         switch(regval_type(value)) {
     89
     90        switch(value->type) {
    8991        case REG_DWORD:
    90                 d_printf(_("\t[%s:%s]: REG_DWORD: 0x%08x\n"), subkey,
    91                         regval_name(value), *((uint32_t *) regval_data_p(value)));
     92                if (value->data.length == sizeof(uint32_t)) {
     93                        d_printf(_("\t[%s:%s]: REG_DWORD: 0x%08x\n"), subkey,
     94                                 name, IVAL(value->data.data,0));
     95                } else {
     96                        d_printf(_("\t[%s:%s]: REG_DWORD: <invalid>\n"), subkey,
     97                                 name);
     98                }
    9299                break;
    93100
    94101        case REG_SZ:
    95                 blob = data_blob_const(regval_data_p(value), regval_size(value));
    96                 pull_reg_sz(talloc_tos(), &blob, &text);
     102                pull_reg_sz(talloc_tos(), &value->data, &text);
    97103                if (!text) {
    98104                        break;
    99105                }
    100                 d_printf(_("\t[%s:%s]: REG_SZ: %s\n"), subkey, regval_name(value),
    101                          text);
     106                d_printf(_("\t[%s:%s]: REG_SZ: %s\n"), subkey, name, text);
    102107                break;
    103108
     
    105110                d_printf(_("\t[%s:%s]: REG_BINARY: unknown length value not "
    106111                           "displayed\n"),
    107                          subkey, regval_name(value));
     112                         subkey, name);
    108113                break;
    109114
     
    111116                uint32_t i;
    112117                const char **values;
    113                 blob = data_blob_const(regval_data_p(value), regval_size(value));
    114 
    115                 if (!pull_reg_multi_sz(NULL, &blob, &values)) {
     118
     119                if (!pull_reg_multi_sz(NULL, &value->data, &values)) {
    116120                        d_printf("pull_reg_multi_sz failed\n");
    117121                        break;
    118122                }
    119123
    120                 printf("%s: REG_MULTI_SZ: \n", regval_name(value));
     124                printf("%s: REG_MULTI_SZ: \n", name);
    121125                for (i=0; values[i] != NULL; i++) {
    122126                        d_printf("%s\n", values[i]);
     
    127131
    128132        default:
    129                 d_printf(_("\t%s: unknown type %d\n"), regval_name(value),
    130                          regval_type(value));
     133                d_printf(_("\t%s: unknown type %d\n"), name, value->type);
    131134        }
    132135
     
    159162                  bool copy_timestamps, bool is_file)
    160163{
    161         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
     164        NTSTATUS nt_status;
    162165        uint16_t fnum_src = 0;
    163166        uint16_t fnum_dst = 0;
     
    166169        time_t f_atime, f_ctime, f_mtime;
    167170
    168 
    169171        if (!copy_timestamps && !copy_acls && !copy_attrs)
    170172                return NT_STATUS_OK;
     
    175177                is_file?"file":"dir", src_name));
    176178
    177         if (!NT_STATUS_IS_OK(cli_ntcreate(cli_share_src, src_name, 0, READ_CONTROL_ACCESS, 0,
    178                                 FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN, 0x0, 0x0, &fnum_src))) {
     179        nt_status = cli_ntcreate(cli_share_src, src_name, 0,
     180                                 READ_CONTROL_ACCESS, 0,
     181                                 FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN,
     182                                 0x0, 0x0, &fnum_src, NULL);
     183        if (!NT_STATUS_IS_OK(nt_status)) {
    179184                DEBUGADD(0,("cannot open %s %s on originating server %s\n",
    180                         is_file?"file":"dir", src_name, cli_errstr(cli_share_src)));
    181                 nt_status = cli_nt_error(cli_share_src);
     185                        is_file?"file":"dir", src_name, nt_errstr(nt_status)));
    182186                goto out;
    183187        }
    184188
    185 
    186189        if (copy_acls) {
    187 
    188190                /* get the security descriptor */
    189                 sd = cli_query_secdesc(cli_share_src, fnum_src, mem_ctx);
    190                 if (!sd) {
     191                nt_status = cli_query_secdesc(cli_share_src, fnum_src,
     192                                              mem_ctx, &sd);
     193                if (!NT_STATUS_IS_OK(nt_status)) {
    191194                        DEBUG(0,("failed to get security descriptor: %s\n",
    192                                 cli_errstr(cli_share_src)));
    193                         nt_status = cli_nt_error(cli_share_src);
     195                                 nt_errstr(nt_status)));
    194196                        goto out;
    195197                }
     
    199201        }
    200202
    201 
    202203        if (copy_attrs || copy_timestamps) {
    203204
    204205                /* get file attributes */
    205                 if (!NT_STATUS_IS_OK(cli_getattrE(cli_share_src, fnum_src, &attr, NULL,
    206                                  &f_ctime, &f_atime, &f_mtime))) {
     206                nt_status = cli_getattrE(cli_share_src, fnum_src, &attr, NULL,
     207                                      &f_ctime, &f_atime, &f_mtime);
     208                if (!NT_STATUS_IS_OK(nt_status)) {
    207209                        DEBUG(0,("failed to get file-attrs: %s\n",
    208                                 cli_errstr(cli_share_src)));
    209                         nt_status = cli_nt_error(cli_share_src);
     210                                nt_errstr(nt_status)));
    210211                        goto out;
    211212                }
    212213        }
    213214
    214 
    215215        /* open the file/dir on the destination server */
    216 
    217         if (!NT_STATUS_IS_OK(cli_ntcreate(cli_share_dst, dst_name, 0, WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS, 0,
    218                                 FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN, 0x0, 0x0, &fnum_dst))) {
     216        nt_status = cli_ntcreate(cli_share_dst, dst_name, 0,
     217                                 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS, 0,
     218                                 FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN,
     219                                 0x0, 0x0, &fnum_dst, NULL);
     220        if (!NT_STATUS_IS_OK(nt_status)) {
    219221                DEBUG(0,("failed to open %s on the destination server: %s: %s\n",
    220                         is_file?"file":"dir", dst_name, cli_errstr(cli_share_dst)));
    221                 nt_status = cli_nt_error(cli_share_dst);
     222                        is_file?"file":"dir", dst_name, nt_errstr(nt_status)));
    222223                goto out;
    223224        }
    224225
    225226        if (copy_timestamps) {
    226 
    227227                /* set timestamps */
    228                 if (!NT_STATUS_IS_OK(cli_setattrE(cli_share_dst, fnum_dst, f_ctime, f_atime, f_mtime))) {
     228                nt_status = cli_setattrE(cli_share_dst, fnum_dst, f_ctime, f_atime, f_mtime);
     229                if (!NT_STATUS_IS_OK(nt_status)) {
    229230                        DEBUG(0,("failed to set file-attrs (timestamps): %s\n",
    230                                 cli_errstr(cli_share_dst)));
    231                         nt_status = cli_nt_error(cli_share_dst);
     231                                nt_errstr(nt_status)));
    232232                        goto out;
    233233                }
     
    235235
    236236        if (copy_acls) {
    237                 NTSTATUS status;
    238 
    239237                /* set acls */
    240                 status = cli_set_secdesc(cli_share_dst, fnum_dst, sd);
    241                 if (!NT_STATUS_IS_OK(status)) {
     238                nt_status = cli_set_secdesc(cli_share_dst, fnum_dst, sd);
     239                if (!NT_STATUS_IS_OK(nt_status)) {
    242240                        DEBUG(0, ("could not set secdesc on %s: %s\n",
    243                                   dst_name, nt_errstr(status)));
    244                         nt_status = status;
     241                                  dst_name, nt_errstr(nt_status)));
    245242                        goto out;
    246243                }
     
    248245
    249246        if (copy_attrs) {
    250 
    251247                /* set attrs */
    252                 if (!NT_STATUS_IS_OK(cli_setatr(cli_share_dst, dst_name, attr, 0))) {
     248                nt_status = cli_setatr(cli_share_dst, dst_name, attr, 0);
     249                if (!NT_STATUS_IS_OK(nt_status)) {
    253250                        DEBUG(0,("failed to set file-attrs: %s\n",
    254                                 cli_errstr(cli_share_dst)));
    255                         nt_status = cli_nt_error(cli_share_dst);
     251                                nt_errstr(nt_status)));
    256252                        goto out;
    257253                }
     
    260256
    261257        /* closing files */
    262 
    263         if (!NT_STATUS_IS_OK(cli_close(cli_share_src, fnum_src))) {
     258        nt_status = cli_close(cli_share_src, fnum_src);
     259        if (!NT_STATUS_IS_OK(nt_status)) {
    264260                d_fprintf(stderr,
    265261                        _("could not close %s on originating server: %s\n"),
    266                         is_file?"file":"dir", cli_errstr(cli_share_src));
    267                 nt_status = cli_nt_error(cli_share_src);
     262                        is_file?"file":"dir", nt_errstr(nt_status));
    268263                goto out;
    269264        }
    270265
    271         if (!NT_STATUS_IS_OK(cli_close(cli_share_dst, fnum_dst))) {
     266        nt_status = cli_close(cli_share_dst, fnum_dst);
     267        if (!NT_STATUS_IS_OK(nt_status)) {
    272268                d_fprintf(stderr,
    273269                        _("could not close %s on destination server: %s\n"),
    274                         is_file?"file":"dir", cli_errstr(cli_share_dst));
    275                 nt_status = cli_nt_error(cli_share_dst);
     270                        is_file?"file":"dir", nt_errstr(nt_status));
    276271                goto out;
    277272        }
     
    339334        else
    340335                nt_status = cli_ntcreate(cli_share_src, src_name, 0, READ_CONTROL_ACCESS, 0,
    341                                 FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN, 0x0, 0x0, &fnum_src);
     336                                FILE_SHARE_READ|FILE_SHARE_WRITE,
     337                                FILE_OPEN, 0x0, 0x0, &fnum_src, NULL);
    342338
    343339        if (!NT_STATUS_IS_OK(nt_status)) {
    344340                DEBUGADD(0,("cannot open %s %s on originating server %s\n",
    345341                        is_file ? "file":"dir",
    346                         src_name, cli_errstr(cli_share_src)));
     342                        src_name, nt_errstr(nt_status)));
    347343                goto out;
    348344        }
     
    358354                if (!NT_STATUS_IS_OK(nt_status)) {
    359355                        DEBUGADD(1,("cannot create file %s on destination server: %s\n",
    360                                 dst_name, cli_errstr(cli_share_dst)));
     356                                dst_name, nt_errstr(nt_status)));
    361357                        goto out;
    362358                }
     
    377373                d_printf(_("copying [\\\\%s\\%s%s] => [\\\\%s\\%s%s] "
    378374                           "%s ACLs and %s DOS Attributes %s\n"),
    379                         cli_share_src->desthost, cli_share_src->share, src_name,
    380                         cli_share_dst->desthost, cli_share_dst->share, dst_name,
     375                        smbXcli_conn_remote_name(cli_share_src->conn),
     376                        cli_share_src->share, src_name,
     377                        smbXcli_conn_remote_name(cli_share_dst->conn),
     378                        cli_share_dst->share, dst_name,
    381379                        copy_acls ?  _("with") : _("without"),
    382380                        copy_attrs ? _("with") : _("without"),
     
    388386
    389387                /* copying file */
    390                 int n;
    391                 n = cli_read(cli_share_src, fnum_src, data, nread,
    392                                 read_size);
    393 
    394                 if (n <= 0)
     388                size_t n;
     389
     390                nt_status = cli_read(cli_share_src, fnum_src, data, nread,
     391                                     read_size, &n);
     392                if (!NT_STATUS_IS_OK(nt_status)) {
     393                        d_fprintf(stderr,
     394                                  _("Error reading file [\\\\%s\\%s%s]: %s\n"),
     395                                  smbXcli_conn_remote_name(cli_share_src->conn),
     396                                  cli_share_src->share,
     397                                  src_name, nt_errstr(nt_status));
     398                        goto out;
     399                }
     400
     401                if (n == 0)
    395402                        break;
    396403
     
    399406
    400407                if (!NT_STATUS_IS_OK(nt_status)) {
    401                         d_fprintf(stderr, _("Error writing file: %s\n"),
    402                                   nt_errstr(nt_status));
     408                        d_fprintf(stderr,
     409                                  _("Error writing file: [\\\\%s\\%s%s]: %s\n"),
     410                                  smbXcli_conn_remote_name(cli_share_dst->conn),
     411                                  cli_share_dst->share,
     412                                  dst_name, nt_errstr(nt_status));
    403413                        goto out;
    404414                }
     
    414424                        dst_name));
    415425
    416                 if (!NT_STATUS_IS_OK(cli_mkdir(cli_share_dst, dst_name))) {
     426                nt_status = cli_mkdir(cli_share_dst, dst_name);
     427                if (!NT_STATUS_IS_OK(nt_status)) {
    417428                        DEBUG(0,("cannot create directory %s: %s\n",
    418                                 dst_name, cli_errstr(cli_share_dst)));
     429                                dst_name, nt_errstr(nt_status)));
    419430                        nt_status = NT_STATUS_NO_SUCH_FILE;
    420431                }
    421432
    422                 if (!NT_STATUS_IS_OK(cli_chkpath(cli_share_dst, dst_name))) {
     433
     434                nt_status = cli_chkpath(cli_share_dst, dst_name);
     435                if (!NT_STATUS_IS_OK(nt_status)) {
    423436                        d_fprintf(stderr,
    424437                                _("cannot check for directory %s: %s\n"),
    425                                 dst_name, cli_errstr(cli_share_dst));
     438                                dst_name, nt_errstr(nt_status));
    426439                        goto out;
    427440                }
     
    430443
    431444        /* closing files */
    432         if (!NT_STATUS_IS_OK(cli_close(cli_share_src, fnum_src))) {
     445        nt_status = cli_close(cli_share_src, fnum_src);
     446        if (!NT_STATUS_IS_OK(nt_status)) {
    433447                d_fprintf(stderr,
    434448                        _("could not close file on originating server: %s\n"),
    435                         cli_errstr(cli_share_src));
    436                 nt_status = cli_nt_error(cli_share_src);
     449                        nt_errstr(nt_status));
    437450                goto out;
    438451        }
    439452
    440         if (is_file && !NT_STATUS_IS_OK(cli_close(cli_share_dst, fnum_dst))) {
    441                 d_fprintf(stderr,
     453        if (is_file) {
     454                nt_status = cli_close(cli_share_dst, fnum_dst);
     455                if (!NT_STATUS_IS_OK(nt_status)) {
     456                        d_fprintf(stderr,
    442457                        _("could not close file on destination server: %s\n"),
    443                         cli_errstr(cli_share_dst));
    444                 nt_status = cli_nt_error(cli_share_dst);
    445                 goto out;
     458                        nt_errstr(nt_status));
     459                        goto out;
     460                }
    446461        }
    447462
     
    563578                short_archi));
    564579
    565         if (!NT_STATUS_IS_OK(cli_mkdir(cli_share, dir))) {
     580        nt_status = cli_mkdir(cli_share, dir);
     581        if (!NT_STATUS_IS_OK(nt_status)) {
    566582                DEBUG(1,("cannot create directory %s: %s\n",
    567                          dir, cli_errstr(cli_share)));
    568                 nt_status = NT_STATUS_NO_SUCH_FILE;
     583                         dir, nt_errstr(nt_status)));
    569584        }
    570585
    571         if (!NT_STATUS_IS_OK(cli_chkpath(cli_share, dir))) {
     586        nt_status = cli_chkpath(cli_share, dir);
     587        if (!NT_STATUS_IS_OK(nt_status)) {
    572588                d_fprintf(stderr, _("cannot check %s: %s\n"),
    573                         dir, cli_errstr(cli_share));
     589                        dir, nt_errstr(nt_status));
    574590                goto out;
    575591        }
     
    691707                                        const char *printername,
    692708                                        uint32_t access_required,
    693                                         const char *username,
    694709                                        struct policy_handle *hnd)
    695710{
     711        struct cli_credentials *creds = gensec_get_credentials(pipe_hnd->auth->auth_ctx);
     712        const char *username = cli_credentials_get_username(creds);
    696713        WERROR result;
    697714        fstring printername2;
     
    922939
    923940static bool net_spoolss_setprinterdataex(struct rpc_pipe_client *pipe_hnd,
    924                                         TALLOC_CTX *mem_ctx,
    925                                         struct policy_handle *hnd,
    926                                         const char *keyname,
    927                                         struct regval_blob *value)
     941                                         TALLOC_CTX *mem_ctx,
     942                                         struct policy_handle *hnd,
     943                                         const char *keyname,
     944                                         const char *name,
     945                                         struct registry_value *value)
    928946{
    929947        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
     
    935953                                                 hnd,
    936954                                                 keyname,
    937                                                  regval_name(value),
    938                                                  regval_type(value),
    939                                                  regval_data_p(value),
    940                                                  regval_size(value),
     955                                                 name,
     956                                                 value->type,
     957                                                 value->data.data,
     958                                                 value->data.length,
    941959                                                 &result);
    942960        if (!NT_STATUS_IS_OK(status)) {
     
    11221140        if (!net_spoolss_open_printer_ex(pipe_hnd, mem_ctx, argv[0],
    11231141                                         MAXIMUM_ALLOWED_ACCESS,
    1124                                          pipe_hnd->auth->user_name,
    11251142                                         &hnd))
    11261143                return false;
     
    12981315        struct spoolss_DevmodeContainer devmode_ctr;
    12991316        struct sec_desc_buf secdesc_ctr;
    1300         struct policy_handle hnd;
     1317        struct policy_handle hnd = { 0, };
    13011318        WERROR result;
    13021319        const char *action_str;
     
    13161333                /* open printer handle */
    13171334                if (!net_spoolss_open_printer_ex(pipe_hnd, mem_ctx, sharename,
    1318                         PRINTER_ALL_ACCESS, pipe_hnd->auth->user_name, &hnd))
     1335                        PRINTER_ALL_ACCESS, &hnd))
    13191336                        goto done;
    13201337
     
    14541471        union spoolss_PrinterInfo *info_enum;
    14551472        union spoolss_PrinterInfo info;
    1456         struct policy_handle hnd;
     1473        struct policy_handle hnd = { 0, };
    14571474        int state;
    14581475        WERROR werr;
     
    14731490                /* open printer handle */
    14741491                if (!net_spoolss_open_printer_ex(pipe_hnd, mem_ctx, sharename,
    1475                         PRINTER_ALL_ACCESS, cli->user_name, &hnd))
     1492                        PRINTER_ALL_ACCESS, &hnd))
    14761493                        goto done;
    14771494
     
    15531570        struct rpc_pipe_client *pipe_hnd_dst = NULL;
    15541571        struct dcerpc_binding_handle *b_dst = NULL;
    1555         struct policy_handle hnd_src, hnd_dst;
     1572        struct policy_handle hnd_src = { 0, };
     1573        struct policy_handle hnd_dst = { 0, };
    15561574        union spoolss_PrinterInfo *info_enum;
    15571575        struct cli_state *cli_dst = NULL;
     
    15631581        /* connect destination PI_SPOOLSS */
    15641582        nt_status = connect_dst_pipe(c, &cli_dst, &pipe_hnd_dst,
    1565                                      &ndr_table_spoolss.syntax_id);
     1583                                     &ndr_table_spoolss);
    15661584        if (!NT_STATUS_IS_OK(nt_status)) {
    15671585                return nt_status;
     
    16081626                /* open src printer handle */
    16091627                if (!net_spoolss_open_printer_ex(pipe_hnd, mem_ctx, sharename,
    1610                         MAXIMUM_ALLOWED_ACCESS, cli->user_name, &hnd_src))
     1628                        MAXIMUM_ALLOWED_ACCESS, &hnd_src))
    16111629                        goto done;
    16121630
    16131631                /* open dst printer handle */
    16141632                if (!net_spoolss_open_printer_ex(pipe_hnd_dst, mem_ctx, sharename,
    1615                         PRINTER_ALL_ACCESS, cli_dst->user_name, &hnd_dst))
     1633                        PRINTER_ALL_ACCESS, &hnd_dst))
    16161634                        goto done;
    16171635
     
    16281646                /* copy secdesc (info level 2) */
    16291647                info_dst.info2.devmode = NULL;
    1630                 info_dst.info2.secdesc = dup_sec_desc(mem_ctx, info_src.info3.secdesc);
     1648                if (info_src.info3.secdesc == NULL) {
     1649                        info_dst.info2.secdesc = NULL;
     1650                } else {
     1651                        info_dst.info2.secdesc
     1652                                = security_descriptor_copy(mem_ctx,
     1653                                                        info_src.info3.secdesc);
     1654                        if (info_dst.info2.secdesc == NULL) {
     1655                                nt_status = NT_STATUS_NO_MEMORY;
     1656                                goto done;
     1657                        }
     1658                }
    16311659
    16321660                if (c->opt_verbose)
     
    17031731        struct rpc_pipe_client *pipe_hnd_dst = NULL;
    17041732        struct dcerpc_binding_handle *b_dst = NULL;
    1705         struct policy_handle hnd_src, hnd_dst;
     1733        struct policy_handle hnd_src = { 0, };
     1734        struct policy_handle hnd_dst = { 0, };
    17061735        union spoolss_PrinterInfo *info_enum;
    17071736        union spoolss_PrinterInfo info_dst;
     
    17141743        /* connect destination PI_SPOOLSS */
    17151744        nt_status = connect_dst_pipe(c, &cli_dst, &pipe_hnd_dst,
    1716                                      &ndr_table_spoolss.syntax_id);
     1745                                     &ndr_table_spoolss);
    17171746        if (!NT_STATUS_IS_OK(nt_status)) {
    17181747                return nt_status;
     
    17531782                /* open src printer handle */
    17541783                if (!net_spoolss_open_printer_ex(pipe_hnd, mem_ctx, sharename,
    1755                         MAXIMUM_ALLOWED_ACCESS, cli->user_name, &hnd_src))
     1784                        MAXIMUM_ALLOWED_ACCESS, &hnd_src))
    17561785                        goto done;
    17571786
    17581787                /* open dst printer handle */
    17591788                if (!net_spoolss_open_printer_ex(pipe_hnd_dst, mem_ctx, sharename,
    1760                         PRINTER_ALL_ACCESS, cli->user_name, &hnd_dst))
     1789                        PRINTER_ALL_ACCESS, &hnd_dst))
    17611790                        goto done;
    17621791
     
    17741803                for (f = 0; f < num_forms; f++) {
    17751804
    1776                         union spoolss_AddFormInfo info;
     1805                        struct spoolss_AddFormInfoCtr info_ctr;
    17771806                        NTSTATUS status;
    17781807
     
    17871816                                        f, forms[f].info1.form_name,
    17881817                                        forms[f].info1.flags);
    1789 
    1790                         info.info1 = (struct spoolss_AddFormInfo1 *)
     1818                        info_ctr.level = 1;
     1819                        info_ctr.info.info1 = (struct spoolss_AddFormInfo1 *)
    17911820                                (void *)&forms[f].info1;
    17921821
     
    17951824                        status = dcerpc_spoolss_AddForm(b_dst, mem_ctx,
    17961825                                                        &hnd_dst,
    1797                                                         1,
    1798                                                         info,
     1826                                                        &info_ctr,
    17991827                                                        &result);
    18001828                        if (!NT_STATUS_IS_OK(status)) {
     
    18781906        struct rpc_pipe_client *pipe_hnd_dst = NULL;
    18791907        struct dcerpc_binding_handle *b_dst = NULL;
    1880         struct policy_handle hnd_src, hnd_dst;
     1908        struct policy_handle hnd_src = { 0, };
     1909        struct policy_handle hnd_dst = { 0, };
    18811910        union spoolss_DriverInfo drv_info_src;
    18821911        union spoolss_PrinterInfo *info_enum;
     
    18911920
    18921921        nt_status = connect_dst_pipe(c, &cli_dst, &pipe_hnd_dst,
    1893                                      &ndr_table_spoolss.syntax_id);
     1922                                     &ndr_table_spoolss);
    18941923        if (!NT_STATUS_IS_OK(nt_status)) {
    18951924                return nt_status;
     
    18981927
    18991928        /* open print$-share on the src server */
    1900         nt_status = connect_to_service(c, &cli_share_src, &cli->dest_ss,
    1901                         cli->desthost, "print$", "A:");
     1929        nt_status = connect_to_service(c, &cli_share_src,
     1930                                       smbXcli_conn_remote_sockaddr(cli->conn),
     1931                                       smbXcli_conn_remote_name(cli->conn),
     1932                                       "print$", "A:");
    19021933        if (!NT_STATUS_IS_OK(nt_status))
    19031934                goto done;
     
    19071938
    19081939        /* open print$-share on the dst server */
    1909         nt_status = connect_to_service(c, &cli_share_dst, &cli_dst->dest_ss,
    1910                         cli_dst->desthost, "print$", "A:");
     1940        nt_status = connect_to_service(c, &cli_share_dst,
     1941                                       smbXcli_conn_remote_sockaddr(cli_dst->conn),
     1942                                       smbXcli_conn_remote_name(cli_dst->conn),
     1943                                       "print$", "A:");
    19111944        if (!NT_STATUS_IS_OK(nt_status))
    19121945                return nt_status;
     
    19491982                /* open dst printer handle */
    19501983                if (!net_spoolss_open_printer_ex(pipe_hnd_dst, mem_ctx, sharename,
    1951                         PRINTER_ALL_ACCESS, cli->user_name, &hnd_dst))
     1984                        PRINTER_ALL_ACCESS, &hnd_dst))
    19521985                        goto done;
    19531986
     
    19601993                if (!net_spoolss_open_printer_ex(pipe_hnd, mem_ctx, sharename,
    19611994                                                 MAXIMUM_ALLOWED_ACCESS,
    1962                                                  pipe_hnd->auth->user_name,
    19631995                                                 &hnd_src))
    19641996                        goto done;
     
    20002032                        }
    20012033
    2002                         DEBUGADD(1,("Sucessfully added driver [%s] for printer [%s]\n",
     2034                        DEBUGADD(1,("Successfully added driver [%s] for printer [%s]\n",
    20032035                                drivername, printername));
    20042036
     
    20192051                }
    20202052
    2021                 DEBUGADD(1,("Sucessfully set driver %s for printer %s\n",
     2053                DEBUGADD(1,("Successfully set driver %s for printer %s\n",
    20222054                        drivername, printername));
    20232055
     
    20952127        union spoolss_PrinterInfo *info_enum;
    20962128        struct cli_state *cli_dst = NULL;
    2097         struct policy_handle hnd_dst, hnd_src;
     2129        struct policy_handle hnd_src = { 0, };
     2130        struct policy_handle hnd_dst = { 0, };
    20982131        const char *printername, *sharename;
    20992132        struct rpc_pipe_client *pipe_hnd_dst = NULL;
     
    21052138        /* connect destination PI_SPOOLSS */
    21062139        nt_status = connect_dst_pipe(c, &cli_dst, &pipe_hnd_dst,
    2107                                      &ndr_table_spoolss.syntax_id);
     2140                                     &ndr_table_spoolss);
    21082141        if (!NT_STATUS_IS_OK(nt_status)) {
    21092142                return nt_status;
     
    21452178                /* open dst printer handle */
    21462179                if (!net_spoolss_open_printer_ex(pipe_hnd_dst, mem_ctx, sharename,
    2147                         PRINTER_ALL_ACCESS, cli->user_name, &hnd_dst)) {
     2180                        PRINTER_ALL_ACCESS, &hnd_dst)) {
    21482181
    21492182                        DEBUG(1,("could not open printer: %s\n", sharename));
     
    21672200                /* open src printer handle */
    21682201                if (!net_spoolss_open_printer_ex(pipe_hnd, mem_ctx, sharename,
    2169                         MAXIMUM_ALLOWED_ACCESS, cli->user_name, &hnd_src))
     2202                        MAXIMUM_ALLOWED_ACCESS, &hnd_src))
    21702203                        goto done;
    21712204
     
    22642297        struct rpc_pipe_client *pipe_hnd_dst = NULL;
    22652298        struct dcerpc_binding_handle *b_dst = NULL;
    2266         struct policy_handle hnd_src, hnd_dst;
     2299        struct policy_handle hnd_src = { 0, };
     2300        struct policy_handle hnd_dst = { 0, };
    22672301        union spoolss_PrinterInfo *info_enum;
    22682302        union spoolss_PrinterInfo info_dst_publish;
    22692303        union spoolss_PrinterInfo info_dst;
    22702304        struct cli_state *cli_dst = NULL;
    2271         char *devicename = NULL, *unc_name = NULL, *url = NULL;
    22722305        const char *longname;
    22732306        const char **keylist = NULL;
     
    22802313        /* connect destination PI_SPOOLSS */
    22812314        nt_status = connect_dst_pipe(c, &cli_dst, &pipe_hnd_dst,
    2282                                      &ndr_table_spoolss.syntax_id);
     2315                                     &ndr_table_spoolss);
    22832316        if (!NT_STATUS_IS_OK(nt_status)) {
    22842317                return nt_status;
     
    23322365                /* open src printer handle */
    23332366                if (!net_spoolss_open_printer_ex(pipe_hnd, mem_ctx, sharename,
    2334                         MAXIMUM_ALLOWED_ACCESS, cli->user_name, &hnd_src))
     2367                        MAXIMUM_ALLOWED_ACCESS, &hnd_src))
    23352368                        goto done;
    23362369
    23372370                /* open dst printer handle */
    23382371                if (!net_spoolss_open_printer_ex(pipe_hnd_dst, mem_ctx, sharename,
    2339                         PRINTER_ALL_ACCESS, cli_dst->user_name, &hnd_dst))
     2372                        PRINTER_ALL_ACCESS, &hnd_dst))
    23402373                        goto done;
    23412374
     
    24342467                                /* display_value */
    24352468                                if (c->opt_verbose) {
    2436                                         struct regval_blob *v;
    2437 
    2438                                         v = regval_compose(talloc_tos(),
    2439                                                            r.out.value_name,
    2440                                                            *r.out.type,
    2441                                                            r.out.data,
    2442                                                            r.in.data_offered);
    2443                                         if (v == NULL) {
    2444                                                 nt_status = NT_STATUS_NO_MEMORY;
    2445                                                 goto done;
    2446                                         }
    2447 
    2448                                         display_reg_value(SPOOL_PRINTERDATA_KEY, v);
    2449                                         talloc_free(v);
     2469                                        struct registry_value v;
     2470                                        v.type = *r.out.type;
     2471                                        v.data = data_blob_const(
     2472                                                r.out.data, r.in.data_offered);
     2473
     2474                                        display_reg_value(SPOOL_PRINTERDATA_KEY,
     2475                                                          r.out.value_name, &v);
    24502476                                }
    24512477
     
    24962522                        for (j=0; j < count; j++) {
    24972523
    2498                                 struct regval_blob *value;
    2499                                 DATA_BLOB blob;
    2500 
    2501                                 ZERO_STRUCT(blob);
     2524                                struct registry_value value;
     2525                                const char *value_name = info[j].value_name;
     2526                                bool ok;
     2527
     2528                                value.type = REG_SZ;
    25022529
    25032530                                /* although samba replies with sane data in most cases we
    25042531                                   should try to avoid writing wrong registry data */
    25052532
    2506                                 if (strequal(info[j].value_name, SPOOL_REG_PORTNAME) ||
    2507                                     strequal(info[j].value_name, SPOOL_REG_UNCNAME) ||
    2508                                     strequal(info[j].value_name, SPOOL_REG_URL) ||
    2509                                     strequal(info[j].value_name, SPOOL_REG_SHORTSERVERNAME) ||
    2510                                     strequal(info[j].value_name, SPOOL_REG_SERVERNAME)) {
    2511 
    2512                                         if (strequal(info[j].value_name, SPOOL_REG_PORTNAME)) {
    2513 
    2514                                                 /* although windows uses a multi-sz, we use a sz */
    2515                                                 push_reg_sz(mem_ctx, &blob, SAMBA_PRINTER_PORT_NAME);
    2516                                         }
    2517 
    2518                                         if (strequal(info[j].value_name, SPOOL_REG_UNCNAME)) {
    2519 
    2520                                                 if (asprintf(&unc_name, "\\\\%s\\%s", longname, sharename) < 0) {
    2521                                                         nt_status = NT_STATUS_NO_MEMORY;
    2522                                                         goto done;
    2523                                                 }
    2524                                                 push_reg_sz(mem_ctx, &blob, unc_name);
    2525                                         }
    2526 
    2527                                         if (strequal(info[j].value_name, SPOOL_REG_URL)) {
    2528 
    2529                                                 continue;
    2530 
    2531 #if 0
    2532                                                 /* FIXME: should we really do that ??? */
    2533                                                 if (asprintf(&url, "http://%s:631/printers/%s", longname, sharename) < 0) {
    2534                                                         nt_status = NT_STATUS_NO_MEMORY;
    2535                                                         goto done;
    2536                                                 }
    2537                                                 push_reg_sz(mem_ctx, NULL, &blob, url);
    2538                                                 fstrcpy(value.valuename, SPOOL_REG_URL);
    2539 #endif
    2540                                         }
    2541 
    2542                                         if (strequal(info[j].value_name, SPOOL_REG_SERVERNAME)) {
    2543 
    2544                                                 push_reg_sz(mem_ctx, &blob, longname);
    2545                                         }
    2546 
    2547                                         if (strequal(info[j].value_name, SPOOL_REG_SHORTSERVERNAME)) {
    2548 
    2549                                                 push_reg_sz(mem_ctx, &blob, global_myname());
    2550                                         }
    2551 
    2552                                         value = regval_compose(talloc_tos(),
    2553                                                                info[j].value_name,
    2554                                                                REG_SZ,
    2555                                                                blob.length == 0 ? NULL : blob.data,
    2556                                                                blob.length);
    2557                                         if (value == NULL) {
     2533                                if (strequal(value_name, SPOOL_REG_PORTNAME)) {
     2534                                        /* although windows uses a multi-sz, we use a sz */
     2535                                        ok = push_reg_sz(mem_ctx, &value.data, SAMBA_PRINTER_PORT_NAME);
     2536                                        if (!ok) {
    25582537                                                nt_status = NT_STATUS_NO_MEMORY;
    25592538                                                goto done;
    25602539                                        }
    2561 
    2562                                         if (c->opt_verbose)
    2563                                                 display_reg_value(subkey, value);
    2564 
    2565                                         /* here we have to set all subkeys on the dst server */
    2566                                         if (!net_spoolss_setprinterdataex(pipe_hnd_dst, mem_ctx, &hnd_dst,
    2567                                                         subkey, value))
    2568                                         {
    2569                                                 talloc_free(value);
    2570                                                 goto done;
    2571                                         }
    2572 
    2573                                         talloc_free(value);
    2574                                 } else {
    2575 
    2576                                         struct regval_blob *v;
    2577 
    2578                                         v = regval_compose(talloc_tos(),
    2579                                                            info[j].value_name,
    2580                                                            info[j].type,
    2581                                                            info[j].data->data,
    2582                                                            info[j].data->length);
    2583                                         if (v == NULL) {
     2540                                }
     2541                                else if (strequal(value_name, SPOOL_REG_UNCNAME)) {
     2542                                        char *unc_name;
     2543                                        if (asprintf(&unc_name, "\\\\%s\\%s", longname, sharename) < 0) {
    25842544                                                nt_status = NT_STATUS_NO_MEMORY;
    25852545                                                goto done;
    25862546                                        }
    2587 
    2588                                         if (c->opt_verbose) {
    2589                                                 display_reg_value(subkey, v);
    2590                                         }
    2591 
    2592                                         /* here we have to set all subkeys on the dst server */
    2593                                         if (!net_spoolss_setprinterdataex(pipe_hnd_dst, mem_ctx, &hnd_dst,
    2594                                                         subkey, v)) {
     2547                                        ok = push_reg_sz(mem_ctx, &value.data, unc_name);
     2548                                        if (!ok) {
     2549                                                nt_status = NT_STATUS_NO_MEMORY;
    25952550                                                goto done;
    25962551                                        }
    2597 
    2598                                         talloc_free(v);
     2552                                        free(unc_name);
     2553                                }
     2554                                else if (strequal(value_name, SPOOL_REG_URL)) {
     2555                                        continue;
     2556#if 0
     2557                                        /* FIXME: should we really do that ??? */
     2558                                        if (asprintf(&url, "http://%s:631/printers/%s", longname, sharename) < 0) {
     2559                                                nt_status = NT_STATUS_NO_MEMORY;
     2560                                                goto done;
     2561                                        }
     2562                                        push_reg_sz(mem_ctx, NULL, &value.data, url);
     2563                                        free(url);
     2564#endif
     2565                                }
     2566                                else if (strequal(value_name, SPOOL_REG_SERVERNAME)) {
     2567                                        ok = push_reg_sz(mem_ctx, &value.data, longname);
     2568                                        if (!ok) {
     2569                                                nt_status = NT_STATUS_NO_MEMORY;
     2570                                                goto done;
     2571                                        }
     2572                                }
     2573                                else if (strequal(value_name, SPOOL_REG_SHORTSERVERNAME)) {
     2574                                        ok = push_reg_sz(mem_ctx, &value.data, lp_netbios_name());
     2575                                        if (!ok) {
     2576                                                nt_status = NT_STATUS_NO_MEMORY;
     2577                                                goto done;
     2578                                        }
     2579                                }
     2580                                else {
     2581                                        value.type = info[j].type;
     2582                                        value.data = *info[j].data;
     2583                                }
     2584
     2585                                if (c->opt_verbose) {
     2586                                        display_reg_value(subkey, value_name, &value);
     2587                                }
     2588
     2589                                /* here we have to set all subkeys on the dst server */
     2590                                if (!net_spoolss_setprinterdataex(pipe_hnd_dst, mem_ctx, &hnd_dst,
     2591                                                                  subkey, value_name, &value))
     2592                                {
     2593                                        goto done;
    25992594                                }
    26002595
     
    26202615
    26212616done:
    2622         SAFE_FREE(devicename);
    2623         SAFE_FREE(url);
    2624         SAFE_FREE(unc_name);
    2625 
    26262617        if (is_valid_policy_hnd(&hnd_src)) {
    26272618                dcerpc_spoolss_ClosePrinter(b_src, mem_ctx, &hnd_src, &result);
  • vendor/current/source3/utils/net_rpc_registry.c

    r740 r988  
    7676
    7777static bool reg_hive_key(TALLOC_CTX *ctx, const char *fullname,
    78                          uint32 *reg_type, const char **key_name)
     78                         uint32_t *reg_type, const char **key_name)
    7979{
    8080        WERROR werr;
     
    129129static NTSTATUS registry_openkey(TALLOC_CTX *mem_ctx,
    130130                                 struct rpc_pipe_client *pipe_hnd,
    131                                  const char *name, uint32 access_mask,
     131                                 const char *name, uint32_t access_mask,
    132132                                 struct policy_handle *hive_hnd,
    133133                                 struct policy_handle *key_hnd)
    134134{
    135         uint32 hive;
     135        uint32_t hive;
    136136        NTSTATUS status;
    137137        WERROR werr;
     
    172172                                  struct rpc_pipe_client *pipe_hnd,
    173173                                  struct policy_handle *key_hnd,
    174                                   uint32 *pnum_keys, char ***pnames,
     174                                  uint32_t *pnum_keys, char ***pnames,
    175175                                  char ***pclasses, NTTIME ***pmodtimes)
    176176{
     
    178178        NTSTATUS status;
    179179        WERROR werr;
    180         uint32 num_subkeys, max_subkeylen, max_classlen;
    181         uint32 num_values, max_valnamelen, max_valbufsize;
    182         uint32 i;
     180        uint32_t num_subkeys, max_subkeylen, max_classlen;
     181        uint32_t num_values, max_valnamelen, max_valbufsize;
     182        uint32_t i;
    183183        NTTIME last_changed_time;
    184         uint32 secdescsize;
     184        uint32_t secdescsize;
    185185        struct winreg_String classname;
    186186        char **names, **classes;
     
    212212        }
    213213
    214         if ((!(names = TALLOC_ZERO_ARRAY(mem_ctx, char *, num_subkeys))) ||
    215             (!(classes = TALLOC_ZERO_ARRAY(mem_ctx, char *, num_subkeys))) ||
    216             (!(modtimes = TALLOC_ZERO_ARRAY(mem_ctx, NTTIME *,
     214        if ((!(names = talloc_zero_array(mem_ctx, char *, num_subkeys))) ||
     215            (!(classes = talloc_zero_array(mem_ctx, char *, num_subkeys))) ||
     216            (!(modtimes = talloc_zero_array(mem_ctx, NTTIME *,
    217217                                            num_subkeys)))) {
    218218                status = NT_STATUS_NO_MEMORY;
     
    294294                                    struct rpc_pipe_client *pipe_hnd,
    295295                                    struct policy_handle *key_hnd,
    296                                     uint32 *pnum_values, char ***pvalnames,
     296                                    uint32_t *pnum_values, char ***pvalnames,
    297297                                    struct registry_value ***pvalues)
    298298{
     
    300300        NTSTATUS status;
    301301        WERROR werr;
    302         uint32 num_subkeys, max_subkeylen, max_classlen;
    303         uint32 num_values, max_valnamelen, max_valbufsize;
    304         uint32 i;
     302        uint32_t num_subkeys, max_subkeylen, max_classlen;
     303        uint32_t num_values, max_valnamelen, max_valbufsize;
     304        uint32_t i;
    305305        NTTIME last_changed_time;
    306         uint32 secdescsize;
     306        uint32_t secdescsize;
    307307        struct winreg_String classname;
    308308        struct registry_value **values;
     
    334334        }
    335335
    336         if ((!(names = TALLOC_ARRAY(mem_ctx, char *, num_values))) ||
    337             (!(values = TALLOC_ARRAY(mem_ctx, struct registry_value *,
     336        if ((!(names = talloc_array(mem_ctx, char *, num_values))) ||
     337            (!(values = talloc_array(mem_ctx, struct registry_value *,
    338338                                     num_values)))) {
    339339                status = NT_STATUS_NO_MEMORY;
     
    343343        for (i=0; i<num_values; i++) {
    344344                enum winreg_Type type = REG_NONE;
    345                 uint8 *data = NULL;
    346                 uint32 data_size;
    347                 uint32 value_length;
     345                uint8_t *data = NULL;
     346                uint32_t data_size;
     347                uint32_t value_length;
    348348
    349349                char n;
     
    356356
    357357                data_size = max_valbufsize;
    358                 data = (uint8 *)TALLOC(mem_ctx, data_size);
     358                data = (uint8_t *)TALLOC(mem_ctx, data_size);
    359359                value_length = 0;
    360360
     
    417417                                     struct rpc_pipe_client *pipe_hnd,
    418418                                     struct policy_handle *key_hnd,
    419                                      uint32 *pnum_values, char ***pvalnames,
     419                                     uint32_t *pnum_values, char ***pvalnames,
    420420                                     struct regval_blob ***pvalues)
    421421{
     
    423423        NTSTATUS status;
    424424        WERROR werr;
    425         uint32 num_subkeys, max_subkeylen, max_classlen;
    426         uint32 num_values, max_valnamelen, max_valbufsize;
    427         uint32 i;
     425        uint32_t num_subkeys, max_subkeylen, max_classlen;
     426        uint32_t num_values, max_valnamelen, max_valbufsize;
     427        uint32_t i;
    428428        NTTIME last_changed_time;
    429         uint32 secdescsize;
     429        uint32_t secdescsize;
    430430        struct winreg_String classname;
    431431        struct regval_blob **values;
     
    457457        }
    458458
    459         if ((!(names = TALLOC_ARRAY(mem_ctx, char *, num_values))) ||
    460             (!(values = TALLOC_ARRAY(mem_ctx, struct regval_blob *,
     459        if ((!(names = talloc_array(mem_ctx, char *, num_values))) ||
     460            (!(values = talloc_array(mem_ctx, struct regval_blob *,
    461461                                     num_values)))) {
    462462                status = NT_STATUS_NO_MEMORY;
     
    466466        for (i=0; i<num_values; i++) {
    467467                enum winreg_Type type = REG_NONE;
    468                 uint8 *data = NULL;
    469                 uint32 data_size;
    470                 uint32 value_length;
     468                uint8_t *data = NULL;
     469                uint32_t data_size;
     470                uint32_t value_length;
    471471
    472472                char n;
     
    479479
    480480                data_size = max_valbufsize;
    481                 data = (uint8 *)TALLOC(mem_ctx, data_size);
     481                data = (uint8_t *)TALLOC(mem_ctx, data_size);
    482482                value_length = 0;
    483483
     
    510510                }
    511511
    512                 assert(value_length<=data_size); //???
     512                assert(value_length<=data_size); /*??? */
    513513
    514514                values[i] = regval_compose(values,
     
    648648        }
    649649
    650         return run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
     650        return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
    651651                rpc_registry_setvalue_internal, argc, argv );
    652652}
     
    708708        }
    709709
    710         return run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
     710        return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
    711711                rpc_registry_deletevalue_internal, argc, argv );
    712712}
     
    836836        }
    837837
    838         return run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
     838        return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
    839839                rpc_registry_getvalue_full, argc, argv);
    840840}
     
    864864        }
    865865
    866         return run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
     866        return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
    867867                rpc_registry_getvalue_raw, argc, argv);
    868868}
     
    877877                                                const char **argv )
    878878{
    879         uint32 hive;
     879        uint32_t hive;
    880880        struct policy_handle hive_hnd, key_hnd;
    881881        struct winreg_String key, keyclass;
     
    950950        }
    951951
    952         return run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
     952        return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
    953953                rpc_registry_createkey_internal, argc, argv );
    954954}
     
    963963                                                const char **argv )
    964964{
    965         uint32 hive;
     965        uint32_t hive;
    966966        struct policy_handle hive_hnd;
    967967        struct winreg_String key;
     
    10161016        }
    10171017
    1018         return run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
     1018        return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
    10191019                rpc_registry_deletekey_internal, argc, argv );
    10201020}
     
    10351035        NTSTATUS status;
    10361036        WERROR werr;
    1037         uint32 num_subkeys = 0;
    1038         uint32 num_values = 0;
     1037        uint32_t num_subkeys = 0;
     1038        uint32_t num_values = 0;
    10391039        char **names = NULL, **classes = NULL;
    10401040        NTTIME **modtimes = NULL;
    1041         uint32 i;
     1041        uint32_t i;
    10421042        struct registry_value **values = NULL;
    10431043        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
     
    10961096                                  const char **argv )
    10971097{
    1098         return run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
     1098        return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
    10991099                rpc_registry_enumerate_internal, argc, argv );
    11001100}
     
    11371137        if (!NT_STATUS_IS_OK(status)) {
    11381138                d_fprintf(stderr, _("Unable to save [%s] to %s:%s\n"), argv[0],
    1139                           cli->desthost, argv[1]);
     1139                          pipe_hnd->desthost, argv[1]);
    11401140        }
    11411141        if (!W_ERROR_IS_OK(result)) {
    11421142                status = werror_to_ntstatus(result);
    11431143                d_fprintf(stderr, _("Unable to save [%s] to %s:%s\n"), argv[0],
    1144                           cli->desthost, argv[1]);
     1144                          pipe_hnd->desthost, argv[1]);
    11451145        }
    11461146
     
    11581158static int rpc_registry_save(struct net_context *c, int argc, const char **argv )
    11591159{
    1160         return run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
     1160        return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
    11611161                rpc_registry_save_internal, argc, argv );
    11621162}
     
    11701170        int i, j;
    11711171        const char *data_str = NULL;
    1172         uint32 data_size, data;
     1172        uint32_t data_size, data;
    11731173        DATA_BLOB blob;
    11741174
     
    11841184                        case REG_SZ:
    11851185                                blob = data_blob_const(nk->values[i].data, data_size);
    1186                                 pull_reg_sz(talloc_tos(), &blob, &data_str);
     1186                                if (!pull_reg_sz(talloc_tos(), &blob,
     1187                                                 &data_str)) {
     1188                                        data_str = NULL;
     1189                                }
    11871190                                if (!data_str) {
    11881191                                        break;
     
    14521455        }
    14531456
    1454         sd = TALLOC_ZERO_P(mem_ctx, struct KeySecurityData);
     1457        sd = talloc_zero(mem_ctx, struct KeySecurityData);
    14551458        if (!sd) {
    14561459                status = NT_STATUS_NO_MEMORY;
     
    15021505static int rpc_registry_getsd(struct net_context *c, int argc, const char **argv)
    15031506{
    1504         return run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
     1507        return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
    15051508                rpc_registry_getsd_internal, argc, argv);
    15061509}
     
    15261529{
    15271530        NTSTATUS status;
    1528         uint32 num_subkeys = 0;
    1529         uint32 num_values = 0;
     1531        uint32_t num_subkeys = 0;
     1532        uint32_t num_values = 0;
    15301533        char **names = NULL, **classes = NULL;
    15311534        NTTIME **modtimes = NULL;
    15321535        struct regval_blob **values = NULL;
    1533         uint32 i;
     1536        uint32_t i;
    15341537        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
    15351538
     
    16571660                               const char **argv )
    16581661{
    1659         return run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
     1662        return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
    16601663                               rpc_registry_export_internal, argc, argv );
    16611664}
     
    16951698
    16961699        if (parent == NULL) {
    1697                 uint32 hive_idx = 0;
     1700                uint32_t hive_idx = 0;
    16981701                if (!reg_hive_key(mem_ctx, name, &hive_idx, &keyname.name)) {
    16991702                        werr = WERR_FOOBAR;
     
    17931796
    17941797        if (parent == NULL) {
    1795                 uint32 hive_idx;
     1798                uint32_t hive_idx;
    17961799                if (!reg_hive_key(mem_ctx, name, &hive_idx, &keyname.name)) {
    17971800                        werr = WERR_FOOBAR;
     
    19951998                               const char **argv )
    19961999{
    1997         return run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
     2000        return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
    19982001                               rpc_registry_import_internal, argc, argv );
    19992002}
  • vendor/current/source3/utils/net_rpc_rights.c

    r740 r988  
    101101{
    102102        NTSTATUS status, result;
    103         uint32 enum_context = 0;
    104         uint32 pref_max_length=0x1000;
     103        uint32_t enum_context = 0;
     104        uint32_t pref_max_length=0x1000;
    105105        int i;
    106         uint16 lang_id=0;
    107         uint16 lang_id_sys=0;
    108         uint16 lang_id_desc;
     106        uint16_t lang_id=0;
     107        uint16_t lang_id_sys=0;
     108        uint16_t lang_id_desc;
    109109        struct lsa_StringLarge *description = NULL;
    110110        struct lsa_PrivArray priv_array;
     
    191191
    192192        for (i = 0; i < rights.count; i++) {
    193                 if (StrCaseCmp(rights.names[i].string, right) == 0) {
     193                if (strcasecmp_m(rights.names[i].string, right) == 0) {
    194194                        return NT_STATUS_OK;
    195195                }
     
    242242{
    243243        NTSTATUS status, result;
    244         uint32 enum_context=0;
    245         uint32 pref_max_length=0x1000;
     244        uint32_t enum_context=0;
     245        uint32_t pref_max_length=0x1000;
    246246        struct lsa_SidArray sid_array;
    247247        int i;
     
    295295{
    296296        NTSTATUS status, result;
    297         uint32 enum_context=0;
    298         uint32 pref_max_length=0x1000;
     297        uint32_t enum_context=0;
     298        uint32_t pref_max_length=0x1000;
    299299        struct lsa_SidArray sid_array;
    300300        int i;
     
    353353        struct lsa_String lsa_name;
    354354        struct lsa_StringLarge *description = NULL;
    355         uint16 lang_id = 0;
    356         uint16 lang_id_sys = 0;
    357         uint16 lang_id_desc;
     355        uint16_t lang_id = 0;
     356        uint16_t lang_id_sys = 0;
     357        uint16_t lang_id_desc;
    358358        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
    359359
     
    507507
    508508        rights.count = argc-1;
    509         rights.names = TALLOC_ARRAY(mem_ctx, struct lsa_StringLarge,
     509        rights.names = talloc_array(mem_ctx, struct lsa_StringLarge,
    510510                                    rights.count);
    511511        if (!rights.names) {
     
    580580
    581581        rights.count = argc-1;
    582         rights.names = TALLOC_ARRAY(mem_ctx, struct lsa_StringLarge,
     582        rights.names = talloc_array(mem_ctx, struct lsa_StringLarge,
    583583                                    rights.count);
    584584        if (!rights.names) {
     
    631631        }
    632632
    633         return run_rpc_command(c, NULL, &ndr_table_lsarpc.syntax_id, 0,
     633        return run_rpc_command(c, NULL, &ndr_table_lsarpc, 0,
    634634                rpc_rights_list_internal, argc, argv );
    635635}
     
    653653        }
    654654
    655         return run_rpc_command(c, NULL, &ndr_table_lsarpc.syntax_id, 0,
     655        return run_rpc_command(c, NULL, &ndr_table_lsarpc, 0,
    656656                rpc_rights_grant_internal, argc, argv );
    657657}
     
    675675        }
    676676
    677         return run_rpc_command(c, NULL, &ndr_table_lsarpc.syntax_id, 0,
     677        return run_rpc_command(c, NULL, &ndr_table_lsarpc, 0,
    678678                rpc_rights_revoke_internal, argc, argv );
    679679}
     
    752752        static struct rpc_sh_cmd cmds[] = {
    753753
    754         { "list", NULL, &ndr_table_lsarpc.syntax_id, rpc_sh_rights_list,
     754        { "list", NULL, &ndr_table_lsarpc, rpc_sh_rights_list,
    755755          N_("View available or assigned privileges") },
    756756
    757         { "grant", NULL, &ndr_table_lsarpc.syntax_id, rpc_sh_rights_grant,
     757        { "grant", NULL, &ndr_table_lsarpc, rpc_sh_rights_grant,
    758758          N_("Assign privilege[s]") },
    759759
    760         { "revoke", NULL, &ndr_table_lsarpc.syntax_id, rpc_sh_rights_revoke,
     760        { "revoke", NULL, &ndr_table_lsarpc, rpc_sh_rights_revoke,
    761761          N_("Revoke privilege[s]") },
    762762
  • vendor/current/source3/utils/net_rpc_samsync.c

    r740 r988  
    5252                ZERO_STRUCT(o);
    5353
    54                 if (!StrnCaseCmp(argv[i], "user_rid=", strlen("user_rid="))) {
     54                if (!strncasecmp_m(argv[i], "user_rid=", strlen("user_rid="))) {
    5555                        o.object_identifier.rid         = get_int_param(argv[i]);
    5656                        o.object_type                   = NETR_DELTA_USER;
    5757                        o.database_id                   = SAM_DATABASE_DOMAIN;
    5858                }
    59                 if (!StrnCaseCmp(argv[i], "group_rid=", strlen("group_rid="))) {
     59                if (!strncasecmp_m(argv[i], "group_rid=", strlen("group_rid="))) {
    6060                        o.object_identifier.rid         = get_int_param(argv[i]);
    6161                        o.object_type                   = NETR_DELTA_GROUP;
    6262                        o.database_id                   = SAM_DATABASE_DOMAIN;
    6363                }
    64                 if (!StrnCaseCmp(argv[i], "group_member_rid=", strlen("group_member_rid="))) {
     64                if (!strncasecmp_m(argv[i], "group_member_rid=", strlen("group_member_rid="))) {
    6565                        o.object_identifier.rid         = get_int_param(argv[i]);
    6666                        o.object_type                   = NETR_DELTA_GROUP_MEMBER;
    6767                        o.database_id                   = SAM_DATABASE_DOMAIN;
    6868                }
    69                 if (!StrnCaseCmp(argv[i], "alias_rid=", strlen("alias_rid="))) {
     69                if (!strncasecmp_m(argv[i], "alias_rid=", strlen("alias_rid="))) {
    7070                        o.object_identifier.rid         = get_int_param(argv[i]);
    7171                        o.object_type                   = NETR_DELTA_ALIAS;
    7272                        o.database_id                   = SAM_DATABASE_BUILTIN;
    7373                }
    74                 if (!StrnCaseCmp(argv[i], "alias_member_rid=", strlen("alias_member_rid="))) {
     74                if (!strncasecmp_m(argv[i], "alias_member_rid=", strlen("alias_member_rid="))) {
    7575                        o.object_identifier.rid         = get_int_param(argv[i]);
    7676                        o.object_type                   = NETR_DELTA_ALIAS_MEMBER;
    7777                        o.database_id                   = SAM_DATABASE_BUILTIN;
    7878                }
    79                 if (!StrnCaseCmp(argv[i], "account_sid=", strlen("account_sid="))) {
     79                if (!strncasecmp_m(argv[i], "account_sid=", strlen("account_sid="))) {
    8080                        const char *sid_str = get_string_param(argv[i]);
    8181                        string_to_sid(&o.object_identifier.sid, sid_str);
     
    8383                        o.database_id                   = SAM_DATABASE_PRIVS;
    8484                }
    85                 if (!StrnCaseCmp(argv[i], "policy_sid=", strlen("policy_sid="))) {
     85                if (!strncasecmp_m(argv[i], "policy_sid=", strlen("policy_sid="))) {
    8686                        const char *sid_str = get_string_param(argv[i]);
    8787                        string_to_sid(&o.object_identifier.sid, sid_str);
     
    8989                        o.database_id                   = SAM_DATABASE_PRIVS;
    9090                }
    91                 if (!StrnCaseCmp(argv[i], "trustdom_sid=", strlen("trustdom_sid="))) {
     91                if (!strncasecmp_m(argv[i], "trustdom_sid=", strlen("trustdom_sid="))) {
    9292                        const char *sid_str = get_string_param(argv[i]);
    9393                        string_to_sid(&o.object_identifier.sid, sid_str);
     
    9595                        o.database_id                   = SAM_DATABASE_PRIVS;
    9696                }
    97                 if (!StrnCaseCmp(argv[i], "secret_name=", strlen("secret_name="))) {
     97                if (!strncasecmp_m(argv[i], "secret_name=", strlen("secret_name="))) {
    9898                        o.object_identifier.name        = get_string_param(argv[i]);
    9999                        o.object_type                   = NETR_DELTA_SECRET;
     
    130130        ctx->mode               = NET_SAMSYNC_MODE_DUMP;
    131131        ctx->cli                = pipe_hnd;
     132        ctx->netlogon_creds     = c->netlogon_creds;
    132133        ctx->ops                = &libnet_samsync_display_ops;
    133134        ctx->domain_name        = domain_name;
     
    336337        if (!dc_info.is_ad) {
    337338                printf(_("DC is not running Active Directory\n"));
    338                 ret = run_rpc_command(c, cli, &ndr_table_netlogon.syntax_id,
     339                ret = run_rpc_command(c, cli, &ndr_table_netlogon,
    339340                                      0,
    340341                                      rpc_vampire_internals, argc, argv);
     
    351352        }
    352353
    353         ret = run_rpc_command(c, cli, &ndr_table_drsuapi.syntax_id,
     354        ret = run_rpc_command(c, cli, &ndr_table_drsuapi,
    354355                              NET_FLAGS_SEAL | NET_FLAGS_TCP,
    355356                              rpc_vampire_ds_internals, argc, argv);
     
    357358                printf(_("Fallback to NT4 vampire on Mixed-Mode AD "
    358359                         "Domain\n"));
    359                 ret = run_rpc_command(c, cli, &ndr_table_netlogon.syntax_id,
     360                ret = run_rpc_command(c, cli, &ndr_table_netlogon,
    360361                                      0,
    361362                                      rpc_vampire_internals, argc, argv);
     
    445446        }
    446447
    447         return run_rpc_command(c, NULL, &ndr_table_netlogon.syntax_id, 0,
     448        return run_rpc_command(c, NULL, &ndr_table_netlogon, 0,
    448449                               rpc_vampire_ldif_internals, argc, argv);
    449450}
     
    602603        if (!dc_info.is_ad) {
    603604                printf(_("DC is not running Active Directory\n"));
    604                 ret = run_rpc_command(c, cli, &ndr_table_netlogon.syntax_id,
     605                ret = run_rpc_command(c, cli, &ndr_table_netlogon,
    605606                                      0,
    606607                                      rpc_vampire_keytab_internals, argc, argv);
    607608        } else {
    608                 ret = run_rpc_command(c, cli, &ndr_table_drsuapi.syntax_id,
     609                ret = run_rpc_command(c, cli, &ndr_table_drsuapi,
    609610                                      NET_FLAGS_SEAL | NET_FLAGS_TCP,
    610611                                      rpc_vampire_keytab_ds_internals, argc, argv);
     
    612613                        printf(_("Fallback to NT4 vampire on Mixed-Mode AD "
    613614                                 "Domain\n"));
    614                         ret = run_rpc_command(c, cli, &ndr_table_netlogon.syntax_id,
     615                        ret = run_rpc_command(c, cli, &ndr_table_netlogon,
    615616                                              0,
    616617                                              rpc_vampire_keytab_internals, argc, argv);
     618                } else {
     619#ifndef HAVE_ADS
     620                        printf(_("Vampire requested against AD DC but ADS"
     621                                " support not built in: HAVE_ADS is not defined\n"));
     622#endif
    617623                }
    618624        }
  • vendor/current/source3/utils/net_rpc_service.c

    r740 r988  
    2424
    2525struct svc_state_msg {
    26         uint32 flag;
     26        uint32_t flag;
    2727        const char *message;
    2828};
     
    4242/********************************************************************
    4343********************************************************************/
    44 const char *svc_status_string( uint32 state )
     44const char *svc_status_string( uint32_t state )
    4545{
    4646        fstring msg;
     
    135135                                struct policy_handle *hSCM,
    136136                                const char *service,
    137                                 uint32 *state )
     137                                uint32_t *state )
    138138{
    139139        struct policy_handle hService;
     
    182182                                struct policy_handle *hSCM,
    183183                                const char *service,
    184                                 uint32 watch_state,
    185                                 uint32 *final_state )
    186 {
    187         uint32 i;
    188         uint32 state = 0;
     184                                uint32_t watch_state,
     185                                uint32_t *final_state )
     186{
     187        uint32_t i;
     188        uint32_t state = 0;
    189189        WERROR result = WERR_GENERAL_FAILURE;
    190190
     
    201201                d_printf(".");
    202202                i++;
    203                 sys_usleep( 100 );
     203                usleep( 100 );
    204204        }
    205205        d_printf("\n");
     
    217217                                struct policy_handle *hSCM,
    218218                                const char *service,
    219                                 uint32 control,
    220                                 uint32 watch_state )
     219                                uint32_t control,
     220                                uint32_t watch_state )
    221221{
    222222        struct policy_handle hService;
     
    224224        NTSTATUS status;
    225225        struct SERVICE_STATUS service_status;
    226         uint32 state = 0;
     226        uint32_t state = 0;
    227227        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
    228228
     
    290290        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
    291291
    292         uint8_t *buffer = NULL;
     292        uint8_t *buffer;
    293293        uint32_t buf_size = 0;
    294294        uint32_t bytes_needed = 0;
     
    306306        if (!W_ERROR_IS_OK(result)) {
    307307                return werror_to_ntstatus(result);
     308        }
     309
     310        buffer = talloc_array(mem_ctx, uint8_t, buf_size);
     311        if (buffer == NULL) {
     312                status = NT_STATUS_NO_MEMORY;
     313                goto done;
    308314        }
    309315
     
    328334
    329335                if (W_ERROR_EQUAL(result, WERR_MORE_DATA) && bytes_needed > 0) {
    330                         buffer = talloc_array(mem_ctx, uint8_t, bytes_needed);
    331336                        buf_size = bytes_needed;
     337                        buffer = talloc_realloc(mem_ctx, buffer, uint8_t, bytes_needed);
     338                        if (buffer == NULL) {
     339                                status = NT_STATUS_NO_MEMORY;
     340                                break;
     341                        }
    332342                        continue;
    333343                }
     
    382392        } while (W_ERROR_EQUAL(result, WERR_MORE_DATA));
    383393
     394done:
    384395        if (is_valid_policy_hnd(&hSCM)) {
    385396                WERROR _result;
     
    674685        WERROR result = WERR_GENERAL_FAILURE;
    675686        NTSTATUS status;
    676         uint32 state = 0;
     687        uint32_t state = 0;
    677688        struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
    678689
     
    919930        }
    920931
    921         return run_rpc_command(c, NULL, &ndr_table_svcctl.syntax_id, 0,
     932        return run_rpc_command(c, NULL, &ndr_table_svcctl, 0,
    922933                rpc_service_list_internal, argc, argv );
    923934}
     
    937948        }
    938949
    939         return run_rpc_command(c, NULL, &ndr_table_svcctl.syntax_id, 0,
     950        return run_rpc_command(c, NULL, &ndr_table_svcctl, 0,
    940951                rpc_service_start_internal, argc, argv );
    941952}
     
    955966        }
    956967
    957         return run_rpc_command(c, NULL, &ndr_table_svcctl.syntax_id, 0,
     968        return run_rpc_command(c, NULL, &ndr_table_svcctl, 0,
    958969                rpc_service_stop_internal, argc, argv );
    959970}
     
    973984        }
    974985
    975         return run_rpc_command(c, NULL, &ndr_table_svcctl.syntax_id, 0,
     986        return run_rpc_command(c, NULL, &ndr_table_svcctl, 0,
    976987                rpc_service_resume_internal, argc, argv );
    977988}
     
    9911002        }
    9921003
    993         return run_rpc_command(c, NULL, &ndr_table_svcctl.syntax_id, 0,
     1004        return run_rpc_command(c, NULL, &ndr_table_svcctl, 0,
    9941005                rpc_service_pause_internal, argc, argv );
    9951006}
     
    10091020        }
    10101021
    1011         return run_rpc_command(c, NULL, &ndr_table_svcctl.syntax_id, 0,
     1022        return run_rpc_command(c, NULL, &ndr_table_svcctl, 0,
    10121023                rpc_service_status_internal, argc, argv );
    10131024}
     
    10271038        }
    10281039
    1029         return run_rpc_command(c, NULL, &ndr_table_svcctl.syntax_id, 0,
     1040        return run_rpc_command(c, NULL, &ndr_table_svcctl, 0,
    10301041                rpc_service_delete_internal, argc, argv);
    10311042}
     
    10451056        }
    10461057
    1047         return run_rpc_command(c, NULL, &ndr_table_svcctl.syntax_id, 0,
     1058        return run_rpc_command(c, NULL, &ndr_table_svcctl, 0,
    10481059                rpc_service_create_internal, argc, argv);
    10491060}
  • vendor/current/source3/utils/net_rpc_sh_acct.c

    r740 r988  
    466466{
    467467        static struct rpc_sh_cmd cmds[9] = {
    468                 { "show", NULL, &ndr_table_samr.syntax_id, rpc_sh_acct_pol_show,
     468                { "show", NULL, &ndr_table_samr, rpc_sh_acct_pol_show,
    469469                  N_("Show current account policy settings") },
    470                 { "badpw", NULL, &ndr_table_samr.syntax_id, rpc_sh_acct_set_badpw,
     470                { "badpw", NULL, &ndr_table_samr, rpc_sh_acct_set_badpw,
    471471                  N_("Set bad password count before lockout") },
    472                 { "lockduration", NULL, &ndr_table_samr.syntax_id, rpc_sh_acct_set_lockduration,
     472                { "lockduration", NULL, &ndr_table_samr, rpc_sh_acct_set_lockduration,
    473473                  N_("Set account lockout duration") },
    474                 { "resetduration", NULL, &ndr_table_samr.syntax_id,
     474                { "resetduration", NULL, &ndr_table_samr,
    475475                  rpc_sh_acct_set_resetduration,
    476476                  N_("Set bad password count reset duration") },
    477                 { "minpwage", NULL, &ndr_table_samr.syntax_id, rpc_sh_acct_set_minpwage,
     477                { "minpwage", NULL, &ndr_table_samr, rpc_sh_acct_set_minpwage,
    478478                  N_("Set minimum password age") },
    479                 { "maxpwage", NULL, &ndr_table_samr.syntax_id, rpc_sh_acct_set_maxpwage,
     479                { "maxpwage", NULL, &ndr_table_samr, rpc_sh_acct_set_maxpwage,
    480480                  N_("Set maximum password age") },
    481                 { "minpwlen", NULL, &ndr_table_samr.syntax_id, rpc_sh_acct_set_minpwlen,
     481                { "minpwlen", NULL, &ndr_table_samr, rpc_sh_acct_set_minpwlen,
    482482                  N_("Set minimum password length") },
    483                 { "pwhistlen", NULL, &ndr_table_samr.syntax_id, rpc_sh_acct_set_pwhistlen,
     483                { "pwhistlen", NULL, &ndr_table_samr, rpc_sh_acct_set_pwhistlen,
    484484                  N_("Set the password history length") },
    485485                { NULL, NULL, 0, NULL, NULL }
  • vendor/current/source3/utils/net_rpc_shell.c

    r740 r988  
    8686        }
    8787
    88         status = cli_rpc_pipe_open_noauth(ctx->cli, cmd->interface,
     88        status = cli_rpc_pipe_open_noauth(ctx->cli, cmd->table,
    8989                                          &pipe_hnd);
    9090        if (!NT_STATUS_IS_OK(status)) {
     
    155155        }
    156156
    157         new_ctx = TALLOC_P(ctx, struct rpc_sh_ctx);
     157        new_ctx = talloc(ctx, struct rpc_sh_ctx);
    158158        if (new_ctx == NULL) {
    159159                d_fprintf(stderr, _("talloc failed\n"));
     
    198198static struct rpc_sh_cmd sh_cmds[6] = {
    199199
    200         { "info", NULL, &ndr_table_samr.syntax_id, rpc_sh_info,
     200        { "info", NULL, &ndr_table_samr, rpc_sh_info,
    201201          N_("Print information about the domain connected to") },
    202202
     
    235235        }
    236236
    237         ctx = TALLOC_P(NULL, struct rpc_sh_ctx);
     237        ctx = talloc(NULL, struct rpc_sh_ctx);
    238238        if (ctx == NULL) {
    239239                d_fprintf(stderr, _("talloc failed\n"));
  • vendor/current/source3/utils/net_rpc_trust.c

    r740 r988  
    129129        r.in.policy_handle = pol_hnd;
    130130        r.in.info = &trustinfo;
    131         r.in.auth_info = authinfo;
     131        r.in.auth_info_internal = authinfo;
    132132        r.in.access_mask = LSA_TRUSTED_SET_POSIX | LSA_TRUSTED_SET_AUTH |
    133133                           LSA_TRUSTED_QUERY_DOMAIN_NAME;
     
    197197                                     struct rpc_pipe_client **pipe_hnd,
    198198                                     struct policy_handle *pol_hnd,
    199                                      struct dom_data *dom_data)
     199                                     struct dom_data *dom_data,
     200                                     DATA_BLOB *session_key)
    200201{
    201202        NTSTATUS status;
     
    210211        }
    211212
    212         status = cli_rpc_pipe_open_noauth(*cli, &ndr_table_lsarpc.syntax_id, pipe_hnd);
     213        status = cli_rpc_pipe_open_noauth(*cli, &ndr_table_lsarpc, pipe_hnd);
    213214        if (!NT_STATUS_IS_OK(status)) {
    214215                DEBUG(0, ("Failed to initialise lsa pipe with error [%s]\n",
     
    245246        }
    246247
     248        status = cli_get_session_key(mem_ctx, *pipe_hnd, session_key);
     249        if (!NT_STATUS_IS_OK(status)) {
     250                DEBUG(0,("Error getting session_key of LSA pipe. Error was %s\n",
     251                        nt_errstr(status)));
     252                return status;
     253        }
     254
    247255        return NT_STATUS_OK;
    248256}
     
    270278                                  strlen(password),
    271279                                  &auth_info_array[0].AuthInfo.clear.password,
    272                                   &converted_size, true)) {
     280                                  &converted_size)) {
    273281                return false;
    274282        }
     
    413421        struct cli_state *cli[2] = {NULL, NULL};
    414422        struct rpc_pipe_client *pipe_hnd[2] = {NULL, NULL};
     423        DATA_BLOB session_key[2];
    415424        struct policy_handle pol_hnd[2];
    416425        struct lsa_TrustDomainInfoAuthInfoInternal authinfo;
     
    421430        struct dom_data dom_data[2];
    422431        void (*usage)(void);
     432
     433        ZERO_STRUCT(session_key);
    423434
    424435        switch (op) {
     
    481492
    482493        status = connect_and_get_info(mem_ctx, net_ctx, &cli[0], &pipe_hnd[0],
    483                                       &pol_hnd[0], &dom_data[0]);
     494                                      &pol_hnd[0], &dom_data[0], &session_key[0]);
    484495        if (!NT_STATUS_IS_OK(status)) {
    485496                DEBUG(0, ("connect_and_get_info failed with error [%s]\n",
     
    491502                status = connect_and_get_info(mem_ctx, other_net_ctx,
    492503                                              &cli[1], &pipe_hnd[1],
    493                                               &pol_hnd[1], &dom_data[1]);
     504                                              &pol_hnd[1], &dom_data[1],
     505                                              &session_key[1]);
    494506                if (!NT_STATUS_IS_OK(status)) {
    495507                        DEBUG(0, ("connect_and_get_info failed with error [%s]\n",
     
    507519
    508520                        DEBUG(0, ("Using random trust password.\n"));
    509         /* FIXME: why only 8 characters work? Would it be possible to use a
    510          * random binary password? */
    511                         trust_pw = generate_random_str(mem_ctx, 8);
     521                        trust_pw = generate_random_password(mem_ctx,
     522                                        DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH,
     523                                        DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH);
    512524                        if (trust_pw == NULL) {
    513                                 DEBUG(0, ("generate_random_str failed.\n"));
     525                                DEBUG(0, ("generate_random_password failed.\n"));
    514526                                goto done;
    515527                        }
     
    535547                arcfour_crypt_blob(authinfo.auth_blob.data,
    536548                                   authinfo.auth_blob.size,
    537                                    &cli[0]->user_session_key);
     549                                   &session_key[0]);
    538550
    539551                status = create_trust(mem_ctx, pipe_hnd[0]->binding_handle,
     
    562574                        arcfour_crypt_blob(authinfo.auth_blob.data,
    563575                                           authinfo.auth_blob.size,
    564                                            &cli[1]->user_session_key);
     576                                           &session_key[1]);
    565577
    566578                        status = create_trust(mem_ctx,
     
    618630
    619631done:
     632        data_blob_clear_free(&session_key[0]);
     633        data_blob_clear_free(&session_key[1]);
    620634        cli_shutdown(cli[0]);
    621635        cli_shutdown(cli[1]);
  • vendor/current/source3/utils/net_sam.c

    r740 r988  
    2727#include "lib/winbind_util.h"
    2828#include "passdb.h"
     29#include "passdb/pdb_ldap_util.h"
     30#include "passdb/pdb_ldap_schema.h"
    2931#include "lib/privileges.h"
     32#include "secrets.h"
     33#include "idmap.h"
    3034
    3135/*
     
    139143static int net_sam_set_userflag(struct net_context *c, int argc,
    140144                                const char **argv, const char *field,
    141                                 uint16 flag)
     145                                uint16_t flag)
    142146{
    143147        struct samu *sam_acct = NULL;
     
    300304                               const char **argv)
    301305{
    302         GROUP_MAP map;
     306        GROUP_MAP *map;
    303307        struct dom_sid sid;
    304308        enum lsa_SidType type;
     
    331335        }
    332336
    333         if (!pdb_getgrsid(&map, sid)) {
     337        map = talloc_zero(talloc_tos(), GROUP_MAP);
     338        if (!map) {
     339                d_fprintf(stderr, _("Out of memory!\n"));
     340                return -1;
     341        }
     342
     343        if (!pdb_getgrsid(map, sid)) {
    334344                d_fprintf(stderr, _("Could not load group %s\n"), argv[0]);
    335345                return -1;
    336346        }
    337347
    338         fstrcpy(map.comment, argv[1]);
    339 
    340         status = pdb_update_group_mapping_entry(&map);
     348        map->comment = talloc_strdup(map, argv[1]);
     349        if (!map->comment) {
     350                d_fprintf(stderr, _("Out of memory!\n"));
     351                return -1;
     352        }
     353
     354        status = pdb_update_group_mapping_entry(map);
    341355
    342356        if (!NT_STATUS_IS_OK(status)) {
     
    349363                 argv[1]);
    350364
     365        TALLOC_FREE(map);
    351366        return 0;
    352367}
     
    466481{
    467482        const char *account_policy = NULL;
    468         uint32 value = 0;
    469         uint32 old_value = 0;
     483        uint32_t value = 0;
     484        uint32_t old_value = 0;
    470485        enum pdb_policy_type field;
    471486        char *endptr;
     
    500515                int i, count;
    501516
    502                 account_policy_names_list(&names, &count);
     517                account_policy_names_list(talloc_tos(), &names, &count);
    503518                d_fprintf(stderr, _("No account policy \"%s\"!\n\n"), argv[0]);
    504519                d_fprintf(stderr, _("Valid account policies are:\n"));
     
    508523                }
    509524
    510                 SAFE_FREE(names);
     525                TALLOC_FREE(names);
     526
    511527                return -1;
    512528        }
     
    535551{
    536552        const char *account_policy = NULL;
    537         uint32 old_value;
     553        uint32_t old_value;
    538554        enum pdb_policy_type field;
    539555
     
    552568                int count;
    553569                int i;
    554                 account_policy_names_list(&names, &count);
     570                account_policy_names_list(talloc_tos(), &names, &count);
    555571                d_fprintf(stderr, _("No account policy by that name!\n"));
    556572                if (count != 0) {
     
    561577                        }
    562578                }
    563                 SAFE_FREE(names);
     579                TALLOC_FREE(names);
    564580                return -1;
    565581        }
     
    593609        }
    594610
    595         account_policy_names_list(&names, &count);
     611        account_policy_names_list(talloc_tos(), &names, &count);
    596612        if (count != 0) {
    597613                d_fprintf(stderr, _("Valid account policies "
     
    601617                }
    602618        }
    603         SAFE_FREE(names);
     619        TALLOC_FREE(names);
    604620        return -1;
    605621}
     
    807823 */
    808824
    809 static NTSTATUS map_unix_group(const struct group *grp, GROUP_MAP *pmap)
    810 {
    811         NTSTATUS status;
    812         GROUP_MAP map;
    813         const char *grpname, *dom, *name;
    814         uint32 rid;
    815 
    816         if (pdb_getgrgid(&map, grp->gr_gid)) {
     825static NTSTATUS map_unix_group(const struct group *grp, GROUP_MAP *map)
     826{
     827        const char *dom, *name;
     828        uint32_t rid;
     829
     830        if (pdb_getgrgid(map, grp->gr_gid)) {
    817831                return NT_STATUS_GROUP_EXISTS;
    818832        }
    819833
    820         map.gid = grp->gr_gid;
    821         grpname = grp->gr_name;
    822 
    823         if (lookup_name(talloc_tos(), grpname, LOOKUP_NAME_LOCAL,
     834        map->gid = grp->gr_gid;
     835
     836        if (lookup_name(talloc_tos(), grp->gr_name, LOOKUP_NAME_LOCAL,
    824837                        &dom, &name, NULL, NULL)) {
    825838
    826                 const char *tmp = talloc_asprintf(
    827                         talloc_tos(), "Unix Group %s", grp->gr_name);
     839                map->nt_name = talloc_asprintf(map, "Unix Group %s",
     840                                                        grp->gr_name);
    828841
    829842                DEBUG(5, ("%s exists as %s\\%s, retrying as \"%s\"\n",
    830                           grpname, dom, name, tmp));
    831                 grpname = tmp;
    832         }
    833 
    834         if (lookup_name(talloc_tos(), grpname, LOOKUP_NAME_LOCAL,
     843                          grp->gr_name, dom, name, map->nt_name));
     844        }
     845
     846        if (lookup_name(talloc_tos(), grp->gr_name, LOOKUP_NAME_LOCAL,
    835847                        NULL, NULL, NULL, NULL)) {
    836848                DEBUG(3, ("\"%s\" exists, can't map it\n", grp->gr_name));
    837849                return NT_STATUS_GROUP_EXISTS;
    838850        }
    839 
    840         fstrcpy(map.nt_name, grpname);
    841851
    842852        if (pdb_capabilities() & PDB_CAP_STORE_RIDS) {
     
    850860        }
    851861
    852         sid_compose(&map.sid, get_global_sam_sid(), rid);
    853         map.sid_name_use = SID_NAME_DOM_GRP;
    854         fstrcpy(map.comment, talloc_asprintf(talloc_tos(), "Unix Group %s",
    855                                              grp->gr_name));
    856 
    857         status = pdb_add_group_mapping_entry(&map);
    858         if (NT_STATUS_IS_OK(status)) {
    859                 *pmap = map;
    860         }
    861         return status;
     862        sid_compose(&map->sid, get_global_sam_sid(), rid);
     863        map->sid_name_use = SID_NAME_DOM_GRP;
     864        map->comment = talloc_asprintf(map, "Unix Group %s", grp->gr_name);
     865
     866        return pdb_add_group_mapping_entry(map);
    862867}
    863868
     
    865870{
    866871        NTSTATUS status;
    867         GROUP_MAP map;
     872        GROUP_MAP *map;
    868873        struct group *grp;
    869874
     
    881886        }
    882887
    883         status = map_unix_group(grp, &map);
     888        map = talloc_zero(talloc_tos(), GROUP_MAP);
     889        if (!map) {
     890                d_fprintf(stderr, _("Out of memory!\n"));
     891                return -1;
     892        }
     893
     894        status = map_unix_group(grp, map);
    884895
    885896        if (!NT_STATUS_IS_OK(status)) {
     
    890901
    891902        d_printf(_("Mapped unix group %s to SID %s\n"), argv[0],
    892                  sid_string_tos(&map.sid));
    893 
     903                 sid_string_tos(&map->sid));
     904
     905        TALLOC_FREE(map);
    894906        return 0;
    895907}
     
    899911 */
    900912
    901 static NTSTATUS unmap_unix_group(const struct group *grp, GROUP_MAP *pmap)
    902 {
    903         GROUP_MAP map;
    904         const char *grpname;
     913static NTSTATUS unmap_unix_group(const struct group *grp)
     914{
    905915        struct dom_sid dom_sid;
    906 
    907         map.gid = grp->gr_gid;
    908         grpname = grp->gr_name;
    909 
    910         if (!lookup_name(talloc_tos(), grpname, LOOKUP_NAME_LOCAL,
     916        struct unixid id;
     917
     918        if (!lookup_name(talloc_tos(), grp->gr_name, LOOKUP_NAME_LOCAL,
    911919                        NULL, NULL, NULL, NULL)) {
    912920                DEBUG(3, ("\"%s\" does not exist, can't unmap it\n", grp->gr_name));
     
    914922        }
    915923
    916         fstrcpy(map.nt_name, grpname);
    917 
    918         if (!pdb_gid_to_sid(map.gid, &dom_sid)) {
     924        id.id = grp->gr_gid;
     925        id.type = ID_TYPE_GID;
     926        if (!pdb_id_to_sid(&id, &dom_sid)) {
    919927                return NT_STATUS_UNSUCCESSFUL;
    920928        }
     
    926934{
    927935        NTSTATUS status;
    928         GROUP_MAP map;
    929936        struct group *grp;
    930937
     
    943950        }
    944951
    945         status = unmap_unix_group(grp, &map);
     952        status = unmap_unix_group(grp);
    946953
    947954        if (!NT_STATUS_IS_OK(status)) {
     
    964971{
    965972        NTSTATUS status;
    966         uint32 rid;
     973        uint32_t rid;
    967974
    968975        if (argc != 1 || c->display_usage) {
     
    10401047{
    10411048        NTSTATUS status;
    1042         uint32 rid;
     1049        uint32_t rid;
    10431050
    10441051        if (argc != 1 || c->display_usage) {
     
    11181125{
    11191126        NTSTATUS status;
    1120         uint32 rid;
     1127        uint32_t rid;
    11211128        enum lsa_SidType type;
    11221129        fstring groupname;
     
    11531160        }
    11541161
    1155         status = pdb_create_builtin_alias( rid );
     1162        status = pdb_create_builtin(rid);
    11561163
    11571164        if (!NT_STATUS_IS_OK(status)) {
     
    12141221        if ((grouptype == SID_NAME_ALIAS) || (grouptype == SID_NAME_WKN_GRP)) {
    12151222                if ((membertype != SID_NAME_USER) &&
     1223                    (membertype != SID_NAME_ALIAS) &&
    12161224                    (membertype != SID_NAME_DOM_GRP)) {
    1217                         d_fprintf(stderr, _("%s is a local group, only users "
    1218                                   "and domain groups can be added.\n"
    1219                                   "%s is a %s\n"), argv[0], argv[1],
     1225                        d_fprintf(stderr, _("Can't add %s: only users, domain "
     1226                                            "groups and domain local groups "
     1227                                            "can be added. %s is a %s\n"),
     1228                                  argv[0], argv[1],
    12201229                                  sid_type_lookup(membertype));
    12211230                        return -1;
     
    15821591        char *ldap_uri = NULL;
    15831592        char *p;
    1584         struct smbldap_state *ls;
    1585         GROUP_MAP gmap;
     1593        struct smbldap_state *state = NULL;
     1594        GROUP_MAP *gmap = NULL;
    15861595        struct dom_sid gsid;
    15871596        gid_t domusers_gid = -1;
     
    15901599        struct passwd *pwd;
    15911600        bool is_ipa = false;
     1601        char *bind_dn = NULL;
     1602        char *bind_secret = NULL;
     1603        NTSTATUS status;
    15921604
    15931605        if (c->display_usage) {
     
    16441656        }
    16451657
    1646         if (!NT_STATUS_IS_OK(smbldap_init(tc, NULL, ldap_uri, &ls))) {
     1658        if (!fetch_ldap_pw(&bind_dn, &bind_secret)) {
     1659                d_fprintf(stderr, _("Failed to retrieve LDAP password from secrets.tdb\n"));
     1660                goto failed;
     1661        }
     1662
     1663        status = smbldap_init(tc, NULL, ldap_uri, false, bind_dn, bind_secret, &state);
     1664
     1665        memset(bind_secret, '\0', strlen(bind_secret));
     1666        SAFE_FREE(bind_secret);
     1667        SAFE_FREE(bind_dn);
     1668
     1669        if (!NT_STATUS_IS_OK(status)) {
    16471670                d_fprintf(stderr, _("Unable to connect to the LDAP server.\n"));
    16481671                goto failed;
     
    16531676        sid_compose(&gsid, get_global_sam_sid(), DOMAIN_RID_USERS);
    16541677
    1655         if (!pdb_getgrsid(&gmap, gsid)) {
     1678        gmap = talloc_zero(tc, GROUP_MAP);
     1679        if (!gmap) {
     1680                d_printf(_("Out of memory!\n"));
     1681                goto failed;
     1682        }
     1683
     1684        if (!pdb_getgrsid(gmap, gsid)) {
    16561685                LDAPMod **mods = NULL;
    16571686                char *dn;
     
    16771706                uname = talloc_strdup(tc, "domusers");
    16781707                wname = talloc_strdup(tc, "Domain Users");
    1679                 dn = talloc_asprintf(tc, "cn=%s,%s", "domusers", lp_ldap_group_suffix());
     1708                dn = talloc_asprintf(tc, "cn=%s,%s", "domusers",
     1709                                     lp_ldap_group_suffix(talloc_tos()));
    16801710                gidstr = talloc_asprintf(tc, "%u", (unsigned int)domusers_gid);
    16811711                gtype = talloc_asprintf(tc, "%d", SID_NAME_DOM_GRP);
     
    17001730                smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", gtype);
    17011731
    1702                 talloc_autofree_ldapmod(tc, mods);
    1703 
    1704                 rc = smbldap_add(ls, dn, mods);
     1732                smbldap_talloc_autofree_ldapmod(tc, mods);
     1733
     1734                rc = smbldap_add(state, dn, mods);
    17051735
    17061736                if (rc != LDAP_SUCCESS) {
     
    17101740
    17111741                if (is_ipa) {
    1712                         if (!pdb_getgrsid(&gmap, gsid)) {
     1742                        if (!pdb_getgrsid(gmap, gsid)) {
    17131743                                d_fprintf(stderr, _("Failed to read just "
    17141744                                                    "created domain group.\n"));
    17151745                                goto failed;
    17161746                        } else {
    1717                                 domusers_gid = gmap.gid;
     1747                                domusers_gid = gmap->gid;
    17181748                        }
    17191749                }
    17201750        } else {
    1721                 domusers_gid = gmap.gid;
     1751                domusers_gid = gmap->gid;
    17221752                d_printf(_("found!\n"));
    17231753        }
     
    17291759        sid_compose(&gsid, get_global_sam_sid(), DOMAIN_RID_ADMINS);
    17301760
    1731         if (!pdb_getgrsid(&gmap, gsid)) {
     1761        if (!pdb_getgrsid(gmap, gsid)) {
    17321762                LDAPMod **mods = NULL;
    17331763                char *dn;
     
    17531783                uname = talloc_strdup(tc, "domadmins");
    17541784                wname = talloc_strdup(tc, "Domain Admins");
    1755                 dn = talloc_asprintf(tc, "cn=%s,%s", "domadmins", lp_ldap_group_suffix());
     1785                dn = talloc_asprintf(tc, "cn=%s,%s", "domadmins",
     1786                                     lp_ldap_group_suffix(talloc_tos()));
    17561787                gidstr = talloc_asprintf(tc, "%u", (unsigned int)domadmins_gid);
    17571788                gtype = talloc_asprintf(tc, "%d", SID_NAME_DOM_GRP);
     
    17761807                smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", gtype);
    17771808
    1778                 talloc_autofree_ldapmod(tc, mods);
    1779 
    1780                 rc = smbldap_add(ls, dn, mods);
     1809                smbldap_talloc_autofree_ldapmod(tc, mods);
     1810
     1811                rc = smbldap_add(state, dn, mods);
    17811812
    17821813                if (rc != LDAP_SUCCESS) {
     
    17861817
    17871818                if (is_ipa) {
    1788                         if (!pdb_getgrsid(&gmap, gsid)) {
     1819                        if (!pdb_getgrsid(gmap, gsid)) {
    17891820                                d_fprintf(stderr, _("Failed to read just "
    17901821                                                    "created domain group.\n"));
    17911822                                goto failed;
    17921823                        } else {
    1793                                 domadmins_gid = gmap.gid;
     1824                                domadmins_gid = gmap->gid;
    17941825                        }
    17951826                }
    17961827        } else {
    1797                 domadmins_gid = gmap.gid;
     1828                domadmins_gid = gmap->gid;
    17981829                d_printf(_("found!\n"));
    17991830        }
     
    18431874
    18441875                name = talloc_strdup(tc, "Administrator");
    1845                 dn = talloc_asprintf(tc, "uid=Administrator,%s", lp_ldap_user_suffix());
     1876                dn = talloc_asprintf(tc, "uid=Administrator,%s",
     1877                                     lp_ldap_user_suffix(talloc_tos()));
    18461878                uidstr = talloc_asprintf(tc, "%u", (unsigned int)uid);
    18471879                gidstr = talloc_asprintf(tc, "%u", (unsigned int)domadmins_gid);
    18481880                dir = talloc_sub_specified(tc, lp_template_homedir(),
    18491881                                                "Administrator",
     1882                                                NULL,
    18501883                                                get_global_sam_name(),
    18511884                                                uid, domadmins_gid);
    18521885                shell = talloc_sub_specified(tc, lp_template_shell(),
    18531886                                                "Administrator",
     1887                                                NULL,
    18541888                                                get_global_sam_name(),
    18551889                                                uid, domadmins_gid);
     
    18611895
    18621896                sid_compose(&sid, get_global_sam_sid(), DOMAIN_RID_ADMINISTRATOR);
    1863 
    1864                 if (!winbind_allocate_uid(&uid)) {
    1865                         d_fprintf(stderr,
    1866                                   _("Unable to allocate a new uid to create "
    1867                                     "the Administrator user!\n"));
    1868                         goto done;
    1869                 }
    18701897
    18711898                smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_ACCOUNT);
     
    19001927                                NEW_PW_FORMAT_SPACE_PADDED_LEN));
    19011928
    1902                 talloc_autofree_ldapmod(tc, mods);
    1903 
    1904                 rc = smbldap_add(ls, dn, mods);
     1929                smbldap_talloc_autofree_ldapmod(tc, mods);
     1930
     1931                rc = smbldap_add(state, dn, mods);
    19051932
    19061933                if (rc != LDAP_SUCCESS) {
     
    19281955        }
    19291956
    1930         if (!pdb_getsampwnam(samuser, lp_guestaccount())) {
     1957        if (!pdb_getsampwnam(samuser, lp_guest_account())) {
    19311958                LDAPMod **mods = NULL;
    19321959                struct dom_sid sid;
     
    19401967                sid_compose(&sid, get_global_sam_sid(), DOMAIN_RID_GUEST);
    19411968
    1942                 pwd = Get_Pwnam_alloc(tc, lp_guestaccount());
     1969                pwd = Get_Pwnam_alloc(tc, lp_guest_account());
    19431970
    19441971                if (!pwd) {
     
    19531980                                goto done;
    19541981                        }
    1955                         pwd->pw_name = talloc_strdup(pwd, lp_guestaccount());
     1982                        pwd->pw_name = talloc_strdup(pwd, lp_guest_account());
    19561983
    19571984                        if (is_ipa) {
     
    19742001                }
    19752002
    1976                 dn = talloc_asprintf(tc, "uid=%s,%s", pwd->pw_name, lp_ldap_user_suffix ());
     2003                dn = talloc_asprintf(tc, "uid=%s,%s", pwd->pw_name,
     2004                                     lp_ldap_user_suffix (talloc_tos()));
    19772005                uidstr = talloc_asprintf(tc, "%u", (unsigned int)pwd->pw_uid);
    19782006                gidstr = talloc_asprintf(tc, "%u", (unsigned int)pwd->pw_gid);
     
    20112039                                NEW_PW_FORMAT_SPACE_PADDED_LEN));
    20122040
    2013                 talloc_autofree_ldapmod(tc, mods);
    2014 
    2015                 rc = smbldap_add(ls, dn, mods);
     2041                smbldap_talloc_autofree_ldapmod(tc, mods);
     2042
     2043                rc = smbldap_add(state, dn, mods);
    20162044
    20172045                if (rc != LDAP_SUCCESS) {
     
    20212049
    20222050                if (is_ipa) {
    2023                         if (!pdb_getsampwnam(samuser, lp_guestaccount())) {
     2051                        if (!pdb_getsampwnam(samuser, lp_guest_account())) {
    20242052                                d_fprintf(stderr, _("Failed to read just "
    20252053                                                    "created user.\n"));
     
    20332061        d_printf(_("Checking Guest's group.\n"));
    20342062
    2035         pwd = Get_Pwnam_alloc(tc, lp_guestaccount());
     2063        pwd = Get_Pwnam_alloc(tc, lp_guest_account());
    20362064        if (!pwd) {
    20372065                d_fprintf(stderr,
     
    20462074        }
    20472075
    2048         if (!pdb_getgrgid(&gmap, pwd->pw_gid)) {
     2076        if (!pdb_getgrgid(gmap, pwd->pw_gid)) {
    20492077                LDAPMod **mods = NULL;
    20502078                char *dn;
     
    20592087                uname = talloc_strdup(tc, "domguests");
    20602088                wname = talloc_strdup(tc, "Domain Guests");
    2061                 dn = talloc_asprintf(tc, "cn=%s,%s", "domguests", lp_ldap_group_suffix());
     2089                dn = talloc_asprintf(tc, "cn=%s,%s", "domguests",
     2090                                     lp_ldap_group_suffix(talloc_tos()));
    20622091                gidstr = talloc_asprintf(tc, "%u", (unsigned int)pwd->pw_gid);
    20632092                gtype = talloc_asprintf(tc, "%d", SID_NAME_DOM_GRP);
     
    20842113                smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", gtype);
    20852114
    2086                 talloc_autofree_ldapmod(tc, mods);
    2087 
    2088                 rc = smbldap_add(ls, dn, mods);
     2115                smbldap_talloc_autofree_ldapmod(tc, mods);
     2116
     2117                rc = smbldap_add(state, dn, mods);
    20892118
    20902119                if (rc != LDAP_SUCCESS) {
     
    20992128
    21002129done:
    2101         talloc_free(tc);
     2130        talloc_free(state);
    21022131        return 0;
    21032132
    21042133failed:
    2105         talloc_free(tc);
     2134        talloc_free(state);
    21062135        return -1;
    21072136}
  • vendor/current/source3/utils/net_serverid.c

    r860 r988  
    2020#include "includes.h"
    2121#include "utils/net.h"
    22 #include "dbwrap.h"
     22#include "dbwrap/dbwrap.h"
     23#include "dbwrap/dbwrap_rbt.h"
    2324#include "serverid.h"
    2425#include "session.h"
     26#include "lib/conn_tdb.h"
     27#include "smbd/globals.h"
     28#include "util_tdb.h"
     29#include "librpc/gen_ndr/ndr_open_files.h"
    2530
    2631static int net_serverid_list_fn(const struct server_id *id,
    2732                                uint32_t msg_flags, void *priv)
    2833{
    29         char *str = procid_str(talloc_tos(), id);
    30         d_printf("%s %llu 0x%x\n", str, (unsigned long long)id->unique_id,
     34        struct server_id_buf idbuf;
     35        d_printf("%s %llu 0x%x\n", server_id_str_buf(*id, &idbuf),
     36                 (unsigned long long)id->unique_id,
    3137                 (unsigned int)msg_flags);
    32         TALLOC_FREE(str);
    3338        return 0;
    3439}
     
    3742                             const char **argv)
    3843{
    39         if (!serverid_init_readonly(c)) {
    40                 d_printf("failed to open serverid.tdb\n");
    41                 return -1;
    42         }
    4344        d_printf("pid unique_id msg_flags\n");
    4445        return serverid_traverse_read(net_serverid_list_fn, NULL) ? 0 : -1;
     
    5152        NTSTATUS status;
    5253
    53         if (id->vnn != get_my_vnn()) {
     54        if (!procid_is_local(id)) {
    5455                return 0;
    5556        }
    56         status = rec->delete_rec(rec);
    57         if (!NT_STATUS_IS_OK(status)) {
    58                 char *str = procid_str(talloc_tos(), id);
     57        status = dbwrap_record_delete(rec);
     58        if (!NT_STATUS_IS_OK(status)) {
     59                struct server_id_buf idbuf;
    5960                DEBUG(1, ("Could not delete serverid.tdb record %s: %s\n",
    60                           str, nt_errstr(status)));
    61                 TALLOC_FREE(str);
     61                          server_id_str_buf(*id, &idbuf), nt_errstr(status)));
    6262        }
    6363        return 0;
     
    7070}
    7171
    72 static int net_serverid_wipedbs_conn(
    73         struct db_record *rec,
    74         const struct connections_key *key,
    75         const struct connections_data *data,
    76         void *private_data)
    77 {
    78         if (!serverid_exists(&key->pid)) {
    79                 NTSTATUS status;
    80 
    81                 DEBUG(10, ("Deleting connections.tdb record for pid %s\n",
    82                            procid_str(talloc_tos(), &key->pid)));
    83 
    84                 status = rec->delete_rec(rec);
     72
     73struct wipedbs_record_marker {
     74        struct wipedbs_record_marker *prev, *next;
     75        TDB_DATA key, val;
     76        const char *desc;
     77};
     78
     79struct wipedbs_server_data {
     80        struct server_id server_id;
     81        const char *server_id_str;
     82        bool exists;
     83        struct wipedbs_record_marker *session_records;
     84        struct wipedbs_record_marker *tcon_records;
     85        struct wipedbs_record_marker *open_records;
     86};
     87
     88struct wipedbs_state {
     89        struct db_context *id2server_data;
     90        struct {
     91                struct {
     92                        int total;
     93                        int existing;
     94                        int disconnected;
     95                } server;
     96                struct {
     97                        int total;
     98                        int disconnected;
     99                        int todelete;
     100                        int failure;
     101                } session, tcon, open;
     102                int open_timed_out;
     103        } stat;
     104        struct server_id *server_ids;
     105        bool *server_exists;
     106        int idx;
     107        struct db_context *session_db;
     108        struct db_context *tcon_db;
     109        struct db_context *open_db;
     110        struct timeval now;
     111        bool testmode;
     112        bool verbose;
     113};
     114
     115static struct wipedbs_server_data *get_server_data(struct wipedbs_state *state,
     116                                                   const struct server_id *id)
     117{
     118        struct wipedbs_server_data *ret = NULL;
     119        TDB_DATA key, val = tdb_null;
     120        NTSTATUS status;
     121
     122        key = make_tdb_data((const void*)&id->unique_id, sizeof(id->unique_id));
     123        status = dbwrap_fetch(state->id2server_data, talloc_tos(), key, &val);
     124        if (NT_STATUS_IS_OK(status)) {
     125                ret = *(struct wipedbs_server_data**) val.dptr;
     126                TALLOC_FREE(val.dptr);
     127        } else if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
     128                struct server_id_buf idbuf;
     129
     130                server_id_str_buf(*id, &idbuf);
     131
     132                ret = talloc_zero(state->id2server_data,
     133                                  struct wipedbs_server_data);
     134                if (ret == NULL) {
     135                        DEBUG(0, ("Failed to allocate server entry for %s\n",
     136                                  idbuf.buf));
     137                        goto done;
     138                }
     139                ret->server_id = *id;
     140                ret->server_id_str = talloc_strdup(ret, idbuf.buf);
     141                ret->exists = true;
     142                val = make_tdb_data((const void*)&ret, sizeof(ret));
     143                status = dbwrap_store(state->id2server_data,
     144                                      key, val, TDB_INSERT);
    85145                if (!NT_STATUS_IS_OK(status)) {
    86                         DEBUG(1, ("Could not delete connections.tdb record "
    87                                   "for pid %s: %s\n",
    88                                   procid_str(talloc_tos(), &key->pid),
    89                                   nt_errstr(status)));
     146                        DEBUG(0, ("Failed to store server entry for %s: %s\n",
     147                                  idbuf.buf, nt_errstr(status)));
    90148                }
    91         }
     149                goto done;
     150        } else {
     151                struct server_id_buf idbuf;
     152                DEBUG(0, ("Failed to fetch server entry for %s: %s\n",
     153                          server_id_str_buf(*id, &idbuf), nt_errstr(status)));
     154                goto done;
     155        }
     156        if (!server_id_equal(id, &ret->server_id)) {
     157                struct server_id_buf idbuf1, idbuf2;
     158                DEBUG(0, ("uniq id collision for %s and %s\n",
     159                          server_id_str_buf(*id, &idbuf1),
     160                          server_id_str_buf(ret->server_id, &idbuf2)));
     161                smb_panic("server_id->unique_id not unique!");
     162        }
     163done:
     164        return ret;
     165}
     166
     167static int wipedbs_traverse_sessions(struct smbXsrv_session_global0 *session,
     168                                     void *wipedbs_state)
     169{
     170        struct wipedbs_state *state =
     171                talloc_get_type_abort(wipedbs_state,
     172                struct wipedbs_state);
     173        struct wipedbs_server_data *sd;
     174        struct wipedbs_record_marker *rec;
     175        TDB_DATA tmp;
     176        int ret = -1;
     177
     178        assert(session->num_channels == 1);
     179
     180        state->stat.session.total++;
     181
     182        sd = get_server_data(state, &session->channels[0].server_id);
     183        if (sd == NULL) {
     184                goto done;
     185        }
     186
     187        if (server_id_is_disconnected(&sd->server_id)) {
     188                state->stat.session.disconnected++;
     189        }
     190
     191        rec = talloc_zero(sd, struct wipedbs_record_marker);
     192        if (rec == NULL) {
     193                DEBUG(0, ("Out of memory!\n"));
     194                goto done;
     195        }
     196
     197        tmp = dbwrap_record_get_key(session->db_rec);
     198        rec->key = tdb_data_talloc_copy(rec, tmp);
     199        tmp = dbwrap_record_get_value(session->db_rec);
     200        rec->val = tdb_data_talloc_copy(rec, tmp);
     201
     202        rec->desc = talloc_asprintf(
     203                rec, "session[global: %u wire: %llu]",
     204                session->session_global_id,
     205                (long long unsigned)session->session_wire_id);
     206
     207        if ((rec->key.dptr == NULL) || (rec->val.dptr == NULL) ||
     208            (rec->desc == NULL))
     209        {
     210                DEBUG(0, ("Out of memory!\n"));
     211                goto done;
     212        }
     213
     214        state->session_db = dbwrap_record_get_db(session->db_rec);
     215
     216        DLIST_ADD(sd->session_records, rec);
     217        ret = 0;
     218done:
     219        return ret;
     220}
     221
     222static int wipedbs_traverse_tcon(struct smbXsrv_tcon_global0 *tcon,
     223                                 void *wipedbs_state)
     224{
     225        struct wipedbs_state *state =
     226                talloc_get_type_abort(wipedbs_state,
     227                struct wipedbs_state);
     228        struct wipedbs_server_data *sd;
     229        struct wipedbs_record_marker *rec;
     230        TDB_DATA tmp;
     231        int ret = -1;
     232
     233        state->stat.tcon.total++;
     234
     235        sd = get_server_data(state, &tcon->server_id);
     236        if (sd == NULL) {
     237                goto done;
     238        }
     239
     240        if (server_id_is_disconnected(&sd->server_id)) {
     241                state->stat.tcon.disconnected++;
     242        }
     243
     244        rec = talloc_zero(sd, struct wipedbs_record_marker);
     245        if (rec == NULL) {
     246                DEBUG(0, ("Out of memory!\n"));
     247                goto done;
     248        }
     249
     250        tmp = dbwrap_record_get_key(tcon->db_rec);
     251        rec->key = tdb_data_talloc_copy(rec, tmp);
     252        tmp = dbwrap_record_get_value(tcon->db_rec);
     253        rec->val = tdb_data_talloc_copy(rec, tmp);
     254
     255        rec->desc = talloc_asprintf(
     256                rec, "tcon[global: %u wire: %u session: %u share: %s]",
     257                tcon->tcon_global_id, tcon->tcon_wire_id,
     258                tcon->session_global_id, tcon->share_name);
     259
     260        if ((rec->key.dptr == NULL) || (rec->val.dptr == NULL) ||
     261            (rec->desc == NULL))
     262        {
     263                DEBUG(0, ("Out of memory!\n"));
     264                goto done;
     265        }
     266
     267        state->tcon_db = dbwrap_record_get_db(tcon->db_rec);
     268
     269        DLIST_ADD(sd->tcon_records, rec);
     270        ret = 0;
     271
     272done:
     273        return ret;
     274}
     275
     276static int wipedbs_traverse_open(struct smbXsrv_open_global0 *open,
     277                                 void *wipedbs_state)
     278{
     279        struct wipedbs_state *state =
     280                talloc_get_type_abort(wipedbs_state,
     281                struct wipedbs_state);
     282        struct wipedbs_server_data *sd;
     283        struct wipedbs_record_marker *rec;
     284        TDB_DATA tmp;
     285        int ret = -1;
     286
     287        state->stat.open.total++;
     288
     289        sd = get_server_data(state, &open->server_id);
     290        if (sd == NULL) {
     291                goto done;
     292        }
     293
     294        if (server_id_is_disconnected(&sd->server_id)) {
     295                struct timeval disconnect_time;
     296                int64_t tdiff;
     297                bool reached;
     298
     299                state->stat.open.disconnected++;
     300
     301                nttime_to_timeval(&disconnect_time, open->disconnect_time);
     302                tdiff = usec_time_diff(&state->now, &disconnect_time);
     303                reached = (tdiff >= 1000*open->durable_timeout_msec);
     304
     305                if (state->verbose) {
     306                        TALLOC_CTX *mem_ctx = talloc_new(talloc_tos());
     307                        enum ndr_err_code ndr_err;
     308                        struct vfs_default_durable_cookie cookie;
     309
     310                        ndr_err = ndr_pull_struct_blob(
     311                                &open->backend_cookie, mem_ctx, &cookie,
     312                                (ndr_pull_flags_fn_t)ndr_pull_vfs_default_durable_cookie);
     313                        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
     314                                d_printf("ndr_pull_struct_blob failed\n");
     315                                ret = -1;
     316                                goto done;
     317                        }
     318
     319                        d_printf("open[%s/%s id: 0x%" PRIx32 "] disconnected at "
     320                                 "[%s] %us ago with timeout of %us "
     321                                 "-%s reached\n",
     322                                 cookie.servicepath, cookie.base_name,
     323                                 open->open_global_id,
     324                                 nt_time_string(mem_ctx, open->disconnect_time),
     325                                 (unsigned)(tdiff/1000000),
     326                                 open->durable_timeout_msec / 1000,
     327                                 reached ? "" : " not");
     328                        talloc_free(mem_ctx);
     329                }
     330
     331                if (!reached) {
     332                        ret = 0;
     333                        goto done;
     334                }
     335                state->stat.open_timed_out++;
     336        }
     337
     338        rec = talloc_zero(sd, struct wipedbs_record_marker);
     339        if (rec == NULL) {
     340                DEBUG(0, ("Out of memory!\n"));
     341                goto done;
     342        }
     343
     344        tmp = dbwrap_record_get_key(open->db_rec);
     345        rec->key = tdb_data_talloc_copy(rec, tmp);
     346        tmp = dbwrap_record_get_value(open->db_rec);
     347        rec->val = tdb_data_talloc_copy(rec, tmp);
     348
     349        rec->desc = talloc_asprintf(
     350                rec, "open[global: %u persistent: %llu volatile: %llu]",
     351                open->open_global_id,
     352                (long long unsigned)open->open_persistent_id,
     353                (long long unsigned)open->open_volatile_id);
     354
     355        if ((rec->key.dptr == NULL) || (rec->val.dptr == NULL) ||
     356            (rec->desc == NULL))
     357        {
     358                DEBUG(0, ("Out of memory!\n"));
     359                goto done;
     360        }
     361
     362        state->open_db = dbwrap_record_get_db(open->db_rec);
     363
     364        DLIST_ADD(sd->open_records, rec);
     365        ret = 0;
     366
     367done:
     368        return ret;
     369}
     370
     371static int wipedbs_traverse_nop(struct db_record *rec, void *private_data)
     372{
    92373        return 0;
    93374}
    94375
    95 static int net_serverid_wipedbs_sessionid(struct db_record *rec,
    96                                           const char *key,
    97                                           struct sessionid *session,
    98                                           void *private_data)
    99 {
    100         if (!serverid_exists(&session->pid)) {
    101                 NTSTATUS status;
    102 
    103                 DEBUG(10, ("Deleting sessionid.tdb record for pid %s\n",
    104                            procid_str(talloc_tos(), &session->pid)));
    105 
    106                 status = rec->delete_rec(rec);
    107                 if (!NT_STATUS_IS_OK(status)) {
    108                         DEBUG(1, ("Could not delete session.tdb record "
    109                                   "for pid %s: %s\n",
    110                                   procid_str(talloc_tos(), &session->pid),
    111                                   nt_errstr(status)));
     376static int wipedbs_traverse_fill_ids(struct db_record *rec, void *wipedbs_state)
     377{
     378        struct wipedbs_state *state = talloc_get_type_abort(
     379                wipedbs_state, struct wipedbs_state);
     380
     381        TDB_DATA val = dbwrap_record_get_value(rec);
     382
     383        struct wipedbs_server_data *sd = talloc_get_type_abort(
     384                *(void**)val.dptr, struct wipedbs_server_data);
     385
     386        state->server_ids[state->idx] = sd->server_id;
     387        state->idx++;
     388        return 0;
     389}
     390
     391static int wipedbs_traverse_set_exists(struct db_record *rec,
     392                                       void *wipedbs_state)
     393{
     394        struct wipedbs_state *state = talloc_get_type_abort(
     395                wipedbs_state, struct wipedbs_state);
     396
     397        TDB_DATA val = dbwrap_record_get_value(rec);
     398
     399        struct wipedbs_server_data *sd = talloc_get_type_abort(
     400                *(void**)val.dptr, struct wipedbs_server_data);
     401
     402        /* assume a stable traverse order for rbt */
     403        SMB_ASSERT(server_id_equal(&state->server_ids[state->idx],
     404                                   &sd->server_id));
     405        sd->exists = state->server_exists[state->idx];
     406
     407        if (sd->exists) {
     408                state->stat.server.existing++;
     409        }
     410        if (server_id_is_disconnected(&sd->server_id)) {
     411                state->stat.server.disconnected++;
     412        }
     413
     414        state->idx++;
     415        return 0;
     416}
     417
     418static bool serverids_exist(const struct server_id *ids, int num_ids,
     419                            bool *results)
     420{
     421        int i;
     422
     423        for (i=0; i<num_ids; i++) {
     424                results[i] = serverid_exists(&ids[i]);
     425        }
     426
     427        return true;
     428}
     429
     430
     431static NTSTATUS wipedbs_check_server_exists(struct wipedbs_state *state)
     432{
     433        NTSTATUS status;
     434        bool ok;
     435        int num_servers;
     436
     437        status = dbwrap_traverse_read(state->id2server_data,
     438                                      wipedbs_traverse_nop, NULL, &num_servers);
     439        if (!NT_STATUS_IS_OK(status)) {
     440                DEBUG(0, ("Failed to traverse temporary database\n"));
     441                goto done;
     442        }
     443        state->stat.server.total = num_servers;
     444
     445        state->server_ids = talloc_array(state, struct server_id, num_servers);
     446        state->server_exists = talloc_array(state, bool, num_servers);
     447        if (state->server_ids == NULL || state->server_exists == NULL) {
     448                DEBUG(0, ("Out of memory\n"));
     449                goto done;
     450        }
     451
     452        state->idx = 0;
     453        status = dbwrap_traverse_read(state->id2server_data,
     454                                      wipedbs_traverse_fill_ids,
     455                                      state, NULL);
     456        if (!NT_STATUS_IS_OK(status)) {
     457                DEBUG(0, ("Failed to traverse temporary database\n"));
     458                goto done;
     459        }
     460
     461        ok = serverids_exist(state->server_ids, num_servers, state->server_exists);
     462        if (!ok) {
     463                DEBUG(0, ("Calling serverids_exist failed\n"));
     464                status = NT_STATUS_UNSUCCESSFUL;
     465                goto done;
     466        }
     467
     468        state->idx = 0;
     469        status = dbwrap_traverse_read(state->id2server_data,
     470                                      wipedbs_traverse_set_exists, state, NULL);
     471        if (!NT_STATUS_IS_OK(status)) {
     472                DEBUG(0, ("Failed to traverse temporary database\n"));
     473                goto done;
     474        }
     475done:
     476        TALLOC_FREE(state->server_ids);
     477        TALLOC_FREE(state->server_exists);
     478        return status;
     479}
     480
     481static int wipedbs_delete_records(struct db_context *db,
     482                                  struct wipedbs_record_marker *records,
     483                                  bool dry_run, bool verbose, int *count)
     484{
     485        struct wipedbs_record_marker *cur;
     486        struct db_record *rec;
     487        TDB_DATA val;
     488        NTSTATUS status;
     489        unsigned num=0, total=0;
     490
     491        if (db == NULL) {
     492                return 0;
     493        }
     494
     495        for (cur = records; cur != NULL; cur = cur->next) {
     496                total++;
     497                rec = dbwrap_fetch_locked(db, talloc_tos(), cur->key);
     498                if (rec == NULL) {
     499                        DEBUG(0, ("Failed to fetch record <%s> from %s",
     500                                  cur->desc, dbwrap_name(db)));
     501                        continue;
    112502                }
    113         }
     503                val = dbwrap_record_get_value(rec);
     504                if (tdb_data_equal(val, cur->val)) {
     505                        if (dry_run) {
     506                                status = NT_STATUS_OK;
     507                        } else {
     508                                status = dbwrap_record_delete(rec);
     509                        }
     510                        if (NT_STATUS_IS_OK(status)) {
     511                                num ++;
     512                        } else {
     513                                DEBUG(0, ("Failed to delete record <%s> from %s"
     514                                          ": %s\n", cur->desc, dbwrap_name(db),
     515                                          nt_errstr(status)));
     516                        }
     517                } else {
     518                        DEBUG(0, ("Warning: record <%s> from %s changed"
     519                                  ", skip record!\n",
     520                                  cur->desc, dbwrap_name(db)));
     521                }
     522                if (verbose) {
     523                        d_printf("deleting %s\n", cur->desc);
     524                }
     525                TALLOC_FREE(rec);
     526        }
     527
     528        if (verbose) {
     529                d_printf("Deleted %u of %u records from %s\n",
     530                         num, total, dbwrap_name(db));
     531        }
     532
     533        if (count) {
     534                *count += total;
     535        }
     536
     537        return total - num;
     538}
     539
     540static int wipedbs_traverse_server_data(struct db_record *rec,
     541                                        void *wipedbs_state)
     542{
     543        struct wipedbs_state *state = talloc_get_type_abort(
     544                wipedbs_state, struct wipedbs_state);
     545        bool dry_run = state->testmode;
     546        TDB_DATA val = dbwrap_record_get_value(rec);
     547        int ret;
     548        struct wipedbs_server_data *sd = talloc_get_type_abort(
     549                *(void**)val.dptr, struct wipedbs_server_data);
     550
     551        if (state->verbose) {
     552                d_printf("Server: '%s' %s\n", sd->server_id_str,
     553                         sd->exists ?
     554                         "exists" :
     555                         "does not exist, cleaning up...");
     556        }
     557
     558        if (sd->exists) {
     559                return 0;
     560        }
     561
     562        ret = wipedbs_delete_records(state->session_db, sd->session_records,
     563                                     dry_run, state->verbose,
     564                                     &state->stat.session.todelete);
     565        state->stat.session.failure += ret;
     566
     567        ret = wipedbs_delete_records(state->tcon_db, sd->tcon_records,
     568                                     dry_run, state->verbose,
     569                                     &state->stat.tcon.todelete);
     570        state->stat.tcon.failure += ret;
     571
     572        ret = wipedbs_delete_records(state->open_db, sd->open_records,
     573                                     dry_run, state->verbose,
     574                                     &state->stat.open.todelete);
     575        state->stat.open.failure += ret;
     576
    114577        return 0;
    115578}
     
    118581                                const char **argv)
    119582{
    120         if (!sessionid_init()) {
    121                 d_printf("failed to open sessionid.tdb\n");
     583        int ret = -1;
     584        NTSTATUS status;
     585        struct wipedbs_state *state = talloc_zero(talloc_tos(),
     586                                                  struct wipedbs_state);
     587
     588        if (c->display_usage) {
     589                d_printf("%s\n%s",
     590                         _("Usage:"),
     591                         _("net serverid wipedbs [--test] [--verbose]\n"));
     592                d_printf("%s\n%s",
     593                         _("Example:"),
     594                         _("net serverid wipedbs -v\n"));
    122595                return -1;
    123         };
    124 
    125         connections_forall(net_serverid_wipedbs_conn, NULL);
    126         sessionid_traverse(net_serverid_wipedbs_sessionid, NULL);
     596        }
     597
     598        state->now = timeval_current();
     599        state->testmode = c->opt_testmode;
     600        state->verbose = c->opt_verbose;
     601
     602        state->id2server_data = db_open_rbt(state);
     603        if (state->id2server_data == NULL) {
     604                DEBUG(0, ("Failed to open temporary database\n"));
     605                goto done;
     606        }
     607
     608        status = smbXsrv_session_global_traverse(wipedbs_traverse_sessions,
     609                                                 state);
     610        if (!NT_STATUS_IS_OK(status)) {
     611                goto done;
     612        }
     613
     614        status = smbXsrv_tcon_global_traverse(wipedbs_traverse_tcon, state);
     615        if (!NT_STATUS_IS_OK(status)) {
     616                goto done;
     617        }
     618
     619        status = smbXsrv_open_global_traverse(wipedbs_traverse_open, state);
     620        if (!NT_STATUS_IS_OK(status)) {
     621                goto done;
     622        }
     623
     624        status = wipedbs_check_server_exists(state);
     625        if (!NT_STATUS_IS_OK(status)) {
     626                goto done;
     627        }
     628
     629        status = dbwrap_traverse_read(state->id2server_data,
     630                                      wipedbs_traverse_server_data,
     631                                      state, NULL);
     632        if (!NT_STATUS_IS_OK(status)) {
     633                DEBUG(0, ("Failed to traverse db: %s\n", nt_errstr(status)));
     634                goto done;
     635        }
     636
     637        d_printf("Found %d serverids, %d alive and %d disconnected\n",
     638                 state->stat.server.total,
     639                 state->stat.server.existing,
     640                 state->stat.server.disconnected);
     641        d_printf("Found %d sessions, %d alive and %d disconnected"
     642                 ", cleaned up %d of %d entries\n",
     643                 state->stat.session.total,
     644                 state->stat.session.total - state->stat.session.todelete,
     645                 state->stat.session.disconnected,
     646                 state->stat.session.todelete - state->stat.session.failure,
     647                 state->stat.session.todelete);
     648        d_printf("Found %d tcons, %d alive and %d disconnected"
     649                 ", cleaned up %d of %d entries\n",
     650                 state->stat.tcon.total,
     651                 state->stat.tcon.total - state->stat.tcon.todelete,
     652                 state->stat.tcon.disconnected,
     653                 state->stat.tcon.todelete - state->stat.tcon.failure,
     654                 state->stat.tcon.todelete);
     655        d_printf("Found %d opens, %d alive, %d disconnected and %d timed out"
     656                 ", cleaned up %d of %d entries\n",
     657                 state->stat.open.total,
     658                 state->stat.open.total - state->stat.open.todelete
     659                 - (state->stat.open.disconnected - state->stat.open_timed_out),
     660                 state->stat.open.disconnected,
     661                 state->stat.open_timed_out,
     662                 state->stat.open.todelete - state->stat.open.failure,
     663                 state->stat.open.todelete);
     664
     665        ret = 0;
     666done:
     667        talloc_free(state);
     668        return ret;
     669}
     670
     671static int net_serverid_exists(struct net_context *c, int argc,
     672                               const char **argv)
     673{
     674        struct server_id pid;
     675        bool ok;
     676
     677        if ((argc != 1) || (c->display_usage)) {
     678                d_printf("Usage:\n"
     679                         "net serverid exists <serverid>\n");
     680                return -1;
     681        }
     682
     683        pid = server_id_from_string(get_my_vnn(), argv[0]);
     684        ok = serverid_exists(&pid);
     685
     686        if (ok) {
     687                d_printf("%s exists\n", argv[0]);
     688        } else {
     689                d_printf("%s does not exist\n", argv[0]);
     690        }
     691
    127692        return 0;
    128693}
     
    151716                        net_serverid_wipedbs,
    152717                        NET_TRANSPORT_LOCAL,
    153                         N_("Clean dead entries from connections.tdb and "
    154                            "sessionid.tdb"),
     718                        N_("Clean dead entries from temporary databases"),
    155719                        N_("net serverid wipedbs\n"
    156                            "    Clean dead entries from connections.tdb and "
    157                            "sessionid.tdb")
     720                           "    Clean dead entries from temporary databases")
     721                },
     722                {
     723                        "exists",
     724                        net_serverid_exists,
     725                        NET_TRANSPORT_LOCAL,
     726                        N_("Show existence of a serverid"),
     727                        N_("net serverid exists <id>")
    158728                },
    159729                {NULL, NULL, 0, NULL, NULL}
  • vendor/current/source3/utils/net_share.c

    r740 r988  
    6363int net_share(struct net_context *c, int argc, const char **argv)
    6464{
    65         if (argc > 0 && StrCaseCmp(argv[0], "HELP") == 0) {
     65        if (argc > 0 && strcasecmp_m(argv[0], "HELP") == 0) {
    6666                        net_share_usage(c, argc, argv);
    6767                        return 0;
  • vendor/current/source3/utils/net_status.c

    r860 r988  
    2121#include "session.h"
    2222#include "messages.h"
     23#include "lib/conn_tdb.h"
    2324
    2425int net_status_usage(struct net_context *c, int argc, const char **argv)
     
    3435                        void *private_data)
    3536{
     37        struct server_id_buf tmp;
    3638        bool *parseable = (bool *)private_data;
    3739
     
    4244        if (*parseable) {
    4345                d_printf("%s\\%s\\%s\\%s\\%s\n",
    44                          procid_str_static(&session->pid),
     46                         server_id_str_buf(session->pid, &tmp),
    4547                         uidtoname(session->uid),
    4648                         gidtoname(session->gid),
     
    4850        } else {
    4951                d_printf("%7s   %-12s  %-12s  %-12s (%s)\n",
    50                          procid_str_static(&session->pid),
     52                         server_id_str_buf(session->pid, &tmp),
    5153                         uidtoname(session->uid),
    5254                         gidtoname(session->gid),
     
    9193}
    9294
    93 static int show_share(struct db_record *rec,
    94                       const struct connections_key *key,
     95static int show_share(const struct connections_key *key,
    9596                      const struct connections_data *crec,
    9697                      void *state)
    9798{
    98         if (crec->cnum == -1)
     99        struct server_id_buf tmp;
     100
     101        if (crec->cnum == TID_FIELD_INVALID)
    99102                return 0;
    100103
     
    104107
    105108        d_printf("%-10.10s   %s   %-12s  %s",
    106                crec->servicename, procid_str_static(&crec->pid),
     109               crec->servicename, server_id_str_buf(crec->pid, &tmp),
    107110               crec->machine,
    108111               time_to_asc(crec->start));
     
    140143{
    141144        struct sessionids *ids = (struct sessionids *)state;
     145        struct server_id_buf tmp;
    142146        int i;
    143147        bool guest = true;
    144148
    145         if (crec->cnum == -1)
     149        if (crec->cnum == TID_FIELD_INVALID)
    146150                return 0;
    147151
     
    152156        for (i=0; i<ids->num_entries; i++) {
    153157                struct server_id id = ids->entries[i].pid;
    154                 if (procid_equal(&id, &crec->pid)) {
     158                if (serverid_equal(&id, &crec->pid)) {
    155159                        guest = false;
    156160                        break;
     
    159163
    160164        d_printf("%s\\%s\\%s\\%s\\%s\\%s\\%s",
    161                  crec->servicename,procid_str_static(&crec->pid),
     165                 crec->servicename, server_id_str_buf(crec->pid, &tmp),
    162166                 guest ? "" : uidtoname(ids->entries[i].uid),
    163167                 guest ? "" : gidtoname(ids->entries[i].gid),
     
    205209                           "------------------\n"));
    206210
    207                 connections_forall(show_share, NULL);
     211                connections_forall_read(show_share, NULL);
    208212
    209213                return 0;
     
    240244                {NULL, NULL, 0, NULL, NULL}
    241245        };
    242 
    243         if (!sessionid_init_readonly()) {
    244                 d_printf("failed to open sessionid.tdb\n");
    245                 return -1;
    246         }
    247 
    248246        return net_run_function(c, argc, argv, "net status", func);
    249247}
  • vendor/current/source3/utils/net_time.c

    r740 r988  
    2121#include "libsmb/nmblib.h"
    2222#include "libsmb/libsmb.h"
     23#include "../libcli/smb/smbXcli_base.h"
    2324
    2425/*
    2526  return the time on a server. This does not require any authentication
    2627*/
    27 static time_t cli_servertime(const char *host, struct sockaddr_storage *pss, int *zone)
    28 {
    29         struct nmb_name calling, called;
     28static time_t cli_servertime(const char *host,
     29                             const struct sockaddr_storage *dest_ss,
     30                             int *zone)
     31{
    3032        time_t ret = 0;
    3133        struct cli_state *cli = NULL;
    3234        NTSTATUS status;
    3335
    34         cli = cli_initialise();
    35         if (!cli) {
    36                 goto done;
    37         }
    38 
    39         status = cli_connect(cli, host, pss);
     36        status = cli_connect_nb(host, dest_ss, 0, 0x20, lp_netbios_name(),
     37                                SMB_SIGNING_DEFAULT, 0, &cli);
    4038        if (!NT_STATUS_IS_OK(status)) {
    4139                fprintf(stderr, _("Can't contact server %s. Error %s\n"),
     
    4442        }
    4543
    46         make_nmb_name(&calling, global_myname(), 0x0);
    47         if (host) {
    48                 make_nmb_name(&called, host, 0x20);
    49         } else {
    50                 make_nmb_name(&called, "*SMBSERVER", 0x20);
    51         }
    52 
    53         if (!cli_session_request(cli, &calling, &called)) {
    54                 fprintf(stderr, _("Session request failed\n"));
    55                 goto done;
    56         }
    57         status = cli_negprot(cli);
     44        status = smbXcli_negprot(cli->conn, cli->timeout, PROTOCOL_CORE,
     45                                 PROTOCOL_NT1);
    5846        if (!NT_STATUS_IS_OK(status)) {
    5947                fprintf(stderr, _("Protocol negotiation failed: %s\n"),
     
    6250        }
    6351
    64         ret = cli->servertime;
    65         if (zone) *zone = cli->serverzone;
     52        ret = cli_state_server_time(cli);
     53        if (zone) *zone = smb1cli_conn_server_time_zone(cli->conn);
    6654
    6755done:
     
    9785{
    9886        d_printf(_(
    99 "net time\n\tdisplays time on a server\n\n"
    100 "net time system\n\tdisplays time on a server in a format ready for /bin/date\n\n"
    101 "net time set\n\truns /bin/date with the time from the server\n\n"
    102 "net time zone\n\tdisplays the timezone in hours from GMT on the remote computer\n\n"
     87"net time\n\tdisplays time on a server (-S server)\n\n"
     88"net time system\n\tdisplays time on a server (-S server) in a format ready for /bin/date\n\n"
     89"net time set\n\truns /bin/date with the time from the server (-S server)\n\n"
     90"net time zone\n\tdisplays the timezone in hours from GMT on the remote server (-S server)\n\n"
    10391"\n"));
    10492        net_common_flags_usage(c, argc, argv);
     
    112100        int result;
    113101
     102        if (c->display_usage || c->opt_host == NULL) {
     103                d_printf(  "%s\n"
     104                           "net time set\n"
     105                           "    %s\n",
     106                         _("Usage:"),
     107                         _("Set local time to that of remote time "
     108                                "server (-S server) "));
     109                return 0;
     110        }
     111
    114112        tv.tv_sec = nettime(c, NULL);
    115113        tv.tv_usec=0;
     
    131129        time_t t;
    132130
    133         if (c->display_usage) {
     131        if (c->display_usage || c->opt_host == NULL) {
    134132                d_printf(  "%s\n"
    135133                           "net time system\n"
    136134                           "    %s\n",
    137135                         _("Usage:"),
    138                          _("Output remote time server time in a format "
    139                            "ready for /bin/date"));
     136                         _("Output remote time server (-S server) "
     137                                "time in a format ready for /bin/date"));
    140138                return 0;
    141139        }
     
    157155        time_t t;
    158156
    159         if (c->display_usage) {
     157        if (c->display_usage || c->opt_host == NULL) {
    160158                d_printf(  "%s\n"
    161159                           "net time zone\n"
    162160                           "   %s\n",
    163161                         _("Usage:"),
    164                          _("Display the remote time server's offset to "
    165                            "UTC"));
     162                         _("Display the remote time server's (-S server) "
     163                                "offset to UTC"));
    166164                return 0;
    167165        }
     
    229227        }
    230228
    231         if (!c->opt_host && !c->opt_have_ip &&
    232             !find_master_ip(c->opt_target_workgroup, &c->opt_dest_ip)) {
    233                 d_fprintf(stderr, _("Could not locate a time server.  Try "
    234                                     "specifying a target host.\n"));
    235                 net_time_usage(c, argc,argv);
    236                 return -1;
     229        if (c->opt_host == NULL && !c->opt_have_ip) {
     230                bool ok;
     231
     232                ok = find_master_ip(c->opt_target_workgroup, &c->opt_dest_ip);
     233                if (!ok) {
     234                        d_fprintf(stderr,
     235                                  _("Could not locate a time server.  "
     236                                    "Try specifying a target host.\n"));
     237                        net_time_usage(c, argc, argv);
     238                        return -1;
     239                }
     240                c->opt_have_ip = true;
    237241        }
    238242
    239243        /* default - print the time */
    240         t = cli_servertime(c->opt_host, c->opt_have_ip? &c->opt_dest_ip : NULL,
     244        t = cli_servertime(c->opt_host,
     245                           c->opt_have_ip? &c->opt_dest_ip : NULL,
    241246                           NULL);
    242247        if (t == 0) return -1;
  • vendor/current/source3/utils/net_user.c

    r414 r988  
    5151                return net_user_usage(c, argc, argv);
    5252
    53         if (StrCaseCmp(argv[0], "HELP") == 0) {
     53        if (strcasecmp_m(argv[0], "HELP") == 0) {
    5454                net_user_usage(c, argc, argv);
    5555                return 0;
  • vendor/current/source3/utils/net_usershare.c

    r740 r988  
    136136static char *get_basepath(TALLOC_CTX *ctx)
    137137{
    138         char *basepath = talloc_strdup(ctx, lp_usershare_path());
     138        char *basepath = lp_usershare_path(ctx);
    139139
    140140        if (!basepath) {
     
    175175        us_path = talloc_asprintf(talloc_tos(),
    176176                                "%s/%s",
    177                                 lp_usershare_path(),
     177                                lp_usershare_path(talloc_tos()),
    178178                                sharename);
    179179        if (!us_path) {
     
    209209static int get_share_list(TALLOC_CTX *ctx, const char *wcard, bool only_ours)
    210210{
    211         SMB_STRUCT_DIR *dp;
    212         SMB_STRUCT_DIRENT *de;
     211        DIR *dp;
     212        struct dirent *de;
    213213        uid_t myuid = geteuid();
    214214        struct file_list *fl = NULL;
     
    218218                return -1;
    219219        }
    220         dp = sys_opendir(basepath);
     220        dp = opendir(basepath);
    221221        if (!dp) {
    222222                d_fprintf(stderr,
     
    227227        }
    228228
    229         while((de = sys_readdir(dp)) != 0) {
     229        while((de = readdir(dp)) != 0) {
    230230                SMB_STRUCT_STAT sbuf;
    231231                char *path;
     
    250250                                        n);
    251251                if (!path) {
    252                         sys_closedir(dp);
     252                        closedir(dp);
    253253                        return -1;
    254254                }
     
    279279
    280280                /* (Finally) - add to list. */
    281                 fl = TALLOC_P(ctx, struct file_list);
     281                fl = talloc(ctx, struct file_list);
    282282                if (!fl) {
    283                         sys_closedir(dp);
     283                        closedir(dp);
    284284                        return -1;
    285285                }
    286286                fl->pathname = talloc_strdup(ctx, n);
    287287                if (!fl->pathname) {
    288                         sys_closedir(dp);
     288                        closedir(dp);
    289289                        return -1;
    290290                }
     
    293293        }
    294294
    295         sys_closedir(dp);
     295        closedir(dp);
    296296        return 0;
    297297}
     
    360360
    361361#ifdef O_NOFOLLOW
    362         fd = sys_open(basepath, O_RDONLY|O_NOFOLLOW, 0);
     362        fd = open(basepath, O_RDONLY|O_NOFOLLOW, 0);
    363363#else
    364         fd = sys_open(basepath, O_RDONLY, 0);
     364        fd = open(basepath, O_RDONLY, 0);
    365365#endif
    366366
     
    524524        }
    525525
    526         strlower_m(wcard);
     526        if (!strlower_m(wcard)) {
     527                return -1;
     528        }
    527529
    528530        ctx = talloc_init("share_info");
     
    547549static int count_num_usershares(void)
    548550{
    549         SMB_STRUCT_DIR *dp;
    550         SMB_STRUCT_DIRENT *de;
     551        DIR *dp;
     552        struct dirent *de;
    551553        int num_usershares = 0;
    552554        TALLOC_CTX *ctx = talloc_tos();
     
    557559        }
    558560
    559         dp = sys_opendir(basepath);
     561        dp = opendir(basepath);
    560562        if (!dp) {
    561563                d_fprintf(stderr,
     
    566568        }
    567569
    568         while((de = sys_readdir(dp)) != 0) {
     570        while((de = readdir(dp)) != 0) {
    569571                SMB_STRUCT_STAT sbuf;
    570572                char *path;
     
    589591                                n);
    590592                if (!path) {
    591                         sys_closedir(dp);
     593                        closedir(dp);
    592594                        return -1;
    593595                }
     
    611613        }
    612614
    613         sys_closedir(dp);
     615        closedir(dp);
    614616        return num_usershares;
    615617}
     
    641643        bool guest_ok = false;
    642644        int num_usershares;
     645        mode_t mask;
    643646
    644647        us_comment = "";
     
    894897
    895898        /* Create a temporary filename for this share. */
     899        mask = umask(S_IRWXO | S_IRWXG);
    896900        tmpfd = mkstemp(full_path_tmp);
     901        umask(mask);
    897902
    898903        if (tmpfd == -1) {
     
    10371042        }
    10381043
    1039         strlower_m(wcard);
     1044        if (!strlower_m(wcard)) {
     1045                return -1;
     1046        }
    10401047
    10411048        ctx = talloc_init("share_list");
     
    10601067int net_usershare(struct net_context *c, int argc, const char **argv)
    10611068{
    1062         SMB_STRUCT_DIR *dp;
     1069        DIR *dp;
    10631070
    10641071        struct functable func[] = {
     
    11051112        }
    11061113
    1107         dp = sys_opendir(lp_usershare_path());
     1114        dp = opendir(lp_usershare_path(talloc_tos()));
    11081115        if (!dp) {
    11091116                int err = errno;
     
    11111118                        _("net usershare: cannot open usershare directory %s. "
    11121119                          "Error %s\n"),
    1113                         lp_usershare_path(), strerror(err) );
     1120                        lp_usershare_path(talloc_tos()), strerror(err) );
    11141121                if (err == EACCES) {
    11151122                        d_fprintf(stderr,
     
    11241131                return -1;
    11251132        }
    1126         sys_closedir(dp);
     1133        closedir(dp);
    11271134
    11281135        return net_run_function(c, argc, argv, "net usershare", func);
  • vendor/current/source3/utils/net_util.c

    r740 r988  
    4646        ZERO_STRUCT(pol);
    4747
    48         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
     48        status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
    4949                                          &lsa_pipe);
    5050        if (!NT_STATUS_IS_OK(status)) {
     
    9999
    100100NTSTATUS connect_to_service(struct net_context *c,
    101                                         struct cli_state **cli_ctx,
    102                                         struct sockaddr_storage *server_ss,
    103                                         const char *server_name,
    104                                         const char *service_name,
    105                                         const char *service_type)
     101                            struct cli_state **cli_ctx,
     102                            const struct sockaddr_storage *server_ss,
     103                            const char *server_name,
     104                            const char *service_name,
     105                            const char *service_type)
    106106{
    107107        NTSTATUS nt_status;
     
    126126                                        service_name, service_type,
    127127                                        c->opt_user_name, c->opt_workgroup,
    128                                         c->opt_password, flags, Undefined);
     128                                        c->opt_password, flags,
     129                                        SMB_SIGNING_IPC_DEFAULT);
    129130        if (!NT_STATUS_IS_OK(nt_status)) {
    130131                d_fprintf(stderr, _("Could not connect to server %s\n"),
     
    188189NTSTATUS connect_to_ipc(struct net_context *c,
    189190                        struct cli_state **cli_ctx,
    190                         struct sockaddr_storage *server_ss,
     191                        const struct sockaddr_storage *server_ss,
    191192                        const char *server_name)
    192193{
     
    201202NTSTATUS connect_to_ipc_anonymous(struct net_context *c,
    202203                                struct cli_state **cli_ctx,
    203                                 struct sockaddr_storage *server_ss,
     204                                const struct sockaddr_storage *server_ss,
    204205                                const char *server_name)
    205206{
     
    210211                                        "IPC$", "IPC",
    211212                                        "", "",
    212                                         "", 0, Undefined);
     213                                        "", 0, SMB_SIGNING_DEFAULT);
    213214
    214215        if (NT_STATUS_IS_OK(nt_status)) {
     
    218219                return nt_status;
    219220        }
    220 }
    221 
    222 /****************************************************************************
    223  Return malloced user@realm for krb5 login.
    224 ****************************************************************************/
    225 
    226 static char *get_user_and_realm(const char *username)
    227 {
    228         char *user_and_realm = NULL;
    229 
    230         if (!username) {
    231                 return NULL;
    232         }
    233         if (strchr_m(username, '@')) {
    234                 user_and_realm = SMB_STRDUP(username);
    235         } else {
    236                 if (asprintf(&user_and_realm, "%s@%s", username, lp_realm()) == -1) {
    237                         user_and_realm = NULL;
    238                 }
    239         }
    240         return user_and_realm;
    241 }
    242 
    243 /****************************************************************************
    244  Connect to \\server\ipc$ using KRB5.
    245 ****************************************************************************/
    246 
    247 NTSTATUS connect_to_ipc_krb5(struct net_context *c,
    248                         struct cli_state **cli_ctx,
    249                         struct sockaddr_storage *server_ss,
    250                         const char *server_name)
    251 {
    252         NTSTATUS nt_status;
    253         char *user_and_realm = NULL;
    254 
    255         /* FIXME: Should get existing kerberos ticket if possible. */
    256         c->opt_password = net_prompt_pass(c, c->opt_user_name);
    257         if (!c->opt_password) {
    258                 return NT_STATUS_NO_MEMORY;
    259         }
    260 
    261         user_and_realm = get_user_and_realm(c->opt_user_name);
    262         if (!user_and_realm) {
    263                 return NT_STATUS_NO_MEMORY;
    264         }
    265 
    266         nt_status = cli_full_connection(cli_ctx, NULL, server_name,
    267                                         server_ss, c->opt_port,
    268                                         "IPC$", "IPC",
    269                                         user_and_realm, c->opt_workgroup,
    270                                         c->opt_password,
    271                                         CLI_FULL_CONNECTION_USE_KERBEROS,
    272                                         Undefined);
    273 
    274         SAFE_FREE(user_and_realm);
    275 
    276         if (!NT_STATUS_IS_OK(nt_status)) {
    277                 DEBUG(1,("Cannot connect to server using kerberos.  Error was %s\n", nt_errstr(nt_status)));
    278                 return nt_status;
    279         }
    280 
    281         if (c->smb_encrypt) {
    282                 nt_status = cli_cm_force_encryption(*cli_ctx,
    283                                         user_and_realm,
    284                                         c->opt_password,
    285                                         c->opt_workgroup,
    286                                         "IPC$");
    287                 if (!NT_STATUS_IS_OK(nt_status)) {
    288                         cli_shutdown(*cli_ctx);
    289                         *cli_ctx = NULL;
    290                 }
    291         }
    292 
    293         return nt_status;
    294221}
    295222
     
    305232NTSTATUS connect_dst_pipe(struct net_context *c, struct cli_state **cli_dst,
    306233                          struct rpc_pipe_client **pp_pipe_hnd,
    307                           const struct ndr_syntax_id *interface)
     234                          const struct ndr_interface_table *table)
    308235{
    309236        NTSTATUS nt_status;
     
    330257        }
    331258
    332         nt_status = cli_rpc_pipe_open_noauth(cli_tmp, interface,
     259        nt_status = cli_rpc_pipe_open_noauth(cli_tmp, table,
    333260                                             &pipe_hnd);
    334261        if (!NT_STATUS_IS_OK(nt_status)) {
     
    361288        c->opt_password = secrets_fetch_machine_password(
    362289                                c->opt_target_workgroup, NULL, NULL);
    363         if (asprintf(&user_name, "%s$@%s", global_myname(), lp_realm()) == -1) {
     290        if (asprintf(&user_name, "%s$@%s", lp_netbios_name(), lp_realm()) == -1) {
    364291                return -1;
    365292        }
     
    383310        c->opt_password = secrets_fetch_machine_password(
    384311                                c->opt_target_workgroup, NULL, NULL);
    385         if (asprintf(&user_name, "%s$", global_myname()) == -1) {
     312        if (asprintf(&user_name, "%s$", lp_netbios_name()) == -1) {
    386313                return -1;
    387314        }
     
    500427NTSTATUS net_make_ipc_connection_ex(struct net_context *c ,const char *domain,
    501428                                    const char *server,
    502                                     struct sockaddr_storage *pss,
     429                                    const struct sockaddr_storage *pss,
    503430                                    unsigned flags, struct cli_state **pcli)
    504431{
     
    532459
    533460        if ( (flags & NET_FLAGS_PDC) && NT_STATUS_IS_OK(nt_status) )
    534                 saf_store( cli->server_domain, cli->desthost );
     461                saf_store(cli->server_domain, server_name);
    535462
    536463        SAFE_FREE(server_name);
     
    556483{
    557484        char *prompt = NULL;
    558         const char *pass = NULL;
     485        char pwd[256] = {0};
     486        int rc;
    559487
    560488        if (c->opt_password) {
     
    574502        }
    575503
    576         pass = getpass(prompt);
     504        rc = samba_getpass(prompt, pwd, sizeof(pwd), false, false);
    577505        SAFE_FREE(prompt);
    578 
    579         return pass;
     506        if (rc < 0) {
     507                return NULL;
     508        }
     509
     510        return SMB_STRDUP(pwd);
    580511}
    581512
     
    587518        if (argc != 0) {
    588519                for (i=0; table[i].funcname != NULL; i++) {
    589                         if (StrCaseCmp(argv[0], table[i].funcname) == 0)
     520                        if (strcasecmp_m(argv[0], table[i].funcname) == 0)
    590521                                return table[i].fn(c, argc-1, argv+1);
    591522                }
     
    641572        ZERO_STRUCT(pol);
    642573
    643         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
     574        status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
    644575                                          &pipe_hnd);
    645576        if (!NT_STATUS_IS_OK(status)) {
     
    704635        ZERO_STRUCTP(dc_info);
    705636
    706         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_dssetup.syntax_id,
     637        status = cli_rpc_pipe_open_noauth(cli, &ndr_table_dssetup,
    707638                                          &dssetup_pipe);
    708639        if (!NT_STATUS_IS_OK(status)) {
  • vendor/current/source3/utils/netlookup.c

    r740 r988  
    7979        }
    8080
    81         cs = TALLOC_P(ctx, struct con_struct);
     81        cs = talloc(ctx, struct con_struct);
    8282        if (!cs) {
    8383                *perr = NT_STATUS_NO_MEMORY;
     
    9999#endif
    100100
    101         nt_status = cli_full_connection(&cs->cli, global_myname(), global_myname(),
     101        nt_status = cli_full_connection(&cs->cli, lp_netbios_name(), lp_netbios_name(),
    102102                                        &loopback_ss, 0,
    103103                                        "IPC$", "IPC",
     
    112112#endif
    113113                                        0,
    114                                         Undefined);
     114                                        SMB_SIGNING_DEFAULT);
    115115
    116116        if (!NT_STATUS_IS_OK(nt_status)) {
     
    123123
    124124        nt_status = cli_rpc_pipe_open_noauth(cs->cli,
    125                                         &ndr_table_lsarpc.syntax_id,
     125                                        &ndr_table_lsarpc,
    126126                                        &cs->lsapipe);
    127127
  • vendor/current/source3/utils/nmblookup.c

    r740 r988  
    4141{
    4242        struct sockaddr_storage ss;
    43         const char *sock_addr = lp_socket_address();
     43        const char *sock_addr = lp_nbt_client_socket_address();
    4444
    4545        if (!interpret_string_addr(&ss, sock_addr,
     
    108108****************************************************************************/
    109109
    110 static void do_node_status(const char *name,
     110static bool do_node_status(const char *name,
    111111                int type,
    112112                struct sockaddr_storage *pss)
     
    143143                d_printf("\n");
    144144                TALLOC_FREE(addrs);
     145                return true;
    145146        } else {
    146147                d_printf("No reply from %s\n\n",addr);
     148                return false;
    147149        }
    148150}
     
    169171                                    &ip_list, &count, &flags);
    170172        } else {
    171                 const struct in_addr *bcast;
    172                 for (j=iface_count() - 1;
    173                      !ip_list && j >= 0;
    174                      j--) {
    175                         char addr[INET6_ADDRSTRLEN];
    176                         struct sockaddr_storage bcast_ss;
    177 
    178                         bcast = iface_n_bcast_v4(j);
    179                         if (!bcast) {
    180                                 continue;
    181                         }
    182                         in_addr_to_sockaddr_storage(&bcast_ss, *bcast);
    183                         print_sockaddr(addr, sizeof(addr), &bcast_ss);
    184                         d_printf("querying %s on %s\n",
    185                                lookup, addr);
    186                         status = name_query(lookup,lookup_type,
    187                                             use_bcast,
    188                                             use_bcast?True:recursion_desired,
    189                                             &bcast_ss, talloc_tos(),
    190                                             &ip_list, &count, &flags);
    191                 }
     173                status = name_resolve_bcast(
     174                        lookup, lookup_type,
     175                        talloc_tos(), &ip_list, &count);
    192176        }
    193177
     
    220204                 */
    221205                if (find_status) {
    222                         do_node_status(lookup, lookup_type, &ip_list[j]);
     206                        if (!do_node_status(lookup, lookup_type, &ip_list[j])) {
     207                                status = NT_STATUS_UNSUCCESSFUL;
     208                        }
    223209                }
    224210        }
     
    233219  main program
    234220****************************************************************************/
    235 int main(int argc,char *argv[])
     221int main(int argc, const char *argv[])
    236222{
    237223        int opt;
     
    240226        static bool find_master=False;
    241227        static bool lookup_by_ip = False;
    242         poptContext pc;
     228        poptContext pc = NULL;
    243229        TALLOC_CTX *frame = talloc_stackframe();
     230        int rc = 0;
    244231
    245232        struct poptOption long_options[] = {
     
    261248        *lookup = 0;
    262249
    263         load_case_tables();
     250        smb_init_locale();
    264251
    265252        setup_logging(argv[0], DEBUG_STDOUT);
    266253
    267         pc = poptGetContext("nmblookup", argc, (const char **)argv,
     254        pc = poptGetContext("nmblookup", argc, argv,
    268255                        long_options, POPT_CONTEXT_KEEP_FIRST);
    269256
     
    316303        if(!poptPeekArg(pc)) {
    317304                poptPrintUsage(pc, stderr, 0);
    318                 exit(1);
    319         }
    320 
    321         if (!lp_load(get_dyn_CONFIGFILE(),True,False,False,True)) {
     305                rc = 1;
     306                goto out;
     307        }
     308
     309        if (!lp_load_global(get_dyn_CONFIGFILE())) {
    322310                fprintf(stderr, "Can't load %s - run testparm to debug it\n",
    323311                                get_dyn_CONFIGFILE());
     
    326314        load_interfaces();
    327315        if (!open_sockets()) {
    328                 return(1);
     316                rc = 1;
     317                goto out;
    329318        }
    330319
     
    332321                char *p;
    333322                struct in_addr ip;
     323                size_t nbt_len;
    334324
    335325                fstrcpy(lookup,poptGetArg(pc));
     
    340330                        in_addr_to_sockaddr_storage(&ss, ip);
    341331                        fstrcpy(lookup,"*");
    342                         do_node_status(lookup, lookup_type, &ss);
     332                        if (!do_node_status(lookup, lookup_type, &ss)) {
     333                                rc = 1;
     334                        }
    343335                        continue;
    344336                }
     
    359351                }
    360352
     353                nbt_len = strlen(lookup);
     354                if (nbt_len > MAX_NETBIOSNAME_LEN - 1) {
     355                        d_printf("The specified netbios name [%s] is too long!\n",
     356                                 lookup);
     357                        continue;
     358                }
     359
     360
    361361                if (!query_one(lookup, lookup_type)) {
     362                        rc = 1;
    362363                        d_printf( "name_query failed to find name %s", lookup );
    363364                        if( 0 != lookup_type ) {
     
    368369        }
    369370
     371out:
    370372        poptFreeContext(pc);
    371373        TALLOC_FREE(frame);
    372         return(0);
    373 }
     374        return rc;
     375}
  • vendor/current/source3/utils/ntlm_auth.c

    r740 r988  
    99   Copyright (C) Robert O'Callahan 2006 (added cached credential code).
    1010   Copyright (C) Kai Blin <kai@samba.org> 2008
     11   Copyright (C) Simo Sorce 2010
    1112
    1213   This program is free software; you can redistribute it and/or modify
     
    2526
    2627#include "includes.h"
     28#include "lib/param/param.h"
    2729#include "popt_common.h"
    2830#include "utils/ntlm_auth.h"
    2931#include "../libcli/auth/libcli_auth.h"
    30 #include "../libcli/auth/spnego.h"
    31 #include "../libcli/auth/ntlmssp.h"
     32#include "auth/ntlmssp/ntlmssp.h"
     33#include "auth/gensec/gensec.h"
     34#include "auth/gensec/gensec_internal.h"
     35#include "auth/credentials/credentials.h"
     36#include "librpc/crypto/gse.h"
    3237#include "smb_krb5.h"
    33 #include <iniparser.h>
     38#include "lib/util/tiniparser.h"
    3439#include "../lib/crypto/arcfour.h"
    35 #include "libads/kerberos_proto.h"
    3640#include "nsswitch/winbind_client.h"
    3741#include "librpc/gen_ndr/krb5pac.h"
    3842#include "../lib/util/asn1.h"
     43#include "auth/common_auth.h"
     44#include "source3/include/auth.h"
     45#include "source3/auth/proto.h"
     46#include "nsswitch/libwbclient/wbclient.h"
     47#include "lib/param/loadparm.h"
     48
     49#if HAVE_KRB5
     50#include "auth/kerberos/pac_utils.h"
     51#endif
    3952
    4053#ifndef PAM_WINBIND_CONFIG_FILE
     
    5568        SQUID_2_5_NTLMSSP,
    5669        NTLMSSP_CLIENT_1,
    57         GSS_SPNEGO,
     70        GSS_SPNEGO_SERVER,
    5871        GSS_SPNEGO_CLIENT,
    5972        NTLM_SERVER_1,
     
    6982};
    7083
    71 enum ntlm_auth_svr_state {
    72         SERVER_INITIAL = 0,
    73         SERVER_CHALLENGE,
    74         SERVER_FINISHED,
    75         SERVER_ERROR
    76 };
    77 
    7884struct ntlm_auth_state {
    7985        TALLOC_CTX *mem_ctx;
    8086        enum stdio_helper_mode helper_mode;
    8187        enum ntlm_auth_cli_state cli_state;
    82         enum ntlm_auth_svr_state svr_state;
    8388        struct ntlmssp_state *ntlmssp_state;
    8489        uint32_t neg_flags;
    8590        char *want_feature_list;
    86         char *spnego_mech;
    87         char *spnego_mech_oid;
    8891        bool have_session_key;
    8992        DATA_BLOB session_key;
    9093        DATA_BLOB initial_message;
     94        void *gensec_private_1;
    9195};
    92 
    93 typedef void (*stdio_helper_function)(struct ntlm_auth_state *state, char *buf,
    94                                         int length);
    95 
    96 static void manage_squid_basic_request (struct ntlm_auth_state *state,
    97                                         char *buf, int length);
    98 
    99 static void manage_squid_ntlmssp_request (struct ntlm_auth_state *state,
    100                                         char *buf, int length);
    101 
    102 static void manage_client_ntlmssp_request (struct ntlm_auth_state *state,
    103                                         char *buf, int length);
    104 
    105 static void manage_gss_spnego_request (struct ntlm_auth_state *state,
    106                                         char *buf, int length);
    107 
    108 static void manage_gss_spnego_client_request (struct ntlm_auth_state *state,
    109                                         char *buf, int length);
    110 
    111 static void manage_ntlm_server_1_request (struct ntlm_auth_state *state,
    112                                         char *buf, int length);
    113 
    114 static void manage_ntlm_change_password_1_request(struct ntlm_auth_state *state,
    115                                         char *buf, int length);
     96typedef void (*stdio_helper_function)(enum stdio_helper_mode stdio_helper_mode,
     97                                      struct loadparm_context *lp_ctx,
     98                                      struct ntlm_auth_state *state, char *buf,
     99                                        int length, void **private2);
     100
     101static void manage_gensec_request(enum stdio_helper_mode stdio_helper_mode,
     102                                  struct loadparm_context *lp_ctx,
     103                                  char *buf, int length, void **private1);
     104
     105static void manage_squid_request(enum stdio_helper_mode stdio_helper_mode,
     106                                 struct loadparm_context *lp_ctx,
     107                                 struct ntlm_auth_state *state,
     108                                 stdio_helper_function fn, void **private2);
     109
     110static void manage_squid_basic_request (enum stdio_helper_mode stdio_helper_mode,
     111                                      struct loadparm_context *lp_ctx,
     112                                      struct ntlm_auth_state *state,
     113                                        char *buf, int length, void **private2);
     114
     115static void manage_squid_ntlmssp_request (enum stdio_helper_mode stdio_helper_mode,
     116                                      struct loadparm_context *lp_ctx,
     117                                      struct ntlm_auth_state *state,
     118                                        char *buf, int length, void **private2);
     119
     120static void manage_client_ntlmssp_request (enum stdio_helper_mode stdio_helper_mode,
     121                                      struct loadparm_context *lp_ctx,
     122                                      struct ntlm_auth_state *state,
     123                                        char *buf, int length, void **private2);
     124
     125static void manage_gss_spnego_request (enum stdio_helper_mode stdio_helper_mode,
     126                                      struct loadparm_context *lp_ctx,
     127                                      struct ntlm_auth_state *state,
     128                                        char *buf, int length, void **private2);
     129
     130static void manage_gss_spnego_client_request (enum stdio_helper_mode stdio_helper_mode,
     131                                      struct loadparm_context *lp_ctx,
     132                                      struct ntlm_auth_state *state,
     133                                        char *buf, int length, void **private2);
     134
     135static void manage_ntlm_server_1_request (enum stdio_helper_mode stdio_helper_mode,
     136                                      struct loadparm_context *lp_ctx,
     137                                      struct ntlm_auth_state *state,
     138                                        char *buf, int length, void **private2);
     139
     140static void manage_ntlm_change_password_1_request(enum stdio_helper_mode stdio_helper_mode,
     141                                      struct loadparm_context *lp_ctx,
     142                                      struct ntlm_auth_state *state,
     143                                        char *buf, int length, void **private2);
    116144
    117145static const struct {
     
    124152        { SQUID_2_5_NTLMSSP, "squid-2.5-ntlmssp", manage_squid_ntlmssp_request},
    125153        { NTLMSSP_CLIENT_1, "ntlmssp-client-1", manage_client_ntlmssp_request},
    126         { GSS_SPNEGO, "gss-spnego", manage_gss_spnego_request},
     154        { GSS_SPNEGO_SERVER, "gss-spnego", manage_gss_spnego_request},
    127155        { GSS_SPNEGO_CLIENT, "gss-spnego-client", manage_gss_spnego_client_request},
    128156        { NTLM_SERVER_1, "ntlm-server-1", manage_ntlm_server_1_request},
     
    141169static int request_user_session_key;
    142170static int use_cached_creds;
     171static int offline_logon;
    143172
    144173static const char *require_membership_of;
     
    146175static const char *opt_pam_winbind_conf;
    147176
     177const char *opt_target_service;
     178const char *opt_target_hostname;
     179
     180
     181/* This is a bit hairy, but the basic idea is to do a password callback
     182   to the calling application.  The callback comes from within gensec */
     183
     184static void manage_gensec_get_pw_request(enum stdio_helper_mode stdio_helper_mode,
     185                                         struct loadparm_context *lp_ctx,
     186                                         struct ntlm_auth_state *state, char *buf, int length,
     187                                         void **password)
     188{
     189        DATA_BLOB in;
     190        if (strlen(buf) < 2) {
     191                DEBUG(1, ("query [%s] invalid", buf));
     192                x_fprintf(x_stdout, "BH Query invalid\n");
     193                return;
     194        }
     195
     196        if (strlen(buf) > 3) {
     197                in = base64_decode_data_blob(buf + 3);
     198        } else {
     199                in = data_blob(NULL, 0);
     200        }
     201
     202        if (strncmp(buf, "PW ", 3) == 0) {
     203
     204                *password = talloc_strndup(NULL,
     205                                           (const char *)in.data, in.length);
     206
     207                if (*password == NULL) {
     208                        DEBUG(1, ("Out of memory\n"));
     209                        x_fprintf(x_stdout, "BH Out of memory\n");
     210                        data_blob_free(&in);
     211                        return;
     212                }
     213
     214                x_fprintf(x_stdout, "OK\n");
     215                data_blob_free(&in);
     216                return;
     217        }
     218        DEBUG(1, ("Asked for (and expected) a password\n"));
     219        x_fprintf(x_stdout, "BH Expected a password\n");
     220        data_blob_free(&in);
     221}
     222
     223/**
     224 * Callback for password credentials.  This is not async, and when
     225 * GENSEC and the credentials code is made async, it will look rather
     226 * different.
     227 */
     228
     229static const char *get_password(struct cli_credentials *credentials)
     230{
     231        TALLOC_CTX *frame = talloc_stackframe();
     232        char *password = NULL;
     233        struct ntlm_auth_state *state;
     234
     235        state = talloc_zero(frame, struct ntlm_auth_state);
     236        if (state == NULL) {
     237                DEBUG(0, ("squid_stream: Failed to talloc ntlm_auth_state\n"));
     238                x_fprintf(x_stderr, "ERR\n");
     239                exit(1);
     240        }
     241
     242        state->mem_ctx = state;
     243
     244        /* Ask for a password */
     245        x_fprintf(x_stdout, "PW\n");
     246
     247        manage_squid_request(NUM_HELPER_MODES /* bogus */, NULL, state, manage_gensec_get_pw_request, (void **)&password);
     248        talloc_steal(credentials, password);
     249        TALLOC_FREE(frame);
     250        return password;
     251}
     252
     253/**
     254 * A limited set of features are defined with text strings as needed
     255 * by ntlm_auth
     256 *
     257 */
     258static void gensec_want_feature_list(struct gensec_security *state, char* feature_list)
     259{
     260        if (in_list("NTLMSSP_FEATURE_SESSION_KEY", feature_list, true)) {
     261                DEBUG(10, ("want GENSEC_FEATURE_SESSION_KEY\n"));
     262                gensec_want_feature(state, GENSEC_FEATURE_SESSION_KEY);
     263        }
     264        if (in_list("NTLMSSP_FEATURE_SIGN", feature_list, true)) {
     265                DEBUG(10, ("want GENSEC_FEATURE_SIGN\n"));
     266                gensec_want_feature(state, GENSEC_FEATURE_SIGN);
     267        }
     268        if (in_list("NTLMSSP_FEATURE_SEAL", feature_list, true)) {
     269                DEBUG(10, ("want GENSEC_FEATURE_SEAL\n"));
     270                gensec_want_feature(state, GENSEC_FEATURE_SEAL);
     271        }
     272        if (in_list("NTLMSSP_FEATURE_CCACHE", feature_list, true)) {
     273                DEBUG(10, ("want GENSEC_FEATURE_NTLM_CCACHE\n"));
     274                gensec_want_feature(state, GENSEC_FEATURE_NTLM_CCACHE);
     275        }
     276}
     277
    148278static char winbind_separator(void)
    149279{
     
    159289        /* Send off request */
    160290
    161         if (winbindd_request_response(WINBINDD_INFO, NULL, &response) !=
     291        if (winbindd_request_response(NULL, WINBINDD_INFO, NULL, &response) !=
    162292            NSS_STATUS_SUCCESS) {
    163293                d_printf("could not obtain winbind separator!\n");
     
    189319        /* Send off request */
    190320
    191         if (winbindd_request_response(WINBINDD_DOMAIN_NAME, NULL, &response) !=
     321        if (winbindd_request_response(NULL, WINBINDD_DOMAIN_NAME, NULL, &response) !=
    192322            NSS_STATUS_SUCCESS) {
    193                 DEBUG(0, ("could not obtain winbind domain name!\n"));
     323                DEBUG(1, ("could not obtain winbind domain name!\n"));
    194324                return lp_workgroup();
    195325        }
     
    215345        /* Send off request */
    216346
    217         if (winbindd_request_response(WINBINDD_NETBIOS_NAME, NULL, &response) !=
     347        if (winbindd_request_response(NULL, WINBINDD_NETBIOS_NAME, NULL, &response) !=
    218348            NSS_STATUS_SUCCESS) {
    219                 DEBUG(0, ("could not obtain winbind netbios name!\n"));
    220                 return global_myname();
     349                DEBUG(1, ("could not obtain winbind netbios name!\n"));
     350                return lp_netbios_name();
    221351        }
    222352
     
    255385        fstrcpy(domain, domuser);
    256386        domain[PTR_DIFF(p, domuser)] = 0;
    257         strupper_m(domain);
    258 
    259         return True;
     387        return strupper_m(domain);
    260388}
    261389
     
    280408                                         request.data.name.dom_name,
    281409                                         request.data.name.name)) {
    282                 DEBUG(0, ("Could not parse %s into seperate domain/name parts!\n",
     410                DEBUG(0, ("Could not parse %s into separate domain/name parts!\n",
    283411                          require_membership_of));
    284412                return False;
    285413        }
    286414
    287         if (winbindd_request_response(WINBINDD_LOOKUPNAME, &request, &response) !=
     415        if (winbindd_request_response(NULL, WINBINDD_LOOKUPNAME, &request, &response) !=
    288416            NSS_STATUS_SUCCESS) {
    289417                DEBUG(0, ("Winbindd lookupname failed to resolve %s into a SID!\n",
     
    308436{
    309437        int ctrl = 0;
    310         dictionary *d = NULL;
     438        struct tiniparser_dictionary *d = NULL;
    311439
    312440        if (!opt_pam_winbind_conf || !*opt_pam_winbind_conf) {
     
    314442        }
    315443
    316         d = iniparser_load(CONST_DISCARD(char *, opt_pam_winbind_conf));
     444        d = tiniparser_load(opt_pam_winbind_conf);
    317445
    318446        if (!d) {
     
    320448        }
    321449
    322         if (iniparser_getboolean(d, CONST_DISCARD(char *, "global:krb5_auth"), false)) {
     450        if (tiniparser_getboolean(d, "global:krb5_auth", false)) {
    323451                ctrl |= WINBIND_KRB5_AUTH;
    324452        }
    325453
    326         iniparser_freedict(d);
     454        tiniparser_freedict(d);
    327455
    328456        return ctrl;
     
    355483        }
    356484
    357         result = winbindd_request_response(WINBINDD_PAM_AUTH, &request, &response);
     485        if (offline_logon) {
     486                request.flags |= WBFLAG_PAM_CACHED_LOGIN;
     487        }
     488
     489        result = winbindd_request_response(NULL, WINBINDD_PAM_AUTH, &request, &response);
    358490
    359491        /* Display response */
     
    390522                                   const DATA_BLOB *lm_response,
    391523                                   const DATA_BLOB *nt_response,
    392                                    uint32 flags,
    393                                    uint8 lm_key[8],
    394                                    uint8 user_session_key[16],
     524                                   uint32_t flags,
     525                                   uint32_t extra_logon_parameters,
     526                                   uint8_t lm_key[8],
     527                                   uint8_t user_session_key[16],
    395528                                   char **error_string,
    396529                                   char **unix_name)
     
    410543        request.flags = flags;
    411544
    412         request.data.auth_crap.logon_parameters = MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT | MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT;
     545        request.data.auth_crap.logon_parameters = extra_logon_parameters
     546                | MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT | MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT;
    413547
    414548        if (require_membership_of_sid)
     
    448582        }
    449583
    450         result = winbindd_request_response(WINBINDD_PAM_AUTH_CRAP, &request, &response);
     584        result = winbindd_request_response(NULL, WINBINDD_PAM_AUTH_CRAP, &request, &response);
    451585        SAFE_FREE(request.extra_data.data);
    452586
     
    543677        }
    544678
    545         result = winbindd_request_response(WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, &request, &response);
     679        result = winbindd_request_response(NULL, WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, &request, &response);
    546680
    547681        /* Display response */
     
    570704}
    571705
    572 static NTSTATUS winbind_pw_check(struct ntlmssp_state *ntlmssp_state, TALLOC_CTX *mem_ctx,
    573                                  DATA_BLOB *user_session_key, DATA_BLOB *lm_session_key)
     706static NTSTATUS ntlm_auth_generate_session_info(struct auth4_context *auth_context,
     707                                                TALLOC_CTX *mem_ctx,
     708                                                void *server_returned_info,
     709                                                const char *original_user_name,
     710                                                uint32_t session_info_flags,
     711                                                struct auth_session_info **session_info_out)
     712{
     713        char *unix_username = (char *)server_returned_info;
     714        struct auth_session_info *session_info = talloc_zero(mem_ctx, struct auth_session_info);
     715        if (!session_info) {
     716                return NT_STATUS_NO_MEMORY;
     717        }
     718
     719        session_info->unix_info = talloc_zero(session_info, struct auth_user_info_unix);
     720        if (!session_info->unix_info) {
     721                TALLOC_FREE(session_info);
     722                return NT_STATUS_NO_MEMORY;
     723        }
     724        session_info->unix_info->unix_name = talloc_steal(session_info->unix_info, unix_username);
     725
     726        *session_info_out = session_info;
     727
     728        return NT_STATUS_OK;
     729}
     730
     731static NTSTATUS ntlm_auth_generate_session_info_pac(struct auth4_context *auth_ctx,
     732                                                    TALLOC_CTX *mem_ctx,
     733                                                    struct smb_krb5_context *smb_krb5_context,
     734                                                    DATA_BLOB *pac_blob,
     735                                                    const char *princ_name,
     736                                                    const struct tsocket_address *remote_address,
     737                                                    uint32_t session_info_flags,
     738                                                    struct auth_session_info **session_info)
     739{
     740        TALLOC_CTX *tmp_ctx;
     741        struct PAC_LOGON_INFO *logon_info = NULL;
     742        char *unixuser;
     743        NTSTATUS status;
     744        char *domain = NULL;
     745        char *realm = NULL;
     746        char *user = NULL;
     747        char *p;
     748
     749        tmp_ctx = talloc_new(mem_ctx);
     750        if (!tmp_ctx) {
     751                return NT_STATUS_NO_MEMORY;
     752        }
     753
     754        if (pac_blob) {
     755#ifdef HAVE_KRB5
     756                status = kerberos_pac_logon_info(tmp_ctx, *pac_blob, NULL, NULL,
     757                                                 NULL, NULL, 0, &logon_info);
     758#else
     759                status = NT_STATUS_ACCESS_DENIED;
     760#endif
     761                if (!NT_STATUS_IS_OK(status)) {
     762                        goto done;
     763                }
     764        }
     765
     766        DEBUG(3, ("Kerberos ticket principal name is [%s]\n", princ_name));
     767
     768        p = strchr_m(princ_name, '@');
     769        if (!p) {
     770                DEBUG(3, ("[%s] Doesn't look like a valid principal\n",
     771                          princ_name));
     772                return NT_STATUS_LOGON_FAILURE;
     773        }
     774
     775        user = talloc_strndup(mem_ctx, princ_name, p - princ_name);
     776        if (!user) {
     777                return NT_STATUS_NO_MEMORY;
     778        }
     779
     780        realm = talloc_strdup(talloc_tos(), p + 1);
     781        if (!realm) {
     782                return NT_STATUS_NO_MEMORY;
     783        }
     784
     785        if (!strequal(realm, lp_realm())) {
     786                DEBUG(3, ("Ticket for foreign realm %s@%s\n", user, realm));
     787                if (!lp_allow_trusted_domains()) {
     788                        return NT_STATUS_LOGON_FAILURE;
     789                }
     790        }
     791
     792        if (logon_info && logon_info->info3.base.logon_domain.string) {
     793                domain = talloc_strdup(mem_ctx,
     794                                        logon_info->info3.base.logon_domain.string);
     795                if (!domain) {
     796                        return NT_STATUS_NO_MEMORY;
     797                }
     798                DEBUG(10, ("Domain is [%s] (using PAC)\n", domain));
     799        } else {
     800
     801                /* If we have winbind running, we can (and must) shorten the
     802                   username by using the short netbios name. Otherwise we will
     803                   have inconsistent user names. With Kerberos, we get the
     804                   fully qualified realm, with ntlmssp we get the short
     805                   name. And even w2k3 does use ntlmssp if you for example
     806                   connect to an ip address. */
     807
     808                wbcErr wbc_status;
     809                struct wbcDomainInfo *info = NULL;
     810
     811                DEBUG(10, ("Mapping [%s] to short name using winbindd\n",
     812                           realm));
     813
     814                wbc_status = wbcDomainInfo(realm, &info);
     815
     816                if (WBC_ERROR_IS_OK(wbc_status)) {
     817                        domain = talloc_strdup(mem_ctx,
     818                                                info->short_name);
     819                        wbcFreeMemory(info);
     820                } else {
     821                        DEBUG(3, ("Could not find short name: %s\n",
     822                                  wbcErrorString(wbc_status)));
     823                        domain = talloc_strdup(mem_ctx, realm);
     824                }
     825                if (!domain) {
     826                        return NT_STATUS_NO_MEMORY;
     827                }
     828                DEBUG(10, ("Domain is [%s] (using Winbind)\n", domain));
     829        }
     830
     831        unixuser = talloc_asprintf(tmp_ctx, "%s%c%s", domain, winbind_separator(), user);
     832        if (!unixuser) {
     833                status = NT_STATUS_NO_MEMORY;
     834                goto done;
     835        }
     836
     837        status = ntlm_auth_generate_session_info(auth_ctx, mem_ctx, unixuser, NULL, session_info_flags, session_info);
     838
     839done:
     840        TALLOC_FREE(tmp_ctx);
     841        return status;
     842}
     843
     844
     845
     846/**
     847 * Return the challenge as determined by the authentication subsystem
     848 * @return an 8 byte random challenge
     849 */
     850
     851static NTSTATUS ntlm_auth_get_challenge(struct auth4_context *auth_ctx,
     852                                        uint8_t chal[8])
     853{
     854        if (auth_ctx->challenge.data.length == 8) {
     855                DEBUG(5, ("auth_get_challenge: returning previous challenge by module %s (normal)\n",
     856                          auth_ctx->challenge.set_by));
     857                memcpy(chal, auth_ctx->challenge.data.data, 8);
     858                return NT_STATUS_OK;
     859        }
     860
     861        if (!auth_ctx->challenge.set_by) {
     862                generate_random_buffer(chal, 8);
     863
     864                auth_ctx->challenge.data                = data_blob_talloc(auth_ctx, chal, 8);
     865                NT_STATUS_HAVE_NO_MEMORY(auth_ctx->challenge.data.data);
     866                auth_ctx->challenge.set_by              = "random";
     867        }
     868
     869        DEBUG(10,("auth_get_challenge: challenge set by %s\n",
     870                 auth_ctx->challenge.set_by));
     871
     872        return NT_STATUS_OK;
     873}
     874
     875/**
     876 * NTLM2 authentication modifies the effective challenge,
     877 * @param challenge The new challenge value
     878 */
     879static NTSTATUS ntlm_auth_set_challenge(struct auth4_context *auth_ctx, const uint8_t chal[8], const char *set_by)
     880{
     881        auth_ctx->challenge.set_by = talloc_strdup(auth_ctx, set_by);
     882        NT_STATUS_HAVE_NO_MEMORY(auth_ctx->challenge.set_by);
     883
     884        auth_ctx->challenge.data = data_blob_talloc(auth_ctx, chal, 8);
     885        NT_STATUS_HAVE_NO_MEMORY(auth_ctx->challenge.data.data);
     886
     887        return NT_STATUS_OK;
     888}
     889
     890/**
     891 * Check the password on an NTLMSSP login. 
     892 *
     893 * Return the session keys used on the connection.
     894 */
     895
     896static NTSTATUS winbind_pw_check(struct auth4_context *auth4_context,
     897                                 TALLOC_CTX *mem_ctx,
     898                                 const struct auth_usersupplied_info *user_info,
     899                                 void **server_returned_info,
     900                                 DATA_BLOB *session_key, DATA_BLOB *lm_session_key)
    574901{
    575902        static const char zeros[16] = { 0, };
    576903        NTSTATUS nt_status;
    577904        char *error_string = NULL;
    578         uint8 lm_key[8];
    579         uint8 user_sess_key[16];
     905        uint8_t lm_key[8];
     906        uint8_t user_sess_key[16];
    580907        char *unix_name = NULL;
    581908
    582         nt_status = contact_winbind_auth_crap(ntlmssp_state->user, ntlmssp_state->domain,
    583                                               ntlmssp_state->client.netbios_name,
    584                                               &ntlmssp_state->chal,
    585                                               &ntlmssp_state->lm_resp,
    586                                               &ntlmssp_state->nt_resp,
     909        nt_status = contact_winbind_auth_crap(user_info->client.account_name, user_info->client.domain_name,
     910                                              user_info->workstation_name,
     911                                              &auth4_context->challenge.data,
     912                                              &user_info->password.response.lanman,
     913                                              &user_info->password.response.nt,
    587914                                              WBFLAG_PAM_LMKEY | WBFLAG_PAM_USER_SESSION_KEY | WBFLAG_PAM_UNIX_NAME,
     915                                              0,
    588916                                              lm_key, user_sess_key,
    589917                                              &error_string, &unix_name);
     
    597925
    598926                if (memcmp(user_sess_key, zeros, 16) != 0) {
    599                         *user_session_key = data_blob_talloc(mem_ctx, user_sess_key, 16);
    600                 }
    601                 ntlmssp_state->callback_private = talloc_strdup(ntlmssp_state,
    602                                                                 unix_name);
     927                        *session_key = data_blob_talloc(mem_ctx, user_sess_key, 16);
     928                }
     929                *server_returned_info = talloc_strdup(mem_ctx,
     930                                                      unix_name);
    603931        } else {
    604932                DEBUG(NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED) ? 0 : 3,
    605933                      ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n",
    606                        ntlmssp_state->domain, ntlmssp_state->user,
    607                        ntlmssp_state->client.netbios_name,
     934                       user_info->client.domain_name, user_info->client.account_name,
     935                       user_info->workstation_name,
    608936                       error_string ? error_string : "unknown error (NULL)"));
    609                 ntlmssp_state->callback_private = NULL;
    610937        }
    611938
     
    615942}
    616943
    617 static NTSTATUS local_pw_check(struct ntlmssp_state *ntlmssp_state, TALLOC_CTX *mem_ctx,
    618                                DATA_BLOB *user_session_key, DATA_BLOB *lm_session_key)
     944static NTSTATUS local_pw_check(struct auth4_context *auth4_context,
     945                                TALLOC_CTX *mem_ctx,
     946                                const struct auth_usersupplied_info *user_info,
     947                                void **server_returned_info,
     948                                DATA_BLOB *session_key, DATA_BLOB *lm_session_key)
    619949{
    620950        NTSTATUS nt_status;
     
    625955        nt_status = ntlm_password_check(mem_ctx,
    626956                                        true, true, 0,
    627                                         &ntlmssp_state->chal,
    628                                         &ntlmssp_state->lm_resp,
    629                                         &ntlmssp_state->nt_resp,
    630                                         ntlmssp_state->user,
    631                                         ntlmssp_state->user,
    632                                         ntlmssp_state->domain,
    633                                         &lm_pw, &nt_pw, user_session_key, lm_session_key);
     957                                        &auth4_context->challenge.data,
     958                                        &user_info->password.response.lanman,
     959                                        &user_info->password.response.nt,
     960                                        user_info->client.account_name,
     961                                        user_info->client.account_name,
     962                                        user_info->client.domain_name,
     963                                        &lm_pw, &nt_pw, session_key, lm_session_key);
    634964
    635965        if (NT_STATUS_IS_OK(nt_status)) {
    636                 ntlmssp_state->callback_private = talloc_asprintf(ntlmssp_state,
    637                                                               "%s%c%s", ntlmssp_state->domain,
    638                                                               *lp_winbind_separator(),
    639                                                               ntlmssp_state->user);
     966                *server_returned_info = talloc_asprintf(mem_ctx,
     967                                                        "%s%c%s", user_info->client.domain_name,
     968                                                        *lp_winbind_separator(),
     969                                                        user_info->client.account_name);
    640970        } else {
    641971                DEBUG(3, ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n",
    642                           ntlmssp_state->domain, ntlmssp_state->user,
    643                           ntlmssp_state->client.netbios_name,
     972                          user_info->client.domain_name, user_info->client.account_name,
     973                          user_info->workstation_name,
    644974                          nt_errstr(nt_status)));
    645                 ntlmssp_state->callback_private = NULL;
    646975        }
    647976        return nt_status;
    648977}
    649978
    650 static NTSTATUS ntlm_auth_start_ntlmssp_client(struct ntlmssp_state **client_ntlmssp_state)
    651 {
    652         NTSTATUS status;
    653         if ( (opt_username == NULL) || (opt_domain == NULL) ) {
    654                 status = NT_STATUS_UNSUCCESSFUL;
    655                 DEBUG(1, ("Need username and domain for NTLMSSP\n"));
    656                 return NT_STATUS_INVALID_PARAMETER;
    657         }
    658 
    659         status = ntlmssp_client_start(NULL,
    660                                       global_myname(),
    661                                       lp_workgroup(),
    662                                       lp_client_ntlmv2_auth(),
    663                                       client_ntlmssp_state);
    664 
    665         if (!NT_STATUS_IS_OK(status)) {
    666                 DEBUG(1, ("Could not start NTLMSSP client: %s\n",
    667                           nt_errstr(status)));
    668                 TALLOC_FREE(*client_ntlmssp_state);
    669                 return status;
    670         }
    671 
    672         status = ntlmssp_set_username(*client_ntlmssp_state, opt_username);
    673 
    674         if (!NT_STATUS_IS_OK(status)) {
    675                 DEBUG(1, ("Could not set username: %s\n",
    676                           nt_errstr(status)));
    677                 TALLOC_FREE(*client_ntlmssp_state);
    678                 return status;
    679         }
    680 
    681         status = ntlmssp_set_domain(*client_ntlmssp_state, opt_domain);
    682 
    683         if (!NT_STATUS_IS_OK(status)) {
    684                 DEBUG(1, ("Could not set domain: %s\n",
    685                           nt_errstr(status)));
    686                 TALLOC_FREE(*client_ntlmssp_state);
    687                 return status;
    688         }
    689 
     979static NTSTATUS ntlm_auth_prepare_gensec_client(TALLOC_CTX *mem_ctx,
     980                                                struct loadparm_context *lp_ctx,
     981                                                struct gensec_security **gensec_security_out)
     982{
     983        struct gensec_security *gensec_security = NULL;
     984        NTSTATUS nt_status;
     985        TALLOC_CTX *tmp_ctx;
     986        const struct gensec_security_ops **backends = NULL;
     987        struct gensec_settings *gensec_settings = NULL;
     988        size_t idx = 0;
     989
     990        tmp_ctx = talloc_new(mem_ctx);
     991        NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
     992
     993        gensec_settings = lpcfg_gensec_settings(tmp_ctx, lp_ctx);
     994        if (gensec_settings == NULL) {
     995                DEBUG(10, ("lpcfg_gensec_settings failed\n"));
     996                TALLOC_FREE(tmp_ctx);
     997                return NT_STATUS_NO_MEMORY;
     998        }
     999
     1000        backends = talloc_zero_array(gensec_settings,
     1001                                     const struct gensec_security_ops *, 4);
     1002        if (backends == NULL) {
     1003                TALLOC_FREE(tmp_ctx);
     1004                return NT_STATUS_NO_MEMORY;
     1005        }
     1006        gensec_settings->backends = backends;
     1007
     1008        gensec_init();
     1009
     1010        /* These need to be in priority order, krb5 before NTLMSSP */
     1011#if defined(HAVE_KRB5)
     1012        backends[idx++] = &gensec_gse_krb5_security_ops;
     1013#endif
     1014
     1015        backends[idx++] = gensec_security_by_oid(NULL, GENSEC_OID_NTLMSSP);
     1016
     1017        backends[idx++] = gensec_security_by_oid(NULL, GENSEC_OID_SPNEGO);
     1018
     1019        nt_status = gensec_client_start(NULL, &gensec_security,
     1020                                        gensec_settings);
     1021        if (!NT_STATUS_IS_OK(nt_status)) {
     1022                TALLOC_FREE(tmp_ctx);
     1023                return nt_status;
     1024        }
     1025
     1026        talloc_unlink(tmp_ctx, gensec_settings);
     1027
     1028        if (opt_target_service != NULL) {
     1029                nt_status = gensec_set_target_service(gensec_security,
     1030                                                      opt_target_service);
     1031                if (!NT_STATUS_IS_OK(nt_status)) {
     1032                        TALLOC_FREE(tmp_ctx);
     1033                        return nt_status;
     1034                }
     1035        }
     1036
     1037        if (opt_target_hostname != NULL) {
     1038                nt_status = gensec_set_target_hostname(gensec_security,
     1039                                                       opt_target_hostname);
     1040                if (!NT_STATUS_IS_OK(nt_status)) {
     1041                        TALLOC_FREE(tmp_ctx);
     1042                        return nt_status;
     1043                }
     1044        }
     1045
     1046        *gensec_security_out = talloc_steal(mem_ctx, gensec_security);
     1047        TALLOC_FREE(tmp_ctx);
     1048        return NT_STATUS_OK;
     1049}
     1050
     1051static struct auth4_context *make_auth4_context_ntlm_auth(TALLOC_CTX *mem_ctx, bool local_pw)
     1052{
     1053        struct auth4_context *auth4_context = talloc_zero(mem_ctx, struct auth4_context);
     1054        if (auth4_context == NULL) {
     1055                DEBUG(10, ("failed to allocate auth4_context failed\n"));
     1056                return NULL;
     1057        }
     1058        auth4_context->generate_session_info = ntlm_auth_generate_session_info;
     1059        auth4_context->generate_session_info_pac = ntlm_auth_generate_session_info_pac;
     1060        auth4_context->get_ntlm_challenge = ntlm_auth_get_challenge;
     1061        auth4_context->set_ntlm_challenge = ntlm_auth_set_challenge;
     1062        if (local_pw) {
     1063                auth4_context->check_ntlm_password = local_pw_check;
     1064        } else {
     1065                auth4_context->check_ntlm_password = winbind_pw_check;
     1066        }
     1067        auth4_context->private_data = NULL;
     1068        return auth4_context;
     1069}
     1070
     1071static NTSTATUS ntlm_auth_prepare_gensec_server(TALLOC_CTX *mem_ctx,
     1072                                                struct loadparm_context *lp_ctx,
     1073                                                struct gensec_security **gensec_security_out)
     1074{
     1075        struct gensec_security *gensec_security;
     1076        NTSTATUS nt_status;
     1077
     1078        TALLOC_CTX *tmp_ctx;
     1079        const struct gensec_security_ops **backends;
     1080        struct gensec_settings *gensec_settings;
     1081        size_t idx = 0;
     1082        struct cli_credentials *server_credentials;
     1083       
     1084        struct auth4_context *auth4_context;
     1085
     1086        tmp_ctx = talloc_new(mem_ctx);
     1087        NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
     1088
     1089        auth4_context = make_auth4_context_ntlm_auth(tmp_ctx, opt_password);
     1090        if (auth4_context == NULL) {
     1091                TALLOC_FREE(tmp_ctx);
     1092                return NT_STATUS_NO_MEMORY;
     1093        }
     1094       
     1095        gensec_settings = lpcfg_gensec_settings(tmp_ctx, lp_ctx);
     1096        if (lp_ctx == NULL) {
     1097                DEBUG(10, ("lpcfg_gensec_settings failed\n"));
     1098                TALLOC_FREE(tmp_ctx);
     1099                return NT_STATUS_NO_MEMORY;
     1100        }
     1101       
     1102        /*
     1103         * This should be a 'netbios domain -> DNS domain'
     1104         * mapping, and can currently validly return NULL on
     1105         * poorly configured systems.
     1106         *
     1107         * This is used for the NTLMSSP server
     1108         *
     1109         */
    6901110        if (opt_password) {
    691                 status = ntlmssp_set_password(*client_ntlmssp_state, opt_password);
    692 
    693                 if (!NT_STATUS_IS_OK(status)) {
    694                         DEBUG(1, ("Could not set password: %s\n",
    695                                   nt_errstr(status)));
    696                         TALLOC_FREE(*client_ntlmssp_state);
    697                         return status;
    698                 }
    699         }
    700 
     1111                gensec_settings->server_netbios_name = lp_netbios_name();
     1112                gensec_settings->server_netbios_domain = lp_workgroup();
     1113        } else {
     1114                gensec_settings->server_netbios_name = get_winbind_netbios_name();
     1115                gensec_settings->server_netbios_domain = get_winbind_domain();
     1116        }
     1117       
     1118        gensec_settings->server_dns_domain = strlower_talloc(gensec_settings,
     1119                                                             get_mydnsdomname(talloc_tos()));
     1120        gensec_settings->server_dns_name = strlower_talloc(gensec_settings,
     1121                                                           get_mydnsfullname());
     1122       
     1123        backends = talloc_zero_array(gensec_settings,
     1124                                     const struct gensec_security_ops *, 4);
     1125       
     1126        if (backends == NULL) {
     1127                TALLOC_FREE(tmp_ctx);
     1128                return NT_STATUS_NO_MEMORY;
     1129        }
     1130        gensec_settings->backends = backends;
     1131
     1132        gensec_init();
     1133       
     1134        /* These need to be in priority order, krb5 before NTLMSSP */
     1135#if defined(HAVE_KRB5)
     1136        backends[idx++] = &gensec_gse_krb5_security_ops;
     1137#endif
     1138
     1139        backends[idx++] = gensec_security_by_oid(NULL, GENSEC_OID_NTLMSSP);
     1140
     1141        backends[idx++] = gensec_security_by_oid(NULL, GENSEC_OID_SPNEGO);
     1142
     1143        /*
     1144         * This is anonymous for now, because we just use it
     1145         * to set the kerberos state at the moment
     1146         */
     1147        server_credentials = cli_credentials_init_anon(tmp_ctx);
     1148        if (!server_credentials) {
     1149                DEBUG(0, ("auth_generic_prepare: Failed to init server credentials\n"));
     1150                return NT_STATUS_NO_MEMORY;
     1151        }
     1152       
     1153        cli_credentials_set_conf(server_credentials, lp_ctx);
     1154       
     1155        if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC || lp_security() == SEC_ADS || USE_KERBEROS_KEYTAB) {
     1156                cli_credentials_set_kerberos_state(server_credentials, CRED_AUTO_USE_KERBEROS);
     1157        } else {
     1158                cli_credentials_set_kerberos_state(server_credentials, CRED_DONT_USE_KERBEROS);
     1159        }
     1160       
     1161        nt_status = gensec_server_start(tmp_ctx, gensec_settings,
     1162                                        auth4_context, &gensec_security);
     1163       
     1164        if (!NT_STATUS_IS_OK(nt_status)) {
     1165                TALLOC_FREE(tmp_ctx);
     1166                return nt_status;
     1167        }
     1168       
     1169        gensec_set_credentials(gensec_security, server_credentials);
     1170       
     1171        gensec_want_feature(gensec_security, GENSEC_FEATURE_SIGN);
     1172        gensec_want_feature(gensec_security, GENSEC_FEATURE_SEAL);
     1173
     1174        talloc_unlink(tmp_ctx, lp_ctx);
     1175        talloc_unlink(tmp_ctx, server_credentials);
     1176        talloc_unlink(tmp_ctx, gensec_settings);
     1177        talloc_unlink(tmp_ctx, auth4_context);
     1178
     1179        *gensec_security_out = talloc_steal(mem_ctx, gensec_security);
     1180        TALLOC_FREE(tmp_ctx);
    7011181        return NT_STATUS_OK;
    7021182}
    7031183
    704 static NTSTATUS ntlm_auth_start_ntlmssp_server(struct ntlmssp_state **ntlmssp_state)
    705 {
    706         NTSTATUS status;
    707         const char *netbios_name;
    708         const char *netbios_domain;
    709         const char *dns_name;
    710         char *dns_domain;
    711         bool is_standalone = false;
    712 
    713         if (opt_password) {
    714                 netbios_name = global_myname();
    715                 netbios_domain = lp_workgroup();
    716         } else {
    717                 netbios_name = get_winbind_netbios_name();
    718                 netbios_domain = get_winbind_domain();
    719         }
    720         /* This should be a 'netbios domain -> DNS domain' mapping */
    721         dns_domain = get_mydnsdomname(talloc_tos());
    722         if (dns_domain) {
    723                 strlower_m(dns_domain);
    724         }
    725         dns_name = get_mydnsfullname();
    726 
    727         status = ntlmssp_server_start(NULL,
    728                                       is_standalone,
    729                                       netbios_name,
    730                                       netbios_domain,
    731                                       dns_name,
    732                                       dns_domain,
    733                                       ntlmssp_state);
    734         if (!NT_STATUS_IS_OK(status)) {
    735                 DEBUG(1, ("Could not start NTLMSSP server: %s\n",
    736                           nt_errstr(status)));
    737                 return status;
    738         }
    739 
    740         /* Have we been given a local password, or should we ask winbind? */
    741         if (opt_password) {
    742                 (*ntlmssp_state)->check_password = local_pw_check;
    743         } else {
    744                 (*ntlmssp_state)->check_password = winbind_pw_check;
    745         }
    746         return NT_STATUS_OK;
    747 }
    748 
    749 /*******************************************************************
    750  Used by firefox to drive NTLM auth to IIS servers.
    751 *******************************************************************/
    752 
    753 static NTSTATUS do_ccache_ntlm_auth(DATA_BLOB initial_msg, DATA_BLOB challenge_msg,
    754                                 DATA_BLOB *reply)
    755 {
    756         struct winbindd_request wb_request;
    757         struct winbindd_response wb_response;
    758         int ctrl = 0;
    759         NSS_STATUS result;
    760 
    761         /* get winbindd to do the ntlmssp step on our behalf */
    762         ZERO_STRUCT(wb_request);
    763         ZERO_STRUCT(wb_response);
    764 
    765         /*
    766          * This is tricky here. If we set krb5_auth in pam_winbind.conf
    767          * creds for users in trusted domain will be stored the winbindd
    768          * child of the trusted domain. If we ask the primary domain for
    769          * ntlm_ccache_auth, it will fail. So, we have to ask the trusted
    770          * domain's child for ccache_ntlm_auth. that is to say, we have to
    771          * set WBFLAG_PAM_CONTACT_TRUSTDOM in request.flags.
    772          */
    773         ctrl = get_pam_winbind_config();
    774 
    775         if (ctrl & WINBIND_KRB5_AUTH) {
    776                 wb_request.flags |= WBFLAG_PAM_CONTACT_TRUSTDOM;
    777         }
    778 
    779         fstr_sprintf(wb_request.data.ccache_ntlm_auth.user,
    780                 "%s%c%s", opt_domain, winbind_separator(), opt_username);
    781         wb_request.data.ccache_ntlm_auth.uid = geteuid();
    782         wb_request.data.ccache_ntlm_auth.initial_blob_len = initial_msg.length;
    783         wb_request.data.ccache_ntlm_auth.challenge_blob_len = challenge_msg.length;
    784         wb_request.extra_len = initial_msg.length + challenge_msg.length;
    785 
    786         if (wb_request.extra_len > 0) {
    787                 wb_request.extra_data.data = SMB_MALLOC_ARRAY(char, wb_request.extra_len);
    788                 if (wb_request.extra_data.data == NULL) {
    789                         return NT_STATUS_NO_MEMORY;
    790                 }
    791 
    792                 memcpy(wb_request.extra_data.data, initial_msg.data, initial_msg.length);
    793                 memcpy(wb_request.extra_data.data + initial_msg.length,
    794                         challenge_msg.data, challenge_msg.length);
    795         }
    796 
    797         result = winbindd_request_response(WINBINDD_CCACHE_NTLMAUTH, &wb_request, &wb_response);
    798         SAFE_FREE(wb_request.extra_data.data);
    799 
    800         if (result != NSS_STATUS_SUCCESS) {
    801                 winbindd_free_response(&wb_response);
    802                 return NT_STATUS_UNSUCCESSFUL;
    803         }
    804 
    805         if (reply) {
    806                 *reply = data_blob(wb_response.extra_data.data,
    807                                 wb_response.data.ccache_ntlm_auth.auth_blob_len);
    808                 if (wb_response.data.ccache_ntlm_auth.auth_blob_len > 0 &&
    809                                 reply->data == NULL) {
    810                         winbindd_free_response(&wb_response);
    811                         return NT_STATUS_NO_MEMORY;
    812                 }
    813         }
    814 
    815         winbindd_free_response(&wb_response);
    816         return NT_STATUS_MORE_PROCESSING_REQUIRED;
    817 }
    818 
    819 static void manage_squid_ntlmssp_request_int(struct ntlm_auth_state *state,
    820                                              char *buf, int length,
    821                                              TALLOC_CTX *mem_ctx,
    822                                              char **response)
    823 {
    824         DATA_BLOB request, reply;
    825         NTSTATUS nt_status;
    826 
    827         if (strlen(buf) < 2) {
    828                 DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf));
    829                 *response = talloc_strdup(mem_ctx, "BH NTLMSSP query invalid");
    830                 return;
    831         }
    832 
    833         if (strlen(buf) > 3) {
    834                 if(strncmp(buf, "SF ", 3) == 0){
    835                         DEBUG(10, ("Setting flags to negotioate\n"));
    836                         TALLOC_FREE(state->want_feature_list);
    837                         state->want_feature_list = talloc_strdup(state->mem_ctx,
    838                                         buf+3);
    839                         *response = talloc_strdup(mem_ctx, "OK");
    840                         return;
    841                 }
    842                 request = base64_decode_data_blob(buf + 3);
    843         } else {
    844                 request = data_blob_null;
    845         }
    846 
    847         if ((strncmp(buf, "PW ", 3) == 0)) {
    848                 /* The calling application wants us to use a local password
    849                  * (rather than winbindd) */
    850 
    851                 opt_password = SMB_STRNDUP((const char *)request.data,
    852                                 request.length);
    853 
    854                 if (opt_password == NULL) {
    855                         DEBUG(1, ("Out of memory\n"));
    856                         *response = talloc_strdup(mem_ctx, "BH Out of memory");
    857                         data_blob_free(&request);
    858                         return;
    859                 }
    860 
    861                 *response = talloc_strdup(mem_ctx, "OK");
    862                 data_blob_free(&request);
    863                 return;
    864         }
    865 
    866         if (strncmp(buf, "YR", 2) == 0) {
    867                 TALLOC_FREE(state->ntlmssp_state);
    868                 state->svr_state = SERVER_INITIAL;
    869         } else if (strncmp(buf, "KK", 2) == 0) {
    870                 /* No special preprocessing required */
    871         } else if (strncmp(buf, "GF", 2) == 0) {
    872                 DEBUG(10, ("Requested negotiated NTLMSSP flags\n"));
    873 
    874                 if (state->svr_state == SERVER_FINISHED) {
    875                         *response = talloc_asprintf(mem_ctx, "GF 0x%08x",
    876                                                  state->neg_flags);
    877                 }
    878                 else {
    879                         *response = talloc_strdup(mem_ctx, "BH\n");
    880                 }
    881                 data_blob_free(&request);
    882                 return;
    883         } else if (strncmp(buf, "GK", 2) == 0) {
    884                 DEBUG(10, ("Requested NTLMSSP session key\n"));
    885                 if(state->have_session_key) {
    886                         char *key64 = base64_encode_data_blob(state->mem_ctx,
    887                                         state->session_key);
    888                         *response = talloc_asprintf(mem_ctx, "GK %s",
    889                                                  key64 ? key64 : "<NULL>");
    890                         TALLOC_FREE(key64);
    891                 } else {
    892                         *response = talloc_strdup(mem_ctx, "BH");
    893                 }
    894 
    895                 data_blob_free(&request);
    896                 return;
    897         } else {
    898                 DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf));
    899                 *response = talloc_strdup(mem_ctx, "BH NTLMSSP query invalid");
    900                 return;
    901         }
    902 
    903         if (!state->ntlmssp_state) {
    904                 nt_status = ntlm_auth_start_ntlmssp_server(
    905                                 &state->ntlmssp_state);
    906                 if (!NT_STATUS_IS_OK(nt_status)) {
    907                         *response = talloc_asprintf(
    908                                 mem_ctx, "BH %s", nt_errstr(nt_status));
    909                         return;
    910                 }
    911                 ntlmssp_want_feature_list(state->ntlmssp_state,
    912                                 state->want_feature_list);
    913         }
    914 
    915         DEBUG(10, ("got NTLMSSP packet:\n"));
    916         dump_data(10, request.data, request.length);
    917 
    918         nt_status = ntlmssp_update(state->ntlmssp_state, request, &reply);
    919 
    920         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
    921                 char *reply_base64 = base64_encode_data_blob(state->mem_ctx,
    922                                 reply);
    923                 *response = talloc_asprintf(mem_ctx, "TT %s", reply_base64);
    924                 TALLOC_FREE(reply_base64);
    925                 data_blob_free(&reply);
    926                 state->svr_state = SERVER_CHALLENGE;
    927                 DEBUG(10, ("NTLMSSP challenge\n"));
    928         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
    929                 *response = talloc_asprintf(mem_ctx, "BH %s",
    930                                          nt_errstr(nt_status));
    931                 DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status)));
    932 
    933                 TALLOC_FREE(state->ntlmssp_state);
    934         } else if (!NT_STATUS_IS_OK(nt_status)) {
    935                 *response = talloc_asprintf(mem_ctx, "NA %s",
    936                                          nt_errstr(nt_status));
    937                 DEBUG(10, ("NTLMSSP %s\n", nt_errstr(nt_status)));
    938         } else {
    939                 *response = talloc_asprintf(
    940                         mem_ctx, "AF %s",
    941                         (char *)state->ntlmssp_state->callback_private);
    942                 DEBUG(10, ("NTLMSSP OK!\n"));
    943 
    944                 if(state->have_session_key)
    945                         data_blob_free(&state->session_key);
    946                 state->session_key = data_blob(
    947                                 state->ntlmssp_state->session_key.data,
    948                                 state->ntlmssp_state->session_key.length);
    949                 state->neg_flags = state->ntlmssp_state->neg_flags;
    950                 state->have_session_key = true;
    951                 state->svr_state = SERVER_FINISHED;
    952         }
    953 
    954         data_blob_free(&request);
    955 }
    956 
    957 static void manage_squid_ntlmssp_request(struct ntlm_auth_state *state,
    958                                          char *buf, int length)
    959 {
    960         char *response;
    961 
    962         manage_squid_ntlmssp_request_int(state, buf, length,
    963                                          talloc_tos(), &response);
    964 
    965         if (response == NULL) {
    966                 x_fprintf(x_stdout, "BH Out of memory\n");
    967                 return;
    968         }
    969         x_fprintf(x_stdout, "%s\n", response);
    970         TALLOC_FREE(response);
    971 }
    972 
    973 static void manage_client_ntlmssp_request(struct ntlm_auth_state *state,
    974                                                 char *buf, int length)
    975 {
    976         DATA_BLOB request, reply;
    977         NTSTATUS nt_status;
    978 
    979         if (!opt_username || !*opt_username) {
    980                 x_fprintf(x_stderr, "username must be specified!\n\n");
    981                 exit(1);
    982         }
    983 
    984         if (strlen(buf) < 2) {
    985                 DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf));
    986                 x_fprintf(x_stdout, "BH NTLMSSP query invalid\n");
    987                 return;
    988         }
    989 
    990         if (strlen(buf) > 3) {
    991                 if(strncmp(buf, "SF ", 3) == 0) {
    992                         DEBUG(10, ("Looking for flags to negotiate\n"));
    993                         talloc_free(state->want_feature_list);
    994                         state->want_feature_list = talloc_strdup(state->mem_ctx,
    995                                         buf+3);
    996                         x_fprintf(x_stdout, "OK\n");
    997                         return;
    998                 }
    999                 request = base64_decode_data_blob(buf + 3);
    1000         } else {
    1001                 request = data_blob_null;
    1002         }
    1003 
    1004         if (strncmp(buf, "PW ", 3) == 0) {
    1005                 /* We asked for a password and obviously got it :-) */
    1006 
    1007                 opt_password = SMB_STRNDUP((const char *)request.data,
    1008                                 request.length);
    1009 
    1010                 if (opt_password == NULL) {
    1011                         DEBUG(1, ("Out of memory\n"));
    1012                         x_fprintf(x_stdout, "BH Out of memory\n");
    1013                         data_blob_free(&request);
    1014                         return;
    1015                 }
    1016 
    1017                 x_fprintf(x_stdout, "OK\n");
    1018                 data_blob_free(&request);
    1019                 return;
    1020         }
    1021 
    1022         if (!state->ntlmssp_state && use_cached_creds) {
    1023                 /* check whether cached credentials are usable. */
    1024                 DATA_BLOB empty_blob = data_blob_null;
    1025 
    1026                 nt_status = do_ccache_ntlm_auth(empty_blob, empty_blob, NULL);
    1027                 if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
    1028                         /* failed to use cached creds */
    1029                         use_cached_creds = False;
    1030                 }
    1031         }
    1032 
    1033         if (opt_password == NULL && !use_cached_creds) {
    1034                 /* Request a password from the calling process.  After
    1035                    sending it, the calling process should retry asking for the
    1036                    negotiate. */
    1037 
    1038                 DEBUG(10, ("Requesting password\n"));
    1039                 x_fprintf(x_stdout, "PW\n");
    1040                 return;
    1041         }
    1042 
    1043         if (strncmp(buf, "YR", 2) == 0) {
    1044                 TALLOC_FREE(state->ntlmssp_state);
    1045                 state->cli_state = CLIENT_INITIAL;
    1046         } else if (strncmp(buf, "TT", 2) == 0) {
    1047                 /* No special preprocessing required */
    1048         } else if (strncmp(buf, "GF", 2) == 0) {
    1049                 DEBUG(10, ("Requested negotiated NTLMSSP flags\n"));
    1050 
    1051                 if(state->cli_state == CLIENT_FINISHED) {
    1052                         x_fprintf(x_stdout, "GF 0x%08x\n", state->neg_flags);
    1053                 }
    1054                 else {
    1055                         x_fprintf(x_stdout, "BH\n");
    1056                 }
    1057 
    1058                 data_blob_free(&request);
    1059                 return;
    1060         } else if (strncmp(buf, "GK", 2) == 0 ) {
    1061                 DEBUG(10, ("Requested session key\n"));
    1062 
    1063                 if(state->cli_state == CLIENT_FINISHED) {
    1064                         char *key64 = base64_encode_data_blob(state->mem_ctx,
    1065                                         state->session_key);
    1066                         x_fprintf(x_stdout, "GK %s\n", key64?key64:"<NULL>");
    1067                         TALLOC_FREE(key64);
    1068                 }
    1069                 else {
    1070                         x_fprintf(x_stdout, "BH\n");
    1071                 }
    1072 
    1073                 data_blob_free(&request);
    1074                 return;
    1075         } else {
    1076                 DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf));
    1077                 x_fprintf(x_stdout, "BH NTLMSSP query invalid\n");
    1078                 return;
    1079         }
    1080 
    1081         if (!state->ntlmssp_state) {
    1082                 nt_status = ntlm_auth_start_ntlmssp_client(
    1083                                 &state->ntlmssp_state);
    1084                 if (!NT_STATUS_IS_OK(nt_status)) {
    1085                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
    1086                         return;
    1087                 }
    1088                 ntlmssp_want_feature_list(state->ntlmssp_state,
    1089                                 state->want_feature_list);
    1090                 state->initial_message = data_blob_null;
    1091         }
    1092 
    1093         DEBUG(10, ("got NTLMSSP packet:\n"));
    1094         dump_data(10, request.data, request.length);
    1095 
    1096         if (use_cached_creds && !opt_password &&
    1097                         (state->cli_state == CLIENT_RESPONSE)) {
    1098                 nt_status = do_ccache_ntlm_auth(state->initial_message, request,
    1099                                 &reply);
    1100         } else {
    1101                 nt_status = ntlmssp_update(state->ntlmssp_state, request,
    1102                                 &reply);
    1103         }
    1104 
    1105         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
    1106                 char *reply_base64 = base64_encode_data_blob(state->mem_ctx,
    1107                                 reply);
    1108                 if (state->cli_state == CLIENT_INITIAL) {
    1109                         x_fprintf(x_stdout, "YR %s\n", reply_base64);
    1110                         state->initial_message = reply;
    1111                         state->cli_state = CLIENT_RESPONSE;
    1112                 } else {
    1113                         x_fprintf(x_stdout, "KK %s\n", reply_base64);
    1114                         data_blob_free(&reply);
    1115                 }
    1116                 TALLOC_FREE(reply_base64);
    1117                 DEBUG(10, ("NTLMSSP challenge\n"));
    1118         } else if (NT_STATUS_IS_OK(nt_status)) {
    1119                 char *reply_base64 = base64_encode_data_blob(talloc_tos(),
    1120                                 reply);
    1121                 x_fprintf(x_stdout, "AF %s\n", reply_base64);
    1122                 TALLOC_FREE(reply_base64);
    1123 
    1124                 if(state->have_session_key)
    1125                         data_blob_free(&state->session_key);
    1126 
    1127                 state->session_key = data_blob(
    1128                                 state->ntlmssp_state->session_key.data,
    1129                                 state->ntlmssp_state->session_key.length);
    1130                 state->neg_flags = state->ntlmssp_state->neg_flags;
    1131                 state->have_session_key = true;
    1132 
    1133                 DEBUG(10, ("NTLMSSP OK!\n"));
    1134                 state->cli_state = CLIENT_FINISHED;
    1135                 TALLOC_FREE(state->ntlmssp_state);
    1136         } else {
    1137                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
    1138                 DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status)));
    1139                 state->cli_state = CLIENT_ERROR;
    1140                 TALLOC_FREE(state->ntlmssp_state);
    1141         }
    1142 
    1143         data_blob_free(&request);
    1144 }
    1145 
    1146 static void manage_squid_basic_request(struct ntlm_auth_state *state,
    1147                                         char *buf, int length)
     1184static void manage_client_ntlmssp_request(enum stdio_helper_mode stdio_helper_mode,
     1185                                   struct loadparm_context *lp_ctx,
     1186                                   struct ntlm_auth_state *state,
     1187                                                char *buf, int length, void **private2)
     1188{
     1189        manage_gensec_request(stdio_helper_mode, lp_ctx, buf, length, &state->gensec_private_1);
     1190        return;
     1191}
     1192
     1193static void manage_squid_basic_request(enum stdio_helper_mode stdio_helper_mode,
     1194                                   struct loadparm_context *lp_ctx,
     1195                                   struct ntlm_auth_state *state,
     1196                                        char *buf, int length, void **private2)
    11481197{
    11491198        char *user, *pass;     
     
    11711220}
    11721221
    1173 static void offer_gss_spnego_mechs(void) {
    1174 
    1175         DATA_BLOB token;
    1176         struct spnego_data spnego;
    1177         ssize_t len;
    1178         char *reply_base64;
    1179         TALLOC_CTX *ctx = talloc_tos();
    1180         char *principal;
    1181         char *myname_lower;
    1182 
    1183         ZERO_STRUCT(spnego);
    1184 
    1185         myname_lower = talloc_strdup(ctx, global_myname());
    1186         if (!myname_lower) {
     1222static void manage_gensec_request(enum stdio_helper_mode stdio_helper_mode,
     1223                                  struct loadparm_context *lp_ctx,
     1224                                  char *buf, int length, void **private1)
     1225{
     1226        DATA_BLOB in;
     1227        DATA_BLOB out = data_blob(NULL, 0);
     1228        char *out_base64 = NULL;
     1229        const char *reply_arg = NULL;
     1230        struct gensec_ntlm_state {
     1231                struct gensec_security *gensec_state;
     1232                const char *set_password;
     1233        };
     1234        struct gensec_ntlm_state *state;
     1235
     1236        NTSTATUS nt_status;
     1237        bool first = false;
     1238        const char *reply_code;
     1239        struct cli_credentials *creds;
     1240
     1241        static char *want_feature_list = NULL;
     1242        static DATA_BLOB session_key;
     1243
     1244        TALLOC_CTX *mem_ctx;
     1245
     1246        if (*private1) {
     1247                state = (struct gensec_ntlm_state *)*private1;
     1248        } else {
     1249                state = talloc_zero(NULL, struct gensec_ntlm_state);
     1250                if (!state) {
     1251                        x_fprintf(x_stdout, "BH No Memory\n");
     1252                        exit(1);
     1253                }
     1254                *private1 = state;
     1255                if (opt_password) {
     1256                        state->set_password = opt_password;
     1257                }
     1258        }
     1259
     1260        if (strlen(buf) < 2) {
     1261                DEBUG(1, ("query [%s] invalid", buf));
     1262                x_fprintf(x_stdout, "BH Query invalid\n");
    11871263                return;
    11881264        }
    1189         strlower_m(myname_lower);
    1190 
    1191         principal = talloc_asprintf(ctx, "%s$@%s", myname_lower, lp_realm());
    1192         if (!principal) {
     1265
     1266        if (strlen(buf) > 3) {
     1267                if(strncmp(buf, "SF ", 3) == 0) {
     1268                        DEBUG(10, ("Setting flags to negotiate\n"));
     1269                        talloc_free(want_feature_list);
     1270                        want_feature_list = talloc_strndup(state, buf+3, strlen(buf)-3);
     1271                        x_fprintf(x_stdout, "OK\n");
     1272                        return;
     1273                }
     1274                in = base64_decode_data_blob(buf + 3);
     1275        } else {
     1276                in = data_blob(NULL, 0);
     1277        }
     1278
     1279        if (strncmp(buf, "YR", 2) == 0) {
     1280                if (state->gensec_state) {
     1281                        talloc_free(state->gensec_state);
     1282                        state->gensec_state = NULL;
     1283                }
     1284        } else if ( (strncmp(buf, "OK", 2) == 0)) {
     1285                /* Just return BH, like ntlm_auth from Samba 3 does. */
     1286                x_fprintf(x_stdout, "BH Command expected\n");
     1287                data_blob_free(&in);
    11931288                return;
    1194         }
    1195 
    1196         /* Server negTokenInit (mech offerings) */
    1197         spnego.type = SPNEGO_NEG_TOKEN_INIT;
    1198         spnego.negTokenInit.mechTypes = talloc_array(ctx, const char *, 4);
    1199 #ifdef HAVE_KRB5
    1200         spnego.negTokenInit.mechTypes[0] = talloc_strdup(ctx, OID_KERBEROS5_OLD);
    1201         spnego.negTokenInit.mechTypes[1] = talloc_strdup(ctx, OID_KERBEROS5);
    1202         spnego.negTokenInit.mechTypes[2] = talloc_strdup(ctx, OID_NTLMSSP);
    1203         spnego.negTokenInit.mechTypes[3] = NULL;
    1204 #else
    1205         spnego.negTokenInit.mechTypes[0] = talloc_strdup(ctx, OID_NTLMSSP);
    1206         spnego.negTokenInit.mechTypes[1] = NULL;
    1207 #endif
    1208 
    1209 
    1210         spnego.negTokenInit.mechListMIC = data_blob_talloc(ctx, principal,
    1211                                                     strlen(principal));
    1212 
    1213         len = spnego_write_data(ctx, &token, &spnego);
    1214         spnego_free_data(&spnego);
    1215 
    1216         if (len == -1) {
    1217                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
    1218                 x_fprintf(x_stdout, "BH Could not write SPNEGO data blob\n");
     1289        } else if ( (strncmp(buf, "TT ", 3) != 0) &&
     1290                    (strncmp(buf, "KK ", 3) != 0) &&
     1291                    (strncmp(buf, "AF ", 3) != 0) &&
     1292                    (strncmp(buf, "NA ", 3) != 0) &&
     1293                    (strncmp(buf, "UG", 2) != 0) &&
     1294                    (strncmp(buf, "PW ", 3) != 0) &&
     1295                    (strncmp(buf, "GK", 2) != 0) &&
     1296                    (strncmp(buf, "GF", 2) != 0)) {
     1297                DEBUG(1, ("SPNEGO request [%s] invalid prefix\n", buf));
     1298                x_fprintf(x_stdout, "BH SPNEGO request invalid prefix\n");
     1299                data_blob_free(&in);
    12191300                return;
    12201301        }
    12211302
    1222         reply_base64 = base64_encode_data_blob(talloc_tos(), token);
    1223         x_fprintf(x_stdout, "TT %s *\n", reply_base64);
    1224 
    1225         TALLOC_FREE(reply_base64);
    1226         data_blob_free(&token);
    1227         DEBUG(10, ("sent SPNEGO negTokenInit\n"));
    1228         return;
    1229 }
    1230 
    1231 bool spnego_parse_krb5_wrap(TALLOC_CTX *ctx, DATA_BLOB blob, DATA_BLOB *ticket, uint8 tok_id[2])
    1232 {
    1233         bool ret;
    1234         ASN1_DATA *data;
    1235         int data_remaining;
    1236 
    1237         data = asn1_init(talloc_tos());
    1238         if (data == NULL) {
    1239                 return false;
    1240         }
    1241 
    1242         asn1_load(data, blob);
    1243         asn1_start_tag(data, ASN1_APPLICATION(0));
    1244         asn1_check_OID(data, OID_KERBEROS5);
    1245 
    1246         data_remaining = asn1_tag_remaining(data);
    1247 
    1248         if (data_remaining < 3) {
    1249                 data->has_error = True;
     1303        mem_ctx = talloc_named(NULL, 0, "manage_gensec_request internal mem_ctx");
     1304
     1305        /* setup gensec */
     1306        if (!(state->gensec_state)) {
     1307                switch (stdio_helper_mode) {
     1308                case GSS_SPNEGO_CLIENT:
     1309                        /*
     1310                         * cached credentials are only supported by
     1311                         * NTLMSSP_CLIENT_1 for now.
     1312                         */
     1313                        use_cached_creds = false;
     1314                        /* fall through */
     1315                case NTLMSSP_CLIENT_1:
     1316                        /* setup the client side */
     1317
     1318                        if (state->set_password != NULL) {
     1319                                use_cached_creds = false;
     1320                        }
     1321
     1322                        if (use_cached_creds) {
     1323                                struct wbcCredentialCacheParams params;
     1324                                struct wbcCredentialCacheInfo *info = NULL;
     1325                                struct wbcAuthErrorInfo *error = NULL;
     1326                                wbcErr wbc_status;
     1327
     1328                                params.account_name = opt_username;
     1329                                params.domain_name = opt_domain;
     1330                                params.level = WBC_CREDENTIAL_CACHE_LEVEL_NTLMSSP;
     1331                                params.num_blobs = 0;
     1332                                params.blobs = NULL;
     1333
     1334                                wbc_status = wbcCredentialCache(&params, &info,
     1335                                                                &error);
     1336                                wbcFreeMemory(error);
     1337                                if (!WBC_ERROR_IS_OK(wbc_status)) {
     1338                                        use_cached_creds = false;
     1339                                }
     1340                                wbcFreeMemory(info);
     1341                        }
     1342
     1343                        nt_status = ntlm_auth_prepare_gensec_client(state, lp_ctx,
     1344                                                                    &state->gensec_state);
     1345                        if (!NT_STATUS_IS_OK(nt_status)) {
     1346                                x_fprintf(x_stdout, "BH GENSEC mech failed to start: %s\n", nt_errstr(nt_status));
     1347                                talloc_free(mem_ctx);
     1348                                return;
     1349                        }
     1350
     1351                        creds = cli_credentials_init(state->gensec_state);
     1352                        cli_credentials_set_conf(creds, lp_ctx);
     1353                        if (opt_username) {
     1354                                cli_credentials_set_username(creds, opt_username, CRED_SPECIFIED);
     1355                        }
     1356                        if (opt_domain) {
     1357                                cli_credentials_set_domain(creds, opt_domain, CRED_SPECIFIED);
     1358                        }
     1359                        if (use_cached_creds) {
     1360                                gensec_want_feature(state->gensec_state,
     1361                                                    GENSEC_FEATURE_NTLM_CCACHE);
     1362                        } else if (state->set_password) {
     1363                                cli_credentials_set_password(creds, state->set_password, CRED_SPECIFIED);
     1364                        } else {
     1365                                cli_credentials_set_password_callback(creds, get_password);
     1366                        }
     1367                        if (opt_workstation) {
     1368                                cli_credentials_set_workstation(creds, opt_workstation, CRED_SPECIFIED);
     1369                        }
     1370
     1371                        gensec_set_credentials(state->gensec_state, creds);
     1372
     1373                        break;
     1374                case GSS_SPNEGO_SERVER:
     1375                case SQUID_2_5_NTLMSSP:
     1376                {
     1377                        nt_status = ntlm_auth_prepare_gensec_server(state, lp_ctx,
     1378                                                                    &state->gensec_state);
     1379                        if (!NT_STATUS_IS_OK(nt_status)) {
     1380                                x_fprintf(x_stdout, "BH GENSEC mech failed to start: %s\n", nt_errstr(nt_status));
     1381                                talloc_free(mem_ctx);
     1382                                return;
     1383                        }
     1384                        break;
     1385                }
     1386                default:
     1387                        talloc_free(mem_ctx);
     1388                        abort();
     1389                }
     1390
     1391                gensec_want_feature_list(state->gensec_state, want_feature_list);
     1392
     1393                switch (stdio_helper_mode) {
     1394                case GSS_SPNEGO_CLIENT:
     1395                case GSS_SPNEGO_SERVER:
     1396                        nt_status = gensec_start_mech_by_oid(state->gensec_state, GENSEC_OID_SPNEGO);
     1397                        if (!in.length) {
     1398                                first = true;
     1399                        }
     1400                        break;
     1401                case NTLMSSP_CLIENT_1:
     1402                        if (!in.length) {
     1403                                first = true;
     1404                        }
     1405                        /* fall through */
     1406                case SQUID_2_5_NTLMSSP:
     1407                        nt_status = gensec_start_mech_by_oid(state->gensec_state, GENSEC_OID_NTLMSSP);
     1408                        break;
     1409                default:
     1410                        talloc_free(mem_ctx);
     1411                        abort();
     1412                }
     1413
     1414                if (!NT_STATUS_IS_OK(nt_status)) {
     1415                        DEBUG(1, ("GENSEC mech failed to start: %s\n", nt_errstr(nt_status)));
     1416                        x_fprintf(x_stdout, "BH GENSEC mech failed to start\n");
     1417                        talloc_free(mem_ctx);
     1418                        return;
     1419                }
     1420
     1421        }
     1422
     1423        /* update */
     1424
     1425        if (strncmp(buf, "PW ", 3) == 0) {
     1426                state->set_password = talloc_strndup(state,
     1427                                                     (const char *)in.data,
     1428                                                     in.length);
     1429
     1430                cli_credentials_set_password(gensec_get_credentials(state->gensec_state),
     1431                                             state->set_password,
     1432                                             CRED_SPECIFIED);
     1433                x_fprintf(x_stdout, "OK\n");
     1434                data_blob_free(&in);
     1435                talloc_free(mem_ctx);
     1436                return;
     1437        }
     1438
     1439        if (strncmp(buf, "GK", 2) == 0) {
     1440                char *base64_key;
     1441                DEBUG(10, ("Requested session key\n"));
     1442                nt_status = gensec_session_key(state->gensec_state, mem_ctx, &session_key);
     1443                if(!NT_STATUS_IS_OK(nt_status)) {
     1444                        DEBUG(1, ("gensec_session_key failed: %s\n", nt_errstr(nt_status)));
     1445                        x_fprintf(x_stdout, "BH No session key\n");
     1446                        talloc_free(mem_ctx);
     1447                        return;
     1448                } else {
     1449                        base64_key = base64_encode_data_blob(state, session_key);
     1450                        x_fprintf(x_stdout, "GK %s\n", base64_key);
     1451                        talloc_free(base64_key);
     1452                }
     1453                talloc_free(mem_ctx);
     1454                return;
     1455        }
     1456
     1457        if (strncmp(buf, "GF", 2) == 0) {
     1458                uint32_t neg_flags;
     1459
     1460                DEBUG(10, ("Requested negotiated NTLMSSP feature flags\n"));
     1461
     1462                neg_flags = gensec_ntlmssp_neg_flags(state->gensec_state);
     1463                if (neg_flags == 0) {
     1464                        x_fprintf(x_stdout, "BH\n");
     1465                        return;
     1466                }
     1467
     1468                x_fprintf(x_stdout, "GF 0x%08x\n", neg_flags);
     1469                return;
     1470        }
     1471
     1472        nt_status = gensec_update(state->gensec_state, mem_ctx, in, &out);
     1473
     1474        /* don't leak 'bad password'/'no such user' info to the network client */
     1475        nt_status = nt_status_squash(nt_status);
     1476
     1477        if (out.length) {
     1478                out_base64 = base64_encode_data_blob(mem_ctx, out);
    12501479        } else {
    1251                 asn1_read(data, tok_id, 2);
    1252                 data_remaining -= 2;
    1253                 *ticket = data_blob_talloc(ctx, NULL, data_remaining);
    1254                 asn1_read(data, ticket->data, ticket->length);
    1255         }
    1256 
    1257         asn1_end_tag(data);
    1258 
    1259         ret = !data->has_error;
    1260 
    1261         if (data->has_error) {
    1262                 data_blob_free(ticket);
    1263         }
    1264 
    1265         asn1_free(data);
    1266 
    1267         return ret;
    1268 }
    1269 
    1270 static void manage_gss_spnego_request(struct ntlm_auth_state *state,
    1271                                         char *buf, int length)
    1272 {
    1273         struct spnego_data request, response;
    1274         DATA_BLOB token;
    1275         DATA_BLOB raw_in_token = data_blob_null;
    1276         DATA_BLOB raw_out_token = data_blob_null;
    1277         NTSTATUS status;
    1278         ssize_t len;
    1279         TALLOC_CTX *ctx = talloc_tos();
    1280 
    1281         char *user = NULL;
    1282         char *domain = NULL;
    1283 
    1284         const char *reply_code;
    1285         char       *reply_base64;
    1286         char *reply_argument = NULL;
    1287         char *supportedMech = NULL;
    1288 
    1289         if (strlen(buf) < 2) {
    1290                 DEBUG(1, ("SPENGO query [%s] invalid\n", buf));
    1291                 x_fprintf(x_stdout, "BH SPENGO query invalid\n");
    1292                 return;
    1293         }
    1294 
    1295         if (strncmp(buf, "YR", 2) == 0) {
    1296                 TALLOC_FREE(state->ntlmssp_state);
    1297                 TALLOC_FREE(state->spnego_mech);
    1298                 TALLOC_FREE(state->spnego_mech_oid);
    1299         } else if (strncmp(buf, "KK", 2) == 0) {
    1300                 ;
     1480                out_base64 = NULL;
     1481        }
     1482
     1483        if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
     1484                reply_arg = "*";
     1485                if (first && state->gensec_state->gensec_role == GENSEC_CLIENT) {
     1486                        reply_code = "YR";
     1487                } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) {
     1488                        reply_code = "KK";
     1489                } else if (state->gensec_state->gensec_role == GENSEC_SERVER) {
     1490                        reply_code = "TT";
     1491                } else {
     1492                        abort();
     1493                }
     1494
     1495
     1496        } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
     1497                reply_code = "BH NT_STATUS_ACCESS_DENIED";
     1498                reply_arg = nt_errstr(nt_status);
     1499                DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
     1500        } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_UNSUCCESSFUL)) {
     1501                reply_code = "BH NT_STATUS_UNSUCCESSFUL";
     1502                reply_arg = nt_errstr(nt_status);
     1503                DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
     1504        } else if (!NT_STATUS_IS_OK(nt_status)) {
     1505                reply_code = "NA";
     1506                reply_arg = nt_errstr(nt_status);
     1507                DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
     1508        } else if /* OK */ (state->gensec_state->gensec_role == GENSEC_SERVER) {
     1509                struct auth_session_info *session_info;
     1510
     1511                nt_status = gensec_session_info(state->gensec_state, mem_ctx, &session_info);
     1512                if (!NT_STATUS_IS_OK(nt_status)) {
     1513                        reply_code = "BH Failed to retrive session info";
     1514                        reply_arg = nt_errstr(nt_status);
     1515                        DEBUG(1, ("GENSEC failed to retrieve the session info: %s\n", nt_errstr(nt_status)));
     1516                } else {
     1517
     1518                        reply_code = "AF";
     1519                        reply_arg = talloc_strdup(state->gensec_state, session_info->unix_info->unix_name);
     1520                        if (reply_arg == NULL) {
     1521                                reply_code = "BH out of memory";
     1522                                reply_arg = nt_errstr(NT_STATUS_NO_MEMORY);
     1523                        }
     1524                        talloc_free(session_info);
     1525                }
     1526        } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) {
     1527                reply_code = "AF";
     1528                reply_arg = out_base64;
    13011529        } else {
    1302                 DEBUG(1, ("SPENGO query [%s] invalid\n", buf));
    1303                 x_fprintf(x_stdout, "BH SPENGO query invalid\n");
    1304                 return;
    1305         }
    1306 
    1307         if ( (strlen(buf) == 2)) {
    1308 
    1309                 /* no client data, get the negTokenInit offering
    1310                    mechanisms */
    1311 
    1312                 offer_gss_spnego_mechs();
    1313                 return;
    1314         }
    1315 
    1316         /* All subsequent requests have a blob. This might be negTokenInit or negTokenTarg */
    1317 
    1318         if (strlen(buf) <= 3) {
    1319                 DEBUG(1, ("GSS-SPNEGO query [%s] invalid\n", buf));
    1320                 x_fprintf(x_stdout, "BH GSS-SPNEGO query invalid\n");
    1321                 return;
    1322         }
    1323 
    1324         token = base64_decode_data_blob(buf + 3);
    1325 
    1326         if ((token.length >= 7)
    1327             && (strncmp((char *)token.data, "NTLMSSP", 7) == 0)) {
    1328                 char *reply;
    1329 
    1330                 data_blob_free(&token);
    1331 
    1332                 DEBUG(10, ("Could not parse GSS-SPNEGO, trying raw "
    1333                            "ntlmssp\n"));
    1334 
    1335                 manage_squid_ntlmssp_request_int(state, buf, length,
    1336                                                  talloc_tos(), &reply);
    1337                 if (reply == NULL) {
    1338                         x_fprintf(x_stdout, "BH Out of memory\n");
    1339                         return;
    1340                 }
    1341 
    1342                 if (strncmp(reply, "AF ", 3) == 0) {
    1343                         x_fprintf(x_stdout, "AF * %s\n", reply+3);
    1344                 } else {
    1345                         x_fprintf(x_stdout, "%s *\n", reply);
    1346                 }
    1347 
    1348                 TALLOC_FREE(reply);
    1349                 return;
    1350         }
    1351 
    1352         ZERO_STRUCT(request);
    1353         len = spnego_read_data(ctx, token, &request);
    1354         data_blob_free(&token);
    1355 
    1356         if (len == -1) {
    1357                 DEBUG(1, ("GSS-SPNEGO query [%s] invalid\n", buf));
    1358                 x_fprintf(x_stdout, "BH GSS-SPNEGO query invalid\n");
    1359                 return;
    1360         }
    1361 
    1362         if (request.type == SPNEGO_NEG_TOKEN_INIT) {
    1363 #ifdef HAVE_KRB5
    1364                 int krb5_idx = -1;
    1365 #endif
    1366                 int ntlm_idx = -1;
    1367                 int used_idx = -1;
    1368                 int i;
    1369 
    1370                 if (state->spnego_mech) {
    1371                         DEBUG(1, ("Client restarted SPNEGO with NegTokenInit "
    1372                                   "while mech[%s] was already negotiated\n",
    1373                                   state->spnego_mech));
    1374                         x_fprintf(x_stdout, "BH Client send NegTokenInit twice\n");
    1375                         return;
    1376                 }
    1377 
    1378                 /* Second request from Client. This is where the
    1379                    client offers its mechanism to use. */
    1380 
    1381                 if ( (request.negTokenInit.mechTypes == NULL) ||
    1382                      (request.negTokenInit.mechTypes[0] == NULL) ) {
    1383                         DEBUG(1, ("Client did not offer any mechanism\n"));
    1384                         x_fprintf(x_stdout, "BH Client did not offer any "
    1385                                             "mechanism\n");
    1386                         return;
    1387                 }
    1388 
    1389                 status = NT_STATUS_UNSUCCESSFUL;
    1390                 for (i = 0; request.negTokenInit.mechTypes[i] != NULL; i++) {
    1391                         DEBUG(10,("got mech[%d][%s]\n",
    1392                                 i, request.negTokenInit.mechTypes[i]));
    1393 #ifdef HAVE_KRB5
    1394                         if (strcmp(request.negTokenInit.mechTypes[i], OID_KERBEROS5_OLD) == 0) {
    1395                                 krb5_idx = i;
    1396                                 break;
    1397                         }
    1398                         if (strcmp(request.negTokenInit.mechTypes[i], OID_KERBEROS5) == 0) {
    1399                                 krb5_idx = i;
    1400                                 break;
    1401                         }
    1402 #endif
    1403                         if (strcmp(request.negTokenInit.mechTypes[i], OID_NTLMSSP) == 0) {
    1404                                 ntlm_idx = i;
    1405                                 break;
    1406                         }
    1407                 }
    1408 
    1409                 used_idx = ntlm_idx;
    1410 #ifdef HAVE_KRB5
    1411                 if (krb5_idx != -1) {
    1412                         ntlm_idx = -1;
    1413                         used_idx = krb5_idx;
    1414                 }
    1415 #endif
    1416                 if (ntlm_idx > -1) {
    1417                         state->spnego_mech = talloc_strdup(state, "ntlmssp");
    1418                         if (state->spnego_mech == NULL) {
    1419                                 x_fprintf(x_stdout, "BH Out of memory\n");
    1420                                 return;
    1421                         }
    1422 
    1423                         if (state->ntlmssp_state) {
    1424                                 DEBUG(1, ("Client wants a new NTLMSSP challenge, but "
    1425                                           "already got one\n"));
    1426                                 x_fprintf(x_stdout, "BH Client wants a new "
    1427                                                     "NTLMSSP challenge, but "
    1428                                                     "already got one\n");
    1429                                 TALLOC_FREE(state->ntlmssp_state);
    1430                                 return;
    1431                         }
    1432 
    1433                         status = ntlm_auth_start_ntlmssp_server(&state->ntlmssp_state);
    1434                         if (!NT_STATUS_IS_OK(status)) {
    1435                                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
    1436                                 return;
    1437                         }
    1438                 }
    1439 
    1440 #ifdef HAVE_KRB5
    1441                 if (krb5_idx > -1) {
    1442                         state->spnego_mech = talloc_strdup(state, "krb5");
    1443                         if (state->spnego_mech == NULL) {
    1444                                 x_fprintf(x_stdout, "BH Out of memory\n");
    1445                                 return;
    1446                         }
    1447                 }
    1448 #endif
    1449                 if (used_idx > -1) {
    1450                         state->spnego_mech_oid = talloc_strdup(state,
    1451                                 request.negTokenInit.mechTypes[used_idx]);
    1452                         if (state->spnego_mech_oid == NULL) {
    1453                                 x_fprintf(x_stdout, "BH Out of memory\n");
    1454                                 return;
    1455                         }
    1456                         supportedMech = talloc_strdup(ctx, state->spnego_mech_oid);
    1457                         if (supportedMech == NULL) {
    1458                                 x_fprintf(x_stdout, "BH Out of memory\n");
    1459                                 return;
    1460                         }
    1461 
    1462                         status = NT_STATUS_MORE_PROCESSING_REQUIRED;
    1463                 } else {
    1464                         status = NT_STATUS_NOT_SUPPORTED;
    1465                 }
    1466                 if (used_idx == 0) {
    1467                         status = NT_STATUS_OK;
    1468                         raw_in_token = request.negTokenInit.mechToken;
    1469                 }
    1470         } else {
    1471                 if (state->spnego_mech == NULL) {
    1472                         DEBUG(1,("Got netTokenTarg without negTokenInit\n"));
    1473                         x_fprintf(x_stdout, "BH Got a negTokenTarg without "
    1474                                             "negTokenInit\n");
    1475                         return;
    1476                 }
    1477 
    1478                 if ((request.negTokenTarg.supportedMech != NULL) &&
    1479                      (strcmp(request.negTokenTarg.supportedMech, state->spnego_mech_oid) != 0 ) ) {
    1480                         DEBUG(1, ("Got a negTokenTarg with mech[%s] while [%s] was already negotiated\n",
    1481                                   request.negTokenTarg.supportedMech,
    1482                                   state->spnego_mech_oid));
    1483                         x_fprintf(x_stdout, "BH Got a negTokenTarg with speficied mech\n");
    1484                         return;
    1485                 }
    1486 
    1487                 status = NT_STATUS_OK;
    1488                 raw_in_token = request.negTokenTarg.responseToken;
    1489         }
    1490 
    1491         if (!NT_STATUS_IS_OK(status)) {
    1492                 /* error or more processing */
    1493         } else if (strcmp(state->spnego_mech, "ntlmssp") == 0) {
    1494 
    1495                 DEBUG(10, ("got NTLMSSP packet:\n"));
    1496                 dump_data(10, raw_in_token.data, raw_in_token.length);
    1497 
    1498                 status = ntlmssp_update(state->ntlmssp_state,
    1499                                         raw_in_token,
    1500                                         &raw_out_token);
    1501                 if (NT_STATUS_IS_OK(status)) {
    1502                         user = talloc_strdup(ctx, state->ntlmssp_state->user);
    1503                         domain = talloc_strdup(ctx, state->ntlmssp_state->domain);
    1504                 }
    1505                 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
    1506                         TALLOC_FREE(state->ntlmssp_state);
    1507                 }
    1508 #ifdef HAVE_KRB5
    1509         } else if (strcmp(state->spnego_mech, "krb5") == 0) {
    1510                 char *principal;
    1511                 DATA_BLOB ap_rep;
    1512                 DATA_BLOB session_key;
    1513                 struct PAC_LOGON_INFO *logon_info = NULL;
    1514                 DATA_BLOB ticket;
    1515                 uint8_t tok_id[2];
    1516 
    1517                 if (!spnego_parse_krb5_wrap(ctx, raw_in_token,
    1518                                             &ticket, tok_id)) {
    1519                         DEBUG(1, ("spnego_parse_krb5_wrap failed\n"));
    1520                         x_fprintf(x_stdout, "BH spnego_parse_krb5_wrap failed\n");
    1521                         return;
    1522                 }
    1523 
    1524                 status = ads_verify_ticket(ctx, lp_realm(), 0,
    1525                                            &ticket,
    1526                                            &principal, &logon_info, &ap_rep,
    1527                                            &session_key, True);
    1528 
    1529                 /* Now in "principal" we have the name we are authenticated as. */
    1530 
    1531                 if (NT_STATUS_IS_OK(status)) {
    1532 
    1533                         domain = strchr_m(principal, '@');
    1534 
    1535                         if (domain == NULL) {
    1536                                 DEBUG(1, ("Did not get a valid principal "
    1537                                           "from ads_verify_ticket\n"));
    1538                                 x_fprintf(x_stdout, "BH Did not get a "
    1539                                           "valid principal from "
    1540                                           "ads_verify_ticket\n");
    1541                                 return;
    1542                         }
    1543 
    1544                         *domain++ = '\0';
    1545                         domain = talloc_strdup(ctx, domain);
    1546                         user = talloc_strdup(ctx, principal);
    1547 
    1548                         if (logon_info) {
    1549                                 netsamlogon_cache_store(
    1550                                         user, &logon_info->info3);
    1551                         }
    1552 
    1553                         data_blob_free(&ap_rep);
    1554                         data_blob_free(&session_key);
    1555                 }
    1556                 data_blob_free(&ticket);
    1557 #endif
    1558         }
    1559 
    1560         spnego_free_data(&request);
    1561         ZERO_STRUCT(response);
    1562         response.type = SPNEGO_NEG_TOKEN_TARG;
    1563 
    1564         if (NT_STATUS_IS_OK(status)) {
    1565                 TALLOC_FREE(state->spnego_mech);
    1566                 TALLOC_FREE(state->spnego_mech_oid);
    1567                 response.negTokenTarg.negResult = SPNEGO_ACCEPT_COMPLETED;
    1568                 response.negTokenTarg.responseToken = raw_out_token;
    1569                 reply_code = "AF";
    1570                 reply_argument = talloc_asprintf(ctx, "%s\\%s", domain, user);
    1571         } else if (NT_STATUS_EQUAL(status,
    1572                                    NT_STATUS_MORE_PROCESSING_REQUIRED)) {
    1573                 response.negTokenTarg.supportedMech = supportedMech;
    1574                 response.negTokenTarg.responseToken = raw_out_token;
    1575                 response.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
    1576                 reply_code = "TT";
    1577                 reply_argument = talloc_strdup(ctx, "*");
    1578         } else {
    1579                 TALLOC_FREE(state->spnego_mech);
    1580                 TALLOC_FREE(state->spnego_mech_oid);
    1581                 data_blob_free(&raw_out_token);
    1582                 response.negTokenTarg.negResult = SPNEGO_REJECT;
    1583                 reply_code = "NA";
    1584                 reply_argument = talloc_strdup(ctx, nt_errstr(status));
    1585         }
    1586 
    1587         if (!reply_argument) {
    1588                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
    1589                 x_fprintf(x_stdout, "BH Could not write SPNEGO data blob\n");
    1590                 spnego_free_data(&response);
    1591                 return;
    1592         }
    1593 
    1594         len = spnego_write_data(ctx, &token, &response);
    1595         spnego_free_data(&response);
    1596 
    1597         if (len == -1) {
    1598                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
    1599                 x_fprintf(x_stdout, "BH Could not write SPNEGO data blob\n");
    1600                 return;
    1601         }
    1602 
    1603         reply_base64 = base64_encode_data_blob(talloc_tos(), token);
    1604 
    1605         x_fprintf(x_stdout, "%s %s %s\n",
    1606                   reply_code, reply_base64, reply_argument);
    1607 
    1608         TALLOC_FREE(reply_base64);
    1609         data_blob_free(&token);
    1610 
    1611         return;
    1612 }
    1613 
    1614 static struct ntlmssp_state *client_ntlmssp_state = NULL;
    1615 
    1616 static bool manage_client_ntlmssp_init(struct spnego_data spnego)
    1617 {
    1618         NTSTATUS status;
    1619         DATA_BLOB null_blob = data_blob_null;
    1620         DATA_BLOB to_server;
    1621         char *to_server_base64;
    1622         const char *my_mechs[] = {OID_NTLMSSP, NULL};
    1623         TALLOC_CTX *ctx = talloc_tos();
    1624 
    1625         DEBUG(10, ("Got spnego negTokenInit with NTLMSSP\n"));
    1626 
    1627         if (client_ntlmssp_state != NULL) {
    1628                 DEBUG(1, ("Request for initial SPNEGO request where "
    1629                           "we already have a state\n"));
    1630                 return False;
    1631         }
    1632 
    1633         if (!client_ntlmssp_state) {
    1634                 if (!NT_STATUS_IS_OK(status = ntlm_auth_start_ntlmssp_client(&client_ntlmssp_state))) {
    1635                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
    1636                         return False;
    1637                 }
    1638         }
    1639 
    1640 
    1641         if (opt_password == NULL) {
    1642 
    1643                 /* Request a password from the calling process.  After
    1644                    sending it, the calling process should retry with
    1645                    the negTokenInit. */
    1646 
    1647                 DEBUG(10, ("Requesting password\n"));
    1648                 x_fprintf(x_stdout, "PW\n");
    1649                 return True;
    1650         }
    1651 
    1652         spnego.type = SPNEGO_NEG_TOKEN_INIT;
    1653         spnego.negTokenInit.mechTypes = my_mechs;
    1654         spnego.negTokenInit.reqFlags = data_blob_null;
    1655         spnego.negTokenInit.reqFlagsPadding = 0;
    1656         spnego.negTokenInit.mechListMIC = null_blob;
    1657 
    1658         status = ntlmssp_update(client_ntlmssp_state, null_blob,
    1659                                        &spnego.negTokenInit.mechToken);
    1660 
    1661         if ( !(NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) ||
    1662                         NT_STATUS_IS_OK(status)) ) {
    1663                 DEBUG(1, ("Expected OK or MORE_PROCESSING_REQUIRED, got: %s\n",
    1664                           nt_errstr(status)));
    1665                 TALLOC_FREE(client_ntlmssp_state);
    1666                 return False;
    1667         }
    1668 
    1669         spnego_write_data(ctx, &to_server, &spnego);
    1670         data_blob_free(&spnego.negTokenInit.mechToken);
    1671 
    1672         to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server);
    1673         data_blob_free(&to_server);
    1674         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
    1675         TALLOC_FREE(to_server_base64);
    1676         return True;
    1677 }
    1678 
    1679 static void manage_client_ntlmssp_targ(struct spnego_data spnego)
    1680 {
    1681         NTSTATUS status;
    1682         DATA_BLOB null_blob = data_blob_null;
    1683         DATA_BLOB request;
    1684         DATA_BLOB to_server;
    1685         char *to_server_base64;
    1686         TALLOC_CTX *ctx = talloc_tos();
    1687 
    1688         DEBUG(10, ("Got spnego negTokenTarg with NTLMSSP\n"));
    1689 
    1690         if (client_ntlmssp_state == NULL) {
    1691                 DEBUG(1, ("Got NTLMSSP tArg without a client state\n"));
    1692                 x_fprintf(x_stdout, "BH Got NTLMSSP tArg without a client state\n");
    1693                 return;
    1694         }
    1695 
    1696         if (spnego.negTokenTarg.negResult == SPNEGO_REJECT) {
    1697                 x_fprintf(x_stdout, "NA\n");
    1698                 TALLOC_FREE(client_ntlmssp_state);
    1699                 return;
    1700         }
    1701 
    1702         if (spnego.negTokenTarg.negResult == SPNEGO_ACCEPT_COMPLETED) {
    1703                 x_fprintf(x_stdout, "AF\n");
    1704                 TALLOC_FREE(client_ntlmssp_state);
    1705                 return;
    1706         }
    1707 
    1708         status = ntlmssp_update(client_ntlmssp_state,
    1709                                        spnego.negTokenTarg.responseToken,
    1710                                        &request);
    1711 
    1712         if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
    1713                 DEBUG(1, ("Expected MORE_PROCESSING_REQUIRED from "
    1714                           "ntlmssp_client_update, got: %s\n",
    1715                           nt_errstr(status)));
    1716                 x_fprintf(x_stdout, "BH Expected MORE_PROCESSING_REQUIRED from "
    1717                                     "ntlmssp_client_update\n");
    1718                 data_blob_free(&request);
    1719                 TALLOC_FREE(client_ntlmssp_state);
    1720                 return;
    1721         }
    1722 
    1723         spnego.type = SPNEGO_NEG_TOKEN_TARG;
    1724         spnego.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
    1725         spnego.negTokenTarg.supportedMech = (char *)OID_NTLMSSP;
    1726         spnego.negTokenTarg.responseToken = request;
    1727         spnego.negTokenTarg.mechListMIC = null_blob;
    1728 
    1729         spnego_write_data(ctx, &to_server, &spnego);
    1730         data_blob_free(&request);
    1731 
    1732         to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server);
    1733         data_blob_free(&to_server);
    1734         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
    1735         TALLOC_FREE(to_server_base64);
    1736         return;
    1737 }
    1738 
    1739 #ifdef HAVE_KRB5
    1740 
    1741 static bool manage_client_krb5_init(struct spnego_data spnego)
    1742 {
    1743         char *principal;
    1744         DATA_BLOB tkt, to_server;
    1745         DATA_BLOB session_key_krb5 = data_blob_null;
    1746         struct spnego_data reply;
    1747         char *reply_base64;
    1748         int retval;
    1749 
    1750         const char *my_mechs[] = {OID_KERBEROS5_OLD, NULL};
    1751         ssize_t len;
    1752         TALLOC_CTX *ctx = talloc_tos();
    1753 
    1754         if ( (spnego.negTokenInit.mechListMIC.data == NULL) ||
    1755              (spnego.negTokenInit.mechListMIC.length == 0) ) {
    1756                 DEBUG(1, ("Did not get a principal for krb5\n"));
    1757                 return False;
    1758         }
    1759 
    1760         principal = (char *)SMB_MALLOC(
    1761                 spnego.negTokenInit.mechListMIC.length+1);
    1762 
    1763         if (principal == NULL) {
    1764                 DEBUG(1, ("Could not malloc principal\n"));
    1765                 return False;
    1766         }
    1767 
    1768         memcpy(principal, spnego.negTokenInit.mechListMIC.data,
    1769                spnego.negTokenInit.mechListMIC.length);
    1770         principal[spnego.negTokenInit.mechListMIC.length] = '\0';
    1771 
    1772         retval = cli_krb5_get_ticket(ctx, principal, 0,
    1773                                           &tkt, &session_key_krb5,
    1774                                           0, NULL, NULL, NULL);
    1775         if (retval) {
    1776                 char *user = NULL;
    1777 
    1778                 /* Let's try to first get the TGT, for that we need a
    1779                    password. */
    1780 
    1781                 if (opt_password == NULL) {
    1782                         DEBUG(10, ("Requesting password\n"));
    1783                         x_fprintf(x_stdout, "PW\n");
    1784                         return True;
    1785                 }
    1786 
    1787                 user = talloc_asprintf(talloc_tos(), "%s@%s", opt_username, opt_domain);
    1788                 if (!user) {
    1789                         return false;
    1790                 }
    1791 
    1792                 if ((retval = kerberos_kinit_password(user, opt_password, 0, NULL))) {
    1793                         DEBUG(10, ("Requesting TGT failed: %s\n", error_message(retval)));
    1794                         return False;
    1795                 }
    1796 
    1797                 retval = cli_krb5_get_ticket(ctx, principal, 0,
    1798                                                   &tkt, &session_key_krb5,
    1799                                                   0, NULL, NULL, NULL);
    1800                 if (retval) {
    1801                         DEBUG(10, ("Kinit suceeded, but getting a ticket failed: %s\n", error_message(retval)));
    1802                         return False;
    1803                 }
    1804         }
    1805 
    1806         data_blob_free(&session_key_krb5);
    1807 
    1808         ZERO_STRUCT(reply);
    1809 
    1810         reply.type = SPNEGO_NEG_TOKEN_INIT;
    1811         reply.negTokenInit.mechTypes = my_mechs;
    1812         reply.negTokenInit.reqFlags = data_blob_null;
    1813         reply.negTokenInit.reqFlagsPadding = 0;
    1814         reply.negTokenInit.mechToken = tkt;
    1815         reply.negTokenInit.mechListMIC = data_blob_null;
    1816 
    1817         len = spnego_write_data(ctx, &to_server, &reply);
    1818         data_blob_free(&tkt);
    1819 
    1820         if (len == -1) {
    1821                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
    1822                 return False;
    1823         }
    1824 
    1825         reply_base64 = base64_encode_data_blob(talloc_tos(), to_server);
    1826         x_fprintf(x_stdout, "KK %s *\n", reply_base64);
    1827 
    1828         TALLOC_FREE(reply_base64);
    1829         data_blob_free(&to_server);
    1830         DEBUG(10, ("sent GSS-SPNEGO KERBEROS5 negTokenInit\n"));
    1831         return True;
    1832 }
    1833 
    1834 static void manage_client_krb5_targ(struct spnego_data spnego)
    1835 {
    1836         switch (spnego.negTokenTarg.negResult) {
    1837         case SPNEGO_ACCEPT_INCOMPLETE:
    1838                 DEBUG(1, ("Got a Kerberos negTokenTarg with ACCEPT_INCOMPLETE\n"));
    1839                 x_fprintf(x_stdout, "BH Got a Kerberos negTokenTarg with "
    1840                                     "ACCEPT_INCOMPLETE\n");
    1841                 break;
    1842         case SPNEGO_ACCEPT_COMPLETED:
    1843                 DEBUG(10, ("Accept completed\n"));
    1844                 x_fprintf(x_stdout, "AF\n");
    1845                 break;
    1846         case SPNEGO_REJECT:
    1847                 DEBUG(10, ("Rejected\n"));
    1848                 x_fprintf(x_stdout, "NA\n");
     1530                abort();
     1531        }
     1532
     1533        switch (stdio_helper_mode) {
     1534        case GSS_SPNEGO_SERVER:
     1535                x_fprintf(x_stdout, "%s %s %s\n", reply_code,
     1536                          out_base64 ? out_base64 : "*",
     1537                          reply_arg ? reply_arg : "*");
    18491538                break;
    18501539        default:
    1851                 DEBUG(1, ("Got an invalid negTokenTarg\n"));
    1852                 x_fprintf(x_stdout, "AF\n");
    1853         }
    1854 }
    1855 
    1856 #endif
    1857 
    1858 static void manage_gss_spnego_client_request(struct ntlm_auth_state *state,
    1859                                                 char *buf, int length)
    1860 {
    1861         DATA_BLOB request;
    1862         struct spnego_data spnego;
    1863         ssize_t len;
    1864         TALLOC_CTX *ctx = talloc_tos();
    1865 
    1866         if (!opt_username || !*opt_username) {
    1867                 x_fprintf(x_stderr, "username must be specified!\n\n");
    1868                 exit(1);
    1869         }
    1870 
    1871         if (strlen(buf) <= 3) {
    1872                 DEBUG(1, ("SPNEGO query [%s] too short\n", buf));
    1873                 x_fprintf(x_stdout, "BH SPNEGO query too short\n");
    1874                 return;
    1875         }
    1876 
    1877         request = base64_decode_data_blob(buf+3);
    1878 
    1879         if (strncmp(buf, "PW ", 3) == 0) {
    1880 
    1881                 /* We asked for a password and obviously got it :-) */
    1882 
    1883                 opt_password = SMB_STRNDUP((const char *)request.data, request.length);
    1884 
    1885                 if (opt_password == NULL) {
    1886                         DEBUG(1, ("Out of memory\n"));
    1887                         x_fprintf(x_stdout, "BH Out of memory\n");
    1888                         data_blob_free(&request);
    1889                         return;
    1890                 }
    1891 
    1892                 x_fprintf(x_stdout, "OK\n");
    1893                 data_blob_free(&request);
    1894                 return;
    1895         }
    1896 
    1897         if ( (strncmp(buf, "TT ", 3) != 0) &&
    1898              (strncmp(buf, "AF ", 3) != 0) &&
    1899              (strncmp(buf, "NA ", 3) != 0) ) {
    1900                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
    1901                 x_fprintf(x_stdout, "BH SPNEGO request invalid\n");
    1902                 data_blob_free(&request);
    1903                 return;
    1904         }
    1905 
    1906         /* So we got a server challenge to generate a SPNEGO
    1907            client-to-server request... */
    1908 
    1909         len = spnego_read_data(ctx, request, &spnego);
    1910         data_blob_free(&request);
    1911 
    1912         if (len == -1) {
    1913                 DEBUG(1, ("Could not read SPNEGO data for [%s]\n", buf));
    1914                 x_fprintf(x_stdout, "BH Could not read SPNEGO data\n");
    1915                 return;
    1916         }
    1917 
    1918         if (spnego.type == SPNEGO_NEG_TOKEN_INIT) {
    1919 
    1920                 /* The server offers a list of mechanisms */
    1921 
    1922                 const char **mechType = (const char **)spnego.negTokenInit.mechTypes;
    1923 
    1924                 while (*mechType != NULL) {
    1925 
    1926 #ifdef HAVE_KRB5
    1927                         if ( (strcmp(*mechType, OID_KERBEROS5_OLD) == 0) ||
    1928                              (strcmp(*mechType, OID_KERBEROS5) == 0) ) {
    1929                                 if (manage_client_krb5_init(spnego))
    1930                                         goto out;
    1931                         }
    1932 #endif
    1933 
    1934                         if (strcmp(*mechType, OID_NTLMSSP) == 0) {
    1935                                 if (manage_client_ntlmssp_init(spnego))
    1936                                         goto out;
    1937                         }
    1938 
    1939                         mechType++;
    1940                 }
    1941 
    1942                 DEBUG(1, ("Server offered no compatible mechanism\n"));
    1943                 x_fprintf(x_stdout, "BH Server offered no compatible mechanism\n");
    1944                 return;
    1945         }
    1946 
    1947         if (spnego.type == SPNEGO_NEG_TOKEN_TARG) {
    1948 
    1949                 if (spnego.negTokenTarg.supportedMech == NULL) {
    1950                         /* On accept/reject Windows does not send the
    1951                            mechanism anymore. Handle that here and
    1952                            shut down the mechanisms. */
    1953 
    1954                         switch (spnego.negTokenTarg.negResult) {
    1955                         case SPNEGO_ACCEPT_COMPLETED:
    1956                                 x_fprintf(x_stdout, "AF\n");
    1957                                 break;
    1958                         case SPNEGO_REJECT:
    1959                                 x_fprintf(x_stdout, "NA\n");
    1960                                 break;
    1961                         default:
    1962                                 DEBUG(1, ("Got a negTokenTarg with no mech and an "
    1963                                           "unknown negResult: %d\n",
    1964                                           spnego.negTokenTarg.negResult));
    1965                                 x_fprintf(x_stdout, "BH Got a negTokenTarg with"
    1966                                                     " no mech and an unknown "
    1967                                                     "negResult\n");
    1968                         }
    1969 
    1970                         TALLOC_FREE(client_ntlmssp_state);
    1971                         goto out;
    1972                 }
    1973 
    1974                 if (strcmp(spnego.negTokenTarg.supportedMech,
    1975                            OID_NTLMSSP) == 0) {
    1976                         manage_client_ntlmssp_targ(spnego);
    1977                         goto out;
    1978                 }
    1979 
    1980 #if HAVE_KRB5
    1981                 if (strcmp(spnego.negTokenTarg.supportedMech,
    1982                            OID_KERBEROS5_OLD) == 0) {
    1983                         manage_client_krb5_targ(spnego);
    1984                         goto out;
    1985                 }
    1986 #endif
    1987 
    1988         }
    1989 
    1990         DEBUG(1, ("Got an SPNEGO token I could not handle [%s]!\n", buf));
    1991         x_fprintf(x_stdout, "BH Got an SPNEGO token I could not handle\n");
     1540                if (out_base64) {
     1541                        x_fprintf(x_stdout, "%s %s\n", reply_code, out_base64);
     1542                } else if (reply_arg) {
     1543                        x_fprintf(x_stdout, "%s %s\n", reply_code, reply_arg);
     1544                } else {
     1545                        x_fprintf(x_stdout, "%s\n", reply_code);
     1546                }
     1547        }
     1548
     1549        talloc_free(mem_ctx);
    19921550        return;
    1993 
    1994  out:
    1995         spnego_free_data(&spnego);
     1551}
     1552
     1553static void manage_gss_spnego_request(enum stdio_helper_mode stdio_helper_mode,
     1554                                   struct loadparm_context *lp_ctx,
     1555                                   struct ntlm_auth_state *state,
     1556                                      char *buf, int length, void **private2)
     1557{
     1558        manage_gensec_request(stdio_helper_mode, lp_ctx, buf, length, &state->gensec_private_1);
    19961559        return;
    19971560}
    19981561
    1999 static void manage_ntlm_server_1_request(struct ntlm_auth_state *state,
    2000                                                 char *buf, int length)
     1562static void manage_squid_ntlmssp_request(enum stdio_helper_mode stdio_helper_mode,
     1563                                   struct loadparm_context *lp_ctx,
     1564                                   struct ntlm_auth_state *state,
     1565                                         char *buf, int length, void **private2)
     1566{
     1567        manage_gensec_request(stdio_helper_mode, lp_ctx, buf, length, &state->gensec_private_1);
     1568        return;
     1569}
     1570
     1571static void manage_gss_spnego_client_request(enum stdio_helper_mode stdio_helper_mode,
     1572                                   struct loadparm_context *lp_ctx,
     1573                                   struct ntlm_auth_state *state,
     1574                                             char *buf, int length, void **private2)
     1575{
     1576        manage_gensec_request(stdio_helper_mode, lp_ctx, buf, length, &state->gensec_private_1);
     1577        return;
     1578}
     1579
     1580static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode,
     1581                                   struct loadparm_context *lp_ctx,
     1582                                   struct ntlm_auth_state *state,
     1583                                                char *buf, int length, void **private2)
    20011584{
    20021585        char *request, *parameter;     
     
    20351618                        uchar lm_key[8];
    20361619                        uchar user_session_key[16];
    2037                         uint32 flags = 0;
    2038 
     1620                        uint32_t flags = 0;
     1621                        NTSTATUS nt_status;
    20391622                        if (full_username && !username) {
    20401623                                fstring fstr_user;
     
    20511634                        }
    20521635
    2053                         if (!domain) {
    2054                                 domain = smb_xstrdup(get_winbind_domain());
    2055                         }
    2056 
    2057                         if (ntlm_server_1_lm_session_key)
    2058                                 flags |= WBFLAG_PAM_LMKEY;
    2059 
    2060                         if (ntlm_server_1_user_session_key)
    2061                                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
    2062 
    2063                         if (!NT_STATUS_IS_OK(
    2064                                     contact_winbind_auth_crap(username,
    2065                                                               domain,
    2066                                                               global_myname(),
    2067                                                               &challenge,
    2068                                                               &lm_response,
    2069                                                               &nt_response,
    2070                                                               flags,
    2071                                                               lm_key,
    2072                                                               user_session_key,
    2073                                                               &error_string,
    2074                                                               NULL))) {
    2075 
     1636                        if (opt_password) {
     1637                                DATA_BLOB nt_session_key, lm_session_key;
     1638                                struct samr_Password lm_pw, nt_pw;
     1639                                TALLOC_CTX *mem_ctx = talloc_new(NULL);
     1640                                ZERO_STRUCT(user_session_key);
     1641                                ZERO_STRUCT(lm_key);
     1642
     1643                                nt_lm_owf_gen (opt_password, nt_pw.hash, lm_pw.hash);
     1644                                nt_status = ntlm_password_check(mem_ctx,
     1645                                                                true, true, 0,
     1646                                                                &challenge,
     1647                                                                &lm_response,
     1648                                                                &nt_response,
     1649                                                                username,
     1650                                                                username,
     1651                                                                domain,
     1652                                                                &lm_pw, &nt_pw,
     1653                                                                &nt_session_key,
     1654                                                                &lm_session_key);
     1655                                error_string = smb_xstrdup(get_friendly_nt_error_msg(nt_status));
     1656                                if (ntlm_server_1_user_session_key) {
     1657                                        if (nt_session_key.length == sizeof(user_session_key)) {
     1658                                                memcpy(user_session_key,
     1659                                                       nt_session_key.data,
     1660                                                       sizeof(user_session_key));
     1661                                        }
     1662                                }
     1663                                if (ntlm_server_1_lm_session_key) {
     1664                                        if (lm_session_key.length == sizeof(lm_key)) {
     1665                                                memcpy(lm_key,
     1666                                                       lm_session_key.data,
     1667                                                       sizeof(lm_key));
     1668                                        }
     1669                                }
     1670                                TALLOC_FREE(mem_ctx);
     1671
     1672                        } else {
     1673                                if (!domain) {
     1674                                        domain = smb_xstrdup(get_winbind_domain());
     1675                                }
     1676
     1677                                if (ntlm_server_1_lm_session_key)
     1678                                        flags |= WBFLAG_PAM_LMKEY;
     1679
     1680                                if (ntlm_server_1_user_session_key)
     1681                                        flags |= WBFLAG_PAM_USER_SESSION_KEY;
     1682
     1683                                nt_status = contact_winbind_auth_crap(username,
     1684                                                                      domain,
     1685                                                                      lp_netbios_name(),
     1686                                                                      &challenge,
     1687                                                                      &lm_response,
     1688                                                                      &nt_response,
     1689                                                                      flags, 0,
     1690                                                                      lm_key,
     1691                                                                      user_session_key,
     1692                                                                      &error_string,
     1693                                                                      NULL);
     1694                        }
     1695
     1696                        if (!NT_STATUS_IS_OK(nt_status)) {
    20761697                                x_fprintf(x_stdout, "Authenticated: No\n");
    20771698                                x_fprintf(x_stdout, "Authentication-Error: %s\n.\n", error_string);
     
    21901811}
    21911812
    2192 static void manage_ntlm_change_password_1_request(struct ntlm_auth_state *state,
    2193                                                         char *buf, int length)
     1813static void manage_ntlm_change_password_1_request(enum stdio_helper_mode stdio_helper_mode,
     1814                                                  struct loadparm_context *lp_ctx,
     1815                                                  struct ntlm_auth_state *state,
     1816                                                  char *buf, int length, void **private2)
    21941817{
    21951818        char *request, *parameter;     
     
    24012024}
    24022025
    2403 static void manage_squid_request(struct ntlm_auth_state *state,
    2404                 stdio_helper_function fn)
     2026static void manage_squid_request(enum stdio_helper_mode stdio_helper_mode,
     2027                                   struct loadparm_context *lp_ctx,
     2028                                   struct ntlm_auth_state *state,
     2029                stdio_helper_function fn, void **private2)
    24052030{
    24062031        char *buf;
     
    24562081        }
    24572082
    2458         fn(state, buf, length);
     2083        fn(stdio_helper_mode, lp_ctx, state, buf, length, private2);
    24592084        talloc_free(buf);
    24602085}
    24612086
    24622087
    2463 static void squid_stream(enum stdio_helper_mode stdio_mode, stdio_helper_function fn) {
     2088static void squid_stream(enum stdio_helper_mode stdio_mode,
     2089                         struct loadparm_context *lp_ctx,
     2090                         stdio_helper_function fn) {
    24642091        TALLOC_CTX *mem_ctx;
    24652092        struct ntlm_auth_state *state;
     
    24882115        while(1) {
    24892116                TALLOC_CTX *frame = talloc_stackframe();
    2490                 manage_squid_request(state, fn);
     2117                manage_squid_request(stdio_mode, lp_ctx, state, fn, NULL);
    24912118                TALLOC_FREE(frame);
    24922119        }
     
    24992126{
    25002127        NTSTATUS nt_status;
    2501         uint32 flags = 0;
     2128        uint32_t flags = 0;
    25022129        char lm_key[8];
    25032130        char user_session_key[16];
     
    25052132        char *hex_user_session_key;
    25062133        char *error_string;
    2507         static uint8 zeros[16];
     2134        static uint8_t zeros[16];
    25082135
    25092136        x_setbuf(x_stdout, NULL);
     
    25222149                                              &opt_lm_response,
    25232150                                              &opt_nt_response,
    2524                                               flags,
     2151                                              flags, 0,
    25252152                                              (unsigned char *)lm_key,
    25262153                                              (unsigned char *)user_session_key,
     
    25712198        OPT_REQUIRE_MEMBERSHIP,
    25722199        OPT_USE_CACHED_CREDS,
    2573         OPT_PAM_WINBIND_CONF
     2200        OPT_PAM_WINBIND_CONF,
     2201        OPT_TARGET_SERVICE,
     2202        OPT_TARGET_HOSTNAME,
     2203        OPT_OFFLINE_LOGON
    25742204};
    25752205
     
    25842214        static const char *hex_lm_response;
    25852215        static const char *hex_nt_response;
    2586 
     2216        struct loadparm_context *lp_ctx;
    25872217        poptContext pc;
    25882218
     
    26082238                { "request-nt-key", 0, POPT_ARG_NONE, &request_user_session_key, OPT_USER_SESSION_KEY, "Retrieve User (NT) session key"},
    26092239                { "use-cached-creds", 0, POPT_ARG_NONE, &use_cached_creds, OPT_USE_CACHED_CREDS, "Use cached credentials if no password is given"},
     2240                { "offline-logon", 0, POPT_ARG_NONE, &offline_logon,
     2241                  OPT_OFFLINE_LOGON,
     2242                  "Use cached passwords when DC is offline"},
    26102243                { "diagnostics", 0, POPT_ARG_NONE, &diagnostics,
    26112244                  OPT_DIAGNOSTICS,
     
    26132246                { "require-membership-of", 0, POPT_ARG_STRING, &require_membership_of, OPT_REQUIRE_MEMBERSHIP, "Require that a user be a member of this group (either name or SID) for authentication to succeed" },
    26142247                { "pam-winbind-conf", 0, POPT_ARG_STRING, &opt_pam_winbind_conf, OPT_PAM_WINBIND_CONF, "Require that request must set WBFLAG_PAM_CONTACT_TRUSTDOM when krb5 auth is required" },
     2248                { "target-service", 0, POPT_ARG_STRING, &opt_target_service, OPT_TARGET_SERVICE, "Target service (eg http)" },
     2249                { "target-hostname", 0, POPT_ARG_STRING, &opt_target_hostname, OPT_TARGET_HOSTNAME, "Target hostname" },
    26152250                POPT_COMMON_CONFIGFILE
    26162251                POPT_COMMON_VERSION
     2252                POPT_COMMON_OPTION
    26172253                POPT_TABLEEND
    26182254        };
    26192255
    26202256        /* Samba client initialisation */
    2621         load_case_tables();
     2257        smb_init_locale();
    26222258
    26232259        setup_logging("ntlm_auth", DEBUG_STDERR);
     
    26402276        poptFreeContext(pc);
    26412277
    2642         if (!lp_load(get_dyn_CONFIGFILE(), True, False, False, True)) {
     2278        if (!lp_load_global(get_dyn_CONFIGFILE())) {
    26432279                d_fprintf(stderr, "ntlm_auth: error opening config file %s. Error was %s\n",
    26442280                        get_dyn_CONFIGFILE(), strerror(errno));
     
    26812317
    26822318                case OPT_REQUIRE_MEMBERSHIP:
    2683                         if (StrnCaseCmp("S-", require_membership_of, 2) == 0) {
     2319                        if (strncasecmp_m("S-", require_membership_of, 2) == 0) {
    26842320                                require_membership_of_sid = require_membership_of;
    26852321                        }
     
    27162352        }
    27172353
     2354        lp_ctx = loadparm_init_s3(NULL, loadparm_s3_helpers());
     2355        if (lp_ctx == NULL) {
     2356                x_fprintf(x_stderr, "loadparm_init_s3() failed!\n");
     2357                exit(1);
     2358        }
     2359
    27182360        if (helper_protocol) {
    27192361                int i;
    27202362                for (i=0; i<NUM_HELPER_MODES; i++) {
    27212363                        if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
    2722                                 squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
     2364                                squid_stream(stdio_helper_protocols[i].mode, lp_ctx, stdio_helper_protocols[i].fn);
    27232365                                exit(0);
    27242366                        }
     
    27472389
    27482390        if (!opt_password) {
    2749                 opt_password = getpass("password: ");
     2391                char pwd[256] = {0};
     2392                int rc;
     2393
     2394                rc = samba_getpass("Password: ", pwd, sizeof(pwd), false, false);
     2395                if (rc == 0) {
     2396                        opt_password = SMB_STRDUP(pwd);
     2397                }
    27502398        }
    27512399
  • vendor/current/source3/utils/ntlm_auth_diagnostics.c

    r740 r988  
    5151        bool pass = True;
    5252        NTSTATUS nt_status;
    53         uint32 flags = 0;
     53        uint32_t flags = 0;
    5454        DATA_BLOB lm_response = data_blob(NULL, 24);
    5555        DATA_BLOB nt_response = data_blob(NULL, 24);
     
    9999                                              &lm_response,
    100100                                              &nt_response,
    101                                               flags,
     101                                              flags, 0,
    102102                                              lm_key,
    103103                                              user_session_key,
     
    175175        bool pass = True;
    176176        NTSTATUS nt_status;
    177         uint32 flags = 0;
     177        uint32_t flags = 0;
    178178        DATA_BLOB nt_response = data_blob(NULL, 24);
    179179
     
    198198                                              &nt_response,
    199199                                              NULL,
    200                                               flags,
     200                                              flags, 0,
    201201                                              lm_key,
    202202                                              user_session_key,
     
    241241        bool pass = True;
    242242        NTSTATUS nt_status;
    243         uint32 flags = 0;
     243        uint32_t flags = 0;
    244244        DATA_BLOB nt_response = data_blob(NULL, 24);
    245245        DATA_BLOB session_key = data_blob(NULL, 16);
    246246
    247         uint8 lm_key[8];
    248         uint8 lm_hash[16];
    249         uint8 user_session_key[16];
    250         uint8 nt_hash[16];
     247        uint8_t lm_key[8];
     248        uint8_t lm_hash[16];
     249        uint8_t user_session_key[16];
     250        uint8_t nt_hash[16];
    251251        DATA_BLOB chall = get_challenge();
    252252        char *error_string;
     
    269269                                              &nt_response,
    270270                                              &nt_response,
    271                                               flags,
     271                                              flags, 0,
    272272                                              lm_key,
    273273                                              user_session_key,
     
    315315        bool pass = True;
    316316        NTSTATUS nt_status;
    317         uint32 flags = 0;
     317        uint32_t flags = 0;
    318318        DATA_BLOB ntlmv2_response = data_blob_null;
    319319        DATA_BLOB lmv2_response = data_blob_null;
     
    360360                                              &lmv2_response,
    361361                                              &ntlmv2_response,
    362                                               flags,
     362                                              flags, 0,
    363363                                              NULL,
    364364                                              user_session_key,
     
    443443{
    444444        NTSTATUS nt_status;
    445         uint32 flags = 0;
     445        uint32_t flags = 0;
    446446        DATA_BLOB nt_response = data_blob_null;
    447447        DATA_BLOB lm_response = data_blob_null;
     
    480480                                   strlen(password)+1,
    481481                                   &lm_response.data,
    482                                    &lm_response.length, True)) {
     482                                   &lm_response.length)) {
    483483                DEBUG(0, ("convert_string_talloc failed!\n"));
    484484                exit(1);
     
    511511                                              &lm_response,
    512512                                              &nt_response,
    513                                               flags,
     513                                              flags, MSV1_0_CLEARTEXT_PASSWORD_ALLOWED,
    514514                                              lm_key,
    515515                                              user_session_key,
  • vendor/current/source3/utils/ntlm_auth_proto.h

    r414 r988  
    3636                                   const DATA_BLOB *lm_response,
    3737                                   const DATA_BLOB *nt_response,
    38                                    uint32 flags,
    39                                    uint8 lm_key[8],
    40                                    uint8 user_session_key[16],
     38                                   uint32_t flags,
     39                                   uint32_t extra_logon_parameters,
     40                                   uint8_t lm_key[8],
     41                                   uint8_t user_session_key[16],
    4142                                   char **error_string,
    4243                                   char **unix_name);
  • vendor/current/source3/utils/passwd_util.c

    r414 r988  
    4343         * a null terminator.
    4444         */
    45         if ( fgets(new_pw, sizeof(new_pw), stdin) != NULL) {
    46                 if ((len = strlen(new_pw)) > 0) {
    47                         if(new_pw[len-1] == '\n')
    48                                 new_pw[len - 1] = 0;
    49                 }
     45        if ( fgets(new_pw, sizeof(new_pw), stdin) == NULL) {
     46                return NULL;
     47        }
     48        if ((len = strlen(new_pw)) > 0) {
     49                if(new_pw[len-1] == '\n')
     50                        new_pw[len - 1] = 0;
    5051        }
    5152        return(new_pw);
     
    5960char *get_pass( const char *prompt, bool stdin_get)
    6061{
     62        char pwd[256] = {0};
    6163        char *p;
     64        int rc;
     65
    6266        if (stdin_get) {
    6367                p = stdin_new_passwd();
     68                if (p == NULL) {
     69                        return NULL;
     70                }
    6471        } else {
    65                 p = getpass( prompt);
     72                rc = samba_getpass(prompt, pwd, sizeof(pwd), false, false);
     73                if (rc < 0) {
     74                        return NULL;
     75                }
     76                p = pwd;
    6677        }
    6778        return smb_xstrdup( p);
  • vendor/current/source3/utils/pdbedit.c

    r740 r988  
    5656#define BIT_KICKOFFTIME 0x20000000
    5757#define BIT_DESCRIPTION 0x40000000
     58#define BIT_PWSETNTHASH 0x80000000
    5859
    5960#define MASK_ALWAYS_GOOD        0x0000001F
    60 #define MASK_USER_GOOD          0x60405FE0
     61#define MASK_USER_GOOD          0xE0405FE0
    6162
    6263static int get_sid_from_cli_string(struct dom_sid *sid, const char *str_sid)
     
    176177static int export_groups (struct pdb_methods *in, struct pdb_methods *out)
    177178{
    178         GROUP_MAP *maps = NULL;
     179        GROUP_MAP **maps = NULL;
    179180        size_t i, entries = 0;
    180181        NTSTATUS status;
     
    189190
    190191        for (i=0; i<entries; i++) {
    191                 out->add_group_mapping_entry(out, &(maps[i]));
    192         }
    193 
    194         SAFE_FREE( maps );
     192                out->add_group_mapping_entry(out, maps[i]);
     193        }
     194
     195        TALLOC_FREE(maps);
    195196
    196197        return 0;
     
    318319                pdb_sethexhours(temp, hours);
    319320                printf ("Logon hours         : %s\n", temp);
     321                if (smbpwdstyle){
     322                        pdb_sethexpwd(temp, pdb_get_lanman_passwd(sam_pwent), pdb_get_acct_ctrl(sam_pwent));
     323                        printf ("LM hash             : %s\n", temp);
     324                        pdb_sethexpwd(temp, pdb_get_nt_passwd(sam_pwent), pdb_get_acct_ctrl(sam_pwent));
     325                        printf ("NT hash             : %s\n", temp);
     326                }       
    320327
    321328        } else if (smbpwdstyle) {
     
    333340                       nt_passwd,
    334341                       pdb_encode_acct_ctrl(pdb_get_acct_ctrl(sam_pwent),NEW_PW_FORMAT_SPACE_PADDED_LEN),
    335                        (uint32)convert_time_t_to_uint32_t(pdb_get_pass_last_set_time(sam_pwent)));
     342                       (uint32_t)convert_time_t_to_uint32_t(pdb_get_pass_last_set_time(sam_pwent)));
    336343        } else {
    337344                uid = nametouid(pdb_get_username(sam_pwent));
     
    500507                         const char *user_sid, const char *user_domain,
    501508                         const bool badpw, const bool hours,
    502                          const char *kickoff_time)
     509                         const char *kickoff_time, const char *str_hex_pwd)
    503510{
    504511        bool updated_autolock = False, updated_badpw = False;
     
    602609                pdb_set_kickoff_time(sam_pwent, value, PDB_CHANGED);
    603610        }
     611        if (str_hex_pwd) {
     612                unsigned char  new_nt_p16[NT_HASH_LEN];
     613                if(strlen(str_hex_pwd) != (NT_HASH_LEN *2)){
     614                        fprintf(stderr, "Invalid hash\n");
     615                        return -1;
     616                }
     617                                         
     618                pdb_gethexpwd(str_hex_pwd, new_nt_p16);
     619               
     620                if (!pdb_set_nt_passwd (sam_pwent, new_nt_p16 , PDB_CHANGED)) {
     621                        fprintf(stderr, "Failed to set password from nt-hash\n");
     622                        return -1;
     623                }       
     624
     625                if (!pdb_set_pass_last_set_time (sam_pwent, time(NULL), PDB_CHANGED)){
     626                        fprintf(stderr, "Failed to set last password set time\n");
     627                        return -1;
     628                }       
     629                if (!pdb_update_history(sam_pwent, new_nt_p16)){
     630                        fprintf(stderr, "Failed to update password history\n");
     631                        return -1;
     632                }
     633        }
    604634
    605635        if (NT_STATUS_IS_OK(pdb_update_sam_account(sam_pwent))) {
    606                 print_user_info(username, True, False);
     636               
     637                print_user_info(username, True, (str_hex_pwd != NULL ));
    607638        } else {
    608639                fprintf (stderr, "Unable to modify entry!\n");
     
    656687        }
    657688
    658         strlower_m(name);
     689        if (!strlower_m(name)) {
     690                fprintf(stderr, "strlower_m %s failed\n", name);
     691                TALLOC_FREE(sam_pwent);
     692                return -1;
     693        }
    659694
    660695        ret = pdb_getsampwnam(sam_pwent, name);
     
    854889        }
    855890
    856         strlower_m(name);
     891        if (!strlower_m(name)) {
     892                fprintf(stderr, "strlower_m %s failed\n", name);
     893                return -1;
     894        }
    857895
    858896        flags = LOCAL_ADD_USER | LOCAL_TRUST_ACCOUNT | LOCAL_SET_PASSWORD;
     
    959997                fprintf (stderr,
    960998                         "machine %s does not exist in the passdb\n", name);
    961                 return -1;
    962999                TALLOC_FREE(samaccount);
     1000                return -1;
    9631001        }
    9641002
     
    9771015**********************************************************/
    9781016
    979 int main (int argc, char **argv)
     1017int main(int argc, const char **argv)
    9801018{
    9811019        static int list_users = False;
     
    9861024        static int delete_user = False;
    9871025        static int modify_user = False;
    988         uint32  setparms, checkparms;
     1026        uint32_t   setparms, checkparms;
    9891027        int opt;
    9901028        static char *full_name = NULL;
     
    10151053        struct pdb_methods *bin, *bout;
    10161054        static char *kickoff_time = NULL;
     1055        static char *str_hex_pwd = NULL;
    10171056        TALLOC_CTX *frame = talloc_stackframe();
    10181057        NTSTATUS status;
     
    10521091                {"password-from-stdin", 't', POPT_ARG_NONE, &pw_from_stdin, 0, "get password from standard in", NULL},
    10531092                {"kickoff-time", 'K', POPT_ARG_STRING, &kickoff_time, 0, "set the kickoff time", NULL},
     1093                {"set-nt-hash", 0, POPT_ARG_STRING, &str_hex_pwd, 0, "set password from nt-hash", NULL},
    10541094                POPT_COMMON_SAMBA
    10551095                POPT_TABLEEND
     
    10581098        bin = bout = NULL;
    10591099
    1060         load_case_tables();
     1100        smb_init_locale();
    10611101
    10621102        setup_logging("pdbedit", DEBUG_STDOUT);
    10631103
    1064         pc = poptGetContext(NULL, argc, (const char **) argv, long_options,
     1104        pc = poptGetContext(NULL, argc, argv, long_options,
    10651105                            POPT_CONTEXT_KEEP_FIRST);
    10661106
     
    10781118                user_name = poptGetArg(pc);
    10791119
    1080         if (!lp_load(get_dyn_CONFIGFILE(),True,False,False,True)) {
     1120        if (!lp_load_global(get_dyn_CONFIGFILE())) {
    10811121                fprintf(stderr, "Can't load %s - run testparm to debug it\n", get_dyn_CONFIGFILE());
    10821122                exit(1);
     
    11121152                        (hours_reset ? BIT_LOGONHOURS : 0) +
    11131153                        (kickoff_time ? BIT_KICKOFFTIME : 0) +
     1154                        (str_hex_pwd ? BIT_PWSETNTHASH : 0 ) +
    11141155                        (acct_desc ? BIT_DESCRIPTION : 0);
     1156                       
    11151157
    11161158        if (setparms & BIT_BACKEND) {
     
    11181160                 * This way we can use regular pdb functions for default
    11191161                 * operations that do not involve passdb migrations */
    1120                 lp_set_passdb_backend(backend);
     1162                lp_set_cmdline("passdb backend", backend);
    11211163        } else {
    11221164                backend = lp_passdb_backend();
     
    11431185                        int count;
    11441186                        int i;
    1145                         account_policy_names_list(&names, &count);
     1187                        account_policy_names_list(talloc_tos(), &names, &count);
    11461188                        fprintf(stderr, "No account policy by that name!\n");
    11471189                        if (count !=0) {
     
    11511193                                }
    11521194                        }
    1153                         SAFE_FREE(names);
     1195                        TALLOC_FREE(names);
    11541196                        exit(1);
    11551197                }
     
    11751217
    11761218        if (reset_account_policies) {
    1177                 if (!reinit_account_policies()) {
     1219                if (reinit_account_policies()) {
    11781220                        exit(1);
    11791221                }
     
    13091351                                                     user_sid, user_domain,
    13101352                                                     badpw_reset, hours_reset,
    1311                                                      kickoff_time);
     1353                                                     kickoff_time, str_hex_pwd);
    13121354                        }
    13131355                }
  • vendor/current/source3/utils/profiles.c

    r740 r988  
    130130        /* swap out the SIDs in the security descriptor */
    131131
    132         if ( !(new_sd = dup_sec_desc( outfile->mem_ctx, nk->sec_desc->sec_desc )) ) {
    133                 fprintf( stderr, "Failed to copy security descriptor!\n" );
     132        if (nk->sec_desc->sec_desc == NULL) {
     133                fprintf(stderr, "Invalid (NULL) security descriptor!\n");
     134                return false;
     135        }
     136
     137        new_sd = security_descriptor_copy(outfile->mem_ctx,
     138                                          nk->sec_desc->sec_desc);
     139        if (new_sd == NULL) {
     140                fprintf(stderr, "Failed to copy security descriptor!\n");
    134141                return False;
    135142        }
     
    183190        }
    184191
     192
     193        verbose_output("[%s]\n", path);
     194
    185195        /* values is a talloc()'d child of subkeys here so just throw it all away */
    186 
    187         TALLOC_FREE( subkeys );
    188 
    189         verbose_output("[%s]\n", path);
     196        TALLOC_FREE(subkeys);
    190197
    191198        return True;
     
    195202*********************************************************************/
    196203
    197 int main( int argc, char *argv[] )
     204int main( int argc, const char *argv[] )
    198205{
    199206        TALLOC_CTX *frame = talloc_stackframe();
     
    213220        poptContext pc;
    214221
    215         load_case_tables();
     222        smb_init_locale();
    216223
    217224        /* setup logging options */
     
    219226        setup_logging( "profiles", DEBUG_STDERR);
    220227
    221         pc = poptGetContext("profiles", argc, (const char **)argv, long_options,
     228        pc = poptGetContext("profiles", argc, argv, long_options,
    222229                POPT_CONTEXT_KEEP_FIRST);
    223230
  • vendor/current/source3/utils/sharesec.c

    r740 r988  
    2222 */
    2323
     24struct cli_state;
    2425
    2526#include "includes.h"
     
    2728#include "../libcli/security/security.h"
    2829#include "passdb/machine_sid.h"
     30#include "util_sd.h"
    2931
    3032static TALLOC_CTX *ctx;
     
    3537                SMB_ACL_SET,
    3638                SMB_SD_DELETE,
    37                 SMB_ACL_VIEW };
    38 
    39 struct perm_value {
    40         const char *perm;
    41         uint32 mask;
    42 };
    43 
    44 /* These values discovered by inspection */
    45 
    46 static const struct perm_value special_values[] = {
    47         { "R", SEC_RIGHTS_FILE_READ },
    48         { "W", SEC_RIGHTS_FILE_WRITE },
    49         { "X", SEC_RIGHTS_FILE_EXECUTE },
    50         { "D", SEC_STD_DELETE },
    51         { "P", SEC_STD_WRITE_DAC },
    52         { "O", SEC_STD_WRITE_OWNER },
    53         { NULL, 0 },
    54 };
    55 
    56 #define SEC_RIGHTS_DIR_CHANGE ( SEC_RIGHTS_DIR_READ|SEC_STD_DELETE|\
    57                                 SEC_RIGHTS_DIR_WRITE|SEC_DIR_TRAVERSE )
    58 
    59 static const struct perm_value standard_values[] = {
    60         { "READ",   SEC_RIGHTS_DIR_READ|SEC_DIR_TRAVERSE },
    61         { "CHANGE", SEC_RIGHTS_DIR_CHANGE },
    62         { "FULL",   SEC_RIGHTS_DIR_ALL },
    63         { NULL, 0 },
    64 };
    65 
    66 /********************************************************************
    67  print an ACE on a FILE
    68 ********************************************************************/
    69 
    70 static void print_ace(FILE *f, struct security_ace *ace)
    71 {
    72         const struct perm_value *v;
    73         int do_print = 0;
    74         uint32 got_mask;
    75 
    76         fprintf(f, "%s:", sid_string_tos(&ace->trustee));
    77 
    78         /* Ace type */
    79 
    80         if (ace->type == SEC_ACE_TYPE_ACCESS_ALLOWED) {
    81                 fprintf(f, "ALLOWED");
    82         } else if (ace->type == SEC_ACE_TYPE_ACCESS_DENIED) {
    83                 fprintf(f, "DENIED");
    84         } else {
    85                 fprintf(f, "%d", ace->type);
    86         }
    87 
    88         /* Not sure what flags can be set in a file ACL */
    89 
    90         fprintf(f, "/%d/", ace->flags);
    91 
    92         /* Standard permissions */
    93 
    94         for (v = standard_values; v->perm; v++) {
    95                 if (ace->access_mask == v->mask) {
    96                         fprintf(f, "%s", v->perm);
    97                         return;
    98                 }
    99         }
    100 
    101         /* Special permissions.  Print out a hex value if we have
    102            leftover bits in the mask. */
    103 
    104         got_mask = ace->access_mask;
    105 
    106  again:
    107         for (v = special_values; v->perm; v++) {
    108                 if ((ace->access_mask & v->mask) == v->mask) {
    109                         if (do_print) {
    110                                 fprintf(f, "%s", v->perm);
    111                         }
    112                         got_mask &= ~v->mask;
    113                 }
    114         }
    115 
    116         if (!do_print) {
    117                 if (got_mask != 0) {
    118                         fprintf(f, "0x%08x", ace->access_mask);
    119                 } else {
    120                         do_print = 1;
    121                         goto again;
    122                 }
    123         }
    124 }
    125 
    126 /********************************************************************
    127  print an ascii version of a security descriptor on a FILE handle
    128 ********************************************************************/
    129 
    130 static void sec_desc_print(FILE *f, struct security_descriptor *sd)
    131 {
    132         uint32 i;
    133 
    134         fprintf(f, "REVISION:%d\n", sd->revision);
    135 
    136         /* Print owner and group sid */
    137 
    138         fprintf(f, "OWNER:%s\n", sid_string_tos(sd->owner_sid));
    139 
    140         fprintf(f, "GROUP:%s\n", sid_string_tos(sd->group_sid));
    141 
    142         /* Print aces */
    143         for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
    144                 struct security_ace *ace = &sd->dacl->aces[i];
    145                 fprintf(f, "ACL:");
    146                 print_ace(f, ace);
    147                 fprintf(f, "\n");
    148         }
    149 }
    150 
    151 /********************************************************************
    152  parse an ACE in the same format as print_ace()
    153 ********************************************************************/
    154 
    155 static bool parse_ace(struct security_ace *ace, const char *orig_str)
    156 {
    157         char *p;
    158         const char *cp;
    159         char *tok;
    160         unsigned int atype = 0;
    161         unsigned int aflags = 0;
    162         unsigned int amask = 0;
    163         struct dom_sid sid;
    164         uint32_t mask;
    165         const struct perm_value *v;
    166         char *str = SMB_STRDUP(orig_str);
    167         TALLOC_CTX *frame = talloc_stackframe();
    168 
    169         if (!str) {
    170                 TALLOC_FREE(frame);
    171                 return False;
    172         }
    173 
    174         ZERO_STRUCTP(ace);
    175         p = strchr_m(str,':');
    176         if (!p) {
    177                 fprintf(stderr, "ACE '%s': missing ':'.\n", orig_str);
    178                 SAFE_FREE(str);
    179                 TALLOC_FREE(frame);
    180                 return False;
    181         }
    182         *p = '\0';
    183         p++;
    184         /* Try to parse numeric form */
    185 
    186         if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
    187             string_to_sid(&sid, str)) {
    188                 goto done;
    189         }
    190 
    191         /* Try to parse text form */
    192 
    193         if (!string_to_sid(&sid, str)) {
    194                 fprintf(stderr, "ACE '%s': failed to convert '%s' to SID\n",
    195                         orig_str, str);
    196                 SAFE_FREE(str);
    197                 TALLOC_FREE(frame);
    198                 return False;
    199         }
    200 
    201         cp = p;
    202         if (!next_token_talloc(frame, &cp, &tok, "/")) {
    203                 fprintf(stderr, "ACE '%s': failed to find '/' character.\n",
    204                         orig_str);
    205                 SAFE_FREE(str);
    206                 TALLOC_FREE(frame);
    207                 return False;
    208         }
    209 
    210         if (strncmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
    211                 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
    212         } else if (strncmp(tok, "DENIED", strlen("DENIED")) == 0) {
    213                 atype = SEC_ACE_TYPE_ACCESS_DENIED;
    214         } else {
    215                 fprintf(stderr, "ACE '%s': missing 'ALLOWED' or 'DENIED' "
    216                         "entry at '%s'\n", orig_str, tok);
    217                 SAFE_FREE(str);
    218                 TALLOC_FREE(frame);
    219                 return False;
    220         }
    221 
    222         /* Only numeric form accepted for flags at present */
    223         /* no flags on share permissions */
    224 
    225         if (!(next_token_talloc(frame, &cp, &tok, "/") &&
    226               sscanf(tok, "%i", &aflags) && aflags == 0)) {
    227                 fprintf(stderr, "ACE '%s': bad integer flags entry at '%s'\n",
    228                         orig_str, tok);
    229                 SAFE_FREE(str);
    230                 TALLOC_FREE(frame);
    231                 return False;
    232         }
    233 
    234         if (!next_token_talloc(frame, &cp, &tok, "/")) {
    235                 fprintf(stderr, "ACE '%s': missing / at '%s'\n",
    236                         orig_str, tok);
    237                 SAFE_FREE(str);
    238                 TALLOC_FREE(frame);
    239                 return False;
    240         }
    241 
    242         if (strncmp(tok, "0x", 2) == 0) {
    243                 if (sscanf(tok, "%i", &amask) != 1) {
    244                         fprintf(stderr, "ACE '%s': bad hex number at '%s'\n",
    245                                 orig_str, tok);
    246                         TALLOC_FREE(frame);
    247                         SAFE_FREE(str);
    248                         return False;
    249                 }
    250                 goto done;
    251         }
    252 
    253         for (v = standard_values; v->perm; v++) {
    254                 if (strcmp(tok, v->perm) == 0) {
    255                         amask = v->mask;
    256                         goto done;
    257                 }
    258         }
    259 
    260         p = tok;
    261 
    262         while(*p) {
    263                 bool found = False;
    264 
    265                 for (v = special_values; v->perm; v++) {
    266                         if (v->perm[0] == *p) {
    267                                 amask |= v->mask;
    268                                 found = True;
    269                         }
    270                 }
    271 
    272                 if (!found) {
    273                         fprintf(stderr, "ACE '%s': bad permission value at "
    274                                 "'%s'\n", orig_str, p);
    275                         TALLOC_FREE(frame);
    276                         SAFE_FREE(str);
    277                         return False;
    278                 }
    279                 p++;
    280         }
    281 
    282         if (*p) {
    283                 TALLOC_FREE(frame);
    284                 SAFE_FREE(str);
    285                 return False;
    286         }
    287 
    288  done:
    289         mask = amask;
    290         init_sec_ace(ace, &sid, atype, mask, aflags);
    291         SAFE_FREE(str);
    292         TALLOC_FREE(frame);
    293         return True;
    294 }
    295 
     39                SMB_SD_SETSDDL,
     40                SMB_SD_VIEWSDDL,
     41                SMB_ACL_VIEW,
     42                SMB_ACL_VIEW_ALL };
    29643
    29744/********************************************************************
     
    31360        num_ace = count_chars( pacl, ',' ) + 1;
    31461
    315         if ( !(ace = TALLOC_ZERO_ARRAY( mem_ctx, struct security_ace, num_ace )) )
     62        if ( !(ace = talloc_zero_array( mem_ctx, struct security_ace, num_ace )) )
    31663                return NULL;
    31764
     
    32370                acl_string[MIN( PTR_DIFF( end_acl, pacl ), sizeof(fstring)-1)] = '\0';
    32471
    325                 if ( !parse_ace( &ace[i], acl_string ) )
     72                if ( !parse_ace(NULL, &ace[i], acl_string ) )
    32673                        return NULL;
    32774
     
    367114static int ace_compare(struct security_ace *ace1, struct security_ace *ace2)
    368115{
    369         if (sec_ace_equal(ace1, ace2))
     116        if (security_ace_equal(ace1, ace2))
    370117                return 0;
    371118
     
    390137static void sort_acl(struct security_acl *the_acl)
    391138{
    392         uint32 i;
     139        uint32_t i;
    393140        if (!the_acl) return;
    394141
     
    396143
    397144        for (i=1;i<the_acl->num_aces;) {
    398                 if (sec_ace_equal(&the_acl->aces[i-1], &the_acl->aces[i])) {
     145                if (security_ace_equal(&the_acl->aces[i-1],
     146                                       &the_acl->aces[i])) {
    399147                        int j;
    400148                        for (j=i; j<the_acl->num_aces-1; j++) {
     
    414162        struct security_descriptor *old = NULL;
    415163        size_t sd_size = 0;
    416         uint32 i, j;
     164        uint32_t i, j;
    417165
    418166        if (mode != SMB_ACL_SET && mode != SMB_SD_DELETE) {
     
    431179
    432180        switch (mode) {
     181        case SMB_ACL_VIEW_ALL:
     182                /* should not happen */
     183                return 0;
    433184        case SMB_ACL_VIEW:
    434                 sec_desc_print( stdout, old);
     185                sec_desc_print(NULL, stdout, old, false);
    435186                return 0;
    436187        case SMB_ACL_DELETE:
     
    439190
    440191                for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
    441                     if (sec_ace_equal(&sd->dacl->aces[i], &old->dacl->aces[j])) {
    442                         uint32 k;
     192                    if (security_ace_equal(&sd->dacl->aces[i],
     193                                           &old->dacl->aces[j])) {
     194                        uint32_t k;
    443195                        for (k=j; k<old->dacl->num_aces-1;k++) {
    444196                            old->dacl->aces[k] = old->dacl->aces[k+1];
     
    451203
    452204                if (!found) {
    453                 printf("ACL for ACE:");
    454                 print_ace(stdout, &sd->dacl->aces[i]);
    455                 printf(" not found\n");
     205                        printf("ACL for ACE:");
     206                        print_ace(NULL, stdout, &sd->dacl->aces[i], false);
     207                        printf(" not found\n");
    456208                }
    457209            }
     
    498250            }
    499251            return 0;
     252        default:
     253                fprintf(stderr, "invalid command\n");
     254                return -1;
    500255        }
    501256
     
    510265}
    511266
     267static int set_sharesec_sddl(const char *sharename, const char *sddl)
     268{
     269        struct security_descriptor *sd;
     270        bool ret;
     271
     272        sd = sddl_decode(talloc_tos(), sddl, get_global_sam_sid());
     273        if (sd == NULL) {
     274                fprintf(stderr, "Failed to parse acl\n");
     275                return -1;
     276        }
     277
     278        ret = set_share_security(sharename, sd);
     279        TALLOC_FREE(sd);
     280        if (!ret) {
     281                fprintf(stderr, "Failed to store acl for share [%s]\n",
     282                        sharename);
     283                return -1;
     284        }
     285
     286        return 0;
     287}
     288
     289static int view_sharesec_sddl(const char *sharename)
     290{
     291        struct security_descriptor *sd;
     292        size_t sd_size;
     293        char *acl;
     294
     295        sd = get_share_security(talloc_tos(), sharename, &sd_size);
     296        if (sd == NULL) {
     297                fprintf(stderr, "Unable to retrieve permissions for share "
     298                        "[%s]\n", sharename);
     299                return -1;
     300        }
     301
     302        acl = sddl_encode(talloc_tos(), sd, get_global_sam_sid());
     303        TALLOC_FREE(sd);
     304        if (acl == NULL) {
     305                fprintf(stderr, "Unable to sddl-encode permissions for share "
     306                        "[%s]\n", sharename);
     307                return -1;
     308        }
     309        printf("%s\n", acl);
     310        TALLOC_FREE(acl);
     311        return 0;
     312}
     313
    512314/********************************************************************
    513315  main program
    514316********************************************************************/
     317
     318enum {
     319        OPT_VIEW_ALL = 1000,
     320};
    515321
    516322int main(int argc, const char *argv[])
     
    532338                { "replace", 'R', POPT_ARG_STRING, &the_acl, 'R', "Overwrite share permission ACL", "ACLS" },
    533339                { "delete", 'D', POPT_ARG_NONE, NULL, 'D', "Delete the entire security descriptor" },
     340                { "setsddl", 'S', POPT_ARG_STRING, the_acl, 'S',
     341                  "Set the SD in sddl format" },
     342                { "viewsddl", 'V', POPT_ARG_NONE, the_acl, 'V',
     343                  "View the SD in sddl format" },
    534344                { "view", 'v', POPT_ARG_NONE, NULL, 'v', "View current share permissions" },
     345                { "view-all", 0, POPT_ARG_NONE, NULL, OPT_VIEW_ALL,
     346                  "View all current share permissions" },
    535347                { "machine-sid", 'M', POPT_ARG_NONE, NULL, 'M', "Initialize the machine SID" },
    536348                { "force", 'F', POPT_ARG_NONE, NULL, 'F', "Force storing the ACL", "ACLS" },
     
    547359        setup_logging( "sharesec", DEBUG_STDERR);
    548360
    549         load_case_tables();
     361        smb_init_locale();
    550362
    551363        lp_set_cmdline("log level", "1");
     
    581393                        break;
    582394
     395                case 'S':
     396                        mode = SMB_SD_SETSDDL;
     397                        the_acl = smb_xstrdup(poptGetOptArg(pc));
     398                        break;
     399
     400                case 'V':
     401                        mode = SMB_SD_VIEWSDDL;
     402                        break;
     403
    583404                case 'v':
    584405                        mode = SMB_ACL_VIEW;
     
    592413                        initialize_sid = True;
    593414                        break;
     415                case OPT_VIEW_ALL:
     416                        mode = SMB_ACL_VIEW_ALL;
     417                        break;
    594418                }
    595419        }
     
    597421        setlinebuf(stdout);
    598422
    599         lp_load_with_registry_shares( get_dyn_CONFIGFILE(), False, False, False,
    600                                       True );
     423        lp_load_with_registry_shares(get_dyn_CONFIGFILE());
    601424
    602425        /* check for initializing secrets.tdb first */
     
    619442        }
    620443
     444        if (mode == SMB_ACL_VIEW_ALL) {
     445                int i;
     446
     447                for (i=0; i<lp_numservices(); i++) {
     448                        TALLOC_CTX *frame = talloc_stackframe();
     449                        const char *service = lp_servicename(frame, i);
     450
     451                        if (service == NULL) {
     452                                continue;
     453                        }
     454
     455                        printf("[%s]\n", service);
     456                        change_share_sec(frame, service, NULL, SMB_ACL_VIEW);
     457                        printf("\n");
     458                        TALLOC_FREE(frame);
     459                }
     460                goto done;
     461        }
     462
    621463        /* get the sharename */
    622464
     
    635477        }
    636478
    637         retval = change_share_sec(ctx, sharename, the_acl, mode);
    638 
     479        switch (mode) {
     480        case SMB_SD_SETSDDL:
     481                retval = set_sharesec_sddl(sharename, the_acl);
     482                break;
     483        case SMB_SD_VIEWSDDL:
     484                retval = view_sharesec_sddl(sharename);
     485                break;
     486        default:
     487                retval = change_share_sec(ctx, sharename, the_acl, mode);
     488                break;
     489        }
     490
     491done:
    639492        talloc_destroy(ctx);
    640493
  • vendor/current/source3/utils/smbcacls.c

    r740 r988  
    3131#include "libsmb/clirap.h"
    3232#include "passdb/machine_sid.h"
     33#include "../librpc/gen_ndr/ndr_lsa_c.h"
     34#include "util_sd.h"
    3335
    3436static int test_args;
     
    3638#define CREATE_ACCESS_READ READ_CONTROL_ACCESS
    3739
    38 /* numeric is set when the user wants numeric SIDs and ACEs rather
    39    than going via LSA calls to resolve them */
    40 static int numeric;
    41 
    4240static int sddl;
     41static int query_sec_info = -1;
     42static int set_sec_info = -1;
     43
     44static const char *domain_sid = NULL;
    4345
    4446enum acl_mode {SMB_ACL_SET, SMB_ACL_DELETE, SMB_ACL_MODIFY, SMB_ACL_ADD };
     
    4648enum exit_values {EXIT_OK, EXIT_FAILED, EXIT_PARSE_ERROR};
    4749
    48 struct perm_value {
    49         const char *perm;
    50         uint32 mask;
    51 };
    52 
    53 /* These values discovered by inspection */
    54 
    55 static const struct perm_value special_values[] = {
    56         { "R", 0x00120089 },
    57         { "W", 0x00120116 },
    58         { "X", 0x001200a0 },
    59         { "D", 0x00010000 },
    60         { "P", 0x00040000 },
    61         { "O", 0x00080000 },
    62         { NULL, 0 },
    63 };
    64 
    65 static const struct perm_value standard_values[] = {
    66         { "READ",   0x001200a9 },
    67         { "CHANGE", 0x001301bf },
    68         { "FULL",   0x001f01ff },
    69         { NULL, 0 },
    70 };
    71 
    72 /* Open cli connection and policy handle */
    73 
    74 static NTSTATUS cli_lsa_lookup_sid(struct cli_state *cli,
    75                                    const struct dom_sid *sid,
    76                                    TALLOC_CTX *mem_ctx,
    77                                    enum lsa_SidType *type,
    78                                    char **domain, char **name)
    79 {
    80         uint16 orig_cnum = cli->cnum;
    81         struct rpc_pipe_client *p = NULL;
     50static NTSTATUS cli_lsa_lookup_domain_sid(struct cli_state *cli,
     51                                          struct dom_sid *sid)
     52{
     53        union lsa_PolicyInformation *info = NULL;
     54        uint16_t orig_cnum = cli_state_get_tid(cli);
     55        struct rpc_pipe_client *rpc_pipe = NULL;
    8256        struct policy_handle handle;
    83         NTSTATUS status;
     57        NTSTATUS status, result;
    8458        TALLOC_CTX *frame = talloc_stackframe();
    85         enum lsa_SidType *types;
    86         char **domains;
    87         char **names;
    88 
    89         status = cli_tcon_andx(cli, "IPC$", "?????", "", 0);
     59
     60        status = cli_tree_connect(cli, "IPC$", "?????", "", 0);
    9061        if (!NT_STATUS_IS_OK(status)) {
    91                 return status;
    92         }
    93 
    94         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
    95                                           &p);
     62                goto done;
     63        }
     64
     65        status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc, &rpc_pipe);
    9666        if (!NT_STATUS_IS_OK(status)) {
    97                 goto fail;
    98         }
    99 
    100         status = rpccli_lsa_open_policy(p, talloc_tos(), True,
     67                goto tdis;
     68        }
     69
     70        status = rpccli_lsa_open_policy(rpc_pipe, frame, True,
    10171                                        GENERIC_EXECUTE_ACCESS, &handle);
    10272        if (!NT_STATUS_IS_OK(status)) {
    103                 goto fail;
    104         }
    105 
    106         status = rpccli_lsa_lookup_sids(p, talloc_tos(), &handle, 1, sid,
    107                                         &domains, &names, &types);
    108         if (!NT_STATUS_IS_OK(status)) {
    109                 goto fail;
    110         }
    111 
    112         *type = types[0];
    113         *domain = talloc_move(mem_ctx, &domains[0]);
    114         *name = talloc_move(mem_ctx, &names[0]);
    115 
    116         status = NT_STATUS_OK;
    117  fail:
    118         TALLOC_FREE(p);
     73                goto tdis;
     74        }
     75
     76        status = dcerpc_lsa_QueryInfoPolicy2(rpc_pipe->binding_handle,
     77                                             frame, &handle,
     78                                             LSA_POLICY_INFO_DOMAIN,
     79                                             &info, &result);
     80
     81        if (any_nt_status_not_ok(status, result, &status)) {
     82                goto tdis;
     83        }
     84
     85        *sid = *info->domain.sid;
     86
     87tdis:
     88        TALLOC_FREE(rpc_pipe);
    11989        cli_tdis(cli);
    120         cli->cnum = orig_cnum;
     90done:
     91        cli_state_set_tid(cli, orig_cnum);
    12192        TALLOC_FREE(frame);
    12293        return status;
    12394}
    12495
    125 static NTSTATUS cli_lsa_lookup_name(struct cli_state *cli,
    126                                     const char *name,
    127                                     enum lsa_SidType *type,
    128                                     struct dom_sid *sid)
    129 {
    130         uint16 orig_cnum = cli->cnum;
    131         struct rpc_pipe_client *p;
    132         struct policy_handle handle;
     96static struct dom_sid *get_domain_sid(struct cli_state *cli)
     97{
    13398        NTSTATUS status;
    134         TALLOC_CTX *frame = talloc_stackframe();
    135         struct dom_sid *sids;
    136         enum lsa_SidType *types;
    137 
    138         status = cli_tcon_andx(cli, "IPC$", "?????", "", 0);
    139         if (!NT_STATUS_IS_OK(status)) {
    140                 return status;
    141         }
    142 
    143         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
    144                                           &p);
    145         if (!NT_STATUS_IS_OK(status)) {
    146                 goto fail;
    147         }
    148 
    149         status = rpccli_lsa_open_policy(p, talloc_tos(), True,
    150                                         GENERIC_EXECUTE_ACCESS, &handle);
    151         if (!NT_STATUS_IS_OK(status)) {
    152                 goto fail;
    153         }
    154 
    155         status = rpccli_lsa_lookup_names(p, talloc_tos(), &handle, 1, &name,
    156                                          NULL, 1, &sids, &types);
    157         if (!NT_STATUS_IS_OK(status)) {
    158                 goto fail;
    159         }
    160 
    161         *type = types[0];
    162         *sid = sids[0];
    163 
    164         status = NT_STATUS_OK;
    165  fail:
    166         TALLOC_FREE(p);
    167         cli_tdis(cli);
    168         cli->cnum = orig_cnum;
    169         TALLOC_FREE(frame);
    170         return status;
    171 }
    172 
    173 /* convert a SID to a string, either numeric or username/group */
    174 static void SidToString(struct cli_state *cli, fstring str, const struct dom_sid *sid)
    175 {
    176         char *domain = NULL;
    177         char *name = NULL;
    178         enum lsa_SidType type;
    179         NTSTATUS status;
    180 
    181         sid_to_fstring(str, sid);
    182 
    183         if (numeric) {
    184                 return;
    185         }
    186 
    187         status = cli_lsa_lookup_sid(cli, sid, talloc_tos(), &type,
    188                                     &domain, &name);
    189 
    190         if (!NT_STATUS_IS_OK(status)) {
    191                 return;
    192         }
    193 
    194         if (*domain) {
    195                 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
    196                         domain, lp_winbind_separator(), name);
     99
     100        struct dom_sid *sid = talloc(talloc_tos(), struct dom_sid);
     101        if (sid == NULL) {
     102                DEBUG(0, ("Out of memory\n"));
     103                return NULL;
     104        }
     105
     106        if (domain_sid) {
     107                if (!dom_sid_parse(domain_sid, sid)) {
     108                        DEBUG(0,("failed to parse domain sid\n"));
     109                        TALLOC_FREE(sid);
     110                }
    197111        } else {
    198                 fstrcpy(str, name);
    199         }
    200 }
    201 
    202 /* convert a string to a SID, either numeric or username/group */
    203 static bool StringToSid(struct cli_state *cli, struct dom_sid *sid, const char *str)
    204 {
    205         enum lsa_SidType type;
    206 
    207         if (string_to_sid(sid, str)) {
    208                 return true;
    209         }
    210 
    211         return NT_STATUS_IS_OK(cli_lsa_lookup_name(cli, str, &type, sid));
    212 }
    213 
    214 static void print_ace_flags(FILE *f, uint8_t flags)
    215 {
    216         char *str = talloc_strdup(NULL, "");
    217 
    218         if (!str) {
    219                 goto out;
    220         }
    221 
    222         if (flags & SEC_ACE_FLAG_OBJECT_INHERIT) {
    223                 str = talloc_asprintf(str, "%s%s",
    224                                 str, "OI|");
    225                 if (!str) {
    226                         goto out;
    227                 }
    228         }
    229         if (flags & SEC_ACE_FLAG_CONTAINER_INHERIT) {
    230                 str = talloc_asprintf(str, "%s%s",
    231                                 str, "CI|");
    232                 if (!str) {
    233                         goto out;
    234                 }
    235         }
    236         if (flags & SEC_ACE_FLAG_NO_PROPAGATE_INHERIT) {
    237                 str = talloc_asprintf(str, "%s%s",
    238                                 str, "NP|");
    239                 if (!str) {
    240                         goto out;
    241                 }
    242         }
    243         if (flags & SEC_ACE_FLAG_INHERIT_ONLY) {
    244                 str = talloc_asprintf(str, "%s%s",
    245                                 str, "IO|");
    246                 if (!str) {
    247                         goto out;
    248                 }
    249         }
    250         if (flags & SEC_ACE_FLAG_INHERITED_ACE) {
    251                 str = talloc_asprintf(str, "%s%s",
    252                                 str, "I|");
    253                 if (!str) {
    254                         goto out;
    255                 }
    256         }
    257         /* Ignore define SEC_ACE_FLAG_SUCCESSFUL_ACCESS ( 0x40 )
    258            and SEC_ACE_FLAG_FAILED_ACCESS ( 0x80 ) as they're
    259            audit ace flags. */
    260 
    261         if (str[strlen(str)-1] == '|') {
    262                 str[strlen(str)-1] = '\0';
    263                 fprintf(f, "/%s/", str);
    264         } else {
    265                 fprintf(f, "/0x%x/", flags);
    266         }
    267         TALLOC_FREE(str);
    268         return;
    269 
    270   out:
    271         fprintf(f, "/0x%x/", flags);
    272 }
    273 
    274 /* print an ACE on a FILE, using either numeric or ascii representation */
    275 static void print_ace(struct cli_state *cli, FILE *f, struct security_ace *ace)
    276 {
    277         const struct perm_value *v;
    278         fstring sidstr;
    279         int do_print = 0;
    280         uint32 got_mask;
    281 
    282         SidToString(cli, sidstr, &ace->trustee);
    283 
    284         fprintf(f, "%s:", sidstr);
    285 
    286         if (numeric) {
    287                 fprintf(f, "%d/0x%x/0x%08x",
    288                         ace->type, ace->flags, ace->access_mask);
    289                 return;
    290         }
    291 
    292         /* Ace type */
    293 
    294         if (ace->type == SEC_ACE_TYPE_ACCESS_ALLOWED) {
    295                 fprintf(f, "ALLOWED");
    296         } else if (ace->type == SEC_ACE_TYPE_ACCESS_DENIED) {
    297                 fprintf(f, "DENIED");
    298         } else {
    299                 fprintf(f, "%d", ace->type);
    300         }
    301 
    302         print_ace_flags(f, ace->flags);
    303 
    304         /* Standard permissions */
    305 
    306         for (v = standard_values; v->perm; v++) {
    307                 if (ace->access_mask == v->mask) {
    308                         fprintf(f, "%s", v->perm);
    309                         return;
    310                 }
    311         }
    312 
    313         /* Special permissions.  Print out a hex value if we have
    314            leftover bits in the mask. */
    315 
    316         got_mask = ace->access_mask;
    317 
    318  again:
    319         for (v = special_values; v->perm; v++) {
    320                 if ((ace->access_mask & v->mask) == v->mask) {
    321                         if (do_print) {
    322                                 fprintf(f, "%s", v->perm);
    323                         }
    324                         got_mask &= ~v->mask;
    325                 }
    326         }
    327 
    328         if (!do_print) {
    329                 if (got_mask != 0) {
    330                         fprintf(f, "0x%08x", ace->access_mask);
    331                 } else {
    332                         do_print = 1;
    333                         goto again;
    334                 }
    335         }
    336 }
    337 
    338 static bool parse_ace_flags(const char *str, unsigned int *pflags)
    339 {
    340         const char *p = str;
    341         *pflags = 0;
    342 
    343         while (*p) {
    344                 if (strnequal(p, "OI", 2)) {
    345                         *pflags |= SEC_ACE_FLAG_OBJECT_INHERIT;
    346                         p += 2;
    347                 } else if (strnequal(p, "CI", 2)) {
    348                         *pflags |= SEC_ACE_FLAG_CONTAINER_INHERIT;
    349                         p += 2;
    350                 } else if (strnequal(p, "NP", 2)) {
    351                         *pflags |= SEC_ACE_FLAG_NO_PROPAGATE_INHERIT;
    352                         p += 2;
    353                 } else if (strnequal(p, "IO", 2)) {
    354                         *pflags |= SEC_ACE_FLAG_INHERIT_ONLY;
    355                         p += 2;
    356                 } else if (*p == 'I') {
    357                         *pflags |= SEC_ACE_FLAG_INHERITED_ACE;
    358                         p += 1;
    359                 } else if (*p) {
    360                         return false;
    361                 }
    362 
    363                 switch (*p) {
    364                 case '|':
    365                         p++;
    366                 case '\0':
    367                         continue;
    368                 default:
    369                         return false;
    370                 }
    371         }
    372         return true;
    373 }
    374 
    375 /* parse an ACE in the same format as print_ace() */
    376 static bool parse_ace(struct cli_state *cli, struct security_ace *ace,
    377                       const char *orig_str)
    378 {
    379         char *p;
    380         const char *cp;
    381         char *tok;
    382         unsigned int atype = 0;
    383         unsigned int aflags = 0;
    384         unsigned int amask = 0;
    385         struct dom_sid sid;
    386         uint32_t mask;
    387         const struct perm_value *v;
    388         char *str = SMB_STRDUP(orig_str);
    389         TALLOC_CTX *frame = talloc_stackframe();
    390 
    391         if (!str) {
    392                 TALLOC_FREE(frame);
    393                 return False;
    394         }
    395 
    396         ZERO_STRUCTP(ace);
    397         p = strchr_m(str,':');
    398         if (!p) {
    399                 printf("ACE '%s': missing ':'.\n", orig_str);
    400                 SAFE_FREE(str);
    401                 TALLOC_FREE(frame);
    402                 return False;
    403         }
    404         *p = '\0';
    405         p++;
    406         /* Try to parse numeric form */
    407 
    408         if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
    409             StringToSid(cli, &sid, str)) {
    410                 goto done;
    411         }
    412 
    413         /* Try to parse text form */
    414 
    415         if (!StringToSid(cli, &sid, str)) {
    416                 printf("ACE '%s': failed to convert '%s' to SID\n",
    417                         orig_str, str);
    418                 SAFE_FREE(str);
    419                 TALLOC_FREE(frame);
    420                 return False;
    421         }
    422 
    423         cp = p;
    424         if (!next_token_talloc(frame, &cp, &tok, "/")) {
    425                 printf("ACE '%s': failed to find '/' character.\n",
    426                         orig_str);
    427                 SAFE_FREE(str);
    428                 TALLOC_FREE(frame);
    429                 return False;
    430         }
    431 
    432         if (strncmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
    433                 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
    434         } else if (strncmp(tok, "DENIED", strlen("DENIED")) == 0) {
    435                 atype = SEC_ACE_TYPE_ACCESS_DENIED;
    436         } else {
    437                 printf("ACE '%s': missing 'ALLOWED' or 'DENIED' entry at '%s'\n",
    438                         orig_str, tok);
    439                 SAFE_FREE(str);
    440                 TALLOC_FREE(frame);
    441                 return False;
    442         }
    443 
    444         /* Only numeric form accepted for flags at present */
    445 
    446         if (!next_token_talloc(frame, &cp, &tok, "/")) {
    447                 printf("ACE '%s': bad flags entry at '%s'\n",
    448                         orig_str, tok);
    449                 SAFE_FREE(str);
    450                 TALLOC_FREE(frame);
    451                 return False;
    452         }
    453 
    454         if (tok[0] < '0' || tok[0] > '9') {
    455                 if (!parse_ace_flags(tok, &aflags)) {
    456                         printf("ACE '%s': bad named flags entry at '%s'\n",
    457                                 orig_str, tok);
    458                         SAFE_FREE(str);
    459                         TALLOC_FREE(frame);
    460                         return False;
    461                 }
    462         } else if (strnequal(tok, "0x", 2)) {
    463                 if (!sscanf(tok, "%x", &aflags)) {
    464                         printf("ACE '%s': bad hex flags entry at '%s'\n",
    465                                 orig_str, tok);
    466                         SAFE_FREE(str);
    467                         TALLOC_FREE(frame);
    468                         return False;
    469                 }
    470         } else {
    471                 if (!sscanf(tok, "%i", &aflags)) {
    472                         printf("ACE '%s': bad integer flags entry at '%s'\n",
    473                                 orig_str, tok);
    474                         SAFE_FREE(str);
    475                         TALLOC_FREE(frame);
    476                         return False;
    477                 }
    478         }
    479 
    480         if (!next_token_talloc(frame, &cp, &tok, "/")) {
    481                 printf("ACE '%s': missing / at '%s'\n",
    482                         orig_str, tok);
    483                 SAFE_FREE(str);
    484                 TALLOC_FREE(frame);
    485                 return False;
    486         }
    487 
    488         if (strncmp(tok, "0x", 2) == 0) {
    489                 if (sscanf(tok, "%i", &amask) != 1) {
    490                         printf("ACE '%s': bad hex number at '%s'\n",
    491                                 orig_str, tok);
    492                         SAFE_FREE(str);
    493                         TALLOC_FREE(frame);
    494                         return False;
    495                 }
    496                 goto done;
    497         }
    498 
    499         for (v = standard_values; v->perm; v++) {
    500                 if (strcmp(tok, v->perm) == 0) {
    501                         amask = v->mask;
    502                         goto done;
    503                 }
    504         }
    505 
    506         p = tok;
    507 
    508         while(*p) {
    509                 bool found = False;
    510 
    511                 for (v = special_values; v->perm; v++) {
    512                         if (v->perm[0] == *p) {
    513                                 amask |= v->mask;
    514                                 found = True;
    515                         }
    516                 }
    517 
    518                 if (!found) {
    519                         printf("ACE '%s': bad permission value at '%s'\n",
    520                                 orig_str, p);
    521                         SAFE_FREE(str);
    522                         TALLOC_FREE(frame);
    523                         return False;
    524                 }
    525                 p++;
    526         }
    527 
    528         if (*p) {
    529                 TALLOC_FREE(frame);
    530                 SAFE_FREE(str);
    531                 return False;
    532         }
    533 
    534  done:
    535         mask = amask;
    536         init_sec_ace(ace, &sid, atype, mask, aflags);
    537         TALLOC_FREE(frame);
    538         SAFE_FREE(str);
    539         return True;
     112                status = cli_lsa_lookup_domain_sid(cli, sid);
     113
     114                if (!NT_STATUS_IS_OK(status)) {
     115                        DEBUG(0,("failed to lookup domain sid: %s\n", nt_errstr(status)));
     116                        TALLOC_FREE(sid);
     117                }
     118
     119        }
     120
     121        DEBUG(2,("Domain SID: %s\n", sid_string_dbg(sid)));
     122        return sid;
    540123}
    541124
     
    633216}
    634217
    635 
    636 /* print a ascii version of a security descriptor on a FILE handle */
    637 static void sec_desc_print(struct cli_state *cli, FILE *f, struct security_descriptor *sd)
    638 {
    639         fstring sidstr;
    640         uint32 i;
    641 
    642         fprintf(f, "REVISION:%d\n", sd->revision);
    643         fprintf(f, "CONTROL:0x%x\n", sd->type);
    644 
    645         /* Print owner and group sid */
    646 
    647         if (sd->owner_sid) {
    648                 SidToString(cli, sidstr, sd->owner_sid);
    649         } else {
    650                 fstrcpy(sidstr, "");
    651         }
    652 
    653         fprintf(f, "OWNER:%s\n", sidstr);
    654 
    655         if (sd->group_sid) {
    656                 SidToString(cli, sidstr, sd->group_sid);
    657         } else {
    658                 fstrcpy(sidstr, "");
    659         }
    660 
    661         fprintf(f, "GROUP:%s\n", sidstr);
    662 
    663         /* Print aces */
    664         for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
    665                 struct security_ace *ace = &sd->dacl->aces[i];
    666                 fprintf(f, "ACL:");
    667                 print_ace(cli, f, ace);
    668                 fprintf(f, "\n");
    669         }
    670 
    671 }
    672 
    673218/*****************************************************
    674219get fileinfo for filename
    675220*******************************************************/
    676 static uint16 get_fileinfo(struct cli_state *cli, const char *filename)
     221static uint16_t get_fileinfo(struct cli_state *cli, const char *filename)
    677222{
    678223        uint16_t fnum = (uint16_t)-1;
    679         uint16 mode = 0;
     224        uint16_t mode = 0;
    680225        NTSTATUS status;
    681226
     
    685230        status = cli_ntcreate(cli, filename, 0, CREATE_ACCESS_READ,
    686231                              0, FILE_SHARE_READ|FILE_SHARE_WRITE,
    687                               FILE_OPEN, 0x0, 0x0, &fnum);
     232                              FILE_OPEN, 0x0, 0x0, &fnum, NULL);
    688233        if (!NT_STATUS_IS_OK(status)) {
    689234                printf("Failed to open %s: %s\n", filename, nt_errstr(status));
     
    711256        struct security_descriptor *sd;
    712257        NTSTATUS status;
    713 
    714         /* The desired access below is the only one I could find that works
    715            with NT4, W2KP and Samba */
    716 
    717         status = cli_ntcreate(cli, filename, 0, CREATE_ACCESS_READ,
     258        uint32_t sec_info;
     259        uint32_t desired_access = 0;
     260
     261        if (query_sec_info == -1) {
     262                sec_info = SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL;
     263        } else {
     264                sec_info = query_sec_info;
     265        }
     266
     267        if (sec_info & (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL)) {
     268                desired_access |= SEC_STD_READ_CONTROL;
     269        }
     270        if (sec_info & SECINFO_SACL) {
     271                desired_access |= SEC_FLAG_SYSTEM_SECURITY;
     272        }
     273
     274        if (desired_access == 0) {
     275                desired_access |= SEC_STD_READ_CONTROL;
     276        }
     277
     278        status = cli_ntcreate(cli, filename, 0, desired_access,
    718279                              0, FILE_SHARE_READ|FILE_SHARE_WRITE,
    719                               FILE_OPEN, 0x0, 0x0, &fnum);
     280                              FILE_OPEN, 0x0, 0x0, &fnum, NULL);
    720281        if (!NT_STATUS_IS_OK(status)) {
    721282                printf("Failed to open %s: %s\n", filename, nt_errstr(status));
     
    723284        }
    724285
    725         sd = cli_query_secdesc(cli, fnum, talloc_tos());
     286        status = cli_query_security_descriptor(cli, fnum, sec_info,
     287                                               talloc_tos(), &sd);
    726288
    727289        cli_close(cli, fnum);
    728290
    729         if (!sd) {
    730                 printf("Failed to get security descriptor\n");
     291        if (!NT_STATUS_IS_OK(status)) {
     292                printf("Failed to get security descriptor: %s\n",
     293                       nt_errstr(status));
    731294                return NULL;
    732295        }
     
    743306        bool result=true;
    744307        NTSTATUS status;
    745 
    746         /* The desired access below is the only one I could find that works
    747            with NT4, W2KP and Samba */
     308        uint32_t desired_access = 0;
     309        uint32_t sec_info;
     310
     311        if (set_sec_info == -1) {
     312                sec_info = 0;
     313
     314                if (sd->dacl || (sd->type & SEC_DESC_DACL_PRESENT)) {
     315                        sec_info |= SECINFO_DACL;
     316                }
     317                if (sd->sacl || (sd->type & SEC_DESC_SACL_PRESENT)) {
     318                        sec_info |= SECINFO_SACL;
     319                }
     320                if (sd->owner_sid) {
     321                        sec_info |= SECINFO_OWNER;
     322                }
     323                if (sd->group_sid) {
     324                        sec_info |= SECINFO_GROUP;
     325                }
     326        } else {
     327                sec_info = set_sec_info;
     328        }
     329
     330        /* Make the desired_access more specific. */
     331        if (sec_info & SECINFO_DACL) {
     332                desired_access |= SEC_STD_WRITE_DAC;
     333        }
     334        if (sec_info & SECINFO_SACL) {
     335                desired_access |= SEC_FLAG_SYSTEM_SECURITY;
     336        }
     337        if (sec_info & (SECINFO_OWNER | SECINFO_GROUP)) {
     338                desired_access |= SEC_STD_WRITE_OWNER;
     339        }
    748340
    749341        status = cli_ntcreate(cli, filename, 0,
    750                               WRITE_DAC_ACCESS|WRITE_OWNER_ACCESS,
     342                              desired_access,
    751343                              0, FILE_SHARE_READ|FILE_SHARE_WRITE,
    752                               FILE_OPEN, 0x0, 0x0, &fnum);
     344                              FILE_OPEN, 0x0, 0x0, &fnum, NULL);
    753345        if (!NT_STATUS_IS_OK(status)) {
    754346                printf("Failed to open %s: %s\n", filename, nt_errstr(status));
     
    756348        }
    757349
    758         status = cli_set_secdesc(cli, fnum, sd);
     350        status = cli_set_security_descriptor(cli, fnum, sec_info, sd);
    759351        if (!NT_STATUS_IS_OK(status)) {
    760352                printf("ERROR: security description set failed: %s\n",
     
    770362dump the acls for a file
    771363*******************************************************/
    772 static int cacl_dump(struct cli_state *cli, const char *filename)
    773 {
    774         int result = EXIT_FAILED;
     364static int cacl_dump(struct cli_state *cli, const char *filename, bool numeric)
     365{
    775366        struct security_descriptor *sd;
    776367
    777         if (test_args)
     368        if (test_args) {
    778369                return EXIT_OK;
     370        }
    779371
    780372        sd = get_secdesc(cli, filename);
    781 
    782         if (sd) {
    783                 if (sddl) {
    784                         printf("%s\n", sddl_encode(talloc_tos(), sd,
    785                                            get_global_sam_sid()));
    786                 } else {
    787                         sec_desc_print(cli, stdout, sd);
    788                 }
    789                 result = EXIT_OK;
    790         }
    791 
    792         return result;
     373        if (sd == NULL) {
     374                return EXIT_FAILED;
     375        }
     376
     377        if (sddl) {
     378                char *str = sddl_encode(talloc_tos(), sd, get_domain_sid(cli));
     379                if (str == NULL) {
     380                        return EXIT_FAILED;
     381                }
     382                printf("%s\n", str);
     383                TALLOC_FREE(str);
     384        } else {
     385                sec_desc_print(cli, stdout, sd, numeric);
     386        }
     387
     388        return EXIT_OK;
    793389}
    794390
     
    814410        }
    815411
    816         sd = make_sec_desc(talloc_tos(),old->revision, old->type,
     412        sd = make_sec_desc(talloc_tos(),old->revision, SEC_DESC_SELF_RELATIVE,
    817413                                (change_mode == REQUEST_CHOWN) ? &sid : NULL,
    818414                                (change_mode == REQUEST_CHGRP) ? &sid : NULL,
     
    837433static int ace_compare(struct security_ace *ace1, struct security_ace *ace2)
    838434{
    839         if (sec_ace_equal(ace1, ace2))
     435        if (security_ace_equal(ace1, ace2))
    840436                return 0;
    841437
     
    870466static void sort_acl(struct security_acl *the_acl)
    871467{
    872         uint32 i;
     468        uint32_t i;
    873469        if (!the_acl) return;
    874470
     
    876472
    877473        for (i=1;i<the_acl->num_aces;) {
    878                 if (sec_ace_equal(&the_acl->aces[i-1], &the_acl->aces[i])) {
     474                if (security_ace_equal(&the_acl->aces[i-1],
     475                                       &the_acl->aces[i])) {
    879476                        int j;
    880477                        for (j=i; j<the_acl->num_aces-1; j++) {
     
    893490
    894491static int cacl_set(struct cli_state *cli, const char *filename,
    895                     char *the_acl, enum acl_mode mode)
     492                    char *the_acl, enum acl_mode mode, bool numeric)
    896493{
    897494        struct security_descriptor *sd, *old;
    898         uint32 i, j;
     495        uint32_t i, j;
    899496        size_t sd_size;
    900497        int result = EXIT_OK;
    901498
    902499        if (sddl) {
    903                 sd = sddl_decode(talloc_tos(), the_acl, get_global_sam_sid());
     500                sd = sddl_decode(talloc_tos(), the_acl, get_domain_sid(cli));
    904501        } else {
    905502                sd = sec_desc_parse(talloc_tos(), cli, the_acl);
     
    922519
    923520                        for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
    924                                 if (sec_ace_equal(&sd->dacl->aces[i],
    925                                                   &old->dacl->aces[j])) {
    926                                         uint32 k;
     521                                if (security_ace_equal(&sd->dacl->aces[i],
     522                                                       &old->dacl->aces[j])) {
     523                                        uint32_t k;
    927524                                        for (k=j; k<old->dacl->num_aces-1;k++) {
    928525                                                old->dacl->aces[k] = old->dacl->aces[k+1];
     
    936533                        if (!found) {
    937534                                printf("ACL for ACE:");
    938                                 print_ace(cli, stdout, &sd->dacl->aces[i]);
     535                                print_ace(cli, stdout, &sd->dacl->aces[i],
     536                                          numeric);
    939537                                printf(" not found\n");
    940538                        }
     
    958556
    959557                                SidToString(cli, str,
    960                                             &sd->dacl->aces[i].trustee);
     558                                            &sd->dacl->aces[i].trustee,
     559                                            numeric);
    961560                                printf("ACL for SID %s not found\n", str);
    962561                        }
     
    1014613{
    1015614        struct security_descriptor *old,*sd;
    1016         uint32 oldattr;
     615        uint32_t oldattr;
    1017616        size_t sd_size;
    1018617        int result = EXIT_OK;
     
    1133732{
    1134733        struct cli_state *c = NULL;
    1135         struct sockaddr_storage ss;
    1136734        NTSTATUS nt_status;
    1137735        uint32_t flags = 0;
    1138 
    1139         zero_sockaddr(&ss);
    1140736
    1141737        if (get_cmdline_auth_info_use_kerberos(auth_info)) {
     
    1151747        set_cmdline_auth_info_getpass(auth_info);
    1152748
    1153         nt_status = cli_full_connection(&c, global_myname(), server,
    1154                                 &ss, 0,
     749        nt_status = cli_full_connection(&c, lp_netbios_name(), server,
     750                                NULL, 0,
    1155751                                share, "?????",
    1156752                                get_cmdline_auth_info_username(auth_info),
     
    1182778  main program
    1183779****************************************************************************/
    1184  int main(int argc, const char *argv[])
    1185 {
     780int main(int argc, char *argv[])
     781{
     782        const char **argv_const = discard_const_p(const char *, argv);
    1186783        char *share;
    1187784        int opt;
     
    1193790        char *filename = NULL;
    1194791        poptContext pc;
     792        /* numeric is set when the user wants numeric SIDs and ACEs rather
     793           than going via LSA calls to resolve them */
     794        int numeric = 0;
     795
    1195796        struct poptOption long_options[] = {
    1196797                POPT_AUTOHELP
     
    1204805                { "numeric", 0, POPT_ARG_NONE, &numeric, 1, "Don't resolve sids or masks to names" },
    1205806                { "sddl", 0, POPT_ARG_NONE, &sddl, 1, "Output and input acls in sddl format" },
     807                { "query-security-info", 0, POPT_ARG_INT, &query_sec_info, 1,
     808                  "The security-info flags for queries"
     809                },
     810                { "set-security-info", 0, POPT_ARG_INT, &set_sec_info, 1,
     811                  "The security-info flags for modifications"
     812                },
    1206813                { "test-args", 't', POPT_ARG_NONE, &test_args, 1, "Test arguments"},
     814                { "domain-sid", 0, POPT_ARG_STRING, &domain_sid, 0, "Domain SID for sddl", "SID"},
     815                { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
    1207816                POPT_COMMON_SAMBA
    1208817                POPT_COMMON_CONNECTION
     
    1217826        struct user_auth_info *auth_info;
    1218827
    1219         load_case_tables();
     828        smb_init_locale();
    1220829
    1221830        /* set default debug level to 1 regardless of what smb.conf sets */
     
    1225834        setlinebuf(stdout);
    1226835
    1227         lp_load(get_dyn_CONFIGFILE(),True,False,False,True);
    1228         load_interfaces();
    1229836
    1230837        auth_info = user_auth_info_init(frame);
     
    1234841        popt_common_set_auth_info(auth_info);
    1235842
    1236         pc = poptGetContext("smbcacls", argc, argv, long_options, 0);
     843        pc = poptGetContext("smbcacls", argc, argv_const, long_options, 0);
    1237844
    1238845        poptSetOtherOptionHelp(pc, "//server1/share1 filename\nACLs look like: "
     
    1275882                        change_mode = REQUEST_INHERIT;
    1276883                        break;
     884                case 'm':
     885                        lp_set_cmdline("client max protocol", poptGetOptArg(pc));
     886                        break;
    1277887                }
    1278888        }
     
    1294904        }
    1295905
     906        lp_load_global(get_dyn_CONFIGFILE());
     907        load_interfaces();
     908
    1296909        filename = talloc_strdup(frame, poptGetArg(pc));
    1297910        if (!filename) {
    1298911                return -1;
    1299912        }
     913
     914        poptFreeContext(pc);
     915        popt_burn_cmdline_password(argc, argv);
    1300916
    1301917        string_replace(path,'/','\\');
     
    1340956                result = owner_set(cli, change_mode, filename, owner_username);
    1341957        } else if (the_acl) {
    1342                 result = cacl_set(cli, filename, the_acl, mode);
     958                result = cacl_set(cli, filename, the_acl, mode, numeric);
    1343959        } else {
    1344                 result = cacl_dump(cli, filename);
     960                result = cacl_dump(cli, filename, numeric);
    1345961        }
    1346962
  • vendor/current/source3/utils/smbcontrol.c

    r860 r988  
    1 /* 
     1/*
    22   Unix SMB/CIFS implementation.
    33
     
    3333#include "messages.h"
    3434#include "util_tdb.h"
     35#include "../lib/util/pidfile.h"
     36#include "serverid.h"
    3537
    3638#if HAVE_LIBUNWIND_H
     
    6567                return NT_STATUS_IS_OK(
    6668                        messaging_send_buf(msg_ctx, pid, msg_type,
    67                                            (uint8 *)buf, len));
     69                                           (const uint8_t *)buf, len));
    6870
    6971        ret = message_send_all(msg_ctx, msg_type, buf, len, &n_sent);
     
    8688/* Wait for one or more reply messages */
    8789
    88 static void wait_replies(struct messaging_context *msg_ctx,
     90static void wait_replies(struct tevent_context *ev_ctx,
     91                         struct messaging_context *msg_ctx,
    8992                         bool multiple_replies)
    9093{
     
    9295        bool timed_out = False;
    9396
    94         if (!(te = tevent_add_timer(messaging_event_context(msg_ctx), NULL,
    95                                     timeval_current_ofs(timeout, 0),
    96                                     smbcontrol_timeout, (void *)&timed_out))) {
     97        te = tevent_add_timer(ev_ctx, NULL,
     98                              timeval_current_ofs(timeout, 0),
     99                              smbcontrol_timeout, (void *)&timed_out);
     100        if (te == NULL) {
    97101                DEBUG(0, ("tevent_add_timer failed\n"));
    98102                return;
     
    103107                if (num_replies > 0 && !multiple_replies)
    104108                        break;
    105                 ret = tevent_loop_once(messaging_event_context(msg_ctx));
     109                ret = tevent_loop_once(ev_ctx);
    106110                if (ret != 0) {
    107111                        break;
     
    118122                                DATA_BLOB *data)
    119123{
    120         char *pidstr;
    121 
    122         pidstr = procid_str(talloc_tos(), &pid);
    123         printf("PID %s: %.*s", pidstr, (int)data->length,
    124                (const char *)data->data);
    125         TALLOC_FREE(pidstr);
     124        struct server_id_buf pidstr;
     125
     126        printf("PID %s: %.*s", server_id_str_buf(pid, &pidstr),
     127               (int)data->length, (const char *)data->data);
    126128        num_replies++;
    127129}
     
    141143/* Send no message.  Useful for testing. */
    142144
    143 static bool do_noop(struct messaging_context *msg_ctx,
     145static bool do_noop(struct tevent_context *ev_ctx,
     146                    struct messaging_context *msg_ctx,
    144147                    const struct server_id pid,
    145148                    const int argc, const char **argv)
     
    157160/* Send a debug string */
    158161
    159 static bool do_debug(struct messaging_context *msg_ctx,
     162static bool do_debug(struct tevent_context *ev_ctx,
     163                     struct messaging_context *msg_ctx,
    160164                     const struct server_id pid,
    161165                     const int argc, const char **argv)
     
    172176
    173177
    174 static bool do_idmap(struct messaging_context *msg_ctx,
     178static bool do_idmap(struct tevent_context *ev,
     179                     struct messaging_context *msg_ctx,
    175180                     const struct server_id pid,
    176181                     const int argc, const char **argv)
     
    178183        static const char* usage = "Usage: "
    179184                "smbcontrol <dest> idmap <cmd> [arg]\n"
    180                 "\tcmd:\tflush [gid|uid]\n"
    181                 "\t\tdelete \"UID <uid>\"|\"GID <gid>\"|<sid>\n"
     185                "\tcmd:"
     186                "\tdelete \"UID <uid>\"|\"GID <gid>\"|<sid>\n"
    182187                "\t\tkill \"UID <uid>\"|\"GID <gid>\"|<sid>\n";
    183188        const char* arg = NULL;
     
    197202        }
    198203
    199         if (strcmp(argv[1], "flush") == 0) {
    200                 msg_type = MSG_IDMAP_FLUSH;
    201         }
    202         else if (strcmp(argv[1], "delete") == 0) {
    203                 msg_type = MSG_IDMAP_DELETE;
     204        if (strcmp(argv[1], "delete") == 0) {
     205                msg_type = ID_CACHE_DELETE;
    204206        }
    205207        else if (strcmp(argv[1], "kill") == 0) {
    206                 msg_type = MSG_IDMAP_KILL;
     208                msg_type = ID_CACHE_KILL;
    207209        }
    208210        else if (strcmp(argv[1], "help") == 0) {
     
    222224
    223225/* Return the name of a process given it's PID. This will only work on Linux,
    224  * but that's probably moot since this whole stack tracing implementatino is
     226 * but that's probably moot since this whole stack tracing implementation is
    225227 * Linux-specific anyway.
    226228 */
     
    320322}
    321323
    322 static int stack_trace_connection(const struct connections_key *key,
    323                                   const struct connections_data *crec,
    324                                   void *priv)
    325 {
    326         print_stack_trace(procid_to_pid(&crec->pid), (int *)priv);
    327 
     324static int stack_trace_server(const struct server_id *id,
     325                              uint32_t msg_flags,
     326                              void *priv)
     327{
     328        if (procid_is_local(id)) {
     329                print_stack_trace(procid_to_pid(id), (int *)priv);
     330        }
    328331        return 0;
    329332}
    330333
    331 static bool do_daemon_stack_trace(struct messaging_context *msg_ctx,
     334static bool do_daemon_stack_trace(struct tevent_context *ev_ctx,
     335                                  struct messaging_context *msg_ctx,
    332336                                  const struct server_id pid,
    333                        const int argc, const char **argv)
     337                                  const int argc, const char **argv)
    334338{
    335339        pid_t   dest;
     
    351355                print_stack_trace(dest, &count);
    352356        } else {
    353                 connections_forall_read(stack_trace_connection, &count);
     357                serverid_traverse_read(stack_trace_server, &count);
    354358        }
    355359
     
    359363#else /* defined(HAVE_LIBUNWIND_PTRACE) && defined(HAVE_LINUX_PTRACE) */
    360364
    361 static bool do_daemon_stack_trace(struct messaging_context *msg_ctx,
     365static bool do_daemon_stack_trace(struct tevent_context *ev_ctx,
     366                                  struct messaging_context *msg_ctx,
    362367                                  const struct server_id pid,
    363                        const int argc, const char **argv)
     368                                  const int argc, const char **argv)
    364369{
    365370        fprintf(stderr,
     
    372377/* Inject a fault (fatal signal) into a running smbd */
    373378
    374 static bool do_inject_fault(struct messaging_context *msg_ctx,
     379static bool do_inject_fault(struct tevent_context *ev_ctx,
     380                            struct messaging_context *msg_ctx,
    375381                            const struct server_id pid,
    376                        const int argc, const char **argv)
     382                            const int argc, const char **argv)
    377383{
    378384        if (argc != 2) {
     
    414420/* Force a browser election */
    415421
    416 static bool do_election(struct messaging_context *msg_ctx,
     422static bool do_election(struct tevent_context *ev_ctx,
     423                        struct messaging_context *msg_ctx,
    417424                        const struct server_id pid,
    418425                        const int argc, const char **argv)
     
    434441                    DATA_BLOB *data)
    435442{
    436         char *src_string = procid_str(NULL, &pid);
    437         printf("PONG from pid %s\n", src_string);
    438         TALLOC_FREE(src_string);
     443        struct server_id_buf src_string;
     444        printf("PONG from pid %s\n", server_id_str_buf(pid, &src_string));
    439445        num_replies++;
    440446}
    441447
    442 static bool do_ping(struct messaging_context *msg_ctx,
     448static bool do_ping(struct tevent_context *ev_ctx,
     449                    struct messaging_context *msg_ctx,
    443450                    const struct server_id pid,
    444451                    const int argc, const char **argv)
     
    456463        messaging_register(msg_ctx, NULL, MSG_PONG, pong_cb);
    457464
    458         wait_replies(msg_ctx, procid_to_pid(&pid) == 0);
     465        wait_replies(ev_ctx, msg_ctx, procid_to_pid(&pid) == 0);
    459466
    460467        /* No replies were received within the timeout period */
     
    470477/* Set profiling options */
    471478
    472 static bool do_profile(struct messaging_context *msg_ctx,
     479static bool do_profile(struct tevent_context *ev_ctx,
     480                       struct messaging_context *msg_ctx,
    473481                       const struct server_id pid,
    474482                       const int argc, const char **argv)
     
    553561}
    554562
    555 static bool do_profilelevel(struct messaging_context *msg_ctx,
     563static bool do_profilelevel(struct tevent_context *ev_ctx,
     564                            struct messaging_context *msg_ctx,
    556565                            const struct server_id pid,
    557566                            const int argc, const char **argv)
     
    571580                           profilelevel_rqst);
    572581
    573         wait_replies(msg_ctx, procid_to_pid(&pid) == 0);
     582        wait_replies(ev_ctx, msg_ctx, procid_to_pid(&pid) == 0);
    574583
    575584        /* No replies were received within the timeout period */
     
    585594/* Display debug level settings */
    586595
    587 static bool do_debuglevel(struct messaging_context *msg_ctx,
     596static bool do_debuglevel(struct tevent_context *ev_ctx,
     597                          struct messaging_context *msg_ctx,
    588598                          const struct server_id pid,
    589599                          const int argc, const char **argv)
     
    601611        messaging_register(msg_ctx, NULL, MSG_DEBUGLEVEL, print_pid_string_cb);
    602612
    603         wait_replies(msg_ctx, procid_to_pid(&pid) == 0);
     613        wait_replies(ev_ctx, msg_ctx, procid_to_pid(&pid) == 0);
    604614
    605615        /* No replies were received within the timeout period */
     
    615625/* Send a print notify message */
    616626
    617 static bool do_printnotify(struct messaging_context *msg_ctx,
     627static bool do_printnotify(struct tevent_context *ev_ctx,
     628                           struct messaging_context *msg_ctx,
    618629                           const struct server_id pid,
    619630                           const int argc, const char **argv)
     
    646657                }
    647658
    648                 notify_printer_status_byname(messaging_event_context(msg_ctx),
    649                                              msg_ctx, argv[2],
     659                notify_printer_status_byname(ev_ctx, msg_ctx, argv[2],
    650660                                             PRINTER_STATUS_PAUSED);
    651661
     
    660670                }
    661671
    662                 notify_printer_status_byname(messaging_event_context(msg_ctx),
    663                                              msg_ctx, argv[2],
     672                notify_printer_status_byname(ev_ctx, msg_ctx, argv[2],
    664673                                             PRINTER_STATUS_OK);
    665674
     
    678687
    679688                notify_job_status_byname(
    680                         messaging_event_context(msg_ctx), msg_ctx,
     689                        ev_ctx, msg_ctx,
    681690                        argv[2], jobid, JOB_STATUS_PAUSED,
    682691                        SPOOLSS_NOTIFY_MSG_UNIX_JOBID);
     
    696705
    697706                notify_job_status_byname(
    698                         messaging_event_context(msg_ctx), msg_ctx,
     707                        ev_ctx, msg_ctx,
    699708                        argv[2], jobid, JOB_STATUS_QUEUED,
    700709                        SPOOLSS_NOTIFY_MSG_UNIX_JOBID);
     
    714723
    715724                notify_job_status_byname(
    716                         messaging_event_context(msg_ctx), msg_ctx,
     725                        ev_ctx, msg_ctx,
    717726                        argv[2], jobid, JOB_STATUS_DELETING,
    718727                        SPOOLSS_NOTIFY_MSG_UNIX_JOBID);
    719728
    720729                notify_job_status_byname(
    721                         messaging_event_context(msg_ctx), msg_ctx,
     730                        ev_ctx, msg_ctx,
    722731                        argv[2], jobid, JOB_STATUS_DELETING|
    723732                        JOB_STATUS_DELETED,
     
    727736
    728737        } else if (strcmp(cmd, "printer") == 0) {
    729                 uint32 attribute;
     738                uint32_t attribute;
    730739
    731740                if (argc != 5) {
     
    748757                }
    749758
    750                 notify_printer_byname(messaging_event_context(msg_ctx),
    751                                       msg_ctx, argv[2], attribute,
    752                                       CONST_DISCARD(char *, argv[4]));
     759                notify_printer_byname(ev_ctx, msg_ctx, argv[2], attribute,
     760                                      discard_const_p(char, argv[4]));
    753761
    754762                goto send;
     
    765773/* Close a share */
    766774
    767 static bool do_closeshare(struct messaging_context *msg_ctx,
     775static bool do_closeshare(struct tevent_context *ev_ctx,
     776                          struct messaging_context *msg_ctx,
    768777                          const struct server_id pid,
    769778                          const int argc, const char **argv)
     
    779788}
    780789
     790/* Kill a client by IP address */
     791static bool do_kill_client_by_ip(struct tevent_context *ev_ctx,
     792                                 struct messaging_context *msg_ctx,
     793                                 const struct server_id pid,
     794                                 const int argc, const char **argv)
     795{
     796        if (argc != 2) {
     797                fprintf(stderr, "Usage: smbcontrol <dest> kill-client-ip "
     798                        "<IP address>\n");
     799                return false;
     800        }
     801
     802        if (!is_ipaddress_v4(argv[1]) && !is_ipaddress_v6(argv[1])) {
     803                fprintf(stderr, "%s is not a valid IP address!\n", argv[1]);
     804                return false;
     805        }
     806
     807        return send_message(msg_ctx, pid, MSG_SMB_KILL_CLIENT_IP,
     808                            argv[1], strlen(argv[1]) + 1);
     809}
     810
    781811/* Tell winbindd an IP got dropped */
    782812
    783 static bool do_ip_dropped(struct messaging_context *msg_ctx,
     813static bool do_ip_dropped(struct tevent_context *ev_ctx,
     814                          struct messaging_context *msg_ctx,
    784815                          const struct server_id pid,
    785816                          const int argc, const char **argv)
     
    797828/* force a blocking lock retry */
    798829
    799 static bool do_lockretry(struct messaging_context *msg_ctx,
     830static bool do_lockretry(struct tevent_context *ev_ctx,
     831                         struct messaging_context *msg_ctx,
    800832                         const struct server_id pid,
    801833                         const int argc, const char **argv)
     
    811843/* force a validation of all brl entries, including re-sends. */
    812844
    813 static bool do_brl_revalidate(struct messaging_context *msg_ctx,
     845static bool do_brl_revalidate(struct tevent_context *ev_ctx,
     846                              struct messaging_context *msg_ctx,
    814847                              const struct server_id pid,
    815848                              const int argc, const char **argv)
     
    823856}
    824857
    825 /* Force a SAM synchronisation */
    826 
    827 static bool do_samsync(struct messaging_context *msg_ctx,
    828                        const struct server_id pid,
    829                        const int argc, const char **argv)
    830 {
    831         if (argc != 1) {
    832                 fprintf(stderr, "Usage: smbcontrol <dest> samsync\n");
    833                 return False;
    834         }
    835 
    836         return send_message(msg_ctx, pid, MSG_SMB_SAM_SYNC, NULL, 0);
    837 }
    838 
    839 /* Force a SAM replication */
    840 
    841 static bool do_samrepl(struct messaging_context *msg_ctx,
    842                        const struct server_id pid,
    843                        const int argc, const char **argv)
    844 {
    845         if (argc != 1) {
    846                 fprintf(stderr, "Usage: smbcontrol <dest> samrepl\n");
    847                 return False;
    848         }
    849 
    850         return send_message(msg_ctx, pid, MSG_SMB_SAM_REPL, NULL, 0);
    851 }
    852 
    853858/* Display talloc pool usage */
    854859
    855 static bool do_poolusage(struct messaging_context *msg_ctx,
     860static bool do_poolusage(struct tevent_context *ev_ctx,
     861                         struct messaging_context *msg_ctx,
    856862                         const struct server_id pid,
    857863                         const int argc, const char **argv)
     
    869875                return False;
    870876
    871         wait_replies(msg_ctx, procid_to_pid(&pid) == 0);
     877        wait_replies(ev_ctx, msg_ctx, procid_to_pid(&pid) == 0);
    872878
    873879        /* No replies were received within the timeout period */
     
    883889/* Perform a dmalloc mark */
    884890
    885 static bool do_dmalloc_mark(struct messaging_context *msg_ctx,
     891static bool do_dmalloc_mark(struct tevent_context *ev_ctx,
     892                            struct messaging_context *msg_ctx,
    886893                            const struct server_id pid,
    887894                            const int argc, const char **argv)
     
    897904/* Perform a dmalloc changed */
    898905
    899 static bool do_dmalloc_changed(struct messaging_context *msg_ctx,
     906static bool do_dmalloc_changed(struct tevent_context *ev_ctx,
     907                               struct messaging_context *msg_ctx,
    900908                               const struct server_id pid,
    901909                               const int argc, const char **argv)
     
    911919}
    912920
     921static void print_uint32_cb(struct messaging_context *msg, void *private_data,
     922                            uint32_t msg_type, struct server_id pid,
     923                            DATA_BLOB *data)
     924{
     925        uint32_t num_children;
     926
     927        if (data->length != sizeof(uint32_t)) {
     928                printf("Invalid response: %d bytes long\n",
     929                       (int)data->length);
     930                goto done;
     931        }
     932        num_children = IVAL(data->data, 0);
     933        printf("%u children\n", (unsigned)num_children);
     934done:
     935        num_replies++;
     936}
     937
     938static bool do_num_children(struct tevent_context *ev_ctx,
     939                            struct messaging_context *msg_ctx,
     940                            const struct server_id pid,
     941                            const int argc, const char **argv)
     942{
     943        if (argc != 1) {
     944                fprintf(stderr, "Usage: smbcontrol <dest> num-children\n");
     945                return False;
     946        }
     947
     948        messaging_register(msg_ctx, NULL, MSG_SMB_NUM_CHILDREN,
     949                           print_uint32_cb);
     950
     951        /* Send a message and register our interest in a reply */
     952
     953        if (!send_message(msg_ctx, pid, MSG_SMB_TELL_NUM_CHILDREN, NULL, 0))
     954                return false;
     955
     956        wait_replies(ev_ctx, msg_ctx, procid_to_pid(&pid) == 0);
     957
     958        /* No replies were received within the timeout period */
     959
     960        if (num_replies == 0)
     961                printf("No replies received\n");
     962
     963        messaging_deregister(msg_ctx, MSG_SMB_NUM_CHILDREN, NULL);
     964
     965        return num_replies;
     966}
     967
     968static bool do_msg_cleanup(struct tevent_context *ev_ctx,
     969                           struct messaging_context *msg_ctx,
     970                           const struct server_id pid,
     971                           const int argc, const char **argv)
     972{
     973        int ret;
     974
     975        ret = messaging_cleanup(msg_ctx, pid.pid);
     976
     977        printf("cleanup(%u) returned %s\n", (unsigned)pid.pid,
     978               ret ? strerror(ret) : "ok");
     979
     980        return (ret == 0);
     981}
     982
    913983/* Shutdown a server process */
    914984
    915 static bool do_shutdown(struct messaging_context *msg_ctx,
     985static bool do_shutdown(struct tevent_context *ev_ctx,
     986                        struct messaging_context *msg_ctx,
    916987                        const struct server_id pid,
    917988                        const int argc, const char **argv)
     
    927998/* Notify a driver upgrade */
    928999
    929 static bool do_drvupgrade(struct messaging_context *msg_ctx,
     1000static bool do_drvupgrade(struct tevent_context *ev_ctx,
     1001                          struct messaging_context *msg_ctx,
    9301002                          const struct server_id pid,
    9311003                          const int argc, const char **argv)
     
    9411013}
    9421014
    943 static bool do_winbind_online(struct messaging_context *msg_ctx,
     1015static bool do_winbind_online(struct tevent_context *ev_ctx,
     1016                              struct messaging_context *msg_ctx,
    9441017                              const struct server_id pid,
    945                              const int argc, const char **argv)
     1018                              const int argc, const char **argv)
    9461019{
    9471020        TDB_CONTEXT *tdb;
     1021        char *db_path;
    9481022
    9491023        if (argc != 1) {
    9501024                fprintf(stderr, "Usage: smbcontrol winbindd online\n");
    9511025                return False;
     1026        }
     1027
     1028        db_path = state_path("winbindd_cache.tdb");
     1029        if (db_path == NULL) {
     1030                return false;
    9521031        }
    9531032
     
    9551034           starting winbindd that we're online. */
    9561035
    957         tdb = tdb_open_log(cache_path("winbindd_cache.tdb"), 0, TDB_DEFAULT, O_RDWR, 0600);
     1036        tdb = tdb_open_log(db_path, 0, TDB_DEFAULT, O_RDWR, 0600);
    9581037        if (!tdb) {
    9591038                fprintf(stderr, "Cannot open the tdb %s for writing.\n",
    960                         cache_path("winbindd_cache.tdb"));
    961                 return False;
    962         }
    963 
     1039                        db_path);
     1040                TALLOC_FREE(db_path);
     1041                return False;
     1042        }
     1043
     1044        TALLOC_FREE(db_path);
    9641045        tdb_delete_bystring(tdb, "WINBINDD_OFFLINE");
    9651046        tdb_close(tdb);
     
    9681049}
    9691050
    970 static bool do_winbind_offline(struct messaging_context *msg_ctx,
     1051static bool do_winbind_offline(struct tevent_context *ev_ctx,
     1052                               struct messaging_context *msg_ctx,
    9711053                               const struct server_id pid,
    972                              const int argc, const char **argv)
     1054                               const int argc, const char **argv)
    9731055{
    9741056        TDB_CONTEXT *tdb;
    9751057        bool ret = False;
    9761058        int retry = 0;
     1059        char *db_path;
    9771060
    9781061        if (argc != 1) {
    9791062                fprintf(stderr, "Usage: smbcontrol winbindd offline\n");
    9801063                return False;
     1064        }
     1065
     1066        db_path = state_path("winbindd_cache.tdb");
     1067        if (db_path == NULL) {
     1068                return false;
    9811069        }
    9821070
     
    9851073           it here... */
    9861074
    987         tdb = tdb_open_log(cache_path("winbindd_cache.tdb"),
     1075        tdb = tdb_open_log(db_path,
    9881076                                WINBINDD_CACHE_TDB_DEFAULT_HASH_SIZE,
    9891077                                TDB_DEFAULT|TDB_INCOMPATIBLE_HASH /* TDB_CLEAR_IF_FIRST */,
     
    9921080        if (!tdb) {
    9931081                fprintf(stderr, "Cannot open the tdb %s for writing.\n",
    994                         cache_path("winbindd_cache.tdb"));
    995                 return False;
    996         }
     1082                        db_path);
     1083                TALLOC_FREE(db_path);
     1084                return False;
     1085        }
     1086        TALLOC_FREE(db_path);
    9971087
    9981088        /* There's a potential race condition that if a child
     
    10041094
    10051095        for (retry = 0; retry < 5; retry++) {
    1006                 TDB_DATA d;
    1007                 uint8 buf[4];
    1008 
    1009                 ZERO_STRUCT(d);
     1096                uint8_t buf[4];
     1097                TDB_DATA d = { .dptr = buf, .dsize = sizeof(buf) };
    10101098
    10111099                SIVAL(buf, 0, time(NULL));
    1012                 d.dptr = buf;
    1013                 d.dsize = 4;
    10141100
    10151101                tdb_store_bystring(tdb, "WINBINDD_OFFLINE", d, TDB_INSERT);
     
    10341120}
    10351121
    1036 static bool do_winbind_onlinestatus(struct messaging_context *msg_ctx,
     1122static bool do_winbind_onlinestatus(struct tevent_context *ev_ctx,
     1123                                    struct messaging_context *msg_ctx,
    10371124                                    const struct server_id pid,
    10381125                                    const int argc, const char **argv)
     
    10541141                return False;
    10551142
    1056         wait_replies(msg_ctx, procid_to_pid(&pid) == 0);
     1143        wait_replies(ev_ctx, msg_ctx, procid_to_pid(&pid) == 0);
    10571144
    10581145        /* No replies were received within the timeout period */
     
    10661153}
    10671154
    1068 static bool do_dump_event_list(struct messaging_context *msg_ctx,
     1155static bool do_dump_event_list(struct tevent_context *ev_ctx,
     1156                               struct messaging_context *msg_ctx,
    10691157                               const struct server_id pid,
    10701158                               const int argc, const char **argv)
    10711159{
    1072         struct server_id myid;
    1073 
    1074         myid = messaging_server_id(msg_ctx);
    1075 
    10761160        if (argc != 1) {
    10771161                fprintf(stderr, "Usage: smbcontrol <dest> dump-event-list\n");
     
    10821166}
    10831167
    1084 static bool do_winbind_dump_domain_list(struct messaging_context *msg_ctx,
     1168static bool do_winbind_dump_domain_list(struct tevent_context *ev_ctx,
     1169                                        struct messaging_context *msg_ctx,
    10851170                                        const struct server_id pid,
    10861171                                        const int argc, const char **argv)
     
    11241209        }
    11251210
    1126         wait_replies(msg_ctx, procid_to_pid(&pid) == 0);
     1211        wait_replies(ev_ctx, msg_ctx, procid_to_pid(&pid) == 0);
    11271212
    11281213        /* No replies were received within the timeout period */
     
    11441229                                      DATA_BLOB *data)
    11451230{
    1146         char *src_string = procid_str(NULL, &pid);
     1231        struct server_id_buf src_string;
    11471232        printf("Winbindd cache is %svalid. (answer from pid %s)\n",
    1148                (*(data->data) == 0 ? "" : "NOT "), src_string);
    1149         TALLOC_FREE(src_string);
     1233               (*(data->data) == 0 ? "" : "NOT "),
     1234               server_id_str_buf(pid, &src_string));
    11501235        num_replies++;
    11511236}
    11521237
    1153 static bool do_winbind_validate_cache(struct messaging_context *msg_ctx,
     1238static bool do_winbind_validate_cache(struct tevent_context *ev_ctx,
     1239                                      struct messaging_context *msg_ctx,
    11541240                                      const struct server_id pid,
    11551241                                      const int argc, const char **argv)
     
    11721258        }
    11731259
    1174         wait_replies(msg_ctx, procid_to_pid(&pid) == 0);
     1260        wait_replies(ev_ctx, msg_ctx, procid_to_pid(&pid) == 0);
    11751261
    11761262        if (num_replies == 0) {
     
    11831269}
    11841270
    1185 static bool do_reload_config(struct messaging_context *msg_ctx,
     1271static bool do_reload_config(struct tevent_context *ev_ctx,
     1272                             struct messaging_context *msg_ctx,
    11861273                             const struct server_id pid,
    11871274                             const int argc, const char **argv)
     
    11931280
    11941281        return send_message(msg_ctx, pid, MSG_SMB_CONF_UPDATED, NULL, 0);
     1282}
     1283
     1284static bool do_reload_printers(struct tevent_context *ev_ctx,
     1285                               struct messaging_context *msg_ctx,
     1286                               const struct server_id pid,
     1287                               const int argc, const char **argv)
     1288{
     1289        if (argc != 1) {
     1290                fprintf(stderr, "Usage: smbcontrol <dest> reload-printers\n");
     1291                return False;
     1292        }
     1293
     1294        return send_message(msg_ctx, pid, MSG_PRINTER_PCAP, NULL, 0);
    11951295}
    11961296
     
    12001300        memset( (char *)n, '\0', sizeof(struct nmb_name) );
    12011301        fstrcpy(unix_name, name);
    1202         strupper_m(unix_name);
     1302        (void)strupper_m(unix_name);
    12031303        push_ascii(n->name, unix_name, sizeof(n->name), STR_TERMINATE);
    12041304        n->name_type = (unsigned int)type & 0xFF;
    1205         push_ascii(n->scope,  global_scope(), 64, STR_TERMINATE);
    1206 }
    1207 
    1208 static bool do_nodestatus(struct messaging_context *msg_ctx,
     1305        push_ascii(n->scope,  lp_netbios_scope(), 64, STR_TERMINATE);
     1306}
     1307
     1308static bool do_nodestatus(struct tevent_context *ev_ctx,
     1309                          struct messaging_context *msg_ctx,
    12091310                          const struct server_id pid,
    12101311                          const int argc, const char **argv)
     
    12431344}
    12441345
     1346static bool do_notify_cleanup(struct tevent_context *ev_ctx,
     1347                              struct messaging_context *msg_ctx,
     1348                              const struct server_id pid,
     1349                              const int argc, const char **argv)
     1350{
     1351        if (argc != 1) {
     1352                fprintf(stderr, "Usage: smbcontrol smbd notify-cleanup\n");
     1353                return false;
     1354        }
     1355        return send_message(msg_ctx, pid, MSG_SMB_NOTIFY_CLEANUP, NULL, 0);
     1356}
     1357
    12451358/* A list of message type supported */
    12461359
    12471360static const struct {
    12481361        const char *name;       /* Option name */
    1249         bool (*fn)(struct messaging_context *msg_ctx,
     1362        bool (*fn)(struct tevent_context *ev_ctx,
     1363                   struct messaging_context *msg_ctx,
    12501364                   const struct server_id pid,
    12511365                   const int argc, const char **argv);
     
    12661380        { "printnotify", do_printnotify, "Send a print notify message" },
    12671381        { "close-share", do_closeshare, "Forcibly disconnect a share" },
     1382        { "kill-client-ip", do_kill_client_by_ip,
     1383          "Forcibly disconnect a client with a specific IP address" },
    12681384        { "ip-dropped", do_ip_dropped, "Tell winbind that an IP got dropped" },
    12691385        { "lockretry", do_lockretry, "Force a blocking lock retry" },
    12701386        { "brl-revalidate", do_brl_revalidate, "Revalidate all brl entries" },
    1271         { "samsync", do_samsync, "Initiate SAM synchronisation" },
    1272         { "samrepl", do_samrepl, "Initiate SAM replication" },
    12731387        { "pool-usage", do_poolusage, "Display talloc memory usage" },
    12741388        { "dmalloc-mark", do_dmalloc_mark, "" },
     
    12771391        { "drvupgrade", do_drvupgrade, "Notify a printer driver has changed" },
    12781392        { "reload-config", do_reload_config, "Force smbd or winbindd to reload config file"},
     1393        { "reload-printers", do_reload_printers, "Force smbd to reload printers"},
    12791394        { "nodestatus", do_nodestatus, "Ask nmbd to do a node status request"},
    12801395        { "online", do_winbind_online, "Ask winbind to go into online state"},
     
    12851400          "Validate winbind's credential cache" },
    12861401        { "dump-domain-list", do_winbind_dump_domain_list, "Dump winbind domain list"},
     1402        { "notify-cleanup", do_notify_cleanup },
     1403        { "num-children", do_num_children,
     1404          "Print number of smbd child processes" },
     1405        { "msg-cleanup", do_msg_cleanup },
    12871406        { "noop", do_noop, "Do nothing" },
    12881407        { NULL }
     
    13481467        /* Look up other destinations in pidfile directory */
    13491468
    1350         if ((pid = pidfile_pid(dest)) != 0) {
     1469        if ((pid = pidfile_pid(lp_pid_directory(), dest)) != 0) {
    13511470                return pid_to_procid(pid);
    13521471        }
     
    13591478/* Execute smbcontrol command */
    13601479
    1361 static bool do_command(struct messaging_context *msg_ctx,
     1480static bool do_command(struct tevent_context *ev_ctx,
     1481                       struct messaging_context *msg_ctx,
    13621482                       int argc, const char **argv)
    13631483{
     
    13771497        for (i = 0; msg_types[i].name; i++) {
    13781498                if (strequal(command, msg_types[i].name))
    1379                         return msg_types[i].fn(msg_ctx, pid,
     1499                        return msg_types[i].fn(ev_ctx, msg_ctx, pid,
    13801500                                               argc - 1, argv + 1);
    13811501        }
     
    14311551        int ret = 0;
    14321552
    1433         load_case_tables();
     1553        smb_init_locale();
    14341554
    14351555        setup_logging(argv[0], DEBUG_STDOUT);
     1556        lp_set_cmdline("log level", "0");
    14361557
    14371558        /* Parse command line arguments using popt */
     
    14721593                usage(pc);
    14731594
    1474         lp_load(get_dyn_CONFIGFILE(),False,False,False,True);
     1595        lp_load_global(get_dyn_CONFIGFILE());
    14751596
    14761597        /* Need to invert sense of return code -- samba
     
    14781599         * shell needs 0. */
    14791600
    1480         if (!(evt_ctx = tevent_context_init(NULL)) ||
    1481             !(msg_ctx = messaging_init(NULL, procid_self(), evt_ctx))) {
     1601        if (!(evt_ctx = samba_tevent_context_init(NULL)) ||
     1602            !(msg_ctx = messaging_init(NULL, evt_ctx))) {
    14821603                fprintf(stderr, "could not init messaging context\n");
    14831604                TALLOC_FREE(frame);
     
    14851606        }
    14861607
    1487         ret = !do_command(msg_ctx, argc, argv);
     1608        ret = !do_command(evt_ctx, msg_ctx, argc, argv);
     1609        TALLOC_FREE(msg_ctx);
    14881610        TALLOC_FREE(frame);
    14891611        return ret;
  • vendor/current/source3/utils/smbcquotas.c

    r740 r988  
    5959                cli_ipc = connect_one("IPC$");
    6060                ret = cli_rpc_pipe_open_noauth(cli_ipc,
    61                                                &ndr_table_lsarpc.syntax_id,
     61                                               &ndr_table_lsarpc,
    6262                                               &global_pipe_hnd);
    6363                if (!NT_STATUS_IS_OK(ret)) {
     
    188188        switch (todo) {
    189189                case PARSE_LIM:
    190                         if (sscanf(p,"%"PRIu64"/%"PRIu64,&pqt->softlim,&pqt->hardlim)!=2) {
     190                        if (sscanf(p,"%"SCNu64"/%"SCNu64,&pqt->softlim,
     191                            &pqt->hardlim) != 2)
     192                        {
    191193                                return -1;
    192194                        }
     
    235237        const char *result;
    236238
    237         if (!_numeric&&special&&(val == SMB_NTQUOTAS_NO_LIMIT)) {
     239        if (!_numeric && special && val == 0) {
    238240                return "NO LIMIT";
    239241        }
     
    331333static int do_quota(struct cli_state *cli,
    332334                enum SMB_QUOTA_TYPE qtype,
    333                 uint16 cmd,
     335                uint16_t cmd,
    334336                const char *username_str,
    335337                SMB_NTQUOTA_STRUCT *pqt)
    336338{
    337         uint32 fs_attrs = 0;
     339        uint32_t fs_attrs = 0;
    338340        uint16_t quota_fnum = 0;
    339341        SMB_NTQUOTA_LIST *qtl = NULL;
     
    505507{
    506508        struct cli_state *c;
    507         struct sockaddr_storage ss;
    508509        NTSTATUS nt_status;
    509510        uint32_t flags = 0;
    510 
    511         zero_sockaddr(&ss);
    512511
    513512        if (get_cmdline_auth_info_use_machine_account(smbcquotas_auth_info) &&
     
    524523        set_cmdline_auth_info_getpass(smbcquotas_auth_info);
    525524
    526         nt_status = cli_full_connection(&c, global_myname(), server,
    527                                             &ss, 0,
     525        nt_status = cli_full_connection(&c, lp_netbios_name(), server,
     526                                            NULL, 0,
    528527                                            share, "?????",
    529528                                            get_cmdline_auth_info_username(smbcquotas_auth_info),
     
    555554  main program
    556555****************************************************************************/
    557  int main(int argc, const char *argv[])
    558 {
     556int main(int argc, char *argv[])
     557{
     558        const char **argv_const = discard_const_p(const char *, argv);
    559559        char *share;
    560560        int opt;
     
    584584                { "numeric", 'n', POPT_ARG_NONE, NULL, 'n', "Don't resolve sids or limits to names" },
    585585                { "verbose", 'v', POPT_ARG_NONE, NULL, 'v', "be verbose" },
    586                 { "test-args", 't', POPT_ARG_NONE, NULL, 'r', "Test arguments"},
     586                { "test-args", 't', POPT_ARG_NONE, NULL, 't', "Test arguments"},
    587587                POPT_COMMON_SAMBA
    588588                POPT_COMMON_CREDENTIALS
     
    590590        };
    591591
    592         load_case_tables();
     592        smb_init_locale();
    593593
    594594        ZERO_STRUCT(qt);
     
    600600        setlinebuf(stdout);
    601601
    602         fault_setup(NULL);
    603 
    604         lp_load(get_dyn_CONFIGFILE(),True,False,False,True);
     602        fault_setup();
     603
     604        lp_load_global(get_dyn_CONFIGFILE());
    605605        load_interfaces();
    606606
     
    611611        popt_common_set_auth_info(smbcquotas_auth_info);
    612612
    613         pc = poptGetContext("smbcquotas", argc, argv, long_options, 0);
     613        pc = poptGetContext("smbcquotas", argc, argv_const, long_options, 0);
    614614
    615615        poptSetOtherOptionHelp(pc, "//server1/share1");
     
    692692        }
    693693
     694        poptFreeContext(pc);
     695        popt_burn_cmdline_password(argc, argv);
     696
    694697        string_replace(path, '/', '\\');
    695698
  • vendor/current/source3/utils/smbfilter.c

    r740 r988  
    2323#include "../lib/util/select.h"
    2424#include "libsmb/nmblib.h"
     25#include "lib/util/sys_rw_data.h"
    2526
    2627#define SECURITY_MASK 0
     
    3637
    3738static char *netbiosname;
    38 static char packet[BUFFER_SIZE];
    3939
    4040static void save_file(const char *fname, void *ppacket, size_t length)
     
    8686        unsigned x;
    8787        fstring name1,name2;
    88         int name_len1, name_len2;
     88        int name_len1 = 0;
     89        int name_len2;
    8990        int name_type1, name_type2;
    9091
     
    179180        NTSTATUS status;
    180181        int s = -1;
     182        char packet[128*1024];
    181183
    182184        /* we have a connection from a new client, now connect to the server */
    183         status = open_socket_out(dest_ss, 445, LONG_CONNECT_TIMEOUT, &s);
    184 
    185         if (s == -1) {
     185        status = open_socket_out(dest_ss, TCP_SMB_PORT, LONG_CONNECT_TIMEOUT, &s);
     186        if (!NT_STATUS_IS_OK(status)) {
    186187                char addr[INET6_ADDRSTRLEN];
    187188                if (dest_ss) {
     
    190191
    191192                d_printf("Unable to connect to %s (%s)\n",
    192                          dest_ss?addr:"NULL",strerror(errno));
     193                         dest_ss?addr:"NULL", nt_errstr(status));
    193194                exit(1);
    194195        }
     
    279280
    280281        zero_sockaddr(&my_ss);
    281         s = open_socket_in(SOCK_STREAM, 445, 0, &my_ss, True);
     282        s = open_socket_in(SOCK_STREAM, TCP_SMB_PORT, 0, &my_ss, True);
    282283
    283284        if (s == -1) {
     
    323324        TALLOC_CTX *frame = talloc_stackframe();
    324325
    325         load_case_tables();
     326        smb_init_locale();
    326327
    327328        setup_logging(argv[0], DEBUG_STDOUT);
     
    339340        }
    340341
    341         if (!lp_load(configfile,True,False,False,True)) {
     342        if (!lp_load_global(configfile)) {
    342343                d_printf("Unable to load config file\n");
    343344        }
  • vendor/current/source3/utils/smbget.c

    r740 r988  
    11/*
    2    smbget: a wget-like utility with support for recursive downloading and
    3         smb:// urls
     2   smbget: a wget-like utility with support for recursive downloading of
     3        smb:// urls
    44   Copyright (C) 2003-2004 Jelmer Vernooij <jelmer@samba.org>
    55
     
    2222#include "libsmbclient.h"
    2323
    24 #if _FILE_OFFSET_BITS==64
    25 #define OFF_T_FORMAT "%lld"
    26 #define OFF_T_FORMAT_CAST long long
    27 #else
    28 #define OFF_T_FORMAT "%ld"
    29 #define OFF_T_FORMAT_CAST long
    30 #endif
    31 
    3224static int columns = 0;
    33 
    34 static int debuglevel, update;
    35 static char *outputfile;
    36 
    3725
    3826static time_t total_start_time = 0;
     
    4129#define SMB_MAXPATHLEN MAXPATHLEN
    4230
    43 /* Number of bytes to read when checking whether local and remote file are really the same file */
    44 #define RESUME_CHECK_SIZE                               512
    45 #define RESUME_DOWNLOAD_OFFSET                  1024
    46 #define RESUME_CHECK_OFFSET                             RESUME_DOWNLOAD_OFFSET+RESUME_CHECK_SIZE
     31/*
     32 * Number of bytes to read when checking whether local and remote file
     33 * are really the same file
     34 */
     35#define RESUME_CHECK_SIZE       512
     36#define RESUME_DOWNLOAD_OFFSET  1024
     37#define RESUME_CHECK_OFFSET     (RESUME_DOWNLOAD_OFFSET+RESUME_CHECK_SIZE)
    4738/* Number of bytes to read at once */
    48 #define SMB_DEFAULT_BLOCKSIZE                                   64000
    49 
    50 static const char *username = NULL, *password = NULL, *workgroup = NULL;
    51 static int nonprompt = 0, quiet = 0, dots = 0, keep_permissions = 0, verbose = 0, send_stdout = 0;
    52 static int blocksize = SMB_DEFAULT_BLOCKSIZE;
    53 
    54 static int smb_download_file(const char *base, const char *name, int recursive,
    55                              int resume, int toplevel, char *outfile);
     39#define SMB_DEFAULT_BLOCKSIZE   64000
     40
     41struct opt {
     42        char *workgroup;
     43        bool username_specified;
     44        char *username;
     45        bool password_specified;
     46        char *password;
     47
     48        char *outputfile;
     49        size_t blocksize;
     50
     51        bool nonprompt;
     52        bool quiet;
     53        bool dots;
     54        bool verbose;
     55        bool send_stdout;
     56        bool update;
     57        int debuglevel;
     58};
     59static struct opt opt = { .blocksize = SMB_DEFAULT_BLOCKSIZE };
     60
     61static bool smb_download_file(const char *base, const char *name,
     62                              bool recursive, bool resume, bool toplevel,
     63                              char *outfile);
    5664
    5765static int get_num_cols(void)
     
    5967#ifdef TIOCGWINSZ
    6068        struct winsize ws;
    61         if(ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0) {
     69        if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0) {
    6270                return 0;
    6371        }
     
    6674#warning No support for TIOCGWINSZ
    6775        char *cols = getenv("COLUMNS");
    68         if(!cols) return 0;
     76        if (!cols) {
     77                return 0;
     78        }
    6979        return atoi(cols);
    7080#endif
     
    8595                snprintf(buffer, l, "%.2fkB", 1.0 * s / 1024);
    8696        } else {
    87                 snprintf(buffer, l, OFF_T_FORMAT"b", (OFF_T_FORMAT_CAST)s);
    88         }
    89 }
    90 
    91 static void get_auth_data(const char *srv, const char *shr, char *wg, int wglen, char *un, int unlen, char *pw, int pwlen)
    92 {
    93         static char hasasked = 0;
    94         char *wgtmp, *usertmp;
     97                snprintf(buffer, l, "%jdb", (intmax_t)s);
     98        }
     99}
     100
     101static void get_auth_data(const char *srv, const char *shr, char *wg, int wglen,
     102                          char *un, int unlen, char *pw, int pwlen)
     103{
     104        static bool hasasked = false;
     105        static char *savedwg;
     106        static char *savedun;
     107        static char *savedpw;
    95108        char tmp[128];
    96109
    97         if(hasasked) return;
    98         hasasked = 1;
    99 
    100         if(!nonprompt && !username) {
     110        if (hasasked) {
     111                strncpy(wg, savedwg, wglen - 1);
     112                strncpy(un, savedun, unlen - 1);
     113                strncpy(pw, savedpw, pwlen - 1);
     114                return;
     115        }
     116        hasasked = true;
     117
     118        if (!opt.nonprompt && !opt.username_specified) {
    101119                printf("Username for %s at %s [guest] ", shr, srv);
    102120                if (fgets(tmp, sizeof(tmp), stdin) == NULL) {
    103121                        return;
    104122                }
    105                 if ((strlen(tmp) > 0) && (tmp[strlen(tmp)-1] == '\n')) {
    106                         tmp[strlen(tmp)-1] = '\0';
    107                 }
    108                 strncpy(un, tmp, unlen-1);
    109         } else if(username) strncpy(un, username, unlen-1);
    110 
    111         if(!nonprompt && !password) {
    112                 char *prompt, *pass;
    113                 if (asprintf(&prompt, "Password for %s at %s: ", shr, srv) == -1) {
     123                if ((strlen(tmp) > 0) && (tmp[strlen(tmp) - 1] == '\n')) {
     124                        tmp[strlen(tmp) - 1] = '\0';
     125                }
     126                strncpy(un, tmp, unlen - 1);
     127        } else if (opt.username != NULL) {
     128                strncpy(un, opt.username, unlen - 1);
     129        }
     130
     131        if (!opt.nonprompt && !opt.password_specified) {
     132                char *prompt;
     133                if (asprintf(&prompt, "Password for %s at %s: ", shr, srv) ==
     134                    -1) {
    114135                        return;
    115136                }
    116                 pass = getpass(prompt);
     137                (void)samba_getpass(prompt, pw, pwlen, false, false);
    117138                free(prompt);
    118                 strncpy(pw, pass, pwlen-1);
    119         } else if(password) strncpy(pw, password, pwlen-1);
    120 
    121         if(workgroup)strncpy(wg, workgroup, wglen-1);
    122 
    123         wgtmp = SMB_STRNDUP(wg, wglen);
    124         usertmp = SMB_STRNDUP(un, unlen);
    125         if(!quiet)printf("Using workgroup %s, %s%s\n", wgtmp, *usertmp?"user ":"guest user", usertmp);
    126         free(wgtmp); free(usertmp);
    127 }
    128 
    129 /* Return 1 on error, 0 on success. */
    130 
    131 static int smb_download_dir(const char *base, const char *name, int resume)
     139        } else if (opt.password != NULL) {
     140                strncpy(pw, opt.password, pwlen-1);
     141        }
     142
     143        if (opt.workgroup != NULL) {
     144                strncpy(wg, opt.workgroup, wglen-1);
     145        }
     146
     147        /* save the values found for later */
     148        savedwg = SMB_STRDUP(wg);
     149        savedun = SMB_STRDUP(un);
     150        savedpw = SMB_STRDUP(pw);
     151
     152        if (!opt.quiet) {
     153                char *wgtmp, *usertmp;
     154                wgtmp = SMB_STRNDUP(wg, wglen);
     155                usertmp = SMB_STRNDUP(un, unlen);
     156                printf("Using workgroup %s, %s%s\n",
     157                       wgtmp,
     158                       *usertmp ? "user " : "guest user",
     159                       usertmp);
     160                free(wgtmp);
     161                free(usertmp);
     162        }
     163}
     164
     165static bool smb_download_dir(const char *base, const char *name, int resume)
    132166{
    133167        char path[SMB_MAXPATHLEN];
     
    136170        const char *relname = name;
    137171        char *tmpname;
    138         struct stat remotestat;
    139         int ret = 0;
    140 
    141         snprintf(path, SMB_MAXPATHLEN-1, "%s%s%s", base, (base[0] && name[0] && name[0] != '/' && base[strlen(base)-1] != '/')?"/":"", name);
     172        bool ok = false;
     173
     174        snprintf(path, SMB_MAXPATHLEN-1, "%s%s%s", base,
     175                 (base[0] && name[0] && name[0] != '/' &&
     176                  base[strlen(base)-1] != '/') ? "/" : "",
     177                 name);
    142178
    143179        /* List files in directory and call smb_download_file on them */
    144180        dirhandle = smbc_opendir(path);
    145         if(dirhandle < 1) {
     181        if (dirhandle < 1) {
    146182                if (errno == ENOTDIR) {
    147                         return smb_download_file(base, name, 1, resume,
    148                                                  0, NULL);
    149                 }
    150                 fprintf(stderr, "Can't open directory %s: %s\n", path, strerror(errno));
    151                 return 1;
    152         }
    153 
    154         while(*relname == '/')relname++;
     183                        return smb_download_file(base, name, true, resume,
     184                                                 false, NULL);
     185                }
     186                fprintf(stderr, "Can't open directory %s: %s\n", path,
     187                        strerror(errno));
     188                return false;
     189        }
     190
     191        while (*relname == '/') {
     192                relname++;
     193        }
    155194        mkdir(relname, 0755);
    156195
    157196        tmpname = SMB_STRDUP(name);
    158197
    159         while((dirent = smbc_readdir(dirhandle))) {
     198        while ((dirent = smbc_readdir(dirhandle))) {
    160199                char *newname;
    161                 if(!strcmp(dirent->name, ".") || !strcmp(dirent->name, ".."))continue;
     200                if (!strcmp(dirent->name, ".") || !strcmp(dirent->name, "..")) {
     201                        continue;
     202                }
    162203                if (asprintf(&newname, "%s/%s", tmpname, dirent->name) == -1) {
    163                         return 1;
    164                 }
    165                 switch(dirent->smbc_type) {
     204                        free(tmpname);
     205                        return false;
     206                }
     207                switch (dirent->smbc_type) {
    166208                case SMBC_DIR:
    167                         ret = smb_download_dir(base, newname, resume);
     209                        ok = smb_download_dir(base, newname, resume);
    168210                        break;
    169211
    170212                case SMBC_WORKGROUP:
    171                         ret = smb_download_dir("smb://", dirent->name, resume);
     213                        ok = smb_download_dir("smb://", dirent->name, resume);
    172214                        break;
    173215
    174216                case SMBC_SERVER:
    175                         ret = smb_download_dir("smb://", dirent->name, resume);
     217                        ok = smb_download_dir("smb://", dirent->name, resume);
    176218                        break;
    177219
    178220                case SMBC_FILE:
    179                         ret = smb_download_file(base, newname, 1, resume, 0,
    180                                                 NULL);
     221                        ok = smb_download_file(base, newname, true, resume,
     222                                                false, NULL);
    181223                        break;
    182224
    183225                case SMBC_FILE_SHARE:
    184                         ret = smb_download_dir(base, newname, resume);
     226                        ok = smb_download_dir(base, newname, resume);
    185227                        break;
    186228
    187229                case SMBC_PRINTER_SHARE:
    188                         if(!quiet)printf("Ignoring printer share %s\n", dirent->name);
     230                        if (!opt.quiet) {
     231                                printf("Ignoring printer share %s\n",
     232                                       dirent->name);
     233                        }
    189234                        break;
    190235
    191236                case SMBC_COMMS_SHARE:
    192                         if(!quiet)printf("Ignoring comms share %s\n", dirent->name);
     237                        if (!opt.quiet) {
     238                                printf("Ignoring comms share %s\n",
     239                                       dirent->name);
     240                        }
    193241                        break;
    194242
    195243                case SMBC_IPC_SHARE:
    196                         if(!quiet)printf("Ignoring ipc$ share %s\n", dirent->name);
     244                        if (!opt.quiet) {
     245                                printf("Ignoring ipc$ share %s\n",
     246                                       dirent->name);
     247                        }
    197248                        break;
    198249
    199250                default:
    200                         fprintf(stderr, "Ignoring file '%s' of type '%d'\n", newname, dirent->smbc_type);
    201                         break;
     251                        fprintf(stderr, "Ignoring file '%s' of type '%d'\n",
     252                                newname, dirent->smbc_type);
     253                        break;
     254                }
     255
     256                if (!ok) {
     257                        fprintf(stderr, "Failed to download %s: %s\n",
     258                                newname, strerror(errno));
     259                        return false;
    202260                }
    203261                free(newname);
     
    205263        free(tmpname);
    206264
    207         if(keep_permissions) {
    208                 if(smbc_fstat(dirhandle, &remotestat) < 0) {
    209                         fprintf(stderr, "Unable to get stats on %s on remote server\n", path);
    210                         smbc_closedir(dirhandle);
    211                         return 1;
    212                 }
    213 
    214                 if(chmod(relname, remotestat.st_mode) < 0) {
    215                         fprintf(stderr, "Unable to change mode of local dir %s to %o\n", relname,
    216                                 (unsigned int)remotestat.st_mode);
    217                         smbc_closedir(dirhandle);
    218                         return 1;
    219                 }
    220         }
    221 
    222265        smbc_closedir(dirhandle);
    223         return ret;
     266        return ok;
    224267}
    225268
     
    228271        static char buffer[100];
    229272        int secs, mins, hours;
    230         if(t < -1) {
     273        if (t < -1) {
    231274                strncpy(buffer, "Unknown", sizeof(buffer));
    232275                return buffer;
     
    236279        mins = (int)t / 60 % 60;
    237280        hours = (int)t / (60 * 60);
    238         snprintf(buffer, sizeof(buffer)-1, "%02d:%02d:%02d", hours, mins, secs);
     281        snprintf(buffer, sizeof(buffer) - 1, "%02d:%02d:%02d", hours, mins,
     282                 secs);
    239283        return buffer;
    240284}
    241285
    242 static void print_progress(const char *name, time_t start, time_t now, off_t start_pos, off_t pos, off_t total)
     286static void print_progress(const char *name, time_t start, time_t now,
     287                           off_t start_pos, off_t pos, off_t total)
    243288{
    244289        double avg = 0.0;
    245         long  eta = -1;
     290        long eta = -1;
    246291        double prcnt = 0.0;
    247292        char hpos[20], htotal[20], havg[20];
    248293        char *status, *filename;
    249294        int len;
    250         if(now - start)avg = 1.0 * (pos - start_pos) / (now - start);
     295        if (now - start) {
     296                avg = 1.0 * (pos - start_pos) / (now - start);
     297        }
    251298        eta = (total - pos) / avg;
    252         if(total)prcnt = 100.0 * pos / total;
     299        if (total) {
     300                prcnt = 100.0 * pos / total;
     301        }
    253302
    254303        human_readable(pos, hpos, sizeof(hpos));
     
    256305        human_readable(avg, havg, sizeof(havg));
    257306
    258         len = asprintf(&status, "%s of %s (%.2f%%) at %s/s ETA: %s", hpos, htotal, prcnt, havg, print_time(eta));
     307        len = asprintf(&status, "%s of %s (%.2f%%) at %s/s ETA: %s", hpos,
     308                       htotal, prcnt, havg, print_time(eta));
    259309        if (len == -1) {
    260310                return;
    261311        }
    262312
    263         if(columns) {
    264                 int required = strlen(name), available = columns - len - strlen("[] ");
    265                 if(required > available) {
    266                         if (asprintf(&filename, "...%s", name + required - available + 3) == -1) {
     313        if (columns) {
     314                int required = strlen(name),
     315                    available = columns - len - strlen("[] ");
     316                if (required > available) {
     317                        if (asprintf(&filename, "...%s",
     318                                     name + required - available + 3) == -1) {
    267319                                return;
    268320                        }
     
    270322                        filename = SMB_STRNDUP(name, available);
    271323                }
    272         } else filename = SMB_STRDUP(name);
     324        } else {
     325                filename = SMB_STRDUP(name);
     326        }
    273327
    274328        fprintf(stderr, "\r[%s] %s", filename, status);
    275329
    276         free(filename); free(status);
    277 }
    278 
    279 /* Return 1 on error, 0 on success. */
    280 
    281 static int smb_download_file(const char *base, const char *name, int recursive,
    282                              int resume, int toplevel, char *outfile)
     330        free(filename);
     331        free(status);
     332}
     333
     334/* Return false on error, true on success. */
     335
     336static bool smb_download_file(const char *base, const char *name,
     337                              bool recursive, bool resume, bool toplevel,
     338                              char *outfile)
    283339{
    284340        int remotehandle, localhandle;
     
    288344        char checkbuf[2][RESUME_CHECK_SIZE];
    289345        char *readbuf = NULL;
    290         off_t offset_download = 0, offset_check = 0, curpos = 0, start_offset = 0;
     346        off_t offset_download = 0, offset_check = 0, curpos = 0,
     347              start_offset = 0;
    291348        struct stat localstat, remotestat;
    292349
    293         snprintf(path, SMB_MAXPATHLEN-1, "%s%s%s", base, (*base && *name && name[0] != '/' && base[strlen(base)-1] != '/')?"/":"", name);
     350        snprintf(path, SMB_MAXPATHLEN-1, "%s%s%s", base,
     351                 (*base && *name && name[0] != '/' &&
     352                  base[strlen(base)-1] != '/') ? "/" : "",
     353                 name);
    294354
    295355        remotehandle = smbc_open(path, O_RDONLY, 0755);
    296356
    297         if(remotehandle < 0) {
    298                 switch(errno) {
    299                 case EISDIR:
    300                         if(!recursive) {
    301                                 fprintf(stderr, "%s is a directory. Specify -R to download recursively\n", path);
    302                                 return 1;
     357        if (remotehandle < 0) {
     358                switch (errno) {
     359                case EISDIR:
     360                        if (!recursive) {
     361                                fprintf(stderr,
     362                                        "%s is a directory. Specify -R "
     363                                        "to download recursively\n",
     364                                        path);
     365                                return false;
    303366                        }
    304367                        return smb_download_dir(base, name, resume);
    305368
    306369                case ENOENT:
    307                         fprintf(stderr, "%s can't be found on the remote server\n", path);
    308                         return 1;
     370                        fprintf(stderr,
     371                                "%s can't be found on the remote server\n",
     372                                path);
     373                        return false;
    309374
    310375                case ENOMEM:
    311376                        fprintf(stderr, "Not enough memory\n");
    312                         return 1;
     377                        return false;
    313378
    314379                case ENODEV:
    315                         fprintf(stderr, "The share name used in %s does not exist\n", path);
    316                         return 1;
     380                        fprintf(stderr,
     381                                "The share name used in %s does not exist\n",
     382                                path);
     383                        return false;
    317384
    318385                case EACCES:
    319                         fprintf(stderr, "You don't have enough permissions to access %s\n", path);
    320                         return 1;
     386                        fprintf(stderr, "You don't have enough permissions "
     387                                "to access %s\n",
     388                                path);
     389                        return false;
    321390
    322391                default:
    323392                        perror("smbc_open");
    324                         return 1;
    325                 }
    326         } 
    327 
    328         if(smbc_fstat(remotehandle, &remotestat) < 0) {
     393                        return false;
     394                }
     395        }
     396
     397        if (smbc_fstat(remotehandle, &remotestat) < 0) {
    329398                fprintf(stderr, "Can't stat %s: %s\n", path, strerror(errno));
    330                 return 1;
    331         }
    332 
    333         if(outfile) newpath = outfile;
    334         else if(!name[0]) {
     399                return false;
     400        }
     401
     402        if (outfile) {
     403                newpath = outfile;
     404        } else if (!name[0]) {
    335405                newpath = strrchr(base, '/');
    336                 if(newpath)newpath++; else newpath = base;
    337         } else newpath = name;
     406                if (newpath) {
     407                        newpath++;
     408                } else {
     409                        newpath = base;
     410                }
     411        } else {
     412                newpath = name;
     413        }
    338414
    339415        if (!toplevel && (newpath[0] == '/')) {
     
    342418
    343419        /* Open local file according to the mode */
    344         if(update) {
     420        if (opt.update) {
    345421                /* if it is up-to-date, skip */
    346                 if(stat(newpath, &localstat) == 0 &&
    347                                 localstat.st_mtime >= remotestat.st_mtime) {
    348                         if(verbose)
     422                if (stat(newpath, &localstat) == 0 &&
     423                    localstat.st_mtime >= remotestat.st_mtime) {
     424                        if (opt.verbose) {
    349425                                printf("%s is up-to-date, skipping\n", newpath);
     426                        }
    350427                        smbc_close(remotehandle);
    351                         return 0;
     428                        return true;
    352429                }
    353430                /* else open it for writing and truncate if it exists */
    354                 localhandle = open(newpath, O_CREAT | O_NONBLOCK | O_RDWR | O_TRUNC, 0775);
    355                 if(localhandle < 0) {
     431                localhandle = open(
     432                    newpath, O_CREAT | O_NONBLOCK | O_RDWR | O_TRUNC, 0775);
     433                if (localhandle < 0) {
    356434                        fprintf(stderr, "Can't open %s : %s\n", newpath,
    357                                         strerror(errno));
     435                                strerror(errno));
    358436                        smbc_close(remotehandle);
    359                         return 1;
     437                        return false;
    360438                }
    361439                /* no offset */
    362         } else if(!send_stdout) {
    363                 localhandle = open(newpath, O_CREAT | O_NONBLOCK | O_RDWR | (!resume?O_EXCL:0), 0755);
    364                 if(localhandle < 0) {
    365                         fprintf(stderr, "Can't open %s: %s\n", newpath, strerror(errno));
     440        } else if (!opt.send_stdout) {
     441                localhandle = open(newpath, O_CREAT | O_NONBLOCK | O_RDWR |
     442                                                (!resume ? O_EXCL : 0),
     443                                   0755);
     444                if (localhandle < 0) {
     445                        fprintf(stderr, "Can't open %s: %s\n", newpath,
     446                                strerror(errno));
    366447                        smbc_close(remotehandle);
    367                         return 1;
     448                        return false;
    368449                }
    369450
    370451                if (fstat(localhandle, &localstat) != 0) {
    371                         fprintf(stderr, "Can't fstat %s: %s\n", newpath, strerror(errno));
     452                        fprintf(stderr, "Can't fstat %s: %s\n", newpath,
     453                                strerror(errno));
    372454                        smbc_close(remotehandle);
    373455                        close(localhandle);
    374                         return 1;
     456                        return false;
    375457                }
    376458
    377459                start_offset = localstat.st_size;
    378460
    379                 if(localstat.st_size && localstat.st_size == remotestat.st_size) {
    380                         if(verbose)fprintf(stderr, "%s is already downloaded completely.\n", path);
    381                         else if(!quiet)fprintf(stderr, "%s\n", path);
     461                if (localstat.st_size &&
     462                    localstat.st_size == remotestat.st_size) {
     463                        if (opt.verbose) {
     464                                fprintf(stderr, "%s is already downloaded "
     465                                        "completely.\n",
     466                                        path);
     467                        } else if (!opt.quiet) {
     468                                fprintf(stderr, "%s\n", path);
     469                        }
    382470                        smbc_close(remotehandle);
    383471                        close(localhandle);
    384                         return 0;
    385                 }
    386 
    387                 if(localstat.st_size > RESUME_CHECK_OFFSET && remotestat.st_size > RESUME_CHECK_OFFSET) {
    388                         offset_download = localstat.st_size - RESUME_DOWNLOAD_OFFSET;
     472                        return true;
     473                }
     474
     475                if (localstat.st_size > RESUME_CHECK_OFFSET &&
     476                    remotestat.st_size > RESUME_CHECK_OFFSET) {
     477                        offset_download =
     478                            localstat.st_size - RESUME_DOWNLOAD_OFFSET;
    389479                        offset_check = localstat.st_size - RESUME_CHECK_OFFSET;
    390                         if(verbose)printf("Trying to start resume of %s at "OFF_T_FORMAT"\n"
    391                                    "At the moment "OFF_T_FORMAT" of "OFF_T_FORMAT" bytes have been retrieved\n",
    392                                 newpath, (OFF_T_FORMAT_CAST)offset_check,
    393                                 (OFF_T_FORMAT_CAST)localstat.st_size,
    394                                 (OFF_T_FORMAT_CAST)remotestat.st_size);
    395                 }
    396 
    397                 if(offset_check) {
     480                        if (opt.verbose) {
     481                                printf("Trying to start resume of %s at %jd\n"
     482                                       "At the moment %jd of %jd bytes have "
     483                                       "been retrieved\n",
     484                                       newpath, (intmax_t)offset_check,
     485                                       (intmax_t)localstat.st_size,
     486                                       (intmax_t)remotestat.st_size);
     487                        }
     488                }
     489
     490                if (offset_check) {
    398491                        off_t off1, off2;
    399                         /* First, check all bytes from offset_check to offset_download */
     492                        /* First, check all bytes from offset_check to
     493                         * offset_download */
    400494                        off1 = lseek(localhandle, offset_check, SEEK_SET);
    401                         if(off1 < 0) {
    402                                 fprintf(stderr, "Can't seek to "OFF_T_FORMAT" in local file %s\n",
    403                                         (OFF_T_FORMAT_CAST)offset_check, newpath);
    404                                 smbc_close(remotehandle); close(localhandle);
    405                                 return 1;
    406                         }
    407 
    408                         off2 = smbc_lseek(remotehandle, offset_check, SEEK_SET);
    409                         if(off2 < 0) {
    410                                 fprintf(stderr, "Can't seek to "OFF_T_FORMAT" in remote file %s\n",
    411                                         (OFF_T_FORMAT_CAST)offset_check, newpath);
    412                                 smbc_close(remotehandle); close(localhandle);
    413                                 return 1;
    414                         }
    415 
    416                         if(off1 != off2) {
    417                                 fprintf(stderr, "Offset in local and remote files is different (local: "OFF_T_FORMAT", remote: "OFF_T_FORMAT")\n",
    418                                         (OFF_T_FORMAT_CAST)off1,
    419                                         (OFF_T_FORMAT_CAST)off2);
    420                                 smbc_close(remotehandle); close(localhandle);
    421                                 return 1;
    422                         }
    423 
    424                         if(smbc_read(remotehandle, checkbuf[0], RESUME_CHECK_SIZE) != RESUME_CHECK_SIZE) {
    425                                 fprintf(stderr, "Can't read %d bytes from remote file %s\n", RESUME_CHECK_SIZE, path);
    426                                 smbc_close(remotehandle); close(localhandle);
    427                                 return 1;
    428                         }
    429 
    430                         if(read(localhandle, checkbuf[1], RESUME_CHECK_SIZE) != RESUME_CHECK_SIZE) {
    431                                 fprintf(stderr, "Can't read %d bytes from local file %s\n", RESUME_CHECK_SIZE, name);
    432                                 smbc_close(remotehandle); close(localhandle);
    433                                 return 1;
    434                         }
    435 
    436                         if(memcmp(checkbuf[0], checkbuf[1], RESUME_CHECK_SIZE) == 0) {
    437                                 if(verbose)printf("Current local and remote file appear to be the same. Starting download from offset "OFF_T_FORMAT"\n", (OFF_T_FORMAT_CAST)offset_download);
     495                        if (off1 < 0) {
     496                                fprintf(stderr,
     497                                        "Can't seek to %jd in local file %s\n",
     498                                        (intmax_t)offset_check, newpath);
     499                                smbc_close(remotehandle);
     500                                close(localhandle);
     501                                return false;
     502                        }
     503
     504                        off2 = smbc_lseek(remotehandle, offset_check, SEEK_SET);
     505                        if (off2 < 0) {
     506                                fprintf(stderr,
     507                                        "Can't seek to %jd in remote file %s\n",
     508                                        (intmax_t)offset_check, newpath);
     509                                smbc_close(remotehandle);
     510                                close(localhandle);
     511                                return false;
     512                        }
     513
     514                        if (off1 != off2) {
     515                                fprintf(stderr, "Offset in local and remote "
     516                                        "files are different "
     517                                        "(local: %jd, remote: %jd)\n",
     518                                        (intmax_t)off1, (intmax_t)off2);
     519                                smbc_close(remotehandle);
     520                                close(localhandle);
     521                                return false;
     522                        }
     523
     524                        if (smbc_read(remotehandle, checkbuf[0],
     525                                      RESUME_CHECK_SIZE) != RESUME_CHECK_SIZE) {
     526                                fprintf(stderr, "Can't read %d bytes from "
     527                                        "remote file %s\n",
     528                                        RESUME_CHECK_SIZE, path);
     529                                smbc_close(remotehandle);
     530                                close(localhandle);
     531                                return false;
     532                        }
     533
     534                        if (read(localhandle, checkbuf[1], RESUME_CHECK_SIZE) !=
     535                            RESUME_CHECK_SIZE) {
     536                                fprintf(stderr, "Can't read %d bytes from "
     537                                        "local file %s\n",
     538                                        RESUME_CHECK_SIZE, name);
     539                                smbc_close(remotehandle);
     540                                close(localhandle);
     541                                return false;
     542                        }
     543
     544                        if (memcmp(checkbuf[0], checkbuf[1],
     545                                   RESUME_CHECK_SIZE) == 0) {
     546                                if (opt.verbose) {
     547                                        printf("Current local and remote file "
     548                                               "appear to be the same. "
     549                                               "Starting download from "
     550                                               "offset %jd\n",
     551                                               (intmax_t)offset_download);
     552                                }
    438553                        } else {
    439                                 fprintf(stderr, "Local and remote file appear to be different, not doing resume for %s\n", path);
    440                                 smbc_close(remotehandle); close(localhandle);
    441                                 return 1;
     554                                fprintf(stderr, "Local and remote file appear "
     555                                        "to be different, not "
     556                                        "doing resume for %s\n",
     557                                        path);
     558                                smbc_close(remotehandle);
     559                                close(localhandle);
     560                                return false;
    442561                        }
    443562                }
     
    449568        }
    450569
    451         readbuf = (char *)SMB_MALLOC(blocksize);
     570        readbuf = (char *)SMB_MALLOC(opt.blocksize);
    452571        if (!readbuf) {
    453                 return 1;
     572                fprintf(stderr, "Failed to allocate %zu bytes for read "
     573                                "buffer (%s)", opt.blocksize, strerror(errno));
     574                if (localhandle != STDOUT_FILENO) {
     575                        close(localhandle);
     576                }
     577                return false;
    454578        }
    455579
    456580        /* Now, download all bytes from offset_download to the end */
    457         for(curpos = offset_download; curpos < remotestat.st_size; curpos+=blocksize) {
    458                 ssize_t bytesread = smbc_read(remotehandle, readbuf, blocksize);
     581        for (curpos = offset_download; curpos < remotestat.st_size;
     582             curpos += opt.blocksize) {
     583                ssize_t bytesread;
     584                ssize_t byteswritten;
     585
     586                bytesread = smbc_read(remotehandle, readbuf, opt.blocksize);
    459587                if(bytesread < 0) {
    460                         fprintf(stderr, "Can't read %u bytes at offset "OFF_T_FORMAT", file %s\n", (unsigned int)blocksize, (OFF_T_FORMAT_CAST)curpos, path);
     588                        fprintf(stderr,
     589                                "Can't read %zu bytes at offset %jd, file %s\n",
     590                                opt.blocksize, (intmax_t)curpos, path);
    461591                        smbc_close(remotehandle);
    462                         if (localhandle != STDOUT_FILENO) close(localhandle);
     592                        if (localhandle != STDOUT_FILENO) {
     593                                close(localhandle);
     594                        }
    463595                        free(readbuf);
    464                         return 1;
     596                        return false;
    465597                }
    466598
    467599                total_bytes += bytesread;
    468600
    469                 if(write(localhandle, readbuf, bytesread) < 0) {
    470                         fprintf(stderr, "Can't write %u bytes to local file %s at offset "OFF_T_FORMAT"\n", (unsigned int)bytesread, path, (OFF_T_FORMAT_CAST)curpos);
     601                byteswritten = write(localhandle, readbuf, bytesread);
     602                if (byteswritten != bytesread) {
     603                        fprintf(stderr,
     604                                "Can't write %zd bytes to local file %s at "
     605                                "offset %jd\n", bytesread, path,
     606                                (intmax_t)curpos);
    471607                        free(readbuf);
    472608                        smbc_close(remotehandle);
    473                         if (localhandle != STDOUT_FILENO) close(localhandle);
    474                         return 1;
    475                 }
    476 
    477                 if(dots)fputc('.', stderr);
    478                 else if(!quiet) {
     609                        if (localhandle != STDOUT_FILENO) {
     610                                close(localhandle);
     611                        }
     612                        return false;
     613                }
     614
     615                if (opt.dots) {
     616                        fputc('.', stderr);
     617                } else if (!opt.quiet) {
    479618                        print_progress(newpath, start_time, time_mono(NULL),
    480                                         start_offset, curpos, remotestat.st_size);
     619                                       start_offset, curpos,
     620                                       remotestat.st_size);
    481621                }
    482622        }
     
    484624        free(readbuf);
    485625
    486         if(dots){
     626        if (opt.dots) {
    487627                fputc('\n', stderr);
    488628                printf("%s downloaded\n", path);
    489         } else if(!quiet) {
     629        } else if (!opt.quiet) {
    490630                int i;
    491631                fprintf(stderr, "\r%s", path);
    492                 if(columns) {
    493                         for(i = strlen(path); i < columns; i++) {
     632                if (columns) {
     633                        for (i = strlen(path); i < columns; i++) {
    494634                                fputc(' ', stderr);
    495635                        }
     
    498638        }
    499639
    500         if(keep_permissions && !send_stdout) {
    501                 if(fchmod(localhandle, remotestat.st_mode) < 0) {
    502                         fprintf(stderr, "Unable to change mode of local file %s to %o\n", path,
    503                                 (unsigned int)remotestat.st_mode);
    504                         smbc_close(remotehandle);
    505                         close(localhandle);
    506                         return 1;
    507                 }
    508         }
    509 
    510640        smbc_close(remotehandle);
    511         if (localhandle != STDOUT_FILENO) close(localhandle);
    512         return 0;
     641        if (localhandle != STDOUT_FILENO) {
     642                close(localhandle);
     643        }
     644        return true;
    513645}
    514646
     
    517649        char bs[100];
    518650        human_readable(total_bytes, bs, sizeof(bs));
    519         if(!quiet)fprintf(stderr, "Downloaded %s in %lu seconds\n", bs,
    520                 (unsigned long)(time_mono(NULL) - total_start_time));
     651        if (!opt.quiet) {
     652                fprintf(stderr, "Downloaded %s in %lu seconds\n", bs,
     653                        (unsigned long)(time_mono(NULL) - total_start_time));
     654        }
    521655        exit(0);
    522656}
     
    532666        int lineno = 0, i;
    533667        char var[101], val[101];
    534         char found;
    535         int *intdata; char **stringdata;
    536         if(!fd) {
     668        bool found;
     669        int *intdata;
     670        char **stringdata;
     671        if (!fd) {
    537672                fprintf(stderr, "Can't open RC file %s\n", name);
    538673                return 1;
    539674        }
    540675
    541         while(!feof(fd)) {
     676        while (!feof(fd)) {
    542677                lineno++;
    543                 if(fscanf(fd, "%100s %100s\n", var, val) < 2) {
    544                         fprintf(stderr, "Can't parse line %d of %s, ignoring.\n", lineno, name);
     678                if (fscanf(fd, "%100s %100s\n", var, val) < 2) {
     679                        fprintf(stderr,
     680                                "Can't parse line %d of %s, ignoring.\n",
     681                                lineno, name);
    545682                        continue;
    546683                }
    547684
    548                 found = 0;
    549 
    550                 for(i = 0; long_options[i].shortName; i++) {
    551                         if(!long_options[i].longName)continue;
    552                         if(strcmp(long_options[i].longName, var)) continue;
    553                         if(!long_options[i].arg)continue;
    554 
    555                         switch(long_options[i].argInfo) {
     685                found = false;
     686
     687                for (i = 0; long_options[i].argInfo; i++) {
     688                        if (!long_options[i].longName) {
     689                                continue;
     690                        }
     691                        if (strcmp(long_options[i].longName, var)) {
     692                                continue;
     693                        }
     694                        if (!long_options[i].arg) {
     695                                continue;
     696                        }
     697
     698                        switch (long_options[i].argInfo) {
    556699                        case POPT_ARG_NONE:
    557700                                intdata = (int *)long_options[i].arg;
    558                                 if(!strcmp(val, "on")) *intdata = 1;
    559                                 else if(!strcmp(val, "off")) *intdata = 0;
    560                                 else fprintf(stderr, "Illegal value %s for %s at line %d in %s\n", val, var, lineno, name);
     701                                if (!strcmp(val, "on")) {
     702                                        *intdata = 1;
     703                                } else if (!strcmp(val, "off")) {
     704                                        *intdata = 0;
     705                                } else {
     706                                        fprintf(stderr, "Illegal value %s for "
     707                                                "%s at line %d in %s\n",
     708                                                val, var, lineno, name);
     709                                }
    561710                                break;
    562711                        case POPT_ARG_INT:
     
    567716                                stringdata = (char **)long_options[i].arg;
    568717                                *stringdata = SMB_STRDUP(val);
     718                                if (long_options[i].shortName == 'U') {
     719                                        char *p;
     720                                        opt.username_specified = true;
     721                                        p = strchr(*stringdata, '%');
     722                                        if (p != NULL) {
     723                                                *p = '\0';
     724                                                opt.password = p + 1;
     725                                                opt.password_specified = true;
     726                                        }
     727                                }
    569728                                break;
    570729                        default:
    571                                 fprintf(stderr, "Invalid variable %s at line %d in %s\n", var, lineno, name);
     730                                fprintf(stderr, "Invalid variable %s at "
     731                                        "line %d in %s\n",
     732                                        var, lineno, name);
    572733                                break;
    573734                        }
    574735
    575                         found = 1;
    576                 }
    577                 if(!found) {
    578                         fprintf(stderr, "Invalid variable %s at line %d in %s\n", var, lineno, name);
     736                        found = true;
     737                }
     738                if (!found) {
     739                        fprintf(stderr,
     740                                "Invalid variable %s at line %d in %s\n", var,
     741                                lineno, name);
    579742                }
    580743        }
     
    584747}
    585748
    586 int main(int argc, const char **argv)
     749int main(int argc, char **argv)
    587750{
    588751        int c = 0;
     
    592755        int resume = 0, recursive = 0;
    593756        TALLOC_CTX *frame = talloc_stackframe();
    594         int ret = 0;
     757        bool ret = true;
     758        char *p;
     759        const char **argv_const = discard_const_p(const char *, argv);
    595760        struct poptOption long_options[] = {
    596                 {"guest", 'a', POPT_ARG_NONE, NULL, 'a', "Work as user guest" },       
    597                 {"encrypt", 'e', POPT_ARG_NONE, NULL, 'e', "Encrypt SMB transport (UNIX extended servers only)" },     
    598                 {"resume", 'r', POPT_ARG_NONE, &resume, 0, "Automatically resume aborted files" },
    599                 {"update", 'U',  POPT_ARG_NONE, &update, 0, "Download only when remote file is newer than local file or local file is missing"},
    600                 {"recursive", 'R',  POPT_ARG_NONE, &recursive, 0, "Recursively download files" },
    601                 {"username", 'u', POPT_ARG_STRING, &username, 'u', "Username to use" },
    602                 {"password", 'p', POPT_ARG_STRING, &password, 'p', "Password to use" },
    603                 {"workgroup", 'w', POPT_ARG_STRING, &workgroup, 'w', "Workgroup to use (optional)" },
    604                 {"nonprompt", 'n', POPT_ARG_NONE, &nonprompt, 'n', "Don't ask anything (non-interactive)" },
    605                 {"debuglevel", 'd', POPT_ARG_INT, &debuglevel, 'd', "Debuglevel to use" },
    606                 {"outputfile", 'o', POPT_ARG_STRING, &outputfile, 'o', "Write downloaded data to specified file" },
    607                 {"stdout", 'O', POPT_ARG_NONE, &send_stdout, 'O', "Write data to stdout" },
    608                 {"dots", 'D', POPT_ARG_NONE, &dots, 'D', "Show dots as progress indication" },
    609                 {"quiet", 'q', POPT_ARG_NONE, &quiet, 'q', "Be quiet" },
    610                 {"verbose", 'v', POPT_ARG_NONE, &verbose, 'v', "Be verbose" },
    611                 {"keep-permissions", 'P', POPT_ARG_NONE, &keep_permissions, 'P', "Keep permissions" },
    612                 {"blocksize", 'b', POPT_ARG_INT, &blocksize, 'b', "Change number of bytes in a block"},
    613                 {"rcfile", 'f', POPT_ARG_STRING, NULL, 'f', "Use specified rc file"},
    614761                POPT_AUTOHELP
     762
     763                {"workgroup",  'w', POPT_ARG_STRING, &opt.workgroup,   'w', "Workgroup to use (optional)" },
     764                {"user",       'U', POPT_ARG_STRING, &opt.username,    'U', "Username to use" },
     765                {"guest",      'a', POPT_ARG_NONE,   NULL,             'a', "Work as user guest" },
     766
     767                {"nonprompt",  'n', POPT_ARG_NONE,   NULL,             'n',  "Don't ask anything (non-interactive)" },
     768                {"debuglevel", 'd', POPT_ARG_INT,    &opt.debuglevel,  'd', "Debuglevel to use" },
     769
     770                {"encrypt",    'e', POPT_ARG_NONE,   NULL,             'e', "Encrypt SMB transport" },
     771                {"resume",     'r', POPT_ARG_NONE,   NULL,             'r',  "Automatically resume aborted files" },
     772                {"update",     'u', POPT_ARG_NONE,   NULL,             'u',  "Download only when remote file is newer than local file or local file is missing"},
     773                {"recursive",  'R', POPT_ARG_NONE,   NULL,             'R',  "Recursively download files" },
     774                {"blocksize",  'b', POPT_ARG_INT,    &opt.blocksize,   'b', "Change number of bytes in a block"},
     775
     776                {"outputfile", 'o', POPT_ARG_STRING, &opt.outputfile,  'o', "Write downloaded data to specified file" },
     777                {"stdout",     'O', POPT_ARG_NONE,   NULL,             'O',  "Write data to stdout" },
     778                {"dots",       'D', POPT_ARG_NONE,   NULL,             'D',  "Show dots as progress indication" },
     779                {"quiet",      'q', POPT_ARG_NONE,   NULL,             'q',  "Be quiet" },
     780                {"verbose",    'v', POPT_ARG_NONE,   NULL,             'v',  "Be verbose" },
     781                {"rcfile",     'f', POPT_ARG_STRING, NULL,             'f', "Use specified rc file"},
     782
    615783                POPT_TABLEEND
    616784        };
    617785        poptContext pc;
    618786
    619         load_case_tables();
     787        smb_init_locale();
    620788
    621789        /* only read rcfile if it exists */
     
    623791                return 1;
    624792        }
    625         if(access(rcfile, F_OK) == 0)
     793        if (access(rcfile, F_OK) == 0) {
    626794                readrcfile(rcfile, long_options);
     795        }
    627796        free(rcfile);
    628797
     
    633802        signal(SIGTERM, signal_quit);
    634803
    635         pc = poptGetContext(argv[0], argc, argv, long_options, 0);
    636 
    637         while((c = poptGetNextOpt(pc)) >= 0) {
    638                 switch(c) {
     804        pc = poptGetContext(argv[0], argc, argv_const, long_options, 0);
     805
     806        while ((c = poptGetNextOpt(pc)) > 0) {
     807                switch (c) {
    639808                case 'f':
    640809                        readrcfile(poptGetOptArg(pc), long_options);
    641810                        break;
    642811                case 'a':
    643                         username = ""; password = "";
     812                        opt.username_specified = true;
     813                        opt.username = talloc_strdup(frame, "");
     814                        opt.password_specified = true;
     815                        opt.password = talloc_strdup(frame, "");
    644816                        break;
    645817                case 'e':
    646818                        smb_encrypt = true;
    647819                        break;
    648                 }
    649         }
    650 
    651         if((send_stdout || resume || outputfile) && update) {
    652                 fprintf(stderr, "The -o, -R or -O and -U options can not be used together.\n");
     820                case 'U':
     821                        opt.username_specified = true;
     822                        opt.username = talloc_strdup(frame, opt.username);
     823                        p = strchr(opt.username,'%');
     824                        if (p != NULL) {
     825                                *p = '\0';
     826                                opt.password = p + 1;
     827                                opt.password_specified = true;
     828                        }
     829                        break;
     830                case 'n':
     831                        opt.nonprompt = true;
     832                        break;
     833                case 'r':
     834                        resume = true;
     835                        break;
     836                case 'u':
     837                        opt.update = true;
     838                        break;
     839                case 'R':
     840                        recursive = true;
     841                        break;
     842                case 'O':
     843                        opt.send_stdout = true;
     844                        break;
     845                case 'D':
     846                        opt.dots = true;
     847                        break;
     848                case 'q':
     849                        opt.quiet = true;
     850                        break;
     851                case 'v':
     852                        opt.verbose = true;
     853                        break;
     854                }
     855        }
     856
     857        if (c < -1) {
     858                fprintf(stderr, "%s: %s\n",
     859                        poptBadOption(pc, POPT_BADOPTION_NOALIAS),
     860                        poptStrerror(c));
    653861                return 1;
    654862        }
    655         if((send_stdout || outputfile) && recursive) {
    656                 fprintf(stderr, "The -o or -O and -R options can not be used together.\n");
     863
     864        if ((opt.send_stdout || resume || opt.outputfile) && opt.update) {
     865                fprintf(stderr, "The -o, -R or -O and -U options can not be "
     866                        "used together.\n");
    657867                return 1;
    658868        }
    659 
    660         if(outputfile && send_stdout) {
    661                 fprintf(stderr, "The -o and -O options cannot be used together.\n");
     869        if ((opt.send_stdout || opt.outputfile) && recursive) {
     870                fprintf(stderr, "The -o or -O and -R options can not be "
     871                        "used together.\n");
    662872                return 1;
    663873        }
    664874
    665         if(smbc_init(get_auth_data, debuglevel) < 0) {
     875        if (opt.outputfile && opt.send_stdout) {
     876                fprintf(stderr, "The -o and -O options can not be "
     877                        "used together.\n");
     878                return 1;
     879        }
     880
     881        popt_burn_cmdline_password(argc, argv);
     882
     883        if (smbc_init(get_auth_data, opt.debuglevel) < 0) {
    666884                fprintf(stderr, "Unable to initialize libsmbclient\n");
    667885                return 1;
     
    671889                SMBCCTX *smb_ctx = smbc_set_context(NULL);
    672890                smbc_option_set(smb_ctx,
    673                         CONST_DISCARD(char *, "smb_encrypt_level"),
    674                         "require");
     891                                discard_const_p(char, "smb_encrypt_level"),
     892                                "require");
    675893        }
    676894
     
    679897        total_start_time = time_mono(NULL);
    680898
    681         while ( (file = poptGetArg(pc)) ) {
    682                 if (!recursive)
     899        while ((file = poptGetArg(pc))) {
     900                if (!recursive) {
    683901                        ret = smb_download_file(file, "", recursive, resume,
    684                                                 1, outputfile);
    685                 else
     902                                                true, opt.outputfile);
     903                } else {
    686904                        ret = smb_download_dir(file, "", resume);
     905                }
    687906        }
    688907
    689908        TALLOC_FREE(frame);
    690         if ( ret == 0){
     909        if (ret) {
    691910                clean_exit();
    692911        }
    693         return ret;
    694 }
     912        return ret?0:1;
     913}
  • vendor/current/source3/utils/smbpasswd.c

    r740 r988  
    9898                switch(ch) {
    9999                case 'L':
    100 #if !defined(NSS_WRAPPER)
    101100                        if (getuid() != 0) {
    102101                                fprintf(stderr, "smbpasswd -L can only be used by root.\n");
    103102                                exit(1);
    104103                        }
    105 #endif
    106104                        local_flags |= LOCAL_AM_ROOT;
    107105                        break;
    108106                case 'c':
    109107                        configfile = optarg;
     108                        set_dyn_CONFIGFILE(optarg);
    110109                        break;
    111110                case 'a':
     
    137136                        local_flags |= LOCAL_SET_NO_PASSWORD;
    138137                        local_flags &= ~LOCAL_SET_PASSWORD;
     138                        SAFE_FREE(new_passwd);
    139139                        new_passwd = smb_xstrdup("NO PASSWORD");
    140140                        break;
     
    153153                        break;
    154154                case 'R':
    155                         lp_set_name_resolve_order(optarg);
     155                        lp_set_cmdline("name resolve order", optarg);
    156156                        break;
    157157                case 'D':
     
    196196        }
    197197
    198         if (!lp_load(configfile,True,False,False,True)) {
     198        if (!lp_load_global(configfile)) {
    199199                fprintf(stderr, "Can't load %s - run testparm to debug it\n",
    200200                        configfile);
     
    216216
    217217        p = get_pass("New SMB password:", stdin_get);
     218        if (p == NULL) {
     219                return NULL;
     220        }
    218221
    219222        fstrcpy(new_pw, p);
     
    221224
    222225        p = get_pass("Retype new SMB password:", stdin_get);
     226        if (p == NULL) {
     227                return NULL;
     228        }
    223229
    224230        if (strcmp(p, new_pw)) {
     
    286292                return False;
    287293
    288         return secrets_store_ldap_pw(lp_ldap_admin_dn(), pw);
     294        return secrets_store_ldap_pw(lp_ldap_admin_dn(talloc_tos()), pw);
    289295}
    290296
     
    301307
    302308        if (local_flags & LOCAL_SET_LDAP_ADMIN_PW) {
    303                 char *ldap_admin_dn = lp_ldap_admin_dn();
     309                char *ldap_admin_dn = lp_ldap_admin_dn(talloc_tos());
    304310                if ( ! *ldap_admin_dn ) {
    305311                        DEBUG(0,("ERROR: 'ldap admin dn' not defined! Please check your smb.conf\n"));
     
    310316                if ( ! *ldap_secret ) {
    311317                        new_passwd = prompt_for_new_password(stdin_passwd_get);
     318                        if (new_passwd == NULL) {
     319                                fprintf(stderr, "Failed to read new password!\n");
     320                                exit(1);
     321                        }
    312322                        fstrcpy(ldap_secret, new_passwd);
    313323                }
     
    370380                        SAFE_FREE(new_passwd);
    371381                        new_passwd = smb_xstrdup(user_name);
    372                         strlower_m(new_passwd);
     382                        if (!strlower_m(new_passwd)) {
     383                                fprintf(stderr, "strlower_m %s failed\n",
     384                                        new_passwd);
     385                                exit(1);
     386                        }
    373387                }
    374388
     
    379393
    380394                slprintf(buf, sizeof(buf)-1, "%s$", user_name);
    381                 fstrcpy(user_name, buf);
     395                strlcpy(user_name, buf, sizeof(user_name));
    382396        } else if (local_flags & LOCAL_INTERDOM_ACCOUNT) {
    383397                static fstring buf;
     
    396410                /* prepare uppercased and '$' terminated username */
    397411                slprintf(buf, sizeof(buf) - 1, "%s$", user_name);
    398                 fstrcpy(user_name, buf);
     412                strlcpy(user_name, buf, sizeof(user_name));
    399413
    400414        } else {
     
    533547        if (remote_machine != NULL) {
    534548                old_pw = get_pass("Old SMB password:",stdin_passwd_get);
     549                if (old_pw == NULL) {
     550                        fprintf(stderr, "Unable to get old password.\n");
     551                        exit(1);
     552                }
    535553        }
    536554
     
    580598        }
    581599
    582         load_case_tables();
     600        smb_init_locale();
    583601
    584602        local_flags = process_options(argc, argv, local_flags);
     
    601619
    602620        if (local_flags & LOCAL_AM_ROOT) {
    603                 secrets_init();
    604                 return process_root(local_flags);
    605         }
    606 
    607         ret = process_nonroot(local_flags);
     621                bool ok;
     622
     623                ok = secrets_init();
     624                if (!ok) {
     625                        return 1;
     626                }
     627                ret = process_root(local_flags);
     628        } else {
     629                ret = process_nonroot(local_flags);
     630        }
    608631        TALLOC_FREE(frame);
    609632        return ret;
  • vendor/current/source3/utils/smbtree.c

    r740 r988  
    3939        struct smb_name_list *prev, *next;
    4040        char *name, *comment;
    41         uint32 server_type;
     41        uint32_t server_type;
    4242};
    4343
     
    5050}
    5151
    52 static void add_name(const char *machine_name, uint32 server_type,
     52static void add_name(const char *machine_name, uint32_t server_type,
    5353                     const char *comment, void *state)
    5454{
     
    9696        }
    9797
    98         if (!use_bcast && !find_master_ip(lp_workgroup(), &server_ss)) {
    99                 DEBUG(4, ("Unable to find master browser for workgroup %s, falling back to broadcast\n",
    100                           master_workgroup));
    101                                 use_bcast = True;
    102                 } else if(!use_bcast) {
    103                         char addr[INET6_ADDRSTRLEN];
    104                         print_sockaddr(addr, sizeof(addr), &server_ss);
    105                         if (!(cli = get_ipc_connect(addr, &server_ss, user_info)))
    106                                 return False;
     98        if (!use_bcast && !find_master_ip(lp_workgroup(), &server_ss)) {
     99                DEBUG(4,("Unable to find master browser for workgroup %s, "
     100                         "falling back to broadcast\n",
     101                         master_workgroup));
     102                use_bcast = true;
     103        }
     104
     105        if (!use_bcast) {
     106                char addr[INET6_ADDRSTRLEN];
     107
     108                print_sockaddr(addr, sizeof(addr), &server_ss);
     109
     110                cli = get_ipc_connect(addr, &server_ss, user_info);
     111                if (cli == NULL) {
     112                        return false;
    107113                }
    108 
    109                 if (!(cli = get_ipc_connect_master_ip_bcast(talloc_tos(),
    110                                                         user_info,
    111                                                         &master_workgroup))) {
     114        } else {
     115                cli = get_ipc_connect_master_ip_bcast(talloc_tos(),
     116                                                      user_info,
     117                                                      &master_workgroup);
     118                if (cli == NULL) {
    112119                        DEBUG(4, ("Unable to find master browser by "
    113120                                  "broadcast\n"));
    114                         return False;
    115         }
     121                        return false;
     122                }
     123        }
    116124
    117125        if (!cli_NetServerEnum(cli, master_workgroup,
     
    150158
    151159static bool get_rpc_shares(struct cli_state *cli,
    152                            void (*fn)(const char *, uint32, const char *, void *),
     160                           void (*fn)(const char *, uint32_t, const char *, void *),
    153161                           void *state)
    154162{
     
    170178        }
    171179
    172         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_srvsvc.syntax_id,
     180        status = cli_rpc_pipe_open_noauth(cli, &ndr_table_srvsvc,
    173181                                          &pipe_hnd);
    174182
     
    202210        }
    203211
    204         for (i=0; i<total_entries; i++) {
     212        for (i=0; i < info_ctr.ctr.ctr1->count; i++) {
    205213                struct srvsvc_NetShareInfo1 info = info_ctr.ctr.ctr1->array[i];
    206214                fn(info.name, info.type, info.comment, state);
     
    278286  main program
    279287****************************************************************************/
    280  int main(int argc,char *argv[])
     288int main(int argc, char *argv[])
    281289{
    282290        TALLOC_CTX *frame = talloc_stackframe();
     291        const char **argv_const = discard_const_p(const char *, argv);
    283292        struct user_auth_info *auth_info;
    284293        struct poptOption long_options[] = {
     
    294303
    295304        /* Initialise samba stuff */
    296         load_case_tables();
     305        smb_init_locale();
    297306
    298307        setlinebuf(stdout);
     
    306315        popt_common_set_auth_info(auth_info);
    307316
    308         pc = poptGetContext("smbtree", argc, (const char **)argv, long_options,
    309                                                 POPT_CONTEXT_KEEP_FIRST);
     317        pc = poptGetContext("smbtree", argc, argv_const, long_options,
     318                            POPT_CONTEXT_KEEP_FIRST);
    310319        while(poptGetNextOpt(pc) != -1);
    311320        poptFreeContext(pc);
    312 
    313         lp_load(get_dyn_CONFIGFILE(),True,False,False,True);
     321        popt_burn_cmdline_password(argc, argv);
     322
     323        lp_load_global(get_dyn_CONFIGFILE());
    314324        load_interfaces();
    315325
  • vendor/current/source3/utils/split_tokens.c

    r740 r988  
    4141        };
    4242
    43         load_case_tables();
     43        smb_init_locale();
    4444
    4545        pc = poptGetContext(NULL, argc, argv, long_options,
     
    5757                return 1;
    5858        }
    59        
     59
    6060        lp_set_cmdline("log level", "0");
    6161
    62         if (!lp_load(config_file,false,true,false,true)) {
     62        if (!lp_load_global(config_file)) {
    6363                fprintf(stderr,"Error loading services.\n");
    6464                return 1;
  • vendor/current/source3/utils/status.c

    r860 r988  
    3232
    3333#include "includes.h"
     34#include "smbd/globals.h"
    3435#include "system/filesys.h"
    3536#include "popt_common.h"
    36 #include "dbwrap.h"
     37#include "dbwrap/dbwrap.h"
     38#include "dbwrap/dbwrap_open.h"
    3739#include "../libcli/security/security.h"
    3840#include "session.h"
    3941#include "locking/proto.h"
    4042#include "messages.h"
     43#include "librpc/gen_ndr/open_files.h"
     44#include "smbd/smbd.h"
     45#include "librpc/gen_ndr/notify.h"
     46#include "lib/conn_tdb.h"
    4147#include "serverid.h"
     48#include "status_profile.h"
     49#include "smbd/notifyd/notifyd.h"
    4250
    4351#define SMB_MAXPIDS             2048
     
    5361static bool show_brl;
    5462static bool numeric_only;
     63static bool do_checks = true;
    5564
    5665const char *username = NULL;
    57 
    58 extern bool status_profile_dump(bool be_verbose);
    59 extern bool status_profile_rates(bool be_verbose);
    6066
    6167/* added by OH */
     
    8591
    8692        for (i=0;i<Ucrit_MaxPid;i++) {
    87                 if (cluster_id_equal(&pid, &Ucrit_pid[i]))
     93                if (serverid_equal(&pid, &Ucrit_pid[i])) {
    8894                        return 1;
     95                }
    8996        }
    9097
     
    109116}
    110117
    111 static void print_share_mode(const struct share_mode_entry *e,
    112                              const char *sharepath,
    113                              const char *fname,
    114                              void *dummy)
     118static int print_share_mode(const struct share_mode_entry *e,
     119                            const char *sharepath,
     120                            const char *fname,
     121                            const char *sname,
     122                            void *dummy)
    115123{
    116124        static int count;
    117125
    118         if (!is_valid_share_mode_entry(e)) {
    119                 return;
    120         }
    121 
    122         if (!process_exists(e->pid)) {
    123                 return;
     126        if (do_checks && !is_valid_share_mode_entry(e)) {
     127                return 0;
    124128        }
    125129
     
    131135        count++;
    132136
     137        if (do_checks && !serverid_exists(&e->pid)) {
     138                /* the process for this entry does not exist any more */
     139                return 0;
     140        }
     141
    133142        if (Ucrit_checkPid(e->pid)) {
    134                 d_printf("%-11s  ",procid_str_static(&e->pid));
     143                struct server_id_buf tmp;
     144                d_printf("%-11s  ", server_id_str_buf(e->pid, &tmp));
    135145                d_printf("%-9u  ", (unsigned int)e->uid);
    136146                switch (map_share_mode_to_deny_mode(e->share_access,
     
    170180                } else if (e->op_type & LEVEL_II_OPLOCK) {
    171181                        d_printf("LEVEL_II        ");
     182                } else if (e->op_type == LEASE_OPLOCK) {
     183                        uint32_t lstate = e->lease->current_state;
     184                        d_printf("LEASE(%s%s%s)%s%s%s      ",
     185                                 (lstate & SMB2_LEASE_READ)?"R":"",
     186                                 (lstate & SMB2_LEASE_WRITE)?"W":"",
     187                                 (lstate & SMB2_LEASE_HANDLE)?"H":"",
     188                                 (lstate & SMB2_LEASE_READ)?"":" ",
     189                                 (lstate & SMB2_LEASE_WRITE)?"":" ",
     190                                 (lstate & SMB2_LEASE_HANDLE)?"":" ");
    172191                } else {
    173192                        d_printf("NONE            ");
    174193                }
    175194
    176                 d_printf(" %s   %s   %s",sharepath, fname, time_to_asc((time_t)e->time.tv_sec));
    177         }
     195                d_printf(" %s   %s%s   %s",
     196                         sharepath, fname,
     197                         sname ? sname : "",
     198                         time_to_asc((time_t)e->time.tv_sec));
     199        }
     200
     201        return 0;
    178202}
    179203
     
    187211{
    188212        static int count;
    189         int i;
     213        unsigned int i;
    190214        static const struct {
    191215                enum brl_type lock_type;
     
    202226        char *fname = NULL;
    203227        struct share_mode_lock *share_mode;
     228        struct server_id_buf tmp;
    204229
    205230        if (count==0) {
     
    212237        share_mode = fetch_share_mode_unlocked(NULL, id);
    213238        if (share_mode) {
    214                 bool has_stream = share_mode->stream_name != NULL;
    215 
    216                 fname = talloc_asprintf(NULL, "%s%s%s", share_mode->base_name,
     239                bool has_stream = share_mode->data->stream_name != NULL;
     240
     241                fname = talloc_asprintf(NULL, "%s%s%s",
     242                                        share_mode->data->base_name,
    217243                                        has_stream ? ":" : "",
    218                                         has_stream ? share_mode->stream_name :
     244                                        has_stream ?
     245                                        share_mode->data->stream_name :
    219246                                        "");
    220247        } else {
     
    231258        }
    232259
    233         d_printf("%-10s %-15s %-4s %-9.0f %-9.0f %-24s %-24s\n",
    234                  procid_str_static(&pid), file_id_string_tos(&id),
     260        d_printf("%-10s %-15s %-4s %-9jd %-9jd %-24s %-24s\n",
     261                 server_id_str_buf(pid, &tmp), file_id_string_tos(&id),
    235262                 desc,
    236                  (double)start, (double)size,
     263                 (intmax_t)start, (intmax_t)size,
    237264                 sharepath, fname);
    238265
     
    241268}
    242269
    243 static int traverse_fn1(const struct connections_key *key,
    244                         const struct connections_data *crec,
    245                         void *state)
    246 {
    247         if (crec->cnum == -1)
     270static const char *session_dialect_str(uint16_t dialect)
     271{
     272        static fstring unkown_dialect;
     273
     274        switch(dialect){
     275        case SMB2_DIALECT_REVISION_000:
     276                return "NT1";
     277        case SMB2_DIALECT_REVISION_202:
     278                return "SMB2_02";
     279        case SMB2_DIALECT_REVISION_210:
     280                return "SMB2_10";
     281        case SMB2_DIALECT_REVISION_222:
     282                return "SMB2_22";
     283        case SMB2_DIALECT_REVISION_224:
     284                return "SMB2_24";
     285        case SMB3_DIALECT_REVISION_300:
     286                return "SMB3_00";
     287        case SMB3_DIALECT_REVISION_302:
     288                return "SMB3_02";
     289        case SMB3_DIALECT_REVISION_310:
     290                return "SMB3_10";
     291        case SMB3_DIALECT_REVISION_311:
     292                return "SMB3_11";
     293        }
     294
     295        fstr_sprintf(unkown_dialect, "Unknown (0x%04x)", dialect);
     296        return unkown_dialect;
     297}
     298
     299static int traverse_connections(const struct connections_key *key,
     300                                const struct connections_data *crec,
     301                                void *private_data)
     302{
     303        TALLOC_CTX *mem_ctx = (TALLOC_CTX *)private_data;
     304        struct server_id_buf tmp;
     305        char *timestr = NULL;
     306        int result = 0;
     307        const char *encryption = "-";
     308        const char *signing = "-";
     309
     310        if (crec->cnum == TID_FIELD_INVALID)
    248311                return 0;
    249312
    250         if (!process_exists(crec->pid) || !Ucrit_checkUid(crec->uid)) {
     313        if (do_checks &&
     314            (!process_exists(crec->pid) || !Ucrit_checkUid(crec->uid))) {
    251315                return 0;
    252316        }
    253317
    254         d_printf("%-10s   %s   %-12s  %s",
    255                  crec->servicename,procid_str_static(&crec->pid),
     318        timestr = timestring(mem_ctx, crec->start);
     319        if (timestr == NULL) {
     320                return -1;
     321        }
     322
     323        if (smbXsrv_is_encrypted(crec->encryption_flags)) {
     324                switch (crec->cipher) {
     325                case SMB_ENCRYPTION_GSSAPI:
     326                        encryption = "GSSAPI";
     327                        break;
     328                case SMB2_ENCRYPTION_AES128_CCM:
     329                        encryption = "AES-128-CCM";
     330                        break;
     331                case SMB2_ENCRYPTION_AES128_GCM:
     332                        encryption = "AES-128-GCM";
     333                        break;
     334                default:
     335                        encryption = "???";
     336                        result = -1;
     337                        break;
     338                }
     339        }
     340
     341        if (smbXsrv_is_signed(crec->signing_flags)) {
     342                if (crec->dialect >= SMB3_DIALECT_REVISION_302) {
     343                        signing = "AES-128-CMAC";
     344                } else if (crec->dialect >= SMB2_DIALECT_REVISION_202) {
     345                        signing = "HMAC-SHA256";
     346                } else {
     347                        signing = "HMAC-MD5";
     348                }
     349        }
     350
     351        d_printf("%-12s %-7s %-13s %-32s %-12s %-12s\n",
     352                 crec->servicename, server_id_str_buf(crec->pid, &tmp),
    256353                 crec->machine,
    257                  time_to_asc(crec->start));
    258 
    259         return 0;
     354                 timestr,
     355                 encryption,
     356                 signing);
     357
     358        TALLOC_FREE(timestr);
     359
     360        return result;
    260361}
    261362
     
    263364                              void *private_data)
    264365{
     366        TALLOC_CTX *mem_ctx = (TALLOC_CTX *)private_data;
    265367        fstring uid_str, gid_str;
    266 
    267         if (!process_exists(session->pid)
    268             || !Ucrit_checkUid(session->uid)) {
     368        struct server_id_buf tmp;
     369        char *machine_hostname = NULL;
     370        int result = 0;
     371        const char *encryption = "-";
     372        const char *signing = "-";
     373
     374        if (do_checks &&
     375            (!process_exists(session->pid) ||
     376             !Ucrit_checkUid(session->uid))) {
    269377                return 0;
    270378        }
     
    272380        Ucrit_addPid(session->pid);
    273381
    274         fstr_sprintf(uid_str, "%u", (unsigned int)session->uid);
    275         fstr_sprintf(gid_str, "%u", (unsigned int)session->gid);
    276 
    277         d_printf("%-7s   %-12s  %-12s  %-12s (%s)\n",
    278                  procid_str_static(&session->pid),
    279                  numeric_only ? uid_str : uidtoname(session->uid),
    280                  numeric_only ? gid_str : gidtoname(session->gid),
    281                  session->remote_machine, session->hostname);
    282 
    283         return 0;
    284 }
    285 
    286 
    287 
    288 
    289  int main(int argc, char *argv[])
     382        fstrcpy(uid_str, "-1");
     383
     384        if (session->uid != -1) {
     385                if (numeric_only) {
     386                        fstr_sprintf(uid_str, "%u", (unsigned int)session->uid);
     387                } else {
     388                        fstrcpy(uid_str, uidtoname(session->uid));
     389                }
     390        }
     391
     392        fstrcpy(gid_str, "-1");
     393
     394        if (session->gid != -1) {
     395                if (numeric_only) {
     396                        fstr_sprintf(gid_str, "%u", (unsigned int)session->gid);
     397                } else {
     398                        fstrcpy(gid_str, gidtoname(session->gid));
     399                }
     400        }
     401
     402        machine_hostname = talloc_asprintf(mem_ctx, "%s (%s)",
     403                                           session->remote_machine,
     404                                           session->hostname);
     405        if (machine_hostname == NULL) {
     406                return -1;
     407        }
     408
     409        if (smbXsrv_is_encrypted(session->encryption_flags)) {
     410                switch (session->cipher) {
     411                case SMB2_ENCRYPTION_AES128_CCM:
     412                        encryption = "AES-128-CCM";
     413                        break;
     414                case SMB2_ENCRYPTION_AES128_GCM:
     415                        encryption = "AES-128-GCM";
     416                        break;
     417                default:
     418                        encryption = "???";
     419                        result = -1;
     420                        break;
     421                }
     422        } else if (smbXsrv_is_partially_encrypted(session->encryption_flags)) {
     423                switch (session->cipher) {
     424                case SMB_ENCRYPTION_GSSAPI:
     425                        encryption = "partial(GSSAPI)";
     426                        break;
     427                case SMB2_ENCRYPTION_AES128_CCM:
     428                        encryption = "partial(AES-128-CCM)";
     429                        break;
     430                case SMB2_ENCRYPTION_AES128_GCM:
     431                        encryption = "partial(AES-128-GCM)";
     432                        break;
     433                default:
     434                        encryption = "???";
     435                        result = -1;
     436                        break;
     437                }
     438        }
     439
     440        if (smbXsrv_is_signed(session->signing_flags)) {
     441                if (session->connection_dialect >= SMB3_DIALECT_REVISION_302) {
     442                        signing = "AES-128-CMAC";
     443                } else if (session->connection_dialect >= SMB2_DIALECT_REVISION_202) {
     444                        signing = "HMAC-SHA256";
     445                } else {
     446                        signing = "HMAC-MD5";
     447                }
     448        } else if (smbXsrv_is_partially_signed(session->signing_flags)) {
     449                if (session->connection_dialect >= SMB3_DIALECT_REVISION_302) {
     450                        signing = "partial(AES-128-CMAC)";
     451                } else if (session->connection_dialect >= SMB2_DIALECT_REVISION_202) {
     452                        signing = "partial(HMAC-SHA256)";
     453                } else {
     454                        signing = "partial(HMAC-MD5)";
     455                }
     456        }
     457
     458
     459        d_printf("%-7s %-12s %-12s %-41s %-17s %-20s %-21s\n",
     460                 server_id_str_buf(session->pid, &tmp),
     461                 uid_str, gid_str,
     462                 machine_hostname,
     463                 session_dialect_str(session->connection_dialect),
     464                 encryption,
     465                 signing);
     466
     467        TALLOC_FREE(machine_hostname);
     468
     469        return result;
     470}
     471
     472
     473static bool print_notify_rec(const char *path, struct server_id server,
     474                             const struct notify_instance *instance,
     475                             void *private_data)
     476{
     477        struct server_id_buf idbuf;
     478
     479        d_printf("%s\\%s\\%x\\%x\n", path, server_id_str_buf(server, &idbuf),
     480                 (unsigned)instance->filter,
     481                 (unsigned)instance->subdir_filter);
     482
     483        return true;
     484}
     485
     486int main(int argc, const char *argv[])
    290487{
    291488        int c;
    292489        int profile_only = 0;
    293490        bool show_processes, show_locks, show_shares;
     491        bool show_notify = false;
    294492        poptContext pc;
    295493        struct poptOption long_options[] = {
     
    299497                {"locks",       'L', POPT_ARG_NONE,     NULL, 'L', "Show locks only" },
    300498                {"shares",      'S', POPT_ARG_NONE,     NULL, 'S', "Show shares only" },
     499                {"notify",      'N', POPT_ARG_NONE,     NULL, 'N', "Show notifies" },
    301500                {"user",        'u', POPT_ARG_STRING,   &username, 'u', "Switch to user" },
    302501                {"brief",       'b', POPT_ARG_NONE,     NULL, 'b', "Be brief" },
     
    305504                {"byterange",   'B', POPT_ARG_NONE,     NULL, 'B', "Include byte range locks"},
    306505                {"numeric",     'n', POPT_ARG_NONE,     NULL, 'n', "Numeric uid/gid"},
     506                {"fast",        'f', POPT_ARG_NONE,     NULL, 'f', "Skip checks if processes still exist"},
    307507                POPT_COMMON_SAMBA
    308508                POPT_TABLEEND
     
    310510        TALLOC_CTX *frame = talloc_stackframe();
    311511        int ret = 0;
    312         struct messaging_context *msg_ctx;
     512        struct messaging_context *msg_ctx = NULL;
     513        char *db_path;
     514        bool ok;
    313515
    314516        sec_init();
    315         load_case_tables();
     517        smb_init_locale();
    316518
    317519        setup_logging(argv[0], DEBUG_STDERR);
     520        lp_set_cmdline("log level", "0");
    318521
    319522        if (getuid() != geteuid()) {
     
    323526        }
    324527
    325         pc = poptGetContext(NULL, argc, (const char **) argv, long_options,
     528        if (getuid() != 0) {
     529                d_printf("smbstatus only works as root!\n");
     530                ret = 1;
     531                goto done;
     532        }
     533
     534
     535        pc = poptGetContext(NULL, argc, argv, long_options,
    326536                            POPT_CONTEXT_KEEP_FIRST);
    327537
     
    340550                        shares_only = true;
    341551                        break;
     552                case 'N':
     553                        show_notify = true;
     554                        break;
    342555                case 'b':
    343556                        brief = true;
     
    355568                case 'n':
    356569                        numeric_only = true;
     570                        break;
     571                case 'f':
     572                        do_checks = false;
    357573                        break;
    358574                }
     
    380596
    381597
    382         if (!sessionid_init_readonly()) {
    383                 fprintf(stderr, "Can't open sessionid.tdb\n");
     598        /*
     599         * This implicitly initializes the global ctdbd connection,
     600         * usable by the db_open() calls further down.
     601         */
     602        msg_ctx = messaging_init(NULL, samba_tevent_context_init(NULL));
     603        if (msg_ctx == NULL) {
     604                fprintf(stderr, "messaging_init failed\n");
    384605                ret = -1;
    385606                goto done;
    386607        }
    387608
    388         if (lp_clustering()) {
    389                 /*
    390                  * This implicitly initializes the global ctdbd
    391                  * connection, usable by the db_open() calls further
    392                  * down.
    393                  */
    394                 msg_ctx = messaging_init(NULL, procid_self(),
    395                                          event_context_init(NULL));
    396                 if (msg_ctx == NULL) {
    397                         fprintf(stderr, "messaging_init failed\n");
    398                         ret = -1;
    399                         goto done;
    400                 }
    401         }
    402 
    403         if (!lp_load(get_dyn_CONFIGFILE(),False,False,False,True)) {
     609        if (!lp_load_global(get_dyn_CONFIGFILE())) {
    404610                fprintf(stderr, "Can't load %s - run testparm to debug it\n",
    405611                        get_dyn_CONFIGFILE());
     
    411617                case 'P':
    412618                        /* Dump profile data */
    413                         return status_profile_dump(verbose);
     619                        ok = status_profile_dump(verbose);
     620                        return ok ? 0 : 1;
    414621                case 'R':
    415622                        /* Continuously display rate-converted data */
    416                         return status_profile_rates(verbose);
     623                        ok = status_profile_rates(verbose);
     624                        return ok ? 0 : 1;
    417625                default:
    418626                        break;
     
    421629        if ( show_processes ) {
    422630                d_printf("\nSamba version %s\n",samba_version_string());
    423                 d_printf("PID     Username      Group         Machine                        \n");
    424                 d_printf("-------------------------------------------------------------------\n");
    425                 if (lp_security() == SEC_SHARE) {
    426                         d_printf(" <processes do not show up in "
    427                                  "anonymous mode>\n");
    428                 }
    429 
    430                 sessionid_traverse_read(traverse_sessionid, NULL);
     631                d_printf("%-7s %-12s %-12s %-41s %-17s %-20s %-21s\n", "PID", "Username", "Group", "Machine", "Protocol Version", "Encryption", "Signing");
     632                d_printf("----------------------------------------------------------------------------------------------------------------------------------------\n");
     633
     634                sessionid_traverse_read(traverse_sessionid, frame);
    431635
    432636                if (processes_only) {
     
    436640
    437641        if ( show_shares ) {
    438                 if (verbose) {
    439                         d_printf("Opened %s\n", lock_path("connections.tdb"));
    440                 }
    441 
    442642                if (brief) {
    443643                        goto done;
    444644                }
    445645
    446                 d_printf("\nService      pid     machine       Connected at\n");
    447                 d_printf("-------------------------------------------------------\n");
    448 
    449                 connections_forall_read(traverse_fn1, NULL);
     646                d_printf("\n%-12s %-7s %-13s %-32s %-12s %-12s\n", "Service", "pid", "Machine", "Connected at", "Encryption", "Signing");
     647                d_printf("---------------------------------------------------------------------------------------------\n");
     648
     649                connections_forall_read(traverse_connections, frame);
    450650
    451651                d_printf("\n");
     
    459659                int result;
    460660                struct db_context *db;
    461                 db = db_open(NULL, lock_path("locking.tdb"), 0,
    462                              TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH, O_RDONLY, 0);
     661
     662                db_path = lock_path("locking.tdb");
     663                if (db_path == NULL) {
     664                        d_printf("Out of memory - exiting\n");
     665                        ret = -1;
     666                        goto done;
     667                }
     668
     669                db = db_open(NULL, db_path, 0,
     670                             TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH, O_RDONLY, 0,
     671                             DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
    463672
    464673                if (!db) {
    465                         d_printf("%s not initialised\n",
    466                                  lock_path("locking.tdb"));
     674                        d_printf("%s not initialised\n", db_path);
    467675                        d_printf("This is normal if an SMB client has never "
    468676                                 "connected to your server.\n");
     677                        TALLOC_FREE(db_path);
    469678                        exit(0);
    470679                } else {
    471680                        TALLOC_FREE(db);
     681                        TALLOC_FREE(db_path);
    472682                }
    473683
     
    478688                }
    479689
    480                 if (!serverid_init_readonly(frame)) {
    481                         d_printf("Can't initialise serverid tdb - exiting\n");
    482                         ret = 1;
    483                         goto done;
    484                 }
    485                 result = share_mode_forall(print_share_mode, NULL);
     690                result = share_entry_forall(print_share_mode, NULL);
    486691
    487692                if (result == 0) {
    488693                        d_printf("No locked files\n");
    489                 } else if (result == -1) {
     694                } else if (result < 0) {
    490695                        d_printf("locked file list truncated\n");
    491696                }
     
    498703
    499704                locking_end();
     705        }
     706
     707        if (show_notify) {
     708                struct notify_context *n;
     709
     710                n = notify_init(talloc_tos(), msg_ctx,
     711                                messaging_tevent_context(msg_ctx));
     712                if (n == NULL) {
     713                        goto done;
     714                }
     715                notify_walk(n, print_notify_rec, NULL);
     716                TALLOC_FREE(n);
    500717        }
    501718
  • vendor/current/source3/utils/status_profile.c

    r740 r988  
    2121#include "includes.h"
    2222#include "smbprofile.h"
    23 
    24 bool status_profile_dump(bool be_verbose);
    25 bool status_profile_rates(bool be_verbose);
    26 
    27 #ifdef WITH_PROFILE
     23#include "status_profile.h"
     24
    2825static void profile_separator(const char * title)
    2926{
     
    4037    d_printf("%s\n", line);
    4138}
    42 #endif
    4339
    4440/*******************************************************************
     
    4743bool status_profile_dump(bool verbose)
    4844{
    49 #ifdef WITH_PROFILE
     45        struct profile_stats stats = {};
     46
    5047        if (!profile_setup(NULL, True)) {
    5148                fprintf(stderr,"Failed to initialise profile memory\n");
     
    5350        }
    5451
    55         d_printf("smb_count:                      %u\n", profile_p->smb_count);
    56         d_printf("uid_changes:                    %u\n", profile_p->uid_changes);
    57 
    58         profile_separator("System Calls");
    59         d_printf("opendir_count:                  %u\n", profile_p->syscall_opendir_count);
    60         d_printf("opendir_time:                   %u\n", profile_p->syscall_opendir_time);
    61         d_printf("fdopendir_count:                %u\n", profile_p->syscall_fdopendir_count);
    62         d_printf("fdopendir_time:                 %u\n", profile_p->syscall_fdopendir_time);
    63         d_printf("readdir_count:                  %u\n", profile_p->syscall_readdir_count);
    64         d_printf("readdir_time:                   %u\n", profile_p->syscall_readdir_time);
    65         d_printf("mkdir_count:                    %u\n", profile_p->syscall_mkdir_count);
    66         d_printf("mkdir_time:                     %u\n", profile_p->syscall_mkdir_time);
    67         d_printf("rmdir_count:                    %u\n", profile_p->syscall_rmdir_count);
    68         d_printf("rmdir_time:                     %u\n", profile_p->syscall_rmdir_time);
    69         d_printf("closedir_count:                 %u\n", profile_p->syscall_closedir_count);
    70         d_printf("closedir_time:                  %u\n", profile_p->syscall_closedir_time);
    71         d_printf("open_count:                     %u\n", profile_p->syscall_open_count);
    72         d_printf("open_time:                      %u\n", profile_p->syscall_open_time);
    73         d_printf("close_count:                    %u\n", profile_p->syscall_close_count);
    74         d_printf("close_time:                     %u\n", profile_p->syscall_close_time);
    75         d_printf("read_count:                     %u\n", profile_p->syscall_read_count);
    76         d_printf("read_time:                      %u\n", profile_p->syscall_read_time);
    77         d_printf("read_bytes:                     %u\n", profile_p->syscall_read_bytes);
    78         d_printf("write_count:                    %u\n", profile_p->syscall_write_count);
    79         d_printf("write_time:                     %u\n", profile_p->syscall_write_time);
    80         d_printf("write_bytes:                    %u\n", profile_p->syscall_write_bytes);
    81         d_printf("pread_count:                    %u\n", profile_p->syscall_pread_count);
    82         d_printf("pread_time:                     %u\n", profile_p->syscall_pread_time);
    83         d_printf("pread_bytes:                    %u\n", profile_p->syscall_pread_bytes);
    84         d_printf("pwrite_count:                   %u\n", profile_p->syscall_pwrite_count);
    85         d_printf("pwrite_time:                    %u\n", profile_p->syscall_pwrite_time);
    86         d_printf("pwrite_bytes:                   %u\n", profile_p->syscall_pwrite_bytes);
    87         d_printf("sendfile_count:                 %u\n", profile_p->syscall_sendfile_count);
    88         d_printf("sendfile_time:                  %u\n", profile_p->syscall_sendfile_time);
    89         d_printf("sendfile_bytes:                 %u\n", profile_p->syscall_sendfile_bytes);
    90         d_printf("lseek_count:                    %u\n", profile_p->syscall_lseek_count);
    91         d_printf("lseek_time:                     %u\n", profile_p->syscall_lseek_time);
    92         d_printf("rename_count:                   %u\n", profile_p->syscall_rename_count);
    93         d_printf("rename_time:                    %u\n", profile_p->syscall_rename_time);
    94         d_printf("fsync_count:                    %u\n", profile_p->syscall_fsync_count);
    95         d_printf("fsync_time:                     %u\n", profile_p->syscall_fsync_time);
    96         d_printf("stat_count:                     %u\n", profile_p->syscall_stat_count);
    97         d_printf("stat_time:                      %u\n", profile_p->syscall_stat_time);
    98         d_printf("fstat_count:                    %u\n", profile_p->syscall_fstat_count);
    99         d_printf("fstat_time:                     %u\n", profile_p->syscall_fstat_time);
    100         d_printf("lstat_count:                    %u\n", profile_p->syscall_lstat_count);
    101         d_printf("lstat_time:                     %u\n", profile_p->syscall_lstat_time);
    102         d_printf("unlink_count:                   %u\n", profile_p->syscall_unlink_count);
    103         d_printf("unlink_time:                    %u\n", profile_p->syscall_unlink_time);
    104         d_printf("chmod_count:                    %u\n", profile_p->syscall_chmod_count);
    105         d_printf("chmod_time:                     %u\n", profile_p->syscall_chmod_time);
    106         d_printf("fchmod_count:                   %u\n", profile_p->syscall_fchmod_count);
    107         d_printf("fchmod_time:                    %u\n", profile_p->syscall_fchmod_time);
    108         d_printf("chown_count:                    %u\n", profile_p->syscall_chown_count);
    109         d_printf("chown_time:                     %u\n", profile_p->syscall_chown_time);
    110         d_printf("fchown_count:                   %u\n", profile_p->syscall_fchown_count);
    111         d_printf("fchown_time:                    %u\n", profile_p->syscall_fchown_time);
    112         d_printf("chdir_count:                    %u\n", profile_p->syscall_chdir_count);
    113         d_printf("chdir_time:                     %u\n", profile_p->syscall_chdir_time);
    114         d_printf("getwd_count:                    %u\n", profile_p->syscall_getwd_count);
    115         d_printf("getwd_time:                     %u\n", profile_p->syscall_getwd_time);
    116         d_printf("ntimes_count:                   %u\n", profile_p->syscall_ntimes_count);
    117         d_printf("ntimes_time:                    %u\n", profile_p->syscall_ntimes_time);
    118         d_printf("ftruncate_count:                %u\n", profile_p->syscall_ftruncate_count);
    119         d_printf("ftruncate_time:                 %u\n", profile_p->syscall_ftruncate_time);
    120         d_printf("fcntl_lock_count:               %u\n", profile_p->syscall_fcntl_lock_count);
    121         d_printf("fcntl_lock_time:                %u\n", profile_p->syscall_fcntl_lock_time);
    122         d_printf("readlink_count:                 %u\n", profile_p->syscall_readlink_count);
    123         d_printf("readlink_time:                  %u\n", profile_p->syscall_readlink_time);
    124         d_printf("symlink_count:                  %u\n", profile_p->syscall_symlink_count);
    125         d_printf("symlink_time:                   %u\n", profile_p->syscall_symlink_time);
    126 
    127         profile_separator("Stat Cache");
    128         d_printf("lookups:                        %u\n", profile_p->statcache_lookups);
    129         d_printf("misses:                         %u\n", profile_p->statcache_misses);
    130         d_printf("hits:                           %u\n", profile_p->statcache_hits);
    131 
    132         profile_separator("Write Cache");
    133         d_printf("read_hits:                      %u\n", profile_p->writecache_read_hits);
    134         d_printf("abutted_writes:                 %u\n", profile_p->writecache_abutted_writes);
    135         d_printf("total_writes:                   %u\n", profile_p->writecache_total_writes);
    136         d_printf("non_oplock_writes:              %u\n", profile_p->writecache_non_oplock_writes);
    137         d_printf("direct_writes:                  %u\n", profile_p->writecache_direct_writes);
    138         d_printf("init_writes:                    %u\n", profile_p->writecache_init_writes);
    139         d_printf("flushed_writes[SEEK]:           %u\n", profile_p->writecache_flushed_writes[SEEK_FLUSH]);
    140         d_printf("flushed_writes[READ]:           %u\n", profile_p->writecache_flushed_writes[READ_FLUSH]);
    141         d_printf("flushed_writes[WRITE]:          %u\n", profile_p->writecache_flushed_writes[WRITE_FLUSH]);
    142         d_printf("flushed_writes[READRAW]:        %u\n", profile_p->writecache_flushed_writes[READRAW_FLUSH]);
    143         d_printf("flushed_writes[OPLOCK_RELEASE]: %u\n", profile_p->writecache_flushed_writes[OPLOCK_RELEASE_FLUSH]);
    144         d_printf("flushed_writes[CLOSE]:          %u\n", profile_p->writecache_flushed_writes[CLOSE_FLUSH]);
    145         d_printf("flushed_writes[SYNC]:           %u\n", profile_p->writecache_flushed_writes[SYNC_FLUSH]);
    146         d_printf("flushed_writes[SIZECHANGE]:     %u\n", profile_p->writecache_flushed_writes[SIZECHANGE_FLUSH]);
    147         d_printf("num_perfect_writes:             %u\n", profile_p->writecache_num_perfect_writes);
    148         d_printf("num_write_caches:               %u\n", profile_p->writecache_num_write_caches);
    149         d_printf("allocated_write_caches:         %u\n", profile_p->writecache_allocated_write_caches);
    150 
    151         profile_separator("SMB Calls");
    152         d_printf("mkdir_count:                    %u\n", profile_p->SMBmkdir_count);
    153         d_printf("mkdir_time:                     %u\n", profile_p->SMBmkdir_time);
    154         d_printf("rmdir_count:                    %u\n", profile_p->SMBrmdir_count);
    155         d_printf("rmdir_time:                     %u\n", profile_p->SMBrmdir_time);
    156         d_printf("open_count:                     %u\n", profile_p->SMBopen_count);
    157         d_printf("open_time:                      %u\n", profile_p->SMBopen_time);
    158         d_printf("create_count:                   %u\n", profile_p->SMBcreate_count);
    159         d_printf("create_time:                    %u\n", profile_p->SMBcreate_time);
    160         d_printf("close_count:                    %u\n", profile_p->SMBclose_count);
    161         d_printf("close_time:                     %u\n", profile_p->SMBclose_time);
    162         d_printf("flush_count:                    %u\n", profile_p->SMBflush_count);
    163         d_printf("flush_time:                     %u\n", profile_p->SMBflush_time);
    164         d_printf("unlink_count:                   %u\n", profile_p->SMBunlink_count);
    165         d_printf("unlink_time:                    %u\n", profile_p->SMBunlink_time);
    166         d_printf("mv_count:                       %u\n", profile_p->SMBmv_count);
    167         d_printf("mv_time:                        %u\n", profile_p->SMBmv_time);
    168         d_printf("getatr_count:                   %u\n", profile_p->SMBgetatr_count);
    169         d_printf("getatr_time:                    %u\n", profile_p->SMBgetatr_time);
    170         d_printf("setatr_count:                   %u\n", profile_p->SMBsetatr_count);
    171         d_printf("setatr_time:                    %u\n", profile_p->SMBsetatr_time);
    172         d_printf("read_count:                     %u\n", profile_p->SMBread_count);
    173         d_printf("read_time:                      %u\n", profile_p->SMBread_time);
    174         d_printf("write_count:                    %u\n", profile_p->SMBwrite_count);
    175         d_printf("write_time:                     %u\n", profile_p->SMBwrite_time);
    176         d_printf("lock_count:                     %u\n", profile_p->SMBlock_count);
    177         d_printf("lock_time:                      %u\n", profile_p->SMBlock_time);
    178         d_printf("unlock_count:                   %u\n", profile_p->SMBunlock_count);
    179         d_printf("unlock_time:                    %u\n", profile_p->SMBunlock_time);
    180         d_printf("ctemp_count:                    %u\n", profile_p->SMBctemp_count);
    181         d_printf("ctemp_time:                     %u\n", profile_p->SMBctemp_time);
    182         d_printf("mknew_count:                    %u\n", profile_p->SMBmknew_count);
    183         d_printf("mknew_time:                     %u\n", profile_p->SMBmknew_time);
    184         d_printf("checkpath_count:                %u\n", profile_p->SMBcheckpath_count);
    185         d_printf("checkpath_time:                 %u\n", profile_p->SMBcheckpath_time);
    186         d_printf("exit_count:                     %u\n", profile_p->SMBexit_count);
    187         d_printf("exit_time:                      %u\n", profile_p->SMBexit_time);
    188         d_printf("lseek_count:                    %u\n", profile_p->SMBlseek_count);
    189         d_printf("lseek_time:                     %u\n", profile_p->SMBlseek_time);
    190         d_printf("lockread_count:                 %u\n", profile_p->SMBlockread_count);
    191         d_printf("lockread_time:                  %u\n", profile_p->SMBlockread_time);
    192         d_printf("writeunlock_count:              %u\n", profile_p->SMBwriteunlock_count);
    193         d_printf("writeunlock_time:               %u\n", profile_p->SMBwriteunlock_time);
    194         d_printf("readbraw_count:                 %u\n", profile_p->SMBreadbraw_count);
    195         d_printf("readbraw_time:                  %u\n", profile_p->SMBreadbraw_time);
    196         d_printf("readBmpx_count:                 %u\n", profile_p->SMBreadBmpx_count);
    197         d_printf("readBmpx_time:                  %u\n", profile_p->SMBreadBmpx_time);
    198         d_printf("readBs_count:                   %u\n", profile_p->SMBreadBs_count);
    199         d_printf("readBs_time:                    %u\n", profile_p->SMBreadBs_time);
    200         d_printf("writebraw_count:                %u\n", profile_p->SMBwritebraw_count);
    201         d_printf("writebraw_time:                 %u\n", profile_p->SMBwritebraw_time);
    202         d_printf("writeBmpx_count:                %u\n", profile_p->SMBwriteBmpx_count);
    203         d_printf("writeBmpx_time:                 %u\n", profile_p->SMBwriteBmpx_time);
    204         d_printf("writeBs_count:                  %u\n", profile_p->SMBwriteBs_count);
    205         d_printf("writeBs_time:                   %u\n", profile_p->SMBwriteBs_time);
    206         d_printf("writec_count:                   %u\n", profile_p->SMBwritec_count);
    207         d_printf("writec_time:                    %u\n", profile_p->SMBwritec_time);
    208         d_printf("setattrE_count:                 %u\n", profile_p->SMBsetattrE_count);
    209         d_printf("setattrE_time:                  %u\n", profile_p->SMBsetattrE_time);
    210         d_printf("getattrE_count:                 %u\n", profile_p->SMBgetattrE_count);
    211         d_printf("getattrE_time:                  %u\n", profile_p->SMBgetattrE_time);
    212         d_printf("lockingX_count:                 %u\n", profile_p->SMBlockingX_count);
    213         d_printf("lockingX_time:                  %u\n", profile_p->SMBlockingX_time);
    214         d_printf("trans_count:                    %u\n", profile_p->SMBtrans_count);
    215         d_printf("trans_time:                     %u\n", profile_p->SMBtrans_time);
    216         d_printf("transs_count:                   %u\n", profile_p->SMBtranss_count);
    217         d_printf("transs_time:                    %u\n", profile_p->SMBtranss_time);
    218         d_printf("ioctl_count:                    %u\n", profile_p->SMBioctl_count);
    219         d_printf("ioctl_time:                     %u\n", profile_p->SMBioctl_time);
    220         d_printf("ioctls_count:                   %u\n", profile_p->SMBioctls_count);
    221         d_printf("ioctls_time:                    %u\n", profile_p->SMBioctls_time);
    222         d_printf("copy_count:                     %u\n", profile_p->SMBcopy_count);
    223         d_printf("copy_time:                      %u\n", profile_p->SMBcopy_time);
    224         d_printf("move_count:                     %u\n", profile_p->SMBmove_count);
    225         d_printf("move_time:                      %u\n", profile_p->SMBmove_time);
    226         d_printf("echo_count:                     %u\n", profile_p->SMBecho_count);
    227         d_printf("echo_time:                      %u\n", profile_p->SMBecho_time);
    228         d_printf("writeclose_count:               %u\n", profile_p->SMBwriteclose_count);
    229         d_printf("writeclose_time:                %u\n", profile_p->SMBwriteclose_time);
    230         d_printf("openX_count:                    %u\n", profile_p->SMBopenX_count);
    231         d_printf("openX_time:                     %u\n", profile_p->SMBopenX_time);
    232         d_printf("readX_count:                    %u\n", profile_p->SMBreadX_count);
    233         d_printf("readX_time:                     %u\n", profile_p->SMBreadX_time);
    234         d_printf("writeX_count:                   %u\n", profile_p->SMBwriteX_count);
    235         d_printf("writeX_time:                    %u\n", profile_p->SMBwriteX_time);
    236         d_printf("trans2_count:                   %u\n", profile_p->SMBtrans2_count);
    237         d_printf("trans2_time:                    %u\n", profile_p->SMBtrans2_time);
    238         d_printf("transs2_count:                  %u\n", profile_p->SMBtranss2_count);
    239         d_printf("transs2_time:                   %u\n", profile_p->SMBtranss2_time);
    240         d_printf("findclose_count:                %u\n", profile_p->SMBfindclose_count);
    241         d_printf("findclose_time:                 %u\n", profile_p->SMBfindclose_time);
    242         d_printf("findnclose_count:               %u\n", profile_p->SMBfindnclose_count);
    243         d_printf("findnclose_time:                %u\n", profile_p->SMBfindnclose_time);
    244         d_printf("tcon_count:                     %u\n", profile_p->SMBtcon_count);
    245         d_printf("tcon_time:                      %u\n", profile_p->SMBtcon_time);
    246         d_printf("tdis_count:                     %u\n", profile_p->SMBtdis_count);
    247         d_printf("tdis_time:                      %u\n", profile_p->SMBtdis_time);
    248         d_printf("negprot_count:                  %u\n", profile_p->SMBnegprot_count);
    249         d_printf("negprot_time:                   %u\n", profile_p->SMBnegprot_time);
    250         d_printf("sesssetupX_count:               %u\n", profile_p->SMBsesssetupX_count);
    251         d_printf("sesssetupX_time:                %u\n", profile_p->SMBsesssetupX_time);
    252         d_printf("ulogoffX_count:                 %u\n", profile_p->SMBulogoffX_count);
    253         d_printf("ulogoffX_time:                  %u\n", profile_p->SMBulogoffX_time);
    254         d_printf("tconX_count:                    %u\n", profile_p->SMBtconX_count);
    255         d_printf("tconX_time:                     %u\n", profile_p->SMBtconX_time);
    256         d_printf("dskattr_count:                  %u\n", profile_p->SMBdskattr_count);
    257         d_printf("dskattr_time:                   %u\n", profile_p->SMBdskattr_time);
    258         d_printf("search_count:                   %u\n", profile_p->SMBsearch_count);
    259         d_printf("search_time:                    %u\n", profile_p->SMBsearch_time);
    260         d_printf("ffirst_count:                   %u\n", profile_p->SMBffirst_count);
    261         d_printf("ffirst_time:                    %u\n", profile_p->SMBffirst_time);
    262         d_printf("funique_count:                  %u\n", profile_p->SMBfunique_count);
    263         d_printf("funique_time:                   %u\n", profile_p->SMBfunique_time);
    264         d_printf("fclose_count:                   %u\n", profile_p->SMBfclose_count);
    265         d_printf("fclose_time:                    %u\n", profile_p->SMBfclose_time);
    266         d_printf("nttrans_count:                  %u\n", profile_p->SMBnttrans_count);
    267         d_printf("nttrans_time:                   %u\n", profile_p->SMBnttrans_time);
    268         d_printf("nttranss_count:                 %u\n", profile_p->SMBnttranss_count);
    269         d_printf("nttranss_time:                  %u\n", profile_p->SMBnttranss_time);
    270         d_printf("ntcreateX_count:                %u\n", profile_p->SMBntcreateX_count);
    271         d_printf("ntcreateX_time:                 %u\n", profile_p->SMBntcreateX_time);
    272         d_printf("ntcancel_count:                 %u\n", profile_p->SMBntcancel_count);
    273         d_printf("ntcancel_time:                  %u\n", profile_p->SMBntcancel_time);
    274         d_printf("splopen_count:                  %u\n", profile_p->SMBsplopen_count);
    275         d_printf("splopen_time:                   %u\n", profile_p->SMBsplopen_time);
    276         d_printf("splwr_count:                    %u\n", profile_p->SMBsplwr_count);
    277         d_printf("splwr_time:                     %u\n", profile_p->SMBsplwr_time);
    278         d_printf("splclose_count:                 %u\n", profile_p->SMBsplclose_count);
    279         d_printf("splclose_time:                  %u\n", profile_p->SMBsplclose_time);
    280         d_printf("splretq_count:                  %u\n", profile_p->SMBsplretq_count);
    281         d_printf("splretq_time:                   %u\n", profile_p->SMBsplretq_time);
    282         d_printf("sends_count:                    %u\n", profile_p->SMBsends_count);
    283         d_printf("sends_time:                     %u\n", profile_p->SMBsends_time);
    284         d_printf("sendb_count:                    %u\n", profile_p->SMBsendb_count);
    285         d_printf("sendb_time:                     %u\n", profile_p->SMBsendb_time);
    286         d_printf("fwdname_count:                  %u\n", profile_p->SMBfwdname_count);
    287         d_printf("fwdname_time:                   %u\n", profile_p->SMBfwdname_time);
    288         d_printf("cancelf_count:                  %u\n", profile_p->SMBcancelf_count);
    289         d_printf("cancelf_time:                   %u\n", profile_p->SMBcancelf_time);
    290         d_printf("getmac_count:                   %u\n", profile_p->SMBgetmac_count);
    291         d_printf("getmac_time:                    %u\n", profile_p->SMBgetmac_time);
    292         d_printf("sendstrt_count:                 %u\n", profile_p->SMBsendstrt_count);
    293         d_printf("sendstrt_time:                  %u\n", profile_p->SMBsendstrt_time);
    294         d_printf("sendend_count:                  %u\n", profile_p->SMBsendend_count);
    295         d_printf("sendend_time:                   %u\n", profile_p->SMBsendend_time);
    296         d_printf("sendtxt_count:                  %u\n", profile_p->SMBsendtxt_count);
    297         d_printf("sendtxt_time:                   %u\n", profile_p->SMBsendtxt_time);
    298         d_printf("invalid_count:                  %u\n", profile_p->SMBinvalid_count);
    299         d_printf("invalid_time:                   %u\n", profile_p->SMBinvalid_time);
    300 
    301         profile_separator("Pathworks Calls");
    302         d_printf("setdir_count:                   %u\n", profile_p->pathworks_setdir_count);
    303         d_printf("setdir_time:                    %u\n", profile_p->pathworks_setdir_time);
    304 
    305         profile_separator("Trans2 Calls");
    306         d_printf("open_count:                     %u\n", profile_p->Trans2_open_count);
    307         d_printf("open_time:                      %u\n", profile_p->Trans2_open_time);
    308         d_printf("findfirst_count:                %u\n", profile_p->Trans2_findfirst_count);
    309         d_printf("findfirst_time:                 %u\n", profile_p->Trans2_findfirst_time);
    310         d_printf("findnext_count:                 %u\n", profile_p->Trans2_findnext_count);
    311         d_printf("findnext_time:                  %u\n", profile_p->Trans2_findnext_time);
    312         d_printf("qfsinfo_count:                  %u\n", profile_p->Trans2_qfsinfo_count);
    313         d_printf("qfsinfo_time:                   %u\n", profile_p->Trans2_qfsinfo_time);
    314         d_printf("setfsinfo_count:                %u\n", profile_p->Trans2_setfsinfo_count);
    315         d_printf("setfsinfo_time:                 %u\n", profile_p->Trans2_setfsinfo_time);
    316         d_printf("qpathinfo_count:                %u\n", profile_p->Trans2_qpathinfo_count);
    317         d_printf("qpathinfo_time:                 %u\n", profile_p->Trans2_qpathinfo_time);
    318         d_printf("setpathinfo_count:              %u\n", profile_p->Trans2_setpathinfo_count);
    319         d_printf("setpathinfo_time:               %u\n", profile_p->Trans2_setpathinfo_time);
    320         d_printf("qfileinfo_count:                %u\n", profile_p->Trans2_qfileinfo_count);
    321         d_printf("qfileinfo_time:                 %u\n", profile_p->Trans2_qfileinfo_time);
    322         d_printf("setfileinfo_count:              %u\n", profile_p->Trans2_setfileinfo_count);
    323         d_printf("setfileinfo_time:               %u\n", profile_p->Trans2_setfileinfo_time);
    324         d_printf("fsctl_count:                    %u\n", profile_p->Trans2_fsctl_count);
    325         d_printf("fsctl_time:                     %u\n", profile_p->Trans2_fsctl_time);
    326         d_printf("ioctl_count:                    %u\n", profile_p->Trans2_ioctl_count);
    327         d_printf("ioctl_time:                     %u\n", profile_p->Trans2_ioctl_time);
    328         d_printf("findnotifyfirst_count:          %u\n", profile_p->Trans2_findnotifyfirst_count);
    329         d_printf("findnotifyfirst_time:           %u\n", profile_p->Trans2_findnotifyfirst_time);
    330         d_printf("findnotifynext_count:           %u\n", profile_p->Trans2_findnotifynext_count);
    331         d_printf("findnotifynext_time:            %u\n", profile_p->Trans2_findnotifynext_time);
    332         d_printf("mkdir_count:                    %u\n", profile_p->Trans2_mkdir_count);
    333         d_printf("mkdir_time:                     %u\n", profile_p->Trans2_mkdir_time);
    334         d_printf("session_setup_count:            %u\n", profile_p->Trans2_session_setup_count);
    335         d_printf("session_setup_time:             %u\n", profile_p->Trans2_session_setup_time);
    336         d_printf("get_dfs_referral_count:         %u\n", profile_p->Trans2_get_dfs_referral_count);
    337         d_printf("get_dfs_referral_time:          %u\n", profile_p->Trans2_get_dfs_referral_time);
    338         d_printf("report_dfs_inconsistancy_count: %u\n", profile_p->Trans2_report_dfs_inconsistancy_count);
    339         d_printf("report_dfs_inconsistancy_time:  %u\n", profile_p->Trans2_report_dfs_inconsistancy_time);
    340 
    341         profile_separator("NT Transact Calls");
    342         d_printf("create_count:                   %u\n", profile_p->NT_transact_create_count);
    343         d_printf("create_time:                    %u\n", profile_p->NT_transact_create_time);
    344         d_printf("ioctl_count:                    %u\n", profile_p->NT_transact_ioctl_count);
    345         d_printf("ioctl_time:                     %u\n", profile_p->NT_transact_ioctl_time);
    346         d_printf("set_security_desc_count:        %u\n", profile_p->NT_transact_set_security_desc_count);
    347         d_printf("set_security_desc_time:         %u\n", profile_p->NT_transact_set_security_desc_time);
    348         d_printf("notify_change_count:            %u\n", profile_p->NT_transact_notify_change_count);
    349         d_printf("notify_change_time:             %u\n", profile_p->NT_transact_notify_change_time);
    350         d_printf("rename_count:                   %u\n", profile_p->NT_transact_rename_count);
    351         d_printf("rename_time:                    %u\n", profile_p->NT_transact_rename_time);
    352         d_printf("query_security_desc_count:      %u\n", profile_p->NT_transact_query_security_desc_count);
    353         d_printf("query_security_desc_time:       %u\n", profile_p->NT_transact_query_security_desc_time);
    354 
    355         profile_separator("ACL Calls");
    356         d_printf("get_nt_acl_count:               %u\n", profile_p->get_nt_acl_count);
    357         d_printf("get_nt_acl_time:                %u\n", profile_p->get_nt_acl_time);
    358         d_printf("fget_nt_acl_count:              %u\n", profile_p->fget_nt_acl_count);
    359         d_printf("fget_nt_acl_time:               %u\n", profile_p->fget_nt_acl_time);
    360         d_printf("fset_nt_acl_count:              %u\n", profile_p->fset_nt_acl_count);
    361         d_printf("fset_nt_acl_time:               %u\n", profile_p->fset_nt_acl_time);
    362         d_printf("chmod_acl_count:                %u\n", profile_p->chmod_acl_count);
    363         d_printf("chmod_acl_time:                 %u\n", profile_p->chmod_acl_time);
    364         d_printf("fchmod_acl_count:               %u\n", profile_p->fchmod_acl_count);
    365         d_printf("fchmod_acl_time:                %u\n", profile_p->fchmod_acl_time);
    366 
    367         profile_separator("NMBD Calls");
    368         d_printf("name_release_count:             %u\n", profile_p->name_release_count);
    369         d_printf("name_release_time:              %u\n", profile_p->name_release_time);
    370         d_printf("name_refresh_count:             %u\n", profile_p->name_refresh_count);
    371         d_printf("name_refresh_time:              %u\n", profile_p->name_refresh_time);
    372         d_printf("name_registration_count:        %u\n", profile_p->name_registration_count);
    373         d_printf("name_registration_time:         %u\n", profile_p->name_registration_time);
    374         d_printf("node_status_count:              %u\n", profile_p->node_status_count);
    375         d_printf("node_status_time:               %u\n", profile_p->node_status_time);
    376         d_printf("name_query_count:               %u\n", profile_p->name_query_count);
    377         d_printf("name_query_time:                %u\n", profile_p->name_query_time);
    378         d_printf("host_announce_count:            %u\n", profile_p->host_announce_count);
    379         d_printf("host_announce_time:             %u\n", profile_p->host_announce_time);
    380         d_printf("workgroup_announce_count:       %u\n", profile_p->workgroup_announce_count);
    381         d_printf("workgroup_announce_time:        %u\n", profile_p->workgroup_announce_time);
    382         d_printf("local_master_announce_count:    %u\n", profile_p->local_master_announce_count);
    383         d_printf("local_master_announce_time:     %u\n", profile_p->local_master_announce_time);
    384         d_printf("master_browser_announce_count:  %u\n", profile_p->master_browser_announce_count);
    385         d_printf("master_browser_announce_time:   %u\n", profile_p->master_browser_announce_time);
    386         d_printf("lm_host_announce_count:         %u\n", profile_p->lm_host_announce_count);
    387         d_printf("lm_host_announce_time:          %u\n", profile_p->lm_host_announce_time);
    388         d_printf("get_backup_list_count:          %u\n", profile_p->get_backup_list_count);
    389         d_printf("get_backup_list_time:           %u\n", profile_p->get_backup_list_time);
    390         d_printf("reset_browser_count:            %u\n", profile_p->reset_browser_count);
    391         d_printf("reset_browser_time:             %u\n", profile_p->reset_browser_time);
    392         d_printf("announce_request_count:         %u\n", profile_p->announce_request_count);
    393         d_printf("announce_request_time:          %u\n", profile_p->announce_request_time);
    394         d_printf("lm_announce_request_count:      %u\n", profile_p->lm_announce_request_count);
    395         d_printf("lm_announce_request_time:       %u\n", profile_p->lm_announce_request_time);
    396         d_printf("domain_logon_count:             %u\n", profile_p->domain_logon_count);
    397         d_printf("domain_logon_time:              %u\n", profile_p->domain_logon_time);
    398         d_printf("sync_browse_lists_count:        %u\n", profile_p->sync_browse_lists_count);
    399         d_printf("sync_browse_lists_time:         %u\n", profile_p->sync_browse_lists_time);
    400         d_printf("run_elections_count:            %u\n", profile_p->run_elections_count);
    401         d_printf("run_elections_time:             %u\n", profile_p->run_elections_time);
    402         d_printf("election_count:                 %u\n", profile_p->election_count);
    403         d_printf("election_time:                  %u\n", profile_p->election_time);
    404         profile_separator("SMB2 Calls");
    405         d_printf("smb2_negprot_count:             %u\n", profile_p->smb2_negprot_count);
    406         d_printf("smb2_negprot_time:              %u\n", profile_p->smb2_negprot_time);
    407         d_printf("smb2_sesssetup_count:           %u\n", profile_p->smb2_sesssetup_count);
    408         d_printf("smb2_sesssetup_time:            %u\n", profile_p->smb2_sesssetup_time);
    409         d_printf("smb2_logoff_count:              %u\n", profile_p->smb2_logoff_count);
    410         d_printf("smb2_logoff_time:               %u\n", profile_p->smb2_logoff_time);
    411         d_printf("smb2_tcon_count:                %u\n", profile_p->smb2_tcon_count);
    412         d_printf("smb2_tcon_time:                 %u\n", profile_p->smb2_tcon_time);
    413         d_printf("smb2_tdis_count:                %u\n", profile_p->smb2_tdis_count);
    414         d_printf("smb2_tdis_time:                 %u\n", profile_p->smb2_tdis_time);
    415         d_printf("smb2_create_count:              %u\n", profile_p->smb2_create_count);
    416         d_printf("smb2_create_time:               %u\n", profile_p->smb2_create_time);
    417         d_printf("smb2_close_count:               %u\n", profile_p->smb2_close_count);
    418         d_printf("smb2_close_time:                %u\n", profile_p->smb2_close_time);
    419         d_printf("smb2_flush_count:               %u\n", profile_p->smb2_flush_count);
    420         d_printf("smb2_flush_time:                %u\n", profile_p->smb2_flush_time);
    421         d_printf("smb2_read_count:                %u\n", profile_p->smb2_read_count);
    422         d_printf("smb2_read_time:                 %u\n", profile_p->smb2_read_time);
    423         d_printf("smb2_write_count:               %u\n", profile_p->smb2_write_count);
    424         d_printf("smb2_write_time:                %u\n", profile_p->smb2_write_time);
    425         d_printf("smb2_lock_count:                %u\n", profile_p->smb2_lock_count);
    426         d_printf("smb2_lock_time:                 %u\n", profile_p->smb2_lock_time);
    427         d_printf("smb2_ioctl_count:               %u\n", profile_p->smb2_ioctl_count);
    428         d_printf("smb2_ioctl_time:                %u\n", profile_p->smb2_ioctl_time);
    429         d_printf("smb2_cancel_count:              %u\n", profile_p->smb2_cancel_count);
    430         d_printf("smb2_cancel_time:               %u\n", profile_p->smb2_cancel_time);
    431         d_printf("smb2_keepalive_count:           %u\n", profile_p->smb2_keepalive_count);
    432         d_printf("smb2_keepalive_time:            %u\n", profile_p->smb2_keepalive_time);
    433         d_printf("smb2_find_count:                %u\n", profile_p->smb2_find_count);
    434         d_printf("smb2_find_time:                 %u\n", profile_p->smb2_find_time);
    435         d_printf("smb2_notify_count:              %u\n", profile_p->smb2_notify_count);
    436         d_printf("smb2_notify_time:               %u\n", profile_p->smb2_notify_time);
    437         d_printf("smb2_getinfo_count:             %u\n", profile_p->smb2_getinfo_count);
    438         d_printf("smb2_getinfo_time:              %u\n", profile_p->smb2_getinfo_time);
    439         d_printf("smb2_setinfo_count:             %u\n", profile_p->smb2_setinfo_count);
    440         d_printf("smb2_setinfo_time:              %u\n", profile_p->smb2_setinfo_time);
    441         d_printf("smb2_break_count:               %u\n", profile_p->smb2_break_count);
    442         d_printf("smb2_break_time:                %u\n", profile_p->smb2_break_time);
    443 
    444 #else /* WITH_PROFILE */
    445 
    446         fprintf(stderr, "Profile data unavailable\n");
    447 #endif /* WITH_PROFILE */
     52        smbprofile_collect(&stats);
     53
     54#define __PRINT_FIELD_LINE(name, _stats, field) do { \
     55        d_printf("%-59s%20ju\n", \
     56                 name "_" #field ":", \
     57                 (uintmax_t)stats.values._stats.field); \
     58} while(0);
     59#define SMBPROFILE_STATS_START
     60#define SMBPROFILE_STATS_SECTION_START(name, display) profile_separator(#display);
     61#define SMBPROFILE_STATS_COUNT(name) do { \
     62        __PRINT_FIELD_LINE(#name, name##_stats,  count); \
     63} while(0);
     64#define SMBPROFILE_STATS_TIME(name) do { \
     65        __PRINT_FIELD_LINE(#name, name##_stats,  time); \
     66} while(0);
     67#define SMBPROFILE_STATS_BASIC(name) do { \
     68        __PRINT_FIELD_LINE(#name, name##_stats,  count); \
     69        __PRINT_FIELD_LINE(#name, name##_stats,  time); \
     70} while(0);
     71#define SMBPROFILE_STATS_BYTES(name) do { \
     72        __PRINT_FIELD_LINE(#name, name##_stats,  count); \
     73        __PRINT_FIELD_LINE(#name, name##_stats,  time); \
     74        __PRINT_FIELD_LINE(#name, name##_stats,  idle); \
     75        __PRINT_FIELD_LINE(#name, name##_stats,  bytes); \
     76} while(0);
     77#define SMBPROFILE_STATS_IOBYTES(name) do { \
     78        __PRINT_FIELD_LINE(#name, name##_stats,  count); \
     79        __PRINT_FIELD_LINE(#name, name##_stats,  time); \
     80        __PRINT_FIELD_LINE(#name, name##_stats,  idle); \
     81        __PRINT_FIELD_LINE(#name, name##_stats,  inbytes); \
     82        __PRINT_FIELD_LINE(#name, name##_stats,  outbytes); \
     83} while(0);
     84#define SMBPROFILE_STATS_SECTION_END
     85#define SMBPROFILE_STATS_END
     86        SMBPROFILE_STATS_ALL_SECTIONS
     87#undef __PRINT_FIELD_LINE
     88#undef SMBPROFILE_STATS_START
     89#undef SMBPROFILE_STATS_SECTION_START
     90#undef SMBPROFILE_STATS_COUNT
     91#undef SMBPROFILE_STATS_TIME
     92#undef SMBPROFILE_STATS_BASIC
     93#undef SMBPROFILE_STATS_BYTES
     94#undef SMBPROFILE_STATS_IOBYTES
     95#undef SMBPROFILE_STATS_SECTION_END
     96#undef SMBPROFILE_STATS_END
    44897
    44998        return True;
    45099}
    451 
    452 #ifdef WITH_PROFILE
    453100
    454101/* Convert microseconds to milliseconds. */
     
    463110#define percent_time(used, period) ((double)(used) / (double)(period) * 100.0 )
    464111
    465 static int print_count_samples(
     112static uint64_t print_count_count_samples(
     113        char *buf, const size_t buflen,
     114        const char *name,
     115        const struct smbprofile_stats_count * const current,
     116        const struct smbprofile_stats_count * const last,
     117        uint64_t delta_usec)
     118{
     119        uint64_t step = current->count - last->count;
     120        uint64_t count = 0;
     121
     122        if (step != 0) {
     123                uint64_t delta_sec = usec_to_sec(delta_usec);
     124
     125                count++;
     126
     127                if (buf[0] == '\0') {
     128                        snprintf(buf, buflen,
     129                                "%s %ju/sec",
     130                                name, (uintmax_t)(step / delta_sec));
     131                } else {
     132                        printf("%-40s %s %ju/sec\n",
     133                                buf, name, (uintmax_t)(step / delta_sec));
     134                        buf[0] = '\0';
     135                }
     136        }
     137
     138        return count;
     139}
     140
     141static uint64_t print_basic_count_samples(
     142        char *buf, const size_t buflen,
     143        const char *name,
     144        const struct smbprofile_stats_basic * const current,
     145        const struct smbprofile_stats_basic * const last,
     146        uint64_t delta_usec)
     147{
     148        uint64_t step = current->count - last->count;
     149        uint64_t spent = current->time - last->time;
     150        uint64_t count = 0;
     151
     152        if (step != 0) {
     153                uint64_t delta_sec = usec_to_sec(delta_usec);
     154
     155                count++;
     156
     157                if (buf[0] == '\0') {
     158                        snprintf(buf, buflen,
     159                                "%s %ju/sec (%.2f%%)",
     160                                name, (uintmax_t)(step / delta_sec),
     161                                percent_time(spent, delta_usec));
     162                } else {
     163                        printf("%-40s %s %ju/sec (%.2f%%)\n",
     164                                buf, name, (uintmax_t)(step / delta_sec),
     165                                percent_time(spent, delta_usec));
     166                        buf[0] = '\0';
     167                }
     168        }
     169
     170        return count;
     171}
     172
     173static uint64_t print_bytes_count_samples(
     174        char *buf, const size_t buflen,
     175        const char *name,
     176        const struct smbprofile_stats_bytes * const current,
     177        const struct smbprofile_stats_bytes * const last,
     178        uint64_t delta_usec)
     179{
     180        uint64_t step = current->count - last->count;
     181        uint64_t spent = current->time - last->time;
     182        uint64_t count = 0;
     183
     184        if (step != 0) {
     185                uint64_t delta_sec = usec_to_sec(delta_usec);
     186
     187                count++;
     188
     189                if (buf[0] == '\0') {
     190                        snprintf(buf, buflen,
     191                                "%s %ju/sec (%.2f%%)",
     192                                name, (uintmax_t)(step / delta_sec),
     193                                percent_time(spent, delta_usec));
     194                } else {
     195                        printf("%-40s %s %ju/sec (%.2f%%)\n",
     196                                buf, name, (uintmax_t)(step / delta_sec),
     197                                percent_time(spent, delta_usec));
     198                        buf[0] = '\0';
     199                }
     200        }
     201
     202        return count;
     203}
     204
     205static uint64_t print_iobytes_count_samples(
     206        char *buf, const size_t buflen,
     207        const char *name,
     208        const struct smbprofile_stats_iobytes * const current,
     209        const struct smbprofile_stats_iobytes * const last,
     210        uint64_t delta_usec)
     211{
     212        uint64_t step = current->count - last->count;
     213        uint64_t spent = current->time - last->time;
     214        uint64_t count = 0;
     215
     216        if (step != 0) {
     217                uint64_t delta_sec = usec_to_sec(delta_usec);
     218
     219                count++;
     220
     221                if (buf[0] == '\0') {
     222                        snprintf(buf, buflen,
     223                                "%s %ju/sec (%.2f%%)",
     224                                name, (uintmax_t)(step / delta_sec),
     225                                percent_time(spent, delta_usec));
     226                } else {
     227                        printf("%-40s %s %ju/sec (%.2f%%)\n",
     228                                buf, name, (uintmax_t)(step / delta_sec),
     229                                percent_time(spent, delta_usec));
     230                        buf[0] = '\0';
     231                }
     232        }
     233
     234        return count;
     235}
     236
     237static uint64_t print_count_samples(
    466238        const struct profile_stats * const current,
    467239        const struct profile_stats * const last,
    468240        uint64_t delta_usec)
    469241{
    470         int i;
    471         int count = 0;
    472         unsigned step;
    473         uint64_t spent;
    474         int delta_sec;
    475         const char * name;
    476         char buf[40];
     242        uint64_t count = 0;
     243        char buf[40] = { '\0', };
    477244
    478245        if (delta_usec == 0) {
     
    480247        }
    481248
    482         buf[0] = '\0';
    483         delta_sec = usec_to_sec(delta_usec);
    484 
    485         for (i = 0; i < PR_VALUE_MAX; ++i) {
    486                 step = current->count[i] - last->count[i];
    487                 spent = current->time[i] - last->time[i];
    488 
    489                 if (step) {
    490                         ++count;
    491 
    492                         name = profile_value_name(i);
    493 
    494                         if (buf[0] == '\0') {
    495                                 snprintf(buf, sizeof(buf),
    496                                         "%s %d/sec (%.2f%%)",
    497                                         name, step / delta_sec,
    498                                         percent_time(spent, delta_usec));
    499                         } else {
    500                                 printf("%-40s %s %d/sec (%.2f%%)\n",
    501                                         buf, name, step / delta_sec,
    502                                         percent_time(spent, delta_usec));
    503                                 buf[0] = '\0';
    504                         }
    505                 }
     249#define SMBPROFILE_STATS_START
     250#define SMBPROFILE_STATS_SECTION_START(name, display)
     251#define SMBPROFILE_STATS_COUNT(name) do { \
     252        count += print_count_count_samples(buf, sizeof(buf), \
     253                                           #name, \
     254                                           &current->values.name##_stats, \
     255                                           &last->values.name##_stats, \
     256                                           delta_usec); \
     257} while(0);
     258#define SMBPROFILE_STATS_TIME(name) do { \
     259} while(0);
     260#define SMBPROFILE_STATS_BASIC(name) do { \
     261        count += print_basic_count_samples(buf, sizeof(buf), \
     262                                           #name, \
     263                                           &current->values.name##_stats, \
     264                                           &last->values.name##_stats, \
     265                                           delta_usec); \
     266} while(0);
     267#define SMBPROFILE_STATS_BYTES(name) do { \
     268        count += print_bytes_count_samples(buf, sizeof(buf), \
     269                                           #name, \
     270                                           &current->values.name##_stats, \
     271                                           &last->values.name##_stats, \
     272                                           delta_usec); \
     273} while(0);
     274#define SMBPROFILE_STATS_IOBYTES(name) do { \
     275        count += print_iobytes_count_samples(buf, sizeof(buf), \
     276                                             #name, \
     277                                             &current->values.name##_stats, \
     278                                             &last->values.name##_stats, \
     279                                             delta_usec); \
     280} while(0);
     281#define SMBPROFILE_STATS_SECTION_END
     282#define SMBPROFILE_STATS_END
     283        SMBPROFILE_STATS_ALL_SECTIONS
     284#undef SMBPROFILE_STATS_START
     285#undef SMBPROFILE_STATS_SECTION_START
     286#undef SMBPROFILE_STATS_COUNT
     287#undef SMBPROFILE_STATS_TIME
     288#undef SMBPROFILE_STATS_BASIC
     289#undef SMBPROFILE_STATS_BYTES
     290#undef SMBPROFILE_STATS_IOBYTES
     291#undef SMBPROFILE_STATS_SECTION_END
     292#undef SMBPROFILE_STATS_END
     293
     294        if (buf[0] != '\0') {
     295                printf("%-40s\n", buf);
     296                buf[0] = '\0';
    506297        }
    507298
     
    532323        }
    533324
    534         memcpy(&sample_data[last], profile_p, sizeof(*profile_p));
     325        smbprofile_collect(&sample_data[last]);
    535326        for (;;) {
    536327                sample_time[current] = profile_timestamp();
     
    538329
    539330                /* Take a sample. */
    540                 memcpy(&sample_data[current], profile_p, sizeof(*profile_p));
     331                smbprofile_collect(&sample_data[current]);
    541332
    542333                /* Rate convert some values and print results. */
     
    564355                        }
    565356
    566                         sys_usleep(remain_usec);
     357                        usleep(remain_usec);
    567358                }
    568359
     
    571362        return True;
    572363}
    573 
    574 #else /* WITH_PROFILE */
    575 
    576 bool status_profile_rates(bool verbose)
    577 {
    578         fprintf(stderr, "Profile data unavailable\n");
    579         return False;
    580 }
    581 
    582 #endif /* WITH_PROFILE */
    583 
  • vendor/current/source3/utils/testparm.c

    r740 r988  
    3535#include "system/filesys.h"
    3636#include "popt_common.h"
     37#include "lib/param/loadparm.h"
    3738
    3839/*******************************************************************
     
    4041********************************************************************/
    4142
    42 static bool directory_exist_stat(char *dname,SMB_STRUCT_STAT *st)
     43static bool directory_exist_stat(const char *dname,SMB_STRUCT_STAT *st)
    4344{
    4445        SMB_STRUCT_STAT st2;
     
    6667        int ret = 0;
    6768        SMB_STRUCT_STAT st;
    68 
    69         if (lp_security() >= SEC_DOMAIN && !lp_encrypted_passwords()) {
    70                 fprintf(stderr, "ERROR: in 'security=domain' mode the 'encrypt passwords' parameter must always be set to 'true'.\n");
    71                 ret = 1;
    72         }
    73 
    74         if (lp_wins_support() && lp_wins_server_list()) {
    75                 fprintf(stderr, "ERROR: both 'wins support = true' and 'wins server = <server list>' \
    76 cannot be set in the smb.conf file. nmbd will abort with this setting.\n");
    77                 ret = 1;
    78         }
    79 
    80         if (strequal(lp_workgroup(), global_myname())) {
    81                 fprintf(stderr, "WARNING: 'workgroup' and 'netbios name' " \
    82                         "must differ.\n");
    83                 ret = 1;
    84         }
    85 
    86         if (!directory_exist_stat(lp_lockdir(), &st)) {
    87                 fprintf(stderr, "ERROR: lock directory %s does not exist\n",
    88                        lp_lockdir());
     69        const char *socket_options;
     70
     71        if (lp_security() >= SEC_DOMAIN && !lp_encrypt_passwords()) {
     72                fprintf(stderr, "ERROR: in 'security=domain' mode the "
     73                                "'encrypt passwords' parameter must always be "
     74                                "set to 'true'.\n\n");
     75                ret = 1;
     76        }
     77
     78        if (lp_we_are_a_wins_server() && lp_wins_server_list()) {
     79                fprintf(stderr, "ERROR: both 'wins support = true' and "
     80                                "'wins server = <server list>' cannot be set in "
     81                                "the smb.conf file. nmbd will abort with this "
     82                                "setting.\n\n");
     83                ret = 1;
     84        }
     85
     86        if (strequal(lp_workgroup(), lp_netbios_name())) {
     87                fprintf(stderr, "WARNING: 'workgroup' and 'netbios name' "
     88                                "must differ.\n\n");
     89        }
     90
     91        if (strlen(lp_netbios_name()) > 15) {
     92                fprintf(stderr, "WARNING: The 'netbios name' is too long "
     93                                "(max. 15 chars).\n\n");
     94        }
     95
     96        if (!directory_exist_stat(lp_lock_directory(), &st)) {
     97                fprintf(stderr, "ERROR: lock directory %s does not exist\n\n",
     98                       lp_lock_directory());
    8999                ret = 1;
    90100        } else if ((st.st_ex_mode & 0777) != 0755) {
    91                 fprintf(stderr, "WARNING: lock directory %s should have permissions 0755 for browsing to work\n",
    92                        lp_lockdir());
    93                 ret = 1;
    94         }
    95 
    96         if (!directory_exist_stat(lp_statedir(), &st)) {
    97                 fprintf(stderr, "ERROR: state directory %s does not exist\n",
    98                        lp_statedir());
     101                fprintf(stderr, "WARNING: lock directory %s should have "
     102                                "permissions 0755 for browsing to work\n\n",
     103                       lp_lock_directory());
     104        }
     105
     106        if (!directory_exist_stat(lp_state_directory(), &st)) {
     107                fprintf(stderr, "ERROR: state directory %s does not exist\n\n",
     108                       lp_state_directory());
    99109                ret = 1;
    100110        } else if ((st.st_ex_mode & 0777) != 0755) {
    101                 fprintf(stderr, "WARNING: state directory %s should have permissions 0755 for browsing to work\n",
    102                        lp_statedir());
    103                 ret = 1;
    104         }
    105 
    106         if (!directory_exist_stat(lp_cachedir(), &st)) {
    107                 fprintf(stderr, "ERROR: cache directory %s does not exist\n",
    108                        lp_cachedir());
     111                fprintf(stderr, "WARNING: state directory %s should have "
     112                                "permissions 0755 for browsing to work\n\n",
     113                       lp_state_directory());
     114        }
     115
     116        if (!directory_exist_stat(lp_cache_directory(), &st)) {
     117                fprintf(stderr, "ERROR: cache directory %s does not exist\n\n",
     118                       lp_cache_directory());
    109119                ret = 1;
    110120        } else if ((st.st_ex_mode & 0777) != 0755) {
    111                 fprintf(stderr, "WARNING: cache directory %s should have permissions 0755 for browsing to work\n",
    112                        lp_cachedir());
    113                 ret = 1;
    114         }
    115 
    116         if (!directory_exist_stat(lp_piddir(), &st)) {
    117                 fprintf(stderr, "ERROR: pid directory %s does not exist\n",
    118                        lp_piddir());
     121                fprintf(stderr, "WARNING: cache directory %s should have "
     122                                "permissions 0755 for browsing to work\n\n",
     123                       lp_cache_directory());
     124        }
     125
     126        if (!directory_exist_stat(lp_pid_directory(), &st)) {
     127                fprintf(stderr, "ERROR: pid directory %s does not exist\n\n",
     128                       lp_pid_directory());
    119129                ret = 1;
    120130        }
     
    122132        if (lp_passdb_expand_explicit()) {
    123133                fprintf(stderr, "WARNING: passdb expand explicit = yes is "
    124                         "deprecated\n");
     134                                "deprecated\n\n");
     135        }
     136
     137        /*
     138         * Socket options.
     139         */
     140        socket_options = lp_socket_options();
     141        if (socket_options != NULL &&
     142            (strstr(socket_options, "SO_SNDBUF") ||
     143             strstr(socket_options, "SO_RCVBUF") ||
     144             strstr(socket_options, "SO_SNDLOWAT") ||
     145             strstr(socket_options, "SO_RCVLOWAT")))
     146        {
     147                fprintf(stderr,
     148                        "WARNING: socket options = %s\n"
     149                        "This warning is printed because you set one of the\n"
     150                        "following options: SO_SNDBUF, SO_RCVBUF, SO_SNDLOWAT,\n"
     151                        "SO_RCVLOWAT\n"
     152                        "Modern server operating systems are tuned for\n"
     153                        "high network performance in the majority of situations;\n"
     154                        "when you set 'socket options' you are overriding those\n"
     155                        "settings.\n"
     156                        "Linux in particular has an auto-tuning mechanism for\n"
     157                        "buffer sizes (SO_SNDBUF, SO_RCVBUF) that will be\n"
     158                        "disabled if you specify a socket buffer size. This can\n"
     159                        "potentially cripple your TCP/IP stack.\n\n"
     160                        "Getting the 'socket options' correct can make a big\n"
     161                        "difference to your performance, but getting them wrong\n"
     162                        "can degrade it by just as much. As with any other low\n"
     163                        "level setting, if you must make changes to it, make\n "
     164                        "small changes and test the effect before making any\n"
     165                        "large changes.\n\n",
     166                        socket_options);
    125167        }
    126168
     
    129171         */
    130172
    131         if((lp_security() == SEC_SERVER || lp_security() >= SEC_DOMAIN) && !*lp_passwordserver()) {
    132                 const char *sec_setting;
    133                 if(lp_security() == SEC_SERVER)
    134                         sec_setting = "server";
    135                 else if(lp_security() == SEC_DOMAIN)
    136                         sec_setting = "domain";
    137                 else if(lp_security() == SEC_ADS)
    138                         sec_setting = "ads";
    139                 else
    140                         sec_setting = "";
    141 
    142                 fprintf(stderr, "ERROR: The setting 'security=%s' requires the 'password server' parameter be set\n"
    143                         "to the default value * or a valid password server.\n", sec_setting );
    144                 ret = 1;
    145         }
    146 
    147         if((lp_security() >= SEC_DOMAIN) && (strcmp(lp_passwordserver(), "*") != 0)) {
     173        if((lp_security() >= SEC_DOMAIN) && !*lp_password_server()) {
    148174                const char *sec_setting;
    149175                if(lp_security() == SEC_DOMAIN)
     
    154180                        sec_setting = "";
    155181
    156                 fprintf(stderr, "WARNING: The setting 'security=%s' should NOT be combined with the 'password server' parameter.\n"
    157                         "(by default Samba will discover the correct DC to contact automatically).\n", sec_setting );
     182                fprintf(stderr, "ERROR: The setting 'security=%s' requires the "
     183                                "'password server' parameter be set to the "
     184                                "default value * or a valid password server.\n\n",
     185                                sec_setting );
     186                ret = 1;
     187        }
     188
     189        if((lp_security() >= SEC_DOMAIN) && (strcmp(lp_password_server(), "*") != 0)) {
     190                const char *sec_setting;
     191                if(lp_security() == SEC_DOMAIN)
     192                        sec_setting = "domain";
     193                else if(lp_security() == SEC_ADS)
     194                        sec_setting = "ads";
     195                else
     196                        sec_setting = "";
     197
     198                fprintf(stderr, "WARNING: The setting 'security=%s' should NOT "
     199                                "be combined with the 'password server' "
     200                                "parameter.\n"
     201                                "(by default Samba will discover the correct DC "
     202                                "to contact automatically).\n\n",
     203                                sec_setting );
    158204        }
    159205
     
    172218#endif
    173219
    174                         if((lp_passwd_program() == NULL) ||
    175                            (strlen(lp_passwd_program()) == 0))
     220                        if((lp_passwd_program(talloc_tos()) == NULL) ||
     221                           (strlen(lp_passwd_program(talloc_tos())) == 0))
    176222                        {
    177                                 fprintf( stderr, "ERROR: the 'unix password sync' parameter is set and there is no valid 'passwd program' \
    178 parameter.\n" );
     223                                fprintf(stderr,
     224                                        "ERROR: the 'unix password sync' "
     225                                        "parameter is set and there is no valid "
     226                                        "'passwd program' parameter.\n\n");
    179227                                ret = 1;
    180228                        } else {
     
    183231                                const char *p;
    184232
    185                                 passwd_prog = lp_passwd_program();
     233                                passwd_prog = lp_passwd_program(talloc_tos());
    186234                                p = passwd_prog;
    187235                                next_token_talloc(talloc_tos(),
     
    189237                                                &truncated_prog, NULL);
    190238                                if (truncated_prog && access(truncated_prog, F_OK) == -1) {
    191                                         fprintf(stderr, "ERROR: the 'unix password sync' parameter is set and the 'passwd program' (%s) \
    192 cannot be executed (error was %s).\n", truncated_prog, strerror(errno) );
     239                                        fprintf(stderr,
     240                                                "ERROR: the 'unix password sync' "
     241                                                "parameter is set and the "
     242                                                "'passwd program' (%s) cannot be "
     243                                                "executed (error was %s).\n\n",
     244                                                truncated_prog,
     245                                                strerror(errno));
    193246                                        ret = 1;
    194247                                }
     
    199252#endif
    200253
    201                 if(lp_passwd_chat() == NULL) {
    202                         fprintf(stderr, "ERROR: the 'unix password sync' parameter is set and there is no valid 'passwd chat' \
    203 parameter.\n");
     254                if(lp_passwd_chat(talloc_tos()) == NULL) {
     255                        fprintf(stderr,
     256                                "ERROR: the 'unix password sync' parameter is "
     257                                "set and there is no valid 'passwd chat' "
     258                                "parameter.\n\n");
    204259                        ret = 1;
    205260                }
    206261
    207                 if ((lp_passwd_program() != NULL) &&
    208                     (strlen(lp_passwd_program()) > 0))
     262                if ((lp_passwd_program(talloc_tos()) != NULL) &&
     263                    (strlen(lp_passwd_program(talloc_tos())) > 0))
    209264                {
    210265                        /* check if there's a %u parameter present */
    211                         if(strstr_m(lp_passwd_program(), "%u") == NULL) {
    212                                 fprintf(stderr, "ERROR: the 'passwd program' (%s) requires a '%%u' parameter.\n", lp_passwd_program());
     266                        if(strstr_m(lp_passwd_program(talloc_tos()), "%u") == NULL) {
     267                                fprintf(stderr,
     268                                        "ERROR: the 'passwd program' (%s) "
     269                                        "requires a '%%u' parameter.\n\n",
     270                                        lp_passwd_program(talloc_tos()));
    213271                                ret = 1;
    214272                        }
     
    220278                 */
    221279
    222                 if(lp_encrypted_passwords()) {
    223                         if(strstr_m( lp_passwd_chat(), "%o")!=NULL) {
    224                                 fprintf(stderr, "ERROR: the 'passwd chat' script [%s] expects to use the old plaintext password \
    225 via the %%o substitution. With encrypted passwords this is not possible.\n", lp_passwd_chat() );
     280                if(lp_encrypt_passwords()) {
     281                        if(strstr_m( lp_passwd_chat(talloc_tos()), "%o")!=NULL) {
     282                                fprintf(stderr,
     283                                        "ERROR: the 'passwd chat' script [%s] "
     284                                        "expects to use the old plaintext "
     285                                        "password via the %%o substitution. With "
     286                                        "encrypted passwords this is not "
     287                                        "possible.\n\n",
     288                                        lp_passwd_chat(talloc_tos()) );
    226289                                ret = 1;
    227290                        }
     
    230293
    231294        if (strlen(lp_winbind_separator()) != 1) {
    232                 fprintf(stderr,"ERROR: the 'winbind separator' parameter must be a single character.\n");
     295                fprintf(stderr, "ERROR: the 'winbind separator' parameter must "
     296                                "be a single character.\n\n");
    233297                ret = 1;
    234298        }
    235299
    236300        if (*lp_winbind_separator() == '+') {
    237                 fprintf(stderr,"'winbind separator = +' might cause problems with group membership.\n");
     301                fprintf(stderr, "'winbind separator = +' might cause problems "
     302                                "with group membership.\n\n");
    238303        }
    239304
     
    241306                /* Try to prevent admin foot-shooting, we can't put algorithmic
    242307                   rids below 1000, that's the 'well known RIDs' on NT */
    243                 fprintf(stderr,"'algorithmic rid base' must be equal to or above %lu\n", BASE_RID);
     308                fprintf(stderr, "'algorithmic rid base' must be equal to or "
     309                                "above %lu\n\n", BASE_RID);
    244310        }
    245311
    246312        if (lp_algorithmic_rid_base() & 1) {
    247                 fprintf(stderr,"'algorithmic rid base' must be even.\n");
     313                fprintf(stderr, "'algorithmic rid base' must be even.\n\n");
    248314        }
    249315
    250316#ifndef HAVE_DLOPEN
    251317        if (lp_preload_modules()) {
    252                 fprintf(stderr,"WARNING: 'preload modules = ' set while loading plugins not supported.\n");
     318                fprintf(stderr, "WARNING: 'preload modules = ' set while loading "
     319                                "plugins not supported.\n\n");
    253320        }
    254321#endif
    255322
    256323        if (!lp_passdb_backend()) {
    257                 fprintf(stderr,"ERROR: passdb backend must have a value or be left out\n");
     324                fprintf(stderr, "ERROR: passdb backend must have a value or be "
     325                                "left out\n\n");
    258326        }
    259327       
    260328        if (lp_os_level() > 255) {
    261                 fprintf(stderr,"WARNING: Maximum value for 'os level' is 255!\n");     
     329                fprintf(stderr, "WARNING: Maximum value for 'os level' is "
     330                                "255!\n\n");
     331        }
     332
     333        if (strequal(lp_dos_charset(), "UTF8") || strequal(lp_dos_charset(), "UTF-8")) {
     334                fprintf(stderr, "ERROR: 'dos charset' must not be UTF8\n\n");
     335                ret = 1;
    262336        }
    263337
     
    270344static void do_per_share_checks(int s)
    271345{
    272         const char **deny_list = lp_hostsdeny(s);
    273         const char **allow_list = lp_hostsallow(s);
     346        const char **deny_list = lp_hosts_deny(s);
     347        const char **allow_list = lp_hosts_allow(s);
    274348        int i;
    275349
     
    279353                        char *hasquery = strchr_m(deny_list[i], '?');
    280354                        if(hasstar || hasquery) {
    281                                 fprintf(stderr,"Invalid character %c in hosts deny list (%s) for service %s.\n",
    282                                            hasstar ? *hasstar : *hasquery, deny_list[i], lp_servicename(s) );
     355                                fprintf(stderr,
     356                                        "Invalid character %c in hosts deny list "
     357                                        "(%s) for service %s.\n\n",
     358                                        hasstar ? *hasstar : *hasquery,
     359                                        deny_list[i],
     360                                        lp_servicename(talloc_tos(), s));
    283361                        }
    284362                }
     
    290368                        char *hasquery = strchr_m(allow_list[i], '?');
    291369                        if(hasstar || hasquery) {
    292                                 fprintf(stderr,"Invalid character %c in hosts allow list (%s) for service %s.\n",
    293                                            hasstar ? *hasstar : *hasquery, allow_list[i], lp_servicename(s) );
     370                                fprintf(stderr,
     371                                        "Invalid character %c in hosts allow "
     372                                        "list (%s) for service %s.\n\n",
     373                                        hasstar ? *hasstar : *hasquery,
     374                                        allow_list[i],
     375                                        lp_servicename(talloc_tos(), s));
    294376                        }
    295377                }
     
    297379
    298380        if(lp_level2_oplocks(s) && !lp_oplocks(s)) {
    299                 fprintf(stderr,"Invalid combination of parameters for service %s. \
    300                            Level II oplocks can only be set if oplocks are also set.\n",
    301                            lp_servicename(s) );
    302         }
    303 
    304         if (lp_map_hidden(s) && !(lp_create_mask(s) & S_IXOTH)) {
    305                 fprintf(stderr,"Invalid combination of parameters for service %s. \
    306                            Map hidden can only work if create mask includes octal 01 (S_IXOTH).\n",
    307                            lp_servicename(s) );
    308         }
    309         if (lp_map_hidden(s) && (lp_force_create_mode(s) & S_IXOTH)) {
    310                 fprintf(stderr,"Invalid combination of parameters for service %s. \
    311                            Map hidden can only work if force create mode excludes octal 01 (S_IXOTH).\n",
    312                            lp_servicename(s) );
    313         }
    314         if (lp_map_system(s) && !(lp_create_mask(s) & S_IXGRP)) {
    315                 fprintf(stderr,"Invalid combination of parameters for service %s. \
    316                            Map system can only work if create mask includes octal 010 (S_IXGRP).\n",
    317                            lp_servicename(s) );
    318         }
    319         if (lp_map_system(s) && (lp_force_create_mode(s) & S_IXGRP)) {
    320                 fprintf(stderr,"Invalid combination of parameters for service %s. \
    321                            Map system can only work if force create mode excludes octal 010 (S_IXGRP).\n",
    322                            lp_servicename(s) );
    323         }
    324 #ifdef HAVE_CUPS
    325         if (lp_printing(s) == PRINT_CUPS && *(lp_printcommand(s)) != '\0') {
    326                  fprintf(stderr,"Warning: Service %s defines a print command, but \
    327 rameter is ignored when using CUPS libraries.\n",
    328                            lp_servicename(s) );
    329         }
    330 #endif
     381                fprintf(stderr, "Invalid combination of parameters for service "
     382                                "%s. Level II oplocks can only be set if oplocks "
     383                                "are also set.\n\n",
     384                                lp_servicename(talloc_tos(), s));
     385        }
     386
     387        if (!lp_store_dos_attributes(s) && lp_map_hidden(s)
     388            && !(lp_create_mask(s) & S_IXOTH))
     389        {
     390                fprintf(stderr,
     391                        "Invalid combination of parameters for service %s. Map "
     392                        "hidden can only work if create mask includes octal "
     393                        "01 (S_IXOTH).\n\n",
     394                        lp_servicename(talloc_tos(), s));
     395        }
     396        if (!lp_store_dos_attributes(s) && lp_map_hidden(s)
     397            && (lp_force_create_mode(s) & S_IXOTH))
     398        {
     399                fprintf(stderr,
     400                        "Invalid combination of parameters for service "
     401                        "%s. Map hidden can only work if force create mode "
     402                        "excludes octal 01 (S_IXOTH).\n\n",
     403                        lp_servicename(talloc_tos(), s));
     404        }
     405        if (!lp_store_dos_attributes(s) && lp_map_system(s)
     406            && !(lp_create_mask(s) & S_IXGRP))
     407        {
     408                fprintf(stderr,
     409                        "Invalid combination of parameters for service "
     410                        "%s. Map system can only work if create mask includes "
     411                        "octal 010 (S_IXGRP).\n\n",
     412                        lp_servicename(talloc_tos(), s));
     413        }
     414        if (!lp_store_dos_attributes(s) && lp_map_system(s)
     415            && (lp_force_create_mode(s) & S_IXGRP))
     416        {
     417                fprintf(stderr,
     418                        "Invalid combination of parameters for service "
     419                        "%s. Map system can only work if force create mode "
     420                        "excludes octal 010 (S_IXGRP).\n\n",
     421                        lp_servicename(talloc_tos(), s));
     422        }
     423        if (lp_printing(s) == PRINT_CUPS && *(lp_print_command(talloc_tos(), s)) != '\0') {
     424                fprintf(stderr,
     425                        "Warning: Service %s defines a print command, but "
     426                        "parameter is ignored when using CUPS libraries.\n\n",
     427                        lp_servicename(talloc_tos(), s));
     428        }
    331429}
    332430
     
    362460        TALLOC_CTX *frame = talloc_stackframe();
    363461
    364         load_case_tables();
     462        smb_init_locale();
    365463        /*
    366464         * Set the default debug level to 2.
     
    399497        fprintf(stderr,"Load smb config files from %s\n",config_file);
    400498
    401         if (!lp_load_with_registry_shares(config_file,False,True,False,True)) {
     499        if (!lp_load_with_registry_shares(config_file)) {
    402500                fprintf(stderr,"Error loading services.\n");
    403501                ret = 1;
     
    413511        for (s=0;s<1000;s++) {
    414512                if (VALID_SNUM(s))
    415                         if (strlen(lp_servicename(s)) > 12) {
     513                        if (strlen(lp_servicename(talloc_tos(), s)) > 12) {
    416514                                fprintf(stderr, "WARNING: You have some share names that are longer than 12 characters.\n" );
    417515                                fprintf(stderr, "These may not be accessible to some older clients.\n" );
     
    429527
    430528        if (!section_name && !parameter_name) {
    431                 fprintf(stderr,"Server role: %s\n", server_role_str(lp_server_role()));
     529                fprintf(stderr,
     530                        "Server role: %s\n\n",
     531                        server_role_str(lp_server_role()));
    432532        }
    433533
     
    475575                for (s=0;s<1000;s++) {
    476576                        if (VALID_SNUM(s)) {
    477                                 if (allow_access(lp_hostsdeny(-1), lp_hostsallow(-1), cname, caddr)
    478                                     && allow_access(lp_hostsdeny(s), lp_hostsallow(s), cname, caddr)) {
     577                                if (allow_access(lp_hosts_deny(-1), lp_hosts_allow(-1), cname, caddr)
     578                                    && allow_access(lp_hosts_deny(s), lp_hosts_allow(s), cname, caddr)) {
    479579                                        fprintf(stderr,"Allow connection from %s (%s) to %s\n",
    480                                                    cname,caddr,lp_servicename(s));
     580                                                   cname,caddr,lp_servicename(talloc_tos(), s));
    481581                                } else {
    482582                                        fprintf(stderr,"Deny connection from %s (%s) to %s\n",
    483                                                    cname,caddr,lp_servicename(s));
     583                                                   cname,caddr,lp_servicename(talloc_tos(), s));
    484584                                }
    485585                        }
Note: See TracChangeset for help on using the changeset viewer.