04ff247c6d32d7f0f2ab35cbdd8b94e63dc0760d
[metze/samba/wip.git] / source3 / locking / share_mode_lock.c
1 /*
2    Unix SMB/CIFS implementation.
3    Locking functions
4    Copyright (C) Andrew Tridgell 1992-2000
5    Copyright (C) Jeremy Allison 1992-2006
6    Copyright (C) Volker Lendecke 2005
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21    Revision History:
22
23    12 aug 96: Erik.Devriendt@te6.siemens.be
24    added support for shared memory implementation of share mode locking
25
26    May 1997. Jeremy Allison (jallison@whistle.com). Modified share mode
27    locking to deal with multiple share modes per open file.
28
29    September 1997. Jeremy Allison (jallison@whistle.com). Added oplock
30    support.
31
32    rewritten completely to use new tdb code. Tridge, Dec '99
33
34    Added POSIX locking support. Jeremy Allison (jeremy@valinux.com), Apr. 2000.
35    Added Unix Extensions POSIX locking support. Jeremy Allison Mar 2006.
36 */
37
38 #include "includes.h"
39 #include "system/filesys.h"
40 #include "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
50 #undef DBGC_CLASS
51 #define DBGC_CLASS DBGC_LOCKING
52
53 #define NO_LOCKING_COUNT (-1)
54
55 /* the locking database handle */
56 static struct db_context *lock_db;
57
58 static bool locking_init_internal(bool read_only)
59 {
60         brl_init(read_only);
61
62         if (lock_db)
63                 return True;
64
65         lock_db = db_open(NULL, lock_path("locking.tdb"),
66                           lp_open_files_db_hash_size(),
67                           TDB_DEFAULT|TDB_VOLATILE|TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH,
68                           read_only?O_RDONLY:O_RDWR|O_CREAT, 0644,
69                           DBWRAP_LOCK_ORDER_1);
70
71         if (!lock_db) {
72                 DEBUG(0,("ERROR: Failed to initialise locking database\n"));
73                 return False;
74         }
75
76         if (!posix_locking_init(read_only))
77                 return False;
78
79         return True;
80 }
81
82 bool locking_init(void)
83 {
84         return locking_init_internal(false);
85 }
86
87 bool locking_init_readonly(void)
88 {
89         return locking_init_internal(true);
90 }
91
92 /*******************************************************************
93  Deinitialize the share_mode management.
94 ******************************************************************/
95
96 bool locking_end(void)
97 {
98         brl_shutdown();
99         TALLOC_FREE(lock_db);
100         return true;
101 }
102
103 /*******************************************************************
104  Form a static locking key for a dev/inode pair.
105 ******************************************************************/
106
107 static TDB_DATA locking_key(const struct file_id *id)
108 {
109         return make_tdb_data((const uint8_t *)id, sizeof(*id));
110 }
111
112 /*******************************************************************
113  Get all share mode entries for a dev/inode pair.
114 ********************************************************************/
115
116 static struct share_mode_data *parse_share_modes(TALLOC_CTX *mem_ctx,
117                                                  const TDB_DATA dbuf)
118 {
119         struct share_mode_data *d;
120         enum ndr_err_code ndr_err;
121         DATA_BLOB blob;
122
123         d = talloc(mem_ctx, struct share_mode_data);
124         if (d == NULL) {
125                 DEBUG(0, ("talloc failed\n"));
126                 goto fail;
127         }
128
129         blob.data = dbuf.dptr;
130         blob.length = dbuf.dsize;
131
132         ndr_err = ndr_pull_struct_blob(
133                 &blob, d, d, (ndr_pull_flags_fn_t)ndr_pull_share_mode_data);
134         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
135                 DEBUG(1, ("ndr_pull_share_mode_lock failed: %s\n",
136                           ndr_errstr(ndr_err)));
137                 goto fail;
138         }
139
140         d->modified = false;
141         d->fresh = false;
142
143         if (DEBUGLEVEL >= 10) {
144                 DEBUG(10, ("parse_share_modes:\n"));
145                 NDR_PRINT_DEBUG(share_mode_data, d);
146         }
147
148         return d;
149 fail:
150         TALLOC_FREE(d);
151         return NULL;
152 }
153
154 /*******************************************************************
155  Create a storable data blob from a modified share_mode_data struct.
156 ********************************************************************/
157
158 static TDB_DATA unparse_share_modes(struct share_mode_data *d)
159 {
160         DATA_BLOB blob;
161         enum ndr_err_code ndr_err;
162
163         if (DEBUGLEVEL >= 10) {
164                 DEBUG(10, ("unparse_share_modes:\n"));
165                 NDR_PRINT_DEBUG(share_mode_data, d);
166         }
167
168         if (d->num_share_modes == 0) {
169                 DEBUG(10, ("No used share mode found\n"));
170                 return make_tdb_data(NULL, 0);
171         }
172
173         ndr_err = ndr_push_struct_blob(
174                 &blob, d, d, (ndr_push_flags_fn_t)ndr_push_share_mode_data);
175         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
176                 smb_panic("ndr_push_share_mode_lock failed");
177         }
178
179         return make_tdb_data(blob.data, blob.length);
180 }
181
182 /*******************************************************************
183  If modified, store the share_mode_data back into the database.
184 ********************************************************************/
185
186 static int share_mode_data_destructor(struct share_mode_data *d)
187 {
188         NTSTATUS status;
189         TDB_DATA data;
190
191         if (!d->modified) {
192                 return 0;
193         }
194
195         data = unparse_share_modes(d);
196
197         if (data.dptr == NULL) {
198                 if (!d->fresh) {
199                         /* There has been an entry before, delete it */
200
201                         status = dbwrap_record_delete(d->record);
202                         if (!NT_STATUS_IS_OK(status)) {
203                                 char *errmsg;
204
205                                 DEBUG(0, ("delete_rec returned %s\n",
206                                           nt_errstr(status)));
207
208                                 if (asprintf(&errmsg, "could not delete share "
209                                              "entry: %s\n",
210                                              nt_errstr(status)) == -1) {
211                                         smb_panic("could not delete share"
212                                                   "entry");
213                                 }
214                                 smb_panic(errmsg);
215                         }
216                 }
217                 goto done;
218         }
219
220         status = dbwrap_record_store(d->record, data, TDB_REPLACE);
221         if (!NT_STATUS_IS_OK(status)) {
222                 char *errmsg;
223
224                 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
225
226                 if (asprintf(&errmsg, "could not store share mode entry: %s",
227                              nt_errstr(status)) == -1) {
228                         smb_panic("could not store share mode entry");
229                 }
230                 smb_panic(errmsg);
231         }
232
233  done:
234
235         return 0;
236 }
237
238 /*******************************************************************
239  Allocate a new share_mode_data struct, mark it unmodified.
240  fresh is set to note that currently there is no database entry.
241 ********************************************************************/
242
243 static struct share_mode_data *fresh_share_mode_lock(
244         TALLOC_CTX *mem_ctx, const char *servicepath,
245         const struct smb_filename *smb_fname,
246         const struct timespec *old_write_time)
247 {
248         struct share_mode_data *d;
249
250         if ((servicepath == NULL) || (smb_fname == NULL) ||
251             (old_write_time == NULL)) {
252                 return NULL;
253         }
254
255         d = talloc_zero(mem_ctx, struct share_mode_data);
256         if (d == NULL) {
257                 goto fail;
258         }
259         d->base_name = talloc_strdup(d, smb_fname->base_name);
260         if (d->base_name == NULL) {
261                 goto fail;
262         }
263         if (smb_fname->stream_name != NULL) {
264                 d->stream_name = talloc_strdup(d, smb_fname->stream_name);
265                 if (d->stream_name == NULL) {
266                         goto fail;
267                 }
268         }
269         d->servicepath = talloc_strdup(d, servicepath);
270         if (d->servicepath == NULL) {
271                 goto fail;
272         }
273         d->old_write_time = *old_write_time;
274         d->modified = false;
275         d->fresh = true;
276         return d;
277 fail:
278         DEBUG(0, ("talloc failed\n"));
279         TALLOC_FREE(d);
280         return NULL;
281 }
282
283 /*******************************************************************
284  Either fetch a share mode from the database, or allocate a fresh
285  one if the record doesn't exist.
286 ********************************************************************/
287
288 static struct share_mode_lock *get_share_mode_lock_internal(
289         TALLOC_CTX *mem_ctx, struct file_id id,
290         const char *servicepath, const struct smb_filename *smb_fname,
291         const struct timespec *old_write_time)
292 {
293         struct share_mode_lock *lck;
294         struct share_mode_data *d;
295         struct db_record *rec;
296         TDB_DATA key = locking_key(&id);
297         TDB_DATA value;
298
299         rec = dbwrap_fetch_locked(lock_db, mem_ctx, key);
300         if (rec == NULL) {
301                 DEBUG(3, ("Could not lock share entry\n"));
302                 return NULL;
303         }
304
305         value = dbwrap_record_get_value(rec);
306
307         if (value.dptr == NULL) {
308                 d = fresh_share_mode_lock(mem_ctx, servicepath, smb_fname,
309                                           old_write_time);
310         } else {
311                 d = parse_share_modes(mem_ctx, value);
312         }
313
314         if (d == NULL) {
315                 DEBUG(5, ("get_share_mode_lock_internal: "
316                         "Could not get share mode lock\n"));
317                 TALLOC_FREE(rec);
318                 return NULL;
319         }
320         d->id = id;
321         d->record = talloc_move(d, &rec);
322         talloc_set_destructor(d, share_mode_data_destructor);
323
324         lck = talloc(mem_ctx, struct share_mode_lock);
325         if (lck == NULL) {
326                 DEBUG(1, ("talloc failed\n"));
327                 TALLOC_FREE(d);
328                 return NULL;
329         }
330         lck->data = talloc_move(lck, &d);
331         return lck;
332 }
333
334 /*
335  * We can only ever have one share mode locked. Users of
336  * get_share_mode_lock never see this, it will be refcounted by
337  * talloc_reference.
338  */
339 static struct share_mode_lock *the_lock;
340
341 static int the_lock_destructor(struct share_mode_lock *l)
342 {
343         the_lock = NULL;
344         return 0;
345 }
346
347 /*******************************************************************
348  Get a share_mode_lock, Reference counted to allow nested calls.
349 ********************************************************************/
350
351 struct share_mode_lock *get_share_mode_lock(
352         TALLOC_CTX *mem_ctx,
353         struct file_id id,
354         const char *servicepath,
355         const struct smb_filename *smb_fname,
356         const struct timespec *old_write_time)
357 {
358         TALLOC_CTX *frame = talloc_stackframe();
359
360         struct share_mode_lock *lck;
361
362         if (the_lock == NULL) {
363                 the_lock = get_share_mode_lock_internal(
364                         frame, id, servicepath, smb_fname, old_write_time);
365                 if (the_lock == NULL) {
366                         goto fail;
367                 }
368                 talloc_set_destructor(the_lock, the_lock_destructor);
369         }
370         if (!file_id_equal(&the_lock->data->id, &id)) {
371                 DEBUG(1, ("Can not lock two share modes simultaneously\n"));
372                 goto fail;
373         }
374         lck = talloc(mem_ctx, struct share_mode_lock);
375         if (lck == NULL) {
376                 DEBUG(1, ("talloc failed\n"));
377                 goto fail;
378         }
379         if (talloc_reference(lck, the_lock) == NULL) {
380                 DEBUG(1, ("talloc_reference failed\n"));
381                 goto fail;
382         }
383         lck->data = the_lock->data;
384         TALLOC_FREE(frame);
385         return lck;
386 fail:
387         TALLOC_FREE(frame);
388         return NULL;
389 }
390
391 static void fetch_share_mode_unlocked_parser(
392         TDB_DATA key, TDB_DATA data, void *private_data)
393 {
394         struct share_mode_lock *lck = talloc_get_type_abort(
395                 private_data, struct share_mode_lock);
396
397         lck->data = parse_share_modes(lck, data);
398 }
399
400 /*******************************************************************
401  Get a share_mode_lock without locking the database or reference
402  counting. Used by smbstatus to display existing share modes.
403 ********************************************************************/
404
405 struct share_mode_lock *fetch_share_mode_unlocked(TALLOC_CTX *mem_ctx,
406                                                   struct file_id id)
407 {
408         struct share_mode_lock *lck;
409         TDB_DATA key = locking_key(&id);
410         NTSTATUS status;
411
412         lck = talloc(mem_ctx, struct share_mode_lock);
413         if (lck == NULL) {
414                 DEBUG(0, ("talloc failed\n"));
415                 return NULL;
416         }
417         status = dbwrap_parse_record(
418                 lock_db, key, fetch_share_mode_unlocked_parser, lck);
419         if (!NT_STATUS_IS_OK(status) ||
420             (lck->data == NULL)) {
421                 TALLOC_FREE(lck);
422                 return NULL;
423         }
424         return lck;
425 }
426
427 struct forall_state {
428         void (*fn)(const struct share_mode_entry *entry,
429                    const char *sharepath,
430                    const char *fname,
431                    void *private_data);
432         void *private_data;
433 };
434
435 static int traverse_fn(struct db_record *rec, void *_state)
436 {
437         struct forall_state *state = (struct forall_state *)_state;
438         uint32_t i;
439         TDB_DATA key;
440         TDB_DATA value;
441         DATA_BLOB blob;
442         enum ndr_err_code ndr_err;
443         struct share_mode_data *d;
444
445         key = dbwrap_record_get_key(rec);
446         value = dbwrap_record_get_value(rec);
447
448         /* Ensure this is a locking_key record. */
449         if (key.dsize != sizeof(struct file_id))
450                 return 0;
451
452         d = talloc(talloc_tos(), struct share_mode_data);
453         if (d == NULL) {
454                 return 0;
455         }
456
457         blob.data = value.dptr;
458         blob.length = value.dsize;
459
460         ndr_err = ndr_pull_struct_blob(
461                 &blob, d, d, (ndr_pull_flags_fn_t)ndr_pull_share_mode_data);
462         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
463                 DEBUG(1, ("ndr_pull_share_mode_lock failed\n"));
464                 return 0;
465         }
466         for (i=0; i<d->num_share_modes; i++) {
467                 state->fn(&d->share_modes[i],
468                           d->servicepath, d->base_name,
469                           state->private_data);
470         }
471         TALLOC_FREE(d);
472
473         return 0;
474 }
475
476 /*******************************************************************
477  Call the specified function on each entry under management by the
478  share mode system.
479 ********************************************************************/
480
481 int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *,
482                                  const char *, void *),
483                       void *private_data)
484 {
485         struct forall_state state;
486         NTSTATUS status;
487         int count;
488
489         if (lock_db == NULL)
490                 return 0;
491
492         state.fn = fn;
493         state.private_data = private_data;
494
495         status = dbwrap_traverse_read(lock_db, traverse_fn, (void *)&state,
496                                       &count);
497
498         if (!NT_STATUS_IS_OK(status)) {
499                 return -1;
500         } else {
501                 return count;
502         }
503 }
504
505 bool share_mode_cleanup_disconnected(struct file_id fid,
506                                      uint64_t open_persistent_id)
507 {
508         bool ret = false;
509         TALLOC_CTX *frame = talloc_stackframe();
510         unsigned n;
511         struct share_mode_data *data;
512         struct share_mode_lock *lck;
513         bool ok;
514
515         lck = get_existing_share_mode_lock(frame, fid);
516         if (lck == NULL) {
517                 DEBUG(5, ("share_mode_cleanup_disconnected: "
518                           "Could not fetch share mode entry for %s\n",
519                           file_id_string(frame, &fid)));
520                 goto done;
521         }
522         data = lck->data;
523
524         for (n=0; n < data->num_share_modes; n++) {
525                 struct share_mode_entry *entry = &data->share_modes[n];
526
527                 if (!server_id_is_disconnected(&entry->pid)) {
528                         DEBUG(5, ("share_mode_cleanup_disconnected: "
529                                   "file (file-id='%s', servicepath='%s', "
530                                   "base_name='%s%s%s') "
531                                   "is used by server %s ==> do not cleanup\n",
532                                   file_id_string(frame, &fid),
533                                   data->servicepath,
534                                   data->base_name,
535                                   (data->stream_name == NULL)
536                                   ? "" : "', stream_name='",
537                                   (data->stream_name == NULL)
538                                   ? "" : data->stream_name,
539                                   server_id_str(frame, &entry->pid)));
540                         goto done;
541                 }
542                 if (open_persistent_id != entry->share_file_id) {
543                         DEBUG(5, ("share_mode_cleanup_disconnected: "
544                                   "entry for file "
545                                   "(file-id='%s', servicepath='%s', "
546                                   "base_name='%s%s%s') "
547                                   "has share_file_id %llu but expected %llu"
548                                   "==> do not cleanup\n",
549                                   file_id_string(frame, &fid),
550                                   data->servicepath,
551                                   data->base_name,
552                                   (data->stream_name == NULL)
553                                   ? "" : "', stream_name='",
554                                   (data->stream_name == NULL)
555                                   ? "" : data->stream_name,
556                                   (unsigned long long)entry->share_file_id,
557                                   (unsigned long long)open_persistent_id));
558                         goto done;
559                 }
560         }
561
562         ok = brl_cleanup_disconnected(fid, open_persistent_id);
563         if (!ok) {
564                 DEBUG(10, ("share_mode_cleanup_disconnected: "
565                            "failed to clean up byte range locks associated "
566                            "with file (file-id='%s', servicepath='%s', "
567                            "base_name='%s%s%s') and open_persistent_id %llu "
568                            "==> do not cleanup\n",
569                            file_id_string(frame, &fid),
570                            data->servicepath,
571                            data->base_name,
572                            (data->stream_name == NULL)
573                            ? "" : "', stream_name='",
574                            (data->stream_name == NULL)
575                            ? "" : data->stream_name,
576                            (unsigned long long)open_persistent_id));
577                 goto done;
578         }
579
580         DEBUG(10, ("share_mode_cleanup_disconnected: "
581                    "cleaning up %u entries for file "
582                    "(file-id='%s', servicepath='%s', "
583                    "base_name='%s%s%s') "
584                    "from open_persistent_id %llu\n",
585                    data->num_share_modes,
586                    file_id_string(frame, &fid),
587                    data->servicepath,
588                    data->base_name,
589                    (data->stream_name == NULL)
590                    ? "" : "', stream_name='",
591                    (data->stream_name == NULL)
592                    ? "" : data->stream_name,
593                    (unsigned long long)open_persistent_id));
594
595         data->num_share_modes = 0;
596         data->modified = true;
597
598         ret = true;
599 done:
600         talloc_free(frame);
601         return ret;
602 }