39040343f60aec0d484f9b58618ae8f0490fad5c
[mat/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 static const char* net_idmap_dbfile(struct net_context *c,
133                                     struct net_idmap_ctx *ctx)
134 {
135         const char* dbfile = NULL;
136         const char *backend = NULL;
137
138         backend = lp_idmap_default_backend();
139         if (!backend) {
140                 d_printf(_("Internal error: 'idmap config * : backend' is not set!\n"));
141                 return NULL;
142         }
143
144         if (c->opt_db != NULL) {
145                 dbfile = talloc_strdup(talloc_tos(), c->opt_db);
146                 if (dbfile == NULL) {
147                         d_fprintf(stderr, _("Out of memory!\n"));
148                 }
149         } else if (strequal(backend, "tdb")) {
150                 dbfile = state_path("winbindd_idmap.tdb");
151                 if (dbfile == NULL) {
152                         d_fprintf(stderr, _("Out of memory!\n"));
153                 }
154                 ctx->backend = TDB;
155         } else if (strequal(backend, "tdb2")) {
156                 dbfile = talloc_asprintf(talloc_tos(), "%s/idmap2.tdb",
157                                          lp_private_dir());
158                 if (dbfile == NULL) {
159                         d_fprintf(stderr, _("Out of memory!\n"));
160                 }
161                 ctx->backend = TDB;
162         } else if (strequal(backend, "autorid")) {
163                 dbfile = state_path("autorid.tdb");
164                 if (dbfile == NULL) {
165                         d_fprintf(stderr, _("Out of memory!\n"));
166                 }
167                 ctx->backend = AUTORID;
168         } else {
169                 char *_backend = talloc_strdup(talloc_tos(), backend);
170                 char* args = strchr(_backend, ':');
171                 if (args != NULL) {
172                         *args = '\0';
173                 }
174
175                 d_printf(_("Sorry, 'idmap backend = %s' is currently not supported\n"),
176                            _backend);
177
178                 talloc_free(_backend);
179         }
180
181         return dbfile;
182 }
183
184 static bool net_idmap_opendb_autorid(TALLOC_CTX *mem_ctx,
185                                      struct net_context *c,
186                                      bool readonly,
187                                      struct db_context **db)
188 {
189         bool ret = false;
190         const char *dbfile;
191         struct net_idmap_ctx ctx = { .backend = AUTORID };
192
193         if (c == NULL) {
194                 goto done;
195         }
196
197         dbfile = net_idmap_dbfile(c, &ctx);
198         if (dbfile == NULL) {
199                 goto done;
200         }
201
202         if (ctx.backend != AUTORID) {
203                 d_fprintf(stderr, _("Unsupported backend\n"));
204                 goto done;
205         }
206
207         if (readonly) {
208                 *db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDONLY, 0,
209                              DBWRAP_LOCK_ORDER_1);
210                 if (*db == NULL) {
211                         d_fprintf(stderr,
212                                   _("Could not open autorid db (%s): %s\n"),
213                                  dbfile, strerror(errno));
214                         goto done;
215                 }
216         } else {
217                 NTSTATUS status;
218                 status = idmap_autorid_db_init(dbfile, mem_ctx, db);
219                 if (!NT_STATUS_IS_OK(status)) {
220                         d_fprintf(stderr,
221                                 _("Error calling idmap_autorid_db_init: %s\n"),
222                                 nt_errstr(status));
223                         goto done;
224                 }
225         }
226
227         ret = true;
228
229 done:
230         return ret;
231 }
232
233
234 /***********************************************************
235  Dump the current idmap
236  **********************************************************/
237 static int net_idmap_dump(struct net_context *c, int argc, const char **argv)
238 {
239         struct db_context *db;
240         TALLOC_CTX *mem_ctx;
241         const char* dbfile;
242         NTSTATUS status;
243         int ret = -1;
244         struct net_idmap_ctx ctx = { .backend = TDB };
245
246         if ( argc > 1  || c->display_usage) {
247                 d_printf("%s\n%s",
248                          _("Usage:"),
249                          _("net idmap dump [[--db=]<inputfile>]\n"
250                            "  Dump current ID mapping.\n"
251                            "    inputfile\tTDB file to read mappings from.\n"));
252                 return c->display_usage?0:-1;
253         }
254
255         mem_ctx = talloc_stackframe();
256
257         dbfile = (argc > 0) ? argv[0] : net_idmap_dbfile(c, &ctx);
258         if (dbfile == NULL) {
259                 goto done;
260         }
261         d_fprintf(stderr, _("dumping id mapping from %s\n"), dbfile);
262
263         db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDONLY, 0,
264                      DBWRAP_LOCK_ORDER_1);
265         if (db == NULL) {
266                 d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
267                           dbfile, strerror(errno));
268                 goto done;
269         }
270
271         if (ctx.backend == AUTORID) {
272                 status = dbwrap_traverse_read(db,
273                                               net_idmap_dump_one_autorid_entry,
274                                               NULL, NULL);
275         } else {
276                 status = dbwrap_traverse_read(db,
277                                               net_idmap_dump_one_tdb_entry,
278                                               NULL, NULL);
279         }
280         if (!NT_STATUS_IS_OK(status)) {
281                 d_fprintf(stderr, _("error traversing the database\n"));
282                 ret = -1;
283                 goto done;
284         }
285
286         ret = 0;
287
288 done:
289         talloc_free(mem_ctx);
290         return ret;
291 }
292
293 /***********************************************************
294  Write entries from stdin to current local idmap
295  **********************************************************/
296
297 static int net_idmap_store_id_mapping(struct db_context *db,
298                                       enum id_type type,
299                                       unsigned long idval,
300                                       const char *sid_string)
301 {
302         NTSTATUS status;
303         char *idstr = NULL;
304
305         switch(type) {
306         case ID_TYPE_UID:
307                 idstr = talloc_asprintf(talloc_tos(), "UID %lu", idval);
308                 break;
309         case ID_TYPE_GID:
310                 idstr = talloc_asprintf(talloc_tos(), "GID %lu", idval);
311                 break;
312         default:
313                 d_fprintf(stderr, "Invalid id mapping type: %d\n", type);
314                 return -1;
315         }
316
317         status = dbwrap_store_bystring(db, idstr,
318                                        string_term_tdb_data(sid_string),
319                                        TDB_REPLACE);
320         if (!NT_STATUS_IS_OK(status)) {
321                 d_fprintf(stderr, "Error storing ID -> SID: "
322                          "%s\n", nt_errstr(status));
323                 talloc_free(idstr);
324                 return -1;
325         }
326         status = dbwrap_store_bystring(db, sid_string,
327                                        string_term_tdb_data(idstr),
328                                        TDB_REPLACE);
329         if (!NT_STATUS_IS_OK(status)) {
330                 d_fprintf(stderr, "Error storing SID -> ID: "
331                          "%s\n", nt_errstr(status));
332                 talloc_free(idstr);
333                 return -1;
334         }
335
336         return 0;
337 }
338
339 static int net_idmap_restore(struct net_context *c, int argc, const char **argv)
340 {
341         TALLOC_CTX *mem_ctx;
342         FILE *input = NULL;
343         struct db_context *db;
344         const char *dbfile = NULL;
345         int ret = 0;
346         struct net_idmap_ctx ctx = { .backend = TDB };
347
348         if (c->display_usage) {
349                 d_printf("%s\n%s",
350                          _("Usage:"),
351                          _("net idmap restore [--db=<TDB>] [<inputfile>]\n"
352                            "  Restore ID mappings from file\n"
353                            "    TDB\tFile to store ID mappings to."
354                            "    inputfile\tFile to load ID mappings from. If not "
355                            "given, load data from stdin.\n"));
356                 return 0;
357         }
358
359         mem_ctx = talloc_stackframe();
360
361         dbfile = net_idmap_dbfile(c, &ctx);
362
363         if (dbfile == NULL) {
364                 ret = -1;
365                 goto done;
366         }
367
368         if (ctx.backend != TDB) {
369                 d_fprintf(stderr, _("Sorry, restoring of non-TDB databases is "
370                                     "currently not supported\n"));
371                 ret = -1;
372                 goto done;
373         }
374
375         d_fprintf(stderr, _("restoring id mapping to %s\n"), dbfile);
376
377         if (argc == 1) {
378                 input = fopen(argv[0], "r");
379                 if (input == NULL) {
380                         d_fprintf(stderr, _("Could not open input file (%s): %s\n"),
381                                   argv[0], strerror(errno));
382                         ret = -1;
383                         goto done;
384                 }
385         } else {
386                 input = stdin;
387         }
388
389         db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0644,
390                      DBWRAP_LOCK_ORDER_1);
391         if (db == NULL) {
392                 d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
393                           dbfile, strerror(errno));
394                 ret = -1;
395                 goto done;
396         }
397
398         if (dbwrap_transaction_start(db) != 0) {
399                 d_fprintf(stderr, _("Failed to start transaction.\n"));
400                 ret = -1;
401                 goto done;
402         }
403
404         while (!feof(input)) {
405                 char line[128], sid_string[128];
406                 int len;
407                 unsigned long idval;
408                 NTSTATUS status;
409
410                 if (fgets(line, 127, input) == NULL)
411                         break;
412
413                 len = strlen(line);
414
415                 if ( (len > 0) && (line[len-1] == '\n') )
416                         line[len-1] = '\0';
417
418                 if (sscanf(line, "GID %lu %128s", &idval, sid_string) == 2)
419                 {
420                         ret = net_idmap_store_id_mapping(db, ID_TYPE_GID,
421                                                          idval, sid_string);
422                         if (ret != 0) {
423                                 break;
424                         }
425                 } else if (sscanf(line, "UID %lu %128s", &idval, sid_string) == 2)
426                 {
427                         ret = net_idmap_store_id_mapping(db, ID_TYPE_UID,
428                                                          idval, sid_string);
429                         if (ret != 0) {
430                                 break;
431                         }
432                 } else if (sscanf(line, "USER HWM %lu", &idval) == 1) {
433                         status = dbwrap_store_int32_bystring(
434                                 db, "USER HWM", idval);
435                         if (!NT_STATUS_IS_OK(status)) {
436                                 d_fprintf(stderr,
437                                           _("Could not store USER HWM: %s\n"),
438                                           nt_errstr(status));
439                                 break;
440                         }
441                 } else if (sscanf(line, "GROUP HWM %lu", &idval) == 1) {
442                         status = dbwrap_store_int32_bystring(
443                                 db, "GROUP HWM", idval);
444                         if (!NT_STATUS_IS_OK(status)) {
445                                 d_fprintf(stderr,
446                                           _("Could not store GROUP HWM: %s\n"),
447                                           nt_errstr(status));
448                                 break;
449                         }
450                 } else {
451                         d_fprintf(stderr, _("ignoring invalid line [%s]\n"),
452                                   line);
453                         continue;
454                 }
455         }
456
457         if (ret == 0) {
458                 if(dbwrap_transaction_commit(db) != 0) {
459                         d_fprintf(stderr, _("Failed to commit transaction.\n"));
460                         ret = -1;
461                 }
462         } else {
463                 if (dbwrap_transaction_cancel(db) != 0) {
464                         d_fprintf(stderr, _("Failed to cancel transaction.\n"));
465                 }
466         }
467
468 done:
469         if ((input != NULL) && (input != stdin)) {
470                 fclose(input);
471         }
472
473         talloc_free(mem_ctx);
474         return ret;
475 }
476
477 static
478 NTSTATUS dbwrap_delete_mapping(struct db_context *db, TDB_DATA key1, bool force)
479 {
480         TALLOC_CTX *mem_ctx = talloc_stackframe();
481         bool is_valid_mapping;
482         NTSTATUS status = NT_STATUS_OK;
483         TDB_DATA val1, val2;
484
485         ZERO_STRUCT(val1);
486         ZERO_STRUCT(val2);
487
488         status = dbwrap_fetch(db, mem_ctx, key1, &val1);
489         if (!NT_STATUS_IS_OK(status)) {
490                 DEBUG(1, ("failed to fetch: %.*s\n", (int)key1.dsize, key1.dptr));
491                 goto done;
492         }
493
494         if (val1.dptr == NULL) {
495                 DEBUG(1, ("invalid mapping: %.*s -> empty value\n",
496                           (int)key1.dsize, key1.dptr));
497                 status = NT_STATUS_FILE_INVALID;
498                 goto done;
499         }
500
501         DEBUG(2, ("mapping: %.*s -> %.*s\n",
502                   (int)key1.dsize, key1.dptr, (int)val1.dsize, val1.dptr));
503
504         status = dbwrap_fetch(db, mem_ctx, val1, &val2);
505         if (!NT_STATUS_IS_OK(status)) {
506                 DEBUG(1, ("failed to fetch: %.*s\n", (int)val1.dsize, val1.dptr));
507                 goto done;
508         }
509
510         is_valid_mapping = tdb_data_equal(key1, val2);
511
512         if (!is_valid_mapping) {
513                 DEBUG(1, ("invalid mapping: %.*s -> %.*s -> %.*s\n",
514                           (int)key1.dsize, key1.dptr,
515                           (int)val1.dsize, val1.dptr,
516                           (int)val2.dsize, val2.dptr));
517                 if ( !force ) {
518                         status = NT_STATUS_FILE_INVALID;
519                         goto done;
520                 }
521         }
522
523         status = dbwrap_delete(db, key1);
524         if (!NT_STATUS_IS_OK(status)) {
525                 DEBUG(1, ("failed to delete: %.*s\n", (int)key1.dsize, key1.dptr));
526                 goto done;
527         }
528
529         if (!is_valid_mapping) {
530                 goto done;
531         }
532
533         status = dbwrap_delete(db, val1);
534         if (!NT_STATUS_IS_OK(status)) {
535                 DEBUG(1, ("failed to delete: %.*s\n", (int)val1.dsize, val1.dptr));
536         }
537
538 done:
539         talloc_free(mem_ctx);
540         return status;
541 }
542
543 static
544 NTSTATUS delete_mapping_action(struct db_context *db, void* data)
545 {
546         return dbwrap_delete_mapping(db, *(TDB_DATA*)data, false);
547 }
548 static
549 NTSTATUS delete_mapping_action_force(struct db_context *db, void* data)
550 {
551         return dbwrap_delete_mapping(db, *(TDB_DATA*)data, true);
552 }
553
554 /***********************************************************
555  Delete a SID mapping from a winbindd_idmap.tdb
556  **********************************************************/
557 static bool delete_args_ok(int argc, const char **argv)
558 {
559         if (argc != 1)
560                 return false;
561         if (strncmp(argv[0], "S-", 2) == 0)
562                 return true;
563         if (strncmp(argv[0], "GID ", 4) == 0)
564                 return true;
565         if (strncmp(argv[0], "UID ", 4) == 0)
566                 return true;
567         return false;
568 }
569
570 static int net_idmap_delete_mapping(struct net_context *c, int argc,
571                                     const char **argv)
572 {
573         int ret = -1;
574         struct db_context *db;
575         TALLOC_CTX *mem_ctx;
576         TDB_DATA key;
577         NTSTATUS status;
578         const char* dbfile;
579         struct net_idmap_ctx ctx = { .backend = TDB };
580
581         if ( !delete_args_ok(argc,argv) || c->display_usage) {
582                 d_printf("%s\n%s",
583                          _("Usage:"),
584                          _("net idmap delete mapping [-f] [--db=<TDB>] <ID>\n"
585                            "  Delete mapping of ID from TDB.\n"
586                            "    -f\tforce\n"
587                            "    TDB\tidmap database\n"
588                            "    ID\tSID|GID|UID\n"));
589                 return c->display_usage ? 0 : -1;
590         }
591
592         mem_ctx = talloc_stackframe();
593
594         dbfile = net_idmap_dbfile(c, &ctx);
595         if (dbfile == NULL) {
596                 goto done;
597         }
598         d_fprintf(stderr, _("deleting id mapping from %s\n"), dbfile);
599
600         db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDWR, 0,
601                      DBWRAP_LOCK_ORDER_1);
602         if (db == NULL) {
603                 d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
604                           dbfile, strerror(errno));
605                 goto done;
606         }
607
608         key = string_term_tdb_data(argv[0]);
609
610         status = dbwrap_trans_do(db, (c->opt_force
611                                       ? delete_mapping_action_force
612                                       : delete_mapping_action),  &key);
613
614         if (!NT_STATUS_IS_OK(status)) {
615                 d_fprintf(stderr, _("could not delete mapping: %s\n"),
616                           nt_errstr(status));
617                 goto done;
618         }
619         ret = 0;
620 done:
621         talloc_free(mem_ctx);
622         return ret;
623 }
624
625 static bool parse_uint32(const char *str, uint32_t *result)
626 {
627         unsigned long val;
628         char *endptr;
629
630         val = strtoul(str, &endptr, 10);
631
632         if (str == endptr) {
633                 return false;
634         }
635         if (*endptr != '\0') {
636                 return false;
637         }
638         if ((val == ULONG_MAX) && (errno == ERANGE)) {
639                 return false;
640         }
641         if ((val & UINT32_MAX) != val) {
642                 /* overflow */
643                 return false;
644         }
645         *result = val;          /* Potential crop */
646         return true;
647 }
648
649 static int net_idmap_delete(struct net_context *c, int argc, const char **argv)
650 {
651         struct functable func[] = {
652                 {
653                         "mapping",
654                         net_idmap_delete_mapping,
655                         NET_TRANSPORT_LOCAL,
656                         N_("Delete ID mapping"),
657                         N_("net idmap delete mapping <ID>\n"
658                            "  Delete ID mapping")
659                 },
660                 {NULL, NULL, 0, NULL, NULL}
661         };
662
663         return net_run_function(c, argc, argv, "net idmap delete", func);
664 }
665
666
667 static int net_idmap_set_mapping(struct net_context *c,
668                                  int argc, const char **argv)
669 {
670         d_printf("%s\n", _("Not implemented yet"));
671         return -1;
672 }
673
674 static void net_idmap_autorid_set_range_usage(void)
675 {
676         d_printf("%s\n%s",
677                  _("Usage:"),
678                  _("net idmap set range"
679                    " <range> <SID> [<index>] [--db=<inputfile>]\n"
680                    "  Store a domain-range mapping for a given domain.\n"
681                    "    range\tRange number to be set for the domain\n"
682                    "    SID\t\tSID of the domain\n"
683                    "    index\trange-index number to be set for the domain\n"
684                    "    inputfile\tTDB file to add mapping to.\n"));
685 }
686
687 static int net_idmap_autorid_set_range(struct net_context *c,
688                                        int argc, const char **argv)
689 {
690         int ret = -1;
691         TALLOC_CTX *mem_ctx;
692         struct db_context *db = NULL;
693         const char *domsid;
694         uint32_t rangenum;
695         uint32_t range_index = 0;
696         NTSTATUS status;
697         bool ok;
698
699         if (c->display_usage) {
700                 net_idmap_autorid_set_range_usage();
701                 return 0;
702         }
703
704         if (argc < 2  || argc > 3) {
705                 net_idmap_autorid_set_range_usage();
706                 return -1;
707         }
708
709         ok = parse_uint32(argv[0], &rangenum);
710         if (!ok) {
711                 d_printf("%s: %s\n", _("Invalid range specification"),
712                          argv[0]);
713                 net_idmap_autorid_set_range_usage();
714                 return -1;
715         }
716
717         domsid = argv[1];
718
719         if (argc == 3) {
720                 ok = parse_uint32(argv[2], &range_index);
721                 if (!ok) {
722                         d_printf("%s: %s\n",
723                                  _("Invalid index specification"), argv[2]);
724                         net_idmap_autorid_set_range_usage();
725                         return -1;
726                 }
727         }
728
729         mem_ctx = talloc_stackframe();
730         if (!net_idmap_opendb_autorid(mem_ctx, c, false, &db)) {
731                 goto done;
732         }
733
734         status = idmap_autorid_setrange(db, domsid, range_index, rangenum);
735         if (!NT_STATUS_IS_OK(status)) {
736                 d_fprintf(stderr, "%s: %s\n",
737                           _("Failed to save domain mapping"),
738                           nt_errstr(status));
739                 goto done;
740         }
741
742         ret = 0;
743
744 done:
745         TALLOC_FREE(mem_ctx);
746         return ret;
747 }
748
749 static bool idmap_store_secret(const char *backend,
750                                const char *domain,
751                                const char *identity,
752                                const char *secret)
753 {
754         char *tmp;
755         int r;
756         bool ret;
757
758         r = asprintf(&tmp, "IDMAP_%s_%s", backend, domain);
759
760         if (r < 0) return false;
761
762         /* make sure the key is case insensitive */
763         if (!strupper_m(tmp)) {
764                 free(tmp);
765                 return false;
766         }
767         ret = secrets_store_generic(tmp, identity, secret);
768
769         free(tmp);
770         return ret;
771 }
772
773
774 static int net_idmap_secret(struct net_context *c, int argc, const char **argv)
775 {
776         TALLOC_CTX *ctx;
777         const char *secret;
778         const char *dn;
779         char *domain;
780         char *backend;
781         char *opt = NULL;
782         bool ret;
783
784         if (argc != 2 || c->display_usage) {
785                 d_printf("%s\n%s",
786                          _("Usage:\n"),
787                          _("net idmap set secret <DOMAIN> <secret>\n"
788                            "  Set the secret for the specified domain\n"
789                            "    DOMAIN\tDomain to set secret for.\n"
790                            "    secret\tNew secret to set.\n"));
791                 return c->display_usage?0:-1;
792         }
793
794         secret = argv[1];
795
796         ctx = talloc_new(NULL);
797         ALLOC_CHECK(ctx);
798
799         domain = talloc_strdup(ctx, argv[0]);
800         ALLOC_CHECK(domain);
801
802         opt = talloc_asprintf(ctx, "idmap config %s", domain);
803         ALLOC_CHECK(opt);
804
805         backend = talloc_strdup(ctx, lp_parm_const_string(-1, opt, "backend", "tdb"));
806         ALLOC_CHECK(backend);
807
808         if ((!backend) || (!strequal(backend, "ldap") &&
809                            !strequal(backend, "rfc2307"))) {
810                 d_fprintf(stderr,
811                           _("The only currently supported backend are LDAP "
812                             "and rfc2307\n"));
813                 talloc_free(ctx);
814                 return -1;
815         }
816
817         dn = lp_parm_const_string(-1, opt, "ldap_user_dn", NULL);
818         if ( ! dn) {
819                 d_fprintf(stderr,
820                           _("Missing ldap_user_dn option for domain %s\n"),
821                           domain);
822                 talloc_free(ctx);
823                 return -1;
824         }
825
826         ret = idmap_store_secret("ldap", domain, dn, secret);
827
828         if ( ! ret) {
829                 d_fprintf(stderr, _("Failed to store secret\n"));
830                 talloc_free(ctx);
831                 return -1;
832         }
833
834         d_printf(_("Secret stored\n"));
835         return 0;
836 }
837
838 static int net_idmap_autorid_set_config(struct net_context *c,
839                                         int argc, const char **argv)
840 {
841         int ret = -1;
842         NTSTATUS status;
843         TALLOC_CTX *mem_ctx;
844         struct db_context *db = NULL;
845
846         if (argc != 1 || c->display_usage) {
847                 d_printf("%s\n%s",
848                          _("Usage:"),
849                          _("net idmap set config <config>"
850                            " [--db=<inputfile>]\n"
851                            " Update CONFIG entry in autorid.\n"
852                            "    config\tConfig string to be stored\n"
853                            "    inputfile\tTDB file to update config.\n"));
854                 return c->display_usage ? 0 : -1;
855         }
856
857         mem_ctx = talloc_stackframe();
858
859         if (!net_idmap_opendb_autorid(mem_ctx, c, false, &db)) {
860                 goto done;
861         }
862
863         status = idmap_autorid_saveconfigstr(db, argv[0]);
864         if (!NT_STATUS_IS_OK(status)) {
865                 printf("Error storing the config in the database: %s\n",
866                        nt_errstr(status));
867                 goto done;
868         }
869
870         ret = 0;
871
872 done:
873         TALLOC_FREE(mem_ctx);
874         return ret;
875 }
876
877 static int net_idmap_set(struct net_context *c, int argc, const char **argv)
878 {
879         struct functable func[] = {
880                 {
881                         "mapping",
882                         net_idmap_set_mapping,
883                         NET_TRANSPORT_LOCAL,
884                         N_("Not implemented yet"),
885                         N_("net idmap set mapping\n"
886                            "  Not implemented yet")
887                 },
888                 {
889                         "range",
890                         net_idmap_autorid_set_range,
891                         NET_TRANSPORT_LOCAL,
892                         N_("Store a domain-range mapping"),
893                         N_("net idmap set range\n"
894                            "  Store a domain-range mapping")
895                 },
896                 {
897                         "config",
898                         net_idmap_autorid_set_config,
899                         NET_TRANSPORT_LOCAL,
900                         N_("Save the global configuration in the autorid database"),
901                         N_("net idmap set config \n"
902                            "  Save the global configuration in the autorid database ")
903                 },
904                 {
905                         "secret",
906                         net_idmap_secret,
907                         NET_TRANSPORT_LOCAL,
908                         N_("Set secret for specified domain"),
909                         N_("net idmap set secret <DOMAIN> <secret>\n"
910                            "  Set secret for specified domain")
911                 },
912                 {NULL, NULL, 0, NULL, NULL}
913         };
914
915         return net_run_function(c, argc, argv, "net idmap set", func);
916 }
917
918 static int net_idmap_autorid_get_config(struct net_context *c, int argc,
919                                         const char **argv)
920 {
921         int ret = -1;
922         char *config;
923         TALLOC_CTX *mem_ctx;
924         NTSTATUS status;
925         struct db_context *db = NULL;
926
927         if (argc > 0 || c->display_usage) {
928                 d_printf("%s\n%s",
929                          _("Usage:"),
930                          _("net idmap get config"
931                            " [--db=<inputfile>]\n"
932                            " Get CONFIG entry from autorid database\n"
933                            "    inputfile\tTDB file to read config from.\n"));
934                 return c->display_usage ? 0 : -1;
935         }
936
937         mem_ctx = talloc_stackframe();
938
939         if (!net_idmap_opendb_autorid(mem_ctx, c, true, &db)) {
940                 goto done;
941         }
942
943         status = idmap_autorid_getconfigstr(db, mem_ctx, &config);
944         if (!NT_STATUS_IS_OK(status)) {
945                 d_fprintf(stderr, "%s: %s\n",
946                           _("Error: unable to read config entry"),
947                           nt_errstr(status));
948                 goto done;
949         }
950
951         printf("CONFIG: %s\n", config);
952         ret = 0;
953
954 done:
955         TALLOC_FREE(mem_ctx);
956         return ret;
957 }
958
959
960 static int net_idmap_get(struct net_context *c, int argc, const char **argv)
961 {
962         struct functable func[] = {
963                 {
964                         "config",
965                         net_idmap_autorid_get_config,
966                         NET_TRANSPORT_LOCAL,
967                         N_("Get the global configuration from the autorid database"),
968                         N_("net idmap get config \n"
969                            "  Get the global configuration from the autorid database ")
970                 },
971                 {NULL, NULL, 0, NULL, NULL}
972         };
973
974         return net_run_function(c, argc, argv, "net idmap get", func);
975 }
976
977 static int net_idmap_check(struct net_context *c, int argc, const char **argv)
978 {
979         const char* dbfile;
980         struct check_options opts;
981         struct net_idmap_ctx ctx = { .backend = TDB };
982
983         if ( argc > 1 || c->display_usage) {
984                 d_printf("%s\n%s",
985                          _("Usage:"),
986                          _("net idmap check  [-v] [-r] [-a] [-T] [-f] [-l] [[--db=]<TDB>]\n"
987                            "  Check an idmap database.\n"
988                            "    --verbose,-v\tverbose\n"
989                            "    --repair,-r\trepair\n"
990                            "    --auto,-a\tnoninteractive mode\n"
991                            "    --test,-T\tdry run\n"
992                            "    --fore,-f\tforce\n"
993                            "    --lock,-l\tlock db while doing the check\n"
994                            "    TDB\tidmap database\n"));
995                 return c->display_usage ? 0 : -1;
996         }
997
998         dbfile = (argc > 0) ? argv[0] : net_idmap_dbfile(c, &ctx);
999         if (dbfile == NULL) {
1000                 return -1;
1001         }
1002
1003         if (ctx.backend != TDB) {
1004                 d_fprintf(stderr, _("Sorry, checking of non-TDB databases is "
1005                                     "currently not supported\n"));
1006                 return -1;
1007         }
1008
1009         d_fprintf(stderr, _("check database: %s\n"), dbfile);
1010
1011         opts = (struct check_options) {
1012                 .lock = c->opt_lock || c->opt_long_list_entries,
1013                 .test = c->opt_testmode,
1014                 .automatic = c->opt_auto,
1015                 .verbose = c->opt_verbose,
1016                 .force = c->opt_force,
1017                 .repair = c->opt_repair || c->opt_reboot,
1018         };
1019
1020         return net_idmap_check_db(dbfile, &opts);
1021 }
1022
1023 /***********************************************************
1024  Look at the current idmap
1025  **********************************************************/
1026 int net_idmap(struct net_context *c, int argc, const char **argv)
1027 {
1028         struct functable func[] = {
1029                 {
1030                         "dump",
1031                         net_idmap_dump,
1032                         NET_TRANSPORT_LOCAL,
1033                         N_("Dump the current ID mapping database"),
1034                         N_("net idmap dump\n"
1035                            "  Dump the current ID mappings")
1036                 },
1037                 {
1038                         "restore",
1039                         net_idmap_restore,
1040                         NET_TRANSPORT_LOCAL,
1041                         N_("Restore entries from a file or stdin"),
1042                         N_("net idmap restore\n"
1043                            "  Restore entries from stdin")
1044                 },
1045                 {
1046                         "get",
1047                         net_idmap_get,
1048                         NET_TRANSPORT_LOCAL,
1049                         N_("Read data from the ID mapping database"),
1050                         N_("net idmap get\n"
1051                            "  Read data from the ID mapping database")
1052                 },
1053                 {
1054                         "set",
1055                         net_idmap_set,
1056                         NET_TRANSPORT_LOCAL,
1057                         N_("Write data to the ID mapping database"),
1058                         N_("net idmap set\n"
1059                            "  Write data to the ID mapping database")
1060                 },
1061                 {
1062                         "delete",
1063                         net_idmap_delete,
1064                         NET_TRANSPORT_LOCAL,
1065                         N_("Delete entries from the ID mapping database"),
1066                         N_("net idmap delete\n"
1067                            "  Delete entries from the ID mapping database")
1068                 },
1069                 {
1070                         "secret",
1071                         net_idmap_secret,
1072                         NET_TRANSPORT_LOCAL,
1073                         N_("Set secret for specified domain"),
1074                         N_("net idmap secret <DOMAIN> <secret>\n"
1075                            "  Set secret for specified domain")
1076                 },
1077                 {
1078                         "check",
1079                         net_idmap_check,
1080                         NET_TRANSPORT_LOCAL,
1081                         N_("Check id mappings"),
1082                         N_("net idmap check\n"
1083                            "  Check id mappings")
1084                 },
1085                 {NULL, NULL, 0, NULL, NULL}
1086         };
1087
1088         return net_run_function(c, argc, argv, "net idmap", func);
1089 }
1090
1091