idl/ioctl: change QAR response array to a DATA_BLOB
[samba.git] / source3 / utils / net_idmap.c
1 /*
2    Samba Unix/Linux SMB client library
3    Distributed SMB/CIFS Server Management Utility
4    Copyright (C) 2003 Andrew Bartlett (abartlet@samba.org)
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "system/filesys.h"
22 #include "utils/net.h"
23 #include "secrets.h"
24 #include "idmap.h"
25 #include "dbwrap/dbwrap.h"
26 #include "dbwrap/dbwrap_open.h"
27 #include "../libcli/security/security.h"
28 #include "net_idmap_check.h"
29 #include "util_tdb.h"
30 #include "idmap_autorid_tdb.h"
31
32 #define ALLOC_CHECK(mem) do { \
33         if (!mem) { \
34                 d_fprintf(stderr, _("Out of memory!\n")); \
35                 talloc_free(ctx); \
36                 return -1; \
37         } } while(0)
38
39 enum idmap_dump_backend {
40         TDB,
41         AUTORID
42 };
43
44 struct net_idmap_ctx {
45         enum idmap_dump_backend backend;
46 };
47
48 static 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
102 /***********************************************************
103  Helper function for net_idmap_dump. Dump one entry.
104  **********************************************************/
105 static 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));
116                 return 0;
117         }
118
119         if (strcmp((char *)key.dptr, "GROUP HWM") == 0) {
120                 printf(_("GROUP HWM %d\n"), IVAL(value.dptr,0));
121                 return 0;
122         }
123
124         if (strncmp((char *)key.dptr, "S-", 2) != 0) {
125                 return 0;
126         }
127
128         printf("%s %s\n", value.dptr, key.dptr);
129         return 0;
130 }
131
132 /* returns db path for idmap backend alloced on talloc_tos */
133 static 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         }
144
145         if (c->opt_db != NULL) {
146                 dbfile = talloc_strdup(talloc_tos(), c->opt_db);
147                 if (dbfile == NULL) {
148                         d_fprintf(stderr, _("Out of memory!\n"));
149                 }
150         } else if (strequal(backend, "tdb")) {
151                 dbfile = state_path("winbindd_idmap.tdb");
152                 if (dbfile == NULL) {
153                         d_fprintf(stderr, _("Out of memory!\n"));
154                 }
155                 ctx->backend = TDB;
156         } else if (strequal(backend, "tdb2")) {
157                 dbfile = talloc_asprintf(talloc_tos(), "%s/idmap2.tdb",
158                                          lp_private_dir());
159                 if (dbfile == NULL) {
160                         d_fprintf(stderr, _("Out of memory!\n"));
161                 }
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;
169         } else {
170                 char *_backend = talloc_strdup(talloc_tos(), backend);
171                 char* args = strchr(_backend, ':');
172                 if (args != NULL) {
173                         *args = '\0';
174                 }
175
176                 d_printf(_("Sorry, 'idmap backend = %s' is currently not supported\n"),
177                            _backend);
178
179                 talloc_free(_backend);
180         }
181
182         return dbfile;
183 }
184
185 static 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
230 done:
231         talloc_free(dbfile);
232         return ret;
233 }
234
235
236 /***********************************************************
237  Dump the current idmap
238  **********************************************************/
239 static int net_idmap_dump(struct net_context *c, int argc, const char **argv)
240 {
241         struct db_context *db;
242         TALLOC_CTX *mem_ctx;
243         const char* dbfile;
244         NTSTATUS status;
245         int ret = -1;
246         struct net_idmap_ctx ctx = { .backend = TDB };
247
248         if ( argc > 1  || c->display_usage) {
249                 d_printf("%s\n%s",
250                          _("Usage:"),
251                          _("net idmap dump [[--db=]<inputfile>]\n"
252                            "  Dump current ID mapping.\n"
253                            "    inputfile\tTDB file to read mappings from.\n"));
254                 return c->display_usage?0:-1;
255         }
256
257         mem_ctx = talloc_stackframe();
258
259         dbfile = (argc > 0) ? argv[0] : net_idmap_dbfile(c, &ctx);
260         if (dbfile == NULL) {
261                 goto done;
262         }
263         d_fprintf(stderr, _("dumping id mapping from %s\n"), dbfile);
264
265         db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDONLY, 0,
266                      DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
267         if (db == NULL) {
268                 d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
269                           dbfile, strerror(errno));
270                 goto done;
271         }
272
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
288         ret = 0;
289
290 done:
291         talloc_free(mem_ctx);
292         return ret;
293 }
294
295 /***********************************************************
296  Write entries from stdin to current local idmap
297  **********************************************************/
298
299 static int net_idmap_store_id_mapping(struct db_context *db,
300                                       enum id_type type,
301                                       unsigned long idval,
302                                       const char *sid_string)
303 {
304         NTSTATUS status;
305         char *idstr = NULL;
306
307         switch(type) {
308         case ID_TYPE_UID:
309                 idstr = talloc_asprintf(talloc_tos(), "UID %lu", idval);
310                 break;
311         case ID_TYPE_GID:
312                 idstr = talloc_asprintf(talloc_tos(), "GID %lu", idval);
313                 break;
314         default:
315                 d_fprintf(stderr, "Invalid id mapping type: %d\n", type);
316                 return -1;
317         }
318
319         status = dbwrap_store_bystring(db, idstr,
320                                        string_term_tdb_data(sid_string),
321                                        TDB_REPLACE);
322         if (!NT_STATUS_IS_OK(status)) {
323                 d_fprintf(stderr, "Error storing ID -> SID: "
324                          "%s\n", nt_errstr(status));
325                 talloc_free(idstr);
326                 return -1;
327         }
328         status = dbwrap_store_bystring(db, sid_string,
329                                        string_term_tdb_data(idstr),
330                                        TDB_REPLACE);
331         if (!NT_STATUS_IS_OK(status)) {
332                 d_fprintf(stderr, "Error storing SID -> ID: "
333                          "%s\n", nt_errstr(status));
334                 talloc_free(idstr);
335                 return -1;
336         }
337
338         return 0;
339 }
340
341 static int net_idmap_restore(struct net_context *c, int argc, const char **argv)
342 {
343         TALLOC_CTX *mem_ctx;
344         FILE *input = NULL;
345         struct db_context *db;
346         const char *dbfile = NULL;
347         int ret = 0;
348         struct net_idmap_ctx ctx = { .backend = TDB };
349
350         if (c->display_usage) {
351                 d_printf("%s\n%s",
352                          _("Usage:"),
353                          _("net idmap restore [--db=<TDB>] [<inputfile>]\n"
354                            "  Restore ID mappings from file\n"
355                            "    TDB\tFile to store ID mappings to."
356                            "    inputfile\tFile to load ID mappings from. If not "
357                            "given, load data from stdin.\n"));
358                 return 0;
359         }
360
361         mem_ctx = talloc_stackframe();
362
363         dbfile = net_idmap_dbfile(c, &ctx);
364
365         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"));
373                 ret = -1;
374                 goto done;
375         }
376
377         d_fprintf(stderr, _("restoring id mapping to %s\n"), dbfile);
378
379         if (argc == 1) {
380                 input = fopen(argv[0], "r");
381                 if (input == NULL) {
382                         d_fprintf(stderr, _("Could not open input file (%s): %s\n"),
383                                   argv[0], strerror(errno));
384                         ret = -1;
385                         goto done;
386                 }
387         } else {
388                 input = stdin;
389         }
390
391         db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0644,
392                      DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
393         if (db == NULL) {
394                 d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
395                           dbfile, strerror(errno));
396                 ret = -1;
397                 goto done;
398         }
399
400         if (dbwrap_transaction_start(db) != 0) {
401                 d_fprintf(stderr, _("Failed to start transaction.\n"));
402                 ret = -1;
403                 goto done;
404         }
405
406         while (!feof(input)) {
407                 char line[128], sid_string[128];
408                 int len;
409                 unsigned long idval;
410                 NTSTATUS status;
411
412                 if (fgets(line, 127, input) == NULL)
413                         break;
414
415                 len = strlen(line);
416
417                 if ( (len > 0) && (line[len-1] == '\n') )
418                         line[len-1] = '\0';
419
420                 if (sscanf(line, "GID %lu %128s", &idval, sid_string) == 2)
421                 {
422                         ret = net_idmap_store_id_mapping(db, ID_TYPE_GID,
423                                                          idval, sid_string);
424                         if (ret != 0) {
425                                 break;
426                         }
427                 } else if (sscanf(line, "UID %lu %128s", &idval, sid_string) == 2)
428                 {
429                         ret = net_idmap_store_id_mapping(db, ID_TYPE_UID,
430                                                          idval, sid_string);
431                         if (ret != 0) {
432                                 break;
433                         }
434                 } else if (sscanf(line, "USER HWM %lu", &idval) == 1) {
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));
441                                 break;
442                         }
443                 } else if (sscanf(line, "GROUP HWM %lu", &idval) == 1) {
444                         status = dbwrap_store_int32_bystring(
445                                 db, "GROUP HWM", idval);
446                         if (!NT_STATUS_IS_OK(status)) {
447                                 d_fprintf(stderr,
448                                           _("Could not store GROUP HWM: %s\n"),
449                                           nt_errstr(status));
450                                 break;
451                         }
452                 } else {
453                         d_fprintf(stderr, _("ignoring invalid line [%s]\n"),
454                                   line);
455                         continue;
456                 }
457         }
458
459         if (ret == 0) {
460                 if(dbwrap_transaction_commit(db) != 0) {
461                         d_fprintf(stderr, _("Failed to commit transaction.\n"));
462                         ret = -1;
463                 }
464         } else {
465                 if (dbwrap_transaction_cancel(db) != 0) {
466                         d_fprintf(stderr, _("Failed to cancel transaction.\n"));
467                 }
468         }
469
470 done:
471         if ((input != NULL) && (input != stdin)) {
472                 fclose(input);
473         }
474
475         talloc_free(mem_ctx);
476         return ret;
477 }
478
479 static
480 NTSTATUS dbwrap_delete_mapping(struct db_context *db, TDB_DATA key1, bool force)
481 {
482         TALLOC_CTX *mem_ctx = talloc_stackframe();
483         bool is_valid_mapping;
484         NTSTATUS status = NT_STATUS_OK;
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)) {
492                 DEBUG(1, ("failed to fetch: %.*s\n", (int)key1.dsize, key1.dptr));
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;
500                 goto done;
501         }
502
503         DEBUG(2, ("mapping: %.*s -> %.*s\n",
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);
513
514         if (!is_valid_mapping) {
515                 DEBUG(1, ("invalid mapping: %.*s -> %.*s -> %.*s\n",
516                           (int)key1.dsize, key1.dptr,
517                           (int)val1.dsize, val1.dptr,
518                           (int)val2.dsize, val2.dptr));
519                 if ( !force ) {
520                         status = NT_STATUS_FILE_INVALID;
521                         goto done;
522                 }
523         }
524
525         status = dbwrap_delete(db, key1);
526         if (!NT_STATUS_IS_OK(status)) {
527                 DEBUG(1, ("failed to delete: %.*s\n", (int)key1.dsize, key1.dptr));
528                 goto done;
529         }
530
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
540 done:
541         talloc_free(mem_ctx);
542         return status;
543 }
544
545 static
546 NTSTATUS delete_mapping_action(struct db_context *db, void* data)
547 {
548         return dbwrap_delete_mapping(db, *(TDB_DATA*)data, false);
549 }
550 static
551 NTSTATUS delete_mapping_action_force(struct db_context *db, void* data)
552 {
553         return dbwrap_delete_mapping(db, *(TDB_DATA*)data, true);
554 }
555
556 /***********************************************************
557  Delete a SID mapping from a winbindd_idmap.tdb
558  **********************************************************/
559 static bool delete_args_ok(int argc, const char **argv)
560 {
561         if (argc != 1)
562                 return false;
563         if (strncmp(argv[0], "S-", 2) == 0)
564                 return true;
565         if (strncmp(argv[0], "GID ", 4) == 0)
566                 return true;
567         if (strncmp(argv[0], "UID ", 4) == 0)
568                 return true;
569         return false;
570 }
571
572 static int net_idmap_delete_mapping(struct net_context *c, int argc,
573                                     const char **argv)
574 {
575         int ret = -1;
576         struct db_context *db;
577         TALLOC_CTX *mem_ctx;
578         TDB_DATA key;
579         NTSTATUS status;
580         const char* dbfile;
581         struct net_idmap_ctx ctx = { .backend = TDB };
582
583         if ( !delete_args_ok(argc,argv) || c->display_usage) {
584                 d_printf("%s\n%s",
585                          _("Usage:"),
586                          _("net idmap delete mapping [-f] [--db=<TDB>] <ID>\n"
587                            "  Delete mapping of ID from TDB.\n"
588                            "    -f\tforce\n"
589                            "    TDB\tidmap database\n"
590                            "    ID\tSID|GID|UID\n"));
591                 return c->display_usage ? 0 : -1;
592         }
593
594         mem_ctx = talloc_stackframe();
595
596         dbfile = net_idmap_dbfile(c, &ctx);
597         if (dbfile == NULL) {
598                 goto done;
599         }
600         d_fprintf(stderr, _("deleting id mapping from %s\n"), dbfile);
601
602         db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDWR, 0,
603                      DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
604         if (db == NULL) {
605                 d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
606                           dbfile, strerror(errno));
607                 goto done;
608         }
609
610         key = string_term_tdb_data(argv[0]);
611
612         status = dbwrap_trans_do(db, (c->opt_force
613                                       ? delete_mapping_action_force
614                                       : delete_mapping_action),  &key);
615
616         if (!NT_STATUS_IS_OK(status)) {
617                 d_fprintf(stderr, _("could not delete mapping: %s\n"),
618                           nt_errstr(status));
619                 goto done;
620         }
621         ret = 0;
622 done:
623         talloc_free(mem_ctx);
624         return ret;
625 }
626
627 static 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
651 static 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
664 static 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
734 done:
735         talloc_free(mem_ctx);
736         return ret;
737 }
738
739 static 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
750 static 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
792 done:
793         talloc_free(mem_ctx);
794         return ret;
795 }
796
797 static 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
832 static int net_idmap_set_mapping(struct net_context *c,
833                                  int argc, const char **argv)
834 {
835         d_printf("%s\n", _("Not implemented yet"));
836         return -1;
837 }
838
839 static 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
852 static 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
909 done:
910         TALLOC_FREE(mem_ctx);
911         return ret;
912 }
913
914 static bool idmap_store_secret(const char *backend,
915                                const char *domain,
916                                const char *identity,
917                                const char *secret)
918 {
919         char *tmp;
920         int r;
921         bool ret;
922
923         r = asprintf(&tmp, "IDMAP_%s_%s", backend, domain);
924
925         if (r < 0) return false;
926
927         /* make sure the key is case insensitive */
928         if (!strupper_m(tmp)) {
929                 free(tmp);
930                 return false;
931         }
932         ret = secrets_store_generic(tmp, identity, secret);
933
934         free(tmp);
935         return ret;
936 }
937
938
939 static int net_idmap_secret(struct net_context *c, int argc, const char **argv)
940 {
941         TALLOC_CTX *ctx;
942         const char *secret;
943         const char *dn;
944         char *domain;
945         char *backend;
946         char *opt = NULL;
947         bool ret;
948
949         if (argc != 2 || c->display_usage) {
950                 d_printf("%s\n%s",
951                          _("Usage:\n"),
952                          _("net idmap set secret <DOMAIN> <secret>\n"
953                            "  Set the secret for the specified domain\n"
954                            "    DOMAIN\tDomain to set secret for.\n"
955                            "    secret\tNew secret to set.\n"));
956                 return c->display_usage?0:-1;
957         }
958
959         secret = argv[1];
960
961         ctx = talloc_new(NULL);
962         ALLOC_CHECK(ctx);
963
964         domain = talloc_strdup(ctx, argv[0]);
965         ALLOC_CHECK(domain);
966
967         opt = talloc_asprintf(ctx, "idmap config %s", domain);
968         ALLOC_CHECK(opt);
969
970         backend = talloc_strdup(ctx, lp_parm_const_string(-1, opt, "backend", "tdb"));
971         ALLOC_CHECK(backend);
972
973         if ((!backend) || (!strequal(backend, "ldap") &&
974                            !strequal(backend, "rfc2307"))) {
975                 d_fprintf(stderr,
976                           _("The only currently supported backend are LDAP "
977                             "and rfc2307\n"));
978                 talloc_free(ctx);
979                 return -1;
980         }
981
982         dn = lp_parm_const_string(-1, opt, "ldap_user_dn", NULL);
983         if ( ! dn) {
984                 d_fprintf(stderr,
985                           _("Missing ldap_user_dn option for domain %s\n"),
986                           domain);
987                 talloc_free(ctx);
988                 return -1;
989         }
990
991         ret = idmap_store_secret("ldap", domain, dn, secret);
992
993         if ( ! ret) {
994                 d_fprintf(stderr, _("Failed to store secret\n"));
995                 talloc_free(ctx);
996                 return -1;
997         }
998
999         d_printf(_("Secret stored\n"));
1000         return 0;
1001 }
1002
1003 static 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
1037 done:
1038         TALLOC_FREE(mem_ctx);
1039         return ret;
1040 }
1041
1042 static 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
1083 static 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
1095 static 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
1156 done:
1157         TALLOC_FREE(mem_ctx);
1158         return ret;
1159 }
1160
1161 static 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
1177 static 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
1187 static 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
1228 done:
1229         talloc_free(mem_ctx);
1230         return ret;
1231 }
1232
1233 static 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
1269 done:
1270         TALLOC_FREE(mem_ctx);
1271         return ret;
1272 }
1273
1274
1275 static 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
1308 static int net_idmap_check(struct net_context *c, int argc, const char **argv)
1309 {
1310         char *dbfile;
1311         struct check_options opts;
1312         struct net_idmap_ctx ctx = { .backend = TDB };
1313         int ret;
1314
1315         if ( argc > 1 || c->display_usage) {
1316                 d_printf("%s\n%s",
1317                          _("Usage:"),
1318                          _("net idmap check  [-v] [-r] [-a] [-T] [-f] [-l] [[--db=]<TDB>]\n"
1319                            "  Check an idmap database.\n"
1320                            "    --verbose,-v\tverbose\n"
1321                            "    --repair,-r\trepair\n"
1322                            "    --auto,-a\tnoninteractive mode\n"
1323                            "    --test,-T\tdry run\n"
1324                            "    --fore,-f\tforce\n"
1325                            "    --lock,-l\tlock db while doing the check\n"
1326                            "    TDB\tidmap database\n"));
1327                 return c->display_usage ? 0 : -1;
1328         }
1329
1330         if (argc > 0) {
1331                 dbfile = talloc_strdup(talloc_tos(), argv[0]);
1332         } else {
1333                 dbfile = net_idmap_dbfile(c, &ctx);
1334         }
1335         if (dbfile == NULL) {
1336                 return -1;
1337         }
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
1346         d_fprintf(stderr, _("check database: %s\n"), dbfile);
1347
1348         opts = (struct check_options) {
1349                 .lock = c->opt_lock || c->opt_long_list_entries,
1350                 .test = c->opt_testmode,
1351                 .automatic = c->opt_auto,
1352                 .verbose = c->opt_verbose,
1353                 .force = c->opt_force,
1354                 .repair = c->opt_repair || c->opt_reboot,
1355         };
1356
1357         ret = net_idmap_check_db(dbfile, &opts);
1358         talloc_free(dbfile);
1359         return ret;
1360 }
1361
1362 /***********************************************************
1363  Look at the current idmap
1364  **********************************************************/
1365 int net_idmap(struct net_context *c, int argc, const char **argv)
1366 {
1367         struct functable func[] = {
1368                 {
1369                         "dump",
1370                         net_idmap_dump,
1371                         NET_TRANSPORT_LOCAL,
1372                         N_("Dump the current ID mapping database"),
1373                         N_("net idmap dump\n"
1374                            "  Dump the current ID mappings")
1375                 },
1376                 {
1377                         "restore",
1378                         net_idmap_restore,
1379                         NET_TRANSPORT_LOCAL,
1380                         N_("Restore entries from a file or stdin"),
1381                         N_("net idmap restore\n"
1382                            "  Restore entries from stdin")
1383                 },
1384                 {
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",
1394                         net_idmap_set,
1395                         NET_TRANSPORT_LOCAL,
1396                         N_("Write data to the ID mapping database"),
1397                         N_("net idmap set\n"
1398                            "  Write data to the ID mapping database")
1399                 },
1400                 {
1401                         "delete",
1402                         net_idmap_delete,
1403                         NET_TRANSPORT_LOCAL,
1404                         N_("Delete entries from the ID mapping database"),
1405                         N_("net idmap delete\n"
1406                            "  Delete entries from the ID mapping database")
1407                 },
1408                 {
1409                         "check",
1410                         net_idmap_check,
1411                         NET_TRANSPORT_LOCAL,
1412                         N_("Check id mappings"),
1413                         N_("net idmap check\n"
1414                            "  Check id mappings")
1415                 },
1416                 {NULL, NULL, 0, NULL, NULL}
1417         };
1418
1419         return net_run_function(c, argc, argv, "net idmap", func);
1420 }
1421
1422