lib/util/charset rename iconv_convenience to iconv_handle
[ira/wip.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 "g_lock.h"
22 #include "librpc/gen_ndr/messaging.h"
23 #include "ctdbd_conn.h"
24 #include "../lib/util/select.h"
25 #include "system/select.h"
26
27 static NTSTATUS g_lock_force_unlock(struct g_lock_ctx *ctx, const char *name,
28                                     struct server_id pid);
29
30 struct g_lock_ctx {
31         struct db_context *db;
32         struct messaging_context *msg;
33 };
34
35 /*
36  * The "g_lock.tdb" file contains records, indexed by the 0-terminated
37  * lockname. The record contains an array of "struct g_lock_rec"
38  * structures. Waiters have the lock_type with G_LOCK_PENDING or'ed.
39  */
40
41 struct g_lock_rec {
42         enum g_lock_type lock_type;
43         struct server_id pid;
44 };
45
46 struct g_lock_ctx *g_lock_ctx_init(TALLOC_CTX *mem_ctx,
47                                    struct messaging_context *msg)
48 {
49         struct g_lock_ctx *result;
50
51         result = talloc(mem_ctx, struct g_lock_ctx);
52         if (result == NULL) {
53                 return NULL;
54         }
55         result->msg = msg;
56
57         result->db = db_open(result, lock_path("g_lock.tdb"), 0,
58                              TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH, O_RDWR|O_CREAT, 0700);
59         if (result->db == NULL) {
60                 DEBUG(1, ("g_lock_init: Could not open g_lock.tdb"));
61                 TALLOC_FREE(result);
62                 return NULL;
63         }
64         return result;
65 }
66
67 static bool g_lock_conflicts(enum g_lock_type lock_type,
68                              const struct g_lock_rec *rec)
69 {
70         enum g_lock_type rec_lock = rec->lock_type;
71
72         if ((rec_lock & G_LOCK_PENDING) != 0) {
73                 return false;
74         }
75
76         /*
77          * Only tested write locks so far. Very likely this routine
78          * needs to be fixed for read locks....
79          */
80         if ((lock_type == G_LOCK_READ) && (rec_lock == G_LOCK_READ)) {
81                 return false;
82         }
83         return true;
84 }
85
86 static bool g_lock_parse(TALLOC_CTX *mem_ctx, TDB_DATA data,
87                          int *pnum_locks, struct g_lock_rec **plocks)
88 {
89         int i, num_locks;
90         struct g_lock_rec *locks;
91
92         if ((data.dsize % sizeof(struct g_lock_rec)) != 0) {
93                 DEBUG(1, ("invalid lock record length %d\n", (int)data.dsize));
94                 return false;
95         }
96
97         num_locks = data.dsize / sizeof(struct g_lock_rec);
98         locks = talloc_array(mem_ctx, struct g_lock_rec, num_locks);
99         if (locks == NULL) {
100                 DEBUG(1, ("talloc failed\n"));
101                 return false;
102         }
103
104         memcpy(locks, data.dptr, data.dsize);
105
106         DEBUG(10, ("locks:\n"));
107         for (i=0; i<num_locks; i++) {
108                 DEBUGADD(10, ("%s: %s %s\n",
109                               procid_str(talloc_tos(), &locks[i].pid),
110                               ((locks[i].lock_type & 1) == G_LOCK_READ) ?
111                               "read" : "write",
112                               (locks[i].lock_type & G_LOCK_PENDING) ?
113                               "(pending)" : "(owner)"));
114
115                 if (((locks[i].lock_type & G_LOCK_PENDING) == 0)
116                     && !process_exists(locks[i].pid)) {
117
118                         DEBUGADD(10, ("lock owner %s died -- discarding\n",
119                                       procid_str(talloc_tos(),
120                                                  &locks[i].pid)));
121
122                         if (i < (num_locks-1)) {
123                                 locks[i] = locks[num_locks-1];
124                         }
125                         num_locks -= 1;
126                 }
127         }
128
129         *plocks = locks;
130         *pnum_locks = num_locks;
131         return true;
132 }
133
134 static void g_lock_cleanup(int *pnum_locks, struct g_lock_rec *locks)
135 {
136         int i, num_locks;
137
138         num_locks = *pnum_locks;
139
140         DEBUG(10, ("g_lock_cleanup: %d locks\n", num_locks));
141
142         for (i=0; i<num_locks; i++) {
143                 if (process_exists(locks[i].pid)) {
144                         continue;
145                 }
146                 DEBUGADD(10, ("%s does not exist -- discarding\n",
147                               procid_str(talloc_tos(), &locks[i].pid)));
148
149                 if (i < (num_locks-1)) {
150                         locks[i] = locks[num_locks-1];
151                 }
152                 num_locks -= 1;
153         }
154         *pnum_locks = num_locks;
155         return;
156 }
157
158 static struct g_lock_rec *g_lock_addrec(TALLOC_CTX *mem_ctx,
159                                         struct g_lock_rec *locks,
160                                         int *pnum_locks,
161                                         const struct server_id pid,
162                                         enum g_lock_type lock_type)
163 {
164         struct g_lock_rec *result;
165         int num_locks = *pnum_locks;
166
167         result = talloc_realloc(mem_ctx, locks, struct g_lock_rec,
168                                 num_locks+1);
169         if (result == NULL) {
170                 return NULL;
171         }
172
173         result[num_locks].pid = pid;
174         result[num_locks].lock_type = lock_type;
175         *pnum_locks += 1;
176         return result;
177 }
178
179 static void g_lock_got_retry(struct messaging_context *msg,
180                              void *private_data,
181                              uint32_t msg_type,
182                              struct server_id server_id,
183                              DATA_BLOB *data);
184
185 static NTSTATUS g_lock_trylock(struct g_lock_ctx *ctx, const char *name,
186                                enum g_lock_type lock_type)
187 {
188         struct db_record *rec = NULL;
189         struct g_lock_rec *locks = NULL;
190         int i, num_locks;
191         struct server_id self;
192         int our_index;
193         TDB_DATA data;
194         NTSTATUS status = NT_STATUS_OK;
195         NTSTATUS store_status;
196
197 again:
198         rec = ctx->db->fetch_locked(ctx->db, talloc_tos(),
199                                     string_term_tdb_data(name));
200         if (rec == NULL) {
201                 DEBUG(10, ("fetch_locked(\"%s\") failed\n", name));
202                 status = NT_STATUS_LOCK_NOT_GRANTED;
203                 goto done;
204         }
205
206         if (!g_lock_parse(talloc_tos(), rec->value, &num_locks, &locks)) {
207                 DEBUG(10, ("g_lock_parse for %s failed\n", name));
208                 status = NT_STATUS_INTERNAL_ERROR;
209                 goto done;
210         }
211
212         self = messaging_server_id(ctx->msg);
213         our_index = -1;
214
215         for (i=0; i<num_locks; i++) {
216                 if (procid_equal(&self, &locks[i].pid)) {
217                         if (our_index != -1) {
218                                 DEBUG(1, ("g_lock_trylock: Added ourself "
219                                           "twice!\n"));
220                                 status = NT_STATUS_INTERNAL_ERROR;
221                                 goto done;
222                         }
223                         if ((locks[i].lock_type & G_LOCK_PENDING) == 0) {
224                                 DEBUG(1, ("g_lock_trylock: Found ourself not "
225                                           "pending!\n"));
226                                 status = NT_STATUS_INTERNAL_ERROR;
227                                 goto done;
228                         }
229
230                         our_index = i;
231
232                         /* never conflict with ourself */
233                         continue;
234                 }
235                 if (g_lock_conflicts(lock_type, &locks[i])) {
236                         struct server_id pid = locks[i].pid;
237
238                         if (!process_exists(pid)) {
239                                 TALLOC_FREE(locks);
240                                 TALLOC_FREE(rec);
241                                 status = g_lock_force_unlock(ctx, name, pid);
242                                 if (!NT_STATUS_IS_OK(status)) {
243                                         DEBUG(1, ("Could not unlock dead lock "
244                                                   "holder!\n"));
245                                         goto done;
246                                 }
247                                 goto again;
248                         }
249                         lock_type |= G_LOCK_PENDING;
250                 }
251         }
252
253         if (our_index == -1) {
254                 /* First round, add ourself */
255
256                 locks = g_lock_addrec(talloc_tos(), locks, &num_locks,
257                                       self, lock_type);
258                 if (locks == NULL) {
259                         DEBUG(10, ("g_lock_addrec failed\n"));
260                         status = NT_STATUS_NO_MEMORY;
261                         goto done;
262                 }
263         } else {
264                 /*
265                  * Retry. We were pending last time. Overwrite the
266                  * stored lock_type with what we calculated, we might
267                  * have acquired the lock this time.
268                  */
269                 locks[our_index].lock_type = lock_type;
270         }
271
272         if (NT_STATUS_IS_OK(status) && ((lock_type & G_LOCK_PENDING) == 0)) {
273                 /*
274                  * Walk through the list of locks, search for dead entries
275                  */
276                 g_lock_cleanup(&num_locks, locks);
277         }
278
279         data = make_tdb_data((uint8_t *)locks, num_locks * sizeof(*locks));
280         store_status = rec->store(rec, data, 0);
281         if (!NT_STATUS_IS_OK(store_status)) {
282                 DEBUG(1, ("rec->store failed: %s\n",
283                           nt_errstr(store_status)));
284                 status = store_status;
285         }
286
287 done:
288         TALLOC_FREE(locks);
289         TALLOC_FREE(rec);
290
291         if (NT_STATUS_IS_OK(status) && (lock_type & G_LOCK_PENDING) != 0) {
292                 return STATUS_PENDING;
293         }
294
295         return NT_STATUS_OK;
296 }
297
298 NTSTATUS g_lock_lock(struct g_lock_ctx *ctx, const char *name,
299                      enum g_lock_type lock_type, struct timeval timeout)
300 {
301         struct tevent_timer *te = NULL;
302         NTSTATUS status;
303         bool retry = false;
304         struct timeval timeout_end;
305         struct timeval time_now;
306
307         DEBUG(10, ("Trying to acquire lock %d for %s\n", (int)lock_type,
308                    name));
309
310         if (lock_type & ~1) {
311                 DEBUG(1, ("Got invalid lock type %d for %s\n",
312                           (int)lock_type, name));
313                 return NT_STATUS_INVALID_PARAMETER;
314         }
315
316 #ifdef CLUSTER_SUPPORT
317         if (lp_clustering()) {
318                 status = ctdb_watch_us(messaging_ctdbd_connection());
319                 if (!NT_STATUS_IS_OK(status)) {
320                         DEBUG(10, ("could not register retry with ctdb: %s\n",
321                                    nt_errstr(status)));
322                         goto done;
323                 }
324         }
325 #endif
326
327         status = messaging_register(ctx->msg, &retry, MSG_DBWRAP_G_LOCK_RETRY,
328                                     g_lock_got_retry);
329         if (!NT_STATUS_IS_OK(status)) {
330                 DEBUG(10, ("messaging_register failed: %s\n",
331                            nt_errstr(status)));
332                 return status;
333         }
334
335         time_now = timeval_current();
336         timeout_end = timeval_sum(&time_now, &timeout);
337
338         while (true) {
339                 struct pollfd *pollfds;
340                 int num_pollfds;
341                 int saved_errno;
342                 int ret;
343                 struct timeval timeout_remaining, select_timeout;
344
345                 status = g_lock_trylock(ctx, name, lock_type);
346                 if (NT_STATUS_IS_OK(status)) {
347                         DEBUG(10, ("Got lock %s\n", name));
348                         break;
349                 }
350                 if (!NT_STATUS_EQUAL(status, STATUS_PENDING)) {
351                         DEBUG(10, ("g_lock_trylock failed: %s\n",
352                                    nt_errstr(status)));
353                         break;
354                 }
355
356                 DEBUG(10, ("g_lock_trylock: Did not get lock, waiting...\n"));
357
358                 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
359                  *             !!! HACK ALERT --- FIX ME !!!
360                  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
361                  * What we really want to do here is to react to
362                  * MSG_DBWRAP_G_LOCK_RETRY messages that are either sent
363                  * by a client doing g_lock_unlock or by ourselves when
364                  * we receive a CTDB_SRVID_SAMBA_NOTIFY or
365                  * CTDB_SRVID_RECONFIGURE message from ctdbd, i.e. when
366                  * either a client holding a lock or a complete node
367                  * has died.
368                  *
369                  * Doing this properly involves calling tevent_loop_once(),
370                  * but doing this here with the main ctdbd messaging context
371                  * creates a nested event loop when g_lock_lock() is called
372                  * from the main event loop, e.g. in a tcon_and_X where the
373                  * share_info.tdb needs to be initialized and is locked by
374                  * another process, or when the remore registry is accessed
375                  * for writing and some other process already holds a lock
376                  * on the registry.tdb.
377                  *
378                  * So as a quick fix, we act a little coarsely here: we do
379                  * a select on the ctdb connection fd and when it is readable
380                  * or we get EINTR, then we retry without actually parsing
381                  * any ctdb packages or dispatching messages. This means that
382                  * we retry more often than intended by design, but this does
383                  * not harm and it is unobtrusive. When we have finished,
384                  * the main loop will pick up all the messages and ctdb
385                  * packets. The only extra twist is that we cannot use timed
386                  * events here but have to handcode a timeout.
387                  */
388
389                 /*
390                  * We allocate 2 entries here. One is needed anyway for
391                  * sys_poll and in the clustering case we might have to add
392                  * the ctdb fd. This avoids the realloc then.
393                  */
394                 pollfds = TALLOC_ARRAY(talloc_tos(), struct pollfd, 2);
395                 if (pollfds == NULL) {
396                         status = NT_STATUS_NO_MEMORY;
397                         break;
398                 }
399                 num_pollfds = 1;
400
401 #ifdef CLUSTER_SUPPORT
402                 if (lp_clustering()) {
403                         struct ctdbd_connection *conn;
404                         conn = messaging_ctdbd_connection();
405
406                         pollfds[0].fd = ctdbd_conn_get_fd(conn);
407                         pollfds[0].events = POLLIN|POLLHUP;
408
409                         num_pollfds += 1;
410                 }
411 #endif
412
413                 time_now = timeval_current();
414                 timeout_remaining = timeval_until(&time_now, &timeout_end);
415                 select_timeout = timeval_set(60, 0);
416
417                 select_timeout = timeval_min(&select_timeout,
418                                              &timeout_remaining);
419
420                 ret = sys_poll(pollfds, num_pollfds,
421                                timeval_to_msec(select_timeout));
422
423                 /*
424                  * We're not *really interested in the actual flags. We just
425                  * need to retry this whole thing.
426                  */
427                 saved_errno = errno;
428                 TALLOC_FREE(pollfds);
429                 errno = saved_errno;
430
431                 if (ret == -1) {
432                         if (errno != EINTR) {
433                                 DEBUG(1, ("error calling select: %s\n",
434                                           strerror(errno)));
435                                 status = NT_STATUS_INTERNAL_ERROR;
436                                 break;
437                         }
438                         /*
439                          * errno == EINTR:
440                          * This means a signal was received.
441                          * It might have been a MSG_DBWRAP_G_LOCK_RETRY message.
442                          * ==> retry
443                          */
444                 } else if (ret == 0) {
445                         if (timeval_expired(&timeout_end)) {
446                                 DEBUG(10, ("g_lock_lock timed out\n"));
447                                 status = NT_STATUS_LOCK_NOT_GRANTED;
448                                 break;
449                         } else {
450                                 DEBUG(10, ("select returned 0 but timeout not "
451                                            "not expired, retrying\n"));
452                         }
453                 } else if (ret != 1) {
454                         DEBUG(1, ("invalid return code of select: %d\n", ret));
455                         status = NT_STATUS_INTERNAL_ERROR;
456                         break;
457                 }
458                 /*
459                  * ret == 1:
460                  * This means ctdbd has sent us some data.
461                  * Might be a CTDB_SRVID_RECONFIGURE or a
462                  * CTDB_SRVID_SAMBA_NOTIFY message.
463                  * ==> retry
464                  */
465         }
466
467 #ifdef CLUSTER_SUPPORT
468 done:
469 #endif
470
471         if (!NT_STATUS_IS_OK(status)) {
472                 NTSTATUS unlock_status;
473
474                 unlock_status = g_lock_unlock(ctx, name);
475
476                 if (!NT_STATUS_IS_OK(unlock_status)) {
477                         DEBUG(1, ("Could not remove ourself from the locking "
478                                   "db: %s\n", nt_errstr(status)));
479                 }
480         }
481
482         messaging_deregister(ctx->msg, MSG_DBWRAP_G_LOCK_RETRY, &retry);
483         TALLOC_FREE(te);
484
485         return status;
486 }
487
488 static void g_lock_got_retry(struct messaging_context *msg,
489                              void *private_data,
490                              uint32_t msg_type,
491                              struct server_id server_id,
492                              DATA_BLOB *data)
493 {
494         bool *pretry = (bool *)private_data;
495
496         DEBUG(10, ("Got retry message from pid %s\n",
497                    procid_str(talloc_tos(), &server_id)));
498
499         *pretry = true;
500 }
501
502 static NTSTATUS g_lock_force_unlock(struct g_lock_ctx *ctx, const char *name,
503                                     struct server_id pid)
504 {
505         struct db_record *rec = NULL;
506         struct g_lock_rec *locks = NULL;
507         int i, num_locks;
508         enum g_lock_type lock_type;
509         NTSTATUS status;
510
511         rec = ctx->db->fetch_locked(ctx->db, talloc_tos(),
512                                     string_term_tdb_data(name));
513         if (rec == NULL) {
514                 DEBUG(10, ("fetch_locked(\"%s\") failed\n", name));
515                 status = NT_STATUS_INTERNAL_ERROR;
516                 goto done;
517         }
518
519         if (!g_lock_parse(talloc_tos(), rec->value, &num_locks, &locks)) {
520                 DEBUG(10, ("g_lock_parse for %s failed\n", name));
521                 status = NT_STATUS_INTERNAL_ERROR;
522                 goto done;
523         }
524
525         for (i=0; i<num_locks; i++) {
526                 if (procid_equal(&pid, &locks[i].pid)) {
527                         break;
528                 }
529         }
530
531         if (i == num_locks) {
532                 DEBUG(10, ("g_lock_force_unlock: Lock not found\n"));
533                 status = NT_STATUS_INTERNAL_ERROR;
534                 goto done;
535         }
536
537         lock_type = locks[i].lock_type;
538
539         if (i < (num_locks-1)) {
540                 locks[i] = locks[num_locks-1];
541         }
542         num_locks -= 1;
543
544         if (num_locks == 0) {
545                 status = rec->delete_rec(rec);
546         } else {
547                 TDB_DATA data;
548                 data = make_tdb_data((uint8_t *)locks,
549                                      sizeof(struct g_lock_rec) * num_locks);
550                 status = rec->store(rec, data, 0);
551         }
552
553         if (!NT_STATUS_IS_OK(status)) {
554                 DEBUG(1, ("g_lock_force_unlock: Could not store record: %s\n",
555                           nt_errstr(status)));
556                 goto done;
557         }
558
559         TALLOC_FREE(rec);
560
561         if ((lock_type & G_LOCK_PENDING) == 0) {
562                 int num_wakeups = 0;
563
564                 /*
565                  * We've been the lock holder. Others to retry. Don't
566                  * tell all others to avoid a thundering herd. In case
567                  * this leads to a complete stall because we miss some
568                  * processes, the loop in g_lock_lock tries at least
569                  * once a minute.
570                  */
571
572                 for (i=0; i<num_locks; i++) {
573                         if ((locks[i].lock_type & G_LOCK_PENDING) == 0) {
574                                 continue;
575                         }
576                         if (!process_exists(locks[i].pid)) {
577                                 continue;
578                         }
579
580                         /*
581                          * Ping all waiters to retry
582                          */
583                         status = messaging_send(ctx->msg, locks[i].pid,
584                                                 MSG_DBWRAP_G_LOCK_RETRY,
585                                                 &data_blob_null);
586                         if (!NT_STATUS_IS_OK(status)) {
587                                 DEBUG(1, ("sending retry to %s failed: %s\n",
588                                           procid_str(talloc_tos(),
589                                                      &locks[i].pid),
590                                           nt_errstr(status)));
591                         } else {
592                                 num_wakeups += 1;
593                         }
594                         if (num_wakeups > 5) {
595                                 break;
596                         }
597                 }
598         }
599 done:
600         /*
601          * For the error path, TALLOC_FREE(rec) as well. In the good
602          * path we have already freed it.
603          */
604         TALLOC_FREE(rec);
605
606         TALLOC_FREE(locks);
607         return status;
608 }
609
610 NTSTATUS g_lock_unlock(struct g_lock_ctx *ctx, const char *name)
611 {
612         NTSTATUS status;
613
614         status = g_lock_force_unlock(ctx, name, messaging_server_id(ctx->msg));
615
616 #ifdef CLUSTER_SUPPORT
617         if (lp_clustering()) {
618                 ctdb_unwatch(messaging_ctdbd_connection());
619         }
620 #endif
621         return status;
622 }
623
624 struct g_lock_locks_state {
625         int (*fn)(const char *name, void *private_data);
626         void *private_data;
627 };
628
629 static int g_lock_locks_fn(struct db_record *rec, void *priv)
630 {
631         struct g_lock_locks_state *state = (struct g_lock_locks_state *)priv;
632
633         if ((rec->key.dsize == 0) || (rec->key.dptr[rec->key.dsize-1] != 0)) {
634                 DEBUG(1, ("invalid key in g_lock.tdb, ignoring\n"));
635                 return 0;
636         }
637         return state->fn((char *)rec->key.dptr, state->private_data);
638 }
639
640 int g_lock_locks(struct g_lock_ctx *ctx,
641                  int (*fn)(const char *name, void *private_data),
642                  void *private_data)
643 {
644         struct g_lock_locks_state state;
645
646         state.fn = fn;
647         state.private_data = private_data;
648
649         return ctx->db->traverse_read(ctx->db, g_lock_locks_fn, &state);
650 }
651
652 NTSTATUS g_lock_dump(struct g_lock_ctx *ctx, const char *name,
653                      int (*fn)(struct server_id pid,
654                                enum g_lock_type lock_type,
655                                void *private_data),
656                      void *private_data)
657 {
658         TDB_DATA data;
659         int i, num_locks;
660         struct g_lock_rec *locks = NULL;
661         bool ret;
662
663         if (ctx->db->fetch(ctx->db, talloc_tos(), string_term_tdb_data(name),
664                            &data) != 0) {
665                 return NT_STATUS_NOT_FOUND;
666         }
667
668         if ((data.dsize == 0) || (data.dptr == NULL)) {
669                 return NT_STATUS_OK;
670         }
671
672         ret = g_lock_parse(talloc_tos(), data, &num_locks, &locks);
673
674         TALLOC_FREE(data.dptr);
675
676         if (!ret) {
677                 DEBUG(10, ("g_lock_parse for %s failed\n", name));
678                 return NT_STATUS_INTERNAL_ERROR;
679         }
680
681         for (i=0; i<num_locks; i++) {
682                 if (fn(locks[i].pid, locks[i].lock_type, private_data) != 0) {
683                         break;
684                 }
685         }
686         TALLOC_FREE(locks);
687         return NT_STATUS_OK;
688 }
689
690 struct g_lock_get_state {
691         bool found;
692         struct server_id *pid;
693 };
694
695 static int g_lock_get_fn(struct server_id pid, enum g_lock_type lock_type,
696                          void *priv)
697 {
698         struct g_lock_get_state *state = (struct g_lock_get_state *)priv;
699
700         if ((lock_type & G_LOCK_PENDING) != 0) {
701                 return 0;
702         }
703
704         state->found = true;
705         *state->pid = pid;
706         return 1;
707 }
708
709 NTSTATUS g_lock_get(struct g_lock_ctx *ctx, const char *name,
710                     struct server_id *pid)
711 {
712         struct g_lock_get_state state;
713         NTSTATUS status;
714
715         state.found = false;
716         state.pid = pid;
717
718         status = g_lock_dump(ctx, name, g_lock_get_fn, &state);
719         if (!NT_STATUS_IS_OK(status)) {
720                 return status;
721         }
722         if (!state.found) {
723                 return NT_STATUS_NOT_FOUND;
724         }
725         return NT_STATUS_OK;
726 }
727
728 static bool g_lock_init_all(TALLOC_CTX *mem_ctx,
729                             struct tevent_context **pev,
730                             struct messaging_context **pmsg,
731                             const struct server_id self,
732                             struct g_lock_ctx **pg_ctx)
733 {
734         struct tevent_context *ev = NULL;
735         struct messaging_context *msg = NULL;
736         struct g_lock_ctx *g_ctx = NULL;
737
738         ev = tevent_context_init(mem_ctx);
739         if (ev == NULL) {
740                 d_fprintf(stderr, "ERROR: could not init event context\n");
741                 goto fail;
742         }
743         msg = messaging_init(mem_ctx, self, ev);
744         if (msg == NULL) {
745                 d_fprintf(stderr, "ERROR: could not init messaging context\n");
746                 goto fail;
747         }
748         g_ctx = g_lock_ctx_init(mem_ctx, msg);
749         if (g_ctx == NULL) {
750                 d_fprintf(stderr, "ERROR: could not init g_lock context\n");
751                 goto fail;
752         }
753
754         *pev = ev;
755         *pmsg = msg;
756         *pg_ctx = g_ctx;
757         return true;
758 fail:
759         TALLOC_FREE(g_ctx);
760         TALLOC_FREE(msg);
761         TALLOC_FREE(ev);
762         return false;
763 }
764
765 NTSTATUS g_lock_do(const char *name, enum g_lock_type lock_type,
766                    struct timeval timeout, const struct server_id self,
767                    void (*fn)(void *private_data), void *private_data)
768 {
769         struct tevent_context *ev = NULL;
770         struct messaging_context *msg = NULL;
771         struct g_lock_ctx *g_ctx = NULL;
772         NTSTATUS status;
773
774         if (!g_lock_init_all(talloc_tos(), &ev, &msg, self, &g_ctx)) {
775                 status = NT_STATUS_ACCESS_DENIED;
776                 goto done;
777         }
778
779         status = g_lock_lock(g_ctx, name, lock_type, timeout);
780         if (!NT_STATUS_IS_OK(status)) {
781                 goto done;
782         }
783         fn(private_data);
784         g_lock_unlock(g_ctx, name);
785
786 done:
787         TALLOC_FREE(g_ctx);
788         TALLOC_FREE(msg);
789         TALLOC_FREE(ev);
790         return status;
791 }