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