smbd: Use dbwrap_record_watch_send for defer_open
[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                           lp_open_files_db_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);
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         DATA_BLOB blob;
125
126         d = talloc(mem_ctx, struct share_mode_data);
127         if (d == NULL) {
128                 DEBUG(0, ("talloc failed\n"));
129                 goto fail;
130         }
131
132         blob.data = dbuf.dptr;
133         blob.length = dbuf.dsize;
134
135         ndr_err = ndr_pull_struct_blob(
136                 &blob, d, d, (ndr_pull_flags_fn_t)ndr_pull_share_mode_data);
137         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
138                 DEBUG(1, ("ndr_pull_share_mode_lock failed: %s\n",
139                           ndr_errstr(ndr_err)));
140                 goto fail;
141         }
142
143         d->modified = false;
144         d->fresh = false;
145
146         if (DEBUGLEVEL >= 10) {
147                 DEBUG(10, ("parse_share_modes:\n"));
148                 NDR_PRINT_DEBUG(share_mode_data, d);
149         }
150
151         return d;
152 fail:
153         TALLOC_FREE(d);
154         return NULL;
155 }
156
157 /*******************************************************************
158  Create a storable data blob from a modified share_mode_data struct.
159 ********************************************************************/
160
161 static TDB_DATA unparse_share_modes(struct share_mode_data *d)
162 {
163         DATA_BLOB blob;
164         enum ndr_err_code ndr_err;
165
166         if (DEBUGLEVEL >= 10) {
167                 DEBUG(10, ("unparse_share_modes:\n"));
168                 NDR_PRINT_DEBUG(share_mode_data, d);
169         }
170
171         if (d->num_share_modes == 0) {
172                 DEBUG(10, ("No used share mode found\n"));
173                 return make_tdb_data(NULL, 0);
174         }
175
176         ndr_err = ndr_push_struct_blob(
177                 &blob, d, d, (ndr_push_flags_fn_t)ndr_push_share_mode_data);
178         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
179                 smb_panic("ndr_push_share_mode_lock failed");
180         }
181
182         return make_tdb_data(blob.data, blob.length);
183 }
184
185 /*******************************************************************
186  If modified, store the share_mode_data back into the database.
187 ********************************************************************/
188
189 static int share_mode_data_destructor(struct share_mode_data *d)
190 {
191         NTSTATUS status;
192         TDB_DATA data;
193
194         if (!d->modified) {
195                 return 0;
196         }
197
198         data = unparse_share_modes(d);
199
200         if (data.dptr == NULL) {
201                 if (!d->fresh) {
202                         /* There has been an entry before, delete it */
203
204                         status = dbwrap_record_delete(d->record);
205                         if (!NT_STATUS_IS_OK(status)) {
206                                 char *errmsg;
207
208                                 DEBUG(0, ("delete_rec returned %s\n",
209                                           nt_errstr(status)));
210
211                                 if (asprintf(&errmsg, "could not delete share "
212                                              "entry: %s\n",
213                                              nt_errstr(status)) == -1) {
214                                         smb_panic("could not delete share"
215                                                   "entry");
216                                 }
217                                 smb_panic(errmsg);
218                         }
219                 }
220                 goto done;
221         }
222
223         status = dbwrap_record_store(d->record, data, TDB_REPLACE);
224         if (!NT_STATUS_IS_OK(status)) {
225                 char *errmsg;
226
227                 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
228
229                 if (asprintf(&errmsg, "could not store share mode entry: %s",
230                              nt_errstr(status)) == -1) {
231                         smb_panic("could not store share mode entry");
232                 }
233                 smb_panic(errmsg);
234         }
235
236  done:
237
238         return 0;
239 }
240
241 /*******************************************************************
242  Allocate a new share_mode_data struct, mark it unmodified.
243  fresh is set to note that currently there is no database entry.
244 ********************************************************************/
245
246 static struct share_mode_data *fresh_share_mode_lock(
247         TALLOC_CTX *mem_ctx, const char *servicepath,
248         const struct smb_filename *smb_fname,
249         const struct timespec *old_write_time)
250 {
251         struct share_mode_data *d;
252
253         if ((servicepath == NULL) || (smb_fname == NULL) ||
254             (old_write_time == NULL)) {
255                 return NULL;
256         }
257
258         d = talloc_zero(mem_ctx, struct share_mode_data);
259         if (d == NULL) {
260                 goto fail;
261         }
262         d->base_name = talloc_strdup(d, smb_fname->base_name);
263         if (d->base_name == NULL) {
264                 goto fail;
265         }
266         if (smb_fname->stream_name != NULL) {
267                 d->stream_name = talloc_strdup(d, smb_fname->stream_name);
268                 if (d->stream_name == NULL) {
269                         goto fail;
270                 }
271         }
272         d->servicepath = talloc_strdup(d, servicepath);
273         if (d->servicepath == NULL) {
274                 goto fail;
275         }
276         d->old_write_time = *old_write_time;
277         d->modified = false;
278         d->fresh = true;
279         return d;
280 fail:
281         DEBUG(0, ("talloc failed\n"));
282         TALLOC_FREE(d);
283         return NULL;
284 }
285
286 /*******************************************************************
287  Either fetch a share mode from the database, or allocate a fresh
288  one if the record doesn't exist.
289 ********************************************************************/
290
291 static struct share_mode_lock *get_share_mode_lock_internal(
292         TALLOC_CTX *mem_ctx, struct file_id id,
293         const char *servicepath, const struct smb_filename *smb_fname,
294         const struct timespec *old_write_time)
295 {
296         struct share_mode_lock *lck;
297         struct share_mode_data *d;
298         struct db_record *rec;
299         TDB_DATA key = locking_key(&id);
300         TDB_DATA value;
301
302         rec = dbwrap_fetch_locked(lock_db, mem_ctx, key);
303         if (rec == NULL) {
304                 DEBUG(3, ("Could not lock share entry\n"));
305                 return NULL;
306         }
307
308         value = dbwrap_record_get_value(rec);
309
310         if (value.dptr == NULL) {
311                 d = fresh_share_mode_lock(mem_ctx, servicepath, smb_fname,
312                                           old_write_time);
313         } else {
314                 d = parse_share_modes(mem_ctx, value);
315         }
316
317         if (d == NULL) {
318                 DEBUG(5, ("get_share_mode_lock_internal: "
319                         "Could not get share mode lock\n"));
320                 TALLOC_FREE(rec);
321                 return NULL;
322         }
323         d->id = id;
324         d->record = talloc_move(d, &rec);
325         talloc_set_destructor(d, share_mode_data_destructor);
326
327         lck = talloc(mem_ctx, struct share_mode_lock);
328         if (lck == NULL) {
329                 DEBUG(1, ("talloc failed\n"));
330                 TALLOC_FREE(d);
331                 return NULL;
332         }
333         lck->data = talloc_move(lck, &d);
334         return lck;
335 }
336
337 /*
338  * We can only ever have one share mode locked. Users of
339  * get_share_mode_lock never see this, it will be refcounted by
340  * talloc_reference.
341  */
342 static struct share_mode_lock *the_lock;
343
344 static int the_lock_destructor(struct share_mode_lock *l)
345 {
346         the_lock = NULL;
347         return 0;
348 }
349
350 /*******************************************************************
351  Get a share_mode_lock, Reference counted to allow nested calls.
352 ********************************************************************/
353
354 struct share_mode_lock *get_share_mode_lock(
355         TALLOC_CTX *mem_ctx,
356         struct file_id id,
357         const char *servicepath,
358         const struct smb_filename *smb_fname,
359         const struct timespec *old_write_time)
360 {
361         TALLOC_CTX *frame = talloc_stackframe();
362
363         struct share_mode_lock *lck;
364
365         if (the_lock == NULL) {
366                 the_lock = get_share_mode_lock_internal(
367                         frame, id, servicepath, smb_fname, old_write_time);
368                 if (the_lock == NULL) {
369                         goto fail;
370                 }
371                 talloc_set_destructor(the_lock, the_lock_destructor);
372         }
373         if (!file_id_equal(&the_lock->data->id, &id)) {
374                 DEBUG(1, ("Can not lock two share modes simultaneously\n"));
375                 goto fail;
376         }
377         lck = talloc(mem_ctx, struct share_mode_lock);
378         if (lck == NULL) {
379                 DEBUG(1, ("talloc failed\n"));
380                 goto fail;
381         }
382         if (talloc_reference(lck, the_lock) == NULL) {
383                 DEBUG(1, ("talloc_reference failed\n"));
384                 goto fail;
385         }
386         lck->data = the_lock->data;
387         TALLOC_FREE(frame);
388         return lck;
389 fail:
390         TALLOC_FREE(frame);
391         return NULL;
392 }
393
394 static void fetch_share_mode_unlocked_parser(
395         TDB_DATA key, TDB_DATA data, void *private_data)
396 {
397         struct share_mode_lock *lck = talloc_get_type_abort(
398                 private_data, struct share_mode_lock);
399
400         lck->data = parse_share_modes(lck, data);
401 }
402
403 /*******************************************************************
404  Get a share_mode_lock without locking the database or reference
405  counting. Used by smbstatus to display existing share modes.
406 ********************************************************************/
407
408 struct share_mode_lock *fetch_share_mode_unlocked(TALLOC_CTX *mem_ctx,
409                                                   struct file_id id)
410 {
411         struct share_mode_lock *lck;
412         TDB_DATA key = locking_key(&id);
413         NTSTATUS status;
414
415         lck = talloc(mem_ctx, struct share_mode_lock);
416         if (lck == NULL) {
417                 DEBUG(0, ("talloc failed\n"));
418                 return NULL;
419         }
420         status = dbwrap_parse_record(
421                 lock_db, key, fetch_share_mode_unlocked_parser, lck);
422         if (!NT_STATUS_IS_OK(status) ||
423             (lck->data == NULL)) {
424                 TALLOC_FREE(lck);
425                 return NULL;
426         }
427         return lck;
428 }
429
430 struct forall_state {
431         void (*fn)(const struct share_mode_entry *entry,
432                    const char *sharepath,
433                    const char *fname,
434                    void *private_data);
435         void *private_data;
436 };
437
438 static int traverse_fn(struct db_record *rec, void *_state)
439 {
440         struct forall_state *state = (struct forall_state *)_state;
441         uint32_t i;
442         TDB_DATA key;
443         TDB_DATA value;
444         DATA_BLOB blob;
445         enum ndr_err_code ndr_err;
446         struct share_mode_data *d;
447
448         key = dbwrap_record_get_key(rec);
449         value = dbwrap_record_get_value(rec);
450
451         /* Ensure this is a locking_key record. */
452         if (key.dsize != sizeof(struct file_id))
453                 return 0;
454
455         d = talloc(talloc_tos(), struct share_mode_data);
456         if (d == NULL) {
457                 return 0;
458         }
459
460         blob.data = value.dptr;
461         blob.length = value.dsize;
462
463         ndr_err = ndr_pull_struct_blob(
464                 &blob, d, d, (ndr_pull_flags_fn_t)ndr_pull_share_mode_data);
465         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
466                 DEBUG(1, ("ndr_pull_share_mode_lock failed\n"));
467                 return 0;
468         }
469         if (DEBUGLEVEL > 10) {
470                 DEBUG(11, ("parse_share_modes:\n"));
471                 NDR_PRINT_DEBUG(share_mode_data, d);
472         }
473         for (i=0; i<d->num_share_modes; i++) {
474                 state->fn(&d->share_modes[i],
475                           d->servicepath, d->base_name,
476                           state->private_data);
477         }
478         TALLOC_FREE(d);
479
480         return 0;
481 }
482
483 /*******************************************************************
484  Call the specified function on each entry under management by the
485  share mode system.
486 ********************************************************************/
487
488 int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *,
489                                  const char *, void *),
490                       void *private_data)
491 {
492         struct forall_state state;
493         NTSTATUS status;
494         int count;
495
496         if (lock_db == NULL)
497                 return 0;
498
499         state.fn = fn;
500         state.private_data = private_data;
501
502         status = dbwrap_traverse_read(lock_db, traverse_fn, (void *)&state,
503                                       &count);
504
505         if (!NT_STATUS_IS_OK(status)) {
506                 return -1;
507         } else {
508                 return count;
509         }
510 }
511
512 bool share_mode_cleanup_disconnected(struct file_id fid,
513                                      uint64_t open_persistent_id)
514 {
515         bool ret = false;
516         TALLOC_CTX *frame = talloc_stackframe();
517         unsigned n;
518         struct share_mode_data *data;
519         struct share_mode_lock *lck;
520         bool ok;
521
522         lck = get_existing_share_mode_lock(frame, fid);
523         if (lck == NULL) {
524                 DEBUG(5, ("share_mode_cleanup_disconnected: "
525                           "Could not fetch share mode entry for %s\n",
526                           file_id_string(frame, &fid)));
527                 goto done;
528         }
529         data = lck->data;
530
531         for (n=0; n < data->num_share_modes; n++) {
532                 struct share_mode_entry *entry = &data->share_modes[n];
533
534                 if (!server_id_is_disconnected(&entry->pid)) {
535                         DEBUG(5, ("share_mode_cleanup_disconnected: "
536                                   "file (file-id='%s', servicepath='%s', "
537                                   "base_name='%s%s%s') "
538                                   "is used by server %s ==> do not cleanup\n",
539                                   file_id_string(frame, &fid),
540                                   data->servicepath,
541                                   data->base_name,
542                                   (data->stream_name == NULL)
543                                   ? "" : "', stream_name='",
544                                   (data->stream_name == NULL)
545                                   ? "" : data->stream_name,
546                                   server_id_str(frame, &entry->pid)));
547                         goto done;
548                 }
549                 if (open_persistent_id != entry->share_file_id) {
550                         DEBUG(5, ("share_mode_cleanup_disconnected: "
551                                   "entry for file "
552                                   "(file-id='%s', servicepath='%s', "
553                                   "base_name='%s%s%s') "
554                                   "has share_file_id %llu but expected %llu"
555                                   "==> do not cleanup\n",
556                                   file_id_string(frame, &fid),
557                                   data->servicepath,
558                                   data->base_name,
559                                   (data->stream_name == NULL)
560                                   ? "" : "', stream_name='",
561                                   (data->stream_name == NULL)
562                                   ? "" : data->stream_name,
563                                   (unsigned long long)entry->share_file_id,
564                                   (unsigned long long)open_persistent_id));
565                         goto done;
566                 }
567         }
568
569         ok = brl_cleanup_disconnected(fid, open_persistent_id);
570         if (!ok) {
571                 DEBUG(10, ("share_mode_cleanup_disconnected: "
572                            "failed to clean up byte range locks associated "
573                            "with file (file-id='%s', servicepath='%s', "
574                            "base_name='%s%s%s') and open_persistent_id %llu "
575                            "==> do not cleanup\n",
576                            file_id_string(frame, &fid),
577                            data->servicepath,
578                            data->base_name,
579                            (data->stream_name == NULL)
580                            ? "" : "', stream_name='",
581                            (data->stream_name == NULL)
582                            ? "" : data->stream_name,
583                            (unsigned long long)open_persistent_id));
584                 goto done;
585         }
586
587         DEBUG(10, ("share_mode_cleanup_disconnected: "
588                    "cleaning up %u entries for file "
589                    "(file-id='%s', servicepath='%s', "
590                    "base_name='%s%s%s') "
591                    "from open_persistent_id %llu\n",
592                    data->num_share_modes,
593                    file_id_string(frame, &fid),
594                    data->servicepath,
595                    data->base_name,
596                    (data->stream_name == NULL)
597                    ? "" : "', stream_name='",
598                    (data->stream_name == NULL)
599                    ? "" : data->stream_name,
600                    (unsigned long long)open_persistent_id));
601
602         data->num_share_modes = 0;
603         data->modified = true;
604
605         ret = true;
606 done:
607         talloc_free(frame);
608         return ret;
609 }