Update 4.2 Roadmap file
[mat/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 "serverid.h"
33
34 struct smbXsrv_open_table {
35         struct {
36                 struct db_context *db_ctx;
37                 uint32_t lowest_id;
38                 uint32_t highest_id;
39                 uint32_t max_opens;
40                 uint32_t num_opens;
41         } local;
42         struct {
43                 struct db_context *db_ctx;
44         } global;
45 };
46
47 static struct db_context *smbXsrv_open_global_db_ctx = NULL;
48
49 NTSTATUS smbXsrv_open_global_init(void)
50 {
51         char *global_path = NULL;
52         struct db_context *db_ctx = NULL;
53
54         if (smbXsrv_open_global_db_ctx != NULL) {
55                 return NT_STATUS_OK;
56         }
57
58         global_path = lock_path("smbXsrv_open_global.tdb");
59         if (global_path == NULL) {
60                 return NT_STATUS_NO_MEMORY;
61         }
62
63         db_ctx = db_open(NULL, global_path,
64                          0, /* hash_size */
65                          TDB_DEFAULT |
66                          TDB_CLEAR_IF_FIRST |
67                          TDB_INCOMPATIBLE_HASH,
68                          O_RDWR | O_CREAT, 0600,
69                          DBWRAP_LOCK_ORDER_1,
70                          DBWRAP_FLAG_NONE);
71         TALLOC_FREE(global_path);
72         if (db_ctx == NULL) {
73                 NTSTATUS status;
74
75                 status = map_nt_error_from_unix_common(errno);
76
77                 return status;
78         }
79
80         smbXsrv_open_global_db_ctx = db_ctx;
81
82         return NT_STATUS_OK;
83 }
84
85 /*
86  * NOTE:
87  * We need to store the keys in big endian so that dbwrap_rbt's memcmp
88  * has the same result as integer comparison between the uint32_t
89  * values.
90  *
91  * TODO: implement string based key
92  */
93
94 #define SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE sizeof(uint32_t)
95
96 static TDB_DATA smbXsrv_open_global_id_to_key(uint32_t id,
97                                               uint8_t *key_buf)
98 {
99         TDB_DATA key;
100
101         RSIVAL(key_buf, 0, id);
102
103         key = make_tdb_data(key_buf, SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE);
104
105         return key;
106 }
107
108 #if 0
109 static NTSTATUS smbXsrv_open_global_key_to_id(TDB_DATA key, uint32_t *id)
110 {
111         if (id == NULL) {
112                 return NT_STATUS_INVALID_PARAMETER;
113         }
114
115         if (key.dsize != SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE) {
116                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
117         }
118
119         *id = RIVAL(key.dptr, 0);
120
121         return NT_STATUS_OK;
122 }
123 #endif
124
125 #define SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE sizeof(uint32_t)
126
127 static TDB_DATA smbXsrv_open_local_id_to_key(uint32_t id,
128                                              uint8_t *key_buf)
129 {
130         TDB_DATA key;
131
132         RSIVAL(key_buf, 0, id);
133
134         key = make_tdb_data(key_buf, SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE);
135
136         return key;
137 }
138
139 static NTSTATUS smbXsrv_open_local_key_to_id(TDB_DATA key, uint32_t *id)
140 {
141         if (id == NULL) {
142                 return NT_STATUS_INVALID_PARAMETER;
143         }
144
145         if (key.dsize != SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE) {
146                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
147         }
148
149         *id = RIVAL(key.dptr, 0);
150
151         return NT_STATUS_OK;
152 }
153
154 static NTSTATUS smbXsrv_open_table_init(struct smbXsrv_connection *conn,
155                                         uint32_t lowest_id,
156                                         uint32_t highest_id,
157                                         uint32_t max_opens)
158 {
159         struct smbXsrv_client *client = conn->client;
160         struct smbXsrv_open_table *table;
161         NTSTATUS status;
162         uint64_t max_range;
163
164         if (lowest_id > highest_id) {
165                 return NT_STATUS_INTERNAL_ERROR;
166         }
167
168         max_range = highest_id;
169         max_range -= lowest_id;
170         max_range += 1;
171
172         if (max_opens > max_range) {
173                 return NT_STATUS_INTERNAL_ERROR;
174         }
175
176         table = talloc_zero(client, struct smbXsrv_open_table);
177         if (table == NULL) {
178                 return NT_STATUS_NO_MEMORY;
179         }
180
181         table->local.db_ctx = db_open_rbt(table);
182         if (table->local.db_ctx == NULL) {
183                 TALLOC_FREE(table);
184                 return NT_STATUS_NO_MEMORY;
185         }
186         table->local.lowest_id = lowest_id;
187         table->local.highest_id = highest_id;
188         table->local.max_opens = max_opens;
189
190         status = smbXsrv_open_global_init();
191         if (!NT_STATUS_IS_OK(status)) {
192                 TALLOC_FREE(table);
193                 return status;
194         }
195
196         table->global.db_ctx = smbXsrv_open_global_db_ctx;
197
198         client->open_table = table;
199         return NT_STATUS_OK;
200 }
201
202 struct smbXsrv_open_local_allocate_state {
203         const uint32_t lowest_id;
204         const uint32_t highest_id;
205         uint32_t last_id;
206         uint32_t useable_id;
207         NTSTATUS status;
208 };
209
210 static int smbXsrv_open_local_allocate_traverse(struct db_record *rec,
211                                                    void *private_data)
212 {
213         struct smbXsrv_open_local_allocate_state *state =
214                 (struct smbXsrv_open_local_allocate_state *)private_data;
215         TDB_DATA key = dbwrap_record_get_key(rec);
216         uint32_t id = 0;
217         NTSTATUS status;
218
219         status = smbXsrv_open_local_key_to_id(key, &id);
220         if (!NT_STATUS_IS_OK(status)) {
221                 state->status = status;
222                 return -1;
223         }
224
225         if (id <= state->last_id) {
226                 state->status = NT_STATUS_INTERNAL_DB_CORRUPTION;
227                 return -1;
228         }
229         state->last_id = id;
230
231         if (id > state->useable_id) {
232                 state->status = NT_STATUS_OK;
233                 return -1;
234         }
235
236         if (state->useable_id == state->highest_id) {
237                 state->status = NT_STATUS_INSUFFICIENT_RESOURCES;
238                 return -1;
239         }
240
241         state->useable_id +=1;
242         return 0;
243 }
244
245 static NTSTATUS smbXsrv_open_local_allocate_id(struct db_context *db,
246                                                uint32_t lowest_id,
247                                                uint32_t highest_id,
248                                                TALLOC_CTX *mem_ctx,
249                                                struct db_record **_rec,
250                                                uint32_t *_id)
251 {
252         struct smbXsrv_open_local_allocate_state state = {
253                 .lowest_id = lowest_id,
254                 .highest_id = highest_id,
255                 .last_id = 0,
256                 .useable_id = lowest_id,
257                 .status = NT_STATUS_INTERNAL_ERROR,
258         };
259         uint32_t i;
260         uint32_t range;
261         NTSTATUS status;
262         int count = 0;
263
264         *_rec = NULL;
265         *_id = 0;
266
267         if (lowest_id > highest_id) {
268                 return NT_STATUS_INSUFFICIENT_RESOURCES;
269         }
270
271         /*
272          * first we try randomly
273          */
274         range = (highest_id - lowest_id) + 1;
275
276         for (i = 0; i < (range / 2); i++) {
277                 uint32_t id;
278                 uint8_t key_buf[SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE];
279                 TDB_DATA key;
280                 TDB_DATA val;
281                 struct db_record *rec = NULL;
282
283                 id = generate_random() % range;
284                 id += lowest_id;
285
286                 if (id < lowest_id) {
287                         id = lowest_id;
288                 }
289                 if (id > highest_id) {
290                         id = highest_id;
291                 }
292
293                 key = smbXsrv_open_local_id_to_key(id, key_buf);
294
295                 rec = dbwrap_fetch_locked(db, mem_ctx, key);
296                 if (rec == NULL) {
297                         return NT_STATUS_INSUFFICIENT_RESOURCES;
298                 }
299
300                 val = dbwrap_record_get_value(rec);
301                 if (val.dsize != 0) {
302                         TALLOC_FREE(rec);
303                         continue;
304                 }
305
306                 *_rec = rec;
307                 *_id = id;
308                 return NT_STATUS_OK;
309         }
310
311         /*
312          * if the range is almost full,
313          * we traverse the whole table
314          * (this relies on sorted behavior of dbwrap_rbt)
315          */
316         status = dbwrap_traverse_read(db, smbXsrv_open_local_allocate_traverse,
317                                       &state, &count);
318         if (NT_STATUS_IS_OK(status)) {
319                 if (NT_STATUS_IS_OK(state.status)) {
320                         return NT_STATUS_INTERNAL_ERROR;
321                 }
322
323                 if (!NT_STATUS_EQUAL(state.status, NT_STATUS_INTERNAL_ERROR)) {
324                         return state.status;
325                 }
326
327                 if (state.useable_id <= state.highest_id) {
328                         state.status = NT_STATUS_OK;
329                 } else {
330                         return NT_STATUS_INSUFFICIENT_RESOURCES;
331                 }
332         } else if (!NT_STATUS_EQUAL(status, NT_STATUS_INTERNAL_DB_CORRUPTION)) {
333                 /*
334                  * Here we really expect NT_STATUS_INTERNAL_DB_CORRUPTION!
335                  *
336                  * If we get anything else it is an error, because it
337                  * means we did not manage to find a free slot in
338                  * the db.
339                  */
340                 return NT_STATUS_INSUFFICIENT_RESOURCES;
341         }
342
343         if (NT_STATUS_IS_OK(state.status)) {
344                 uint32_t id;
345                 uint8_t key_buf[SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE];
346                 TDB_DATA key;
347                 TDB_DATA val;
348                 struct db_record *rec = NULL;
349
350                 id = state.useable_id;
351
352                 key = smbXsrv_open_local_id_to_key(id, key_buf);
353
354                 rec = dbwrap_fetch_locked(db, mem_ctx, key);
355                 if (rec == NULL) {
356                         return NT_STATUS_INSUFFICIENT_RESOURCES;
357                 }
358
359                 val = dbwrap_record_get_value(rec);
360                 if (val.dsize != 0) {
361                         TALLOC_FREE(rec);
362                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
363                 }
364
365                 *_rec = rec;
366                 *_id = id;
367                 return NT_STATUS_OK;
368         }
369
370         return state.status;
371 }
372
373 struct smbXsrv_open_local_fetch_state {
374         struct smbXsrv_open *op;
375         NTSTATUS status;
376 };
377
378 static void smbXsrv_open_local_fetch_parser(TDB_DATA key, TDB_DATA data,
379                                             void *private_data)
380 {
381         struct smbXsrv_open_local_fetch_state *state =
382                 (struct smbXsrv_open_local_fetch_state *)private_data;
383         void *ptr;
384
385         if (data.dsize != sizeof(ptr)) {
386                 state->status = NT_STATUS_INTERNAL_DB_ERROR;
387                 return;
388         }
389
390         memcpy(&ptr, data.dptr, data.dsize);
391         state->op = talloc_get_type_abort(ptr, struct smbXsrv_open);
392         state->status = NT_STATUS_OK;
393 }
394
395 static NTSTATUS smbXsrv_open_local_lookup(struct smbXsrv_open_table *table,
396                                           uint32_t open_local_id,
397                                           uint32_t open_global_id,
398                                           NTTIME now,
399                                           struct smbXsrv_open **_open)
400 {
401         struct smbXsrv_open_local_fetch_state state = {
402                 .op = NULL,
403                 .status = NT_STATUS_INTERNAL_ERROR,
404         };
405         uint8_t key_buf[SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE];
406         TDB_DATA key;
407         NTSTATUS status;
408
409         *_open = NULL;
410
411         if (open_local_id == 0) {
412                 return NT_STATUS_FILE_CLOSED;
413         }
414
415         if (table == NULL) {
416                 /* this might happen before the end of negprot */
417                 return NT_STATUS_FILE_CLOSED;
418         }
419
420         if (table->local.db_ctx == NULL) {
421                 return NT_STATUS_INTERNAL_ERROR;
422         }
423
424         key = smbXsrv_open_local_id_to_key(open_local_id, key_buf);
425
426         status = dbwrap_parse_record(table->local.db_ctx, key,
427                                      smbXsrv_open_local_fetch_parser,
428                                      &state);
429         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
430                 return NT_STATUS_FILE_CLOSED;
431         } else if (!NT_STATUS_IS_OK(status)) {
432                 return status;
433         }
434         if (!NT_STATUS_IS_OK(state.status)) {
435                 return state.status;
436         }
437
438         if (NT_STATUS_EQUAL(state.op->status, NT_STATUS_FILE_CLOSED)) {
439                 return NT_STATUS_FILE_CLOSED;
440         }
441
442         if (open_global_id == 0) {
443                 /* make the global check a no-op for SMB1 */
444                 open_global_id = state.op->global->open_global_id;
445         }
446
447         if (state.op->global->open_global_id != open_global_id) {
448                 return NT_STATUS_FILE_CLOSED;
449         }
450
451         if (now != 0) {
452                 state.op->idle_time = now;
453         }
454
455         *_open = state.op;
456         return state.op->status;
457 }
458
459 static int smbXsrv_open_global_destructor(struct smbXsrv_open_global0 *global)
460 {
461         return 0;
462 }
463
464 static void smbXsrv_open_global_verify_record(struct db_record *db_rec,
465                                         bool *is_free,
466                                         bool *was_free,
467                                         TALLOC_CTX *mem_ctx,
468                                         struct smbXsrv_open_global0 **_g);
469
470 static NTSTATUS smbXsrv_open_global_allocate(struct db_context *db,
471                                         TALLOC_CTX *mem_ctx,
472                                         struct smbXsrv_open_global0 **_global)
473 {
474         uint32_t i;
475         struct smbXsrv_open_global0 *global = NULL;
476         uint32_t last_free = 0;
477         const uint32_t min_tries = 3;
478
479         *_global = NULL;
480
481         global = talloc_zero(mem_ctx, struct smbXsrv_open_global0);
482         if (global == NULL) {
483                 return NT_STATUS_NO_MEMORY;
484         }
485         talloc_set_destructor(global, smbXsrv_open_global_destructor);
486
487         /*
488          * Here we just randomly try the whole 32-bit space
489          *
490          * We use just 32-bit, because we want to reuse the
491          * ID for SRVSVC.
492          */
493         for (i = 0; i < UINT32_MAX; i++) {
494                 bool is_free = false;
495                 bool was_free = false;
496                 uint32_t id;
497                 uint8_t key_buf[SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE];
498                 TDB_DATA key;
499
500                 if (i >= min_tries && last_free != 0) {
501                         id = last_free;
502                 } else {
503                         id = generate_random();
504                 }
505                 if (id == 0) {
506                         id++;
507                 }
508                 if (id == UINT32_MAX) {
509                         id--;
510                 }
511
512                 key = smbXsrv_open_global_id_to_key(id, key_buf);
513
514                 global->db_rec = dbwrap_fetch_locked(db, mem_ctx, key);
515                 if (global->db_rec == NULL) {
516                         talloc_free(global);
517                         return NT_STATUS_INSUFFICIENT_RESOURCES;
518                 }
519
520                 smbXsrv_open_global_verify_record(global->db_rec,
521                                                   &is_free,
522                                                   &was_free,
523                                                   NULL, NULL);
524
525                 if (!is_free) {
526                         TALLOC_FREE(global->db_rec);
527                         continue;
528                 }
529
530                 if (!was_free && i < min_tries) {
531                         /*
532                          * The session_id is free now,
533                          * but was not free before.
534                          *
535                          * This happens if a smbd crashed
536                          * and did not cleanup the record.
537                          *
538                          * If this is one of our first tries,
539                          * then we try to find a real free one.
540                          */
541                         if (last_free == 0) {
542                                 last_free = id;
543                         }
544                         TALLOC_FREE(global->db_rec);
545                         continue;
546                 }
547
548                 global->open_global_id = id;
549
550                 *_global = global;
551                 return NT_STATUS_OK;
552         }
553
554         /* should not be reached */
555         talloc_free(global);
556         return NT_STATUS_INTERNAL_ERROR;
557 }
558
559 static void smbXsrv_open_global_verify_record(struct db_record *db_rec,
560                                         bool *is_free,
561                                         bool *was_free,
562                                         TALLOC_CTX *mem_ctx,
563                                         struct smbXsrv_open_global0 **_g)
564 {
565         TDB_DATA key;
566         TDB_DATA val;
567         DATA_BLOB blob;
568         struct smbXsrv_open_globalB global_blob;
569         enum ndr_err_code ndr_err;
570         struct smbXsrv_open_global0 *global = NULL;
571         bool exists;
572         TALLOC_CTX *frame = talloc_stackframe();
573
574         *is_free = false;
575
576         if (was_free) {
577                 *was_free = false;
578         }
579         if (_g) {
580                 *_g = NULL;
581         }
582
583         key = dbwrap_record_get_key(db_rec);
584
585         val = dbwrap_record_get_value(db_rec);
586         if (val.dsize == 0) {
587                 DEBUG(10, ("%s: empty value\n", __func__));
588                 TALLOC_FREE(frame);
589                 *is_free = true;
590                 if (was_free) {
591                         *was_free = true;
592                 }
593                 return;
594         }
595
596         blob = data_blob_const(val.dptr, val.dsize);
597
598         ndr_err = ndr_pull_struct_blob(&blob, frame, &global_blob,
599                         (ndr_pull_flags_fn_t)ndr_pull_smbXsrv_open_globalB);
600         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
601                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
602                 DEBUG(1,("smbXsrv_open_global_verify_record: "
603                          "key '%s' ndr_pull_struct_blob - %s\n",
604                          hex_encode_talloc(frame, key.dptr, key.dsize),
605                          nt_errstr(status)));
606                 TALLOC_FREE(frame);
607                 return;
608         }
609
610         DEBUG(10,("smbXsrv_open_global_verify_record\n"));
611         if (CHECK_DEBUGLVL(10)) {
612                 NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
613         }
614
615         if (global_blob.version != SMBXSRV_VERSION_0) {
616                 DEBUG(0,("smbXsrv_open_global_verify_record: "
617                          "key '%s' use unsupported version %u\n",
618                          hex_encode_talloc(frame, key.dptr, key.dsize),
619                          global_blob.version));
620                 NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
621                 TALLOC_FREE(frame);
622                 return;
623         }
624
625         global = global_blob.info.info0;
626
627         if (server_id_is_disconnected(&global->server_id)) {
628                 exists = true;
629         } else {
630                 exists = serverid_exists(&global->server_id);
631         }
632         if (!exists) {
633                 struct server_id_buf idbuf;
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_buf(global->server_id, &idbuf)));
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         TDB_DATA key;
893
894         SBVAL(buf,  0, _open->global->open_persistent_id);
895         SBVAL(buf,  8, _open->global->open_volatile_id);
896         SBVAL(buf, 16, _open->global->open_time);
897
898         key = (TDB_DATA) { .dptr = buf, .dsize = sizeof(buf) };
899         ret = tdb_jenkins_hash(&key);
900
901         if (ret == 0) {
902                 ret = 1;
903         }
904
905         return ret;
906 }
907
908 NTSTATUS smbXsrv_open_update(struct smbXsrv_open *op)
909 {
910         struct smbXsrv_open_table *table = op->table;
911         NTSTATUS status;
912         uint8_t key_buf[SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE];
913         TDB_DATA key;
914
915         if (op->global->db_rec != NULL) {
916                 DEBUG(0, ("smbXsrv_open_update(0x%08x): "
917                           "Called with db_rec != NULL'\n",
918                           op->global->open_global_id));
919                 return NT_STATUS_INTERNAL_ERROR;
920         }
921
922         key = smbXsrv_open_global_id_to_key(op->global->open_global_id,
923                                             key_buf);
924
925         op->global->db_rec = dbwrap_fetch_locked(table->global.db_ctx,
926                                                  op->global, key);
927         if (op->global->db_rec == NULL) {
928                 DEBUG(0, ("smbXsrv_open_update(0x%08x): "
929                           "Failed to lock global key '%s'\n",
930                           op->global->open_global_id,
931                           hex_encode_talloc(talloc_tos(), key.dptr,
932                                             key.dsize)));
933                 return NT_STATUS_INTERNAL_DB_ERROR;
934         }
935
936         status = smbXsrv_open_global_store(op->global);
937         if (!NT_STATUS_IS_OK(status)) {
938                 DEBUG(0,("smbXsrv_open_update: "
939                          "global_id (0x%08x) store failed - %s\n",
940                          op->global->open_global_id,
941                          nt_errstr(status)));
942                 return status;
943         }
944
945         if (CHECK_DEBUGLVL(10)) {
946                 struct smbXsrv_openB open_blob;
947
948                 ZERO_STRUCT(open_blob);
949                 open_blob.version = SMBXSRV_VERSION_0;
950                 open_blob.info.info0 = op;
951
952                 DEBUG(10,("smbXsrv_open_update: global_id (0x%08x) stored\n",
953                           op->global->open_global_id));
954                 NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
955         }
956
957         return NT_STATUS_OK;
958 }
959
960 NTSTATUS smbXsrv_open_close(struct smbXsrv_open *op, NTTIME now)
961 {
962         struct smbXsrv_open_table *table;
963         struct db_record *local_rec = NULL;
964         struct db_record *global_rec = NULL;
965         NTSTATUS status;
966         NTSTATUS error = NT_STATUS_OK;
967
968         if (op->table == NULL) {
969                 return NT_STATUS_OK;
970         }
971
972         table = op->table;
973         op->table = NULL;
974
975         op->status = NT_STATUS_FILE_CLOSED;
976         op->global->disconnect_time = now;
977         server_id_set_disconnected(&op->global->server_id);
978
979         global_rec = op->global->db_rec;
980         op->global->db_rec = NULL;
981         if (global_rec == NULL) {
982                 uint8_t key_buf[SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE];
983                 TDB_DATA key;
984
985                 key = smbXsrv_open_global_id_to_key(
986                                                 op->global->open_global_id,
987                                                 key_buf);
988
989                 global_rec = dbwrap_fetch_locked(table->global.db_ctx,
990                                                  op->global, key);
991                 if (global_rec == NULL) {
992                         DEBUG(0, ("smbXsrv_open_close(0x%08x): "
993                                   "Failed to lock global key '%s'\n",
994                                   op->global->open_global_id,
995                                   hex_encode_talloc(global_rec, key.dptr,
996                                                     key.dsize)));
997                         error = NT_STATUS_INTERNAL_ERROR;
998                 }
999         }
1000
1001         if (global_rec != NULL && op->global->durable) {
1002                 /*
1003                  * If it is a durable open we need to update the global part
1004                  * instead of deleting it
1005                  */
1006                 op->global->db_rec = global_rec;
1007                 status = smbXsrv_open_global_store(op->global);
1008                 if (NT_STATUS_IS_OK(status)) {
1009                         /*
1010                          * smbXsrv_open_global_store does the free
1011                          * of op->global->db_rec
1012                          */
1013                         global_rec = NULL;
1014                 }
1015                 if (!NT_STATUS_IS_OK(status)) {
1016                         DEBUG(0,("smbXsrv_open_close(0x%08x)"
1017                                  "smbXsrv_open_global_store() failed - %s\n",
1018                                  op->global->open_global_id,
1019                                  nt_errstr(status)));
1020                         error = status;
1021                 }
1022
1023                 if (NT_STATUS_IS_OK(status) && CHECK_DEBUGLVL(10)) {
1024                         struct smbXsrv_openB open_blob;
1025
1026                         ZERO_STRUCT(open_blob);
1027                         open_blob.version = SMBXSRV_VERSION_0;
1028                         open_blob.info.info0 = op;
1029
1030                         DEBUG(10,("smbXsrv_open_close(0x%08x): "
1031                                   "stored disconnect\n",
1032                                   op->global->open_global_id));
1033                         NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
1034                 }
1035         }
1036
1037         if (global_rec != NULL) {
1038                 status = dbwrap_record_delete(global_rec);
1039                 if (!NT_STATUS_IS_OK(status)) {
1040                         TDB_DATA key = dbwrap_record_get_key(global_rec);
1041
1042                         DEBUG(0, ("smbXsrv_open_close(0x%08x): "
1043                                   "failed to delete global key '%s': %s\n",
1044                                   op->global->open_global_id,
1045                                   hex_encode_talloc(global_rec, key.dptr,
1046                                                     key.dsize),
1047                                   nt_errstr(status)));
1048                         error = status;
1049                 }
1050         }
1051         TALLOC_FREE(global_rec);
1052
1053         local_rec = op->db_rec;
1054         if (local_rec == NULL) {
1055                 uint8_t key_buf[SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE];
1056                 TDB_DATA key;
1057
1058                 key = smbXsrv_open_local_id_to_key(op->local_id, key_buf);
1059
1060                 local_rec = dbwrap_fetch_locked(table->local.db_ctx,
1061                                                 op, key);
1062                 if (local_rec == NULL) {
1063                         DEBUG(0, ("smbXsrv_open_close(0x%08x): "
1064                                   "Failed to lock local key '%s'\n",
1065                                   op->global->open_global_id,
1066                                   hex_encode_talloc(local_rec, key.dptr,
1067                                                     key.dsize)));
1068                         error = NT_STATUS_INTERNAL_ERROR;
1069                 }
1070         }
1071
1072         if (local_rec != NULL) {
1073                 status = dbwrap_record_delete(local_rec);
1074                 if (!NT_STATUS_IS_OK(status)) {
1075                         TDB_DATA key = dbwrap_record_get_key(local_rec);
1076
1077                         DEBUG(0, ("smbXsrv_open_close(0x%08x): "
1078                                   "failed to delete local key '%s': %s\n",
1079                                   op->global->open_global_id,
1080                                   hex_encode_talloc(local_rec, key.dptr,
1081                                                     key.dsize),
1082                                   nt_errstr(status)));
1083                         error = status;
1084                 }
1085                 table->local.num_opens -= 1;
1086         }
1087         if (op->db_rec == NULL) {
1088                 TALLOC_FREE(local_rec);
1089         }
1090         op->db_rec = NULL;
1091
1092         if (op->compat) {
1093                 op->compat->op = NULL;
1094                 file_free(NULL, op->compat);
1095                 op->compat = NULL;
1096         }
1097
1098         return error;
1099 }
1100
1101 NTSTATUS smb1srv_open_table_init(struct smbXsrv_connection *conn)
1102 {
1103         uint32_t max_opens;
1104
1105         /*
1106          * Allow a range from 1..65534.
1107          *
1108          * With real_max_open_files possible ids,
1109          * truncated to the SMB1 limit of 16-bit.
1110          *
1111          * 0 and 0xFFFF are no valid ids.
1112          */
1113         max_opens = conn->client->sconn->real_max_open_files;
1114         max_opens = MIN(max_opens, UINT16_MAX - 1);
1115
1116         return smbXsrv_open_table_init(conn, 1, UINT16_MAX - 1, max_opens);
1117 }
1118
1119 NTSTATUS smb1srv_open_lookup(struct smbXsrv_connection *conn,
1120                              uint16_t fnum, NTTIME now,
1121                              struct smbXsrv_open **_open)
1122 {
1123         struct smbXsrv_open_table *table = conn->client->open_table;
1124         uint32_t local_id = fnum;
1125         uint32_t global_id = 0;
1126
1127         return smbXsrv_open_local_lookup(table, local_id, global_id, now, _open);
1128 }
1129
1130 NTSTATUS smb2srv_open_table_init(struct smbXsrv_connection *conn)
1131 {
1132         uint32_t max_opens;
1133
1134         /*
1135          * Allow a range from 1..4294967294.
1136          *
1137          * With real_max_open_files possible ids,
1138          * truncated to 16-bit (the same as SMB1 for now).
1139          *
1140          * 0 and 0xFFFFFFFF are no valid ids.
1141          *
1142          * The usage of conn->sconn->real_max_open_files
1143          * is the reason that we use one open table per
1144          * transport connection (as we still have a 1:1 mapping
1145          * between process and transport connection).
1146          */
1147         max_opens = conn->client->sconn->real_max_open_files;
1148         max_opens = MIN(max_opens, UINT16_MAX - 1);
1149
1150         return smbXsrv_open_table_init(conn, 1, UINT32_MAX - 1, max_opens);
1151 }
1152
1153 NTSTATUS smb2srv_open_lookup(struct smbXsrv_connection *conn,
1154                              uint64_t persistent_id,
1155                              uint64_t volatile_id,
1156                              NTTIME now,
1157                              struct smbXsrv_open **_open)
1158 {
1159         struct smbXsrv_open_table *table = conn->client->open_table;
1160         uint32_t local_id = volatile_id & UINT32_MAX;
1161         uint64_t local_zeros = volatile_id & 0xFFFFFFFF00000000LLU;
1162         uint32_t global_id = persistent_id & UINT32_MAX;
1163         uint64_t global_zeros = persistent_id & 0xFFFFFFFF00000000LLU;
1164
1165         if (local_zeros != 0) {
1166                 return NT_STATUS_FILE_CLOSED;
1167         }
1168
1169         if (global_zeros != 0) {
1170                 return NT_STATUS_FILE_CLOSED;
1171         }
1172
1173         if (global_id == 0) {
1174                 return NT_STATUS_FILE_CLOSED;
1175         }
1176
1177         return smbXsrv_open_local_lookup(table, local_id, global_id, now, _open);
1178 }
1179
1180 NTSTATUS smb2srv_open_recreate(struct smbXsrv_connection *conn,
1181                                struct auth_session_info *session_info,
1182                                uint64_t persistent_id,
1183                                const struct GUID *create_guid,
1184                                NTTIME now,
1185                                struct smbXsrv_open **_open)
1186 {
1187         struct smbXsrv_open_table *table = conn->client->open_table;
1188         struct db_record *local_rec = NULL;
1189         struct smbXsrv_open *op = NULL;
1190         void *ptr = NULL;
1191         TDB_DATA val;
1192         uint32_t global_id = persistent_id & UINT32_MAX;
1193         uint64_t global_zeros = persistent_id & 0xFFFFFFFF00000000LLU;
1194         NTSTATUS status;
1195         struct security_token *current_token = NULL;
1196
1197         if (session_info == NULL) {
1198                 DEBUG(10, ("session_info=NULL\n"));
1199                 return NT_STATUS_INVALID_HANDLE;
1200         }
1201         current_token = session_info->security_token;
1202
1203         if (current_token == NULL) {
1204                 DEBUG(10, ("current_token=NULL\n"));
1205                 return NT_STATUS_INVALID_HANDLE;
1206         }
1207
1208         if (global_zeros != 0) {
1209                 DEBUG(10, ("global_zeros!=0\n"));
1210                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1211         }
1212
1213         op = talloc_zero(table, struct smbXsrv_open);
1214         if (op == NULL) {
1215                 return NT_STATUS_NO_MEMORY;
1216         }
1217         op->table = table;
1218
1219         status = smbXsrv_open_global_lookup(table, global_id, op, &op->global);
1220         if (!NT_STATUS_IS_OK(status)) {
1221                 TALLOC_FREE(op);
1222                 DEBUG(10, ("smbXsrv_open_global_lookup returned %s\n",
1223                            nt_errstr(status)));
1224                 return status;
1225         }
1226
1227         /*
1228          * If the provided create_guid is NULL, this means that
1229          * the reconnect request was a v1 request. In that case
1230          * we should skipt the create GUID verification, since
1231          * it is valid to v1-reconnect a v2-opened handle.
1232          */
1233         if ((create_guid != NULL) &&
1234             !GUID_equal(&op->global->create_guid, create_guid))
1235         {
1236                 TALLOC_FREE(op);
1237                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1238         }
1239
1240         if (!security_token_is_sid(current_token, &op->global->open_owner)) {
1241                 TALLOC_FREE(op);
1242                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1243         }
1244
1245         if (!op->global->durable) {
1246                 TALLOC_FREE(op);
1247                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1248         }
1249
1250         if (table->local.num_opens >= table->local.max_opens) {
1251                 TALLOC_FREE(op);
1252                 return NT_STATUS_INSUFFICIENT_RESOURCES;
1253         }
1254
1255         status = smbXsrv_open_local_allocate_id(table->local.db_ctx,
1256                                                 table->local.lowest_id,
1257                                                 table->local.highest_id,
1258                                                 op,
1259                                                 &local_rec,
1260                                                 &op->local_id);
1261         if (!NT_STATUS_IS_OK(status)) {
1262                 TALLOC_FREE(op);
1263                 return status;
1264         }
1265
1266         op->idle_time = now;
1267         op->status = NT_STATUS_FILE_CLOSED;
1268
1269         op->global->open_volatile_id = op->local_id;
1270         op->global->server_id = messaging_server_id(conn->msg_ctx);
1271
1272         ptr = op;
1273         val = make_tdb_data((uint8_t const *)&ptr, sizeof(ptr));
1274         status = dbwrap_record_store(local_rec, val, TDB_REPLACE);
1275         TALLOC_FREE(local_rec);
1276         if (!NT_STATUS_IS_OK(status)) {
1277                 TALLOC_FREE(op);
1278                 return status;
1279         }
1280         table->local.num_opens += 1;
1281
1282         talloc_set_destructor(op, smbXsrv_open_destructor);
1283
1284         status = smbXsrv_open_global_store(op->global);
1285         if (!NT_STATUS_IS_OK(status)) {
1286                 TALLOC_FREE(op);
1287                 return status;
1288         }
1289
1290         if (CHECK_DEBUGLVL(10)) {
1291                 struct smbXsrv_openB open_blob;
1292
1293                 ZERO_STRUCT(open_blob);
1294                 open_blob.version = 0;
1295                 open_blob.info.info0 = op;
1296
1297                 DEBUG(10,("smbXsrv_open_recreate: global_id (0x%08x) stored\n",
1298                          op->global->open_global_id));
1299                 NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
1300         }
1301
1302         *_open = op;
1303         return NT_STATUS_OK;
1304 }
1305
1306
1307 static NTSTATUS smbXsrv_open_global_parse_record(TALLOC_CTX *mem_ctx,
1308                                                  struct db_record *rec,
1309                                                  struct smbXsrv_open_global0 **global)
1310 {
1311         TDB_DATA key = dbwrap_record_get_key(rec);
1312         TDB_DATA val = dbwrap_record_get_value(rec);
1313         DATA_BLOB blob = data_blob_const(val.dptr, val.dsize);
1314         struct smbXsrv_open_globalB global_blob;
1315         enum ndr_err_code ndr_err;
1316         NTSTATUS status;
1317         TALLOC_CTX *frame = talloc_stackframe();
1318
1319         ndr_err = ndr_pull_struct_blob(&blob, frame, &global_blob,
1320                         (ndr_pull_flags_fn_t)ndr_pull_smbXsrv_open_globalB);
1321         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1322                 DEBUG(1,("Invalid record in smbXsrv_open_global.tdb:"
1323                          "key '%s' ndr_pull_struct_blob - %s\n",
1324                          hex_encode_talloc(frame, key.dptr, key.dsize),
1325                          ndr_errstr(ndr_err)));
1326                 status = ndr_map_error2ntstatus(ndr_err);
1327                 goto done;
1328         }
1329
1330         if (global_blob.version != SMBXSRV_VERSION_0) {
1331                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
1332                 DEBUG(1,("Invalid record in smbXsrv_open_global.tdb:"
1333                          "key '%s' unsuported version - %d - %s\n",
1334                          hex_encode_talloc(frame, key.dptr, key.dsize),
1335                          (int)global_blob.version,
1336                          nt_errstr(status)));
1337                 goto done;
1338         }
1339
1340         *global = talloc_move(mem_ctx, &global_blob.info.info0);
1341         status = NT_STATUS_OK;
1342 done:
1343         talloc_free(frame);
1344         return status;
1345 }
1346
1347 struct smbXsrv_open_global_traverse_state {
1348         int (*fn)(struct smbXsrv_open_global0 *, void *);
1349         void *private_data;
1350 };
1351
1352 static int smbXsrv_open_global_traverse_fn(struct db_record *rec, void *data)
1353 {
1354         struct smbXsrv_open_global_traverse_state *state =
1355                 (struct smbXsrv_open_global_traverse_state*)data;
1356         struct smbXsrv_open_global0 *global = NULL;
1357         NTSTATUS status;
1358         int ret = -1;
1359
1360         status = smbXsrv_open_global_parse_record(talloc_tos(), rec, &global);
1361         if (!NT_STATUS_IS_OK(status)) {
1362                 return -1;
1363         }
1364
1365         global->db_rec = rec;
1366         ret = state->fn(global, state->private_data);
1367         talloc_free(global);
1368         return ret;
1369 }
1370
1371 NTSTATUS smbXsrv_open_global_traverse(
1372                         int (*fn)(struct smbXsrv_open_global0 *, void *),
1373                         void *private_data)
1374 {
1375
1376         NTSTATUS status;
1377         int count = 0;
1378         struct smbXsrv_open_global_traverse_state state = {
1379                 .fn = fn,
1380                 .private_data = private_data,
1381         };
1382
1383         become_root();
1384         status = smbXsrv_open_global_init();
1385         if (!NT_STATUS_IS_OK(status)) {
1386                 unbecome_root();
1387                 DEBUG(0, ("Failed to initialize open_global: %s\n",
1388                           nt_errstr(status)));
1389                 return status;
1390         }
1391
1392         status = dbwrap_traverse_read(smbXsrv_open_global_db_ctx,
1393                                       smbXsrv_open_global_traverse_fn,
1394                                       &state,
1395                                       &count);
1396         unbecome_root();
1397
1398         return status;
1399 }
1400
1401 NTSTATUS smbXsrv_open_cleanup(uint64_t persistent_id)
1402 {
1403         NTSTATUS status = NT_STATUS_OK;
1404         TALLOC_CTX *frame = talloc_stackframe();
1405         struct smbXsrv_open_global0 *op = NULL;
1406         uint8_t key_buf[SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE];
1407         TDB_DATA key;
1408         TDB_DATA val;
1409         struct db_record *rec;
1410         bool delete_open = false;
1411         uint32_t global_id = persistent_id & UINT32_MAX;
1412
1413         key = smbXsrv_open_global_id_to_key(global_id, key_buf);
1414         rec = dbwrap_fetch_locked(smbXsrv_open_global_db_ctx, frame, key);
1415         if (rec == NULL) {
1416                 status = NT_STATUS_NOT_FOUND;
1417                 DEBUG(1, ("smbXsrv_open_cleanup[global: 0x%08x] "
1418                           "failed to fetch record from %s - %s\n",
1419                            global_id, dbwrap_name(smbXsrv_open_global_db_ctx),
1420                            nt_errstr(status)));
1421                 goto done;
1422         }
1423
1424         val = dbwrap_record_get_value(rec);
1425         if (val.dsize == 0) {
1426                 DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1427                           "empty record in %s, skipping...\n",
1428                            global_id, dbwrap_name(smbXsrv_open_global_db_ctx)));
1429                 goto done;
1430         }
1431
1432         status = smbXsrv_open_global_parse_record(talloc_tos(), rec, &op);
1433         if (!NT_STATUS_IS_OK(status)) {
1434                 DEBUG(1, ("smbXsrv_open_cleanup[global: 0x%08x] "
1435                           "failed to read record: %s\n",
1436                           global_id, nt_errstr(status)));
1437                 goto done;
1438         }
1439
1440         if (server_id_is_disconnected(&op->server_id)) {
1441                 struct timeval now, disconnect_time;
1442                 int64_t tdiff;
1443                 now = timeval_current();
1444                 nttime_to_timeval(&disconnect_time, op->disconnect_time);
1445                 tdiff = usec_time_diff(&now, &disconnect_time);
1446                 delete_open = (tdiff >= 1000*op->durable_timeout_msec);
1447
1448                 DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1449                            "disconnected at [%s] %us ago with "
1450                            "timeout of %us -%s reached\n",
1451                            global_id,
1452                            nt_time_string(frame, op->disconnect_time),
1453                            (unsigned)(tdiff/1000000),
1454                            op->durable_timeout_msec / 1000,
1455                            delete_open ? "" : " not"));
1456         } else if (!serverid_exists(&op->server_id)) {
1457                 struct server_id_buf idbuf;
1458                 DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1459                            "server[%s] does not exist\n",
1460                            global_id,
1461                            server_id_str_buf(op->server_id, &idbuf)));
1462                 delete_open = true;
1463         }
1464
1465         if (!delete_open) {
1466                 goto done;
1467         }
1468
1469         status = dbwrap_record_delete(rec);
1470         if (!NT_STATUS_IS_OK(status)) {
1471                 DEBUG(1, ("smbXsrv_open_cleanup[global: 0x%08x] "
1472                           "failed to delete record"
1473                           "from %s: %s\n", global_id,
1474                           dbwrap_name(smbXsrv_open_global_db_ctx),
1475                           nt_errstr(status)));
1476                 goto done;
1477         }
1478
1479         DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1480                    "delete record from %s\n",
1481                    global_id,
1482                    dbwrap_name(smbXsrv_open_global_db_ctx)));
1483
1484 done:
1485         talloc_free(frame);
1486         return status;
1487 }