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