smbd: Pass "share_mode_data" to share_entry_forall callback
[metze/samba/wip.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 "locking/proto.h"
42 #include "smbd/globals.h"
43 #include "dbwrap/dbwrap.h"
44 #include "dbwrap/dbwrap_open.h"
45 #include "../libcli/security/security.h"
46 #include "serverid.h"
47 #include "messages.h"
48 #include "util_tdb.h"
49 #include "../librpc/gen_ndr/ndr_open_files.h"
50 #include "source3/lib/dbwrap/dbwrap_watch.h"
51 #include "locking/leases_db.h"
52 #include "../lib/util/memcache.h"
53 #include "lib/util/tevent_ntstatus.h"
54
55 #undef DBGC_CLASS
56 #define DBGC_CLASS DBGC_LOCKING
57
58 #define NO_LOCKING_COUNT (-1)
59
60 /* the locking database handle */
61 static struct db_context *lock_db;
62
63 static bool locking_init_internal(bool read_only)
64 {
65         struct db_context *backend;
66         char *db_path;
67
68         brl_init(read_only);
69
70         if (lock_db)
71                 return True;
72
73         db_path = lock_path("locking.tdb");
74         if (db_path == NULL) {
75                 return false;
76         }
77
78         backend = db_open(NULL, db_path,
79                           SMB_OPEN_DATABASE_TDB_HASH_SIZE,
80                           TDB_DEFAULT|TDB_VOLATILE|TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH,
81                           read_only?O_RDONLY:O_RDWR|O_CREAT, 0644,
82                           DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
83         TALLOC_FREE(db_path);
84         if (!backend) {
85                 DEBUG(0,("ERROR: Failed to initialise locking database\n"));
86                 return False;
87         }
88
89         lock_db = db_open_watched(NULL, backend, server_messaging_context());
90         if (lock_db == NULL) {
91                 DBG_ERR("db_open_watched failed\n");
92                 TALLOC_FREE(backend);
93                 return false;
94         }
95
96         if (!posix_locking_init(read_only)) {
97                 TALLOC_FREE(lock_db);
98                 return False;
99         }
100
101         return True;
102 }
103
104 bool locking_init(void)
105 {
106         return locking_init_internal(false);
107 }
108
109 bool locking_init_readonly(void)
110 {
111         return locking_init_internal(true);
112 }
113
114 /*******************************************************************
115  Deinitialize the share_mode management.
116 ******************************************************************/
117
118 bool locking_end(void)
119 {
120         brl_shutdown();
121         TALLOC_FREE(lock_db);
122         return true;
123 }
124
125 /*******************************************************************
126  Form a static locking key for a dev/inode pair.
127 ******************************************************************/
128
129 static TDB_DATA locking_key(const struct file_id *id)
130 {
131         return make_tdb_data((const uint8_t *)id, sizeof(*id));
132 }
133
134 /*******************************************************************
135  Share mode cache utility functions that store/delete/retrieve
136  entries from memcache.
137
138  For now share the statcache (global cache) memory space. If
139  a lock record gets orphaned (which shouldn't happen as we're
140  using the same locking_key data as lookup) it will eventually
141  fall out of the cache via the normal LRU trim mechanism. If
142  necessary we can always make this a separate (smaller) cache.
143 ******************************************************************/
144
145 static const DATA_BLOB memcache_key(const struct file_id *id)
146 {
147         return data_blob_const((const void *)id, sizeof(*id));
148 }
149
150 static void share_mode_memcache_delete(struct share_mode_data *d)
151 {
152         const DATA_BLOB key = memcache_key(&d->id);
153
154         DEBUG(10,("deleting entry for file %s seq 0x%llu key %s\n",
155                 d->base_name,
156                 (unsigned long long) d->sequence_number,
157                 file_id_string(talloc_tos(), &d->id)));
158
159         memcache_delete(NULL,
160                         SHARE_MODE_LOCK_CACHE,
161                         key);
162 }
163
164 static void share_mode_memcache_store(struct share_mode_data *d)
165 {
166         const DATA_BLOB key = memcache_key(&d->id);
167
168         DEBUG(10,("stored entry for file %s seq 0x%llu key %s\n",
169                 d->base_name,
170                 (unsigned long long) d->sequence_number,
171                 file_id_string(talloc_tos(), &d->id)));
172
173         /* Ensure everything stored in the cache is pristine. */
174         d->modified = false;
175         d->fresh = false;
176
177         /*
178          * Ensure the memory going into the cache
179          * doesn't have a destructor so it can be
180          * cleanly freed by share_mode_memcache_delete().
181          */
182         talloc_set_destructor(d, NULL);
183
184         /* Cache will own d after this call. */
185         memcache_add_talloc(NULL,
186                         SHARE_MODE_LOCK_CACHE,
187                         key,
188                         &d);
189 }
190
191 /*
192  * NB. We use ndr_pull_hyper on a stack-created
193  * struct ndr_pull with no talloc allowed, as we
194  * need this to be really fast as an ndr-peek into
195  * the first 8 bytes of the blob.
196  */
197
198 static enum ndr_err_code get_blob_sequence_number(DATA_BLOB *blob,
199                                                 uint64_t *pseq)
200 {
201         struct ndr_pull ndr = {.data = blob->data, .data_size = blob->length};
202         NDR_CHECK(ndr_pull_hyper(&ndr, NDR_SCALARS, pseq));
203         return NDR_ERR_SUCCESS;
204 }
205
206 static int share_mode_data_nofree_destructor(struct share_mode_data *d)
207 {
208         return -1;
209 }
210
211 static struct share_mode_data *share_mode_memcache_fetch(TALLOC_CTX *mem_ctx,
212                                         const TDB_DATA id_key,
213                                         DATA_BLOB *blob)
214 {
215         enum ndr_err_code ndr_err;
216         struct share_mode_data *d;
217         uint64_t sequence_number;
218         void *ptr;
219         struct file_id id;
220         DATA_BLOB key;
221
222         /* Ensure this is a locking_key record. */
223         if (id_key.dsize != sizeof(id)) {
224                 return NULL;
225         }
226
227         memcpy(&id, id_key.dptr, id_key.dsize);
228         key = memcache_key(&id);
229
230         ptr = memcache_lookup_talloc(NULL,
231                         SHARE_MODE_LOCK_CACHE,
232                         key);
233         if (ptr == NULL) {
234                 DEBUG(10,("failed to find entry for key %s\n",
235                         file_id_string(mem_ctx, &id)));
236                 return NULL;
237         }
238         /* sequence number key is at start of blob. */
239         ndr_err = get_blob_sequence_number(blob, &sequence_number);
240         if (ndr_err != NDR_ERR_SUCCESS) {
241                 /* Bad blob. Remove entry. */
242                 DEBUG(10,("bad blob %u key %s\n",
243                         (unsigned int)ndr_err,
244                         file_id_string(mem_ctx, &id)));
245                 memcache_delete(NULL,
246                         SHARE_MODE_LOCK_CACHE,
247                         key);
248                 return NULL;
249         }
250
251         d = (struct share_mode_data *)ptr;
252         if (d->sequence_number != sequence_number) {
253                 DEBUG(10,("seq changed (cached 0x%llu) (new 0x%llu) "
254                         "for key %s\n",
255                         (unsigned long long)d->sequence_number,
256                         (unsigned long long)sequence_number,
257                         file_id_string(mem_ctx, &id)));
258                 /* Cache out of date. Remove entry. */
259                 memcache_delete(NULL,
260                         SHARE_MODE_LOCK_CACHE,
261                         key);
262                 return NULL;
263         }
264
265         /* Move onto mem_ctx. */
266         d = talloc_move(mem_ctx, &ptr);
267
268         /*
269          * Now we own d, prevent the cache from freeing it
270          * when we delete the entry.
271          */
272         talloc_set_destructor(d, share_mode_data_nofree_destructor);
273
274         /* Remove from the cache. We own it now. */
275         memcache_delete(NULL,
276                         SHARE_MODE_LOCK_CACHE,
277                         key);
278
279         /* And reset the destructor to none. */
280         talloc_set_destructor(d, NULL);
281
282         DEBUG(10,("fetched entry for file %s seq 0x%llu key %s\n",
283                 d->base_name,
284                 (unsigned long long)d->sequence_number,
285                 file_id_string(mem_ctx, &id)));
286
287         return d;
288 }
289
290 /*******************************************************************
291  Get all share mode entries for a dev/inode pair.
292 ********************************************************************/
293
294 static struct share_mode_data *parse_share_modes(TALLOC_CTX *mem_ctx,
295                                                 const TDB_DATA key,
296                                                 const TDB_DATA dbuf)
297 {
298         struct share_mode_data *d;
299         enum ndr_err_code ndr_err;
300         uint32_t i;
301         DATA_BLOB blob;
302
303         blob.data = dbuf.dptr;
304         blob.length = dbuf.dsize;
305
306         /* See if we already have a cached copy of this key. */
307         d = share_mode_memcache_fetch(mem_ctx, key, &blob);
308         if (d != NULL) {
309                 return d;
310         }
311
312         d = talloc(mem_ctx, struct share_mode_data);
313         if (d == NULL) {
314                 DEBUG(0, ("talloc failed\n"));
315                 goto fail;
316         }
317
318         ndr_err = ndr_pull_struct_blob_all(
319                 &blob, d, d, (ndr_pull_flags_fn_t)ndr_pull_share_mode_data);
320         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
321                 DEBUG(1, ("ndr_pull_share_mode_lock failed: %s\n",
322                           ndr_errstr(ndr_err)));
323                 goto fail;
324         }
325
326         /*
327          * Initialize the values that are [skip] or [ignore]
328          * in the idl. The NDR code does not initialize them.
329          */
330
331         for (i=0; i<d->num_share_modes; i++) {
332                 struct share_mode_entry *e = &d->share_modes[i];
333
334                 e->stale = false;
335                 e->lease = NULL;
336                 if (e->op_type != LEASE_OPLOCK) {
337                         continue;
338                 }
339                 if (e->lease_idx >= d->num_leases) {
340                         continue;
341                 }
342                 e->lease = &d->leases[e->lease_idx];
343         }
344         d->modified = false;
345         d->fresh = false;
346
347         if (DEBUGLEVEL >= 10) {
348                 DEBUG(10, ("parse_share_modes:\n"));
349                 NDR_PRINT_DEBUG(share_mode_data, d);
350         }
351
352         return d;
353 fail:
354         TALLOC_FREE(d);
355         return NULL;
356 }
357
358 /*******************************************************************
359  Create a storable data blob from a modified share_mode_data struct.
360 ********************************************************************/
361
362 static TDB_DATA unparse_share_modes(struct share_mode_data *d)
363 {
364         DATA_BLOB blob;
365         enum ndr_err_code ndr_err;
366
367         if (DEBUGLEVEL >= 10) {
368                 DEBUG(10, ("unparse_share_modes:\n"));
369                 NDR_PRINT_DEBUG(share_mode_data, d);
370         }
371
372         share_mode_memcache_delete(d);
373
374         /* Update the sequence number. */
375         d->sequence_number += 1;
376
377         remove_stale_share_mode_entries(d);
378
379         if (d->num_share_modes == 0) {
380                 DEBUG(10, ("No used share mode found\n"));
381                 return make_tdb_data(NULL, 0);
382         }
383
384         ndr_err = ndr_push_struct_blob(
385                 &blob, d, d, (ndr_push_flags_fn_t)ndr_push_share_mode_data);
386         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
387                 smb_panic("ndr_push_share_mode_lock failed");
388         }
389
390         return make_tdb_data(blob.data, blob.length);
391 }
392
393 /*******************************************************************
394  If modified, store the share_mode_data back into the database.
395 ********************************************************************/
396
397 static int share_mode_data_destructor(struct share_mode_data *d)
398 {
399         NTSTATUS status;
400         TDB_DATA data;
401
402         if (!d->modified) {
403                 return 0;
404         }
405
406         data = unparse_share_modes(d);
407
408         if (data.dptr == NULL) {
409                 if (!d->fresh) {
410                         /* There has been an entry before, delete it */
411
412                         status = dbwrap_record_delete(d->record);
413                         if (!NT_STATUS_IS_OK(status)) {
414                                 char *errmsg;
415
416                                 DEBUG(0, ("delete_rec returned %s\n",
417                                           nt_errstr(status)));
418
419                                 if (asprintf(&errmsg, "could not delete share "
420                                              "entry: %s\n",
421                                              nt_errstr(status)) == -1) {
422                                         smb_panic("could not delete share"
423                                                   "entry");
424                                 }
425                                 smb_panic(errmsg);
426                         }
427                 }
428                 /*
429                  * Nothing to store in cache - allow the normal
430                  * release of record lock and memory free.
431                  */
432                 return 0;
433         }
434
435         status = dbwrap_record_store(d->record, data, TDB_REPLACE);
436         if (!NT_STATUS_IS_OK(status)) {
437                 char *errmsg;
438
439                 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
440
441                 if (asprintf(&errmsg, "could not store share mode entry: %s",
442                              nt_errstr(status)) == -1) {
443                         smb_panic("could not store share mode entry");
444                 }
445                 smb_panic(errmsg);
446         }
447
448         /*
449          * Release the record lock before putting in the cache.
450          */
451         TALLOC_FREE(d->record);
452
453         /*
454          * Release the dptr as well before reparenting to NULL
455          * (in-memory cache) context.
456          */
457         TALLOC_FREE(data.dptr);
458         /*
459          * Reparent d into the in-memory cache so it can be reused if the
460          * sequence number matches. See parse_share_modes()
461          * for details.
462          */
463
464         share_mode_memcache_store(d);
465         return -1;
466 }
467
468 /*******************************************************************
469  Allocate a new share_mode_data struct, mark it unmodified.
470  fresh is set to note that currently there is no database entry.
471 ********************************************************************/
472
473 static struct share_mode_data *fresh_share_mode_lock(
474         TALLOC_CTX *mem_ctx, const char *servicepath,
475         const struct smb_filename *smb_fname,
476         const struct timespec *old_write_time)
477 {
478         struct share_mode_data *d;
479
480         if ((servicepath == NULL) || (smb_fname == NULL) ||
481             (old_write_time == NULL)) {
482                 return NULL;
483         }
484
485         d = talloc_zero(mem_ctx, struct share_mode_data);
486         if (d == NULL) {
487                 goto fail;
488         }
489         /* New record - new sequence number. */
490         generate_random_buffer((uint8_t *)&d->sequence_number, 8);
491
492         d->base_name = talloc_strdup(d, smb_fname->base_name);
493         if (d->base_name == NULL) {
494                 goto fail;
495         }
496         if (smb_fname->stream_name != NULL) {
497                 d->stream_name = talloc_strdup(d, smb_fname->stream_name);
498                 if (d->stream_name == NULL) {
499                         goto fail;
500                 }
501         }
502         d->servicepath = talloc_strdup(d, servicepath);
503         if (d->servicepath == NULL) {
504                 goto fail;
505         }
506         d->old_write_time = *old_write_time;
507         d->modified = false;
508         d->fresh = true;
509         return d;
510 fail:
511         DEBUG(0, ("talloc failed\n"));
512         TALLOC_FREE(d);
513         return NULL;
514 }
515
516 /*******************************************************************
517  Either fetch a share mode from the database, or allocate a fresh
518  one if the record doesn't exist.
519 ********************************************************************/
520
521 static struct share_mode_lock *get_share_mode_lock_internal(
522         TALLOC_CTX *mem_ctx, struct file_id id,
523         const char *servicepath, const struct smb_filename *smb_fname,
524         const struct timespec *old_write_time)
525 {
526         struct share_mode_lock *lck;
527         struct share_mode_data *d;
528         struct db_record *rec;
529         TDB_DATA key = locking_key(&id);
530         TDB_DATA value;
531
532         rec = dbwrap_fetch_locked(lock_db, mem_ctx, key);
533         if (rec == NULL) {
534                 DEBUG(3, ("Could not lock share entry\n"));
535                 return NULL;
536         }
537
538         value = dbwrap_record_get_value(rec);
539
540         if (value.dptr == NULL) {
541                 d = fresh_share_mode_lock(mem_ctx, servicepath, smb_fname,
542                                           old_write_time);
543         } else {
544                 d = parse_share_modes(mem_ctx, key, value);
545         }
546
547         if (d == NULL) {
548                 DEBUG(5, ("get_share_mode_lock_internal: "
549                         "Could not get share mode lock\n"));
550                 TALLOC_FREE(rec);
551                 return NULL;
552         }
553         d->id = id;
554         d->record = talloc_move(d, &rec);
555         talloc_set_destructor(d, share_mode_data_destructor);
556
557         lck = talloc(mem_ctx, struct share_mode_lock);
558         if (lck == NULL) {
559                 DEBUG(1, ("talloc failed\n"));
560                 TALLOC_FREE(d);
561                 return NULL;
562         }
563         lck->data = talloc_move(lck, &d);
564         return lck;
565 }
566
567 /*
568  * We can only ever have one share mode locked. Users of
569  * get_share_mode_lock never see this, it will be refcounted by
570  * talloc_reference.
571  */
572 static struct share_mode_lock *the_lock;
573 static struct file_id the_lock_id;
574
575 static int the_lock_destructor(struct share_mode_lock *l)
576 {
577         the_lock = NULL;
578         ZERO_STRUCT(the_lock_id);
579         return 0;
580 }
581
582 /*******************************************************************
583  Get a share_mode_lock, Reference counted to allow nested calls.
584 ********************************************************************/
585
586 struct share_mode_lock *get_share_mode_lock(
587         TALLOC_CTX *mem_ctx,
588         struct file_id id,
589         const char *servicepath,
590         const struct smb_filename *smb_fname,
591         const struct timespec *old_write_time)
592 {
593         struct share_mode_lock *lck;
594
595         lck = talloc(mem_ctx, struct share_mode_lock);
596         if (lck == NULL) {
597                 DEBUG(1, ("talloc failed\n"));
598                 return NULL;
599         }
600
601         if (the_lock == NULL) {
602                 the_lock = get_share_mode_lock_internal(
603                         lck, id, servicepath, smb_fname, old_write_time);
604                 if (the_lock == NULL) {
605                         goto fail;
606                 }
607                 talloc_set_destructor(the_lock, the_lock_destructor);
608                 the_lock_id = id;
609         } else {
610                 if (!file_id_equal(&the_lock_id, &id)) {
611                         DEBUG(1, ("Can not lock two share modes "
612                                   "simultaneously\n"));
613                         goto fail;
614                 }
615                 if (talloc_reference(lck, the_lock) == NULL) {
616                         DEBUG(1, ("talloc_reference failed\n"));
617                         goto fail;
618                 }
619         }
620         lck->data = the_lock->data;
621         return lck;
622 fail:
623         TALLOC_FREE(lck);
624         return NULL;
625 }
626
627 struct fetch_share_mode_unlocked_state {
628         TALLOC_CTX *mem_ctx;
629         struct share_mode_lock *lck;
630 };
631
632 static void fetch_share_mode_unlocked_parser(
633         TDB_DATA key, TDB_DATA data, void *private_data)
634 {
635         struct fetch_share_mode_unlocked_state *state = private_data;
636
637         if (data.dsize == 0) {
638                 /* Likely a ctdb tombstone record, ignore it */
639                 return;
640         }
641
642         state->lck = talloc(state->mem_ctx, struct share_mode_lock);
643         if (state->lck == NULL) {
644                 DEBUG(0, ("talloc failed\n"));
645                 return;
646         }
647
648         state->lck->data = parse_share_modes(state->lck, key, data);
649 }
650
651 /*******************************************************************
652  Get a share_mode_lock without locking the database or reference
653  counting. Used by smbstatus to display existing share modes.
654 ********************************************************************/
655
656 struct share_mode_lock *fetch_share_mode_unlocked(TALLOC_CTX *mem_ctx,
657                                                   struct file_id id)
658 {
659         struct fetch_share_mode_unlocked_state state = { .mem_ctx = mem_ctx };
660         TDB_DATA key = locking_key(&id);
661         NTSTATUS status;
662
663         status = dbwrap_parse_record(
664                 lock_db, key, fetch_share_mode_unlocked_parser, &state);
665         if (!NT_STATUS_IS_OK(status)) {
666                 return NULL;
667         }
668         return state.lck;
669 }
670
671 static void fetch_share_mode_done(struct tevent_req *subreq);
672
673 struct fetch_share_mode_state {
674         struct file_id id;
675         TDB_DATA key;
676         struct share_mode_lock *lck;
677         enum dbwrap_req_state req_state;
678 };
679
680 /**
681  * @brief Get a share_mode_lock without locking or refcounting
682  *
683  * This can be used in a clustered Samba environment where the async dbwrap
684  * request is sent over a socket to the local ctdbd. If the send queue is full
685  * and the caller was issuing multiple async dbwrap requests in a loop, the
686  * caller knows it's probably time to stop sending requests for now and try
687  * again later.
688  *
689  * @param[in]  mem_ctx The talloc memory context to use.
690  *
691  * @param[in]  ev      The event context to work on.
692  *
693  * @param[in]  id      The file id for the locking.tdb key
694  *
695  * @param[out] queued  This boolean out parameter tells the caller whether the
696  *                     async request is blocked in a full send queue:
697  *
698  *                     false := request is dispatched
699  *
700  *                     true  := send queue is full, request waiting to be
701  *                              dispatched
702  *
703  * @return             The new async request, NULL on error.
704  **/
705 struct tevent_req *fetch_share_mode_send(TALLOC_CTX *mem_ctx,
706                                          struct tevent_context *ev,
707                                          struct file_id id,
708                                          bool *queued)
709 {
710         struct tevent_req *req = NULL;
711         struct fetch_share_mode_state *state = NULL;
712         struct tevent_req *subreq = NULL;
713
714         *queued = false;
715
716         req = tevent_req_create(mem_ctx, &state,
717                                 struct fetch_share_mode_state);
718         if (req == NULL) {
719                 return NULL;
720         }
721
722         state->id = id;
723         state->key = locking_key(&state->id);
724         state->lck = talloc_zero(state, struct share_mode_lock);
725         if (tevent_req_nomem(state->lck, req)) {
726                 return tevent_req_post(req, ev);
727         }
728
729         subreq = dbwrap_parse_record_send(state,
730                                           ev,
731                                           lock_db,
732                                           state->key,
733                                           fetch_share_mode_unlocked_parser,
734                                           state->lck,
735                                           &state->req_state);
736         if (tevent_req_nomem(subreq, req)) {
737                 return tevent_req_post(req, ev);
738         }
739         tevent_req_set_callback(subreq, fetch_share_mode_done, req);
740
741         if (state->req_state < DBWRAP_REQ_DISPATCHED) {
742                 *queued = true;
743         }
744         return req;
745 }
746
747 static void fetch_share_mode_done(struct tevent_req *subreq)
748 {
749         struct tevent_req *req = tevent_req_callback_data(
750                 subreq, struct tevent_req);
751         NTSTATUS status;
752
753         status = dbwrap_parse_record_recv(subreq);
754         TALLOC_FREE(subreq);
755         if (tevent_req_nterror(req, status)) {
756                 return;
757         }
758
759         tevent_req_done(req);
760         return;
761 }
762
763 NTSTATUS fetch_share_mode_recv(struct tevent_req *req,
764                                TALLOC_CTX *mem_ctx,
765                                struct share_mode_lock **_lck)
766 {
767         struct fetch_share_mode_state *state = tevent_req_data(
768                 req, struct fetch_share_mode_state);
769         struct share_mode_lock *lck = NULL;
770
771         NTSTATUS status;
772
773         if (tevent_req_is_nterror(req, &status)) {
774                 tevent_req_received(req);
775                 return status;
776         }
777
778         if (state->lck->data == NULL) {
779                 tevent_req_received(req);
780                 return NT_STATUS_NOT_FOUND;
781         }
782
783         lck = talloc_move(mem_ctx, &state->lck);
784
785         if (DEBUGLEVEL >= 10) {
786                 DBG_DEBUG("share_mode_data:\n");
787                 NDR_PRINT_DEBUG(share_mode_data, lck->data);
788         }
789
790         *_lck = lck;
791         tevent_req_received(req);
792         return NT_STATUS_OK;
793 }
794
795 struct share_mode_forall_state {
796         int (*fn)(struct file_id fid, const struct share_mode_data *data,
797                   void *private_data);
798         void *private_data;
799 };
800
801 static int share_mode_traverse_fn(struct db_record *rec, void *_state)
802 {
803         struct share_mode_forall_state *state =
804                 (struct share_mode_forall_state *)_state;
805         uint32_t i;
806         TDB_DATA key;
807         TDB_DATA value;
808         DATA_BLOB blob;
809         enum ndr_err_code ndr_err;
810         struct share_mode_data *d;
811         struct file_id fid;
812         int ret;
813
814         key = dbwrap_record_get_key(rec);
815         value = dbwrap_record_get_value(rec);
816
817         /* Ensure this is a locking_key record. */
818         if (key.dsize != sizeof(fid)) {
819                 return 0;
820         }
821         memcpy(&fid, key.dptr, sizeof(fid));
822
823         d = talloc(talloc_tos(), struct share_mode_data);
824         if (d == NULL) {
825                 return 0;
826         }
827
828         blob.data = value.dptr;
829         blob.length = value.dsize;
830
831         ndr_err = ndr_pull_struct_blob_all(
832                 &blob, d, d, (ndr_pull_flags_fn_t)ndr_pull_share_mode_data);
833         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
834                 DEBUG(1, ("ndr_pull_share_mode_lock failed\n"));
835                 return 0;
836         }
837
838         for (i=0; i<d->num_share_modes; i++) {
839                 struct share_mode_entry *entry = &d->share_modes[i];
840                 entry->stale = false; /* [skip] in idl */
841                 entry->lease = &d->leases[entry->lease_idx];
842         }
843
844         if (DEBUGLEVEL > 10) {
845                 DEBUG(11, ("parse_share_modes:\n"));
846                 NDR_PRINT_DEBUG(share_mode_data, d);
847         }
848
849         ret = state->fn(fid, d, state->private_data);
850
851         TALLOC_FREE(d);
852         return ret;
853 }
854
855 int share_mode_forall(int (*fn)(struct file_id fid,
856                                 const struct share_mode_data *data,
857                                 void *private_data),
858                       void *private_data)
859 {
860         struct share_mode_forall_state state = {
861                 .fn = fn,
862                 .private_data = private_data
863         };
864         NTSTATUS status;
865         int count;
866
867         if (lock_db == NULL) {
868                 return 0;
869         }
870
871         status = dbwrap_traverse_read(lock_db, share_mode_traverse_fn,
872                                       &state, &count);
873         if (!NT_STATUS_IS_OK(status)) {
874                 return -1;
875         }
876
877         return count;
878 }
879
880 struct share_entry_forall_state {
881         int (*fn)(struct file_id fid,
882                   const struct share_mode_data *data,
883                   const struct share_mode_entry *entry,
884                   void *private_data);
885         void *private_data;
886 };
887
888 static int share_entry_traverse_fn(struct file_id fid,
889                                    const struct share_mode_data *data,
890                                    void *private_data)
891 {
892         struct share_entry_forall_state *state = private_data;
893         uint32_t i;
894
895         for (i=0; i<data->num_share_modes; i++) {
896                 int ret;
897
898                 ret = state->fn(fid,
899                                 data,
900                                 &data->share_modes[i],
901                                 state->private_data);
902                 if (ret != 0) {
903                         return ret;
904                 }
905         }
906
907         return 0;
908 }
909
910 /*******************************************************************
911  Call the specified function on each entry under management by the
912  share mode system.
913 ********************************************************************/
914
915 int share_entry_forall(int (*fn)(struct file_id fid,
916                                  const struct share_mode_data *data,
917                                  const struct share_mode_entry *entry,
918                                  void *private_data),
919                       void *private_data)
920 {
921         struct share_entry_forall_state state = {
922                 .fn = fn, .private_data = private_data };
923
924         return share_mode_forall(share_entry_traverse_fn, &state);
925 }
926
927 bool share_mode_cleanup_disconnected(struct file_id fid,
928                                      uint64_t open_persistent_id)
929 {
930         bool ret = false;
931         TALLOC_CTX *frame = talloc_stackframe();
932         unsigned n;
933         struct share_mode_data *data;
934         struct share_mode_lock *lck;
935         bool ok;
936
937         lck = get_existing_share_mode_lock(frame, fid);
938         if (lck == NULL) {
939                 DEBUG(5, ("share_mode_cleanup_disconnected: "
940                           "Could not fetch share mode entry for %s\n",
941                           file_id_string(frame, &fid)));
942                 goto done;
943         }
944         data = lck->data;
945
946         for (n=0; n < data->num_share_modes; n++) {
947                 struct share_mode_entry *entry = &data->share_modes[n];
948
949                 if (!server_id_is_disconnected(&entry->pid)) {
950                         struct server_id_buf tmp;
951                         DEBUG(5, ("share_mode_cleanup_disconnected: "
952                                   "file (file-id='%s', servicepath='%s', "
953                                   "base_name='%s%s%s') "
954                                   "is used by server %s ==> do not cleanup\n",
955                                   file_id_string(frame, &fid),
956                                   data->servicepath,
957                                   data->base_name,
958                                   (data->stream_name == NULL)
959                                   ? "" : "', stream_name='",
960                                   (data->stream_name == NULL)
961                                   ? "" : data->stream_name,
962                                   server_id_str_buf(entry->pid, &tmp)));
963                         goto done;
964                 }
965                 if (open_persistent_id != entry->share_file_id) {
966                         DEBUG(5, ("share_mode_cleanup_disconnected: "
967                                   "entry for file "
968                                   "(file-id='%s', servicepath='%s', "
969                                   "base_name='%s%s%s') "
970                                   "has share_file_id %llu but expected %llu"
971                                   "==> do not cleanup\n",
972                                   file_id_string(frame, &fid),
973                                   data->servicepath,
974                                   data->base_name,
975                                   (data->stream_name == NULL)
976                                   ? "" : "', stream_name='",
977                                   (data->stream_name == NULL)
978                                   ? "" : data->stream_name,
979                                   (unsigned long long)entry->share_file_id,
980                                   (unsigned long long)open_persistent_id));
981                         goto done;
982                 }
983         }
984
985         for (n=0; n < data->num_leases; n++) {
986                 struct share_mode_lease *l = &data->leases[n];
987                 NTSTATUS status;
988
989                 status = leases_db_del(&l->client_guid, &l->lease_key, &fid);
990
991                 DEBUG(10, ("%s: leases_db_del returned %s\n", __func__,
992                            nt_errstr(status)));
993         }
994
995         ok = brl_cleanup_disconnected(fid, open_persistent_id);
996         if (!ok) {
997                 DEBUG(10, ("share_mode_cleanup_disconnected: "
998                            "failed to clean up byte range locks associated "
999                            "with file (file-id='%s', servicepath='%s', "
1000                            "base_name='%s%s%s') and open_persistent_id %llu "
1001                            "==> do not cleanup\n",
1002                            file_id_string(frame, &fid),
1003                            data->servicepath,
1004                            data->base_name,
1005                            (data->stream_name == NULL)
1006                            ? "" : "', stream_name='",
1007                            (data->stream_name == NULL)
1008                            ? "" : data->stream_name,
1009                            (unsigned long long)open_persistent_id));
1010                 goto done;
1011         }
1012
1013         DEBUG(10, ("share_mode_cleanup_disconnected: "
1014                    "cleaning up %u entries for file "
1015                    "(file-id='%s', servicepath='%s', "
1016                    "base_name='%s%s%s') "
1017                    "from open_persistent_id %llu\n",
1018                    data->num_share_modes,
1019                    file_id_string(frame, &fid),
1020                    data->servicepath,
1021                    data->base_name,
1022                    (data->stream_name == NULL)
1023                    ? "" : "', stream_name='",
1024                    (data->stream_name == NULL)
1025                    ? "" : data->stream_name,
1026                    (unsigned long long)open_persistent_id));
1027
1028         data->num_share_modes = 0;
1029         data->num_leases = 0;
1030         data->modified = true;
1031
1032         ret = true;
1033 done:
1034         talloc_free(frame);
1035         return ret;
1036 }