f7fe3db73189a61444c99f34d27bfc12cb52ab51
[kai/samba.git] / source3 / lib / g_lock.c
1 /*
2    Unix SMB/CIFS implementation.
3    global locks based on dbwrap and messaging
4    Copyright (C) 2009 by Volker Lendecke
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "system/filesys.h"
22 #include "dbwrap/dbwrap.h"
23 #include "dbwrap/dbwrap_open.h"
24 #include "dbwrap/dbwrap_watch.h"
25 #include "g_lock.h"
26 #include "util_tdb.h"
27 #include "ctdbd_conn.h"
28 #include "../lib/util/select.h"
29 #include "../lib/util/tevent_ntstatus.h"
30 #include "system/select.h"
31 #include "messages.h"
32
33 struct g_lock_ctx {
34         struct db_context *db;
35         struct messaging_context *msg;
36 };
37
38 /*
39  * The "g_lock.tdb" file contains records, indexed by the 0-terminated
40  * lockname. The record contains an array of "struct g_lock_rec"
41  * structures.
42  */
43
44 struct g_lock_rec {
45         enum g_lock_type lock_type;
46         struct server_id pid;
47 };
48
49 struct g_lock_ctx *g_lock_ctx_init(TALLOC_CTX *mem_ctx,
50                                    struct messaging_context *msg)
51 {
52         struct g_lock_ctx *result;
53
54         result = talloc(mem_ctx, struct g_lock_ctx);
55         if (result == NULL) {
56                 return NULL;
57         }
58         result->msg = msg;
59
60         result->db = db_open(result, lock_path("g_lock.tdb"), 0,
61                              TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH,
62                              O_RDWR|O_CREAT, 0600,
63                              DBWRAP_LOCK_ORDER_2);
64         if (result->db == NULL) {
65                 DEBUG(1, ("g_lock_init: Could not open g_lock.tdb\n"));
66                 TALLOC_FREE(result);
67                 return NULL;
68         }
69         dbwrap_watch_db(result->db, msg);
70         return result;
71 }
72
73 static bool g_lock_conflicts(enum g_lock_type l1, enum g_lock_type l2)
74 {
75         /*
76          * Only tested write locks so far. Very likely this routine
77          * needs to be fixed for read locks....
78          */
79         if ((l1 == G_LOCK_READ) && (l2 == G_LOCK_READ)) {
80                 return false;
81         }
82         return true;
83 }
84
85 static bool g_lock_parse(TALLOC_CTX *mem_ctx, TDB_DATA data,
86                          unsigned *pnum_locks, struct g_lock_rec **plocks)
87 {
88         unsigned num_locks;
89         struct g_lock_rec *locks;
90
91         if ((data.dsize % sizeof(struct g_lock_rec)) != 0) {
92                 DEBUG(1, ("invalid lock record length %d\n", (int)data.dsize));
93                 return false;
94         }
95         num_locks = data.dsize / sizeof(struct g_lock_rec);
96         locks = talloc_memdup(mem_ctx, data.dptr, data.dsize);
97         if (locks == NULL) {
98                 DEBUG(1, ("talloc_memdup failed\n"));
99                 return false;
100         }
101         *plocks = locks;
102         *pnum_locks = num_locks;
103         return true;
104 }
105
106 static NTSTATUS g_lock_trylock(struct db_record *rec, struct server_id self,
107                                enum g_lock_type type)
108 {
109         TDB_DATA data;
110         unsigned i, num_locks;
111         struct g_lock_rec *locks, *tmp;
112         NTSTATUS status;
113         bool modified = false;
114
115         data = dbwrap_record_get_value(rec);
116
117         if (!g_lock_parse(talloc_tos(), data, &num_locks, &locks)) {
118                 return NT_STATUS_INTERNAL_ERROR;
119         }
120
121         for (i=0; i<num_locks; i++) {
122                 if (serverid_equal(&self, &locks[i].pid)) {
123                         status = NT_STATUS_INTERNAL_ERROR;
124                         goto done;
125                 }
126                 if (g_lock_conflicts(type, locks[i].lock_type)) {
127
128                         if (process_exists(locks[i].pid)) {
129                                 status = NT_STATUS_LOCK_NOT_GRANTED;
130                                 goto done;
131                         }
132
133                         /*
134                          * Delete stale conflicting entry
135                          */
136                         locks[i] = locks[num_locks-1];
137                         num_locks -= 1;
138                         modified = true;
139                 }
140         }
141
142         tmp = talloc_realloc(talloc_tos(), locks, struct g_lock_rec,
143                              num_locks+1);
144         if (tmp == NULL) {
145                 status = NT_STATUS_NO_MEMORY;
146                 goto done;
147         }
148         locks = tmp;
149
150         ZERO_STRUCT(locks[num_locks]);
151         locks[num_locks].pid = self;
152         locks[num_locks].lock_type = type;
153         num_locks += 1;
154         modified = true;
155
156         status = NT_STATUS_OK;
157 done:
158         if (modified) {
159                 NTSTATUS store_status;
160
161                 data = make_tdb_data((uint8_t *)locks, num_locks * sizeof(*locks));
162                 store_status = dbwrap_record_store(rec, data, 0);
163                 if (!NT_STATUS_IS_OK(store_status)) {
164                         DEBUG(1, ("rec->store failed: %s\n",
165                                   nt_errstr(store_status)));
166                         status = store_status;
167                 }
168         }
169         TALLOC_FREE(locks);
170         return status;
171 }
172
173 struct g_lock_lock_state {
174         struct tevent_context *ev;
175         struct g_lock_ctx *ctx;
176         const char *name;
177         enum g_lock_type type;
178 };
179
180 static void g_lock_lock_retry(struct tevent_req *subreq);
181
182 struct tevent_req *g_lock_lock_send(TALLOC_CTX *mem_ctx,
183                                     struct tevent_context *ev,
184                                     struct g_lock_ctx *ctx,
185                                     const char *name,
186                                     enum g_lock_type type)
187 {
188         struct tevent_req *req, *subreq;
189         struct g_lock_lock_state *state;
190         struct db_record *rec;
191         struct server_id self;
192         NTSTATUS status;
193
194         req = tevent_req_create(mem_ctx, &state, struct g_lock_lock_state);
195         if (req == NULL) {
196                 return NULL;
197         }
198         state->ev = ev;
199         state->ctx = ctx;
200         state->name = name;
201         state->type = type;
202
203         rec = dbwrap_fetch_locked(ctx->db, talloc_tos(),
204                                   string_term_tdb_data(state->name));
205         if (rec == NULL) {
206                 DEBUG(10, ("fetch_locked(\"%s\") failed\n", name));
207                 tevent_req_nterror(req, NT_STATUS_LOCK_NOT_GRANTED);
208                 return tevent_req_post(req, ev);
209         }
210
211         self = messaging_server_id(state->ctx->msg);
212
213         status = g_lock_trylock(rec, self, state->type);
214         if (NT_STATUS_IS_OK(status)) {
215                 TALLOC_FREE(rec);
216                 tevent_req_done(req);
217                 return tevent_req_post(req, ev);
218         }
219         if (!NT_STATUS_EQUAL(status, NT_STATUS_LOCK_NOT_GRANTED)) {
220                 TALLOC_FREE(rec);
221                 tevent_req_nterror(req, status);
222                 return tevent_req_post(req, ev);
223         }
224         subreq = dbwrap_record_watch_send(state, state->ev, rec,
225                                           state->ctx->msg);
226         TALLOC_FREE(rec);
227         if (tevent_req_nomem(subreq, req)) {
228                 return tevent_req_post(req, ev);
229         }
230         tevent_req_set_callback(subreq, g_lock_lock_retry, req);
231         return req;
232 }
233
234 static void g_lock_lock_retry(struct tevent_req *subreq)
235 {
236         struct tevent_req *req = tevent_req_callback_data(
237                 subreq, struct tevent_req);
238         struct g_lock_lock_state *state = tevent_req_data(
239                 req, struct g_lock_lock_state);
240         struct server_id self = messaging_server_id(state->ctx->msg);
241         struct db_record *rec;
242         NTSTATUS status;
243
244         status = dbwrap_record_watch_recv(subreq, talloc_tos(), &rec);
245         TALLOC_FREE(subreq);
246         if (tevent_req_nterror(req, status)) {
247                 return;
248         }
249         status = g_lock_trylock(rec, self, state->type);
250         if (NT_STATUS_IS_OK(status)) {
251                 TALLOC_FREE(rec);
252                 tevent_req_done(req);
253                 return;
254         }
255         if (!NT_STATUS_EQUAL(status, NT_STATUS_LOCK_NOT_GRANTED)) {
256                 TALLOC_FREE(rec);
257                 tevent_req_nterror(req, status);
258                 return;
259         }
260         subreq = dbwrap_record_watch_send(state, state->ev, rec,
261                                           state->ctx->msg);
262         TALLOC_FREE(rec);
263         if (tevent_req_nomem(subreq, req)) {
264                 return;
265         }
266         tevent_req_set_callback(subreq, g_lock_lock_retry, req);
267         return;
268
269 }
270
271 NTSTATUS g_lock_lock_recv(struct tevent_req *req)
272 {
273         return tevent_req_simple_recv_ntstatus(req);
274 }
275
276 NTSTATUS g_lock_lock(struct g_lock_ctx *ctx, const char *name,
277                      enum g_lock_type type, struct timeval timeout)
278 {
279         TALLOC_CTX *frame = talloc_stackframe();
280         struct tevent_context *ev;
281         struct tevent_req *req;
282         struct timeval end;
283         NTSTATUS status = NT_STATUS_NO_MEMORY;
284
285         ev = tevent_context_init(frame);
286         if (ev == NULL) {
287                 goto fail;
288         }
289         req = g_lock_lock_send(frame, ev, ctx, name, type);
290         if (req == NULL) {
291                 goto fail;
292         }
293         end = timeval_current_ofs(timeout.tv_sec, timeout.tv_usec);
294         if (!tevent_req_set_endtime(req, ev, end)) {
295                 goto fail;
296         }
297         if (!tevent_req_poll_ntstatus(req, ev, &status)) {
298                 goto fail;
299         }
300         status = g_lock_lock_recv(req);
301  fail:
302         TALLOC_FREE(frame);
303         return status;
304 }
305
306 NTSTATUS g_lock_unlock(struct g_lock_ctx *ctx, const char *name)
307 {
308         struct server_id self = messaging_server_id(ctx->msg);
309         struct db_record *rec = NULL;
310         struct g_lock_rec *locks = NULL;
311         unsigned i, num_locks;
312         NTSTATUS status;
313         TDB_DATA value;
314
315         rec = dbwrap_fetch_locked(ctx->db, talloc_tos(),
316                                   string_term_tdb_data(name));
317         if (rec == NULL) {
318                 DEBUG(10, ("fetch_locked(\"%s\") failed\n", name));
319                 status = NT_STATUS_INTERNAL_ERROR;
320                 goto done;
321         }
322
323         value = dbwrap_record_get_value(rec);
324
325         if (!g_lock_parse(talloc_tos(), value, &num_locks, &locks)) {
326                 DEBUG(10, ("g_lock_parse for %s failed\n", name));
327                 status = NT_STATUS_FILE_INVALID;
328                 goto done;
329         }
330         for (i=0; i<num_locks; i++) {
331                 if (serverid_equal(&self, &locks[i].pid)) {
332                         break;
333                 }
334         }
335         if (i == num_locks) {
336                 DEBUG(10, ("g_lock_force_unlock: Lock not found\n"));
337                 status = NT_STATUS_NOT_FOUND;
338                 goto done;
339         }
340
341         locks[i] = locks[num_locks-1];
342         num_locks -= 1;
343
344         if (num_locks == 0) {
345                 status = dbwrap_record_delete(rec);
346         } else {
347                 TDB_DATA data;
348                 data = make_tdb_data((uint8_t *)locks,
349                                      sizeof(struct g_lock_rec) * num_locks);
350                 status = dbwrap_record_store(rec, data, 0);
351         }
352         if (!NT_STATUS_IS_OK(status)) {
353                 DEBUG(1, ("g_lock_force_unlock: Could not store record: %s\n",
354                           nt_errstr(status)));
355                 goto done;
356         }
357
358         status = NT_STATUS_OK;
359 done:
360         TALLOC_FREE(rec);
361         TALLOC_FREE(locks);
362         return status;
363 }
364
365 struct g_lock_locks_state {
366         int (*fn)(const char *name, void *private_data);
367         void *private_data;
368 };
369
370 static int g_lock_locks_fn(struct db_record *rec, void *priv)
371 {
372         TDB_DATA key;
373         struct g_lock_locks_state *state = (struct g_lock_locks_state *)priv;
374
375         key = dbwrap_record_get_key(rec);
376         if ((key.dsize == 0) || (key.dptr[key.dsize-1] != 0)) {
377                 DEBUG(1, ("invalid key in g_lock.tdb, ignoring\n"));
378                 return 0;
379         }
380         return state->fn((char *)key.dptr, state->private_data);
381 }
382
383 int g_lock_locks(struct g_lock_ctx *ctx,
384                  int (*fn)(const char *name, void *private_data),
385                  void *private_data)
386 {
387         struct g_lock_locks_state state;
388         NTSTATUS status;
389         int count;
390
391         state.fn = fn;
392         state.private_data = private_data;
393
394         status = dbwrap_traverse_read(ctx->db, g_lock_locks_fn, &state, &count);
395         if (!NT_STATUS_IS_OK(status)) {
396                 return -1;
397         } else {
398                 return count;
399         }
400 }
401
402 NTSTATUS g_lock_dump(struct g_lock_ctx *ctx, const char *name,
403                      int (*fn)(struct server_id pid,
404                                enum g_lock_type lock_type,
405                                void *private_data),
406                      void *private_data)
407 {
408         TDB_DATA data;
409         unsigned i, num_locks;
410         struct g_lock_rec *locks = NULL;
411         bool ret;
412         NTSTATUS status;
413
414         status = dbwrap_fetch_bystring(ctx->db, talloc_tos(), name, &data);
415         if (!NT_STATUS_IS_OK(status)) {
416                 return status;
417         }
418
419         if ((data.dsize == 0) || (data.dptr == NULL)) {
420                 return NT_STATUS_OK;
421         }
422
423         ret = g_lock_parse(talloc_tos(), data, &num_locks, &locks);
424
425         TALLOC_FREE(data.dptr);
426
427         if (!ret) {
428                 DEBUG(10, ("g_lock_parse for %s failed\n", name));
429                 return NT_STATUS_INTERNAL_ERROR;
430         }
431
432         for (i=0; i<num_locks; i++) {
433                 if (fn(locks[i].pid, locks[i].lock_type, private_data) != 0) {
434                         break;
435                 }
436         }
437         TALLOC_FREE(locks);
438         return NT_STATUS_OK;
439 }
440
441 struct g_lock_get_state {
442         bool found;
443         struct server_id *pid;
444 };
445
446 static int g_lock_get_fn(struct server_id pid, enum g_lock_type lock_type,
447                          void *priv)
448 {
449         struct g_lock_get_state *state = (struct g_lock_get_state *)priv;
450         state->found = true;
451         *state->pid = pid;
452         return 1;
453 }
454
455 NTSTATUS g_lock_get(struct g_lock_ctx *ctx, const char *name,
456                     struct server_id *pid)
457 {
458         struct g_lock_get_state state;
459         NTSTATUS status;
460
461         state.found = false;
462         state.pid = pid;
463
464         status = g_lock_dump(ctx, name, g_lock_get_fn, &state);
465         if (!NT_STATUS_IS_OK(status)) {
466                 return status;
467         }
468         if (!state.found) {
469                 return NT_STATUS_NOT_FOUND;
470         }
471         return NT_STATUS_OK;
472 }
473
474 static bool g_lock_init_all(TALLOC_CTX *mem_ctx,
475                             struct tevent_context **pev,
476                             struct messaging_context **pmsg,
477                             struct g_lock_ctx **pg_ctx)
478 {
479         struct tevent_context *ev = NULL;
480         struct messaging_context *msg = NULL;
481         struct g_lock_ctx *g_ctx = NULL;
482
483         ev = tevent_context_init(mem_ctx);
484         if (ev == NULL) {
485                 d_fprintf(stderr, "ERROR: could not init event context\n");
486                 goto fail;
487         }
488         msg = messaging_init(mem_ctx, ev);
489         if (msg == NULL) {
490                 d_fprintf(stderr, "ERROR: could not init messaging context\n");
491                 goto fail;
492         }
493         g_ctx = g_lock_ctx_init(mem_ctx, msg);
494         if (g_ctx == NULL) {
495                 d_fprintf(stderr, "ERROR: could not init g_lock context\n");
496                 goto fail;
497         }
498
499         *pev = ev;
500         *pmsg = msg;
501         *pg_ctx = g_ctx;
502         return true;
503 fail:
504         TALLOC_FREE(g_ctx);
505         TALLOC_FREE(msg);
506         TALLOC_FREE(ev);
507         return false;
508 }
509
510 NTSTATUS g_lock_do(const char *name, enum g_lock_type lock_type,
511                    struct timeval timeout,
512                    void (*fn)(void *private_data), void *private_data)
513 {
514         struct tevent_context *ev = NULL;
515         struct messaging_context *msg = NULL;
516         struct g_lock_ctx *g_ctx = NULL;
517         NTSTATUS status;
518
519         if (!g_lock_init_all(talloc_tos(), &ev, &msg, &g_ctx)) {
520                 status = NT_STATUS_ACCESS_DENIED;
521                 goto done;
522         }
523
524         status = g_lock_lock(g_ctx, name, lock_type, timeout);
525         if (!NT_STATUS_IS_OK(status)) {
526                 goto done;
527         }
528         fn(private_data);
529         g_lock_unlock(g_ctx, name);
530
531 done:
532         TALLOC_FREE(g_ctx);
533         TALLOC_FREE(msg);
534         TALLOC_FREE(ev);
535         return status;
536 }