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