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