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