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