lib: Pass mem_ctx to state_path()
[amitay/samba.git] / source3 / winbindd / idmap_tdb_common.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    common functions for TDB based idmapping backends
5
6    Copyright (C) Christian Ambach 2012
7
8    These functions were initially copied over from idmap_tdb.c and idmap_tdb2.c
9    which are:
10
11    Copyright (C) Tim Potter 2000
12    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
13    Copyright (C) Jeremy Allison 2006
14    Copyright (C) Simo Sorce 2003-2006
15    Copyright (C) Michael Adam 2009-2010
16    Copyright (C) Andrew Tridgell 2007
17
18    This program is free software; you can redistribute it and/or modify
19    it under the terms of the GNU General Public License as published by
20    the Free Software Foundation; either version 2 of the License, or
21    (at your option) any later version.
22
23    This program is distributed in the hope that it will be useful,
24    but WITHOUT ANY WARRANTY; without even the implied warranty of
25    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26    GNU General Public License for more details.
27
28    You should have received a copy of the GNU General Public License
29    along with this program; if not, write to the Free Software
30    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 */
32
33 #include "includes.h"
34 #include "idmap_tdb_common.h"
35 #include "dbwrap/dbwrap.h"
36 #include "util_tdb.h"
37 #include "idmap_rw.h"
38 #include "../libcli/security/dom_sid.h"
39
40 #undef DBGC_CLASS
41 #define DBGC_CLASS DBGC_IDMAP
42
43 struct idmap_tdb_common_allocate_id_context {
44         const char *hwmkey;
45         const char *hwmtype;
46         uint32_t high_hwm;
47         uint32_t hwm;
48 };
49
50 static NTSTATUS idmap_tdb_common_allocate_id_action(struct db_context *db,
51                                                     void *private_data)
52 {
53         NTSTATUS ret;
54         struct idmap_tdb_common_allocate_id_context *state = private_data;
55         uint32_t hwm;
56
57         ret = dbwrap_fetch_uint32_bystring(db, state->hwmkey, &hwm);
58         if (!NT_STATUS_IS_OK(ret)) {
59                 ret = NT_STATUS_INTERNAL_DB_ERROR;
60                 goto done;
61         }
62
63         /* check it is in the range */
64         if (hwm > state->high_hwm) {
65                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n",
66                           state->hwmtype, (unsigned long)state->high_hwm));
67                 ret = NT_STATUS_UNSUCCESSFUL;
68                 goto done;
69         }
70
71         /* fetch a new id and increment it */
72         ret = dbwrap_change_uint32_atomic_bystring(db, state->hwmkey, &hwm, 1);
73         if (!NT_STATUS_IS_OK(ret)) {
74                 DEBUG(1, ("Fatal error while fetching a new %s value\n!",
75                           state->hwmtype));
76                 goto done;
77         }
78
79         /* recheck it is in the range */
80         if (hwm > state->high_hwm) {
81                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n",
82                           state->hwmtype, (unsigned long)state->high_hwm));
83                 ret = NT_STATUS_UNSUCCESSFUL;
84                 goto done;
85         }
86
87         ret = NT_STATUS_OK;
88         state->hwm = hwm;
89
90       done:
91         return ret;
92 }
93
94 static NTSTATUS idmap_tdb_common_allocate_id(struct idmap_domain *dom,
95                                              struct unixid *xid)
96 {
97         const char *hwmkey;
98         const char *hwmtype;
99         uint32_t hwm = 0;
100         NTSTATUS status;
101         struct idmap_tdb_common_allocate_id_context state;
102         struct idmap_tdb_common_context *ctx;
103
104         ctx =
105             talloc_get_type_abort(dom->private_data,
106                                   struct idmap_tdb_common_context);
107
108         /* Get current high water mark */
109         switch (xid->type) {
110
111         case ID_TYPE_UID:
112                 hwmkey = ctx->hwmkey_uid;
113                 hwmtype = "UID";
114                 break;
115
116         case ID_TYPE_GID:
117                 hwmkey = ctx->hwmkey_gid;
118                 hwmtype = "GID";
119                 break;
120
121         default:
122                 DEBUG(2, ("Invalid ID type (0x%x)\n", xid->type));
123                 return NT_STATUS_INVALID_PARAMETER;
124         }
125
126         state.hwm = hwm;
127         state.high_hwm = ctx->max_id;
128         state.hwmtype = hwmtype;
129         state.hwmkey = hwmkey;
130
131         status = dbwrap_trans_do(ctx->db, idmap_tdb_common_allocate_id_action,
132                                  &state);
133
134         if (NT_STATUS_IS_OK(status)) {
135                 xid->id = state.hwm;
136                 DEBUG(10, ("New %s = %d\n", hwmtype, state.hwm));
137         } else {
138                 DEBUG(1, ("Error allocating a new %s\n", hwmtype));
139         }
140
141         return status;
142 }
143
144 /**
145  * Allocate a new unix-ID.
146  * For now this is for the default idmap domain only.
147  * Should be extended later on.
148  */
149 NTSTATUS idmap_tdb_common_get_new_id(struct idmap_domain * dom,
150                                      struct unixid * id)
151 {
152         NTSTATUS ret;
153
154         if (!strequal(dom->name, "*")) {
155                 DEBUG(3, ("idmap_tdb_common_get_new_id: "
156                           "Refusing allocation of a new unixid for domain'%s'. "
157                           "Currently only supported for the default "
158                           "domain \"*\".\n", dom->name));
159                 return NT_STATUS_NOT_IMPLEMENTED;
160         }
161
162         ret = idmap_tdb_common_allocate_id(dom, id);
163
164         return ret;
165 }
166
167 /**
168  * store a mapping in the database.
169  */
170
171 struct idmap_tdb_common_set_mapping_context {
172         const char *ksidstr;
173         const char *kidstr;
174 };
175
176 static NTSTATUS idmap_tdb_common_set_mapping_action(struct db_context *db,
177                                                     void *private_data)
178 {
179         TDB_DATA data;
180         NTSTATUS ret;
181         struct idmap_tdb_common_set_mapping_context *state = private_data;
182         TALLOC_CTX *tmp_ctx = talloc_stackframe();
183
184         DEBUG(10, ("Storing %s <-> %s map\n", state->ksidstr, state->kidstr));
185
186         /* check whether sid mapping is already present in db */
187         ret = dbwrap_fetch_bystring(db, tmp_ctx, state->ksidstr, &data);
188         if (NT_STATUS_IS_OK(ret)) {
189                 ret = NT_STATUS_OBJECT_NAME_COLLISION;
190                 goto done;
191         }
192
193         ret = dbwrap_store_bystring(db, state->ksidstr,
194                                     string_term_tdb_data(state->kidstr),
195                                     TDB_INSERT);
196         if (!NT_STATUS_IS_OK(ret)) {
197                 DEBUG(0, ("Error storing SID -> ID: %s\n", nt_errstr(ret)));
198                 goto done;
199         }
200
201         ret = dbwrap_store_bystring(db, state->kidstr,
202                                     string_term_tdb_data(state->ksidstr),
203                                     TDB_INSERT);
204         if (!NT_STATUS_IS_OK(ret)) {
205                 DEBUG(0, ("Error storing ID -> SID: %s\n", nt_errstr(ret)));
206                 /* try to remove the previous stored SID -> ID map */
207                 dbwrap_delete_bystring(db, state->ksidstr);
208                 goto done;
209         }
210
211         DEBUG(10, ("Stored %s <-> %s\n", state->ksidstr, state->kidstr));
212
213       done:
214         talloc_free(tmp_ctx);
215         return ret;
216 }
217
218 NTSTATUS idmap_tdb_common_set_mapping(struct idmap_domain * dom,
219                                       const struct id_map * map)
220 {
221         struct idmap_tdb_common_context *ctx;
222         struct idmap_tdb_common_set_mapping_context state;
223         NTSTATUS ret;
224         char *ksidstr = NULL;
225         char *kidstr = NULL;
226
227         if (!map || !map->sid) {
228                 return NT_STATUS_INVALID_PARAMETER;
229         }
230
231         /* TODO: should we filter a set_mapping using low/high filters ? */
232
233         ctx =
234             talloc_get_type_abort(dom->private_data,
235                                   struct idmap_tdb_common_context);
236
237         switch (map->xid.type) {
238
239         case ID_TYPE_UID:
240                 kidstr =
241                     talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
242                 break;
243
244         case ID_TYPE_GID:
245                 kidstr =
246                     talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
247                 break;
248
249         default:
250                 DEBUG(2, ("INVALID unix ID type: 0x%02x\n", map->xid.type));
251                 return NT_STATUS_INVALID_PARAMETER;
252         }
253
254         if (kidstr == NULL) {
255                 DEBUG(0, ("ERROR: Out of memory!\n"));
256                 ret = NT_STATUS_NO_MEMORY;
257                 goto done;
258         }
259
260         ksidstr = sid_string_talloc(ctx, map->sid);
261         if (ksidstr == NULL) {
262                 DEBUG(0, ("Out of memory!\n"));
263                 ret = NT_STATUS_NO_MEMORY;
264                 goto done;
265         }
266
267         state.ksidstr = ksidstr;
268         state.kidstr = kidstr;
269
270         ret = dbwrap_trans_do(ctx->db, idmap_tdb_common_set_mapping_action,
271                               &state);
272
273       done:
274         talloc_free(ksidstr);
275         talloc_free(kidstr);
276         return ret;
277 }
278
279 /*
280  * Create a new mapping for an unmapped SID, also allocating a new ID.
281  * This should be run inside a transaction.
282  *
283  * TODO:
284  *  Properly integrate this with multi domain idmap config:
285  *  Currently, the allocator is default-config only.
286  */
287 NTSTATUS idmap_tdb_common_new_mapping(struct idmap_domain * dom,
288                                       struct id_map * map)
289 {
290         NTSTATUS ret;
291         struct idmap_tdb_common_context *ctx;
292
293         ctx =
294             talloc_get_type_abort(dom->private_data,
295                                   struct idmap_tdb_common_context);
296
297         ret = idmap_rw_new_mapping(dom, ctx->rw_ops, map);
298
299         return ret;
300 }
301
302 /*
303   lookup a set of unix ids
304 */
305 NTSTATUS idmap_tdb_common_unixids_to_sids(struct idmap_domain * dom,
306                                           struct id_map ** ids)
307 {
308         NTSTATUS ret;
309         size_t i, num_mapped = 0;
310         struct idmap_tdb_common_context *ctx;
311
312         NTSTATUS(*unixid_to_sid_fn) (struct idmap_domain * dom,
313                                      struct id_map * map);
314         ctx =
315             talloc_get_type_abort(dom->private_data,
316                                   struct idmap_tdb_common_context);
317
318         if (ctx->unixid_to_sid_fn == NULL) {
319                 unixid_to_sid_fn = idmap_tdb_common_unixid_to_sid;
320         } else {
321                 unixid_to_sid_fn = ctx->unixid_to_sid_fn;
322         }
323
324         /* initialize the status to avoid surprise */
325         for (i = 0; ids[i]; i++) {
326                 ids[i]->status = ID_UNKNOWN;
327         }
328
329         for (i = 0; ids[i]; i++) {
330                 ret = unixid_to_sid_fn(dom, ids[i]);
331                 if (!NT_STATUS_IS_OK(ret)) {
332
333                         /* if it is just a failed mapping continue */
334                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
335
336                                 /* make sure it is marked as unmapped */
337                                 ids[i]->status = ID_UNMAPPED;
338                                 continue;
339                         }
340
341                         /* some fatal error occurred, return immediately */
342                         goto done;
343                 }
344
345                 /* all ok, id is mapped */
346                 ids[i]->status = ID_MAPPED;
347                 num_mapped += 1;
348         }
349
350         ret = NT_STATUS_OK;
351
352 done:
353
354         if (NT_STATUS_IS_OK(ret)) {
355                 if (i == 0 || num_mapped == 0) {
356                         ret = NT_STATUS_NONE_MAPPED;
357                 } else if (num_mapped < i) {
358                         ret = STATUS_SOME_UNMAPPED;
359                 } else {
360                         ret = NT_STATUS_OK;
361                 }
362         }
363
364         return ret;
365 }
366
367 /*
368   default single id to sid lookup function
369 */
370 NTSTATUS idmap_tdb_common_unixid_to_sid(struct idmap_domain * dom,
371                                         struct id_map * map)
372 {
373         NTSTATUS ret;
374         TDB_DATA data;
375         char *keystr;
376         struct idmap_tdb_common_context *ctx;
377
378         if (!dom || !map) {
379                 return NT_STATUS_INVALID_PARAMETER;
380         }
381
382         ctx =
383             talloc_get_type_abort(dom->private_data,
384                                   struct idmap_tdb_common_context);
385
386         /* apply filters before checking */
387         if (!idmap_unix_id_is_in_range(map->xid.id, dom)) {
388                 DEBUG(5,
389                       ("Requested id (%u) out of range (%u - %u). Filtered!\n",
390                        map->xid.id, dom->low_id, dom->high_id));
391                 return NT_STATUS_NONE_MAPPED;
392         }
393
394         switch (map->xid.type) {
395
396         case ID_TYPE_UID:
397                 keystr =
398                     talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
399                 break;
400
401         case ID_TYPE_GID:
402                 keystr =
403                     talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
404                 break;
405
406         default:
407                 DEBUG(2, ("INVALID unix ID type: 0x%02x\n", map->xid.type));
408                 return NT_STATUS_INVALID_PARAMETER;
409         }
410
411         if (keystr == NULL) {
412                 DEBUG(0, ("Out of memory!\n"));
413                 ret = NT_STATUS_NO_MEMORY;
414                 goto done;
415         }
416
417         DEBUG(10, ("Fetching record %s\n", keystr));
418
419         /* Check if the mapping exists */
420         ret = dbwrap_fetch_bystring(ctx->db, keystr, keystr, &data);
421
422         if (!NT_STATUS_IS_OK(ret)) {
423                 DEBUG(10, ("Record %s not found\n", keystr));
424                 ret = NT_STATUS_NONE_MAPPED;
425                 goto done;
426         }
427
428         if ((data.dsize == 0) || (data.dptr[data.dsize-1] != '\0')) {
429                 DBG_DEBUG("Invalid record length %zu\n", data.dsize);
430                 ret = NT_STATUS_INTERNAL_DB_ERROR;
431                 goto done;
432         }
433
434         if (!string_to_sid(map->sid, (const char *)data.dptr)) {
435                 DEBUG(10, ("INVALID SID (%s) in record %s\n",
436                            (const char *)data.dptr, keystr));
437                 ret = NT_STATUS_INTERNAL_DB_ERROR;
438                 goto done;
439         }
440
441         DEBUG(10, ("Found record %s -> %s\n", keystr, (const char *)data.dptr));
442         ret = NT_STATUS_OK;
443
444       done:
445         talloc_free(keystr);
446         return ret;
447 }
448
449 /**********************************
450  Single sid to id lookup function.
451 **********************************/
452
453 NTSTATUS idmap_tdb_common_sid_to_unixid(struct idmap_domain * dom,
454                                         struct id_map * map)
455 {
456         NTSTATUS ret;
457         TDB_DATA data;
458         char *keystr;
459         unsigned long rec_id = 0;
460         struct idmap_tdb_common_context *ctx;
461         TALLOC_CTX *tmp_ctx = talloc_stackframe();
462
463         if (!dom || !map) {
464                 talloc_free(tmp_ctx);
465                 return NT_STATUS_INVALID_PARAMETER;
466         }
467
468         ctx =
469             talloc_get_type_abort(dom->private_data,
470                                   struct idmap_tdb_common_context);
471
472         keystr = sid_string_talloc(tmp_ctx, map->sid);
473         if (keystr == NULL) {
474                 DEBUG(0, ("Out of memory!\n"));
475                 ret = NT_STATUS_NO_MEMORY;
476                 goto done;
477         }
478
479         DEBUG(10, ("Fetching record %s\n", keystr));
480
481         /* Check if sid is present in database */
482         ret = dbwrap_fetch_bystring(ctx->db, tmp_ctx, keystr, &data);
483         if (!NT_STATUS_IS_OK(ret)) {
484                 DEBUG(10, ("Record %s not found\n", keystr));
485                 ret = NT_STATUS_NONE_MAPPED;
486                 goto done;
487         }
488
489         /* What type of record is this ? */
490         if (sscanf((const char *)data.dptr, "UID %lu", &rec_id) == 1) {
491                 /* Try a UID record. */
492                 map->xid.id = rec_id;
493                 map->xid.type = ID_TYPE_UID;
494                 DEBUG(10,
495                       ("Found uid record %s -> %s \n", keystr,
496                        (const char *)data.dptr));
497                 ret = NT_STATUS_OK;
498
499         } else if (sscanf((const char *)data.dptr, "GID %lu", &rec_id) == 1) {
500                 /* Try a GID record. */
501                 map->xid.id = rec_id;
502                 map->xid.type = ID_TYPE_GID;
503                 DEBUG(10,
504                       ("Found gid record %s -> %s \n", keystr,
505                        (const char *)data.dptr));
506                 ret = NT_STATUS_OK;
507
508         } else {                /* Unknown record type ! */
509                 DEBUG(2,
510                       ("Found INVALID record %s -> %s\n", keystr,
511                        (const char *)data.dptr));
512                 ret = NT_STATUS_INTERNAL_DB_ERROR;
513                 goto done;
514         }
515
516         /* apply filters before returning result */
517         if (!idmap_unix_id_is_in_range(map->xid.id, dom)) {
518                 DEBUG(5,
519                       ("Requested id (%u) out of range (%u - %u). Filtered!\n",
520                        map->xid.id, dom->low_id, dom->high_id));
521                 ret = NT_STATUS_NONE_MAPPED;
522         }
523
524       done:
525         talloc_free(tmp_ctx);
526         return ret;
527 }
528
529 /**********************************
530  lookup a set of sids
531 **********************************/
532
533 struct idmap_tdb_common_sids_to_unixids_context {
534         struct idmap_domain *dom;
535         struct id_map **ids;
536         bool allocate_unmapped;
537          NTSTATUS(*sid_to_unixid_fn) (struct idmap_domain * dom,
538                                       struct id_map * map);
539 };
540
541 static NTSTATUS idmap_tdb_common_sids_to_unixids_action(struct db_context *db,
542                                                         void *private_data)
543 {
544         struct idmap_tdb_common_sids_to_unixids_context *state = private_data;
545         size_t i, num_mapped = 0;
546         NTSTATUS ret = NT_STATUS_OK;
547
548         DEBUG(10, ("idmap_tdb_common_sids_to_unixids: "
549                    " domain: [%s], allocate: %s\n",
550                    state->dom->name, state->allocate_unmapped ? "yes" : "no"));
551
552         for (i = 0; state->ids[i]; i++) {
553                 if ((state->ids[i]->status == ID_UNKNOWN) ||
554                     /* retry if we could not map in previous run: */
555                     (state->ids[i]->status == ID_UNMAPPED)) {
556                         NTSTATUS ret2;
557
558                         ret2 = state->sid_to_unixid_fn(state->dom,
559                                         state->ids[i]);
560
561                         if (!NT_STATUS_IS_OK(ret2)) {
562
563                                 /* if it is just a failed mapping, continue */
564                                 if (NT_STATUS_EQUAL
565                                     (ret2, NT_STATUS_NONE_MAPPED)) {
566
567                                         /* make sure it is marked as unmapped */
568                                         state->ids[i]->status = ID_UNMAPPED;
569                                         ret = STATUS_SOME_UNMAPPED;
570                                 } else {
571                                         /*
572                                          * some fatal error occurred,
573                                          * return immediately
574                                          */
575                                         ret = ret2;
576                                         goto done;
577                                 }
578                         } else {
579                                 /* all ok, id is mapped */
580                                 state->ids[i]->status = ID_MAPPED;
581                         }
582                 }
583
584                 if (state->ids[i]->status == ID_MAPPED) {
585                         num_mapped += 1;
586                 }
587
588                 if ((state->ids[i]->status == ID_UNMAPPED) &&
589                     state->allocate_unmapped) {
590                         ret =
591                             idmap_tdb_common_new_mapping(state->dom,
592                                                          state->ids[i]);
593                         if (!NT_STATUS_IS_OK(ret)) {
594                                 goto done;
595                         }
596                         num_mapped += 1;
597                 }
598         }
599
600 done:
601
602         if (NT_STATUS_IS_OK(ret) ||
603             NT_STATUS_EQUAL(ret, STATUS_SOME_UNMAPPED)) {
604                 if (i == 0 || num_mapped == 0) {
605                         ret = NT_STATUS_NONE_MAPPED;
606                 } else if (num_mapped < i) {
607                         ret = STATUS_SOME_UNMAPPED;
608                 } else {
609                         ret = NT_STATUS_OK;
610                 }
611         }
612
613         return ret;
614 }
615
616 NTSTATUS idmap_tdb_common_sids_to_unixids(struct idmap_domain * dom,
617                                           struct id_map ** ids)
618 {
619         NTSTATUS ret;
620         int i;
621         struct idmap_tdb_common_sids_to_unixids_context state;
622         struct idmap_tdb_common_context *ctx;
623
624         ctx =
625             talloc_get_type_abort(dom->private_data,
626                                   struct idmap_tdb_common_context);
627
628         /* initialize the status to avoid surprise */
629         for (i = 0; ids[i]; i++) {
630                 ids[i]->status = ID_UNKNOWN;
631         }
632
633         state.dom = dom;
634         state.ids = ids;
635         state.allocate_unmapped = false;
636         if (ctx->sid_to_unixid_fn == NULL) {
637                 state.sid_to_unixid_fn = idmap_tdb_common_sid_to_unixid;
638         } else {
639                 state.sid_to_unixid_fn = ctx->sid_to_unixid_fn;
640         }
641
642         ret = idmap_tdb_common_sids_to_unixids_action(ctx->db, &state);
643
644         if ( (NT_STATUS_EQUAL(ret, STATUS_SOME_UNMAPPED) ||
645               NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) &&
646              !dom->read_only) {
647                 state.allocate_unmapped = true;
648                 ret = dbwrap_trans_do(ctx->db,
649                                       idmap_tdb_common_sids_to_unixids_action,
650                                       &state);
651         }
652
653         return ret;
654 }