fc7d4345067154e9856c95492a29b08b47e1ea9d
[sfrench/samba-autobuild/.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                 struct db_context *replay_cache_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 struct db_record *smbXsrv_open_global_fetch_locked(
156                         struct db_context *db,
157                         uint32_t id,
158                         TALLOC_CTX *mem_ctx)
159 {
160         TDB_DATA key;
161         uint8_t key_buf[SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE];
162         struct db_record *rec = NULL;
163
164         key = smbXsrv_open_global_id_to_key(id, key_buf);
165
166         rec = dbwrap_fetch_locked(db, mem_ctx, key);
167
168         if (rec == NULL) {
169                 DBG_DEBUG("Failed to lock global id 0x%08x, key '%s'\n", id,
170                           hex_encode_talloc(talloc_tos(), key.dptr, key.dsize));
171         }
172
173         return rec;
174 }
175
176 static struct db_record *smbXsrv_open_local_fetch_locked(
177                         struct db_context *db,
178                         uint32_t id,
179                         TALLOC_CTX *mem_ctx)
180 {
181         TDB_DATA key;
182         uint8_t key_buf[SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE];
183         struct db_record *rec = NULL;
184
185         key = smbXsrv_open_local_id_to_key(id, key_buf);
186
187         rec = dbwrap_fetch_locked(db, mem_ctx, key);
188
189         if (rec == NULL) {
190                 DBG_DEBUG("Failed to lock local id 0x%08x, key '%s'\n", id,
191                           hex_encode_talloc(talloc_tos(), key.dptr, key.dsize));
192         }
193
194         return rec;
195 }
196
197 static NTSTATUS smbXsrv_open_table_init(struct smbXsrv_connection *conn,
198                                         uint32_t lowest_id,
199                                         uint32_t highest_id,
200                                         uint32_t max_opens)
201 {
202         struct smbXsrv_client *client = conn->client;
203         struct smbXsrv_open_table *table;
204         NTSTATUS status;
205         uint64_t max_range;
206
207         if (lowest_id > highest_id) {
208                 return NT_STATUS_INTERNAL_ERROR;
209         }
210
211         max_range = highest_id;
212         max_range -= lowest_id;
213         max_range += 1;
214
215         if (max_opens > max_range) {
216                 return NT_STATUS_INTERNAL_ERROR;
217         }
218
219         table = talloc_zero(client, struct smbXsrv_open_table);
220         if (table == NULL) {
221                 return NT_STATUS_NO_MEMORY;
222         }
223
224         table->local.db_ctx = db_open_rbt(table);
225         if (table->local.db_ctx == NULL) {
226                 TALLOC_FREE(table);
227                 return NT_STATUS_NO_MEMORY;
228         }
229         table->local.replay_cache_db_ctx = db_open_rbt(table);
230         if (table->local.replay_cache_db_ctx == NULL) {
231                 TALLOC_FREE(table);
232                 return NT_STATUS_NO_MEMORY;
233         }
234         table->local.lowest_id = lowest_id;
235         table->local.highest_id = highest_id;
236         table->local.max_opens = max_opens;
237
238         status = smbXsrv_open_global_init();
239         if (!NT_STATUS_IS_OK(status)) {
240                 TALLOC_FREE(table);
241                 return status;
242         }
243
244         table->global.db_ctx = smbXsrv_open_global_db_ctx;
245
246         client->open_table = table;
247         return NT_STATUS_OK;
248 }
249
250 struct smbXsrv_open_local_allocate_state {
251         const uint32_t lowest_id;
252         const uint32_t highest_id;
253         uint32_t last_id;
254         uint32_t useable_id;
255         NTSTATUS status;
256 };
257
258 static int smbXsrv_open_local_allocate_traverse(struct db_record *rec,
259                                                    void *private_data)
260 {
261         struct smbXsrv_open_local_allocate_state *state =
262                 (struct smbXsrv_open_local_allocate_state *)private_data;
263         TDB_DATA key = dbwrap_record_get_key(rec);
264         uint32_t id = 0;
265         NTSTATUS status;
266
267         status = smbXsrv_open_local_key_to_id(key, &id);
268         if (!NT_STATUS_IS_OK(status)) {
269                 state->status = status;
270                 return -1;
271         }
272
273         if (id <= state->last_id) {
274                 state->status = NT_STATUS_INTERNAL_DB_CORRUPTION;
275                 return -1;
276         }
277         state->last_id = id;
278
279         if (id > state->useable_id) {
280                 state->status = NT_STATUS_OK;
281                 return -1;
282         }
283
284         if (state->useable_id == state->highest_id) {
285                 state->status = NT_STATUS_INSUFFICIENT_RESOURCES;
286                 return -1;
287         }
288
289         state->useable_id +=1;
290         return 0;
291 }
292
293 static NTSTATUS smbXsrv_open_local_allocate_id(struct db_context *db,
294                                                uint32_t lowest_id,
295                                                uint32_t highest_id,
296                                                TALLOC_CTX *mem_ctx,
297                                                struct db_record **_rec,
298                                                uint32_t *_id)
299 {
300         struct smbXsrv_open_local_allocate_state state = {
301                 .lowest_id = lowest_id,
302                 .highest_id = highest_id,
303                 .last_id = 0,
304                 .useable_id = lowest_id,
305                 .status = NT_STATUS_INTERNAL_ERROR,
306         };
307         uint32_t i;
308         uint32_t range;
309         NTSTATUS status;
310         int count = 0;
311
312         *_rec = NULL;
313         *_id = 0;
314
315         if (lowest_id > highest_id) {
316                 return NT_STATUS_INSUFFICIENT_RESOURCES;
317         }
318
319         /*
320          * first we try randomly
321          */
322         range = (highest_id - lowest_id) + 1;
323
324         for (i = 0; i < (range / 2); i++) {
325                 uint32_t id;
326                 TDB_DATA val;
327                 struct db_record *rec = NULL;
328
329                 id = generate_random() % range;
330                 id += lowest_id;
331
332                 if (id < lowest_id) {
333                         id = lowest_id;
334                 }
335                 if (id > highest_id) {
336                         id = highest_id;
337                 }
338
339                 rec = smbXsrv_open_local_fetch_locked(db, id, mem_ctx);
340                 if (rec == NULL) {
341                         return NT_STATUS_INSUFFICIENT_RESOURCES;
342                 }
343
344                 val = dbwrap_record_get_value(rec);
345                 if (val.dsize != 0) {
346                         TALLOC_FREE(rec);
347                         continue;
348                 }
349
350                 *_rec = rec;
351                 *_id = id;
352                 return NT_STATUS_OK;
353         }
354
355         /*
356          * if the range is almost full,
357          * we traverse the whole table
358          * (this relies on sorted behavior of dbwrap_rbt)
359          */
360         status = dbwrap_traverse_read(db, smbXsrv_open_local_allocate_traverse,
361                                       &state, &count);
362         if (NT_STATUS_IS_OK(status)) {
363                 if (NT_STATUS_IS_OK(state.status)) {
364                         return NT_STATUS_INTERNAL_ERROR;
365                 }
366
367                 if (!NT_STATUS_EQUAL(state.status, NT_STATUS_INTERNAL_ERROR)) {
368                         return state.status;
369                 }
370
371                 if (state.useable_id <= state.highest_id) {
372                         state.status = NT_STATUS_OK;
373                 } else {
374                         return NT_STATUS_INSUFFICIENT_RESOURCES;
375                 }
376         } else if (!NT_STATUS_EQUAL(status, NT_STATUS_INTERNAL_DB_CORRUPTION)) {
377                 /*
378                  * Here we really expect NT_STATUS_INTERNAL_DB_CORRUPTION!
379                  *
380                  * If we get anything else it is an error, because it
381                  * means we did not manage to find a free slot in
382                  * the db.
383                  */
384                 return NT_STATUS_INSUFFICIENT_RESOURCES;
385         }
386
387         if (NT_STATUS_IS_OK(state.status)) {
388                 uint32_t id;
389                 TDB_DATA val;
390                 struct db_record *rec = NULL;
391
392                 id = state.useable_id;
393
394                 rec = smbXsrv_open_local_fetch_locked(db, id, mem_ctx);
395                 if (rec == NULL) {
396                         return NT_STATUS_INSUFFICIENT_RESOURCES;
397                 }
398
399                 val = dbwrap_record_get_value(rec);
400                 if (val.dsize != 0) {
401                         TALLOC_FREE(rec);
402                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
403                 }
404
405                 *_rec = rec;
406                 *_id = id;
407                 return NT_STATUS_OK;
408         }
409
410         return state.status;
411 }
412
413 struct smbXsrv_open_local_fetch_state {
414         struct smbXsrv_open *op;
415         NTSTATUS status;
416 };
417
418 static void smbXsrv_open_local_fetch_parser(TDB_DATA key, TDB_DATA data,
419                                             void *private_data)
420 {
421         struct smbXsrv_open_local_fetch_state *state =
422                 (struct smbXsrv_open_local_fetch_state *)private_data;
423         void *ptr;
424
425         if (data.dsize != sizeof(ptr)) {
426                 state->status = NT_STATUS_INTERNAL_DB_ERROR;
427                 return;
428         }
429
430         memcpy(&ptr, data.dptr, data.dsize);
431         state->op = talloc_get_type_abort(ptr, struct smbXsrv_open);
432         state->status = NT_STATUS_OK;
433 }
434
435 static NTSTATUS smbXsrv_open_local_lookup(struct smbXsrv_open_table *table,
436                                           uint32_t open_local_id,
437                                           uint32_t open_global_id,
438                                           NTTIME now,
439                                           struct smbXsrv_open **_open)
440 {
441         struct smbXsrv_open_local_fetch_state state = {
442                 .op = NULL,
443                 .status = NT_STATUS_INTERNAL_ERROR,
444         };
445         uint8_t key_buf[SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE];
446         TDB_DATA key;
447         NTSTATUS status;
448
449         *_open = NULL;
450
451         if (open_local_id == 0) {
452                 return NT_STATUS_FILE_CLOSED;
453         }
454
455         if (table == NULL) {
456                 /* this might happen before the end of negprot */
457                 return NT_STATUS_FILE_CLOSED;
458         }
459
460         if (table->local.db_ctx == NULL) {
461                 return NT_STATUS_INTERNAL_ERROR;
462         }
463
464         key = smbXsrv_open_local_id_to_key(open_local_id, key_buf);
465
466         status = dbwrap_parse_record(table->local.db_ctx, key,
467                                      smbXsrv_open_local_fetch_parser,
468                                      &state);
469         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
470                 return NT_STATUS_FILE_CLOSED;
471         }
472         if (!NT_STATUS_IS_OK(status)) {
473                 return status;
474         }
475         if (!NT_STATUS_IS_OK(state.status)) {
476                 return state.status;
477         }
478
479         if (NT_STATUS_EQUAL(state.op->status, NT_STATUS_FILE_CLOSED)) {
480                 return NT_STATUS_FILE_CLOSED;
481         }
482
483         if (open_global_id == 0) {
484                 /* make the global check a no-op for SMB1 */
485                 open_global_id = state.op->global->open_global_id;
486         }
487
488         if (state.op->global->open_global_id != open_global_id) {
489                 return NT_STATUS_FILE_CLOSED;
490         }
491
492         if (now != 0) {
493                 state.op->idle_time = now;
494         }
495
496         *_open = state.op;
497         return state.op->status;
498 }
499
500 static int smbXsrv_open_global_destructor(struct smbXsrv_open_global0 *global)
501 {
502         return 0;
503 }
504
505 static void smbXsrv_open_global_verify_record(struct db_record *db_rec,
506                                         bool *is_free,
507                                         bool *was_free,
508                                         TALLOC_CTX *mem_ctx,
509                                         struct smbXsrv_open_global0 **_g);
510
511 static NTSTATUS smbXsrv_open_global_allocate(struct db_context *db,
512                                         TALLOC_CTX *mem_ctx,
513                                         struct smbXsrv_open_global0 **_global)
514 {
515         uint32_t i;
516         struct smbXsrv_open_global0 *global = NULL;
517         uint32_t last_free = 0;
518         const uint32_t min_tries = 3;
519
520         *_global = NULL;
521
522         global = talloc_zero(mem_ctx, struct smbXsrv_open_global0);
523         if (global == NULL) {
524                 return NT_STATUS_NO_MEMORY;
525         }
526         talloc_set_destructor(global, smbXsrv_open_global_destructor);
527
528         /*
529          * Here we just randomly try the whole 32-bit space
530          *
531          * We use just 32-bit, because we want to reuse the
532          * ID for SRVSVC.
533          */
534         for (i = 0; i < UINT32_MAX; i++) {
535                 bool is_free = false;
536                 bool was_free = false;
537                 uint32_t id;
538
539                 if (i >= min_tries && last_free != 0) {
540                         id = last_free;
541                 } else {
542                         id = generate_random();
543                 }
544                 if (id == 0) {
545                         id++;
546                 }
547                 if (id == UINT32_MAX) {
548                         id--;
549                 }
550
551                 global->db_rec = smbXsrv_open_global_fetch_locked(db, id, mem_ctx);
552                 if (global->db_rec == NULL) {
553                         talloc_free(global);
554                         return NT_STATUS_INSUFFICIENT_RESOURCES;
555                 }
556
557                 smbXsrv_open_global_verify_record(global->db_rec,
558                                                   &is_free,
559                                                   &was_free,
560                                                   NULL, NULL);
561
562                 if (!is_free) {
563                         TALLOC_FREE(global->db_rec);
564                         continue;
565                 }
566
567                 if (!was_free && i < min_tries) {
568                         /*
569                          * The session_id is free now,
570                          * but was not free before.
571                          *
572                          * This happens if a smbd crashed
573                          * and did not cleanup the record.
574                          *
575                          * If this is one of our first tries,
576                          * then we try to find a real free one.
577                          */
578                         if (last_free == 0) {
579                                 last_free = id;
580                         }
581                         TALLOC_FREE(global->db_rec);
582                         continue;
583                 }
584
585                 global->open_global_id = id;
586
587                 *_global = global;
588                 return NT_STATUS_OK;
589         }
590
591         /* should not be reached */
592         talloc_free(global);
593         return NT_STATUS_INTERNAL_ERROR;
594 }
595
596 static void smbXsrv_open_global_verify_record(struct db_record *db_rec,
597                                         bool *is_free,
598                                         bool *was_free,
599                                         TALLOC_CTX *mem_ctx,
600                                         struct smbXsrv_open_global0 **_g)
601 {
602         TDB_DATA key;
603         TDB_DATA val;
604         DATA_BLOB blob;
605         struct smbXsrv_open_globalB global_blob;
606         enum ndr_err_code ndr_err;
607         struct smbXsrv_open_global0 *global = NULL;
608         bool exists;
609         TALLOC_CTX *frame = talloc_stackframe();
610
611         *is_free = false;
612
613         if (was_free) {
614                 *was_free = false;
615         }
616         if (_g) {
617                 *_g = NULL;
618         }
619
620         key = dbwrap_record_get_key(db_rec);
621
622         val = dbwrap_record_get_value(db_rec);
623         if (val.dsize == 0) {
624                 DEBUG(10, ("%s: empty value\n", __func__));
625                 TALLOC_FREE(frame);
626                 *is_free = true;
627                 if (was_free) {
628                         *was_free = true;
629                 }
630                 return;
631         }
632
633         blob = data_blob_const(val.dptr, val.dsize);
634
635         ndr_err = ndr_pull_struct_blob(&blob, frame, &global_blob,
636                         (ndr_pull_flags_fn_t)ndr_pull_smbXsrv_open_globalB);
637         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
638                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
639                 DEBUG(1,("smbXsrv_open_global_verify_record: "
640                          "key '%s' ndr_pull_struct_blob - %s\n",
641                          hex_encode_talloc(frame, key.dptr, key.dsize),
642                          nt_errstr(status)));
643                 TALLOC_FREE(frame);
644                 return;
645         }
646
647         DEBUG(10,("smbXsrv_open_global_verify_record\n"));
648         if (CHECK_DEBUGLVL(10)) {
649                 NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
650         }
651
652         if (global_blob.version != SMBXSRV_VERSION_0) {
653                 DEBUG(0,("smbXsrv_open_global_verify_record: "
654                          "key '%s' use unsupported version %u\n",
655                          hex_encode_talloc(frame, key.dptr, key.dsize),
656                          global_blob.version));
657                 NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
658                 TALLOC_FREE(frame);
659                 return;
660         }
661
662         global = global_blob.info.info0;
663
664         if (server_id_is_disconnected(&global->server_id)) {
665                 exists = true;
666         } else {
667                 exists = serverid_exists(&global->server_id);
668         }
669         if (!exists) {
670                 struct server_id_buf idbuf;
671                 DEBUG(2,("smbXsrv_open_global_verify_record: "
672                          "key '%s' server_id %s does not exist.\n",
673                          hex_encode_talloc(frame, key.dptr, key.dsize),
674                          server_id_str_buf(global->server_id, &idbuf)));
675                 if (CHECK_DEBUGLVL(2)) {
676                         NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
677                 }
678                 TALLOC_FREE(frame);
679                 dbwrap_record_delete(db_rec);
680                 *is_free = true;
681                 return;
682         }
683
684         if (_g) {
685                 *_g = talloc_move(mem_ctx, &global);
686         }
687         TALLOC_FREE(frame);
688 }
689
690 static NTSTATUS smbXsrv_open_global_store(struct smbXsrv_open_global0 *global)
691 {
692         struct smbXsrv_open_globalB global_blob;
693         DATA_BLOB blob = data_blob_null;
694         TDB_DATA key;
695         TDB_DATA val;
696         NTSTATUS status;
697         enum ndr_err_code ndr_err;
698
699         /*
700          * TODO: if we use other versions than '0'
701          * we would add glue code here, that would be able to
702          * store the information in the old format.
703          */
704
705         if (global->db_rec == NULL) {
706                 return NT_STATUS_INTERNAL_ERROR;
707         }
708
709         key = dbwrap_record_get_key(global->db_rec);
710         val = dbwrap_record_get_value(global->db_rec);
711
712         ZERO_STRUCT(global_blob);
713         global_blob.version = smbXsrv_version_global_current();
714         if (val.dsize >= 8) {
715                 global_blob.seqnum = IVAL(val.dptr, 4);
716         }
717         global_blob.seqnum += 1;
718         global_blob.info.info0 = global;
719
720         ndr_err = ndr_push_struct_blob(&blob, global->db_rec, &global_blob,
721                         (ndr_push_flags_fn_t)ndr_push_smbXsrv_open_globalB);
722         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
723                 status = ndr_map_error2ntstatus(ndr_err);
724                 DEBUG(1,("smbXsrv_open_global_store: key '%s' ndr_push - %s\n",
725                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize),
726                          nt_errstr(status)));
727                 TALLOC_FREE(global->db_rec);
728                 return status;
729         }
730
731         val = make_tdb_data(blob.data, blob.length);
732         status = dbwrap_record_store(global->db_rec, val, TDB_REPLACE);
733         if (!NT_STATUS_IS_OK(status)) {
734                 DEBUG(1,("smbXsrv_open_global_store: key '%s' store - %s\n",
735                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize),
736                          nt_errstr(status)));
737                 TALLOC_FREE(global->db_rec);
738                 return status;
739         }
740
741         if (CHECK_DEBUGLVL(10)) {
742                 DEBUG(10,("smbXsrv_open_global_store: key '%s' stored\n",
743                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize)));
744                 NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
745         }
746
747         TALLOC_FREE(global->db_rec);
748
749         return NT_STATUS_OK;
750 }
751
752 static NTSTATUS smbXsrv_open_global_lookup(struct smbXsrv_open_table *table,
753                                            uint32_t open_global_id,
754                                            TALLOC_CTX *mem_ctx,
755                                            struct smbXsrv_open_global0 **_global)
756 {
757         struct db_record *global_rec = NULL;
758         bool is_free = false;
759
760         *_global = NULL;
761
762         if (table->global.db_ctx == NULL) {
763                 return NT_STATUS_INTERNAL_ERROR;
764         }
765
766         global_rec = smbXsrv_open_global_fetch_locked(table->global.db_ctx,
767                                                       open_global_id,
768                                                       mem_ctx);
769         if (global_rec == NULL) {
770                 return NT_STATUS_INTERNAL_DB_ERROR;
771         }
772
773         smbXsrv_open_global_verify_record(global_rec,
774                                           &is_free,
775                                           NULL,
776                                           mem_ctx,
777                                           _global);
778         if (is_free) {
779                 DEBUG(10, ("%s: is_free=true\n", __func__));
780                 talloc_free(global_rec);
781                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
782         }
783
784         (*_global)->db_rec = talloc_move(*_global, &global_rec);
785
786         talloc_set_destructor(*_global, smbXsrv_open_global_destructor);
787
788         return NT_STATUS_OK;
789 }
790
791 static int smbXsrv_open_destructor(struct smbXsrv_open *op)
792 {
793         NTSTATUS status;
794
795         status = smbXsrv_open_close(op, 0);
796         if (!NT_STATUS_IS_OK(status)) {
797                 DEBUG(0, ("smbXsrv_open_destructor: "
798                           "smbXsrv_open_close() failed - %s\n",
799                           nt_errstr(status)));
800         }
801
802         TALLOC_FREE(op->global);
803
804         return 0;
805 }
806
807 NTSTATUS smbXsrv_open_create(struct smbXsrv_connection *conn,
808                              struct auth_session_info *session_info,
809                              NTTIME now,
810                              struct smbXsrv_open **_open)
811 {
812         struct smbXsrv_open_table *table = conn->client->open_table;
813         struct db_record *local_rec = NULL;
814         struct smbXsrv_open *op = NULL;
815         void *ptr = NULL;
816         TDB_DATA val;
817         struct smbXsrv_open_global0 *global = NULL;
818         NTSTATUS status;
819         struct dom_sid *current_sid = NULL;
820         struct security_token *current_token = NULL;
821
822         if (session_info == NULL) {
823                 return NT_STATUS_INVALID_HANDLE;
824         }
825         current_token = session_info->security_token;
826
827         if (current_token == NULL) {
828                 return NT_STATUS_INVALID_HANDLE;
829         }
830
831         if (current_token->num_sids > PRIMARY_USER_SID_INDEX) {
832                 current_sid = &current_token->sids[PRIMARY_USER_SID_INDEX];
833         }
834
835         if (current_sid == NULL) {
836                 return NT_STATUS_INVALID_HANDLE;
837         }
838
839         if (table->local.num_opens >= table->local.max_opens) {
840                 return NT_STATUS_INSUFFICIENT_RESOURCES;
841         }
842
843         op = talloc_zero(table, struct smbXsrv_open);
844         if (op == NULL) {
845                 return NT_STATUS_NO_MEMORY;
846         }
847         op->table = table;
848         op->status = NT_STATUS_OK; /* TODO: start with INTERNAL_ERROR */
849         op->idle_time = now;
850
851         status = smbXsrv_open_global_allocate(table->global.db_ctx,
852                                               op, &global);
853         if (!NT_STATUS_IS_OK(status)) {
854                 TALLOC_FREE(op);
855                 return status;
856         }
857         op->global = global;
858
859         status = smbXsrv_open_local_allocate_id(table->local.db_ctx,
860                                                 table->local.lowest_id,
861                                                 table->local.highest_id,
862                                                 op,
863                                                 &local_rec,
864                                                 &op->local_id);
865         if (!NT_STATUS_IS_OK(status)) {
866                 TALLOC_FREE(op);
867                 return status;
868         }
869
870         global->open_persistent_id = global->open_global_id;
871         global->open_volatile_id = op->local_id;
872
873         global->server_id = messaging_server_id(conn->msg_ctx);
874         global->open_time = now;
875         global->open_owner = *current_sid;
876         if (conn->protocol >= PROTOCOL_SMB2_10) {
877                 global->client_guid = conn->smb2.client.guid;
878         }
879
880         ptr = op;
881         val = make_tdb_data((uint8_t const *)&ptr, sizeof(ptr));
882         status = dbwrap_record_store(local_rec, val, TDB_REPLACE);
883         TALLOC_FREE(local_rec);
884         if (!NT_STATUS_IS_OK(status)) {
885                 TALLOC_FREE(op);
886                 return status;
887         }
888         table->local.num_opens += 1;
889
890         talloc_set_destructor(op, smbXsrv_open_destructor);
891
892         status = smbXsrv_open_global_store(global);
893         if (!NT_STATUS_IS_OK(status)) {
894                 DEBUG(0,("smbXsrv_open_create: "
895                          "global_id (0x%08x) store failed - %s\n",
896                          op->global->open_global_id,
897                          nt_errstr(status)));
898                 TALLOC_FREE(op);
899                 return status;
900         }
901
902         if (CHECK_DEBUGLVL(10)) {
903                 struct smbXsrv_openB open_blob;
904
905                 ZERO_STRUCT(open_blob);
906                 open_blob.version = SMBXSRV_VERSION_0;
907                 open_blob.info.info0 = op;
908
909                 DEBUG(10,("smbXsrv_open_create: global_id (0x%08x) stored\n",
910                          op->global->open_global_id));
911                 NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
912         }
913
914         *_open = op;
915         return NT_STATUS_OK;
916 }
917
918 uint32_t smbXsrv_open_hash(struct smbXsrv_open *_open)
919 {
920         uint8_t buf[8+8+8];
921         uint32_t ret;
922         TDB_DATA key;
923
924         SBVAL(buf,  0, _open->global->open_persistent_id);
925         SBVAL(buf,  8, _open->global->open_volatile_id);
926         SBVAL(buf, 16, _open->global->open_time);
927
928         key = (TDB_DATA) { .dptr = buf, .dsize = sizeof(buf) };
929         ret = tdb_jenkins_hash(&key);
930
931         if (ret == 0) {
932                 ret = 1;
933         }
934
935         return ret;
936 }
937
938 static NTSTATUS smbXsrv_open_set_replay_cache(struct smbXsrv_open *op)
939 {
940         struct GUID *create_guid;
941         struct GUID_txt_buf buf;
942         char *guid_string;
943         struct db_context *db = op->table->local.replay_cache_db_ctx;
944         NTSTATUS status;
945
946         if (!(op->flags & SMBXSRV_OPEN_NEED_REPLAY_CACHE)) {
947                 return NT_STATUS_OK;
948         }
949
950         if (op->flags & SMBXSRV_OPEN_HAVE_REPLAY_CACHE) {
951                 return NT_STATUS_OK;
952         }
953
954         create_guid = &op->global->create_guid;
955         if (GUID_all_zero(create_guid)) {
956                 return NT_STATUS_OK;
957         }
958
959         guid_string = GUID_buf_string(create_guid, &buf);
960         if (guid_string == NULL) {
961                 return NT_STATUS_INVALID_PARAMETER;
962         }
963
964         status = dbwrap_store_uint32_bystring(db, guid_string, op->local_id);
965
966         if (NT_STATUS_IS_OK(status)) {
967                 op->flags |= SMBXSRV_OPEN_HAVE_REPLAY_CACHE;
968                 op->flags &= ~SMBXSRV_OPEN_NEED_REPLAY_CACHE;
969         }
970
971         return status;
972 }
973
974 static NTSTATUS smbXsrv_open_clear_replay_cache(struct smbXsrv_open *op)
975 {
976         struct GUID *create_guid;
977         struct GUID_txt_buf buf;
978         char *guid_string;
979         struct db_context *db;
980         NTSTATUS status;
981
982         if (op->table == NULL) {
983                 return NT_STATUS_OK;
984         }
985
986         db = op->table->local.replay_cache_db_ctx;
987
988         if (!(op->flags & SMBXSRV_OPEN_HAVE_REPLAY_CACHE)) {
989                 return NT_STATUS_OK;
990         }
991
992         create_guid = &op->global->create_guid;
993         if (GUID_all_zero(create_guid)) {
994                 return NT_STATUS_OK;
995         }
996
997         guid_string = GUID_buf_string(create_guid, &buf);
998         if (guid_string == NULL) {
999                 return NT_STATUS_INVALID_PARAMETER;
1000         }
1001
1002         status = dbwrap_purge_bystring(db, guid_string);
1003
1004         if (NT_STATUS_IS_OK(status)) {
1005                 op->flags &= ~SMBXSRV_OPEN_HAVE_REPLAY_CACHE;
1006         }
1007
1008         return status;
1009 }
1010
1011 NTSTATUS smbXsrv_open_update(struct smbXsrv_open *op)
1012 {
1013         struct smbXsrv_open_table *table = op->table;
1014         NTSTATUS status;
1015
1016         if (op->global->db_rec != NULL) {
1017                 DEBUG(0, ("smbXsrv_open_update(0x%08x): "
1018                           "Called with db_rec != NULL'\n",
1019                           op->global->open_global_id));
1020                 return NT_STATUS_INTERNAL_ERROR;
1021         }
1022
1023         op->global->db_rec = smbXsrv_open_global_fetch_locked(
1024                                                 table->global.db_ctx,
1025                                                 op->global->open_global_id,
1026                                                 op->global /* TALLOC_CTX */);
1027         if (op->global->db_rec == NULL) {
1028                 return NT_STATUS_INTERNAL_DB_ERROR;
1029         }
1030
1031         status = smbXsrv_open_global_store(op->global);
1032         if (!NT_STATUS_IS_OK(status)) {
1033                 DEBUG(0,("smbXsrv_open_update: "
1034                          "global_id (0x%08x) store failed - %s\n",
1035                          op->global->open_global_id,
1036                          nt_errstr(status)));
1037                 return status;
1038         }
1039
1040         status = smbXsrv_open_set_replay_cache(op);
1041         if (!NT_STATUS_IS_OK(status)) {
1042                 DBG_ERR("smbXsrv_open_set_replay_cache failed: %s\n",
1043                         nt_errstr(status));
1044                 return status;
1045         }
1046
1047         if (CHECK_DEBUGLVL(10)) {
1048                 struct smbXsrv_openB open_blob;
1049
1050                 ZERO_STRUCT(open_blob);
1051                 open_blob.version = SMBXSRV_VERSION_0;
1052                 open_blob.info.info0 = op;
1053
1054                 DEBUG(10,("smbXsrv_open_update: global_id (0x%08x) stored\n",
1055                           op->global->open_global_id));
1056                 NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
1057         }
1058
1059         return NT_STATUS_OK;
1060 }
1061
1062 NTSTATUS smbXsrv_open_close(struct smbXsrv_open *op, NTTIME now)
1063 {
1064         struct smbXsrv_open_table *table;
1065         struct db_record *local_rec = NULL;
1066         struct db_record *global_rec = NULL;
1067         NTSTATUS status;
1068         NTSTATUS error = NT_STATUS_OK;
1069
1070         error = smbXsrv_open_clear_replay_cache(op);
1071         if (!NT_STATUS_IS_OK(error)) {
1072                 DBG_ERR("smbXsrv_open_clear_replay_cache failed: %s\n",
1073                         nt_errstr(error));
1074         }
1075
1076         if (op->table == NULL) {
1077                 return error;
1078         }
1079
1080         table = op->table;
1081         op->table = NULL;
1082
1083         op->status = NT_STATUS_FILE_CLOSED;
1084         op->global->disconnect_time = now;
1085         server_id_set_disconnected(&op->global->server_id);
1086
1087         global_rec = op->global->db_rec;
1088         op->global->db_rec = NULL;
1089         if (global_rec == NULL) {
1090                 global_rec = smbXsrv_open_global_fetch_locked(
1091                                         table->global.db_ctx,
1092                                         op->global->open_global_id,
1093                                         op->global /* TALLOC_CTX */);
1094                 if (global_rec == NULL) {
1095                         error = NT_STATUS_INTERNAL_ERROR;
1096                 }
1097         }
1098
1099         if (global_rec != NULL && op->global->durable) {
1100                 /*
1101                  * If it is a durable open we need to update the global part
1102                  * instead of deleting it
1103                  */
1104                 op->global->db_rec = global_rec;
1105                 status = smbXsrv_open_global_store(op->global);
1106                 if (NT_STATUS_IS_OK(status)) {
1107                         /*
1108                          * smbXsrv_open_global_store does the free
1109                          * of op->global->db_rec
1110                          */
1111                         global_rec = NULL;
1112                 }
1113                 if (!NT_STATUS_IS_OK(status)) {
1114                         DEBUG(0,("smbXsrv_open_close(0x%08x)"
1115                                  "smbXsrv_open_global_store() failed - %s\n",
1116                                  op->global->open_global_id,
1117                                  nt_errstr(status)));
1118                         error = status;
1119                 }
1120
1121                 if (NT_STATUS_IS_OK(status) && CHECK_DEBUGLVL(10)) {
1122                         struct smbXsrv_openB open_blob;
1123
1124                         ZERO_STRUCT(open_blob);
1125                         open_blob.version = SMBXSRV_VERSION_0;
1126                         open_blob.info.info0 = op;
1127
1128                         DEBUG(10,("smbXsrv_open_close(0x%08x): "
1129                                   "stored disconnect\n",
1130                                   op->global->open_global_id));
1131                         NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
1132                 }
1133         }
1134
1135         if (global_rec != NULL) {
1136                 status = dbwrap_record_delete(global_rec);
1137                 if (!NT_STATUS_IS_OK(status)) {
1138                         TDB_DATA key = dbwrap_record_get_key(global_rec);
1139
1140                         DEBUG(0, ("smbXsrv_open_close(0x%08x): "
1141                                   "failed to delete global key '%s': %s\n",
1142                                   op->global->open_global_id,
1143                                   hex_encode_talloc(global_rec, key.dptr,
1144                                                     key.dsize),
1145                                   nt_errstr(status)));
1146                         error = status;
1147                 }
1148         }
1149         TALLOC_FREE(global_rec);
1150
1151         local_rec = op->db_rec;
1152         if (local_rec == NULL) {
1153                 local_rec = smbXsrv_open_local_fetch_locked(table->local.db_ctx,
1154                                                             op->local_id,
1155                                                             op /* TALLOC_CTX*/);
1156                 if (local_rec == NULL) {
1157                         error = NT_STATUS_INTERNAL_ERROR;
1158                 }
1159         }
1160
1161         if (local_rec != NULL) {
1162                 status = dbwrap_record_delete(local_rec);
1163                 if (!NT_STATUS_IS_OK(status)) {
1164                         TDB_DATA key = dbwrap_record_get_key(local_rec);
1165
1166                         DEBUG(0, ("smbXsrv_open_close(0x%08x): "
1167                                   "failed to delete local key '%s': %s\n",
1168                                   op->global->open_global_id,
1169                                   hex_encode_talloc(local_rec, key.dptr,
1170                                                     key.dsize),
1171                                   nt_errstr(status)));
1172                         error = status;
1173                 }
1174                 table->local.num_opens -= 1;
1175         }
1176         if (op->db_rec == NULL) {
1177                 TALLOC_FREE(local_rec);
1178         }
1179         op->db_rec = NULL;
1180
1181         if (op->compat) {
1182                 op->compat->op = NULL;
1183                 file_free(NULL, op->compat);
1184                 op->compat = NULL;
1185         }
1186
1187         return error;
1188 }
1189
1190 NTSTATUS smb1srv_open_table_init(struct smbXsrv_connection *conn)
1191 {
1192         uint32_t max_opens;
1193
1194         /*
1195          * Allow a range from 1..65534.
1196          *
1197          * With real_max_open_files possible ids,
1198          * truncated to the SMB1 limit of 16-bit.
1199          *
1200          * 0 and 0xFFFF are no valid ids.
1201          */
1202         max_opens = conn->client->sconn->real_max_open_files;
1203         max_opens = MIN(max_opens, UINT16_MAX - 1);
1204
1205         return smbXsrv_open_table_init(conn, 1, UINT16_MAX - 1, max_opens);
1206 }
1207
1208 NTSTATUS smb1srv_open_lookup(struct smbXsrv_connection *conn,
1209                              uint16_t fnum, NTTIME now,
1210                              struct smbXsrv_open **_open)
1211 {
1212         struct smbXsrv_open_table *table = conn->client->open_table;
1213         uint32_t local_id = fnum;
1214         uint32_t global_id = 0;
1215
1216         return smbXsrv_open_local_lookup(table, local_id, global_id, now, _open);
1217 }
1218
1219 NTSTATUS smb2srv_open_table_init(struct smbXsrv_connection *conn)
1220 {
1221         uint32_t max_opens;
1222
1223         /*
1224          * Allow a range from 1..4294967294.
1225          *
1226          * With real_max_open_files possible ids,
1227          * truncated to 16-bit (the same as SMB1 for now).
1228          *
1229          * 0 and 0xFFFFFFFF are no valid ids.
1230          *
1231          * The usage of conn->sconn->real_max_open_files
1232          * is the reason that we use one open table per
1233          * transport connection (as we still have a 1:1 mapping
1234          * between process and transport connection).
1235          */
1236         max_opens = conn->client->sconn->real_max_open_files;
1237         max_opens = MIN(max_opens, UINT16_MAX - 1);
1238
1239         return smbXsrv_open_table_init(conn, 1, UINT32_MAX - 1, max_opens);
1240 }
1241
1242 NTSTATUS smb2srv_open_lookup(struct smbXsrv_connection *conn,
1243                              uint64_t persistent_id,
1244                              uint64_t volatile_id,
1245                              NTTIME now,
1246                              struct smbXsrv_open **_open)
1247 {
1248         struct smbXsrv_open_table *table = conn->client->open_table;
1249         uint32_t local_id = volatile_id & UINT32_MAX;
1250         uint64_t local_zeros = volatile_id & 0xFFFFFFFF00000000LLU;
1251         uint32_t global_id = persistent_id & UINT32_MAX;
1252         uint64_t global_zeros = persistent_id & 0xFFFFFFFF00000000LLU;
1253         NTSTATUS status;
1254
1255         if (local_zeros != 0) {
1256                 return NT_STATUS_FILE_CLOSED;
1257         }
1258
1259         if (global_zeros != 0) {
1260                 return NT_STATUS_FILE_CLOSED;
1261         }
1262
1263         if (global_id == 0) {
1264                 return NT_STATUS_FILE_CLOSED;
1265         }
1266
1267         status = smbXsrv_open_local_lookup(table, local_id, global_id, now,
1268                                            _open);
1269         if (!NT_STATUS_IS_OK(status)) {
1270                 return status;
1271         }
1272
1273         /*
1274          * Clear the replay cache for this create_guid if it exists:
1275          * This is based on the assumption that this lookup will be
1276          * triggered by a client request using the file-id for lookup.
1277          * Hence the client has proven that it has in fact seen the
1278          * reply to its initial create call. So subsequent create replays
1279          * should be treated as invalid. Hence the index for create_guid
1280          * lookup needs to be removed.
1281          */
1282         status = smbXsrv_open_clear_replay_cache(*_open);
1283
1284         return status;
1285 }
1286
1287 NTSTATUS smb2srv_open_lookup_replay_cache(struct smbXsrv_connection *conn,
1288                                           const struct GUID *create_guid,
1289                                           NTTIME now, /* TODO: needed ? */
1290                                           struct smbXsrv_open **_open)
1291 {
1292         NTSTATUS status;
1293         char *guid_string;
1294         struct GUID_txt_buf buf;
1295         uint32_t local_id = 0;
1296         struct smbXsrv_open_table *table = conn->client->open_table;
1297         struct db_context *db = table->local.replay_cache_db_ctx;
1298
1299         if (GUID_all_zero(create_guid)) {
1300                 return NT_STATUS_NOT_FOUND;
1301         }
1302
1303         guid_string = GUID_buf_string(create_guid, &buf);
1304         if (guid_string == NULL) {
1305                 return NT_STATUS_INVALID_PARAMETER;
1306         }
1307
1308         status = dbwrap_fetch_uint32_bystring(db, guid_string, &local_id);
1309         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
1310                 return status;
1311         }
1312         if (!NT_STATUS_IS_OK(status)) {
1313                 DBG_ERR("failed to fetch local_id from replay cache: %s\n",
1314                         nt_errstr(status));
1315                 return status;
1316         }
1317
1318         status = smbXsrv_open_local_lookup(table, local_id, 0, /* global_id */
1319                                            now, _open);
1320         if (!NT_STATUS_IS_OK(status)) {
1321                 DBG_ERR("smbXsrv_open_local_lookup failed for local_id %u\n",
1322                         (unsigned)local_id);
1323         }
1324
1325         return status;
1326 }
1327
1328 NTSTATUS smb2srv_open_recreate(struct smbXsrv_connection *conn,
1329                                struct auth_session_info *session_info,
1330                                uint64_t persistent_id,
1331                                const struct GUID *create_guid,
1332                                NTTIME now,
1333                                struct smbXsrv_open **_open)
1334 {
1335         struct smbXsrv_open_table *table = conn->client->open_table;
1336         struct db_record *local_rec = NULL;
1337         struct smbXsrv_open *op = NULL;
1338         void *ptr = NULL;
1339         TDB_DATA val;
1340         uint32_t global_id = persistent_id & UINT32_MAX;
1341         uint64_t global_zeros = persistent_id & 0xFFFFFFFF00000000LLU;
1342         NTSTATUS status;
1343         struct security_token *current_token = NULL;
1344
1345         if (session_info == NULL) {
1346                 DEBUG(10, ("session_info=NULL\n"));
1347                 return NT_STATUS_INVALID_HANDLE;
1348         }
1349         current_token = session_info->security_token;
1350
1351         if (current_token == NULL) {
1352                 DEBUG(10, ("current_token=NULL\n"));
1353                 return NT_STATUS_INVALID_HANDLE;
1354         }
1355
1356         if (global_zeros != 0) {
1357                 DEBUG(10, ("global_zeros!=0\n"));
1358                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1359         }
1360
1361         op = talloc_zero(table, struct smbXsrv_open);
1362         if (op == NULL) {
1363                 return NT_STATUS_NO_MEMORY;
1364         }
1365         op->table = table;
1366
1367         status = smbXsrv_open_global_lookup(table, global_id, op, &op->global);
1368         if (!NT_STATUS_IS_OK(status)) {
1369                 TALLOC_FREE(op);
1370                 DEBUG(10, ("smbXsrv_open_global_lookup returned %s\n",
1371                            nt_errstr(status)));
1372                 return status;
1373         }
1374
1375         /*
1376          * If the provided create_guid is NULL, this means that
1377          * the reconnect request was a v1 request. In that case
1378          * we should skipt the create GUID verification, since
1379          * it is valid to v1-reconnect a v2-opened handle.
1380          */
1381         if ((create_guid != NULL) &&
1382             !GUID_equal(&op->global->create_guid, create_guid))
1383         {
1384                 TALLOC_FREE(op);
1385                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1386         }
1387
1388         if (!security_token_is_sid(current_token, &op->global->open_owner)) {
1389                 TALLOC_FREE(op);
1390                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1391         }
1392
1393         if (!op->global->durable) {
1394                 TALLOC_FREE(op);
1395                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1396         }
1397
1398         if (table->local.num_opens >= table->local.max_opens) {
1399                 TALLOC_FREE(op);
1400                 return NT_STATUS_INSUFFICIENT_RESOURCES;
1401         }
1402
1403         status = smbXsrv_open_local_allocate_id(table->local.db_ctx,
1404                                                 table->local.lowest_id,
1405                                                 table->local.highest_id,
1406                                                 op,
1407                                                 &local_rec,
1408                                                 &op->local_id);
1409         if (!NT_STATUS_IS_OK(status)) {
1410                 TALLOC_FREE(op);
1411                 return status;
1412         }
1413
1414         op->idle_time = now;
1415         op->status = NT_STATUS_FILE_CLOSED;
1416
1417         op->global->open_volatile_id = op->local_id;
1418         op->global->server_id = messaging_server_id(conn->msg_ctx);
1419
1420         ptr = op;
1421         val = make_tdb_data((uint8_t const *)&ptr, sizeof(ptr));
1422         status = dbwrap_record_store(local_rec, val, TDB_REPLACE);
1423         TALLOC_FREE(local_rec);
1424         if (!NT_STATUS_IS_OK(status)) {
1425                 TALLOC_FREE(op);
1426                 return status;
1427         }
1428         table->local.num_opens += 1;
1429
1430         talloc_set_destructor(op, smbXsrv_open_destructor);
1431
1432         status = smbXsrv_open_global_store(op->global);
1433         if (!NT_STATUS_IS_OK(status)) {
1434                 TALLOC_FREE(op);
1435                 return status;
1436         }
1437
1438         if (CHECK_DEBUGLVL(10)) {
1439                 struct smbXsrv_openB open_blob;
1440
1441                 ZERO_STRUCT(open_blob);
1442                 open_blob.version = 0;
1443                 open_blob.info.info0 = op;
1444
1445                 DEBUG(10,("smbXsrv_open_recreate: global_id (0x%08x) stored\n",
1446                          op->global->open_global_id));
1447                 NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
1448         }
1449
1450         *_open = op;
1451         return NT_STATUS_OK;
1452 }
1453
1454
1455 static NTSTATUS smbXsrv_open_global_parse_record(TALLOC_CTX *mem_ctx,
1456                                                  struct db_record *rec,
1457                                                  struct smbXsrv_open_global0 **global)
1458 {
1459         TDB_DATA key = dbwrap_record_get_key(rec);
1460         TDB_DATA val = dbwrap_record_get_value(rec);
1461         DATA_BLOB blob = data_blob_const(val.dptr, val.dsize);
1462         struct smbXsrv_open_globalB global_blob;
1463         enum ndr_err_code ndr_err;
1464         NTSTATUS status;
1465         TALLOC_CTX *frame = talloc_stackframe();
1466
1467         ndr_err = ndr_pull_struct_blob(&blob, frame, &global_blob,
1468                         (ndr_pull_flags_fn_t)ndr_pull_smbXsrv_open_globalB);
1469         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1470                 DEBUG(1,("Invalid record in smbXsrv_open_global.tdb:"
1471                          "key '%s' ndr_pull_struct_blob - %s\n",
1472                          hex_encode_talloc(frame, key.dptr, key.dsize),
1473                          ndr_errstr(ndr_err)));
1474                 status = ndr_map_error2ntstatus(ndr_err);
1475                 goto done;
1476         }
1477
1478         if (global_blob.version != SMBXSRV_VERSION_0) {
1479                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
1480                 DEBUG(1,("Invalid record in smbXsrv_open_global.tdb:"
1481                          "key '%s' unsuported version - %d - %s\n",
1482                          hex_encode_talloc(frame, key.dptr, key.dsize),
1483                          (int)global_blob.version,
1484                          nt_errstr(status)));
1485                 goto done;
1486         }
1487
1488         *global = talloc_move(mem_ctx, &global_blob.info.info0);
1489         status = NT_STATUS_OK;
1490 done:
1491         talloc_free(frame);
1492         return status;
1493 }
1494
1495 struct smbXsrv_open_global_traverse_state {
1496         int (*fn)(struct smbXsrv_open_global0 *, void *);
1497         void *private_data;
1498 };
1499
1500 static int smbXsrv_open_global_traverse_fn(struct db_record *rec, void *data)
1501 {
1502         struct smbXsrv_open_global_traverse_state *state =
1503                 (struct smbXsrv_open_global_traverse_state*)data;
1504         struct smbXsrv_open_global0 *global = NULL;
1505         NTSTATUS status;
1506         int ret = -1;
1507
1508         status = smbXsrv_open_global_parse_record(talloc_tos(), rec, &global);
1509         if (!NT_STATUS_IS_OK(status)) {
1510                 return -1;
1511         }
1512
1513         global->db_rec = rec;
1514         ret = state->fn(global, state->private_data);
1515         talloc_free(global);
1516         return ret;
1517 }
1518
1519 NTSTATUS smbXsrv_open_global_traverse(
1520                         int (*fn)(struct smbXsrv_open_global0 *, void *),
1521                         void *private_data)
1522 {
1523
1524         NTSTATUS status;
1525         int count = 0;
1526         struct smbXsrv_open_global_traverse_state state = {
1527                 .fn = fn,
1528                 .private_data = private_data,
1529         };
1530
1531         become_root();
1532         status = smbXsrv_open_global_init();
1533         if (!NT_STATUS_IS_OK(status)) {
1534                 unbecome_root();
1535                 DEBUG(0, ("Failed to initialize open_global: %s\n",
1536                           nt_errstr(status)));
1537                 return status;
1538         }
1539
1540         status = dbwrap_traverse_read(smbXsrv_open_global_db_ctx,
1541                                       smbXsrv_open_global_traverse_fn,
1542                                       &state,
1543                                       &count);
1544         unbecome_root();
1545
1546         return status;
1547 }
1548
1549 NTSTATUS smbXsrv_open_cleanup(uint64_t persistent_id)
1550 {
1551         NTSTATUS status = NT_STATUS_OK;
1552         TALLOC_CTX *frame = talloc_stackframe();
1553         struct smbXsrv_open_global0 *op = NULL;
1554         TDB_DATA val;
1555         struct db_record *rec;
1556         bool delete_open = false;
1557         uint32_t global_id = persistent_id & UINT32_MAX;
1558
1559         rec = smbXsrv_open_global_fetch_locked(smbXsrv_open_global_db_ctx,
1560                                                global_id,
1561                                                frame);
1562         if (rec == NULL) {
1563                 status = NT_STATUS_NOT_FOUND;
1564                 goto done;
1565         }
1566
1567         val = dbwrap_record_get_value(rec);
1568         if (val.dsize == 0) {
1569                 DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1570                           "empty record in %s, skipping...\n",
1571                            global_id, dbwrap_name(smbXsrv_open_global_db_ctx)));
1572                 goto done;
1573         }
1574
1575         status = smbXsrv_open_global_parse_record(talloc_tos(), rec, &op);
1576         if (!NT_STATUS_IS_OK(status)) {
1577                 DEBUG(1, ("smbXsrv_open_cleanup[global: 0x%08x] "
1578                           "failed to read record: %s\n",
1579                           global_id, nt_errstr(status)));
1580                 goto done;
1581         }
1582
1583         if (server_id_is_disconnected(&op->server_id)) {
1584                 struct timeval now, disconnect_time;
1585                 int64_t tdiff;
1586                 now = timeval_current();
1587                 nttime_to_timeval(&disconnect_time, op->disconnect_time);
1588                 tdiff = usec_time_diff(&now, &disconnect_time);
1589                 delete_open = (tdiff >= 1000*op->durable_timeout_msec);
1590
1591                 DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1592                            "disconnected at [%s] %us ago with "
1593                            "timeout of %us -%s reached\n",
1594                            global_id,
1595                            nt_time_string(frame, op->disconnect_time),
1596                            (unsigned)(tdiff/1000000),
1597                            op->durable_timeout_msec / 1000,
1598                            delete_open ? "" : " not"));
1599         } else if (!serverid_exists(&op->server_id)) {
1600                 struct server_id_buf idbuf;
1601                 DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1602                            "server[%s] does not exist\n",
1603                            global_id,
1604                            server_id_str_buf(op->server_id, &idbuf)));
1605                 delete_open = true;
1606         }
1607
1608         if (!delete_open) {
1609                 goto done;
1610         }
1611
1612         status = dbwrap_record_delete(rec);
1613         if (!NT_STATUS_IS_OK(status)) {
1614                 DEBUG(1, ("smbXsrv_open_cleanup[global: 0x%08x] "
1615                           "failed to delete record"
1616                           "from %s: %s\n", global_id,
1617                           dbwrap_name(smbXsrv_open_global_db_ctx),
1618                           nt_errstr(status)));
1619                 goto done;
1620         }
1621
1622         DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1623                    "delete record from %s\n",
1624                    global_id,
1625                    dbwrap_name(smbXsrv_open_global_db_ctx)));
1626
1627 done:
1628         talloc_free(frame);
1629         return status;
1630 }