s3:locking: cleanup leases_db from share_mode_cleanup_disconnected()
[obnox/samba/samba-obnox.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
52 #undef DBGC_CLASS
53 #define DBGC_CLASS DBGC_LOCKING
54
55 #define NO_LOCKING_COUNT (-1)
56
57 /* the locking database handle */
58 static struct db_context *lock_db;
59
60 static bool locking_init_internal(bool read_only)
61 {
62         char *db_path;
63
64         brl_init(read_only);
65
66         if (lock_db)
67                 return True;
68
69         db_path = lock_path("locking.tdb");
70         if (db_path == NULL) {
71                 return false;
72         }
73
74         lock_db = db_open(NULL, db_path,
75                           SMB_OPEN_DATABASE_TDB_HASH_SIZE,
76                           TDB_DEFAULT|TDB_VOLATILE|TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH,
77                           read_only?O_RDONLY:O_RDWR|O_CREAT, 0644,
78                           DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
79         TALLOC_FREE(db_path);
80         if (!lock_db) {
81                 DEBUG(0,("ERROR: Failed to initialise locking database\n"));
82                 return False;
83         }
84
85         if (!posix_locking_init(read_only))
86                 return False;
87
88         dbwrap_watch_db(lock_db, server_messaging_context());
89
90         return True;
91 }
92
93 bool locking_init(void)
94 {
95         return locking_init_internal(false);
96 }
97
98 bool locking_init_readonly(void)
99 {
100         return locking_init_internal(true);
101 }
102
103 /*******************************************************************
104  Deinitialize the share_mode management.
105 ******************************************************************/
106
107 bool locking_end(void)
108 {
109         brl_shutdown();
110         TALLOC_FREE(lock_db);
111         return true;
112 }
113
114 /*******************************************************************
115  Form a static locking key for a dev/inode pair.
116 ******************************************************************/
117
118 static TDB_DATA locking_key(const struct file_id *id)
119 {
120         return make_tdb_data((const uint8_t *)id, sizeof(*id));
121 }
122
123 /*******************************************************************
124  Get all share mode entries for a dev/inode pair.
125 ********************************************************************/
126
127 static struct share_mode_data *parse_share_modes(TALLOC_CTX *mem_ctx,
128                                                  const TDB_DATA dbuf)
129 {
130         struct share_mode_data *d;
131         enum ndr_err_code ndr_err;
132         uint32_t i;
133         DATA_BLOB blob;
134
135         d = talloc(mem_ctx, struct share_mode_data);
136         if (d == NULL) {
137                 DEBUG(0, ("talloc failed\n"));
138                 goto fail;
139         }
140
141         blob.data = dbuf.dptr;
142         blob.length = dbuf.dsize;
143
144         ndr_err = ndr_pull_struct_blob_all(
145                 &blob, d, d, (ndr_pull_flags_fn_t)ndr_pull_share_mode_data);
146         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
147                 DEBUG(1, ("ndr_pull_share_mode_lock failed: %s\n",
148                           ndr_errstr(ndr_err)));
149                 goto fail;
150         }
151
152         /*
153          * Initialize the values that are [skip] in the idl. The NDR code does
154          * not initialize them.
155          */
156
157         for (i=0; i<d->num_share_modes; i++) {
158                 struct share_mode_entry *e = &d->share_modes[i];
159
160                 e->stale = false;
161                 e->lease = NULL;
162                 if (e->op_type != LEASE_OPLOCK) {
163                         continue;
164                 }
165                 if (e->lease_idx >= d->num_leases) {
166                         continue;
167                 }
168                 e->lease = &d->leases[e->lease_idx];
169         }
170         d->modified = false;
171         d->fresh = false;
172
173         if (DEBUGLEVEL >= 10) {
174                 DEBUG(10, ("parse_share_modes:\n"));
175                 NDR_PRINT_DEBUG(share_mode_data, d);
176         }
177
178         return d;
179 fail:
180         TALLOC_FREE(d);
181         return NULL;
182 }
183
184 /*******************************************************************
185  Create a storable data blob from a modified share_mode_data struct.
186 ********************************************************************/
187
188 static TDB_DATA unparse_share_modes(struct share_mode_data *d)
189 {
190         DATA_BLOB blob;
191         enum ndr_err_code ndr_err;
192
193         if (DEBUGLEVEL >= 10) {
194                 DEBUG(10, ("unparse_share_modes:\n"));
195                 NDR_PRINT_DEBUG(share_mode_data, d);
196         }
197
198         remove_stale_share_mode_entries(d);
199
200         if (d->num_share_modes == 0) {
201                 DEBUG(10, ("No used share mode found\n"));
202                 return make_tdb_data(NULL, 0);
203         }
204
205         ndr_err = ndr_push_struct_blob(
206                 &blob, d, d, (ndr_push_flags_fn_t)ndr_push_share_mode_data);
207         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
208                 smb_panic("ndr_push_share_mode_lock failed");
209         }
210
211         return make_tdb_data(blob.data, blob.length);
212 }
213
214 /*******************************************************************
215  If modified, store the share_mode_data back into the database.
216 ********************************************************************/
217
218 static int share_mode_data_destructor(struct share_mode_data *d)
219 {
220         NTSTATUS status;
221         TDB_DATA data;
222
223         if (!d->modified) {
224                 return 0;
225         }
226
227         data = unparse_share_modes(d);
228
229         if (data.dptr == NULL) {
230                 if (!d->fresh) {
231                         /* There has been an entry before, delete it */
232
233                         status = dbwrap_record_delete(d->record);
234                         if (!NT_STATUS_IS_OK(status)) {
235                                 char *errmsg;
236
237                                 DEBUG(0, ("delete_rec returned %s\n",
238                                           nt_errstr(status)));
239
240                                 if (asprintf(&errmsg, "could not delete share "
241                                              "entry: %s\n",
242                                              nt_errstr(status)) == -1) {
243                                         smb_panic("could not delete share"
244                                                   "entry");
245                                 }
246                                 smb_panic(errmsg);
247                         }
248                 }
249                 goto done;
250         }
251
252         status = dbwrap_record_store(d->record, data, TDB_REPLACE);
253         if (!NT_STATUS_IS_OK(status)) {
254                 char *errmsg;
255
256                 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
257
258                 if (asprintf(&errmsg, "could not store share mode entry: %s",
259                              nt_errstr(status)) == -1) {
260                         smb_panic("could not store share mode entry");
261                 }
262                 smb_panic(errmsg);
263         }
264
265  done:
266
267         return 0;
268 }
269
270 /*******************************************************************
271  Allocate a new share_mode_data struct, mark it unmodified.
272  fresh is set to note that currently there is no database entry.
273 ********************************************************************/
274
275 static struct share_mode_data *fresh_share_mode_lock(
276         TALLOC_CTX *mem_ctx, const char *servicepath,
277         const struct smb_filename *smb_fname,
278         const struct timespec *old_write_time)
279 {
280         struct share_mode_data *d;
281
282         if ((servicepath == NULL) || (smb_fname == NULL) ||
283             (old_write_time == NULL)) {
284                 return NULL;
285         }
286
287         d = talloc_zero(mem_ctx, struct share_mode_data);
288         if (d == NULL) {
289                 goto fail;
290         }
291         d->base_name = talloc_strdup(d, smb_fname->base_name);
292         if (d->base_name == NULL) {
293                 goto fail;
294         }
295         if (smb_fname->stream_name != NULL) {
296                 d->stream_name = talloc_strdup(d, smb_fname->stream_name);
297                 if (d->stream_name == NULL) {
298                         goto fail;
299                 }
300         }
301         d->servicepath = talloc_strdup(d, servicepath);
302         if (d->servicepath == NULL) {
303                 goto fail;
304         }
305         d->old_write_time = *old_write_time;
306         d->modified = false;
307         d->fresh = true;
308         return d;
309 fail:
310         DEBUG(0, ("talloc failed\n"));
311         TALLOC_FREE(d);
312         return NULL;
313 }
314
315 /*******************************************************************
316  Either fetch a share mode from the database, or allocate a fresh
317  one if the record doesn't exist.
318 ********************************************************************/
319
320 static struct share_mode_lock *get_share_mode_lock_internal(
321         TALLOC_CTX *mem_ctx, struct file_id id,
322         const char *servicepath, const struct smb_filename *smb_fname,
323         const struct timespec *old_write_time)
324 {
325         struct share_mode_lock *lck;
326         struct share_mode_data *d;
327         struct db_record *rec;
328         TDB_DATA key = locking_key(&id);
329         TDB_DATA value;
330
331         rec = dbwrap_fetch_locked(lock_db, mem_ctx, key);
332         if (rec == NULL) {
333                 DEBUG(3, ("Could not lock share entry\n"));
334                 return NULL;
335         }
336
337         value = dbwrap_record_get_value(rec);
338
339         if (value.dptr == NULL) {
340                 d = fresh_share_mode_lock(mem_ctx, servicepath, smb_fname,
341                                           old_write_time);
342         } else {
343                 d = parse_share_modes(mem_ctx, value);
344         }
345
346         if (d == NULL) {
347                 DEBUG(5, ("get_share_mode_lock_internal: "
348                         "Could not get share mode lock\n"));
349                 TALLOC_FREE(rec);
350                 return NULL;
351         }
352         d->record = talloc_move(d, &rec);
353         talloc_set_destructor(d, share_mode_data_destructor);
354
355         lck = talloc(mem_ctx, struct share_mode_lock);
356         if (lck == NULL) {
357                 DEBUG(1, ("talloc failed\n"));
358                 TALLOC_FREE(d);
359                 return NULL;
360         }
361         lck->data = talloc_move(lck, &d);
362         return lck;
363 }
364
365 /*
366  * We can only ever have one share mode locked. Users of
367  * get_share_mode_lock never see this, it will be refcounted by
368  * talloc_reference.
369  */
370 static struct share_mode_lock *the_lock;
371 static struct file_id the_lock_id;
372
373 static int the_lock_destructor(struct share_mode_lock *l)
374 {
375         the_lock = NULL;
376         ZERO_STRUCT(the_lock_id);
377         return 0;
378 }
379
380 /*******************************************************************
381  Get a share_mode_lock, Reference counted to allow nested calls.
382 ********************************************************************/
383
384 struct share_mode_lock *get_share_mode_lock(
385         TALLOC_CTX *mem_ctx,
386         struct file_id id,
387         const char *servicepath,
388         const struct smb_filename *smb_fname,
389         const struct timespec *old_write_time)
390 {
391         struct share_mode_lock *lck;
392
393         lck = talloc(mem_ctx, struct share_mode_lock);
394         if (lck == NULL) {
395                 DEBUG(1, ("talloc failed\n"));
396                 return NULL;
397         }
398
399         if (the_lock == NULL) {
400                 the_lock = get_share_mode_lock_internal(
401                         lck, id, servicepath, smb_fname, old_write_time);
402                 if (the_lock == NULL) {
403                         goto fail;
404                 }
405                 talloc_set_destructor(the_lock, the_lock_destructor);
406                 the_lock_id = id;
407         } else {
408                 if (!file_id_equal(&the_lock_id, &id)) {
409                         DEBUG(1, ("Can not lock two share modes "
410                                   "simultaneously\n"));
411                         goto fail;
412                 }
413                 if (talloc_reference(lck, the_lock) == NULL) {
414                         DEBUG(1, ("talloc_reference failed\n"));
415                         goto fail;
416                 }
417         }
418         lck->data = the_lock->data;
419         return lck;
420 fail:
421         TALLOC_FREE(lck);
422         return NULL;
423 }
424
425 static void fetch_share_mode_unlocked_parser(
426         TDB_DATA key, TDB_DATA data, void *private_data)
427 {
428         struct share_mode_lock *lck = talloc_get_type_abort(
429                 private_data, struct share_mode_lock);
430
431         lck->data = parse_share_modes(lck, data);
432 }
433
434 /*******************************************************************
435  Get a share_mode_lock without locking the database or reference
436  counting. Used by smbstatus to display existing share modes.
437 ********************************************************************/
438
439 struct share_mode_lock *fetch_share_mode_unlocked(TALLOC_CTX *mem_ctx,
440                                                   struct file_id id)
441 {
442         struct share_mode_lock *lck;
443         TDB_DATA key = locking_key(&id);
444         NTSTATUS status;
445
446         lck = talloc(mem_ctx, struct share_mode_lock);
447         if (lck == NULL) {
448                 DEBUG(0, ("talloc failed\n"));
449                 return NULL;
450         }
451         status = dbwrap_parse_record(
452                 lock_db, key, fetch_share_mode_unlocked_parser, lck);
453         if (!NT_STATUS_IS_OK(status) ||
454             (lck->data == NULL)) {
455                 TALLOC_FREE(lck);
456                 return NULL;
457         }
458         return lck;
459 }
460
461 struct share_mode_forall_state {
462         int (*fn)(struct file_id fid, const struct share_mode_data *data,
463                   void *private_data);
464         void *private_data;
465 };
466
467 static int share_mode_traverse_fn(struct db_record *rec, void *_state)
468 {
469         struct share_mode_forall_state *state =
470                 (struct share_mode_forall_state *)_state;
471         uint32_t i;
472         TDB_DATA key;
473         TDB_DATA value;
474         DATA_BLOB blob;
475         enum ndr_err_code ndr_err;
476         struct share_mode_data *d;
477         struct file_id fid;
478         int ret;
479
480         key = dbwrap_record_get_key(rec);
481         value = dbwrap_record_get_value(rec);
482
483         /* Ensure this is a locking_key record. */
484         if (key.dsize != sizeof(fid)) {
485                 return 0;
486         }
487         memcpy(&fid, key.dptr, sizeof(fid));
488
489         d = talloc(talloc_tos(), struct share_mode_data);
490         if (d == NULL) {
491                 return 0;
492         }
493
494         blob.data = value.dptr;
495         blob.length = value.dsize;
496
497         ndr_err = ndr_pull_struct_blob_all(
498                 &blob, d, d, (ndr_pull_flags_fn_t)ndr_pull_share_mode_data);
499         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
500                 DEBUG(1, ("ndr_pull_share_mode_lock failed\n"));
501                 return 0;
502         }
503         if (DEBUGLEVEL > 10) {
504                 DEBUG(11, ("parse_share_modes:\n"));
505                 NDR_PRINT_DEBUG(share_mode_data, d);
506         }
507         for (i=0; i<d->num_share_modes; i++) {
508                 d->share_modes[i].stale = false; /* [skip] in idl */
509         }
510
511         ret = state->fn(fid, d, state->private_data);
512
513         TALLOC_FREE(d);
514         return ret;
515 }
516
517 int share_mode_forall(int (*fn)(struct file_id fid,
518                                 const struct share_mode_data *data,
519                                 void *private_data),
520                       void *private_data)
521 {
522         struct share_mode_forall_state state = {
523                 .fn = fn,
524                 .private_data = private_data
525         };
526         NTSTATUS status;
527         int count;
528
529         if (lock_db == NULL) {
530                 return 0;
531         }
532
533         status = dbwrap_traverse_read(lock_db, share_mode_traverse_fn,
534                                       &state, &count);
535         if (!NT_STATUS_IS_OK(status)) {
536                 return -1;
537         }
538
539         return count;
540 }
541
542 struct share_entry_forall_state {
543         int (*fn)(const struct share_mode_entry *e,
544                   const char *service_path, const char *base_name,
545                   void *private_data);
546         void *private_data;
547 };
548
549 static int share_entry_traverse_fn(struct file_id fid,
550                                    const struct share_mode_data *data,
551                                    void *private_data)
552 {
553         struct share_entry_forall_state *state = private_data;
554         uint32_t i;
555
556         for (i=0; i<data->num_share_modes; i++) {
557                 int ret;
558
559                 ret = state->fn(&data->share_modes[i],
560                                 data->servicepath, data->base_name,
561                                 state->private_data);
562                 if (ret != 0) {
563                         return ret;
564                 }
565         }
566
567         return 0;
568 }
569
570 /*******************************************************************
571  Call the specified function on each entry under management by the
572  share mode system.
573 ********************************************************************/
574
575 int share_entry_forall(int (*fn)(const struct share_mode_entry *,
576                                  const char *, const char *, void *),
577                        void *private_data)
578 {
579         struct share_entry_forall_state state = {
580                 .fn = fn, .private_data = private_data };
581
582         return share_mode_forall(share_entry_traverse_fn, &state);
583 }
584
585 bool share_mode_cleanup_disconnected(struct file_id fid,
586                                      uint64_t open_persistent_id)
587 {
588         bool ret = false;
589         TALLOC_CTX *frame = talloc_stackframe();
590         unsigned n;
591         struct share_mode_data *data;
592         struct share_mode_lock *lck;
593         bool ok;
594
595         lck = get_existing_share_mode_lock(frame, fid);
596         if (lck == NULL) {
597                 DEBUG(5, ("share_mode_cleanup_disconnected: "
598                           "Could not fetch share mode entry for %s\n",
599                           file_id_string(frame, &fid)));
600                 goto done;
601         }
602         data = lck->data;
603
604         for (n=0; n < data->num_share_modes; n++) {
605                 struct share_mode_entry *entry = &data->share_modes[n];
606
607                 if (!server_id_is_disconnected(&entry->pid)) {
608                         DEBUG(5, ("share_mode_cleanup_disconnected: "
609                                   "file (file-id='%s', servicepath='%s', "
610                                   "base_name='%s%s%s') "
611                                   "is used by server %s ==> do not cleanup\n",
612                                   file_id_string(frame, &fid),
613                                   data->servicepath,
614                                   data->base_name,
615                                   (data->stream_name == NULL)
616                                   ? "" : "', stream_name='",
617                                   (data->stream_name == NULL)
618                                   ? "" : data->stream_name,
619                                   server_id_str(frame, &entry->pid)));
620                         goto done;
621                 }
622                 if (open_persistent_id != entry->share_file_id) {
623                         DEBUG(5, ("share_mode_cleanup_disconnected: "
624                                   "entry for file "
625                                   "(file-id='%s', servicepath='%s', "
626                                   "base_name='%s%s%s') "
627                                   "has share_file_id %llu but expected %llu"
628                                   "==> do not cleanup\n",
629                                   file_id_string(frame, &fid),
630                                   data->servicepath,
631                                   data->base_name,
632                                   (data->stream_name == NULL)
633                                   ? "" : "', stream_name='",
634                                   (data->stream_name == NULL)
635                                   ? "" : data->stream_name,
636                                   (unsigned long long)entry->share_file_id,
637                                   (unsigned long long)open_persistent_id));
638                         goto done;
639                 }
640         }
641
642         for (n=0; n < data->num_leases; n++) {
643                 struct share_mode_lease *l = &data->leases[n];
644                 NTSTATUS status;
645
646                 status = leases_db_del(&l->client_guid, &l->lease_key, &fid);
647
648                 DEBUG(10, ("%s: leases_db_del returned %s\n", __func__,
649                            nt_errstr(status)));
650         }
651
652         ok = brl_cleanup_disconnected(fid, open_persistent_id);
653         if (!ok) {
654                 DEBUG(10, ("share_mode_cleanup_disconnected: "
655                            "failed to clean up byte range locks associated "
656                            "with file (file-id='%s', servicepath='%s', "
657                            "base_name='%s%s%s') and open_persistent_id %llu "
658                            "==> do not cleanup\n",
659                            file_id_string(frame, &fid),
660                            data->servicepath,
661                            data->base_name,
662                            (data->stream_name == NULL)
663                            ? "" : "', stream_name='",
664                            (data->stream_name == NULL)
665                            ? "" : data->stream_name,
666                            (unsigned long long)open_persistent_id));
667                 goto done;
668         }
669
670         DEBUG(10, ("share_mode_cleanup_disconnected: "
671                    "cleaning up %u entries for file "
672                    "(file-id='%s', servicepath='%s', "
673                    "base_name='%s%s%s') "
674                    "from open_persistent_id %llu\n",
675                    data->num_share_modes,
676                    file_id_string(frame, &fid),
677                    data->servicepath,
678                    data->base_name,
679                    (data->stream_name == NULL)
680                    ? "" : "', stream_name='",
681                    (data->stream_name == NULL)
682                    ? "" : data->stream_name,
683                    (unsigned long long)open_persistent_id));
684
685         data->num_share_modes = 0;
686         data->num_leases = 0;
687         data->modified = true;
688
689         ret = true;
690 done:
691         talloc_free(frame);
692         return ret;
693 }