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