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