smbXsrv: don't leak lock_path onto talloc tos
[samba.git] / source3 / smbd / smbXsrv_open.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Copyright (C) Stefan Metzmacher 2012
5    Copyright (C) Michael Adam 2012
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "system/filesys.h"
23 #include "smbd/smbd.h"
24 #include "smbd/globals.h"
25 #include "dbwrap/dbwrap.h"
26 #include "dbwrap/dbwrap_rbt.h"
27 #include "dbwrap/dbwrap_open.h"
28 #include "../libcli/security/security.h"
29 #include "messages.h"
30 #include "lib/util/util_tdb.h"
31 #include "librpc/gen_ndr/ndr_smbXsrv.h"
32 #include <ccan/hash/hash.h>
33 #include "serverid.h"
34
35 struct smbXsrv_open_table {
36         struct {
37                 struct db_context *db_ctx;
38                 uint32_t lowest_id;
39                 uint32_t highest_id;
40                 uint32_t max_opens;
41                 uint32_t num_opens;
42         } local;
43         struct {
44                 struct db_context *db_ctx;
45         } global;
46 };
47
48 static struct db_context *smbXsrv_open_global_db_ctx = NULL;
49
50 NTSTATUS smbXsrv_open_global_init(void)
51 {
52         char *global_path = NULL;
53         struct db_context *db_ctx = NULL;
54
55         if (smbXsrv_open_global_db_ctx != NULL) {
56                 return NT_STATUS_OK;
57         }
58
59         global_path = lock_path("smbXsrv_open_global.tdb");
60         if (global_path == NULL) {
61                 return NT_STATUS_NO_MEMORY;
62         }
63
64         db_ctx = db_open(NULL, global_path,
65                          0, /* hash_size */
66                          TDB_DEFAULT |
67                          TDB_CLEAR_IF_FIRST |
68                          TDB_INCOMPATIBLE_HASH,
69                          O_RDWR | O_CREAT, 0600,
70                          DBWRAP_LOCK_ORDER_1,
71                          DBWRAP_FLAG_NONE);
72         TALLOC_FREE(global_path);
73         if (db_ctx == NULL) {
74                 NTSTATUS status;
75
76                 status = map_nt_error_from_unix_common(errno);
77
78                 return status;
79         }
80
81         smbXsrv_open_global_db_ctx = db_ctx;
82
83         return NT_STATUS_OK;
84 }
85
86 /*
87  * NOTE:
88  * We need to store the keys in big endian so that dbwrap_rbt's memcmp
89  * has the same result as integer comparison between the uint32_t
90  * values.
91  *
92  * TODO: implement string based key
93  */
94
95 #define SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE sizeof(uint32_t)
96
97 static TDB_DATA smbXsrv_open_global_id_to_key(uint32_t id,
98                                               uint8_t *key_buf)
99 {
100         TDB_DATA key;
101
102         RSIVAL(key_buf, 0, id);
103
104         key = make_tdb_data(key_buf, SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE);
105
106         return key;
107 }
108
109 #if 0
110 static NTSTATUS smbXsrv_open_global_key_to_id(TDB_DATA key, uint32_t *id)
111 {
112         if (id == NULL) {
113                 return NT_STATUS_INVALID_PARAMETER;
114         }
115
116         if (key.dsize != SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE) {
117                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
118         }
119
120         *id = RIVAL(key.dptr, 0);
121
122         return NT_STATUS_OK;
123 }
124 #endif
125
126 #define SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE sizeof(uint32_t)
127
128 static TDB_DATA smbXsrv_open_local_id_to_key(uint32_t id,
129                                              uint8_t *key_buf)
130 {
131         TDB_DATA key;
132
133         RSIVAL(key_buf, 0, id);
134
135         key = make_tdb_data(key_buf, SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE);
136
137         return key;
138 }
139
140 static NTSTATUS smbXsrv_open_local_key_to_id(TDB_DATA key, uint32_t *id)
141 {
142         if (id == NULL) {
143                 return NT_STATUS_INVALID_PARAMETER;
144         }
145
146         if (key.dsize != SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE) {
147                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
148         }
149
150         *id = RIVAL(key.dptr, 0);
151
152         return NT_STATUS_OK;
153 }
154
155 static NTSTATUS smbXsrv_open_table_init(struct smbXsrv_connection *conn,
156                                         uint32_t lowest_id,
157                                         uint32_t highest_id,
158                                         uint32_t max_opens)
159 {
160         struct smbXsrv_client *client = conn->client;
161         struct smbXsrv_open_table *table;
162         NTSTATUS status;
163         uint64_t max_range;
164
165         if (lowest_id > highest_id) {
166                 return NT_STATUS_INTERNAL_ERROR;
167         }
168
169         max_range = highest_id;
170         max_range -= lowest_id;
171         max_range += 1;
172
173         if (max_opens > max_range) {
174                 return NT_STATUS_INTERNAL_ERROR;
175         }
176
177         table = talloc_zero(client, struct smbXsrv_open_table);
178         if (table == NULL) {
179                 return NT_STATUS_NO_MEMORY;
180         }
181
182         table->local.db_ctx = db_open_rbt(table);
183         if (table->local.db_ctx == NULL) {
184                 TALLOC_FREE(table);
185                 return NT_STATUS_NO_MEMORY;
186         }
187         table->local.lowest_id = lowest_id;
188         table->local.highest_id = highest_id;
189         table->local.max_opens = max_opens;
190
191         status = smbXsrv_open_global_init();
192         if (!NT_STATUS_IS_OK(status)) {
193                 TALLOC_FREE(table);
194                 return status;
195         }
196
197         table->global.db_ctx = smbXsrv_open_global_db_ctx;
198
199         client->open_table = table;
200         return NT_STATUS_OK;
201 }
202
203 struct smbXsrv_open_local_allocate_state {
204         const uint32_t lowest_id;
205         const uint32_t highest_id;
206         uint32_t last_id;
207         uint32_t useable_id;
208         NTSTATUS status;
209 };
210
211 static int smbXsrv_open_local_allocate_traverse(struct db_record *rec,
212                                                    void *private_data)
213 {
214         struct smbXsrv_open_local_allocate_state *state =
215                 (struct smbXsrv_open_local_allocate_state *)private_data;
216         TDB_DATA key = dbwrap_record_get_key(rec);
217         uint32_t id = 0;
218         NTSTATUS status;
219
220         status = smbXsrv_open_local_key_to_id(key, &id);
221         if (!NT_STATUS_IS_OK(status)) {
222                 state->status = status;
223                 return -1;
224         }
225
226         if (id <= state->last_id) {
227                 state->status = NT_STATUS_INTERNAL_DB_CORRUPTION;
228                 return -1;
229         }
230         state->last_id = id;
231
232         if (id > state->useable_id) {
233                 state->status = NT_STATUS_OK;
234                 return -1;
235         }
236
237         if (state->useable_id == state->highest_id) {
238                 state->status = NT_STATUS_INSUFFICIENT_RESOURCES;
239                 return -1;
240         }
241
242         state->useable_id +=1;
243         return 0;
244 }
245
246 static NTSTATUS smbXsrv_open_local_allocate_id(struct db_context *db,
247                                                uint32_t lowest_id,
248                                                uint32_t highest_id,
249                                                TALLOC_CTX *mem_ctx,
250                                                struct db_record **_rec,
251                                                uint32_t *_id)
252 {
253         struct smbXsrv_open_local_allocate_state state = {
254                 .lowest_id = lowest_id,
255                 .highest_id = highest_id,
256                 .last_id = 0,
257                 .useable_id = lowest_id,
258                 .status = NT_STATUS_INTERNAL_ERROR,
259         };
260         uint32_t i;
261         uint32_t range;
262         NTSTATUS status;
263         int count = 0;
264
265         *_rec = NULL;
266         *_id = 0;
267
268         if (lowest_id > highest_id) {
269                 return NT_STATUS_INSUFFICIENT_RESOURCES;
270         }
271
272         /*
273          * first we try randomly
274          */
275         range = (highest_id - lowest_id) + 1;
276
277         for (i = 0; i < (range / 2); i++) {
278                 uint32_t id;
279                 uint8_t key_buf[SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE];
280                 TDB_DATA key;
281                 TDB_DATA val;
282                 struct db_record *rec = NULL;
283
284                 id = generate_random() % range;
285                 id += lowest_id;
286
287                 if (id < lowest_id) {
288                         id = lowest_id;
289                 }
290                 if (id > highest_id) {
291                         id = highest_id;
292                 }
293
294                 key = smbXsrv_open_local_id_to_key(id, key_buf);
295
296                 rec = dbwrap_fetch_locked(db, mem_ctx, key);
297                 if (rec == NULL) {
298                         return NT_STATUS_INSUFFICIENT_RESOURCES;
299                 }
300
301                 val = dbwrap_record_get_value(rec);
302                 if (val.dsize != 0) {
303                         TALLOC_FREE(rec);
304                         continue;
305                 }
306
307                 *_rec = rec;
308                 *_id = id;
309                 return NT_STATUS_OK;
310         }
311
312         /*
313          * if the range is almost full,
314          * we traverse the whole table
315          * (this relies on sorted behavior of dbwrap_rbt)
316          */
317         status = dbwrap_traverse_read(db, smbXsrv_open_local_allocate_traverse,
318                                       &state, &count);
319         if (NT_STATUS_IS_OK(status)) {
320                 if (NT_STATUS_IS_OK(state.status)) {
321                         return NT_STATUS_INTERNAL_ERROR;
322                 }
323
324                 if (!NT_STATUS_EQUAL(state.status, NT_STATUS_INTERNAL_ERROR)) {
325                         return state.status;
326                 }
327
328                 if (state.useable_id <= state.highest_id) {
329                         state.status = NT_STATUS_OK;
330                 } else {
331                         return NT_STATUS_INSUFFICIENT_RESOURCES;
332                 }
333         } else if (!NT_STATUS_EQUAL(status, NT_STATUS_INTERNAL_DB_CORRUPTION)) {
334                 /*
335                  * Here we really expect NT_STATUS_INTERNAL_DB_CORRUPTION!
336                  *
337                  * If we get anything else it is an error, because it
338                  * means we did not manage to find a free slot in
339                  * the db.
340                  */
341                 return NT_STATUS_INSUFFICIENT_RESOURCES;
342         }
343
344         if (NT_STATUS_IS_OK(state.status)) {
345                 uint32_t id;
346                 uint8_t key_buf[SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE];
347                 TDB_DATA key;
348                 TDB_DATA val;
349                 struct db_record *rec = NULL;
350
351                 id = state.useable_id;
352
353                 key = smbXsrv_open_local_id_to_key(id, key_buf);
354
355                 rec = dbwrap_fetch_locked(db, mem_ctx, key);
356                 if (rec == NULL) {
357                         return NT_STATUS_INSUFFICIENT_RESOURCES;
358                 }
359
360                 val = dbwrap_record_get_value(rec);
361                 if (val.dsize != 0) {
362                         TALLOC_FREE(rec);
363                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
364                 }
365
366                 *_rec = rec;
367                 *_id = id;
368                 return NT_STATUS_OK;
369         }
370
371         return state.status;
372 }
373
374 struct smbXsrv_open_local_fetch_state {
375         struct smbXsrv_open *op;
376         NTSTATUS status;
377 };
378
379 static void smbXsrv_open_local_fetch_parser(TDB_DATA key, TDB_DATA data,
380                                             void *private_data)
381 {
382         struct smbXsrv_open_local_fetch_state *state =
383                 (struct smbXsrv_open_local_fetch_state *)private_data;
384         void *ptr;
385
386         if (data.dsize != sizeof(ptr)) {
387                 state->status = NT_STATUS_INTERNAL_DB_ERROR;
388                 return;
389         }
390
391         memcpy(&ptr, data.dptr, data.dsize);
392         state->op = talloc_get_type_abort(ptr, struct smbXsrv_open);
393         state->status = NT_STATUS_OK;
394 }
395
396 static NTSTATUS smbXsrv_open_local_lookup(struct smbXsrv_open_table *table,
397                                           uint32_t open_local_id,
398                                           uint32_t open_global_id,
399                                           NTTIME now,
400                                           struct smbXsrv_open **_open)
401 {
402         struct smbXsrv_open_local_fetch_state state = {
403                 .op = NULL,
404                 .status = NT_STATUS_INTERNAL_ERROR,
405         };
406         uint8_t key_buf[SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE];
407         TDB_DATA key;
408         NTSTATUS status;
409
410         *_open = NULL;
411
412         if (open_local_id == 0) {
413                 return NT_STATUS_FILE_CLOSED;
414         }
415
416         if (table == NULL) {
417                 /* this might happen before the end of negprot */
418                 return NT_STATUS_FILE_CLOSED;
419         }
420
421         if (table->local.db_ctx == NULL) {
422                 return NT_STATUS_INTERNAL_ERROR;
423         }
424
425         key = smbXsrv_open_local_id_to_key(open_local_id, key_buf);
426
427         status = dbwrap_parse_record(table->local.db_ctx, key,
428                                      smbXsrv_open_local_fetch_parser,
429                                      &state);
430         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
431                 return NT_STATUS_FILE_CLOSED;
432         } else if (!NT_STATUS_IS_OK(status)) {
433                 return status;
434         }
435         if (!NT_STATUS_IS_OK(state.status)) {
436                 return state.status;
437         }
438
439         if (NT_STATUS_EQUAL(state.op->status, NT_STATUS_FILE_CLOSED)) {
440                 return NT_STATUS_FILE_CLOSED;
441         }
442
443         if (open_global_id == 0) {
444                 /* make the global check a no-op for SMB1 */
445                 open_global_id = state.op->global->open_global_id;
446         }
447
448         if (state.op->global->open_global_id != open_global_id) {
449                 return NT_STATUS_FILE_CLOSED;
450         }
451
452         if (now != 0) {
453                 state.op->idle_time = now;
454         }
455
456         *_open = state.op;
457         return state.op->status;
458 }
459
460 static int smbXsrv_open_global_destructor(struct smbXsrv_open_global0 *global)
461 {
462         return 0;
463 }
464
465 static void smbXsrv_open_global_verify_record(struct db_record *db_rec,
466                                         bool *is_free,
467                                         bool *was_free,
468                                         TALLOC_CTX *mem_ctx,
469                                         struct smbXsrv_open_global0 **_g);
470
471 static NTSTATUS smbXsrv_open_global_allocate(struct db_context *db,
472                                         TALLOC_CTX *mem_ctx,
473                                         struct smbXsrv_open_global0 **_global)
474 {
475         uint32_t i;
476         struct smbXsrv_open_global0 *global = NULL;
477         uint32_t last_free = 0;
478         const uint32_t min_tries = 3;
479
480         *_global = NULL;
481
482         global = talloc_zero(mem_ctx, struct smbXsrv_open_global0);
483         if (global == NULL) {
484                 return NT_STATUS_NO_MEMORY;
485         }
486         talloc_set_destructor(global, smbXsrv_open_global_destructor);
487
488         /*
489          * Here we just randomly try the whole 32-bit space
490          *
491          * We use just 32-bit, because we want to reuse the
492          * ID for SRVSVC.
493          */
494         for (i = 0; i < UINT32_MAX; i++) {
495                 bool is_free = false;
496                 bool was_free = false;
497                 uint32_t id;
498                 uint8_t key_buf[SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE];
499                 TDB_DATA key;
500
501                 if (i >= min_tries && last_free != 0) {
502                         id = last_free;
503                 } else {
504                         id = generate_random();
505                 }
506                 if (id == 0) {
507                         id++;
508                 }
509                 if (id == UINT32_MAX) {
510                         id--;
511                 }
512
513                 key = smbXsrv_open_global_id_to_key(id, key_buf);
514
515                 global->db_rec = dbwrap_fetch_locked(db, mem_ctx, key);
516                 if (global->db_rec == NULL) {
517                         talloc_free(global);
518                         return NT_STATUS_INSUFFICIENT_RESOURCES;
519                 }
520
521                 smbXsrv_open_global_verify_record(global->db_rec,
522                                                   &is_free,
523                                                   &was_free,
524                                                   NULL, NULL);
525
526                 if (!is_free) {
527                         TALLOC_FREE(global->db_rec);
528                         continue;
529                 }
530
531                 if (!was_free && i < min_tries) {
532                         /*
533                          * The session_id is free now,
534                          * but was not free before.
535                          *
536                          * This happens if a smbd crashed
537                          * and did not cleanup the record.
538                          *
539                          * If this is one of our first tries,
540                          * then we try to find a real free one.
541                          */
542                         if (last_free == 0) {
543                                 last_free = id;
544                         }
545                         TALLOC_FREE(global->db_rec);
546                         continue;
547                 }
548
549                 global->open_global_id = id;
550
551                 *_global = global;
552                 return NT_STATUS_OK;
553         }
554
555         /* should not be reached */
556         talloc_free(global);
557         return NT_STATUS_INTERNAL_ERROR;
558 }
559
560 static void smbXsrv_open_global_verify_record(struct db_record *db_rec,
561                                         bool *is_free,
562                                         bool *was_free,
563                                         TALLOC_CTX *mem_ctx,
564                                         struct smbXsrv_open_global0 **_g)
565 {
566         TDB_DATA key;
567         TDB_DATA val;
568         DATA_BLOB blob;
569         struct smbXsrv_open_globalB global_blob;
570         enum ndr_err_code ndr_err;
571         struct smbXsrv_open_global0 *global = NULL;
572         bool exists;
573         TALLOC_CTX *frame = talloc_stackframe();
574
575         *is_free = false;
576
577         if (was_free) {
578                 *was_free = false;
579         }
580         if (_g) {
581                 *_g = NULL;
582         }
583
584         key = dbwrap_record_get_key(db_rec);
585
586         val = dbwrap_record_get_value(db_rec);
587         if (val.dsize == 0) {
588                 DEBUG(10, ("%s: empty value\n", __func__));
589                 TALLOC_FREE(frame);
590                 *is_free = true;
591                 if (was_free) {
592                         *was_free = true;
593                 }
594                 return;
595         }
596
597         blob = data_blob_const(val.dptr, val.dsize);
598
599         ndr_err = ndr_pull_struct_blob(&blob, frame, &global_blob,
600                         (ndr_pull_flags_fn_t)ndr_pull_smbXsrv_open_globalB);
601         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
602                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
603                 DEBUG(1,("smbXsrv_open_global_verify_record: "
604                          "key '%s' ndr_pull_struct_blob - %s\n",
605                          hex_encode_talloc(frame, key.dptr, key.dsize),
606                          nt_errstr(status)));
607                 TALLOC_FREE(frame);
608                 return;
609         }
610
611         DEBUG(10,("smbXsrv_open_global_verify_record\n"));
612         if (CHECK_DEBUGLVL(10)) {
613                 NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
614         }
615
616         if (global_blob.version != SMBXSRV_VERSION_0) {
617                 DEBUG(0,("smbXsrv_open_global_verify_record: "
618                          "key '%s' use unsupported version %u\n",
619                          hex_encode_talloc(frame, key.dptr, key.dsize),
620                          global_blob.version));
621                 NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
622                 TALLOC_FREE(frame);
623                 return;
624         }
625
626         global = global_blob.info.info0;
627
628         if (server_id_is_disconnected(&global->server_id)) {
629                 exists = true;
630         } else {
631                 exists = serverid_exists(&global->server_id);
632         }
633         if (!exists) {
634                 DEBUG(2,("smbXsrv_open_global_verify_record: "
635                          "key '%s' server_id %s does not exist.\n",
636                          hex_encode_talloc(frame, key.dptr, key.dsize),
637                          server_id_str(frame, &global->server_id)));
638                 if (CHECK_DEBUGLVL(2)) {
639                         NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
640                 }
641                 TALLOC_FREE(frame);
642                 dbwrap_record_delete(db_rec);
643                 *is_free = true;
644                 return;
645         }
646
647         if (_g) {
648                 *_g = talloc_move(mem_ctx, &global);
649         }
650         TALLOC_FREE(frame);
651 }
652
653 static NTSTATUS smbXsrv_open_global_store(struct smbXsrv_open_global0 *global)
654 {
655         struct smbXsrv_open_globalB global_blob;
656         DATA_BLOB blob = data_blob_null;
657         TDB_DATA key;
658         TDB_DATA val;
659         NTSTATUS status;
660         enum ndr_err_code ndr_err;
661
662         /*
663          * TODO: if we use other versions than '0'
664          * we would add glue code here, that would be able to
665          * store the information in the old format.
666          */
667
668         if (global->db_rec == NULL) {
669                 return NT_STATUS_INTERNAL_ERROR;
670         }
671
672         key = dbwrap_record_get_key(global->db_rec);
673         val = dbwrap_record_get_value(global->db_rec);
674
675         ZERO_STRUCT(global_blob);
676         global_blob.version = smbXsrv_version_global_current();
677         if (val.dsize >= 8) {
678                 global_blob.seqnum = IVAL(val.dptr, 4);
679         }
680         global_blob.seqnum += 1;
681         global_blob.info.info0 = global;
682
683         ndr_err = ndr_push_struct_blob(&blob, global->db_rec, &global_blob,
684                         (ndr_push_flags_fn_t)ndr_push_smbXsrv_open_globalB);
685         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
686                 status = ndr_map_error2ntstatus(ndr_err);
687                 DEBUG(1,("smbXsrv_open_global_store: key '%s' ndr_push - %s\n",
688                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize),
689                          nt_errstr(status)));
690                 TALLOC_FREE(global->db_rec);
691                 return status;
692         }
693
694         val = make_tdb_data(blob.data, blob.length);
695         status = dbwrap_record_store(global->db_rec, val, TDB_REPLACE);
696         if (!NT_STATUS_IS_OK(status)) {
697                 DEBUG(1,("smbXsrv_open_global_store: key '%s' store - %s\n",
698                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize),
699                          nt_errstr(status)));
700                 TALLOC_FREE(global->db_rec);
701                 return status;
702         }
703
704         if (CHECK_DEBUGLVL(10)) {
705                 DEBUG(10,("smbXsrv_open_global_store: key '%s' stored\n",
706                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize)));
707                 NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
708         }
709
710         TALLOC_FREE(global->db_rec);
711
712         return NT_STATUS_OK;
713 }
714
715 static NTSTATUS smbXsrv_open_global_lookup(struct smbXsrv_open_table *table,
716                                            uint32_t open_global_id,
717                                            TALLOC_CTX *mem_ctx,
718                                            struct smbXsrv_open_global0 **_global)
719 {
720         TDB_DATA key;
721         uint8_t key_buf[SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE];
722         struct db_record *global_rec = NULL;
723         bool is_free = false;
724
725         *_global = NULL;
726
727         if (table->global.db_ctx == NULL) {
728                 return NT_STATUS_INTERNAL_ERROR;
729         }
730
731         key = smbXsrv_open_global_id_to_key(open_global_id, key_buf);
732
733         global_rec = dbwrap_fetch_locked(table->global.db_ctx, mem_ctx, key);
734         if (global_rec == NULL) {
735                 DEBUG(0, ("smbXsrv_open_global_lookup(0x%08x): "
736                           "Failed to lock global key '%s'\n",
737                           open_global_id,
738                           hex_encode_talloc(talloc_tos(), key.dptr,
739                                             key.dsize)));
740                 return NT_STATUS_INTERNAL_DB_ERROR;
741         }
742
743         smbXsrv_open_global_verify_record(global_rec,
744                                           &is_free,
745                                           NULL,
746                                           mem_ctx,
747                                           _global);
748         if (is_free) {
749                 DEBUG(10, ("%s: is_free=true\n", __func__));
750                 talloc_free(global_rec);
751                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
752         }
753
754         (*_global)->db_rec = talloc_move(*_global, &global_rec);
755
756         talloc_set_destructor(*_global, smbXsrv_open_global_destructor);
757
758         return NT_STATUS_OK;
759 }
760
761 static int smbXsrv_open_destructor(struct smbXsrv_open *op)
762 {
763         NTSTATUS status;
764
765         status = smbXsrv_open_close(op, 0);
766         if (!NT_STATUS_IS_OK(status)) {
767                 DEBUG(0, ("smbXsrv_open_destructor: "
768                           "smbXsrv_open_close() failed - %s\n",
769                           nt_errstr(status)));
770         }
771
772         TALLOC_FREE(op->global);
773
774         return 0;
775 }
776
777 NTSTATUS smbXsrv_open_create(struct smbXsrv_connection *conn,
778                              struct auth_session_info *session_info,
779                              NTTIME now,
780                              struct smbXsrv_open **_open)
781 {
782         struct smbXsrv_open_table *table = conn->client->open_table;
783         struct db_record *local_rec = NULL;
784         struct smbXsrv_open *op = NULL;
785         void *ptr = NULL;
786         TDB_DATA val;
787         struct smbXsrv_open_global0 *global = NULL;
788         NTSTATUS status;
789         struct dom_sid *current_sid = NULL;
790         struct security_token *current_token = NULL;
791
792         if (session_info == NULL) {
793                 return NT_STATUS_INVALID_HANDLE;
794         }
795         current_token = session_info->security_token;
796
797         if (current_token == NULL) {
798                 return NT_STATUS_INVALID_HANDLE;
799         }
800
801         if (current_token->num_sids > PRIMARY_USER_SID_INDEX) {
802                 current_sid = &current_token->sids[PRIMARY_USER_SID_INDEX];
803         }
804
805         if (current_sid == NULL) {
806                 return NT_STATUS_INVALID_HANDLE;
807         }
808
809         if (table->local.num_opens >= table->local.max_opens) {
810                 return NT_STATUS_INSUFFICIENT_RESOURCES;
811         }
812
813         op = talloc_zero(table, struct smbXsrv_open);
814         if (op == NULL) {
815                 return NT_STATUS_NO_MEMORY;
816         }
817         op->table = table;
818         op->status = NT_STATUS_OK; /* TODO: start with INTERNAL_ERROR */
819         op->idle_time = now;
820
821         status = smbXsrv_open_global_allocate(table->global.db_ctx,
822                                               op, &global);
823         if (!NT_STATUS_IS_OK(status)) {
824                 TALLOC_FREE(op);
825                 return status;
826         }
827         op->global = global;
828
829         status = smbXsrv_open_local_allocate_id(table->local.db_ctx,
830                                                 table->local.lowest_id,
831                                                 table->local.highest_id,
832                                                 op,
833                                                 &local_rec,
834                                                 &op->local_id);
835         if (!NT_STATUS_IS_OK(status)) {
836                 TALLOC_FREE(op);
837                 return status;
838         }
839
840         global->open_persistent_id = global->open_global_id;
841         global->open_volatile_id = op->local_id;
842
843         global->server_id = messaging_server_id(conn->msg_ctx);
844         global->open_time = now;
845         global->open_owner = *current_sid;
846         if (conn->protocol >= PROTOCOL_SMB2_10) {
847                 global->client_guid = conn->smb2.client.guid;
848         }
849
850         ptr = op;
851         val = make_tdb_data((uint8_t const *)&ptr, sizeof(ptr));
852         status = dbwrap_record_store(local_rec, val, TDB_REPLACE);
853         TALLOC_FREE(local_rec);
854         if (!NT_STATUS_IS_OK(status)) {
855                 TALLOC_FREE(op);
856                 return status;
857         }
858         table->local.num_opens += 1;
859
860         talloc_set_destructor(op, smbXsrv_open_destructor);
861
862         status = smbXsrv_open_global_store(global);
863         if (!NT_STATUS_IS_OK(status)) {
864                 DEBUG(0,("smbXsrv_open_create: "
865                          "global_id (0x%08x) store failed - %s\n",
866                          op->global->open_global_id,
867                          nt_errstr(status)));
868                 TALLOC_FREE(op);
869                 return status;
870         }
871
872         if (CHECK_DEBUGLVL(10)) {
873                 struct smbXsrv_openB open_blob;
874
875                 ZERO_STRUCT(open_blob);
876                 open_blob.version = SMBXSRV_VERSION_0;
877                 open_blob.info.info0 = op;
878
879                 DEBUG(10,("smbXsrv_open_create: global_id (0x%08x) stored\n",
880                          op->global->open_global_id));
881                 NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
882         }
883
884         *_open = op;
885         return NT_STATUS_OK;
886 }
887
888 uint32_t smbXsrv_open_hash(struct smbXsrv_open *_open)
889 {
890         uint8_t buf[8+8+8];
891         uint32_t ret;
892
893         SBVAL(buf,  0, _open->global->open_persistent_id);
894         SBVAL(buf,  8, _open->global->open_volatile_id);
895         SBVAL(buf, 16, _open->global->open_time);
896
897         ret = hash(buf, sizeof(buf), 0);
898
899         if (ret == 0) {
900                 ret = 1;
901         }
902
903         return ret;
904 }
905
906 NTSTATUS smbXsrv_open_update(struct smbXsrv_open *op)
907 {
908         struct smbXsrv_open_table *table = op->table;
909         NTSTATUS status;
910         uint8_t key_buf[SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE];
911         TDB_DATA key;
912
913         if (op->global->db_rec != NULL) {
914                 DEBUG(0, ("smbXsrv_open_update(0x%08x): "
915                           "Called with db_rec != NULL'\n",
916                           op->global->open_global_id));
917                 return NT_STATUS_INTERNAL_ERROR;
918         }
919
920         key = smbXsrv_open_global_id_to_key(op->global->open_global_id,
921                                             key_buf);
922
923         op->global->db_rec = dbwrap_fetch_locked(table->global.db_ctx,
924                                                  op->global, key);
925         if (op->global->db_rec == NULL) {
926                 DEBUG(0, ("smbXsrv_open_update(0x%08x): "
927                           "Failed to lock global key '%s'\n",
928                           op->global->open_global_id,
929                           hex_encode_talloc(talloc_tos(), key.dptr,
930                                             key.dsize)));
931                 return NT_STATUS_INTERNAL_DB_ERROR;
932         }
933
934         status = smbXsrv_open_global_store(op->global);
935         if (!NT_STATUS_IS_OK(status)) {
936                 DEBUG(0,("smbXsrv_open_update: "
937                          "global_id (0x%08x) store failed - %s\n",
938                          op->global->open_global_id,
939                          nt_errstr(status)));
940                 return status;
941         }
942
943         if (CHECK_DEBUGLVL(10)) {
944                 struct smbXsrv_openB open_blob;
945
946                 ZERO_STRUCT(open_blob);
947                 open_blob.version = SMBXSRV_VERSION_0;
948                 open_blob.info.info0 = op;
949
950                 DEBUG(10,("smbXsrv_open_update: global_id (0x%08x) stored\n",
951                           op->global->open_global_id));
952                 NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
953         }
954
955         return NT_STATUS_OK;
956 }
957
958 NTSTATUS smbXsrv_open_close(struct smbXsrv_open *op, NTTIME now)
959 {
960         struct smbXsrv_open_table *table;
961         struct db_record *local_rec = NULL;
962         struct db_record *global_rec = NULL;
963         NTSTATUS status;
964         NTSTATUS error = NT_STATUS_OK;
965
966         if (op->table == NULL) {
967                 return NT_STATUS_OK;
968         }
969
970         table = op->table;
971         op->table = NULL;
972
973         op->status = NT_STATUS_FILE_CLOSED;
974         op->global->disconnect_time = now;
975         server_id_set_disconnected(&op->global->server_id);
976
977         global_rec = op->global->db_rec;
978         op->global->db_rec = NULL;
979         if (global_rec == NULL) {
980                 uint8_t key_buf[SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE];
981                 TDB_DATA key;
982
983                 key = smbXsrv_open_global_id_to_key(
984                                                 op->global->open_global_id,
985                                                 key_buf);
986
987                 global_rec = dbwrap_fetch_locked(table->global.db_ctx,
988                                                  op->global, key);
989                 if (global_rec == NULL) {
990                         DEBUG(0, ("smbXsrv_open_close(0x%08x): "
991                                   "Failed to lock global key '%s'\n",
992                                   op->global->open_global_id,
993                                   hex_encode_talloc(global_rec, key.dptr,
994                                                     key.dsize)));
995                         error = NT_STATUS_INTERNAL_ERROR;
996                 }
997         }
998
999         if (global_rec != NULL && op->global->durable) {
1000                 /*
1001                  * If it is a durable open we need to update the global part
1002                  * instead of deleting it
1003                  */
1004                 op->global->db_rec = global_rec;
1005                 status = smbXsrv_open_global_store(op->global);
1006                 if (NT_STATUS_IS_OK(status)) {
1007                         /*
1008                          * smbXsrv_open_global_store does the free
1009                          * of op->global->db_rec
1010                          */
1011                         global_rec = NULL;
1012                 }
1013                 if (!NT_STATUS_IS_OK(status)) {
1014                         DEBUG(0,("smbXsrv_open_close(0x%08x)"
1015                                  "smbXsrv_open_global_store() failed - %s\n",
1016                                  op->global->open_global_id,
1017                                  nt_errstr(status)));
1018                         error = status;
1019                 }
1020
1021                 if (NT_STATUS_IS_OK(status) && CHECK_DEBUGLVL(10)) {
1022                         struct smbXsrv_openB open_blob;
1023
1024                         ZERO_STRUCT(open_blob);
1025                         open_blob.version = SMBXSRV_VERSION_0;
1026                         open_blob.info.info0 = op;
1027
1028                         DEBUG(10,("smbXsrv_open_close(0x%08x): "
1029                                   "stored disconnect\n",
1030                                   op->global->open_global_id));
1031                         NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
1032                 }
1033         }
1034
1035         if (global_rec != NULL) {
1036                 status = dbwrap_record_delete(global_rec);
1037                 if (!NT_STATUS_IS_OK(status)) {
1038                         TDB_DATA key = dbwrap_record_get_key(global_rec);
1039
1040                         DEBUG(0, ("smbXsrv_open_close(0x%08x): "
1041                                   "failed to delete global key '%s': %s\n",
1042                                   op->global->open_global_id,
1043                                   hex_encode_talloc(global_rec, key.dptr,
1044                                                     key.dsize),
1045                                   nt_errstr(status)));
1046                         error = status;
1047                 }
1048         }
1049         TALLOC_FREE(global_rec);
1050
1051         local_rec = op->db_rec;
1052         if (local_rec == NULL) {
1053                 uint8_t key_buf[SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE];
1054                 TDB_DATA key;
1055
1056                 key = smbXsrv_open_local_id_to_key(op->local_id, key_buf);
1057
1058                 local_rec = dbwrap_fetch_locked(table->local.db_ctx,
1059                                                 op, key);
1060                 if (local_rec == NULL) {
1061                         DEBUG(0, ("smbXsrv_open_close(0x%08x): "
1062                                   "Failed to lock local key '%s'\n",
1063                                   op->global->open_global_id,
1064                                   hex_encode_talloc(local_rec, key.dptr,
1065                                                     key.dsize)));
1066                         error = NT_STATUS_INTERNAL_ERROR;
1067                 }
1068         }
1069
1070         if (local_rec != NULL) {
1071                 status = dbwrap_record_delete(local_rec);
1072                 if (!NT_STATUS_IS_OK(status)) {
1073                         TDB_DATA key = dbwrap_record_get_key(local_rec);
1074
1075                         DEBUG(0, ("smbXsrv_open_close(0x%08x): "
1076                                   "failed to delete local key '%s': %s\n",
1077                                   op->global->open_global_id,
1078                                   hex_encode_talloc(local_rec, key.dptr,
1079                                                     key.dsize),
1080                                   nt_errstr(status)));
1081                         error = status;
1082                 }
1083                 table->local.num_opens -= 1;
1084         }
1085         if (op->db_rec == NULL) {
1086                 TALLOC_FREE(local_rec);
1087         }
1088         op->db_rec = NULL;
1089
1090         if (op->compat) {
1091                 op->compat->op = NULL;
1092                 file_free(NULL, op->compat);
1093                 op->compat = NULL;
1094         }
1095
1096         return error;
1097 }
1098
1099 NTSTATUS smb1srv_open_table_init(struct smbXsrv_connection *conn)
1100 {
1101         uint32_t max_opens;
1102
1103         /*
1104          * Allow a range from 1..65534.
1105          *
1106          * With real_max_open_files possible ids,
1107          * truncated to the SMB1 limit of 16-bit.
1108          *
1109          * 0 and 0xFFFF are no valid ids.
1110          */
1111         max_opens = conn->client->sconn->real_max_open_files;
1112         max_opens = MIN(max_opens, UINT16_MAX - 1);
1113
1114         return smbXsrv_open_table_init(conn, 1, UINT16_MAX - 1, max_opens);
1115 }
1116
1117 NTSTATUS smb1srv_open_lookup(struct smbXsrv_connection *conn,
1118                              uint16_t fnum, NTTIME now,
1119                              struct smbXsrv_open **_open)
1120 {
1121         struct smbXsrv_open_table *table = conn->client->open_table;
1122         uint32_t local_id = fnum;
1123         uint32_t global_id = 0;
1124
1125         return smbXsrv_open_local_lookup(table, local_id, global_id, now, _open);
1126 }
1127
1128 NTSTATUS smb2srv_open_table_init(struct smbXsrv_connection *conn)
1129 {
1130         uint32_t max_opens;
1131
1132         /*
1133          * Allow a range from 1..4294967294.
1134          *
1135          * With real_max_open_files possible ids,
1136          * truncated to 16-bit (the same as SMB1 for now).
1137          *
1138          * 0 and 0xFFFFFFFF are no valid ids.
1139          *
1140          * The usage of conn->sconn->real_max_open_files
1141          * is the reason that we use one open table per
1142          * transport connection (as we still have a 1:1 mapping
1143          * between process and transport connection).
1144          */
1145         max_opens = conn->client->sconn->real_max_open_files;
1146         max_opens = MIN(max_opens, UINT16_MAX - 1);
1147
1148         return smbXsrv_open_table_init(conn, 1, UINT32_MAX - 1, max_opens);
1149 }
1150
1151 NTSTATUS smb2srv_open_lookup(struct smbXsrv_connection *conn,
1152                              uint64_t persistent_id,
1153                              uint64_t volatile_id,
1154                              NTTIME now,
1155                              struct smbXsrv_open **_open)
1156 {
1157         struct smbXsrv_open_table *table = conn->client->open_table;
1158         uint32_t local_id = volatile_id & UINT32_MAX;
1159         uint64_t local_zeros = volatile_id & 0xFFFFFFFF00000000LLU;
1160         uint32_t global_id = persistent_id & UINT32_MAX;
1161         uint64_t global_zeros = persistent_id & 0xFFFFFFFF00000000LLU;
1162
1163         if (local_zeros != 0) {
1164                 return NT_STATUS_FILE_CLOSED;
1165         }
1166
1167         if (global_zeros != 0) {
1168                 return NT_STATUS_FILE_CLOSED;
1169         }
1170
1171         if (global_id == 0) {
1172                 return NT_STATUS_FILE_CLOSED;
1173         }
1174
1175         return smbXsrv_open_local_lookup(table, local_id, global_id, now, _open);
1176 }
1177
1178 NTSTATUS smb2srv_open_recreate(struct smbXsrv_connection *conn,
1179                                struct auth_session_info *session_info,
1180                                uint64_t persistent_id,
1181                                const struct GUID *create_guid,
1182                                NTTIME now,
1183                                struct smbXsrv_open **_open)
1184 {
1185         struct smbXsrv_open_table *table = conn->client->open_table;
1186         struct db_record *local_rec = NULL;
1187         struct smbXsrv_open *op = NULL;
1188         void *ptr = NULL;
1189         TDB_DATA val;
1190         uint32_t global_id = persistent_id & UINT32_MAX;
1191         uint64_t global_zeros = persistent_id & 0xFFFFFFFF00000000LLU;
1192         NTSTATUS status;
1193         struct security_token *current_token = NULL;
1194
1195         if (session_info == NULL) {
1196                 DEBUG(10, ("session_info=NULL\n"));
1197                 return NT_STATUS_INVALID_HANDLE;
1198         }
1199         current_token = session_info->security_token;
1200
1201         if (current_token == NULL) {
1202                 DEBUG(10, ("current_token=NULL\n"));
1203                 return NT_STATUS_INVALID_HANDLE;
1204         }
1205
1206         if (global_zeros != 0) {
1207                 DEBUG(10, ("global_zeros!=0\n"));
1208                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1209         }
1210
1211         op = talloc_zero(table, struct smbXsrv_open);
1212         if (op == NULL) {
1213                 return NT_STATUS_NO_MEMORY;
1214         }
1215         op->table = table;
1216
1217         status = smbXsrv_open_global_lookup(table, global_id, op, &op->global);
1218         if (!NT_STATUS_IS_OK(status)) {
1219                 TALLOC_FREE(op);
1220                 DEBUG(10, ("smbXsrv_open_global_lookup returned %s\n",
1221                            nt_errstr(status)));
1222                 return status;
1223         }
1224
1225         /*
1226          * If the provided create_guid is NULL, this means that
1227          * the reconnect request was a v1 request. In that case
1228          * we should skipt the create GUID verification, since
1229          * it is valid to v1-reconnect a v2-opened handle.
1230          */
1231         if ((create_guid != NULL) &&
1232             !GUID_equal(&op->global->create_guid, create_guid))
1233         {
1234                 TALLOC_FREE(op);
1235                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1236         }
1237
1238         if (!security_token_is_sid(current_token, &op->global->open_owner)) {
1239                 TALLOC_FREE(op);
1240                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1241         }
1242
1243         if (!op->global->durable) {
1244                 TALLOC_FREE(op);
1245                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1246         }
1247
1248         if (table->local.num_opens >= table->local.max_opens) {
1249                 TALLOC_FREE(op);
1250                 return NT_STATUS_INSUFFICIENT_RESOURCES;
1251         }
1252
1253         status = smbXsrv_open_local_allocate_id(table->local.db_ctx,
1254                                                 table->local.lowest_id,
1255                                                 table->local.highest_id,
1256                                                 op,
1257                                                 &local_rec,
1258                                                 &op->local_id);
1259         if (!NT_STATUS_IS_OK(status)) {
1260                 TALLOC_FREE(op);
1261                 return status;
1262         }
1263
1264         op->idle_time = now;
1265         op->status = NT_STATUS_FILE_CLOSED;
1266
1267         op->global->open_volatile_id = op->local_id;
1268         op->global->server_id = messaging_server_id(conn->msg_ctx);
1269
1270         ptr = op;
1271         val = make_tdb_data((uint8_t const *)&ptr, sizeof(ptr));
1272         status = dbwrap_record_store(local_rec, val, TDB_REPLACE);
1273         TALLOC_FREE(local_rec);
1274         if (!NT_STATUS_IS_OK(status)) {
1275                 TALLOC_FREE(op);
1276                 return status;
1277         }
1278         table->local.num_opens += 1;
1279
1280         talloc_set_destructor(op, smbXsrv_open_destructor);
1281
1282         status = smbXsrv_open_global_store(op->global);
1283         if (!NT_STATUS_IS_OK(status)) {
1284                 TALLOC_FREE(op);
1285                 return status;
1286         }
1287
1288         if (CHECK_DEBUGLVL(10)) {
1289                 struct smbXsrv_openB open_blob;
1290
1291                 ZERO_STRUCT(open_blob);
1292                 open_blob.version = 0;
1293                 open_blob.info.info0 = op;
1294
1295                 DEBUG(10,("smbXsrv_open_recreate: global_id (0x%08x) stored\n",
1296                          op->global->open_global_id));
1297                 NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
1298         }
1299
1300         *_open = op;
1301         return NT_STATUS_OK;
1302 }
1303
1304
1305 static NTSTATUS smbXsrv_open_global_parse_record(TALLOC_CTX *mem_ctx,
1306                                                  struct db_record *rec,
1307                                                  struct smbXsrv_open_global0 **global)
1308 {
1309         TDB_DATA key = dbwrap_record_get_key(rec);
1310         TDB_DATA val = dbwrap_record_get_value(rec);
1311         DATA_BLOB blob = data_blob_const(val.dptr, val.dsize);
1312         struct smbXsrv_open_globalB global_blob;
1313         enum ndr_err_code ndr_err;
1314         NTSTATUS status;
1315         TALLOC_CTX *frame = talloc_stackframe();
1316
1317         ndr_err = ndr_pull_struct_blob(&blob, frame, &global_blob,
1318                         (ndr_pull_flags_fn_t)ndr_pull_smbXsrv_open_globalB);
1319         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1320                 DEBUG(1,("Invalid record in smbXsrv_open_global.tdb:"
1321                          "key '%s' ndr_pull_struct_blob - %s\n",
1322                          hex_encode_talloc(frame, key.dptr, key.dsize),
1323                          ndr_errstr(ndr_err)));
1324                 status = ndr_map_error2ntstatus(ndr_err);
1325                 goto done;
1326         }
1327
1328         if (global_blob.version != SMBXSRV_VERSION_0) {
1329                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
1330                 DEBUG(1,("Invalid record in smbXsrv_open_global.tdb:"
1331                          "key '%s' unsuported version - %d - %s\n",
1332                          hex_encode_talloc(frame, key.dptr, key.dsize),
1333                          (int)global_blob.version,
1334                          nt_errstr(status)));
1335                 goto done;
1336         }
1337
1338         *global = talloc_move(mem_ctx, &global_blob.info.info0);
1339         status = NT_STATUS_OK;
1340 done:
1341         talloc_free(frame);
1342         return status;
1343 }
1344
1345 struct smbXsrv_open_global_traverse_state {
1346         int (*fn)(struct smbXsrv_open_global0 *, void *);
1347         void *private_data;
1348 };
1349
1350 static int smbXsrv_open_global_traverse_fn(struct db_record *rec, void *data)
1351 {
1352         struct smbXsrv_open_global_traverse_state *state =
1353                 (struct smbXsrv_open_global_traverse_state*)data;
1354         struct smbXsrv_open_global0 *global = NULL;
1355         NTSTATUS status;
1356         int ret = -1;
1357
1358         status = smbXsrv_open_global_parse_record(talloc_tos(), rec, &global);
1359         if (!NT_STATUS_IS_OK(status)) {
1360                 return -1;
1361         }
1362
1363         global->db_rec = rec;
1364         ret = state->fn(global, state->private_data);
1365         talloc_free(global);
1366         return ret;
1367 }
1368
1369 NTSTATUS smbXsrv_open_global_traverse(
1370                         int (*fn)(struct smbXsrv_open_global0 *, void *),
1371                         void *private_data)
1372 {
1373
1374         NTSTATUS status;
1375         int count = 0;
1376         struct smbXsrv_open_global_traverse_state state = {
1377                 .fn = fn,
1378                 .private_data = private_data,
1379         };
1380
1381         become_root();
1382         status = smbXsrv_open_global_init();
1383         if (!NT_STATUS_IS_OK(status)) {
1384                 unbecome_root();
1385                 DEBUG(0, ("Failed to initialize open_global: %s\n",
1386                           nt_errstr(status)));
1387                 return status;
1388         }
1389
1390         status = dbwrap_traverse_read(smbXsrv_open_global_db_ctx,
1391                                       smbXsrv_open_global_traverse_fn,
1392                                       &state,
1393                                       &count);
1394         unbecome_root();
1395
1396         return status;
1397 }
1398
1399 NTSTATUS smbXsrv_open_cleanup(uint64_t persistent_id)
1400 {
1401         NTSTATUS status = NT_STATUS_OK;
1402         TALLOC_CTX *frame = talloc_stackframe();
1403         struct smbXsrv_open_global0 *op = NULL;
1404         uint8_t key_buf[SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE];
1405         TDB_DATA key;
1406         TDB_DATA val;
1407         struct db_record *rec;
1408         bool delete_open = false;
1409         uint32_t global_id = persistent_id & UINT32_MAX;
1410
1411         key = smbXsrv_open_global_id_to_key(global_id, key_buf);
1412         rec = dbwrap_fetch_locked(smbXsrv_open_global_db_ctx, frame, key);
1413         if (rec == NULL) {
1414                 status = NT_STATUS_NOT_FOUND;
1415                 DEBUG(1, ("smbXsrv_open_cleanup[global: 0x%08x] "
1416                           "failed to fetch record from %s - %s\n",
1417                            global_id, dbwrap_name(smbXsrv_open_global_db_ctx),
1418                            nt_errstr(status)));
1419                 goto done;
1420         }
1421
1422         val = dbwrap_record_get_value(rec);
1423         if (val.dsize == 0) {
1424                 DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1425                           "empty record in %s, skipping...\n",
1426                            global_id, dbwrap_name(smbXsrv_open_global_db_ctx)));
1427                 goto done;
1428         }
1429
1430         status = smbXsrv_open_global_parse_record(talloc_tos(), rec, &op);
1431         if (!NT_STATUS_IS_OK(status)) {
1432                 DEBUG(1, ("smbXsrv_open_cleanup[global: 0x%08x] "
1433                           "failed to read record: %s\n",
1434                           global_id, nt_errstr(status)));
1435                 goto done;
1436         }
1437
1438         if (server_id_is_disconnected(&op->server_id)) {
1439                 struct timeval now, disconnect_time;
1440                 int64_t tdiff;
1441                 now = timeval_current();
1442                 nttime_to_timeval(&disconnect_time, op->disconnect_time);
1443                 tdiff = usec_time_diff(&now, &disconnect_time);
1444                 delete_open = (tdiff >= 1000*op->durable_timeout_msec);
1445
1446                 DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1447                            "disconnected at [%s] %us ago with "
1448                            "timeout of %us -%s reached\n",
1449                            global_id,
1450                            nt_time_string(frame, op->disconnect_time),
1451                            (unsigned)(tdiff/1000000),
1452                            op->durable_timeout_msec / 1000,
1453                            delete_open ? "" : " not"));
1454         } else if (!serverid_exists(&op->server_id)) {
1455                 DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1456                            "server[%s] does not exist\n",
1457                            global_id, server_id_str(frame, &op->server_id)));
1458                 delete_open = true;
1459         }
1460
1461         if (!delete_open) {
1462                 goto done;
1463         }
1464
1465         status = dbwrap_record_delete(rec);
1466         if (!NT_STATUS_IS_OK(status)) {
1467                 DEBUG(1, ("smbXsrv_open_cleanup[global: 0x%08x] "
1468                           "failed to delete record"
1469                           "from %s: %s\n", global_id,
1470                           dbwrap_name(smbXsrv_open_global_db_ctx),
1471                           nt_errstr(status)));
1472                 goto done;
1473         }
1474
1475         DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1476                    "delete record from %s\n",
1477                    global_id,
1478                    dbwrap_name(smbXsrv_open_global_db_ctx)));
1479
1480 done:
1481         talloc_free(frame);
1482         return status;
1483 }