s3:locking: make use of share_mode_lock_file_id() in share_mode_watch_send()
[samba.git] / source3 / locking / share_mode_lock.c
1 /*
2    Unix SMB/CIFS implementation.
3    Locking functions
4    Copyright (C) Andrew Tridgell 1992-2000
5    Copyright (C) Jeremy Allison 1992-2006
6    Copyright (C) Volker Lendecke 2005
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21    Revision History:
22
23    12 aug 96: Erik.Devriendt@te6.siemens.be
24    added support for shared memory implementation of share mode locking
25
26    May 1997. Jeremy Allison (jallison@whistle.com). Modified share mode
27    locking to deal with multiple share modes per open file.
28
29    September 1997. Jeremy Allison (jallison@whistle.com). Added oplock
30    support.
31
32    rewritten completely to use new tdb code. Tridge, Dec '99
33
34    Added POSIX locking support. Jeremy Allison (jeremy@valinux.com), Apr. 2000.
35    Added Unix Extensions POSIX locking support. Jeremy Allison Mar 2006.
36 */
37
38 #include "includes.h"
39 #include "system/filesys.h"
40 #include "lib/util/server_id.h"
41 #include "share_mode_lock.h"
42 #include "share_mode_lock_private.h"
43 #include "locking/proto.h"
44 #include "smbd/globals.h"
45 #include "dbwrap/dbwrap.h"
46 #include "dbwrap/dbwrap_open.h"
47 #include "dbwrap/dbwrap_private.h"
48 #include "../libcli/security/security.h"
49 #include "serverid.h"
50 #include "messages.h"
51 #include "util_tdb.h"
52 #include "../librpc/gen_ndr/ndr_open_files.h"
53 #include "source3/lib/dbwrap/dbwrap_watch.h"
54 #include "locking/leases_db.h"
55 #include "../lib/util/memcache.h"
56 #include "lib/util/tevent_ntstatus.h"
57 #include "g_lock.h"
58 #include "smbd/fd_handle.h"
59 #include "lib/global_contexts.h"
60
61 #undef DBGC_CLASS
62 #define DBGC_CLASS DBGC_LOCKING
63
64 #define DBG_GET_SHARE_MODE_LOCK(__status, ...) \
65         DBG_PREFIX( \
66                 NT_STATUS_EQUAL(__status, NT_STATUS_NOT_FOUND) ? \
67                 DBGLVL_DEBUG : DBGLVL_ERR, \
68                 (__VA_ARGS__))
69
70 /* the locking database handle */
71 static struct g_lock_ctx *lock_ctx;
72
73 static bool locking_init_internal(bool read_only)
74 {
75         struct db_context *backend;
76         char *db_path;
77
78         brl_init(read_only);
79
80         if (lock_ctx != NULL) {
81                 return True;
82         }
83
84         db_path = lock_path(talloc_tos(), "locking.tdb");
85         if (db_path == NULL) {
86                 return false;
87         }
88
89         backend = db_open(NULL, db_path,
90                           SMB_OPEN_DATABASE_TDB_HASH_SIZE,
91                           TDB_DEFAULT|
92                           TDB_VOLATILE|
93                           TDB_CLEAR_IF_FIRST|
94                           TDB_INCOMPATIBLE_HASH|
95                           TDB_SEQNUM,
96                           read_only?O_RDONLY:O_RDWR|O_CREAT, 0644,
97                           DBWRAP_LOCK_ORDER_NONE,
98                           DBWRAP_FLAG_NONE);
99         TALLOC_FREE(db_path);
100         if (!backend) {
101                 DEBUG(0,("ERROR: Failed to initialise locking database\n"));
102                 return False;
103         }
104
105         lock_ctx = g_lock_ctx_init_backend(
106                 NULL, global_messaging_context(), &backend);
107         if (lock_ctx == NULL) {
108                 TALLOC_FREE(backend);
109                 return false;
110         }
111         g_lock_set_lock_order(lock_ctx, DBWRAP_LOCK_ORDER_1);
112
113         if (!posix_locking_init(read_only)) {
114                 TALLOC_FREE(lock_ctx);
115                 return False;
116         }
117
118         return True;
119 }
120
121 bool locking_init(void)
122 {
123         return locking_init_internal(false);
124 }
125
126 bool locking_init_readonly(void)
127 {
128         return locking_init_internal(true);
129 }
130
131 /*******************************************************************
132  Deinitialize the share_mode management.
133 ******************************************************************/
134
135 bool locking_end(void)
136 {
137         brl_shutdown();
138         TALLOC_FREE(lock_ctx);
139         return true;
140 }
141
142 /*******************************************************************
143  Form a static locking key for a dev/inode pair.
144 ******************************************************************/
145
146 static TDB_DATA locking_key(const struct file_id *id)
147 {
148         return make_tdb_data((const uint8_t *)id, sizeof(*id));
149 }
150
151 /*******************************************************************
152  Share mode cache utility functions that store/delete/retrieve
153  entries from memcache.
154
155  For now share the statcache (global cache) memory space. If
156  a lock record gets orphaned (which shouldn't happen as we're
157  using the same locking_key data as lookup) it will eventually
158  fall out of the cache via the normal LRU trim mechanism. If
159  necessary we can always make this a separate (smaller) cache.
160 ******************************************************************/
161
162 static DATA_BLOB memcache_key(const struct file_id *id)
163 {
164         return data_blob_const((const void *)id, sizeof(*id));
165 }
166
167 static void share_mode_memcache_store(struct share_mode_data *d)
168 {
169         const DATA_BLOB key = memcache_key(&d->id);
170         struct file_id_buf idbuf;
171
172         DBG_DEBUG("stored entry for file %s epoch %"PRIx64" key %s\n",
173                   d->base_name,
174                   d->unique_content_epoch,
175                   file_id_str_buf(d->id, &idbuf));
176
177         /* Ensure everything stored in the cache is pristine. */
178         SMB_ASSERT(!d->modified);
179         SMB_ASSERT(!d->not_stored);
180
181         /*
182          * Ensure the memory going into the cache
183          * doesn't have a destructor so it can be
184          * cleanly evicted by the memcache LRU
185          * mechanism.
186          */
187         talloc_set_destructor(d, NULL);
188
189         /* Cache will own d after this call. */
190         memcache_add_talloc(NULL,
191                         SHARE_MODE_LOCK_CACHE,
192                         key,
193                         &d);
194 }
195
196 /*
197  * NB. We use ndr_pull_hyper on a stack-created
198  * struct ndr_pull with no talloc allowed, as we
199  * need this to be really fast as an ndr-peek into
200  * the first 10 bytes of the blob.
201  */
202
203 static enum ndr_err_code get_share_mode_blob_header(
204         const uint8_t *buf, size_t buflen, uint64_t *pepoch, uint16_t *pflags)
205 {
206         struct ndr_pull ndr = {
207                 .data = discard_const_p(uint8_t, buf),
208                 .data_size = buflen,
209         };
210         NDR_CHECK(ndr_pull_hyper(&ndr, NDR_SCALARS, pepoch));
211         NDR_CHECK(ndr_pull_uint16(&ndr, NDR_SCALARS, pflags));
212         return NDR_ERR_SUCCESS;
213 }
214
215 static int share_mode_data_nofree_destructor(struct share_mode_data *d)
216 {
217         return -1;
218 }
219
220 static struct share_mode_data *share_mode_memcache_fetch(
221         TALLOC_CTX *mem_ctx,
222         struct file_id id,
223         const uint8_t *buf,
224         size_t buflen)
225 {
226         const DATA_BLOB key = memcache_key(&id);
227         enum ndr_err_code ndr_err;
228         struct share_mode_data *d;
229         uint64_t unique_content_epoch;
230         uint16_t flags;
231         void *ptr;
232         struct file_id_buf idbuf;
233
234         ptr = memcache_lookup_talloc(NULL,
235                         SHARE_MODE_LOCK_CACHE,
236                         key);
237         if (ptr == NULL) {
238                 DBG_DEBUG("failed to find entry for key %s\n",
239                           file_id_str_buf(id, &idbuf));
240                 return NULL;
241         }
242         /* sequence number key is at start of blob. */
243         ndr_err = get_share_mode_blob_header(
244                 buf, buflen, &unique_content_epoch, &flags);
245         if (ndr_err != NDR_ERR_SUCCESS) {
246                 /* Bad blob. Remove entry. */
247                 DBG_DEBUG("bad blob %u key %s\n",
248                           (unsigned int)ndr_err,
249                           file_id_str_buf(id, &idbuf));
250                 memcache_delete(NULL,
251                         SHARE_MODE_LOCK_CACHE,
252                         key);
253                 return NULL;
254         }
255
256         d = (struct share_mode_data *)ptr;
257         if (d->unique_content_epoch != unique_content_epoch) {
258                 DBG_DEBUG("epoch changed (cached %"PRIx64") (new %"PRIx64") "
259                           "for key %s\n",
260                           d->unique_content_epoch,
261                           unique_content_epoch,
262                           file_id_str_buf(id, &idbuf));
263                 /* Cache out of date. Remove entry. */
264                 memcache_delete(NULL,
265                         SHARE_MODE_LOCK_CACHE,
266                         key);
267                 return NULL;
268         }
269
270         /* Move onto mem_ctx. */
271         d = talloc_move(mem_ctx, &ptr);
272
273         /*
274          * Now we own d, prevent the cache from freeing it
275          * when we delete the entry.
276          */
277         talloc_set_destructor(d, share_mode_data_nofree_destructor);
278
279         /* Remove from the cache. We own it now. */
280         memcache_delete(NULL,
281                         SHARE_MODE_LOCK_CACHE,
282                         key);
283
284         /* And reset the destructor to none. */
285         talloc_set_destructor(d, NULL);
286
287         DBG_DEBUG("fetched entry for file %s epoch %"PRIx64" key %s\n",
288                   d->base_name,
289                   d->unique_content_epoch,
290                   file_id_str_buf(id, &idbuf));
291
292         return d;
293 }
294
295 /*
296  * 132 is the sizeof an ndr-encoded struct share_mode_entry_buf.
297  * Reading/writing entries will immediately error out if this
298  * size differs (push/pull is done without allocs).
299  */
300
301 struct share_mode_entry_buf {
302         uint8_t buf[132];
303 };
304 #define SHARE_MODE_ENTRY_SIZE (sizeof(struct share_mode_entry_buf))
305
306 static bool share_mode_entry_put(
307         const struct share_mode_entry *e,
308         struct share_mode_entry_buf *dst)
309 {
310         DATA_BLOB blob = { .data = dst->buf, .length = sizeof(dst->buf) };
311         enum ndr_err_code ndr_err;
312
313         if (DEBUGLEVEL>=10) {
314                 DBG_DEBUG("share_mode_entry:\n");
315                 NDR_PRINT_DEBUG(share_mode_entry, discard_const_p(void, e));
316         }
317
318         ndr_err = ndr_push_struct_into_fixed_blob(
319                 &blob,
320                 e,
321                 (ndr_push_flags_fn_t)ndr_push_share_mode_entry);
322         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
323                 DBG_WARNING("ndr_push_share_mode_entry failed: %s\n",
324                             ndr_errstr(ndr_err));
325                 return false;
326         }
327
328         return true;
329 }
330
331 static bool share_mode_entry_get(
332         const uint8_t ptr[SHARE_MODE_ENTRY_SIZE], struct share_mode_entry *e)
333 {
334         enum ndr_err_code ndr_err = NDR_ERR_SUCCESS;
335         DATA_BLOB blob = {
336                 .data = discard_const_p(uint8_t, ptr),
337                 .length = SHARE_MODE_ENTRY_SIZE,
338         };
339
340         ndr_err = ndr_pull_struct_blob_all_noalloc(
341                 &blob, e, (ndr_pull_flags_fn_t)ndr_pull_share_mode_entry);
342         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
343                 DBG_WARNING("ndr_pull_share_mode_entry failed\n");
344                 return false;
345         }
346         return true;
347 }
348
349 /*
350  * locking.tdb records consist of
351  *
352  * uint32_t share_mode_data_len
353  * uint8_t [share_mode_data]       This is struct share_mode_data in NDR
354  *
355  * 0 [SHARE_MODE_ENTRY_SIZE]       Sorted array of share modes,
356  * 1 [SHARE_MODE_ENTRY_SIZE]       filling up the rest of the data in the
357  * 2 [SHARE_MODE_ENTRY_SIZE]       g_lock.c maintained record in locking.tdb
358  */
359
360 struct locking_tdb_data {
361         const uint8_t *share_mode_data_buf;
362         size_t share_mode_data_len;
363         const uint8_t *share_entries;
364         size_t num_share_entries;
365 };
366
367 static bool locking_tdb_data_get(
368         struct locking_tdb_data *data, const uint8_t *buf, size_t buflen)
369 {
370         uint32_t share_mode_data_len, share_entries_len;
371
372         if (buflen == 0) {
373                 *data = (struct locking_tdb_data) { 0 };
374                 return true;
375         }
376         if (buflen < sizeof(uint32_t)) {
377                 return false;
378         }
379
380         share_mode_data_len = PULL_LE_U32(buf, 0);
381
382         buf += sizeof(uint32_t);
383         buflen -= sizeof(uint32_t);
384
385         if (buflen < share_mode_data_len) {
386                 return false;
387         }
388
389         share_entries_len = buflen - share_mode_data_len;
390
391         if ((share_entries_len % SHARE_MODE_ENTRY_SIZE) != 0) {
392                 return false;
393         }
394
395         *data = (struct locking_tdb_data) {
396                 .share_mode_data_buf = buf,
397                 .share_mode_data_len = share_mode_data_len,
398                 .share_entries = buf + share_mode_data_len,
399                 .num_share_entries = share_entries_len / SHARE_MODE_ENTRY_SIZE,
400         };
401
402         return true;
403 }
404
405 struct locking_tdb_data_fetch_state {
406         TALLOC_CTX *mem_ctx;
407         uint8_t *data;
408         size_t datalen;
409 };
410
411 static void locking_tdb_data_fetch_fn(
412         struct server_id exclusive,
413         size_t num_shared,
414         const struct server_id *shared,
415         const uint8_t *data,
416         size_t datalen,
417         void *private_data)
418 {
419         struct locking_tdb_data_fetch_state *state = private_data;
420         state->datalen = datalen;
421         state->data = talloc_memdup(state->mem_ctx, data, datalen);
422 }
423
424 static NTSTATUS locking_tdb_data_fetch(
425         TDB_DATA key, TALLOC_CTX *mem_ctx, struct locking_tdb_data **ltdb)
426 {
427         struct locking_tdb_data_fetch_state state = { 0 };
428         struct locking_tdb_data *result = NULL;
429         NTSTATUS status;
430         bool ok;
431
432         result = talloc_zero(mem_ctx, struct locking_tdb_data);
433         if (result == NULL) {
434                 return NT_STATUS_NO_MEMORY;
435         }
436         state.mem_ctx = result;
437
438         status = g_lock_dump(lock_ctx, key, locking_tdb_data_fetch_fn, &state);
439
440         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
441                 /*
442                  * Just return an empty record
443                  */
444                 goto done;
445         }
446         if (!NT_STATUS_IS_OK(status)) {
447                 DBG_ERR("g_lock_dump failed: %s\n",
448                         nt_errstr(status));
449                 return status;
450         }
451         if (state.datalen == 0) {
452                 goto done;
453         }
454
455         ok = locking_tdb_data_get(result, state.data, state.datalen);
456         if (!ok) {
457                 DBG_ERR("locking_tdb_data_get failed for %zu bytes\n",
458                           state.datalen);
459                 TALLOC_FREE(result);
460                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
461         }
462
463 done:
464         *ltdb = result;
465         return NT_STATUS_OK;
466 }
467
468 static NTSTATUS locking_tdb_data_store(
469         TDB_DATA key,
470         const struct locking_tdb_data *ltdb,
471         const TDB_DATA *share_mode_dbufs,
472         size_t num_share_mode_dbufs)
473 {
474         uint8_t share_mode_data_len_buf[4];
475         TDB_DATA dbufs[num_share_mode_dbufs+3];
476         NTSTATUS status;
477
478         if ((ltdb->share_mode_data_len == 0) &&
479             (ltdb->num_share_entries == 0) &&
480             (num_share_mode_dbufs == 0)) {
481                 /*
482                  * Nothing to write
483                  */
484                 status = g_lock_write_data(lock_ctx, key, NULL, 0);
485                 if (!NT_STATUS_IS_OK(status)) {
486                         DBG_ERR("g_lock_writev_data() failed: %s\n",
487                                 nt_errstr(status));
488                 }
489                 return status;
490         }
491
492         PUSH_LE_U32(share_mode_data_len_buf, 0, ltdb->share_mode_data_len);
493
494         dbufs[0] = (TDB_DATA) {
495                 .dptr = share_mode_data_len_buf,
496                 .dsize = sizeof(share_mode_data_len_buf),
497         };
498         dbufs[1] = (TDB_DATA) {
499                 .dptr = discard_const_p(uint8_t, ltdb->share_mode_data_buf),
500                 .dsize = ltdb->share_mode_data_len,
501         };
502
503         if (ltdb->num_share_entries > SIZE_MAX/SHARE_MODE_ENTRY_SIZE) {
504                 /* overflow */
505                 return NT_STATUS_BUFFER_OVERFLOW;
506         }
507         dbufs[2] = (TDB_DATA) {
508                 .dptr = discard_const_p(uint8_t, ltdb->share_entries),
509                 .dsize = ltdb->num_share_entries * SHARE_MODE_ENTRY_SIZE,
510         };
511
512         if (num_share_mode_dbufs != 0) {
513                 memcpy(&dbufs[3],
514                        share_mode_dbufs,
515                        num_share_mode_dbufs * sizeof(TDB_DATA));
516         }
517
518         status = g_lock_writev_data(lock_ctx, key, dbufs, ARRAY_SIZE(dbufs));
519         if (!NT_STATUS_IS_OK(status)) {
520                 DBG_ERR("g_lock_writev_data() failed: %s\n",
521                         nt_errstr(status));
522         }
523         return status;
524 }
525
526 /*******************************************************************
527  Get all share mode entries for a dev/inode pair.
528 ********************************************************************/
529
530 static struct share_mode_data *parse_share_modes(
531         TALLOC_CTX *mem_ctx,
532         struct file_id id,
533         const uint8_t *buf,
534         size_t buflen)
535 {
536         struct share_mode_data *d;
537         enum ndr_err_code ndr_err;
538         DATA_BLOB blob;
539
540         /* See if we already have a cached copy of this key. */
541         d = share_mode_memcache_fetch(mem_ctx, id, buf, buflen);
542         if (d != NULL) {
543                 return d;
544         }
545
546         d = talloc(mem_ctx, struct share_mode_data);
547         if (d == NULL) {
548                 DEBUG(0, ("talloc failed\n"));
549                 goto fail;
550         }
551
552         blob = (DATA_BLOB) {
553                 .data = discard_const_p(uint8_t, buf),
554                 .length = buflen,
555         };
556         ndr_err = ndr_pull_struct_blob_all(
557                 &blob, d, d, (ndr_pull_flags_fn_t)ndr_pull_share_mode_data);
558         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
559                 DBG_WARNING("ndr_pull_share_mode_data failed: %s\n",
560                             ndr_errstr(ndr_err));
561                 goto fail;
562         }
563
564         if (DEBUGLEVEL >= 10) {
565                 DEBUG(10, ("parse_share_modes:\n"));
566                 NDR_PRINT_DEBUG(share_mode_data, d);
567         }
568
569         return d;
570 fail:
571         TALLOC_FREE(d);
572         return NULL;
573 }
574
575 static NTSTATUS share_mode_data_ltdb_store(struct share_mode_data *d,
576                                            TDB_DATA key,
577                                            struct locking_tdb_data *ltdb,
578                                            const TDB_DATA *share_mode_dbufs,
579                                            size_t num_share_mode_dbufs)
580 {
581         DATA_BLOB blob = { 0 };
582         NTSTATUS status;
583
584         if (!d->modified) {
585                 DBG_DEBUG("share_mode_data not modified\n");
586                 goto store;
587         }
588
589         d->unique_content_epoch = generate_unique_u64(d->unique_content_epoch);
590
591         if (DEBUGLEVEL >= 10) {
592                 DBG_DEBUG("\n");
593                 NDR_PRINT_DEBUG(share_mode_data, d);
594         }
595
596         if (ltdb->num_share_entries != 0 || num_share_mode_dbufs != 0) {
597                 enum ndr_err_code ndr_err;
598
599                 ndr_err = ndr_push_struct_blob(
600                         &blob,
601                         ltdb,
602                         d,
603                         (ndr_push_flags_fn_t)ndr_push_share_mode_data);
604                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
605                         DBG_ERR("ndr_push_share_mode_data failed: %s\n",
606                                   ndr_errstr(ndr_err));
607                         return ndr_map_error2ntstatus(ndr_err);
608                 }
609         }
610
611         ltdb->share_mode_data_buf = blob.data;
612         ltdb->share_mode_data_len = blob.length;
613
614 store:
615         status = locking_tdb_data_store(key,
616                                         ltdb,
617                                         share_mode_dbufs,
618                                         num_share_mode_dbufs);
619         if (!NT_STATUS_IS_OK(status)) {
620                 DBG_ERR("locking_tdb_data_store failed: %s\n",
621                         nt_errstr(status));
622                 return status;
623         }
624
625         d->modified = false;
626         d->not_stored = (ltdb->share_mode_data_len == 0);
627
628         return NT_STATUS_OK;
629 }
630
631 /*******************************************************************
632  If modified, store the share_mode_data back into the database.
633 ********************************************************************/
634
635 static NTSTATUS share_mode_data_store(struct share_mode_data *d)
636 {
637         TDB_DATA key = locking_key(&d->id);
638         struct locking_tdb_data *ltdb = NULL;
639         NTSTATUS status;
640
641         if (!d->modified) {
642                 DBG_DEBUG("not modified\n");
643                 return NT_STATUS_OK;
644         }
645
646         if (DEBUGLEVEL >= 10) {
647                 DBG_DEBUG("\n");
648                 NDR_PRINT_DEBUG(share_mode_data, d);
649         }
650
651         status = locking_tdb_data_fetch(key, d, &ltdb);
652         if (!NT_STATUS_IS_OK(status)) {
653                 DBG_ERR("locking_tdb_data_fetch failed: %s\n",
654                         nt_errstr(status));
655                 return status;
656         }
657
658         status = share_mode_data_ltdb_store(d, key, ltdb, NULL, 0);
659         TALLOC_FREE(ltdb);
660         if (!NT_STATUS_IS_OK(status)) {
661                 DBG_ERR("share_mode_data_ltdb_store failed: %s\n",
662                         nt_errstr(status));
663                 return status;
664         }
665
666         return NT_STATUS_OK;
667 }
668
669 /*******************************************************************
670  Allocate a new share_mode_data struct, mark it unmodified.
671  fresh is set to note that currently there is no database entry.
672 ********************************************************************/
673
674 static struct share_mode_data *fresh_share_mode_lock(
675         TALLOC_CTX *mem_ctx, const char *servicepath,
676         const struct smb_filename *smb_fname,
677         const struct timespec *old_write_time)
678 {
679         struct share_mode_data *d;
680
681         if ((servicepath == NULL) || (smb_fname == NULL) ||
682             (old_write_time == NULL)) {
683                 return NULL;
684         }
685
686         d = talloc_zero(mem_ctx, struct share_mode_data);
687         if (d == NULL) {
688                 goto fail;
689         }
690         d->unique_content_epoch = generate_unique_u64(0);
691
692         d->base_name = talloc_strdup(d, smb_fname->base_name);
693         if (d->base_name == NULL) {
694                 goto fail;
695         }
696         if (smb_fname->stream_name != NULL) {
697                 d->stream_name = talloc_strdup(d, smb_fname->stream_name);
698                 if (d->stream_name == NULL) {
699                         goto fail;
700                 }
701         }
702         d->servicepath = talloc_strdup(d, servicepath);
703         if (d->servicepath == NULL) {
704                 goto fail;
705         }
706         d->old_write_time = full_timespec_to_nt_time(old_write_time);
707         d->flags = SHARE_MODE_SHARE_DELETE |
708                 SHARE_MODE_SHARE_WRITE |
709                 SHARE_MODE_SHARE_READ;
710         d->modified = false;
711         d->not_stored = true;
712         return d;
713 fail:
714         DEBUG(0, ("talloc failed\n"));
715         TALLOC_FREE(d);
716         return NULL;
717 }
718
719 /*
720  * Key that's locked with g_lock
721  */
722 static uint8_t share_mode_lock_key_data[sizeof(struct file_id)];
723 static TDB_DATA share_mode_lock_key = {
724         .dptr = share_mode_lock_key_data,
725         .dsize = sizeof(share_mode_lock_key_data),
726 };
727 static size_t share_mode_lock_key_refcount = 0;
728
729 /*
730  * We can only ever have one share mode locked. Use a static
731  * share_mode_data pointer that is shared by multiple nested
732  * share_mode_lock structures, explicitly refcounted.
733  */
734 static struct share_mode_data *static_share_mode_data = NULL;
735 static size_t static_share_mode_data_refcount = 0;
736
737 /*******************************************************************
738  Either fetch a share mode from the database, or allocate a fresh
739  one if the record doesn't exist.
740 ********************************************************************/
741
742 struct get_static_share_mode_data_state {
743         TALLOC_CTX *mem_ctx;
744         struct file_id id;
745         const char *servicepath;
746         const struct smb_filename *smb_fname;
747         const struct timespec *old_write_time;
748         NTSTATUS status;
749 };
750
751 static void get_static_share_mode_data_fn(
752         struct server_id exclusive,
753         size_t num_shared,
754         const struct server_id *shared,
755         const uint8_t *data,
756         size_t datalen,
757         void *private_data)
758 {
759         struct get_static_share_mode_data_state *state = private_data;
760         struct share_mode_data *d = NULL;
761         struct locking_tdb_data ltdb = { 0 };
762
763         if (datalen != 0) {
764                 bool ok;
765
766                 ok = locking_tdb_data_get(&ltdb, data, datalen);
767                 if (!ok) {
768                         DBG_ERR("locking_tdb_data_get failed\n");
769                         state->status = NT_STATUS_INTERNAL_DB_CORRUPTION;
770                         return;
771                 }
772         }
773
774         if (ltdb.share_mode_data_len == 0) {
775                 if (state->smb_fname == NULL) {
776                         state->status = NT_STATUS_NOT_FOUND;
777                         return;
778                 }
779                 d = fresh_share_mode_lock(
780                         state->mem_ctx,
781                         state->servicepath,
782                         state->smb_fname,
783                         state->old_write_time);
784                 if (d == NULL) {
785                         state->status = NT_STATUS_NO_MEMORY;
786                         return;
787                 }
788         } else {
789                 d = parse_share_modes(
790                         lock_ctx,
791                         state->id,
792                         ltdb.share_mode_data_buf,
793                         ltdb.share_mode_data_len);
794                 if (d == NULL) {
795                         state->status = NT_STATUS_INTERNAL_DB_CORRUPTION;
796                         return;
797                 }
798         }
799
800         d->id = state->id;
801         static_share_mode_data = d;
802 }
803
804 static NTSTATUS get_static_share_mode_data(
805         struct file_id id,
806         const char *servicepath,
807         const struct smb_filename *smb_fname,
808         const struct timespec *old_write_time)
809 {
810         struct get_static_share_mode_data_state state = {
811                 .mem_ctx = lock_ctx,
812                 .id = id,
813                 .servicepath = servicepath,
814                 .smb_fname = smb_fname,
815                 .old_write_time = old_write_time,
816         };
817         NTSTATUS status;
818
819         SMB_ASSERT(static_share_mode_data == NULL);
820
821         status = g_lock_dump(
822                 lock_ctx,
823                 share_mode_lock_key,
824                 get_static_share_mode_data_fn,
825                 &state);
826         if (!NT_STATUS_IS_OK(status)) {
827                 DBG_GET_SHARE_MODE_LOCK(status,
828                         "g_lock_dump failed: %s\n",
829                         nt_errstr(status));
830                 return status;
831         }
832         if (!NT_STATUS_IS_OK(state.status)) {
833                 DBG_GET_SHARE_MODE_LOCK(status,
834                         "get_static_share_mode_data_fn failed: %s\n",
835                         nt_errstr(state.status));
836                 return state.status;
837         }
838
839         return NT_STATUS_OK;
840 }
841
842 struct file_id share_mode_lock_file_id(const struct share_mode_lock *lck)
843 {
844         return lck->id;
845 }
846
847 NTSTATUS share_mode_lock_access_private_data(struct share_mode_lock *lck,
848                                              struct share_mode_data **data)
849 {
850         /*
851          * For now we always have lck->data,
852          * but we may change that in future.
853          */
854         SMB_ASSERT(lck->data != NULL);
855         *data = lck->data;
856         return NT_STATUS_OK;
857 }
858
859 /*******************************************************************
860  Get a share_mode_lock, Reference counted to allow nested calls.
861 ********************************************************************/
862
863 static int share_mode_lock_destructor(struct share_mode_lock *lck);
864
865 struct share_mode_lock *get_share_mode_lock(
866         TALLOC_CTX *mem_ctx,
867         struct file_id id,
868         const char *servicepath,
869         const struct smb_filename *smb_fname,
870         const struct timespec *old_write_time)
871 {
872         TDB_DATA key = locking_key(&id);
873         struct share_mode_lock *lck = NULL;
874         NTSTATUS status;
875         int cmp;
876
877         lck = talloc(mem_ctx, struct share_mode_lock);
878         if (lck == NULL) {
879                 DEBUG(1, ("talloc failed\n"));
880                 return NULL;
881         }
882         lck->id = id;
883
884         if (static_share_mode_data != NULL) {
885                 if (!file_id_equal(&static_share_mode_data->id, &id)) {
886                         struct file_id_buf existing;
887                         struct file_id_buf requested;
888
889                         DBG_ERR("Can not lock two share modes "
890                                 "simultaneously: existing %s requested %s\n",
891                                 file_id_str_buf(static_share_mode_data->id, &existing),
892                                 file_id_str_buf(id, &requested));
893
894                         smb_panic(__location__);
895                         goto fail;
896                 }
897                 goto done;
898         }
899
900         if (share_mode_lock_key_refcount == 0) {
901                 status = g_lock_lock(
902                         lock_ctx,
903                         key,
904                         G_LOCK_WRITE,
905                         (struct timeval) { .tv_sec = 3600 });
906                 if (!NT_STATUS_IS_OK(status)) {
907                         DBG_DEBUG("g_lock_lock failed: %s\n",
908                                   nt_errstr(status));
909                         goto fail;
910                 }
911                 memcpy(share_mode_lock_key_data, key.dptr, key.dsize);
912         }
913
914         cmp = tdb_data_cmp(share_mode_lock_key, key);
915         if (cmp != 0) {
916                 DBG_WARNING("Can not lock two share modes simultaneously\n");
917                 smb_panic(__location__);
918                 goto fail;
919         }
920
921         SMB_ASSERT(share_mode_lock_key_refcount < SIZE_MAX);
922         share_mode_lock_key_refcount += 1;
923
924         SMB_ASSERT(static_share_mode_data_refcount == 0);
925
926         status = get_static_share_mode_data(
927                 id,
928                 servicepath,
929                 smb_fname,
930                 old_write_time);
931         if (!NT_STATUS_IS_OK(status)) {
932                 DBG_DEBUG("get_static_share_mode_data failed: %s\n",
933                           nt_errstr(status));
934                 share_mode_lock_key_refcount -= 1;
935                 goto fail;
936         }
937 done:
938         static_share_mode_data_refcount += 1;
939         lck->data = static_share_mode_data;
940
941         talloc_set_destructor(lck, share_mode_lock_destructor);
942
943         if (CHECK_DEBUGLVL(DBGLVL_DEBUG)) {
944                 struct file_id_buf returned;
945
946                 DBG_DEBUG("Returning %s (data_refcount=%zu key_refcount=%zu)\n",
947                           file_id_str_buf(id, &returned),
948                           static_share_mode_data_refcount,
949                           share_mode_lock_key_refcount);
950         }
951
952         return lck;
953 fail:
954         TALLOC_FREE(lck);
955         if (share_mode_lock_key_refcount == 0) {
956                 status = g_lock_unlock(lock_ctx, share_mode_lock_key);
957                 if (!NT_STATUS_IS_OK(status)) {
958                         DBG_ERR("g_lock_unlock failed: %s\n",
959                                 nt_errstr(status));
960                 }
961         }
962         return NULL;
963 }
964
965 static int share_mode_lock_destructor(struct share_mode_lock *lck)
966 {
967         NTSTATUS status;
968
969         SMB_ASSERT(static_share_mode_data_refcount > 0);
970         static_share_mode_data_refcount -= 1;
971
972         if (static_share_mode_data_refcount > 0) {
973                 return 0;
974         }
975
976         status = share_mode_data_store(static_share_mode_data);
977         if (!NT_STATUS_IS_OK(status)) {
978                 DBG_ERR("share_mode_data_store failed: %s\n",
979                         nt_errstr(status));
980                 smb_panic("Could not store share mode data\n");
981         }
982
983         SMB_ASSERT(share_mode_lock_key_refcount > 0);
984         share_mode_lock_key_refcount -= 1;
985
986         if (share_mode_lock_key_refcount == 0) {
987                 status = g_lock_unlock(lock_ctx, share_mode_lock_key);
988                 if (!NT_STATUS_IS_OK(status)) {
989                         DBG_ERR("g_lock_unlock failed: %s\n",
990                                 nt_errstr(status));
991                         smb_panic("Could not unlock share mode\n");
992                 }
993         }
994
995         if (!static_share_mode_data->not_stored) {
996                 /*
997                  * This is worth keeping. Without share modes,
998                  * share_mode_data_store above has left nothing in the
999                  * database.
1000                  */
1001                 share_mode_memcache_store(static_share_mode_data);
1002                 static_share_mode_data = NULL;
1003         }
1004
1005         TALLOC_FREE(static_share_mode_data);
1006         return 0;
1007 }
1008
1009 /*******************************************************************
1010  Fetch a share mode where we know one MUST exist. This call reference
1011  counts it internally to allow for nested lock fetches.
1012 ********************************************************************/
1013
1014 struct share_mode_lock *get_existing_share_mode_lock(TALLOC_CTX *mem_ctx,
1015                                                      const struct file_id id)
1016 {
1017         return get_share_mode_lock(mem_ctx, id, NULL, NULL, NULL);
1018 }
1019
1020 static void share_mode_wakeup_waiters_fn(
1021         struct share_mode_lock *lck,
1022         void *private_data)
1023 {
1024         g_lock_wake_watchers(lock_ctx, share_mode_lock_key);
1025 }
1026
1027 NTSTATUS share_mode_wakeup_waiters(struct file_id id)
1028 {
1029         return share_mode_do_locked_vfs_denied(id,
1030                                                share_mode_wakeup_waiters_fn,
1031                                                NULL);
1032 }
1033
1034 struct fsp_update_share_mode_flags_state {
1035         struct files_struct *fsp;
1036         enum ndr_err_code ndr_err;
1037         uint64_t share_mode_epoch;
1038         uint16_t share_mode_flags;
1039 };
1040
1041 static void fsp_update_share_mode_flags_fn(
1042         struct server_id exclusive,
1043         size_t num_shared,
1044         const struct server_id *shared,
1045         const uint8_t *data,
1046         size_t datalen,
1047         void *private_data)
1048 {
1049         struct fsp_update_share_mode_flags_state *state = private_data;
1050         struct locking_tdb_data ltdb = { 0 };
1051
1052         if (datalen != 0) {
1053                 bool ok = locking_tdb_data_get(&ltdb, data, datalen);
1054                 if (!ok) {
1055                         DBG_DEBUG("locking_tdb_data_get failed\n");
1056                         return;
1057                 }
1058         }
1059
1060         if (ltdb.share_mode_data_len == 0) {
1061                 /* Likely a ctdb tombstone record, ignore it */
1062                 return;
1063         }
1064
1065         if (exclusive.pid != 0) {
1066                 struct server_id self =
1067                         messaging_server_id(state->fsp->conn->sconn->msg_ctx);
1068                 bool is_self = server_id_equal(&self, &exclusive);
1069
1070                 if (!is_self) {
1071                         /*
1072                          * If someone else is holding an exclusive
1073                          * lock, pretend there's a read lease
1074                          */
1075                         state->share_mode_flags = SHARE_MODE_LEASE_READ;
1076                         return;
1077                 }
1078         }
1079
1080         state->ndr_err = get_share_mode_blob_header(ltdb.share_mode_data_buf,
1081                                                     ltdb.share_mode_data_len,
1082                                                     &state->share_mode_epoch,
1083                                                     &state->share_mode_flags);
1084 }
1085
1086 static NTSTATUS fsp_update_share_mode_flags(struct files_struct *fsp)
1087 {
1088         struct fsp_update_share_mode_flags_state state = { .fsp = fsp, };
1089         int seqnum = g_lock_seqnum(lock_ctx);
1090         TDB_DATA key = {0};
1091         NTSTATUS status;
1092
1093         if (seqnum == fsp->share_mode_flags_seqnum) {
1094                 return NT_STATUS_OK;
1095         }
1096
1097         key = locking_key(&fsp->file_id);
1098         status = g_lock_dump(lock_ctx, key,
1099                              fsp_update_share_mode_flags_fn,
1100                              &state);
1101         if (!NT_STATUS_IS_OK(status)) {
1102                 /* no DBG_GET_SHARE_MODE_LOCK here! */
1103                 DBG_ERR("g_lock_dump returned %s\n",
1104                         nt_errstr(status));
1105                 return status;
1106         }
1107
1108         if (!NDR_ERR_CODE_IS_SUCCESS(state.ndr_err)) {
1109                 DBG_ERR("get_share_mode_blob_header returned %s\n",
1110                         ndr_errstr(state.ndr_err));
1111                 return ndr_map_error2ntstatus(state.ndr_err);
1112         }
1113
1114         fsp->share_mode_flags_seqnum = seqnum;
1115         fsp->share_mode_flags = state.share_mode_flags;
1116
1117         return NT_STATUS_OK;
1118 }
1119
1120 bool file_has_read_lease(struct files_struct *fsp)
1121 {
1122         NTSTATUS status;
1123
1124         status = fsp_update_share_mode_flags(fsp);
1125         if (!NT_STATUS_IS_OK(status)) {
1126                 /* Safe default for leases */
1127                 return true;
1128         }
1129
1130         return (fsp->share_mode_flags & SHARE_MODE_LEASE_READ) != 0;
1131 }
1132
1133 #define share_mode_lock_assert_private_data(__lck) \
1134         _share_mode_lock_assert_private_data(__lck, __func__, __location__)
1135 static struct share_mode_data *_share_mode_lock_assert_private_data(
1136                                         struct share_mode_lock *lck,
1137                                         const char *caller_function,
1138                                         const char *caller_location)
1139 {
1140         struct share_mode_data *d = NULL;
1141         NTSTATUS status;
1142
1143         status = share_mode_lock_access_private_data(lck, &d);
1144         if (!NT_STATUS_IS_OK(status)) {
1145                 struct file_id id = share_mode_lock_file_id(lck);
1146                 struct file_id_buf id_buf;
1147                 /* Any error recovery possible here ? */
1148                 D_ERR("%s:%s(): share_mode_lock_access_private_data() "
1149                       "failed for id=%s - %s\n",
1150                       caller_location, caller_function,
1151                       file_id_str_buf(id, &id_buf),
1152                       nt_errstr(status));
1153                 smb_panic(caller_location);
1154                 return NULL;
1155         }
1156
1157         return d;
1158 }
1159
1160 NTTIME share_mode_changed_write_time(struct share_mode_lock *lck)
1161 {
1162         struct share_mode_data *d = share_mode_lock_assert_private_data(lck);
1163         return d->changed_write_time;
1164 }
1165
1166 const char *share_mode_servicepath(struct share_mode_lock *lck)
1167 {
1168         struct share_mode_data *d = share_mode_lock_assert_private_data(lck);
1169         return d->servicepath;
1170 }
1171
1172 char *share_mode_filename(TALLOC_CTX *mem_ctx, struct share_mode_lock *lck)
1173 {
1174         struct share_mode_data *d = share_mode_lock_assert_private_data(lck);
1175         bool has_stream = (d->stream_name != NULL);
1176         char *fname = NULL;
1177
1178         fname = talloc_asprintf(
1179                 mem_ctx,
1180                 "%s%s%s",
1181                 d->base_name,
1182                 has_stream ? ":" : "",
1183                 has_stream ? d->stream_name : "");
1184         return fname;
1185 }
1186
1187 char *share_mode_data_dump(
1188         TALLOC_CTX *mem_ctx, struct share_mode_lock *lck)
1189 {
1190         struct share_mode_data *d = share_mode_lock_assert_private_data(lck);
1191         struct ndr_print *p = talloc(mem_ctx, struct ndr_print);
1192         char *ret = NULL;
1193
1194         if (p == NULL) {
1195                 return NULL;
1196         }
1197
1198         *p = (struct ndr_print) {
1199                 .print = ndr_print_string_helper,
1200                 .depth = 1,
1201                 .private_data = talloc_strdup(mem_ctx, ""),
1202         };
1203
1204         if (p->private_data == NULL) {
1205                 TALLOC_FREE(p);
1206                 return NULL;
1207         }
1208
1209         ndr_print_share_mode_data(p, "SHARE_MODE_DATA", d);
1210
1211         ret = p->private_data;
1212
1213         TALLOC_FREE(p);
1214
1215         return ret;
1216 }
1217
1218 void share_mode_flags_get(
1219         struct share_mode_lock *lck,
1220         uint32_t *access_mask,
1221         uint32_t *share_mode,
1222         uint32_t *lease_type)
1223 {
1224         struct share_mode_data *d = share_mode_lock_assert_private_data(lck);
1225         uint16_t flags = d->flags;
1226
1227         if (access_mask != NULL) {
1228                 *access_mask =
1229                         ((flags & SHARE_MODE_ACCESS_READ) ?
1230                          FILE_READ_DATA : 0) |
1231                         ((flags & SHARE_MODE_ACCESS_WRITE) ?
1232                          FILE_WRITE_DATA : 0) |
1233                         ((flags & SHARE_MODE_ACCESS_DELETE) ?
1234                          DELETE_ACCESS : 0);
1235         }
1236         if (share_mode != NULL) {
1237                 *share_mode =
1238                         ((flags & SHARE_MODE_SHARE_READ) ?
1239                          FILE_SHARE_READ : 0) |
1240                         ((flags & SHARE_MODE_SHARE_WRITE) ?
1241                          FILE_SHARE_WRITE : 0) |
1242                         ((flags & SHARE_MODE_SHARE_DELETE) ?
1243                          FILE_SHARE_DELETE : 0);
1244         }
1245         if (lease_type != NULL) {
1246                 *lease_type =
1247                         ((flags & SHARE_MODE_LEASE_READ) ?
1248                          SMB2_LEASE_READ : 0) |
1249                         ((flags & SHARE_MODE_LEASE_WRITE) ?
1250                          SMB2_LEASE_WRITE : 0) |
1251                         ((flags & SHARE_MODE_LEASE_HANDLE) ?
1252                          SMB2_LEASE_HANDLE : 0);
1253         }
1254 }
1255
1256 void share_mode_flags_set(
1257         struct share_mode_lock *lck,
1258         uint32_t access_mask,
1259         uint32_t share_mode,
1260         uint32_t lease_type,
1261         bool *modified)
1262 {
1263         struct share_mode_data *d = share_mode_lock_assert_private_data(lck);
1264         uint16_t flags = 0;
1265
1266         flags |= (access_mask & (FILE_READ_DATA | FILE_EXECUTE)) ?
1267                 SHARE_MODE_ACCESS_READ : 0;
1268         flags |= (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
1269                 SHARE_MODE_ACCESS_WRITE : 0;
1270         flags |= (access_mask & (DELETE_ACCESS)) ?
1271                 SHARE_MODE_ACCESS_DELETE : 0;
1272
1273         flags |= (share_mode & FILE_SHARE_READ) ?
1274                 SHARE_MODE_SHARE_READ : 0;
1275         flags |= (share_mode & FILE_SHARE_WRITE) ?
1276                 SHARE_MODE_SHARE_WRITE : 0;
1277         flags |= (share_mode & FILE_SHARE_DELETE) ?
1278                 SHARE_MODE_SHARE_DELETE : 0;
1279
1280         flags |= (lease_type & SMB2_LEASE_READ) ?
1281                 SHARE_MODE_LEASE_READ : 0;
1282         flags |= (lease_type & SMB2_LEASE_WRITE) ?
1283                 SHARE_MODE_LEASE_WRITE : 0;
1284         flags |= (lease_type & SMB2_LEASE_HANDLE) ?
1285                 SHARE_MODE_LEASE_HANDLE : 0;
1286
1287         if (d->flags == flags) {
1288                 return;
1289         }
1290
1291         if (modified != NULL) {
1292                 *modified = true;
1293         }
1294         d->flags = flags;
1295         d->modified = true;
1296 }
1297
1298 struct share_mode_watch_state {
1299         bool blockerdead;
1300         struct server_id blocker;
1301 };
1302
1303 static void share_mode_watch_done(struct tevent_req *subreq);
1304
1305 struct tevent_req *share_mode_watch_send(
1306         TALLOC_CTX *mem_ctx,
1307         struct tevent_context *ev,
1308         struct share_mode_lock *lck,
1309         struct server_id blocker)
1310 {
1311         struct file_id id = share_mode_lock_file_id(lck);
1312         TDB_DATA key = locking_key(&id);
1313         struct tevent_req *req = NULL, *subreq = NULL;
1314         struct share_mode_watch_state *state = NULL;
1315
1316         req = tevent_req_create(
1317                 mem_ctx, &state, struct share_mode_watch_state);
1318         if (req == NULL) {
1319                 return NULL;
1320         }
1321
1322         subreq = g_lock_watch_data_send(state, ev, lock_ctx, key, blocker);
1323         if (tevent_req_nomem(subreq, req)) {
1324                 return tevent_req_post(req, ev);
1325         }
1326         tevent_req_set_callback(subreq, share_mode_watch_done, req);
1327         return req;
1328 }
1329
1330 static void share_mode_watch_done(struct tevent_req *subreq)
1331 {
1332         struct tevent_req *req = tevent_req_callback_data(
1333                 subreq, struct tevent_req);
1334         struct share_mode_watch_state *state = tevent_req_data(
1335                 req, struct share_mode_watch_state);
1336         NTSTATUS status;
1337
1338         status = g_lock_watch_data_recv(
1339                 subreq, &state->blockerdead, &state->blocker);
1340         if (tevent_req_nterror(req, status)) {
1341                 return;
1342         }
1343         tevent_req_done(req);
1344 }
1345
1346 NTSTATUS share_mode_watch_recv(
1347         struct tevent_req *req, bool *blockerdead, struct server_id *blocker)
1348 {
1349         struct share_mode_watch_state *state = tevent_req_data(
1350                 req, struct share_mode_watch_state);
1351         NTSTATUS status;
1352
1353         if (tevent_req_is_nterror(req, &status)) {
1354                 return status;
1355         }
1356         if (blockerdead != NULL) {
1357                 *blockerdead = state->blockerdead;
1358         }
1359         if (blocker != NULL) {
1360                 *blocker = state->blocker;
1361         }
1362         return NT_STATUS_OK;
1363 }
1364
1365 struct fetch_share_mode_unlocked_state {
1366         TALLOC_CTX *mem_ctx;
1367         struct file_id id;
1368         struct share_mode_lock *lck;
1369 };
1370
1371 static void fetch_share_mode_unlocked_parser(
1372         struct server_id exclusive,
1373         size_t num_shared,
1374         const struct server_id *shared,
1375         const uint8_t *data,
1376         size_t datalen,
1377         void *private_data)
1378 {
1379         struct fetch_share_mode_unlocked_state *state = private_data;
1380         struct locking_tdb_data ltdb = { 0 };
1381
1382         if (datalen != 0) {
1383                 bool ok = locking_tdb_data_get(&ltdb, data, datalen);
1384                 if (!ok) {
1385                         DBG_DEBUG("locking_tdb_data_get failed\n");
1386                         return;
1387                 }
1388         }
1389
1390         if (ltdb.share_mode_data_len == 0) {
1391                 /* Likely a ctdb tombstone record, ignore it */
1392                 return;
1393         }
1394
1395         state->lck = talloc(state->mem_ctx, struct share_mode_lock);
1396         if (state->lck == NULL) {
1397                 DEBUG(0, ("talloc failed\n"));
1398                 return;
1399         }
1400         state->lck->id = state->id;
1401
1402         state->lck->data = parse_share_modes(
1403                 state->lck,
1404                 state->id,
1405                 ltdb.share_mode_data_buf,
1406                 ltdb.share_mode_data_len);
1407         if (state->lck->data == NULL) {
1408                 DBG_DEBUG("parse_share_modes failed\n");
1409                 TALLOC_FREE(state->lck);
1410         }
1411 }
1412
1413 /*******************************************************************
1414  Get a share_mode_lock without locking the database or reference
1415  counting. Used by smbstatus to display existing share modes.
1416 ********************************************************************/
1417
1418 struct share_mode_lock *fetch_share_mode_unlocked(TALLOC_CTX *mem_ctx,
1419                                                   struct file_id id)
1420 {
1421         struct fetch_share_mode_unlocked_state state = {
1422                 .mem_ctx = mem_ctx,
1423                 .id = id,
1424         };
1425         TDB_DATA key = locking_key(&id);
1426         NTSTATUS status;
1427
1428         status = g_lock_dump(
1429                 lock_ctx, key, fetch_share_mode_unlocked_parser, &state);
1430         if (!NT_STATUS_IS_OK(status)) {
1431                 DBG_DEBUG("g_lock_dump failed: %s\n", nt_errstr(status));
1432                 return NULL;
1433         }
1434         return state.lck;
1435 }
1436
1437 struct fetch_share_mode_state {
1438         struct file_id id;
1439         struct share_mode_lock *lck;
1440         NTSTATUS status;
1441 };
1442
1443 static void fetch_share_mode_fn(
1444         struct server_id exclusive,
1445         size_t num_shared,
1446         const struct server_id *shared,
1447         const uint8_t *data,
1448         size_t datalen,
1449         void *private_data);
1450 static void fetch_share_mode_done(struct tevent_req *subreq);
1451
1452 /**
1453  * @brief Get a share_mode_lock without locking or refcounting
1454  *
1455  * This can be used in a clustered Samba environment where the async dbwrap
1456  * request is sent over a socket to the local ctdbd. If the send queue is full
1457  * and the caller was issuing multiple async dbwrap requests in a loop, the
1458  * caller knows it's probably time to stop sending requests for now and try
1459  * again later.
1460  *
1461  * @param[in]  mem_ctx The talloc memory context to use.
1462  *
1463  * @param[in]  ev      The event context to work on.
1464  *
1465  * @param[in]  id      The file id for the locking.tdb key
1466  *
1467  * @param[out] queued  This boolean out parameter tells the caller whether the
1468  *                     async request is blocked in a full send queue:
1469  *
1470  *                     false := request is dispatched
1471  *
1472  *                     true  := send queue is full, request waiting to be
1473  *                              dispatched
1474  *
1475  * @return             The new async request, NULL on error.
1476  **/
1477 struct tevent_req *fetch_share_mode_send(TALLOC_CTX *mem_ctx,
1478                                          struct tevent_context *ev,
1479                                          struct file_id id,
1480                                          bool *queued)
1481 {
1482         struct tevent_req *req = NULL, *subreq = NULL;
1483         struct fetch_share_mode_state *state = NULL;
1484
1485         *queued = false;
1486
1487         req = tevent_req_create(mem_ctx, &state,
1488                                 struct fetch_share_mode_state);
1489         if (req == NULL) {
1490                 return NULL;
1491         }
1492         state->id = id;
1493
1494         subreq = g_lock_dump_send(
1495                 state,
1496                 ev,
1497                 lock_ctx,
1498                 locking_key(&id),
1499                 fetch_share_mode_fn,
1500                 state);
1501         if (tevent_req_nomem(subreq, req)) {
1502                 return tevent_req_post(req, ev);
1503         }
1504         tevent_req_set_callback(subreq, fetch_share_mode_done, req);
1505         return req;
1506 }
1507
1508 static void fetch_share_mode_fn(
1509         struct server_id exclusive,
1510         size_t num_shared,
1511         const struct server_id *shared,
1512         const uint8_t *data,
1513         size_t datalen,
1514         void *private_data)
1515 {
1516         struct fetch_share_mode_state *state = talloc_get_type_abort(
1517                 private_data, struct fetch_share_mode_state);
1518         struct locking_tdb_data ltdb = { 0 };
1519
1520         if (datalen != 0) {
1521                 bool ok = locking_tdb_data_get(&ltdb, data, datalen);
1522                 if (!ok) {
1523                         DBG_DEBUG("locking_tdb_data_get failed\n");
1524                         return;
1525                 }
1526         }
1527
1528         if (ltdb.share_mode_data_len == 0) {
1529                 /* Likely a ctdb tombstone record, ignore it */
1530                 return;
1531         }
1532
1533         state->lck = talloc(state, struct share_mode_lock);
1534         if (state->lck == NULL) {
1535                 DBG_WARNING("talloc failed\n");
1536                 state->status = NT_STATUS_NO_MEMORY;
1537                 return;
1538         }
1539         state->lck->id = state->id,
1540
1541         state->lck->data = parse_share_modes(
1542                 state->lck,
1543                 state->id,
1544                 ltdb.share_mode_data_buf,
1545                 ltdb.share_mode_data_len);
1546         if (state->lck->data == NULL) {
1547                 DBG_DEBUG("parse_share_modes failed\n");
1548                 state->status = NT_STATUS_INTERNAL_DB_CORRUPTION;
1549                 TALLOC_FREE(state->lck);
1550                 return;
1551         }
1552 }
1553
1554 static void fetch_share_mode_done(struct tevent_req *subreq)
1555 {
1556         struct tevent_req *req = tevent_req_callback_data(
1557                 subreq, struct tevent_req);
1558         struct fetch_share_mode_state *state = tevent_req_data(
1559                 req, struct fetch_share_mode_state);
1560         NTSTATUS status;
1561
1562         status = g_lock_dump_recv(subreq);
1563         TALLOC_FREE(subreq);
1564         if (tevent_req_nterror(req, status)) {
1565                 return;
1566         }
1567         if (tevent_req_nterror(req, state->status)) {
1568                 return;
1569         }
1570         tevent_req_done(req);
1571 }
1572
1573 NTSTATUS fetch_share_mode_recv(struct tevent_req *req,
1574                                TALLOC_CTX *mem_ctx,
1575                                struct share_mode_lock **_lck)
1576 {
1577         struct fetch_share_mode_state *state = tevent_req_data(
1578                 req, struct fetch_share_mode_state);
1579         struct share_mode_lock *lck = NULL;
1580
1581         NTSTATUS status;
1582
1583         if (tevent_req_is_nterror(req, &status)) {
1584                 tevent_req_received(req);
1585                 return status;
1586         }
1587
1588         if (state->lck == NULL) {
1589                 tevent_req_received(req);
1590                 return NT_STATUS_NOT_FOUND;
1591         }
1592
1593         lck = talloc_move(mem_ctx, &state->lck);
1594
1595         if (DEBUGLEVEL >= 10) {
1596                 DBG_DEBUG("share_mode_data:\n");
1597                 NDR_PRINT_DEBUG(share_mode_data, lck->data);
1598         }
1599
1600         *_lck = lck;
1601         tevent_req_received(req);
1602         return NT_STATUS_OK;
1603 }
1604
1605 struct share_mode_forall_state {
1606         TDB_DATA key;
1607         int (*fn)(struct file_id fid,
1608                   const struct share_mode_data *data,
1609                   void *private_data);
1610         void *private_data;
1611 };
1612
1613 static void share_mode_forall_dump_fn(
1614         struct server_id exclusive,
1615         size_t num_shared,
1616         const struct server_id *shared,
1617         const uint8_t *data,
1618         size_t datalen,
1619         void *private_data)
1620 {
1621         struct share_mode_forall_state *state = private_data;
1622         struct file_id fid;
1623         struct locking_tdb_data ltdb = { 0 };
1624         bool ok;
1625         struct share_mode_data *d;
1626
1627         if (state->key.dsize != sizeof(fid)) {
1628                 DBG_DEBUG("Got invalid key length %zu\n", state->key.dsize);
1629                 return;
1630         }
1631         memcpy(&fid, state->key.dptr, sizeof(fid));
1632
1633         ok = locking_tdb_data_get(&ltdb, data, datalen);
1634         if (!ok) {
1635                 DBG_DEBUG("locking_tdb_data_get() failed\n");
1636                 return;
1637         }
1638
1639         d = parse_share_modes(
1640                 talloc_tos(),
1641                 fid,
1642                 ltdb.share_mode_data_buf,
1643                 ltdb.share_mode_data_len);
1644         if (d == NULL) {
1645                 DBG_DEBUG("parse_share_modes() failed\n");
1646                 return;
1647         }
1648
1649         state->fn(fid, d, state->private_data);
1650         TALLOC_FREE(d);
1651 }
1652
1653 static int share_mode_forall_fn(TDB_DATA key, void *private_data)
1654 {
1655         struct share_mode_forall_state *state = private_data;
1656         NTSTATUS status;
1657
1658         state->key = key;
1659
1660         status = g_lock_dump(
1661                 lock_ctx, key, share_mode_forall_dump_fn, private_data);
1662         if (!NT_STATUS_IS_OK(status)) {
1663                 DBG_GET_SHARE_MODE_LOCK(status,
1664                         "g_lock_dump failed: %s\n",
1665                         nt_errstr(status));
1666         }
1667         return 0;
1668 }
1669
1670 int share_mode_forall(int (*fn)(struct file_id fid,
1671                                 const struct share_mode_data *data,
1672                                 void *private_data),
1673                       void *private_data)
1674 {
1675         struct share_mode_forall_state state = {
1676                 .fn = fn,
1677                 .private_data = private_data
1678         };
1679         int ret;
1680
1681         if (lock_ctx == NULL) {
1682                 return 0;
1683         }
1684
1685         ret = g_lock_locks(
1686                 lock_ctx, share_mode_forall_fn, &state);
1687         if (ret < 0) {
1688                 DBG_ERR("g_lock_locks failed\n");
1689         }
1690         return ret;
1691 }
1692
1693 struct share_entry_forall_state {
1694         struct file_id fid;
1695         const struct share_mode_data *data;
1696         int (*fn)(struct file_id fid,
1697                   const struct share_mode_data *data,
1698                   const struct share_mode_entry *entry,
1699                   void *private_data);
1700         void *private_data;
1701         int ret;
1702 };
1703
1704 static bool share_entry_traverse_walker(
1705         struct share_mode_entry *e,
1706         bool *modified,
1707         void *private_data)
1708 {
1709         struct share_entry_forall_state *state = private_data;
1710
1711         state->ret = state->fn(
1712                 state->fid, state->data, e, state->private_data);
1713         return (state->ret != 0);
1714 }
1715
1716 static int share_entry_traverse_fn(struct file_id fid,
1717                                    const struct share_mode_data *data,
1718                                    void *private_data)
1719 {
1720         struct share_entry_forall_state *state = private_data;
1721         struct share_mode_lock lck = {
1722                 .id = fid,
1723                 .data = discard_const_p(struct share_mode_data, data)
1724         };
1725         bool ok;
1726
1727         state->fid = fid;
1728         state->data = data;
1729
1730         ok = share_mode_forall_entries(
1731                 &lck, share_entry_traverse_walker, state);
1732         if (!ok) {
1733                 DBG_ERR("share_mode_forall_entries failed\n");
1734                 return false;
1735         }
1736
1737         return state->ret;
1738 }
1739
1740 /*******************************************************************
1741  Call the specified function on each entry under management by the
1742  share mode system.
1743 ********************************************************************/
1744
1745 int share_entry_forall(int (*fn)(struct file_id fid,
1746                                  const struct share_mode_data *data,
1747                                  const struct share_mode_entry *entry,
1748                                  void *private_data),
1749                       void *private_data)
1750 {
1751         struct share_entry_forall_state state = {
1752                 .fn = fn, .private_data = private_data };
1753
1754         return share_mode_forall(share_entry_traverse_fn, &state);
1755 }
1756
1757 static int share_mode_entry_cmp(
1758         struct server_id pid1,
1759         uint64_t share_file_id1,
1760         struct server_id pid2,
1761         uint64_t share_file_id2)
1762 {
1763         int cmp;
1764
1765         cmp = server_id_cmp(&pid1, &pid2);
1766         if (cmp != 0) {
1767                 return cmp;
1768         }
1769         if (share_file_id1 != share_file_id2) {
1770                 return (share_file_id1 < share_file_id2) ? -1 : 1;
1771         }
1772         return 0;
1773 }
1774
1775 static size_t share_mode_entry_find(
1776         const uint8_t *data,
1777         size_t num_share_modes,
1778         struct server_id pid,
1779         uint64_t share_file_id,
1780         struct share_mode_entry *e,
1781         bool *match)
1782 {
1783         ssize_t left, right, middle;
1784
1785         *match = false;
1786
1787         if (num_share_modes == 0) {
1788                 return 0;
1789         }
1790
1791         left = 0;
1792         right = (num_share_modes-1);
1793
1794         while (left <= right) {
1795                 const uint8_t *middle_ptr = NULL;
1796                 int cmp;
1797                 bool ok;
1798
1799                 middle = left + ((right - left) / 2);
1800                 middle_ptr = data + middle * SHARE_MODE_ENTRY_SIZE;
1801
1802                 DBG_DEBUG("left=%zu, right=%zu, middle=%zu, middle_ptr=%p\n",
1803                           left,
1804                           right,
1805                           middle,
1806                           middle_ptr);
1807
1808                 ok = share_mode_entry_get(middle_ptr, e);
1809                 if (!ok) {
1810                         DBG_DEBUG("share_mode_entry_get failed\n");
1811                         return 0;
1812                 }
1813
1814                 cmp = share_mode_entry_cmp(
1815                         e->pid, e->share_file_id, pid, share_file_id);
1816                 if (cmp == 0) {
1817                         *match = true;
1818                         return middle;
1819                 }
1820
1821                 if (cmp < 0) {
1822                         right = middle-1;
1823                 } else {
1824                         left = middle+1;
1825                 }
1826         }
1827
1828         return left;
1829 }
1830
1831 bool set_share_mode(struct share_mode_lock *lck,
1832                     struct files_struct *fsp,
1833                     uid_t uid,
1834                     uint64_t mid,
1835                     uint16_t op_type,
1836                     const struct smb2_lease_key *lease_key,
1837                     uint32_t share_access,
1838                     uint32_t access_mask)
1839 {
1840         struct share_mode_data *d = share_mode_lock_assert_private_data(lck);
1841         TDB_DATA key = locking_key(&d->id);
1842         struct server_id my_pid = messaging_server_id(
1843                 fsp->conn->sconn->msg_ctx);
1844         struct locking_tdb_data *ltdb = NULL;
1845         size_t idx;
1846         struct share_mode_entry e = { .pid.pid = 0 };
1847         struct share_mode_entry_buf e_buf;
1848         NTSTATUS status;
1849         bool ok, found;
1850
1851         TDB_DATA dbufs[3];
1852         size_t num_dbufs = 0;
1853
1854         status = locking_tdb_data_fetch(key, talloc_tos(), &ltdb);
1855         if (!NT_STATUS_IS_OK(status)) {
1856                 DBG_ERR("locking_tdb_data_fetch failed: %s\n",
1857                         nt_errstr(status));
1858                 return false;
1859         }
1860         DBG_DEBUG("num_share_modes=%zu\n", ltdb->num_share_entries);
1861
1862         idx = share_mode_entry_find(
1863                 ltdb->share_entries,
1864                 ltdb->num_share_entries,
1865                 my_pid,
1866                 fh_get_gen_id(fsp->fh),
1867                 &e,
1868                 &found);
1869         if (found) {
1870                 DBG_WARNING("Found duplicate share mode\n");
1871                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
1872                 goto done;
1873         }
1874
1875         e = (struct share_mode_entry) {
1876                 .pid = my_pid,
1877                 .share_access = share_access,
1878                 .private_options = fh_get_private_options(fsp->fh),
1879                 .access_mask = access_mask,
1880                 .op_mid = mid,
1881                 .op_type = op_type,
1882                 .time.tv_sec = fsp->open_time.tv_sec,
1883                 .time.tv_usec = fsp->open_time.tv_usec,
1884                 .share_file_id = fh_get_gen_id(fsp->fh),
1885                 .uid = (uint32_t)uid,
1886                 .flags = (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) ?
1887                         SHARE_MODE_FLAG_POSIX_OPEN : 0,
1888                 .name_hash = fsp->name_hash,
1889         };
1890
1891         if (op_type == LEASE_OPLOCK) {
1892                 const struct GUID *client_guid = fsp_client_guid(fsp);
1893                 e.client_guid = *client_guid;
1894                 e.lease_key = *lease_key;
1895         }
1896
1897         ok = share_mode_entry_put(&e, &e_buf);
1898         if (!ok) {
1899                 DBG_DEBUG("share_mode_entry_put failed\n");
1900                 status = NT_STATUS_INTERNAL_ERROR;
1901                 goto done;
1902         }
1903
1904         DBG_DEBUG("idx=%zu, found=%d\n", idx, (int)found);
1905
1906         if (idx > 0) {
1907                 dbufs[num_dbufs] = (TDB_DATA) {
1908                         .dptr = discard_const_p(uint8_t, ltdb->share_entries),
1909                         .dsize = idx * SHARE_MODE_ENTRY_SIZE,
1910                 };
1911                 num_dbufs += 1;
1912         }
1913
1914         dbufs[num_dbufs] = (TDB_DATA) {
1915                 .dptr = e_buf.buf, .dsize = SHARE_MODE_ENTRY_SIZE,
1916         };
1917         num_dbufs += 1;
1918
1919         if (idx < ltdb->num_share_entries) {
1920                 size_t num_after_idx = (ltdb->num_share_entries-idx);
1921                 dbufs[num_dbufs] = (TDB_DATA) {
1922                         .dptr = discard_const_p(uint8_t, ltdb->share_entries) +
1923                                 idx * SHARE_MODE_ENTRY_SIZE,
1924                         .dsize = num_after_idx * SHARE_MODE_ENTRY_SIZE,
1925                 };
1926                 num_dbufs += 1;
1927         }
1928
1929         {
1930                 size_t i;
1931                 for (i=0; i<num_dbufs; i++) {
1932                         DBG_DEBUG("dbufs[%zu]=(%p, %zu)\n",
1933                                   i,
1934                                   dbufs[i].dptr,
1935                                   dbufs[i].dsize);
1936                 }
1937         }
1938
1939         if (num_dbufs == 1) {
1940                 /*
1941                  * Storing a fresh record with just one share entry
1942                  */
1943                 d->modified = true;
1944         }
1945
1946         /*
1947          * If there was any existing data in
1948          * ltdb->share_entries, it's now been
1949          * moved and we've split it into:
1950          *
1951          * num_dbufs = 3
1952          * dbufs[0] -> old sorted data less than new_entry
1953          * dbufs[1] -> new_share_mode_entry
1954          * dbufs[2] -> old sorted_data greater than new entry.
1955          *
1956          * So the old data inside ltdb->share_entries is
1957          * no longer valid.
1958          *
1959          * If we're storing a brand new entry the
1960          * dbufs look like:
1961          *
1962          * num_dbufs = 1
1963          * dbufs[0] -> new_share_mode_entry
1964          *
1965          * Either way we must set ltdb->share_entries = NULL
1966          * and ltdb->num_share_entries = 0 so that
1967          * locking_tdb_data_store() doesn't use it to
1968          * store any data. It's no longer there.
1969          */
1970
1971         ltdb->share_entries = NULL;
1972         ltdb->num_share_entries = 0;
1973
1974         status = share_mode_data_ltdb_store(d, key, ltdb, dbufs, num_dbufs);
1975         if (!NT_STATUS_IS_OK(status)) {
1976                 DBG_ERR("share_mode_data_ltdb_store failed: %s\n",
1977                         nt_errstr(status));
1978         }
1979 done:
1980         TALLOC_FREE(ltdb);
1981         return NT_STATUS_IS_OK(status);
1982 }
1983
1984 static bool share_mode_for_one_entry(
1985         bool (*fn)(struct share_mode_entry *e,
1986                    bool *modified,
1987                    void *private_data),
1988         void *private_data,
1989         size_t *i,
1990         uint8_t *data,
1991         size_t *num_share_modes,
1992         bool *writeback)
1993 {
1994         DATA_BLOB blob = {
1995                 .data = data + (*i) * SHARE_MODE_ENTRY_SIZE,
1996                 .length = SHARE_MODE_ENTRY_SIZE,
1997         };
1998         struct share_mode_entry e = {.pid.pid=0};
1999         enum ndr_err_code ndr_err = NDR_ERR_SUCCESS;
2000         bool modified = false;
2001         bool stop = false;
2002         struct server_id e_pid;
2003         uint64_t e_share_file_id;
2004
2005         ndr_err = ndr_pull_struct_blob_all_noalloc(
2006                 &blob,
2007                 &e,
2008                 (ndr_pull_flags_fn_t)ndr_pull_share_mode_entry);
2009         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2010                 DBG_WARNING("ndr_pull_share_mode_entry failed\n");
2011                 *i += 1;
2012                 return false;
2013         }
2014         if (DEBUGLEVEL >= 10) {
2015                 DBG_DEBUG("entry[%zu]:\n", *i);
2016                 NDR_PRINT_DEBUG(share_mode_entry, &e);
2017         }
2018
2019         e_pid = e.pid;
2020         e_share_file_id = e.share_file_id;
2021
2022         stop = fn(&e, &modified, private_data);
2023
2024         DBG_DEBUG("entry[%zu]: modified=%d, e.stale=%d\n",
2025                   *i,
2026                   (int)modified,
2027                   (int)e.stale);
2028
2029         if (e.stale) {
2030                 if (DEBUGLEVEL>=10) {
2031                         DBG_DEBUG("share_mode_entry:\n");
2032                         NDR_PRINT_DEBUG(share_mode_entry, &e);
2033                 }
2034
2035                 if (*i < *num_share_modes) {
2036                         memmove(blob.data,
2037                                 blob.data + SHARE_MODE_ENTRY_SIZE,
2038                                 (*num_share_modes - *i - 1) *
2039                                 SHARE_MODE_ENTRY_SIZE);
2040                 }
2041                 *num_share_modes -= 1;
2042                 *writeback = true;
2043                 return stop;
2044         }
2045
2046         if (modified) {
2047                 if (DEBUGLEVEL>=10) {
2048                         DBG_DEBUG("share_mode_entry:\n");
2049                         NDR_PRINT_DEBUG(share_mode_entry, &e);
2050                 }
2051
2052                 /*
2053                  * Make sure sorting order is kept intact
2054                  */
2055                 SMB_ASSERT(server_id_equal(&e_pid, &e.pid));
2056                 SMB_ASSERT(e_share_file_id == e.share_file_id);
2057
2058                 ndr_err = ndr_push_struct_into_fixed_blob(
2059                         &blob,
2060                         &e,
2061                         (ndr_push_flags_fn_t)
2062                         ndr_push_share_mode_entry);
2063                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2064                         DBG_WARNING("ndr_push_share_mode_entry "
2065                                     "failed: %s\n",
2066                                     ndr_errstr(ndr_err));
2067                         /*
2068                          * Not much we can do, just ignore it
2069                          */
2070                 }
2071                 *i += 1;
2072                 *writeback = true;
2073                 return stop;
2074         }
2075
2076         if (stop) {
2077                 return true;
2078         }
2079
2080         *i += 1;
2081         return false;
2082 }
2083
2084 bool share_mode_forall_entries(
2085         struct share_mode_lock *lck,
2086         bool (*fn)(struct share_mode_entry *e,
2087                    bool *modified,
2088                    void *private_data),
2089         void *private_data)
2090 {
2091         struct share_mode_data *d = lck->data;
2092         TDB_DATA key = locking_key(&d->id);
2093         struct locking_tdb_data *ltdb = NULL;
2094         uint8_t *share_entries = NULL;
2095         size_t num_share_entries;
2096         bool writeback = false;
2097         NTSTATUS status;
2098         bool stop = false;
2099         size_t i;
2100
2101         status = locking_tdb_data_fetch(key, talloc_tos(), &ltdb);
2102         if (!NT_STATUS_IS_OK(status)) {
2103                 DBG_ERR("locking_tdb_data_fetch failed: %s\n",
2104                         nt_errstr(status));
2105                 return false;
2106         }
2107         DBG_DEBUG("num_share_modes=%zu\n", ltdb->num_share_entries);
2108
2109         num_share_entries = ltdb->num_share_entries;
2110         share_entries = discard_const_p(uint8_t, ltdb->share_entries);
2111
2112         i = 0;
2113         while (i<num_share_entries) {
2114                 stop = share_mode_for_one_entry(
2115                         fn,
2116                         private_data,
2117                         &i,
2118                         share_entries,
2119                         &num_share_entries,
2120                         &writeback);
2121                 if (stop) {
2122                         break;
2123                 }
2124         }
2125
2126         DBG_DEBUG("num_share_entries=%zu, writeback=%d\n",
2127                   num_share_entries,
2128                   (int)writeback);
2129
2130         if (!writeback) {
2131                 TALLOC_FREE(ltdb);
2132                 return true;
2133         }
2134
2135         if ((ltdb->num_share_entries != 0 ) && (num_share_entries == 0)) {
2136                 /*
2137                  * This routine wiped all share entries, let
2138                  * share_mode_data_store() delete the record
2139                  */
2140                 d->modified = true;
2141         }
2142
2143         ltdb->num_share_entries = num_share_entries;
2144         ltdb->share_entries = share_entries;
2145
2146         status = share_mode_data_ltdb_store(d, key, ltdb, NULL, 0);
2147         TALLOC_FREE(ltdb);
2148         if (!NT_STATUS_IS_OK(status)) {
2149                 DBG_ERR("share_mode_data_ltdb_store failed: %s\n",
2150                         nt_errstr(status));
2151                 return false;
2152         }
2153
2154         return true;
2155 }
2156
2157 struct share_mode_count_entries_state {
2158         size_t num_share_modes;
2159         NTSTATUS status;
2160 };
2161
2162 static void share_mode_count_entries_fn(
2163         struct server_id exclusive,
2164         size_t num_shared,
2165         const struct server_id *shared,
2166         const uint8_t *data,
2167         size_t datalen,
2168         void *private_data)
2169 {
2170         struct share_mode_count_entries_state *state = private_data;
2171         struct locking_tdb_data ltdb = { 0 };
2172         bool ok;
2173
2174         ok = locking_tdb_data_get(&ltdb, data, datalen);
2175         if (!ok) {
2176                 DBG_WARNING("locking_tdb_data_get failed for %zu\n", datalen);
2177                 state->status = NT_STATUS_INTERNAL_DB_CORRUPTION;
2178                 return;
2179         }
2180         state->num_share_modes = ltdb.num_share_entries;
2181         state->status = NT_STATUS_OK;
2182 }
2183
2184 NTSTATUS share_mode_count_entries(struct file_id fid, size_t *num_share_modes)
2185 {
2186         struct share_mode_count_entries_state state = {
2187                 .status = NT_STATUS_NOT_FOUND,
2188         };
2189         NTSTATUS status;
2190
2191         status = g_lock_dump(
2192                 lock_ctx,
2193                 locking_key(&fid),
2194                 share_mode_count_entries_fn,
2195                 &state);
2196         if (!NT_STATUS_IS_OK(status)) {
2197                 DBG_DEBUG("g_lock_dump failed: %s\n",
2198                           nt_errstr(status));
2199                 return status;
2200         }
2201         if (!NT_STATUS_IS_OK(state.status)) {
2202                 DBG_DEBUG("share_mode_count_entries_fn failed: %s\n",
2203                           nt_errstr(state.status));
2204                 return state.status;
2205         }
2206
2207         *num_share_modes = state.num_share_modes;
2208         return NT_STATUS_OK;
2209 }
2210
2211 static bool share_mode_entry_do(
2212         struct share_mode_lock *lck,
2213         struct server_id pid,
2214         uint64_t share_file_id,
2215         void (*fn)(struct share_mode_entry *e,
2216                    size_t num_share_modes,
2217                    bool *modified,
2218                    void *private_data),
2219         void *private_data)
2220 {
2221         struct share_mode_data *d = lck->data;
2222         TDB_DATA key = locking_key(&d->id);
2223         struct locking_tdb_data *ltdb = NULL;
2224         size_t idx;
2225         bool found = false;
2226         bool modified = false;
2227         struct share_mode_entry e;
2228         uint8_t *e_ptr = NULL;
2229         NTSTATUS status;
2230         bool ret = false;
2231
2232         status = locking_tdb_data_fetch(key, talloc_tos(), &ltdb);
2233         if (!NT_STATUS_IS_OK(status)) {
2234                 DBG_ERR("locking_tdb_data_fetch failed: %s\n",
2235                         nt_errstr(status));
2236                 return false;
2237         }
2238         DBG_DEBUG("num_share_modes=%zu\n", ltdb->num_share_entries);
2239
2240         idx = share_mode_entry_find(
2241                 ltdb->share_entries,
2242                 ltdb->num_share_entries,
2243                 pid,
2244                 share_file_id,
2245                 &e,
2246                 &found);
2247         if (!found) {
2248                 DBG_WARNING("Did not find share mode entry for %"PRIu64"\n",
2249                             share_file_id);
2250                 goto done;
2251         }
2252
2253         if (DEBUGLEVEL>=10) {
2254                 DBG_DEBUG("entry[%zu]:\n", idx);
2255                 NDR_PRINT_DEBUG(share_mode_entry, &e);
2256         }
2257
2258         fn(&e, ltdb->num_share_entries, &modified, private_data);
2259
2260         DBG_DEBUG("entry[%zu]: modified=%d, e.stale=%d\n",
2261                   idx,
2262                   (int)modified,
2263                   (int)e.stale);
2264
2265         if (!e.stale && !modified) {
2266                 ret = true;
2267                 goto done;
2268         }
2269
2270         e_ptr = discard_const_p(uint8_t, ltdb->share_entries) +
2271                 idx * SHARE_MODE_ENTRY_SIZE;
2272
2273         if (e.stale) {
2274                 /*
2275                  * Move the rest down one entry
2276                  */
2277                 size_t behind = ltdb->num_share_entries - idx - 1;
2278                 if (behind != 0) {
2279                         memmove(e_ptr,
2280                                 e_ptr + SHARE_MODE_ENTRY_SIZE,
2281                                 behind * SHARE_MODE_ENTRY_SIZE);
2282                 }
2283                 ltdb->num_share_entries -= 1;
2284
2285                 if (ltdb->num_share_entries == 0) {
2286                         /*
2287                          * Tell share_mode_lock_destructor() to delete
2288                          * the whole record
2289                          */
2290                         d->modified = true;
2291                 }
2292
2293                 if (DEBUGLEVEL>=10) {
2294                         DBG_DEBUG("share_mode_entry:\n");
2295                         NDR_PRINT_DEBUG(share_mode_entry, &e);
2296                 }
2297         } else {
2298                 struct share_mode_entry_buf buf;
2299                 bool ok;
2300
2301                 if (ltdb->num_share_entries != 1) {
2302                         /*
2303                          * Make sure the sorting order stays intact
2304                          */
2305                         SMB_ASSERT(server_id_equal(&e.pid, &pid));
2306                         SMB_ASSERT(e.share_file_id == share_file_id);
2307                 }
2308
2309                 ok = share_mode_entry_put(&e, &buf);
2310                 if (!ok) {
2311                         DBG_DEBUG("share_mode_entry_put failed\n");
2312                         goto done;
2313                 }
2314                 memcpy(e_ptr, buf.buf, SHARE_MODE_ENTRY_SIZE);
2315         }
2316
2317         status = share_mode_data_ltdb_store(d, key, ltdb, NULL, 0);
2318         if (!NT_STATUS_IS_OK(status)) {
2319                 DBG_ERR("share_mode_data_ltdb_store failed: %s\n",
2320                         nt_errstr(status));
2321                 goto done;
2322         }
2323
2324         ret = true;
2325 done:
2326         TALLOC_FREE(ltdb);
2327         return ret;
2328 }
2329
2330 struct del_share_mode_state {
2331         bool ok;
2332 };
2333
2334 static void del_share_mode_fn(
2335         struct share_mode_entry *e,
2336         size_t num_share_modes,
2337         bool *modified,
2338         void *private_data)
2339 {
2340         struct del_share_mode_state *state = private_data;
2341         e->stale = true;
2342         state->ok = true;
2343 }
2344
2345 bool del_share_mode(struct share_mode_lock *lck, files_struct *fsp)
2346 {
2347         struct del_share_mode_state state = { .ok = false };
2348         bool ok;
2349
2350         ok = share_mode_entry_do(
2351                 lck,
2352                 messaging_server_id(fsp->conn->sconn->msg_ctx),
2353                 fh_get_gen_id(fsp->fh),
2354                 del_share_mode_fn,
2355                 &state);
2356         if (!ok) {
2357                 DBG_DEBUG("share_mode_entry_do failed\n");
2358                 return false;
2359         }
2360         if (!state.ok) {
2361                 DBG_DEBUG("del_share_mode_fn failed\n");
2362                 return false;
2363         }
2364         return true;
2365 }
2366
2367 struct remove_share_oplock_state {
2368         bool ok;
2369 };
2370
2371 static void remove_share_oplock_fn(
2372         struct share_mode_entry *e,
2373         size_t num_share_modes,
2374         bool *modified,
2375         void *private_data)
2376 {
2377         struct remove_share_oplock_state *state = private_data;
2378
2379         e->op_type = NO_OPLOCK;
2380         *modified = true;
2381         state->ok = true;
2382 }
2383
2384 bool remove_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
2385 {
2386         struct remove_share_oplock_state state = { .ok = false };
2387         bool ok;
2388
2389         ok = share_mode_entry_do(
2390                 lck,
2391                 messaging_server_id(fsp->conn->sconn->msg_ctx),
2392                 fh_get_gen_id(fsp->fh),
2393                 remove_share_oplock_fn,
2394                 &state);
2395         if (!ok) {
2396                 DBG_DEBUG("share_mode_entry_do failed\n");
2397                 return false;
2398         }
2399         if (!state.ok) {
2400                 DBG_DEBUG("remove_share_oplock_fn failed\n");
2401                 return false;
2402         }
2403
2404         if (fsp->oplock_type == LEASE_OPLOCK) {
2405                 remove_lease_if_stale(
2406                         lck,
2407                         fsp_client_guid(fsp),
2408                         &fsp->lease->lease.lease_key);
2409         }
2410
2411         share_mode_wakeup_waiters(fsp->file_id);
2412
2413         return true;
2414 }
2415
2416 struct downgrade_share_oplock_state {
2417         bool ok;
2418 };
2419
2420 static void downgrade_share_oplock_fn(
2421         struct share_mode_entry *e,
2422         size_t num_share_modes,
2423         bool *modified,
2424         void *private_data)
2425 {
2426         struct downgrade_share_oplock_state *state = private_data;
2427
2428         e->op_type = LEVEL_II_OPLOCK;
2429         *modified = true;
2430         state->ok = true;
2431 }
2432
2433 bool downgrade_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
2434 {
2435         struct downgrade_share_oplock_state state = { .ok = false };
2436         bool ok;
2437
2438         ok = share_mode_entry_do(
2439                 lck,
2440                 messaging_server_id(fsp->conn->sconn->msg_ctx),
2441                 fh_get_gen_id(fsp->fh),
2442                 downgrade_share_oplock_fn,
2443                 &state);
2444         if (!ok) {
2445                 DBG_DEBUG("share_mode_entry_do failed\n");
2446                 return false;
2447         }
2448         if (!state.ok) {
2449                 DBG_DEBUG("downgrade_share_oplock_fn failed\n");
2450                 return false;
2451         }
2452
2453         lck->data->flags |= SHARE_MODE_LEASE_READ;
2454         lck->data->modified = true;
2455
2456         return true;
2457 }
2458
2459 bool mark_share_mode_disconnected(struct share_mode_lock *lck,
2460                                   struct files_struct *fsp)
2461 {
2462         struct server_id disconnected_pid = { .pid = 0 };
2463         bool ok;
2464
2465         if (fsp->op == NULL) {
2466                 return false;
2467         }
2468         if (!fsp->op->global->durable) {
2469                 return false;
2470         }
2471
2472         server_id_set_disconnected(&disconnected_pid);
2473
2474         ok = reset_share_mode_entry(
2475                 lck,
2476                 messaging_server_id(fsp->conn->sconn->msg_ctx),
2477                 fh_get_gen_id(fsp->fh),
2478                 disconnected_pid,
2479                 UINT64_MAX,
2480                 fsp->op->global->open_persistent_id);
2481
2482         return ok;
2483 }
2484
2485 bool reset_share_mode_entry(
2486         struct share_mode_lock *lck,
2487         struct server_id old_pid,
2488         uint64_t old_share_file_id,
2489         struct server_id new_pid,
2490         uint64_t new_mid,
2491         uint64_t new_share_file_id)
2492 {
2493         struct share_mode_data *d = lck->data;
2494         TDB_DATA key = locking_key(&d->id);
2495         struct locking_tdb_data *ltdb = NULL;
2496         struct share_mode_entry e;
2497         struct share_mode_entry_buf e_buf;
2498         NTSTATUS status;
2499         int cmp;
2500         bool ret = false;
2501         bool ok;
2502
2503         status = locking_tdb_data_fetch(key, talloc_tos(), &ltdb);
2504         if (!NT_STATUS_IS_OK(status)) {
2505                 DBG_ERR("locking_tdb_data_fetch failed: %s\n",
2506                         nt_errstr(status));
2507                 return false;
2508         }
2509
2510         if (ltdb->num_share_entries != 1) {
2511                 DBG_DEBUG("num_share_modes=%zu\n", ltdb->num_share_entries);
2512                 goto done;
2513         }
2514
2515         ok = share_mode_entry_get(ltdb->share_entries, &e);
2516         if (!ok) {
2517                 DBG_WARNING("share_mode_entry_get failed\n");
2518                 goto done;
2519         }
2520
2521         cmp = share_mode_entry_cmp(
2522                 old_pid, old_share_file_id, e.pid, e.share_file_id);
2523         if (cmp != 0) {
2524                 struct server_id_buf tmp1, tmp2;
2525                 DBG_WARNING("Expected pid=%s, file_id=%"PRIu64", "
2526                             "got pid=%s, file_id=%"PRIu64"\n",
2527                             server_id_str_buf(old_pid, &tmp1),
2528                             old_share_file_id,
2529                             server_id_str_buf(e.pid, &tmp2),
2530                             e.share_file_id);
2531                 goto done;
2532         }
2533
2534         e.pid = new_pid;
2535         if (new_mid != UINT64_MAX) {
2536                 e.op_mid = new_mid;
2537         }
2538         e.share_file_id = new_share_file_id;
2539
2540         ok = share_mode_entry_put(&e, &e_buf);
2541         if (!ok) {
2542                 DBG_WARNING("share_mode_entry_put failed\n");
2543                 goto done;
2544         }
2545
2546         ltdb->share_entries = e_buf.buf;
2547
2548         d->modified = true;
2549
2550         status = share_mode_data_ltdb_store(d, key, ltdb, NULL, 0);
2551         if (!NT_STATUS_IS_OK(status)) {
2552                 DBG_ERR("share_mode_data_ltdb_store failed: %s\n",
2553                         nt_errstr(status));
2554                 goto done;
2555         }
2556
2557         ret = true;
2558 done:
2559         TALLOC_FREE(ltdb);
2560         return ret;
2561 }
2562
2563 /**
2564  * @brief Run @fn protected with G_LOCK_WRITE in the given file_id
2565  *
2566  * @fn is NOT allowed to call SMB_VFS_* or similar functions,
2567  * which may block for some time in the kernel.
2568  *
2569  * There must be at least one share_mode_entry, otherwise
2570  * NT_STATUS_NOT_FOUND is returned.
2571  *
2572  * @param[in]  id           The key for the share_mode record.
2573  * @param[in]  fn           The function to run under the g_lock.
2574  * @param[in]  private_date A private pointer passed to @fn.
2575  */
2576 NTSTATUS _share_mode_do_locked_vfs_denied(
2577         struct file_id id,
2578         share_mode_do_locked_vfs_fn_t fn,
2579         void *private_data,
2580         const char *location)
2581 {
2582         struct smb_vfs_deny_state vfs_deny = {};
2583         struct share_mode_lock *lck = NULL;
2584
2585         lck = get_existing_share_mode_lock(talloc_tos(), id);
2586         if (lck == NULL) {
2587                 NTSTATUS status = NT_STATUS_NOT_FOUND;
2588                 DBG_DEBUG("get_existing_share_mode_lock failed: %s\n",
2589                           nt_errstr(status));
2590                 return status;
2591         }
2592
2593         _smb_vfs_deny_push(&vfs_deny, location);
2594         fn(lck, private_data);
2595         _smb_vfs_deny_pop(&vfs_deny, location);
2596
2597         TALLOC_FREE(lck);
2598
2599         return NT_STATUS_OK;
2600 }
2601
2602 /**
2603  * @brief Run @fn protected with G_LOCK_WRITE in the given file_id
2604  *
2605  * @fn is allowed to call SMB_VFS_* or similar functions,
2606  * which may block for some time in the kernel.
2607  *
2608  * There must be at least one share_mode_entry, otherwise
2609  * NT_STATUS_NOT_FOUND is returned.
2610  *
2611  * @param[in]  id           The key for the share_mode record.
2612  * @param[in]  fn           The function to run under the g_lock.
2613  * @param[in]  private_date A private pointer passed to @fn.
2614  */
2615 NTSTATUS _share_mode_do_locked_vfs_allowed(
2616         struct file_id id,
2617         share_mode_do_locked_vfs_fn_t fn,
2618         void *private_data,
2619         const char *location)
2620 {
2621         struct share_mode_lock *lck = NULL;
2622
2623         smb_vfs_assert_allowed();
2624
2625         lck = get_existing_share_mode_lock(talloc_tos(), id);
2626         if (lck == NULL) {
2627                 NTSTATUS status = NT_STATUS_NOT_FOUND;
2628                 DBG_DEBUG("get_existing_share_mode_lock failed: %s\n",
2629                           nt_errstr(status));
2630                 return status;
2631         }
2632
2633         fn(lck, private_data);
2634
2635         TALLOC_FREE(lck);
2636
2637         return NT_STATUS_OK;
2638 }