smbd: Factor out file_has_read_oplocks()
[bbaumbach/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 "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         /*
530          * Here we just randomly try the whole 32-bit space
531          *
532          * We use just 32-bit, because we want to reuse the
533          * ID for SRVSVC.
534          */
535         for (i = 0; i < UINT32_MAX; i++) {
536                 bool is_free = false;
537                 bool was_free = false;
538                 uint32_t id;
539
540                 if (i >= min_tries && last_free != 0) {
541                         id = last_free;
542                 } else {
543                         id = generate_random();
544                 }
545                 if (id == 0) {
546                         id++;
547                 }
548                 if (id == UINT32_MAX) {
549                         id--;
550                 }
551
552                 global->db_rec = smbXsrv_open_global_fetch_locked(db, id, mem_ctx);
553                 if (global->db_rec == NULL) {
554                         talloc_free(global);
555                         return NT_STATUS_INSUFFICIENT_RESOURCES;
556                 }
557
558                 smbXsrv_open_global_verify_record(global->db_rec,
559                                                   &is_free,
560                                                   &was_free,
561                                                   NULL, NULL);
562
563                 if (!is_free) {
564                         TALLOC_FREE(global->db_rec);
565                         continue;
566                 }
567
568                 if (!was_free && i < min_tries) {
569                         /*
570                          * The session_id is free now,
571                          * but was not free before.
572                          *
573                          * This happens if a smbd crashed
574                          * and did not cleanup the record.
575                          *
576                          * If this is one of our first tries,
577                          * then we try to find a real free one.
578                          */
579                         if (last_free == 0) {
580                                 last_free = id;
581                         }
582                         TALLOC_FREE(global->db_rec);
583                         continue;
584                 }
585
586                 global->open_global_id = id;
587
588                 *_global = global;
589                 return NT_STATUS_OK;
590         }
591
592         /* should not be reached */
593         talloc_free(global);
594         return NT_STATUS_INTERNAL_ERROR;
595 }
596
597 static void smbXsrv_open_global_verify_record(struct db_record *db_rec,
598                                         bool *is_free,
599                                         bool *was_free,
600                                         TALLOC_CTX *mem_ctx,
601                                         struct smbXsrv_open_global0 **_g)
602 {
603         TDB_DATA key;
604         TDB_DATA val;
605         DATA_BLOB blob;
606         struct smbXsrv_open_globalB global_blob;
607         enum ndr_err_code ndr_err;
608         struct smbXsrv_open_global0 *global = NULL;
609         bool exists;
610         TALLOC_CTX *frame = talloc_stackframe();
611
612         *is_free = false;
613
614         if (was_free) {
615                 *was_free = false;
616         }
617         if (_g) {
618                 *_g = NULL;
619         }
620
621         key = dbwrap_record_get_key(db_rec);
622
623         val = dbwrap_record_get_value(db_rec);
624         if (val.dsize == 0) {
625                 DEBUG(10, ("%s: empty value\n", __func__));
626                 TALLOC_FREE(frame);
627                 *is_free = true;
628                 if (was_free) {
629                         *was_free = true;
630                 }
631                 return;
632         }
633
634         blob = data_blob_const(val.dptr, val.dsize);
635
636         ndr_err = ndr_pull_struct_blob(&blob, frame, &global_blob,
637                         (ndr_pull_flags_fn_t)ndr_pull_smbXsrv_open_globalB);
638         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
639                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
640                 DEBUG(1,("smbXsrv_open_global_verify_record: "
641                          "key '%s' ndr_pull_struct_blob - %s\n",
642                          hex_encode_talloc(frame, key.dptr, key.dsize),
643                          nt_errstr(status)));
644                 TALLOC_FREE(frame);
645                 return;
646         }
647
648         DEBUG(10,("smbXsrv_open_global_verify_record\n"));
649         if (CHECK_DEBUGLVL(10)) {
650                 NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
651         }
652
653         if (global_blob.version != SMBXSRV_VERSION_0) {
654                 DEBUG(0,("smbXsrv_open_global_verify_record: "
655                          "key '%s' use unsupported version %u\n",
656                          hex_encode_talloc(frame, key.dptr, key.dsize),
657                          global_blob.version));
658                 NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
659                 TALLOC_FREE(frame);
660                 return;
661         }
662
663         global = global_blob.info.info0;
664
665         if (server_id_is_disconnected(&global->server_id)) {
666                 exists = true;
667         } else {
668                 exists = serverid_exists(&global->server_id);
669         }
670         if (!exists) {
671                 struct server_id_buf idbuf;
672                 DEBUG(2,("smbXsrv_open_global_verify_record: "
673                          "key '%s' server_id %s does not exist.\n",
674                          hex_encode_talloc(frame, key.dptr, key.dsize),
675                          server_id_str_buf(global->server_id, &idbuf)));
676                 if (CHECK_DEBUGLVL(2)) {
677                         NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
678                 }
679                 TALLOC_FREE(frame);
680                 dbwrap_record_delete(db_rec);
681                 *is_free = true;
682                 return;
683         }
684
685         if (_g) {
686                 *_g = talloc_move(mem_ctx, &global);
687         }
688         TALLOC_FREE(frame);
689 }
690
691 static NTSTATUS smbXsrv_open_global_store(struct smbXsrv_open_global0 *global)
692 {
693         struct smbXsrv_open_globalB global_blob;
694         DATA_BLOB blob = data_blob_null;
695         TDB_DATA key;
696         TDB_DATA val;
697         NTSTATUS status;
698         enum ndr_err_code ndr_err;
699
700         /*
701          * TODO: if we use other versions than '0'
702          * we would add glue code here, that would be able to
703          * store the information in the old format.
704          */
705
706         if (global->db_rec == NULL) {
707                 return NT_STATUS_INTERNAL_ERROR;
708         }
709
710         key = dbwrap_record_get_key(global->db_rec);
711         val = dbwrap_record_get_value(global->db_rec);
712
713         ZERO_STRUCT(global_blob);
714         global_blob.version = smbXsrv_version_global_current();
715         if (val.dsize >= 8) {
716                 global_blob.seqnum = IVAL(val.dptr, 4);
717         }
718         global_blob.seqnum += 1;
719         global_blob.info.info0 = global;
720
721         ndr_err = ndr_push_struct_blob(&blob, global->db_rec, &global_blob,
722                         (ndr_push_flags_fn_t)ndr_push_smbXsrv_open_globalB);
723         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
724                 status = ndr_map_error2ntstatus(ndr_err);
725                 DEBUG(1,("smbXsrv_open_global_store: key '%s' ndr_push - %s\n",
726                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize),
727                          nt_errstr(status)));
728                 TALLOC_FREE(global->db_rec);
729                 return status;
730         }
731
732         val = make_tdb_data(blob.data, blob.length);
733         status = dbwrap_record_store(global->db_rec, val, TDB_REPLACE);
734         if (!NT_STATUS_IS_OK(status)) {
735                 DEBUG(1,("smbXsrv_open_global_store: key '%s' store - %s\n",
736                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize),
737                          nt_errstr(status)));
738                 TALLOC_FREE(global->db_rec);
739                 return status;
740         }
741
742         if (CHECK_DEBUGLVL(10)) {
743                 DEBUG(10,("smbXsrv_open_global_store: key '%s' stored\n",
744                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize)));
745                 NDR_PRINT_DEBUG(smbXsrv_open_globalB, &global_blob);
746         }
747
748         TALLOC_FREE(global->db_rec);
749
750         return NT_STATUS_OK;
751 }
752
753 static NTSTATUS smbXsrv_open_global_lookup(struct smbXsrv_open_table *table,
754                                            uint32_t open_global_id,
755                                            TALLOC_CTX *mem_ctx,
756                                            struct smbXsrv_open_global0 **_global)
757 {
758         struct db_record *global_rec = NULL;
759         bool is_free = false;
760
761         *_global = NULL;
762
763         if (table->global.db_ctx == NULL) {
764                 return NT_STATUS_INTERNAL_ERROR;
765         }
766
767         global_rec = smbXsrv_open_global_fetch_locked(table->global.db_ctx,
768                                                       open_global_id,
769                                                       mem_ctx);
770         if (global_rec == NULL) {
771                 return NT_STATUS_INTERNAL_DB_ERROR;
772         }
773
774         smbXsrv_open_global_verify_record(global_rec,
775                                           &is_free,
776                                           NULL,
777                                           mem_ctx,
778                                           _global);
779         if (is_free) {
780                 DEBUG(10, ("%s: is_free=true\n", __func__));
781                 talloc_free(global_rec);
782                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
783         }
784
785         (*_global)->db_rec = talloc_move(*_global, &global_rec);
786
787         talloc_set_destructor(*_global, smbXsrv_open_global_destructor);
788
789         return NT_STATUS_OK;
790 }
791
792 static int smbXsrv_open_destructor(struct smbXsrv_open *op)
793 {
794         NTSTATUS status;
795
796         status = smbXsrv_open_close(op, 0);
797         if (!NT_STATUS_IS_OK(status)) {
798                 DEBUG(0, ("smbXsrv_open_destructor: "
799                           "smbXsrv_open_close() failed - %s\n",
800                           nt_errstr(status)));
801         }
802
803         TALLOC_FREE(op->global);
804
805         return 0;
806 }
807
808 NTSTATUS smbXsrv_open_create(struct smbXsrv_connection *conn,
809                              struct auth_session_info *session_info,
810                              NTTIME now,
811                              struct smbXsrv_open **_open)
812 {
813         struct smbXsrv_open_table *table = conn->client->open_table;
814         struct db_record *local_rec = NULL;
815         struct smbXsrv_open *op = NULL;
816         void *ptr = NULL;
817         TDB_DATA val;
818         struct smbXsrv_open_global0 *global = NULL;
819         NTSTATUS status;
820         struct dom_sid *current_sid = NULL;
821         struct security_token *current_token = NULL;
822
823         if (session_info == NULL) {
824                 return NT_STATUS_INVALID_HANDLE;
825         }
826         current_token = session_info->security_token;
827
828         if (current_token == NULL) {
829                 return NT_STATUS_INVALID_HANDLE;
830         }
831
832         if (current_token->num_sids > PRIMARY_USER_SID_INDEX) {
833                 current_sid = &current_token->sids[PRIMARY_USER_SID_INDEX];
834         }
835
836         if (current_sid == NULL) {
837                 return NT_STATUS_INVALID_HANDLE;
838         }
839
840         if (table->local.num_opens >= table->local.max_opens) {
841                 return NT_STATUS_INSUFFICIENT_RESOURCES;
842         }
843
844         op = talloc_zero(table, struct smbXsrv_open);
845         if (op == NULL) {
846                 return NT_STATUS_NO_MEMORY;
847         }
848         op->table = table;
849         op->status = NT_STATUS_OK; /* TODO: start with INTERNAL_ERROR */
850         op->idle_time = now;
851
852         status = smbXsrv_open_global_allocate(table->global.db_ctx,
853                                               op, &global);
854         if (!NT_STATUS_IS_OK(status)) {
855                 TALLOC_FREE(op);
856                 return status;
857         }
858         op->global = global;
859
860         status = smbXsrv_open_local_allocate_id(table->local.db_ctx,
861                                                 table->local.lowest_id,
862                                                 table->local.highest_id,
863                                                 op,
864                                                 &local_rec,
865                                                 &op->local_id);
866         if (!NT_STATUS_IS_OK(status)) {
867                 TALLOC_FREE(op);
868                 return status;
869         }
870
871         global->open_persistent_id = global->open_global_id;
872         global->open_volatile_id = op->local_id;
873
874         global->server_id = messaging_server_id(conn->client->msg_ctx);
875         global->open_time = now;
876         global->open_owner = *current_sid;
877         if (conn->protocol >= PROTOCOL_SMB2_10) {
878                 global->client_guid = conn->smb2.client.guid;
879         }
880
881         ptr = op;
882         val = make_tdb_data((uint8_t const *)&ptr, sizeof(ptr));
883         status = dbwrap_record_store(local_rec, val, TDB_REPLACE);
884         TALLOC_FREE(local_rec);
885         if (!NT_STATUS_IS_OK(status)) {
886                 TALLOC_FREE(op);
887                 return status;
888         }
889         table->local.num_opens += 1;
890
891         talloc_set_destructor(op, smbXsrv_open_destructor);
892
893         status = smbXsrv_open_global_store(global);
894         if (!NT_STATUS_IS_OK(status)) {
895                 DEBUG(0,("smbXsrv_open_create: "
896                          "global_id (0x%08x) store failed - %s\n",
897                          op->global->open_global_id,
898                          nt_errstr(status)));
899                 TALLOC_FREE(op);
900                 return status;
901         }
902
903         if (CHECK_DEBUGLVL(10)) {
904                 struct smbXsrv_openB open_blob;
905
906                 ZERO_STRUCT(open_blob);
907                 open_blob.version = SMBXSRV_VERSION_0;
908                 open_blob.info.info0 = op;
909
910                 DEBUG(10,("smbXsrv_open_create: global_id (0x%08x) stored\n",
911                          op->global->open_global_id));
912                 NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
913         }
914
915         *_open = op;
916         return NT_STATUS_OK;
917 }
918
919 uint32_t smbXsrv_open_hash(struct smbXsrv_open *_open)
920 {
921         uint8_t buf[8+8+8];
922         uint32_t ret;
923         TDB_DATA key;
924
925         SBVAL(buf,  0, _open->global->open_persistent_id);
926         SBVAL(buf,  8, _open->global->open_volatile_id);
927         SBVAL(buf, 16, _open->global->open_time);
928
929         key = (TDB_DATA) { .dptr = buf, .dsize = sizeof(buf) };
930         ret = tdb_jenkins_hash(&key);
931
932         if (ret == 0) {
933                 ret = 1;
934         }
935
936         return ret;
937 }
938
939 static NTSTATUS smbXsrv_open_set_replay_cache(struct smbXsrv_open *op)
940 {
941         struct GUID *create_guid;
942         struct GUID_txt_buf buf;
943         char *guid_string;
944         struct db_context *db = op->table->local.replay_cache_db_ctx;
945         NTSTATUS status;
946
947         if (!(op->flags & SMBXSRV_OPEN_NEED_REPLAY_CACHE)) {
948                 return NT_STATUS_OK;
949         }
950
951         if (op->flags & SMBXSRV_OPEN_HAVE_REPLAY_CACHE) {
952                 return NT_STATUS_OK;
953         }
954
955         create_guid = &op->global->create_guid;
956         if (GUID_all_zero(create_guid)) {
957                 return NT_STATUS_OK;
958         }
959
960         guid_string = GUID_buf_string(create_guid, &buf);
961         if (guid_string == NULL) {
962                 return NT_STATUS_INVALID_PARAMETER;
963         }
964
965         status = dbwrap_store_uint32_bystring(db, guid_string, op->local_id);
966
967         if (NT_STATUS_IS_OK(status)) {
968                 op->flags |= SMBXSRV_OPEN_HAVE_REPLAY_CACHE;
969                 op->flags &= ~SMBXSRV_OPEN_NEED_REPLAY_CACHE;
970         }
971
972         return status;
973 }
974
975 static NTSTATUS smbXsrv_open_clear_replay_cache(struct smbXsrv_open *op)
976 {
977         struct GUID *create_guid;
978         struct GUID_txt_buf buf;
979         char *guid_string;
980         struct db_context *db;
981         NTSTATUS status;
982
983         if (op->table == NULL) {
984                 return NT_STATUS_OK;
985         }
986
987         db = op->table->local.replay_cache_db_ctx;
988
989         if (!(op->flags & SMBXSRV_OPEN_HAVE_REPLAY_CACHE)) {
990                 return NT_STATUS_OK;
991         }
992
993         create_guid = &op->global->create_guid;
994         if (GUID_all_zero(create_guid)) {
995                 return NT_STATUS_OK;
996         }
997
998         guid_string = GUID_buf_string(create_guid, &buf);
999         if (guid_string == NULL) {
1000                 return NT_STATUS_INVALID_PARAMETER;
1001         }
1002
1003         status = dbwrap_purge_bystring(db, guid_string);
1004
1005         if (NT_STATUS_IS_OK(status)) {
1006                 op->flags &= ~SMBXSRV_OPEN_HAVE_REPLAY_CACHE;
1007         }
1008
1009         return status;
1010 }
1011
1012 NTSTATUS smbXsrv_open_update(struct smbXsrv_open *op)
1013 {
1014         struct smbXsrv_open_table *table = op->table;
1015         NTSTATUS status;
1016
1017         if (op->global->db_rec != NULL) {
1018                 DEBUG(0, ("smbXsrv_open_update(0x%08x): "
1019                           "Called with db_rec != NULL'\n",
1020                           op->global->open_global_id));
1021                 return NT_STATUS_INTERNAL_ERROR;
1022         }
1023
1024         op->global->db_rec = smbXsrv_open_global_fetch_locked(
1025                                                 table->global.db_ctx,
1026                                                 op->global->open_global_id,
1027                                                 op->global /* TALLOC_CTX */);
1028         if (op->global->db_rec == NULL) {
1029                 return NT_STATUS_INTERNAL_DB_ERROR;
1030         }
1031
1032         status = smbXsrv_open_global_store(op->global);
1033         if (!NT_STATUS_IS_OK(status)) {
1034                 DEBUG(0,("smbXsrv_open_update: "
1035                          "global_id (0x%08x) store failed - %s\n",
1036                          op->global->open_global_id,
1037                          nt_errstr(status)));
1038                 return status;
1039         }
1040
1041         status = smbXsrv_open_set_replay_cache(op);
1042         if (!NT_STATUS_IS_OK(status)) {
1043                 DBG_ERR("smbXsrv_open_set_replay_cache failed: %s\n",
1044                         nt_errstr(status));
1045                 return status;
1046         }
1047
1048         if (CHECK_DEBUGLVL(10)) {
1049                 struct smbXsrv_openB open_blob;
1050
1051                 ZERO_STRUCT(open_blob);
1052                 open_blob.version = SMBXSRV_VERSION_0;
1053                 open_blob.info.info0 = op;
1054
1055                 DEBUG(10,("smbXsrv_open_update: global_id (0x%08x) stored\n",
1056                           op->global->open_global_id));
1057                 NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
1058         }
1059
1060         return NT_STATUS_OK;
1061 }
1062
1063 NTSTATUS smbXsrv_open_close(struct smbXsrv_open *op, NTTIME now)
1064 {
1065         struct smbXsrv_open_table *table;
1066         struct db_record *local_rec = NULL;
1067         struct db_record *global_rec = NULL;
1068         NTSTATUS status;
1069         NTSTATUS error = NT_STATUS_OK;
1070
1071         error = smbXsrv_open_clear_replay_cache(op);
1072         if (!NT_STATUS_IS_OK(error)) {
1073                 DBG_ERR("smbXsrv_open_clear_replay_cache failed: %s\n",
1074                         nt_errstr(error));
1075         }
1076
1077         if (op->table == NULL) {
1078                 return error;
1079         }
1080
1081         table = op->table;
1082         op->table = NULL;
1083
1084         op->status = NT_STATUS_FILE_CLOSED;
1085         op->global->disconnect_time = now;
1086         server_id_set_disconnected(&op->global->server_id);
1087
1088         global_rec = op->global->db_rec;
1089         op->global->db_rec = NULL;
1090         if (global_rec == NULL) {
1091                 global_rec = smbXsrv_open_global_fetch_locked(
1092                                         table->global.db_ctx,
1093                                         op->global->open_global_id,
1094                                         op->global /* TALLOC_CTX */);
1095                 if (global_rec == NULL) {
1096                         error = NT_STATUS_INTERNAL_ERROR;
1097                 }
1098         }
1099
1100         if (global_rec != NULL && op->global->durable) {
1101                 /*
1102                  * If it is a durable open we need to update the global part
1103                  * instead of deleting it
1104                  */
1105                 op->global->db_rec = global_rec;
1106                 status = smbXsrv_open_global_store(op->global);
1107                 if (NT_STATUS_IS_OK(status)) {
1108                         /*
1109                          * smbXsrv_open_global_store does the free
1110                          * of op->global->db_rec
1111                          */
1112                         global_rec = NULL;
1113                 }
1114                 if (!NT_STATUS_IS_OK(status)) {
1115                         DEBUG(0,("smbXsrv_open_close(0x%08x)"
1116                                  "smbXsrv_open_global_store() failed - %s\n",
1117                                  op->global->open_global_id,
1118                                  nt_errstr(status)));
1119                         error = status;
1120                 }
1121
1122                 if (NT_STATUS_IS_OK(status) && CHECK_DEBUGLVL(10)) {
1123                         struct smbXsrv_openB open_blob;
1124
1125                         ZERO_STRUCT(open_blob);
1126                         open_blob.version = SMBXSRV_VERSION_0;
1127                         open_blob.info.info0 = op;
1128
1129                         DEBUG(10,("smbXsrv_open_close(0x%08x): "
1130                                   "stored disconnect\n",
1131                                   op->global->open_global_id));
1132                         NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
1133                 }
1134         }
1135
1136         if (global_rec != NULL) {
1137                 status = dbwrap_record_delete(global_rec);
1138                 if (!NT_STATUS_IS_OK(status)) {
1139                         TDB_DATA key = dbwrap_record_get_key(global_rec);
1140
1141                         DEBUG(0, ("smbXsrv_open_close(0x%08x): "
1142                                   "failed to delete global key '%s': %s\n",
1143                                   op->global->open_global_id,
1144                                   hex_encode_talloc(global_rec, key.dptr,
1145                                                     key.dsize),
1146                                   nt_errstr(status)));
1147                         error = status;
1148                 }
1149         }
1150         TALLOC_FREE(global_rec);
1151
1152         local_rec = op->db_rec;
1153         if (local_rec == NULL) {
1154                 local_rec = smbXsrv_open_local_fetch_locked(table->local.db_ctx,
1155                                                             op->local_id,
1156                                                             op /* TALLOC_CTX*/);
1157                 if (local_rec == NULL) {
1158                         error = NT_STATUS_INTERNAL_ERROR;
1159                 }
1160         }
1161
1162         if (local_rec != NULL) {
1163                 status = dbwrap_record_delete(local_rec);
1164                 if (!NT_STATUS_IS_OK(status)) {
1165                         TDB_DATA key = dbwrap_record_get_key(local_rec);
1166
1167                         DEBUG(0, ("smbXsrv_open_close(0x%08x): "
1168                                   "failed to delete local key '%s': %s\n",
1169                                   op->global->open_global_id,
1170                                   hex_encode_talloc(local_rec, key.dptr,
1171                                                     key.dsize),
1172                                   nt_errstr(status)));
1173                         error = status;
1174                 }
1175                 table->local.num_opens -= 1;
1176         }
1177         if (op->db_rec == NULL) {
1178                 TALLOC_FREE(local_rec);
1179         }
1180         op->db_rec = NULL;
1181
1182         if (op->compat) {
1183                 op->compat->op = NULL;
1184                 file_free(NULL, op->compat);
1185                 op->compat = NULL;
1186         }
1187
1188         return error;
1189 }
1190
1191 NTSTATUS smb1srv_open_table_init(struct smbXsrv_connection *conn)
1192 {
1193         uint32_t max_opens;
1194
1195         /*
1196          * Allow a range from 1..65534.
1197          *
1198          * With real_max_open_files possible ids,
1199          * truncated to the SMB1 limit of 16-bit.
1200          *
1201          * 0 and 0xFFFF are no valid ids.
1202          */
1203         max_opens = conn->client->sconn->real_max_open_files;
1204         max_opens = MIN(max_opens, UINT16_MAX - 1);
1205
1206         return smbXsrv_open_table_init(conn, 1, UINT16_MAX - 1, max_opens);
1207 }
1208
1209 NTSTATUS smb1srv_open_lookup(struct smbXsrv_connection *conn,
1210                              uint16_t fnum, NTTIME now,
1211                              struct smbXsrv_open **_open)
1212 {
1213         struct smbXsrv_open_table *table = conn->client->open_table;
1214         uint32_t local_id = fnum;
1215         uint32_t global_id = 0;
1216
1217         return smbXsrv_open_local_lookup(table, local_id, global_id, now, _open);
1218 }
1219
1220 NTSTATUS smb2srv_open_table_init(struct smbXsrv_connection *conn)
1221 {
1222         uint32_t max_opens;
1223
1224         /*
1225          * Allow a range from 1..4294967294.
1226          *
1227          * With real_max_open_files possible ids,
1228          * truncated to 16-bit (the same as SMB1 for now).
1229          *
1230          * 0 and 0xFFFFFFFF are no valid ids.
1231          *
1232          * The usage of conn->sconn->real_max_open_files
1233          * is the reason that we use one open table per
1234          * transport connection (as we still have a 1:1 mapping
1235          * between process and transport connection).
1236          */
1237         max_opens = conn->client->sconn->real_max_open_files;
1238         max_opens = MIN(max_opens, UINT16_MAX - 1);
1239
1240         return smbXsrv_open_table_init(conn, 1, UINT32_MAX - 1, max_opens);
1241 }
1242
1243 NTSTATUS smb2srv_open_lookup(struct smbXsrv_connection *conn,
1244                              uint64_t persistent_id,
1245                              uint64_t volatile_id,
1246                              NTTIME now,
1247                              struct smbXsrv_open **_open)
1248 {
1249         struct smbXsrv_open_table *table = conn->client->open_table;
1250         uint32_t local_id = volatile_id & UINT32_MAX;
1251         uint64_t local_zeros = volatile_id & 0xFFFFFFFF00000000LLU;
1252         uint32_t global_id = persistent_id & UINT32_MAX;
1253         uint64_t global_zeros = persistent_id & 0xFFFFFFFF00000000LLU;
1254         NTSTATUS status;
1255
1256         if (local_zeros != 0) {
1257                 return NT_STATUS_FILE_CLOSED;
1258         }
1259
1260         if (global_zeros != 0) {
1261                 return NT_STATUS_FILE_CLOSED;
1262         }
1263
1264         if (global_id == 0) {
1265                 return NT_STATUS_FILE_CLOSED;
1266         }
1267
1268         status = smbXsrv_open_local_lookup(table, local_id, global_id, now,
1269                                            _open);
1270         if (!NT_STATUS_IS_OK(status)) {
1271                 return status;
1272         }
1273
1274         /*
1275          * Clear the replay cache for this create_guid if it exists:
1276          * This is based on the assumption that this lookup will be
1277          * triggered by a client request using the file-id for lookup.
1278          * Hence the client has proven that it has in fact seen the
1279          * reply to its initial create call. So subsequent create replays
1280          * should be treated as invalid. Hence the index for create_guid
1281          * lookup needs to be removed.
1282          */
1283         status = smbXsrv_open_clear_replay_cache(*_open);
1284
1285         return status;
1286 }
1287
1288 NTSTATUS smb2srv_open_lookup_replay_cache(struct smbXsrv_connection *conn,
1289                                           const struct GUID *create_guid,
1290                                           NTTIME now, /* TODO: needed ? */
1291                                           struct smbXsrv_open **_open)
1292 {
1293         NTSTATUS status;
1294         char *guid_string;
1295         struct GUID_txt_buf buf;
1296         uint32_t local_id = 0;
1297         struct smbXsrv_open_table *table = conn->client->open_table;
1298         struct db_context *db = table->local.replay_cache_db_ctx;
1299
1300         if (GUID_all_zero(create_guid)) {
1301                 return NT_STATUS_NOT_FOUND;
1302         }
1303
1304         guid_string = GUID_buf_string(create_guid, &buf);
1305         if (guid_string == NULL) {
1306                 return NT_STATUS_INVALID_PARAMETER;
1307         }
1308
1309         status = dbwrap_fetch_uint32_bystring(db, guid_string, &local_id);
1310         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
1311                 return status;
1312         }
1313         if (!NT_STATUS_IS_OK(status)) {
1314                 DBG_ERR("failed to fetch local_id from replay cache: %s\n",
1315                         nt_errstr(status));
1316                 return status;
1317         }
1318
1319         status = smbXsrv_open_local_lookup(table, local_id, 0, /* global_id */
1320                                            now, _open);
1321         if (!NT_STATUS_IS_OK(status)) {
1322                 DBG_ERR("smbXsrv_open_local_lookup failed for local_id %u\n",
1323                         (unsigned)local_id);
1324         }
1325
1326         return status;
1327 }
1328
1329 NTSTATUS smb2srv_open_recreate(struct smbXsrv_connection *conn,
1330                                struct auth_session_info *session_info,
1331                                uint64_t persistent_id,
1332                                const struct GUID *create_guid,
1333                                NTTIME now,
1334                                struct smbXsrv_open **_open)
1335 {
1336         struct smbXsrv_open_table *table = conn->client->open_table;
1337         struct db_record *local_rec = NULL;
1338         struct smbXsrv_open *op = NULL;
1339         void *ptr = NULL;
1340         TDB_DATA val;
1341         uint32_t global_id = persistent_id & UINT32_MAX;
1342         uint64_t global_zeros = persistent_id & 0xFFFFFFFF00000000LLU;
1343         NTSTATUS status;
1344         struct security_token *current_token = NULL;
1345
1346         if (session_info == NULL) {
1347                 DEBUG(10, ("session_info=NULL\n"));
1348                 return NT_STATUS_INVALID_HANDLE;
1349         }
1350         current_token = session_info->security_token;
1351
1352         if (current_token == NULL) {
1353                 DEBUG(10, ("current_token=NULL\n"));
1354                 return NT_STATUS_INVALID_HANDLE;
1355         }
1356
1357         if (global_zeros != 0) {
1358                 DEBUG(10, ("global_zeros!=0\n"));
1359                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1360         }
1361
1362         op = talloc_zero(table, struct smbXsrv_open);
1363         if (op == NULL) {
1364                 return NT_STATUS_NO_MEMORY;
1365         }
1366         op->table = table;
1367
1368         status = smbXsrv_open_global_lookup(table, global_id, op, &op->global);
1369         if (!NT_STATUS_IS_OK(status)) {
1370                 TALLOC_FREE(op);
1371                 DEBUG(10, ("smbXsrv_open_global_lookup returned %s\n",
1372                            nt_errstr(status)));
1373                 return status;
1374         }
1375
1376         /*
1377          * If the provided create_guid is NULL, this means that
1378          * the reconnect request was a v1 request. In that case
1379          * we should skipt the create GUID verification, since
1380          * it is valid to v1-reconnect a v2-opened handle.
1381          */
1382         if ((create_guid != NULL) &&
1383             !GUID_equal(&op->global->create_guid, create_guid))
1384         {
1385                 TALLOC_FREE(op);
1386                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1387         }
1388
1389         if (!security_token_is_sid(current_token, &op->global->open_owner)) {
1390                 TALLOC_FREE(op);
1391                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1392         }
1393
1394         if (!op->global->durable) {
1395                 TALLOC_FREE(op);
1396                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1397         }
1398
1399         if (table->local.num_opens >= table->local.max_opens) {
1400                 TALLOC_FREE(op);
1401                 return NT_STATUS_INSUFFICIENT_RESOURCES;
1402         }
1403
1404         status = smbXsrv_open_local_allocate_id(table->local.db_ctx,
1405                                                 table->local.lowest_id,
1406                                                 table->local.highest_id,
1407                                                 op,
1408                                                 &local_rec,
1409                                                 &op->local_id);
1410         if (!NT_STATUS_IS_OK(status)) {
1411                 TALLOC_FREE(op);
1412                 return status;
1413         }
1414
1415         op->idle_time = now;
1416         op->status = NT_STATUS_FILE_CLOSED;
1417
1418         op->global->open_volatile_id = op->local_id;
1419         op->global->server_id = messaging_server_id(conn->client->msg_ctx);
1420
1421         ptr = op;
1422         val = make_tdb_data((uint8_t const *)&ptr, sizeof(ptr));
1423         status = dbwrap_record_store(local_rec, val, TDB_REPLACE);
1424         TALLOC_FREE(local_rec);
1425         if (!NT_STATUS_IS_OK(status)) {
1426                 TALLOC_FREE(op);
1427                 return status;
1428         }
1429         table->local.num_opens += 1;
1430
1431         talloc_set_destructor(op, smbXsrv_open_destructor);
1432
1433         status = smbXsrv_open_global_store(op->global);
1434         if (!NT_STATUS_IS_OK(status)) {
1435                 TALLOC_FREE(op);
1436                 return status;
1437         }
1438
1439         if (CHECK_DEBUGLVL(10)) {
1440                 struct smbXsrv_openB open_blob;
1441
1442                 ZERO_STRUCT(open_blob);
1443                 open_blob.version = 0;
1444                 open_blob.info.info0 = op;
1445
1446                 DEBUG(10,("smbXsrv_open_recreate: global_id (0x%08x) stored\n",
1447                          op->global->open_global_id));
1448                 NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
1449         }
1450
1451         *_open = op;
1452         return NT_STATUS_OK;
1453 }
1454
1455
1456 static NTSTATUS smbXsrv_open_global_parse_record(TALLOC_CTX *mem_ctx,
1457                                                  struct db_record *rec,
1458                                                  struct smbXsrv_open_global0 **global)
1459 {
1460         TDB_DATA key = dbwrap_record_get_key(rec);
1461         TDB_DATA val = dbwrap_record_get_value(rec);
1462         DATA_BLOB blob = data_blob_const(val.dptr, val.dsize);
1463         struct smbXsrv_open_globalB global_blob;
1464         enum ndr_err_code ndr_err;
1465         NTSTATUS status;
1466         TALLOC_CTX *frame = talloc_stackframe();
1467
1468         ndr_err = ndr_pull_struct_blob(&blob, frame, &global_blob,
1469                         (ndr_pull_flags_fn_t)ndr_pull_smbXsrv_open_globalB);
1470         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1471                 DEBUG(1,("Invalid record in smbXsrv_open_global.tdb:"
1472                          "key '%s' ndr_pull_struct_blob - %s\n",
1473                          hex_encode_talloc(frame, key.dptr, key.dsize),
1474                          ndr_errstr(ndr_err)));
1475                 status = ndr_map_error2ntstatus(ndr_err);
1476                 goto done;
1477         }
1478
1479         if (global_blob.version != SMBXSRV_VERSION_0) {
1480                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
1481                 DEBUG(1,("Invalid record in smbXsrv_open_global.tdb:"
1482                          "key '%s' unsupported version - %d - %s\n",
1483                          hex_encode_talloc(frame, key.dptr, key.dsize),
1484                          (int)global_blob.version,
1485                          nt_errstr(status)));
1486                 goto done;
1487         }
1488
1489         *global = talloc_move(mem_ctx, &global_blob.info.info0);
1490         status = NT_STATUS_OK;
1491 done:
1492         talloc_free(frame);
1493         return status;
1494 }
1495
1496 struct smbXsrv_open_global_traverse_state {
1497         int (*fn)(struct smbXsrv_open_global0 *, void *);
1498         void *private_data;
1499 };
1500
1501 static int smbXsrv_open_global_traverse_fn(struct db_record *rec, void *data)
1502 {
1503         struct smbXsrv_open_global_traverse_state *state =
1504                 (struct smbXsrv_open_global_traverse_state*)data;
1505         struct smbXsrv_open_global0 *global = NULL;
1506         NTSTATUS status;
1507         int ret = -1;
1508
1509         status = smbXsrv_open_global_parse_record(talloc_tos(), rec, &global);
1510         if (!NT_STATUS_IS_OK(status)) {
1511                 return -1;
1512         }
1513
1514         global->db_rec = rec;
1515         ret = state->fn(global, state->private_data);
1516         talloc_free(global);
1517         return ret;
1518 }
1519
1520 NTSTATUS smbXsrv_open_global_traverse(
1521                         int (*fn)(struct smbXsrv_open_global0 *, void *),
1522                         void *private_data)
1523 {
1524
1525         NTSTATUS status;
1526         int count = 0;
1527         struct smbXsrv_open_global_traverse_state state = {
1528                 .fn = fn,
1529                 .private_data = private_data,
1530         };
1531
1532         become_root();
1533         status = smbXsrv_open_global_init();
1534         if (!NT_STATUS_IS_OK(status)) {
1535                 unbecome_root();
1536                 DEBUG(0, ("Failed to initialize open_global: %s\n",
1537                           nt_errstr(status)));
1538                 return status;
1539         }
1540
1541         status = dbwrap_traverse_read(smbXsrv_open_global_db_ctx,
1542                                       smbXsrv_open_global_traverse_fn,
1543                                       &state,
1544                                       &count);
1545         unbecome_root();
1546
1547         return status;
1548 }
1549
1550 NTSTATUS smbXsrv_open_cleanup(uint64_t persistent_id)
1551 {
1552         NTSTATUS status = NT_STATUS_OK;
1553         TALLOC_CTX *frame = talloc_stackframe();
1554         struct smbXsrv_open_global0 *op = NULL;
1555         TDB_DATA val;
1556         struct db_record *rec;
1557         bool delete_open = false;
1558         uint32_t global_id = persistent_id & UINT32_MAX;
1559
1560         rec = smbXsrv_open_global_fetch_locked(smbXsrv_open_global_db_ctx,
1561                                                global_id,
1562                                                frame);
1563         if (rec == NULL) {
1564                 status = NT_STATUS_NOT_FOUND;
1565                 goto done;
1566         }
1567
1568         val = dbwrap_record_get_value(rec);
1569         if (val.dsize == 0) {
1570                 DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1571                           "empty record in %s, skipping...\n",
1572                            global_id, dbwrap_name(smbXsrv_open_global_db_ctx)));
1573                 goto done;
1574         }
1575
1576         status = smbXsrv_open_global_parse_record(talloc_tos(), rec, &op);
1577         if (!NT_STATUS_IS_OK(status)) {
1578                 DEBUG(1, ("smbXsrv_open_cleanup[global: 0x%08x] "
1579                           "failed to read record: %s\n",
1580                           global_id, nt_errstr(status)));
1581                 goto done;
1582         }
1583
1584         if (server_id_is_disconnected(&op->server_id)) {
1585                 struct timeval now, disconnect_time;
1586                 int64_t tdiff;
1587                 now = timeval_current();
1588                 nttime_to_timeval(&disconnect_time, op->disconnect_time);
1589                 tdiff = usec_time_diff(&now, &disconnect_time);
1590                 delete_open = (tdiff >= 1000*op->durable_timeout_msec);
1591
1592                 DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1593                            "disconnected at [%s] %us ago with "
1594                            "timeout of %us -%s reached\n",
1595                            global_id,
1596                            nt_time_string(frame, op->disconnect_time),
1597                            (unsigned)(tdiff/1000000),
1598                            op->durable_timeout_msec / 1000,
1599                            delete_open ? "" : " not"));
1600         } else if (!serverid_exists(&op->server_id)) {
1601                 struct server_id_buf idbuf;
1602                 DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1603                            "server[%s] does not exist\n",
1604                            global_id,
1605                            server_id_str_buf(op->server_id, &idbuf)));
1606                 delete_open = true;
1607         }
1608
1609         if (!delete_open) {
1610                 goto done;
1611         }
1612
1613         status = dbwrap_record_delete(rec);
1614         if (!NT_STATUS_IS_OK(status)) {
1615                 DEBUG(1, ("smbXsrv_open_cleanup[global: 0x%08x] "
1616                           "failed to delete record"
1617                           "from %s: %s\n", global_id,
1618                           dbwrap_name(smbXsrv_open_global_db_ctx),
1619                           nt_errstr(status)));
1620                 goto done;
1621         }
1622
1623         DEBUG(10, ("smbXsrv_open_cleanup[global: 0x%08x] "
1624                    "delete record from %s\n",
1625                    global_id,
1626                    dbwrap_name(smbXsrv_open_global_db_ctx)));
1627
1628 done:
1629         talloc_free(frame);
1630         return status;
1631 }