Add comments to all functions (to help me understand it better).
[kai/samba.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
70         if (!lock_db) {
71                 DEBUG(0,("ERROR: Failed to initialise locking database\n"));
72                 return False;
73         }
74
75         if (!posix_locking_init(read_only))
76                 return False;
77
78         return True;
79 }
80
81 bool locking_init(void)
82 {
83         return locking_init_internal(false);
84 }
85
86 bool locking_init_readonly(void)
87 {
88         return locking_init_internal(true);
89 }
90
91 /*******************************************************************
92  Deinitialize the share_mode management.
93 ******************************************************************/
94
95 bool locking_end(void)
96 {
97         brl_shutdown();
98         TALLOC_FREE(lock_db);
99         return true;
100 }
101
102 /*******************************************************************
103  Form a static locking key for a dev/inode pair.
104 ******************************************************************/
105
106 static TDB_DATA locking_key(const struct file_id *id, struct file_id *tmp)
107 {
108         *tmp = *id;
109         return make_tdb_data((const uint8_t *)tmp, sizeof(*tmp));
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         int i;
121         struct server_id *pids;
122         bool *pid_exists;
123         enum ndr_err_code ndr_err;
124         DATA_BLOB blob;
125
126         d = talloc_zero(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\n"));
139                 goto fail;
140         }
141
142         d->modified = false;
143         d->fresh = false;
144
145         if (DEBUGLEVEL >= 10) {
146                 DEBUG(10, ("parse_share_modes:\n"));
147                 NDR_PRINT_DEBUG(share_mode_data, d);
148         }
149
150         /*
151          * Ensure that each entry has a real process attached.
152          */
153
154         pids = talloc_array(talloc_tos(), struct server_id,
155                             d->num_share_modes);
156         if (pids == NULL) {
157                 DEBUG(0, ("talloc failed\n"));
158                 goto fail;
159         }
160         pid_exists = talloc_array(talloc_tos(), bool, d->num_share_modes);
161         if (pid_exists == NULL) {
162                 DEBUG(0, ("talloc failed\n"));
163                 goto fail;
164         }
165
166         for (i=0; i<d->num_share_modes; i++) {
167                 pids[i] = d->share_modes[i].pid;
168         }
169         if (!serverids_exist(pids, d->num_share_modes, pid_exists)) {
170                 DEBUG(0, ("serverid_exists failed\n"));
171                 goto fail;
172         }
173
174         i = 0;
175         while (i < d->num_share_modes) {
176                 struct share_mode_entry *e = &d->share_modes[i];
177                 if (!pid_exists[i]) {
178                         *e = d->share_modes[d->num_share_modes-1];
179                         d->num_share_modes -= 1;
180                         d->modified = True;
181                         continue;
182                 }
183                 i += 1;
184         }
185         TALLOC_FREE(pid_exists);
186         TALLOC_FREE(pids);
187         return d;
188 fail:
189         TALLOC_FREE(d);
190         return NULL;
191 }
192
193 /*******************************************************************
194  Create a storable data blob from a modified share_mode_data struct.
195 ********************************************************************/
196
197 static TDB_DATA unparse_share_modes(struct share_mode_data *d)
198 {
199         DATA_BLOB blob;
200         enum ndr_err_code ndr_err;
201
202         if (DEBUGLEVEL >= 10) {
203                 DEBUG(10, ("unparse_share_modes:\n"));
204                 NDR_PRINT_DEBUG(share_mode_data, d);
205         }
206
207         if (d->num_share_modes == 0) {
208                 DEBUG(10, ("No used share mode found\n"));
209                 return make_tdb_data(NULL, 0);
210         }
211
212         ndr_err = ndr_push_struct_blob(
213                 &blob, d, d, (ndr_push_flags_fn_t)ndr_push_share_mode_data);
214         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
215                 smb_panic("ndr_push_share_mode_lock failed");
216         }
217
218         return make_tdb_data(blob.data, blob.length);
219 }
220
221 /*******************************************************************
222  If modified, store the share_mode_data back into the database.
223 ********************************************************************/
224
225 static int share_mode_data_destructor(struct share_mode_data *d)
226 {
227         NTSTATUS status;
228         TDB_DATA data;
229
230         if (!d->modified) {
231                 return 0;
232         }
233
234         data = unparse_share_modes(d);
235
236         if (data.dptr == NULL) {
237                 if (!d->fresh) {
238                         /* There has been an entry before, delete it */
239
240                         status = dbwrap_record_delete(d->record);
241                         if (!NT_STATUS_IS_OK(status)) {
242                                 char *errmsg;
243
244                                 DEBUG(0, ("delete_rec returned %s\n",
245                                           nt_errstr(status)));
246
247                                 if (asprintf(&errmsg, "could not delete share "
248                                              "entry: %s\n",
249                                              nt_errstr(status)) == -1) {
250                                         smb_panic("could not delete share"
251                                                   "entry");
252                                 }
253                                 smb_panic(errmsg);
254                         }
255                 }
256                 goto done;
257         }
258
259         status = dbwrap_record_store(d->record, data, TDB_REPLACE);
260         if (!NT_STATUS_IS_OK(status)) {
261                 char *errmsg;
262
263                 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
264
265                 if (asprintf(&errmsg, "could not store share mode entry: %s",
266                              nt_errstr(status)) == -1) {
267                         smb_panic("could not store share mode entry");
268                 }
269                 smb_panic(errmsg);
270         }
271
272  done:
273
274         return 0;
275 }
276
277 /*******************************************************************
278  Allocate a new share_mode_data struct, mark it unmodified.
279  fresh is set to note that currently there is no database entry.
280 ********************************************************************/
281
282 static struct share_mode_data *fresh_share_mode_lock(
283         TALLOC_CTX *mem_ctx, const char *servicepath,
284         const struct smb_filename *smb_fname,
285         const struct timespec *old_write_time)
286 {
287         struct share_mode_data *d;
288
289         if ((servicepath == NULL) || (smb_fname == NULL) ||
290             (old_write_time == NULL)) {
291                 return NULL;
292         }
293
294         d = talloc_zero(mem_ctx, struct share_mode_data);
295         if (d == NULL) {
296                 goto fail;
297         }
298         d->base_name = talloc_strdup(d, smb_fname->base_name);
299         if (d->base_name == NULL) {
300                 goto fail;
301         }
302         if (smb_fname->stream_name != NULL) {
303                 d->stream_name = talloc_strdup(d, smb_fname->stream_name);
304                 if (d->stream_name == NULL) {
305                         goto fail;
306                 }
307         }
308         d->servicepath = talloc_strdup(d, servicepath);
309         if (d->servicepath == NULL) {
310                 goto fail;
311         }
312         d->old_write_time = *old_write_time;
313         d->modified = false;
314         d->fresh = true;
315         return d;
316 fail:
317         DEBUG(0, ("talloc failed\n"));
318         TALLOC_FREE(d);
319         return NULL;
320 }
321
322 /*******************************************************************
323  Either fetch a share mode from the database, or allocate a fresh
324  one if the record doesn't exist.
325 ********************************************************************/
326
327 static struct share_mode_lock *get_share_mode_lock_internal(
328         TALLOC_CTX *mem_ctx, const struct file_id id,
329         const char *servicepath, const struct smb_filename *smb_fname,
330         const struct timespec *old_write_time)
331 {
332         struct share_mode_lock *lck;
333         struct share_mode_data *d;
334         struct file_id tmp;
335         struct db_record *rec;
336         TDB_DATA key = locking_key(&id, &tmp);
337         TDB_DATA value;
338
339         rec = dbwrap_fetch_locked(lock_db, mem_ctx, key);
340         if (rec == NULL) {
341                 DEBUG(3, ("Could not lock share entry\n"));
342                 return NULL;
343         }
344
345         value = dbwrap_record_get_value(rec);
346
347         if (value.dptr == NULL) {
348                 d = fresh_share_mode_lock(mem_ctx, servicepath, smb_fname,
349                                           old_write_time);
350         } else {
351                 d = parse_share_modes(mem_ctx, value);
352         }
353
354         if (d == NULL) {
355                 DEBUG(1, ("Could not get share mode lock\n"));
356                 TALLOC_FREE(rec);
357                 return NULL;
358         }
359         d->id = id;
360         d->record = talloc_move(d, &rec);
361         talloc_set_destructor(d, share_mode_data_destructor);
362
363         lck = talloc(mem_ctx, struct share_mode_lock);
364         if (lck == NULL) {
365                 DEBUG(1, ("talloc failed\n"));
366                 TALLOC_FREE(d);
367                 return NULL;
368         }
369         lck->data = talloc_move(lck, &d);
370         return lck;
371 }
372
373 /*
374  * We can only ever have one share mode locked. Users of
375  * get_share_mode_lock never see this, it will be refcounted by
376  * talloc_reference.
377  */
378 static struct share_mode_lock *the_lock;
379
380 static int the_lock_destructor(struct share_mode_lock *l)
381 {
382         the_lock = NULL;
383         return 0;
384 }
385
386 /*******************************************************************
387  Get a share_mode_lock, Reference counted to allow nexted calls.
388 ********************************************************************/
389
390 struct share_mode_lock *get_share_mode_lock_fresh(
391         TALLOC_CTX *mem_ctx,
392         const struct file_id id,
393         const char *servicepath,
394         const struct smb_filename *smb_fname,
395         const struct timespec *old_write_time)
396 {
397         TALLOC_CTX *frame = talloc_stackframe();
398
399         struct share_mode_lock *lck;
400
401         if (the_lock == NULL) {
402                 the_lock = get_share_mode_lock_internal(
403                         frame, id, servicepath, smb_fname, old_write_time);
404                 if (the_lock == NULL) {
405                         goto fail;
406                 }
407                 talloc_set_destructor(the_lock, the_lock_destructor);
408         }
409         if (!file_id_equal(&the_lock->data->id, &id)) {
410                 DEBUG(1, ("Can not lock two share modes simultaneously\n"));
411                 goto fail;
412         }
413         lck = talloc(mem_ctx, struct share_mode_lock);
414         if (lck == NULL) {
415                 DEBUG(1, ("talloc failed\n"));
416                 goto fail;
417         }
418         if (talloc_reference(lck, the_lock) == NULL) {
419                 DEBUG(1, ("talloc_reference failed\n"));
420                 goto fail;
421         }
422         lck->data = the_lock->data;
423         TALLOC_FREE(frame);
424         return lck;
425 fail:
426         TALLOC_FREE(frame);
427         return NULL;
428 }
429
430 /*******************************************************************
431  Get a share_mode_lock without locking the database or reference
432  counting. Used by smbstatus to display existing share modes.
433 ********************************************************************/
434
435 struct share_mode_lock *fetch_share_mode_unlocked(TALLOC_CTX *mem_ctx,
436                                                   const struct file_id id)
437 {
438         struct share_mode_lock *lck;
439         struct file_id tmp;
440         TDB_DATA key = locking_key(&id, &tmp);
441         TDB_DATA data;
442         NTSTATUS status;
443
444         status = dbwrap_fetch(lock_db, talloc_tos(), key, &data);
445         if (!NT_STATUS_IS_OK(status)) {
446                 DEBUG(3, ("Could not fetch share entry\n"));
447                 return NULL;
448         }
449         if (data.dptr == NULL) {
450                 return NULL;
451         }
452         lck = talloc(mem_ctx, struct share_mode_lock);
453         if (lck == NULL) {
454                 TALLOC_FREE(data.dptr);
455                 return NULL;
456         }
457         lck->data = parse_share_modes(mem_ctx, data);
458         TALLOC_FREE(data.dptr);
459         if (lck->data == NULL) {
460                 TALLOC_FREE(lck);
461                 return NULL;
462         }
463         return lck;
464 }
465
466 struct forall_state {
467         void (*fn)(const struct share_mode_entry *entry,
468                    const char *sharepath,
469                    const char *fname,
470                    void *private_data);
471         void *private_data;
472 };
473
474 static int traverse_fn(struct db_record *rec, void *_state)
475 {
476         struct forall_state *state = (struct forall_state *)_state;
477         uint32_t i;
478         TDB_DATA key;
479         TDB_DATA value;
480         DATA_BLOB blob;
481         enum ndr_err_code ndr_err;
482         struct share_mode_data *d;
483
484         key = dbwrap_record_get_key(rec);
485         value = dbwrap_record_get_value(rec);
486
487         /* Ensure this is a locking_key record. */
488         if (key.dsize != sizeof(struct file_id))
489                 return 0;
490
491         d = talloc(talloc_tos(), struct share_mode_data);
492         if (d == NULL) {
493                 return 0;
494         }
495
496         blob.data = value.dptr;
497         blob.length = value.dsize;
498
499         ndr_err = ndr_pull_struct_blob(
500                 &blob, d, d, (ndr_pull_flags_fn_t)ndr_pull_share_mode_data);
501         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
502                 DEBUG(1, ("ndr_pull_share_mode_lock failed\n"));
503                 return 0;
504         }
505         for (i=0; i<d->num_share_modes; i++) {
506                 state->fn(&d->share_modes[i],
507                           d->servicepath, d->base_name,
508                           state->private_data);
509         }
510         TALLOC_FREE(d);
511
512         return 0;
513 }
514
515 /*******************************************************************
516  Call the specified function on each entry under management by the
517  share mode system.
518 ********************************************************************/
519
520 int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *,
521                                  const char *, void *),
522                       void *private_data)
523 {
524         struct forall_state state;
525         NTSTATUS status;
526         int count;
527
528         if (lock_db == NULL)
529                 return 0;
530
531         state.fn = fn;
532         state.private_data = private_data;
533
534         status = dbwrap_traverse_read(lock_db, traverse_fn, (void *)&state,
535                                       &count);
536
537         if (!NT_STATUS_IS_OK(status)) {
538                 return -1;
539         } else {
540                 return count;
541         }
542 }