3b481cdef9fbabc04ee96b8ea7c18fec9c7a465e
[amitay/samba.git] / source3 / smbd / notify_internal.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Copyright (C) Andrew Tridgell 2006
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 /*
21   this is the change notify database. It implements mechanisms for
22   storing current change notify waiters in a tdb, and checking if a
23   given event matches any of the stored notify waiiters.
24 */
25
26 #include "includes.h"
27 #include "system/filesys.h"
28 #include "librpc/gen_ndr/ndr_notify.h"
29 #include "librpc/gen_ndr/messaging.h"
30 #include "dbwrap.h"
31
32 struct notify_context {
33         struct db_context *db_recursive;
34         struct db_context *db_onelevel;
35         struct server_id server;
36         struct messaging_context *messaging_ctx;
37         struct notify_list *list;
38         struct notify_array *array;
39         int seqnum;
40         struct sys_notify_context *sys_notify_ctx;
41         TDB_DATA key;
42 };
43
44
45 struct notify_list {
46         struct notify_list *next, *prev;
47         void *private_data;
48         void (*callback)(void *, const struct notify_event *);
49         void *sys_notify_handle;
50         int depth;
51 };
52
53 #define NOTIFY_KEY "notify array"
54
55 #define NOTIFY_ENABLE           "notify:enable"
56 #define NOTIFY_ENABLE_DEFAULT   True
57
58 static NTSTATUS notify_remove_all(struct notify_context *notify,
59                                   const struct server_id *server);
60 static void notify_handler(struct messaging_context *msg_ctx, void *private_data, 
61                            uint32_t msg_type, struct server_id server_id, DATA_BLOB *data);
62
63 /*
64   destroy the notify context
65 */
66 static int notify_destructor(struct notify_context *notify)
67 {
68         messaging_deregister(notify->messaging_ctx, MSG_PVFS_NOTIFY, notify);
69
70         if (notify->list != NULL) {
71                 notify_remove_all(notify, &notify->server);
72         }
73
74         return 0;
75 }
76
77 /*
78   Open up the notify.tdb database. You should close it down using
79   talloc_free(). We need the messaging_ctx to allow for notifications
80   via internal messages
81 */
82 struct notify_context *notify_init(TALLOC_CTX *mem_ctx, struct server_id server, 
83                                    struct messaging_context *messaging_ctx,
84                                    struct event_context *ev,
85                                    connection_struct *conn)
86 {
87         struct notify_context *notify;
88
89         if (!lp_change_notify(conn->params)) {
90                 return NULL;
91         }
92
93         notify = talloc(mem_ctx, struct notify_context);
94         if (notify == NULL) {
95                 return NULL;
96         }
97
98         notify->db_recursive = db_open(notify, lock_path("notify.tdb"),
99                                        0, TDB_SEQNUM|TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH,
100                                        O_RDWR|O_CREAT, 0644);
101         if (notify->db_recursive == NULL) {
102                 talloc_free(notify);
103                 return NULL;
104         }
105
106         notify->db_onelevel = db_open(notify, lock_path("notify_onelevel.tdb"),
107                                       0, TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH,
108                                       O_RDWR|O_CREAT, 0644);
109         if (notify->db_onelevel == NULL) {
110                 talloc_free(notify);
111                 return NULL;
112         }
113
114         notify->server = server;
115         notify->messaging_ctx = messaging_ctx;
116         notify->list = NULL;
117         notify->array = NULL;
118         notify->seqnum = notify->db_recursive->get_seqnum(
119                 notify->db_recursive);
120         notify->key = string_term_tdb_data(NOTIFY_KEY);
121
122         talloc_set_destructor(notify, notify_destructor);
123
124         /* register with the messaging subsystem for the notify
125            message type */
126         messaging_register(notify->messaging_ctx, notify, 
127                            MSG_PVFS_NOTIFY, notify_handler);
128
129         notify->sys_notify_ctx = sys_notify_context_create(conn, notify, ev);
130
131         return notify;
132 }
133
134 bool notify_internal_parent_init(TALLOC_CTX *mem_ctx)
135 {
136         struct tdb_wrap *db1, *db2;
137
138         if (lp_clustering()) {
139                 return true;
140         }
141
142         /*
143          * Open the tdbs in the parent process (smbd) so that our
144          * CLEAR_IF_FIRST optimization in tdb_reopen_all can properly
145          * work.
146          */
147
148         db1 = tdb_wrap_open(mem_ctx, lock_path("notify.tdb"),
149                             0, TDB_SEQNUM|TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH,
150                            O_RDWR|O_CREAT, 0644);
151         if (db1 == NULL) {
152                 DEBUG(1, ("could not open notify.tdb: %s\n", strerror(errno)));
153                 return false;
154         }
155         db2 = tdb_wrap_open(mem_ctx, lock_path("notify_onelevel.tdb"),
156                             0, TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH, O_RDWR|O_CREAT, 0644);
157         if (db2 == NULL) {
158                 DEBUG(1, ("could not open notify_onelevel.tdb: %s\n",
159                           strerror(errno)));
160                 TALLOC_FREE(db1);
161                 return false;
162         }
163         return true;
164 }
165
166 /*
167   lock and fetch the record
168 */
169 static NTSTATUS notify_fetch_locked(struct notify_context *notify, struct db_record **rec)
170 {
171         *rec = notify->db_recursive->fetch_locked(notify->db_recursive,
172                                                   notify, notify->key);
173         if (*rec == NULL) {
174                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
175         }
176         return NT_STATUS_OK;
177 }
178
179 /*
180   load the notify array
181 */
182 static NTSTATUS notify_load(struct notify_context *notify, struct db_record *rec)
183 {
184         TDB_DATA dbuf;
185         DATA_BLOB blob;
186         NTSTATUS status;
187         int seqnum;
188
189         seqnum = notify->db_recursive->get_seqnum(notify->db_recursive);
190
191         if (seqnum == notify->seqnum && notify->array != NULL) {
192                 return NT_STATUS_OK;
193         }
194
195         notify->seqnum = seqnum;
196
197         talloc_free(notify->array);
198         notify->array = TALLOC_ZERO_P(notify, struct notify_array);
199         NT_STATUS_HAVE_NO_MEMORY(notify->array);
200
201         if (!rec) {
202                 if (notify->db_recursive->fetch(notify->db_recursive, notify,
203                                                 notify->key, &dbuf) != 0) {
204                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
205                 }
206         } else {
207                 dbuf = rec->value;
208         }
209
210         blob.data = (uint8 *)dbuf.dptr;
211         blob.length = dbuf.dsize;
212
213         status = NT_STATUS_OK;
214         if (blob.length > 0) {
215                 enum ndr_err_code ndr_err;
216                 ndr_err = ndr_pull_struct_blob(&blob, notify->array, notify->array,
217                                                (ndr_pull_flags_fn_t)ndr_pull_notify_array);
218                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
219                         /* 1. log that we got a corrupt notify_array
220                          * 2. clear the variable the garbage was stored into to not trip
221                          *  over it next time this method is entered with the same seqnum
222                          * 3. delete it from the database */
223                         DEBUG(2, ("notify_array is corrupt, discarding it\n"));
224
225                         ZERO_STRUCTP(notify->array);
226                         if (rec != NULL) {
227                                 rec->delete_rec(rec);
228                         }
229
230                 } else {
231                         if (DEBUGLEVEL >= 10) {
232                                 DEBUG(10, ("notify_load:\n"));
233                                 NDR_PRINT_DEBUG(notify_array, notify->array);
234                         }
235                 }
236         }
237
238
239         if (!rec) {
240                 talloc_free(dbuf.dptr);
241         }
242
243         return status;
244 }
245
246 /*
247   compare notify entries for sorting
248 */
249 static int notify_compare(const struct notify_entry *e1, const struct notify_entry *e2)
250 {
251         return strcmp(e1->path, e2->path);
252 }
253
254 /*
255   save the notify array
256 */
257 static NTSTATUS notify_save(struct notify_context *notify, struct db_record *rec)
258 {
259         TDB_DATA dbuf;
260         DATA_BLOB blob;
261         NTSTATUS status;
262         enum ndr_err_code ndr_err;
263         TALLOC_CTX *tmp_ctx;
264
265         /* if possible, remove some depth arrays */
266         while (notify->array->num_depths > 0 &&
267                notify->array->depth[notify->array->num_depths-1].num_entries == 0) {
268                 notify->array->num_depths--;
269         }
270
271         /* we might just be able to delete the record */
272         if (notify->array->num_depths == 0) {
273                 return rec->delete_rec(rec);
274         }
275
276         tmp_ctx = talloc_new(notify);
277         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
278
279         ndr_err = ndr_push_struct_blob(&blob, tmp_ctx, notify->array,
280                                       (ndr_push_flags_fn_t)ndr_push_notify_array);
281         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
282                 talloc_free(tmp_ctx);
283                 return ndr_map_error2ntstatus(ndr_err);
284         }
285
286         if (DEBUGLEVEL >= 10) {
287                 DEBUG(10, ("notify_save:\n"));
288                 NDR_PRINT_DEBUG(notify_array, notify->array);
289         }
290
291         dbuf.dptr = blob.data;
292         dbuf.dsize = blob.length;
293
294         status = rec->store(rec, dbuf, TDB_REPLACE);
295         talloc_free(tmp_ctx);
296
297         return status;
298 }
299
300
301 /*
302   handle incoming notify messages
303 */
304 static void notify_handler(struct messaging_context *msg_ctx, void *private_data, 
305                            uint32_t msg_type, struct server_id server_id, DATA_BLOB *data)
306 {
307         struct notify_context *notify = talloc_get_type(private_data, struct notify_context);
308         enum ndr_err_code ndr_err;
309         struct notify_event ev;
310         TALLOC_CTX *tmp_ctx = talloc_new(notify);
311         struct notify_list *listel;
312
313         if (tmp_ctx == NULL) {
314                 return;
315         }
316
317         ndr_err = ndr_pull_struct_blob(data, tmp_ctx, &ev,
318                                        (ndr_pull_flags_fn_t)ndr_pull_notify_event);
319         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
320                 talloc_free(tmp_ctx);
321                 return;
322         }
323
324         for (listel=notify->list;listel;listel=listel->next) {
325                 if (listel->private_data == ev.private_data) {
326                         listel->callback(listel->private_data, &ev);
327                         break;
328                 }
329         }
330
331         talloc_free(tmp_ctx);   
332 }
333
334 /*
335   callback from sys_notify telling us about changes from the OS
336 */
337 static void sys_notify_callback(struct sys_notify_context *ctx, 
338                                 void *ptr, struct notify_event *ev)
339 {
340         struct notify_list *listel = talloc_get_type(ptr, struct notify_list);
341         ev->private_data = listel;
342         DEBUG(10, ("sys_notify_callback called with action=%d, for %s\n",
343                    ev->action, ev->path));
344         listel->callback(listel->private_data, ev);
345 }
346
347 /*
348   add an entry to the notify array
349 */
350 static NTSTATUS notify_add_array(struct notify_context *notify, struct db_record *rec,
351                                  struct notify_entry *e,
352                                  void *private_data, int depth)
353 {
354         int i;
355         struct notify_depth *d;
356         struct notify_entry *ee;
357
358         /* possibly expand the depths array */
359         if (depth >= notify->array->num_depths) {
360                 d = talloc_realloc(notify->array, notify->array->depth, 
361                                    struct notify_depth, depth+1);
362                 NT_STATUS_HAVE_NO_MEMORY(d);
363                 for (i=notify->array->num_depths;i<=depth;i++) {
364                         ZERO_STRUCT(d[i]);
365                 }
366                 notify->array->depth = d;
367                 notify->array->num_depths = depth+1;
368         }
369         d = &notify->array->depth[depth];
370
371         /* expand the entries array */
372         ee = talloc_realloc(notify->array->depth, d->entries, struct notify_entry,
373                             d->num_entries+1);
374         NT_STATUS_HAVE_NO_MEMORY(ee);
375         d->entries = ee;
376
377         d->entries[d->num_entries] = *e;
378         d->entries[d->num_entries].private_data = private_data;
379         d->entries[d->num_entries].server = notify->server;
380         d->entries[d->num_entries].path_len = strlen(e->path);
381         d->num_entries++;
382
383         d->max_mask |= e->filter;
384         d->max_mask_subdir |= e->subdir_filter;
385
386         TYPESAFE_QSORT(d->entries, d->num_entries, notify_compare);
387
388         /* recalculate the maximum masks */
389         d->max_mask = 0;
390         d->max_mask_subdir = 0;
391
392         for (i=0;i<d->num_entries;i++) {
393                 d->max_mask |= d->entries[i].filter;
394                 d->max_mask_subdir |= d->entries[i].subdir_filter;
395         }
396
397         return notify_save(notify, rec);
398 }
399
400 /*
401   Add a non-recursive watch
402 */
403
404 static void notify_add_onelevel(struct notify_context *notify,
405                                 struct notify_entry *e, void *private_data)
406 {
407         struct notify_entry_array *array;
408         struct db_record *rec;
409         DATA_BLOB blob;
410         TDB_DATA dbuf;
411         enum ndr_err_code ndr_err;
412         NTSTATUS status;
413
414         array = talloc_zero(talloc_tos(), struct notify_entry_array);
415         if (array == NULL) {
416                 return;
417         }
418
419         rec = notify->db_onelevel->fetch_locked(
420                 notify->db_onelevel, talloc_tos(),
421                 make_tdb_data((uint8_t *)&e->dir_id, sizeof(e->dir_id)));
422         if (rec == NULL) {
423                 DEBUG(10, ("notify_add_onelevel: fetch_locked for %s failed"
424                            "\n", file_id_string_tos(&e->dir_id)));
425                 TALLOC_FREE(array);
426                 return;
427         }
428
429         blob.data = (uint8_t *)rec->value.dptr;
430         blob.length = rec->value.dsize;
431
432         if (blob.length > 0) {
433                 ndr_err = ndr_pull_struct_blob(&blob, array, array,
434                         (ndr_pull_flags_fn_t)ndr_pull_notify_entry_array);
435                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
436                         DEBUG(10, ("ndr_pull_notify_entry_array failed: %s\n",
437                                    ndr_errstr(ndr_err)));
438                         TALLOC_FREE(array);
439                         return;
440                 }
441                 if (DEBUGLEVEL >= 10) {
442                         DEBUG(10, ("notify_add_onelevel:\n"));
443                         NDR_PRINT_DEBUG(notify_entry_array, array);
444                 }
445         }
446
447         array->entries = talloc_realloc(array, array->entries,
448                                         struct notify_entry,
449                                         array->num_entries+1);
450         if (array->entries == NULL) {
451                 TALLOC_FREE(array);
452                 return;
453         }
454         array->entries[array->num_entries] = *e;
455         array->entries[array->num_entries].private_data = private_data;
456         array->entries[array->num_entries].server = notify->server;
457         array->num_entries += 1;
458
459         ndr_err = ndr_push_struct_blob(&blob, rec, array,
460                 (ndr_push_flags_fn_t)ndr_push_notify_entry_array);
461         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
462                 DEBUG(10, ("ndr_push_notify_entry_array failed: %s\n",
463                            ndr_errstr(ndr_err)));
464                 TALLOC_FREE(array);
465                 return;
466         }
467
468         if (DEBUGLEVEL >= 10) {
469                 DEBUG(10, ("notify_add_onelevel:\n"));
470                 NDR_PRINT_DEBUG(notify_entry_array, array);
471         }
472
473         dbuf.dptr = blob.data;
474         dbuf.dsize = blob.length;
475
476         status = rec->store(rec, dbuf, TDB_REPLACE);
477         TALLOC_FREE(array);
478         if (!NT_STATUS_IS_OK(status)) {
479                 DEBUG(10, ("notify_add_onelevel: store failed: %s\n",
480                            nt_errstr(status)));
481                 return;
482         }
483         e->filter = 0;
484         return;
485 }
486
487
488 /*
489   add a notify watch. This is called when a notify is first setup on a open
490   directory handle.
491 */
492 NTSTATUS notify_add(struct notify_context *notify, struct notify_entry *e0,
493                     void (*callback)(void *, const struct notify_event *), 
494                     void *private_data)
495 {
496         struct notify_entry e = *e0;
497         NTSTATUS status;
498         char *tmp_path = NULL;
499         struct notify_list *listel;
500         size_t len;
501         int depth;
502         struct db_record *rec;
503
504         /* see if change notify is enabled at all */
505         if (notify == NULL) {
506                 return NT_STATUS_NOT_IMPLEMENTED;
507         }
508
509         status = notify_fetch_locked(notify, &rec);
510         NT_STATUS_NOT_OK_RETURN(status);
511
512         status = notify_load(notify, rec);
513         if (!NT_STATUS_IS_OK(status)) {
514                 talloc_free(rec);
515                 return status;
516         }
517
518         /* cope with /. on the end of the path */
519         len = strlen(e.path);
520         if (len > 1 && e.path[len-1] == '.' && e.path[len-2] == '/') {
521                 tmp_path = talloc_strndup(notify, e.path, len-2);
522                 if (tmp_path == NULL) {
523                         status = NT_STATUS_NO_MEMORY;
524                         goto done;
525                 }
526                 e.path = tmp_path;
527         }
528
529         depth = count_chars(e.path, '/');
530
531         listel = TALLOC_ZERO_P(notify, struct notify_list);
532         if (listel == NULL) {
533                 status = NT_STATUS_NO_MEMORY;
534                 goto done;
535         }
536
537         listel->private_data = private_data;
538         listel->callback = callback;
539         listel->depth = depth;
540         DLIST_ADD(notify->list, listel);
541
542         /* ignore failures from sys_notify */
543         if (notify->sys_notify_ctx != NULL) {
544                 /*
545                   this call will modify e.filter and e.subdir_filter
546                   to remove bits handled by the backend
547                 */
548                 status = sys_notify_watch(notify->sys_notify_ctx, &e,
549                                           sys_notify_callback, listel, 
550                                           &listel->sys_notify_handle);
551                 if (NT_STATUS_IS_OK(status)) {
552                         talloc_steal(listel, listel->sys_notify_handle);
553                 }
554         }
555
556         if (e.filter != 0) {
557                 notify_add_onelevel(notify, &e, private_data);
558                 status = NT_STATUS_OK;
559         }
560
561         /* if the system notify handler couldn't handle some of the
562            filter bits, or couldn't handle a request for recursion
563            then we need to install it in the array used for the
564            intra-samba notify handling */
565         if (e.filter != 0 || e.subdir_filter != 0) {
566                 status = notify_add_array(notify, rec, &e, private_data, depth);
567         }
568
569 done:
570         talloc_free(rec);
571         talloc_free(tmp_path);
572
573         return status;
574 }
575
576 NTSTATUS notify_remove_onelevel(struct notify_context *notify,
577                                 const struct file_id *fid,
578                                 void *private_data)
579 {
580         struct notify_entry_array *array;
581         struct db_record *rec;
582         DATA_BLOB blob;
583         TDB_DATA dbuf;
584         enum ndr_err_code ndr_err;
585         NTSTATUS status;
586         int i;
587
588         if (notify == NULL) {
589                 return NT_STATUS_NOT_IMPLEMENTED;
590         }
591
592         array = talloc_zero(talloc_tos(), struct notify_entry_array);
593         if (array == NULL) {
594                 return NT_STATUS_NO_MEMORY;
595         }
596
597         rec = notify->db_onelevel->fetch_locked(
598                 notify->db_onelevel, array,
599                 make_tdb_data((uint8_t *)fid, sizeof(*fid)));
600         if (rec == NULL) {
601                 DEBUG(10, ("notify_remove_onelevel: fetch_locked for %s failed"
602                            "\n", file_id_string_tos(fid)));
603                 TALLOC_FREE(array);
604                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
605         }
606
607         blob.data = (uint8_t *)rec->value.dptr;
608         blob.length = rec->value.dsize;
609
610         if (blob.length > 0) {
611                 ndr_err = ndr_pull_struct_blob(&blob, array, array,
612                         (ndr_pull_flags_fn_t)ndr_pull_notify_entry_array);
613                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
614                         DEBUG(10, ("ndr_pull_notify_entry_array failed: %s\n",
615                                    ndr_errstr(ndr_err)));
616                         TALLOC_FREE(array);
617                         return ndr_map_error2ntstatus(ndr_err);
618                 }
619                 if (DEBUGLEVEL >= 10) {
620                         DEBUG(10, ("notify_remove_onelevel:\n"));
621                         NDR_PRINT_DEBUG(notify_entry_array, array);
622                 }
623         }
624
625         for (i=0; i<array->num_entries; i++) {
626                 if ((private_data == array->entries[i].private_data) &&
627                     cluster_id_equal(&notify->server,
628                                      &array->entries[i].server)) {
629                         break;
630                 }
631         }
632
633         if (i == array->num_entries) {
634                 TALLOC_FREE(array);
635                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
636         }
637
638         array->entries[i] = array->entries[array->num_entries-1];
639         array->num_entries -= 1;
640
641         if (array->num_entries == 0) {
642                 rec->delete_rec(rec);
643                 TALLOC_FREE(array);
644                 return NT_STATUS_OK;
645         }
646
647         ndr_err = ndr_push_struct_blob(&blob, rec, array,
648                 (ndr_push_flags_fn_t)ndr_push_notify_entry_array);
649         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
650                 DEBUG(10, ("ndr_push_notify_entry_array failed: %s\n",
651                            ndr_errstr(ndr_err)));
652                 TALLOC_FREE(array);
653                 return ndr_map_error2ntstatus(ndr_err);
654         }
655
656         if (DEBUGLEVEL >= 10) {
657                 DEBUG(10, ("notify_add_onelevel:\n"));
658                 NDR_PRINT_DEBUG(notify_entry_array, array);
659         }
660
661         dbuf.dptr = blob.data;
662         dbuf.dsize = blob.length;
663
664         status = rec->store(rec, dbuf, TDB_REPLACE);
665         TALLOC_FREE(array);
666         if (!NT_STATUS_IS_OK(status)) {
667                 DEBUG(10, ("notify_add_onelevel: store failed: %s\n",
668                            nt_errstr(status)));
669                 return status;
670         }
671         return NT_STATUS_OK;
672 }
673
674 /*
675   remove a notify watch. Called when the directory handle is closed
676 */
677 NTSTATUS notify_remove(struct notify_context *notify, void *private_data)
678 {
679         NTSTATUS status;
680         struct notify_list *listel;
681         int i, depth;
682         struct notify_depth *d;
683         struct db_record *rec;
684
685         /* see if change notify is enabled at all */
686         if (notify == NULL) {
687                 return NT_STATUS_NOT_IMPLEMENTED;
688         }
689
690         for (listel=notify->list;listel;listel=listel->next) {
691                 if (listel->private_data == private_data) {
692                         DLIST_REMOVE(notify->list, listel);
693                         break;
694                 }
695         }
696         if (listel == NULL) {
697                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
698         }
699
700         depth = listel->depth;
701
702         talloc_free(listel);
703
704         status = notify_fetch_locked(notify, &rec);
705         NT_STATUS_NOT_OK_RETURN(status);
706
707         status = notify_load(notify, rec);
708         if (!NT_STATUS_IS_OK(status)) {
709                 talloc_free(rec);
710                 return status;
711         }
712
713         if (depth >= notify->array->num_depths) {
714                 talloc_free(rec);
715                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
716         }
717
718         /* we only have to search at the depth of this element */
719         d = &notify->array->depth[depth];
720
721         for (i=0;i<d->num_entries;i++) {
722                 if (private_data == d->entries[i].private_data &&
723                     cluster_id_equal(&notify->server, &d->entries[i].server)) {
724                         break;
725                 }
726         }
727         if (i == d->num_entries) {
728                 talloc_free(rec);
729                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
730         }
731
732         if (i < d->num_entries-1) {
733                 memmove(&d->entries[i], &d->entries[i+1], 
734                         sizeof(d->entries[i])*(d->num_entries-(i+1)));
735         }
736         d->num_entries--;
737
738         status = notify_save(notify, rec);
739
740         talloc_free(rec);
741
742         return status;
743 }
744
745 /*
746   remove all notify watches for a messaging server
747 */
748 static NTSTATUS notify_remove_all(struct notify_context *notify,
749                                   const struct server_id *server)
750 {
751         NTSTATUS status;
752         int i, depth, del_count=0;
753         struct db_record *rec;
754
755         status = notify_fetch_locked(notify, &rec);
756         NT_STATUS_NOT_OK_RETURN(status);
757
758         status = notify_load(notify, rec);
759         if (!NT_STATUS_IS_OK(status)) {
760                 talloc_free(rec);
761                 return status;
762         }
763
764         /* we have to search for all entries across all depths, looking for matches
765            for the server id */
766         for (depth=0;depth<notify->array->num_depths;depth++) {
767                 struct notify_depth *d = &notify->array->depth[depth];
768                 for (i=0;i<d->num_entries;i++) {
769                         if (cluster_id_equal(server, &d->entries[i].server)) {
770                                 if (i < d->num_entries-1) {
771                                         memmove(&d->entries[i], &d->entries[i+1], 
772                                                 sizeof(d->entries[i])*(d->num_entries-(i+1)));
773                                 }
774                                 i--;
775                                 d->num_entries--;
776                                 del_count++;
777                         }
778                 }
779         }
780
781         if (del_count > 0) {
782                 status = notify_save(notify, rec);
783         }
784
785         talloc_free(rec);
786
787         return status;
788 }
789
790
791 /*
792   send a notify message to another messaging server
793 */
794 static NTSTATUS notify_send(struct notify_context *notify, struct notify_entry *e,
795                             const char *path, uint32_t action)
796 {
797         struct notify_event ev;
798         DATA_BLOB data;
799         NTSTATUS status;
800         enum ndr_err_code ndr_err;
801         TALLOC_CTX *tmp_ctx;
802
803         ev.action = action;
804         ev.path = path;
805         ev.private_data = e->private_data;
806
807         tmp_ctx = talloc_new(notify);
808
809         ndr_err = ndr_push_struct_blob(&data, tmp_ctx, &ev,
810                                        (ndr_push_flags_fn_t)ndr_push_notify_event);
811         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
812                 talloc_free(tmp_ctx);
813                 return ndr_map_error2ntstatus(ndr_err);
814         }
815
816         status = messaging_send(notify->messaging_ctx, e->server, 
817                                 MSG_PVFS_NOTIFY, &data);
818         talloc_free(tmp_ctx);
819         return status;
820 }
821
822 void notify_onelevel(struct notify_context *notify, uint32_t action,
823                      uint32_t filter, struct file_id fid, const char *name)
824 {
825         struct notify_entry_array *array;
826         TDB_DATA dbuf;
827         DATA_BLOB blob;
828         bool have_dead_entries = false;
829         int i;
830
831         if (notify == NULL) {
832                 return;
833         }
834
835         array = talloc_zero(talloc_tos(), struct notify_entry_array);
836         if (array == NULL) {
837                 return;
838         }
839
840         if (notify->db_onelevel->fetch(
841                     notify->db_onelevel, array,
842                     make_tdb_data((uint8_t *)&fid, sizeof(fid)),
843                     &dbuf) == -1) {
844                 TALLOC_FREE(array);
845                 return;
846         }
847
848         blob.data = (uint8 *)dbuf.dptr;
849         blob.length = dbuf.dsize;
850
851         if (blob.length > 0) {
852                 enum ndr_err_code ndr_err;
853                 ndr_err = ndr_pull_struct_blob(&blob, array, array,
854                         (ndr_pull_flags_fn_t)ndr_pull_notify_entry_array);
855                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
856                         DEBUG(10, ("ndr_pull_notify_entry_array failed: %s\n",
857                                    ndr_errstr(ndr_err)));
858                         TALLOC_FREE(array);
859                         return;
860                 }
861                 if (DEBUGLEVEL >= 10) {
862                         DEBUG(10, ("notify_onelevel:\n"));
863                         NDR_PRINT_DEBUG(notify_entry_array, array);
864                 }
865         }
866
867         for (i=0; i<array->num_entries; i++) {
868                 struct notify_entry *e = &array->entries[i];
869
870                 if ((e->filter & filter) != 0) {
871                         NTSTATUS status;
872
873                         status = notify_send(notify, e, name, action);
874                         if (NT_STATUS_EQUAL(
875                                     status, NT_STATUS_INVALID_HANDLE)) {
876                                 /*
877                                  * Mark the entry as dead. All entries have a
878                                  * path set. The marker used here is setting
879                                  * that to NULL.
880                                  */
881                                 e->path = NULL;
882                                 have_dead_entries = true;
883                         }
884                 }
885         }
886
887         if (!have_dead_entries) {
888                 TALLOC_FREE(array);
889                 return;
890         }
891
892         for (i=0; i<array->num_entries; i++) {
893                 struct notify_entry *e = &array->entries[i];
894                 if (e->path != NULL) {
895                         continue;
896                 }
897                 DEBUG(10, ("Deleting notify entries for process %s because "
898                            "it's gone\n", procid_str_static(&e->server)));
899                 /*
900                  * Potential TODO: This might need optimizing,
901                  * notify_remove_onelevel() does a fetch_locked() operation at
902                  * every call. But this would only matter if a process with
903                  * MANY notifies has died without shutting down properly.
904                  */
905                 notify_remove_onelevel(notify, &e->dir_id, e->private_data);
906         }
907
908         TALLOC_FREE(array);
909         return;
910 }
911
912 /*
913   trigger a notify message for anyone waiting on a matching event
914
915   This function is called a lot, and needs to be very fast. The unusual data structure
916   and traversal is designed to be fast in the average case, even for large numbers of
917   notifies
918 */
919 void notify_trigger(struct notify_context *notify,
920                     uint32_t action, uint32_t filter, const char *path)
921 {
922         NTSTATUS status;
923         int depth;
924         const char *p, *next_p;
925
926         DEBUG(10, ("notify_trigger called action=0x%x, filter=0x%x, "
927                    "path=%s\n", (unsigned)action, (unsigned)filter, path));
928
929         /* see if change notify is enabled at all */
930         if (notify == NULL) {
931                 return;
932         }
933
934  again:
935         status = notify_load(notify, NULL);
936         if (!NT_STATUS_IS_OK(status)) {
937                 return;
938         }
939
940         /* loop along the given path, working with each directory depth separately */
941         for (depth=0,p=path;
942              p && depth < notify->array->num_depths;
943              p=next_p,depth++) {
944                 int p_len = p - path;
945                 int min_i, max_i, i;
946                 struct notify_depth *d = &notify->array->depth[depth];
947                 next_p = strchr(p+1, '/');
948
949                 /* see if there are any entries at this depth */
950                 if (d->num_entries == 0) continue;
951
952                 /* try to skip based on the maximum mask. If next_p is
953                  NULL then we know it will be a 'this directory'
954                  match, otherwise it must be a subdir match */
955                 if (next_p != NULL) {
956                         if (0 == (filter & d->max_mask_subdir)) {
957                                 continue;
958                         }
959                 } else {
960                         if (0 == (filter & d->max_mask)) {
961                                 continue;
962                         }
963                 }
964
965                 /* we know there is an entry here worth looking
966                  for. Use a bisection search to find the first entry
967                  with a matching path */
968                 min_i = 0;
969                 max_i = d->num_entries-1;
970
971                 while (min_i < max_i) {
972                         struct notify_entry *e;
973                         int cmp;
974                         i = (min_i+max_i)/2;
975                         e = &d->entries[i];
976                         cmp = strncmp(path, e->path, p_len);
977                         if (cmp == 0) {
978                                 if (p_len == e->path_len) {
979                                         max_i = i;
980                                 } else {
981                                         max_i = i-1;
982                                 }
983                         } else if (cmp < 0) {
984                                 max_i = i-1;
985                         } else {
986                                 min_i = i+1;
987                         }
988                 }
989
990                 if (min_i != max_i) {
991                         /* none match */
992                         continue;
993                 }
994
995                 /* we now know that the entries start at min_i */
996                 for (i=min_i;i<d->num_entries;i++) {
997                         struct notify_entry *e = &d->entries[i];
998                         if (p_len != e->path_len ||
999                             strncmp(path, e->path, p_len) != 0) break;
1000                         if (next_p != NULL) {
1001                                 if (0 == (filter & e->subdir_filter)) {
1002                                         continue;
1003                                 }
1004                         } else {
1005                                 if (0 == (filter & e->filter)) {
1006                                         continue;
1007                                 }
1008                         }
1009                         status = notify_send(notify, e, path + e->path_len + 1,
1010                                              action);
1011
1012                         if (NT_STATUS_EQUAL(
1013                                     status, NT_STATUS_INVALID_HANDLE)) {
1014                                 struct server_id server = e->server;
1015
1016                                 DEBUG(10, ("Deleting notify entries for "
1017                                            "process %s because it's gone\n",
1018                                            procid_str_static(&e->server)));
1019                                 notify_remove_all(notify, &server);
1020                                 goto again;
1021                         }
1022                 }
1023         }
1024 }