4837ca5bda46dd25abe1992d0ba0a0520379ffaa
[kai/samba-autobuild/.git] / source3 / smbd / notify.c
1 /*
2    Unix SMB/CIFS implementation.
3    change notify handling
4    Copyright (C) Andrew Tridgell 2000
5    Copyright (C) Jeremy Allison 1994-1998
6    Copyright (C) Volker Lendecke 2007
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "smbd/smbd.h"
24 #include "smbd/globals.h"
25 #include "../librpc/gen_ndr/ndr_notify.h"
26 #include "librpc/gen_ndr/ndr_file_id.h"
27
28 struct notify_change_event {
29         struct timespec when;
30         uint32_t action;
31         const char *name;
32 };
33
34 struct notify_change_buf {
35         /*
36          * Filters for reinitializing after notifyd has been restarted
37          */
38         uint32_t filter;
39         uint32_t subdir_filter;
40
41         /*
42          * If no requests are pending, changes are queued here. Simple array,
43          * we only append.
44          */
45
46         /*
47          * num_changes == -1 means that we have got a catch-all change, when
48          * asked we just return NT_STATUS_OK without specific changes.
49          */
50         int num_changes;
51         struct notify_change_event *changes;
52
53         /*
54          * If no changes are around requests are queued here. Using a linked
55          * list, because we have to append at the end and delete from the top.
56          */
57         struct notify_change_request *requests;
58 };
59
60 struct notify_change_request {
61         struct notify_change_request *prev, *next;
62         struct files_struct *fsp;       /* backpointer for cancel by mid */
63         struct smb_request *req;
64         uint32_t filter;
65         uint32_t max_param;
66         void (*reply_fn)(struct smb_request *req,
67                          NTSTATUS error_code,
68                          uint8_t *buf, size_t len);
69         struct notify_mid_map *mid_map;
70         void *backend_data;
71 };
72
73 static void notify_fsp(files_struct *fsp, struct timespec when,
74                        uint32_t action, const char *name);
75
76 bool change_notify_fsp_has_changes(struct files_struct *fsp)
77 {
78         if (fsp == NULL) {
79                 return false;
80         }
81
82         if (fsp->notify == NULL) {
83                 return false;
84         }
85
86         if (fsp->notify->num_changes == 0) {
87                 return false;
88         }
89
90         return true;
91 }
92
93 /*
94  * For NTCancel, we need to find the notify_change_request indexed by
95  * mid. Separate list here.
96  */
97
98 struct notify_mid_map {
99         struct notify_mid_map *prev, *next;
100         struct notify_change_request *req;
101         uint64_t mid;
102 };
103
104 static bool notify_change_record_identical(struct notify_change_event *c1,
105                                            struct notify_change_event *c2)
106 {
107         /* Note this is deliberately case sensitive. */
108         if (c1->action == c2->action &&
109                         strcmp(c1->name, c2->name) == 0) {
110                 return True;
111         }
112         return False;
113 }
114
115 static int compare_notify_change_events(const void *p1, const void *p2)
116 {
117         const struct notify_change_event *e1 = p1;
118         const struct notify_change_event *e2 = p2;
119
120         return timespec_compare(&e1->when, &e2->when);
121 }
122
123 static bool notify_marshall_changes(int num_changes,
124                                 uint32_t max_offset,
125                                 struct notify_change_event *changes,
126                                 DATA_BLOB *final_blob)
127 {
128         int i;
129
130         if (num_changes == -1) {
131                 return false;
132         }
133
134         /*
135          * Sort the notifies by timestamp when the event happened to avoid
136          * coalescing and thus dropping events.
137          */
138
139         qsort(changes, num_changes,
140               sizeof(*changes), compare_notify_change_events);
141
142         for (i=0; i<num_changes; i++) {
143                 enum ndr_err_code ndr_err;
144                 struct notify_change_event *c;
145                 struct FILE_NOTIFY_INFORMATION m;
146                 DATA_BLOB blob;
147                 uint16_t pad = 0;
148
149                 /* Coalesce any identical records. */
150                 while (i+1 < num_changes &&
151                         notify_change_record_identical(&changes[i],
152                                                 &changes[i+1])) {
153                         i++;
154                 }
155
156                 c = &changes[i];
157
158                 m.FileName1 = c->name;
159                 m.FileNameLength = strlen_m(c->name)*2;
160                 m.Action = c->action;
161
162                 m._pad = data_blob_null;
163
164                 /*
165                  * Offset to next entry, only if there is one
166                  */
167
168                 if (i == (num_changes-1)) {
169                         m.NextEntryOffset = 0;
170                 } else {
171                         if ((m.FileNameLength % 4) == 2) {
172                                 m._pad = data_blob_const(&pad, 2);
173                         }
174                         m.NextEntryOffset =
175                                 ndr_size_FILE_NOTIFY_INFORMATION(&m, 0);
176                 }
177
178                 ndr_err = ndr_push_struct_blob(&blob, talloc_tos(), &m,
179                         (ndr_push_flags_fn_t)ndr_push_FILE_NOTIFY_INFORMATION);
180                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
181                         return false;
182                 }
183
184                 if (DEBUGLEVEL >= 10) {
185                         NDR_PRINT_DEBUG(FILE_NOTIFY_INFORMATION, &m);
186                 }
187
188                 if (!data_blob_append(talloc_tos(), final_blob,
189                                       blob.data, blob.length)) {
190                         data_blob_free(&blob);
191                         return false;
192                 }
193
194                 data_blob_free(&blob);
195
196                 if (final_blob->length > max_offset) {
197                         /* Too much data for client. */
198                         DEBUG(10, ("Client only wanted %d bytes, trying to "
199                                    "marshall %d bytes\n", (int)max_offset,
200                                    (int)final_blob->length));
201                         return False;
202                 }
203         }
204
205         return True;
206 }
207
208 /****************************************************************************
209  Setup the common parts of the return packet and send it.
210 *****************************************************************************/
211
212 void change_notify_reply(struct smb_request *req,
213                          NTSTATUS error_code,
214                          uint32_t max_param,
215                          struct notify_change_buf *notify_buf,
216                          void (*reply_fn)(struct smb_request *req,
217                                           NTSTATUS error_code,
218                                           uint8_t *buf, size_t len))
219 {
220         DATA_BLOB blob = data_blob_null;
221
222         if (!NT_STATUS_IS_OK(error_code)) {
223                 reply_fn(req, error_code, NULL, 0);
224                 return;
225         }
226
227         if (max_param == 0 || notify_buf == NULL) {
228                 reply_fn(req, NT_STATUS_OK, NULL, 0);
229                 return;
230         }
231
232         if (!notify_marshall_changes(notify_buf->num_changes, max_param,
233                                         notify_buf->changes, &blob)) {
234                 /*
235                  * We exceed what the client is willing to accept. Send
236                  * nothing.
237                  */
238                 data_blob_free(&blob);
239         }
240
241         reply_fn(req, NT_STATUS_OK, blob.data, blob.length);
242
243         data_blob_free(&blob);
244
245         TALLOC_FREE(notify_buf->changes);
246         notify_buf->num_changes = 0;
247 }
248
249 struct notify_fsp_state {
250         struct files_struct *notified_fsp;
251         struct timespec when;
252         const struct notify_event *e;
253 };
254
255 static struct files_struct *notify_fsp_cb(struct files_struct *fsp,
256                                           void *private_data)
257 {
258         struct notify_fsp_state *state = private_data;
259
260         if (fsp == state->notified_fsp) {
261                 DBG_DEBUG("notify_callback called for %s\n", fsp_str_dbg(fsp));
262                 notify_fsp(fsp, state->when, state->e->action, state->e->path);
263                 return fsp;
264         }
265
266         return NULL;
267 }
268
269 void notify_callback(struct smbd_server_connection *sconn,
270                      void *private_data, struct timespec when,
271                      const struct notify_event *e)
272 {
273         struct notify_fsp_state state = {
274                 .notified_fsp = private_data, .when = when, .e = e
275         };
276         files_forall(sconn, notify_fsp_cb, &state);
277 }
278
279 NTSTATUS change_notify_create(struct files_struct *fsp, uint32_t filter,
280                               bool recursive)
281 {
282         size_t len = fsp_fullbasepath(fsp, NULL, 0);
283         char fullpath[len+1];
284         NTSTATUS status = NT_STATUS_NOT_IMPLEMENTED;
285
286         if (fsp->notify != NULL) {
287                 DEBUG(1, ("change_notify_create: fsp->notify != NULL, "
288                           "fname = %s\n", fsp->fsp_name->base_name));
289                 return NT_STATUS_INVALID_PARAMETER;
290         }
291
292         if (!(fsp->notify = talloc_zero(NULL, struct notify_change_buf))) {
293                 DEBUG(0, ("talloc failed\n"));
294                 return NT_STATUS_NO_MEMORY;
295         }
296         fsp->notify->filter = filter;
297         fsp->notify->subdir_filter = recursive ? filter : 0;
298
299         fsp_fullbasepath(fsp, fullpath, sizeof(fullpath));
300
301         /*
302          * Avoid /. at the end of the path name. notify can't deal with it.
303          */
304         if (len > 1 && fullpath[len-1] == '.' && fullpath[len-2] == '/') {
305                 fullpath[len-2] = '\0';
306         }
307
308         if ((fsp->notify->filter != 0) ||
309             (fsp->notify->subdir_filter != 0)) {
310                 status = notify_add(fsp->conn->sconn->notify_ctx,
311                                     fullpath, fsp->notify->filter,
312                                     fsp->notify->subdir_filter, fsp);
313         }
314
315         return status;
316 }
317
318 NTSTATUS change_notify_add_request(struct smb_request *req,
319                                 uint32_t max_param,
320                                 uint32_t filter, bool recursive,
321                                 struct files_struct *fsp,
322                                 void (*reply_fn)(struct smb_request *req,
323                                         NTSTATUS error_code,
324                                         uint8_t *buf, size_t len))
325 {
326         struct notify_change_request *request = NULL;
327         struct notify_mid_map *map = NULL;
328         struct smbd_server_connection *sconn = req->sconn;
329
330         DEBUG(10, ("change_notify_add_request: Adding request for %s: "
331                    "max_param = %d\n", fsp_str_dbg(fsp), (int)max_param));
332
333         if (!(request = talloc(NULL, struct notify_change_request))
334             || !(map = talloc(request, struct notify_mid_map))) {
335                 TALLOC_FREE(request);
336                 return NT_STATUS_NO_MEMORY;
337         }
338
339         request->mid_map = map;
340         map->req = request;
341
342         request->req = talloc_move(request, &req);
343         request->max_param = max_param;
344         request->filter = filter;
345         request->fsp = fsp;
346         request->reply_fn = reply_fn;
347         request->backend_data = NULL;
348
349         DLIST_ADD_END(fsp->notify->requests, request);
350
351         map->mid = request->req->mid;
352         DLIST_ADD(sconn->smb1.notify_mid_maps, map);
353
354         return NT_STATUS_OK;
355 }
356
357 static void change_notify_remove_request(struct smbd_server_connection *sconn,
358                                          struct notify_change_request *remove_req)
359 {
360         files_struct *fsp;
361         struct notify_change_request *req;
362
363         /*
364          * Paranoia checks, the fsp referenced must must have the request in
365          * its list of pending requests
366          */
367
368         fsp = remove_req->fsp;
369         SMB_ASSERT(fsp->notify != NULL);
370
371         for (req = fsp->notify->requests; req; req = req->next) {
372                 if (req == remove_req) {
373                         break;
374                 }
375         }
376
377         if (req == NULL) {
378                 smb_panic("notify_req not found in fsp's requests");
379         }
380
381         DLIST_REMOVE(fsp->notify->requests, req);
382         DLIST_REMOVE(sconn->smb1.notify_mid_maps, req->mid_map);
383         TALLOC_FREE(req);
384 }
385
386 static void smbd_notify_cancel_by_map(struct notify_mid_map *map)
387 {
388         struct smb_request *smbreq = map->req->req;
389         struct smbd_server_connection *sconn = smbreq->sconn;
390         struct smbd_smb2_request *smb2req = smbreq->smb2req;
391         NTSTATUS notify_status = NT_STATUS_CANCELLED;
392
393         if (smb2req != NULL) {
394                 if (smb2req->session == NULL) {
395                         notify_status = STATUS_NOTIFY_CLEANUP;
396                 } else if (!NT_STATUS_IS_OK(smb2req->session->status)) {
397                         notify_status = STATUS_NOTIFY_CLEANUP;
398                 }
399                 if (smb2req->tcon == NULL) {
400                         notify_status = STATUS_NOTIFY_CLEANUP;
401                 } else if (!NT_STATUS_IS_OK(smb2req->tcon->status)) {
402                         notify_status = STATUS_NOTIFY_CLEANUP;
403                 }
404         }
405
406         change_notify_reply(smbreq, notify_status,
407                             0, NULL, map->req->reply_fn);
408         change_notify_remove_request(sconn, map->req);
409 }
410
411 /****************************************************************************
412  Delete entries by mid from the change notify pending queue. Always send reply.
413 *****************************************************************************/
414
415 void remove_pending_change_notify_requests_by_mid(
416         struct smbd_server_connection *sconn, uint64_t mid)
417 {
418         struct notify_mid_map *map;
419
420         for (map = sconn->smb1.notify_mid_maps; map; map = map->next) {
421                 if (map->mid == mid) {
422                         break;
423                 }
424         }
425
426         if (map == NULL) {
427                 return;
428         }
429
430         smbd_notify_cancel_by_map(map);
431 }
432
433 void smbd_notify_cancel_by_smbreq(const struct smb_request *smbreq)
434 {
435         struct smbd_server_connection *sconn = smbreq->sconn;
436         struct notify_mid_map *map;
437
438         for (map = sconn->smb1.notify_mid_maps; map; map = map->next) {
439                 if (map->req->req == smbreq) {
440                         break;
441                 }
442         }
443
444         if (map == NULL) {
445                 return;
446         }
447
448         smbd_notify_cancel_by_map(map);
449 }
450
451 static struct files_struct *smbd_notify_cancel_deleted_fn(
452         struct files_struct *fsp, void *private_data)
453 {
454         struct file_id *fid = talloc_get_type_abort(
455                 private_data, struct file_id);
456
457         if (file_id_equal(&fsp->file_id, fid)) {
458                 remove_pending_change_notify_requests_by_fid(
459                         fsp, NT_STATUS_DELETE_PENDING);
460         }
461         return NULL;
462 }
463
464 void smbd_notify_cancel_deleted(struct messaging_context *msg,
465                                 void *private_data, uint32_t msg_type,
466                                 struct server_id server_id, DATA_BLOB *data)
467 {
468         struct smbd_server_connection *sconn = talloc_get_type_abort(
469                 private_data, struct smbd_server_connection);
470         struct file_id *fid;
471         enum ndr_err_code ndr_err;
472
473         fid = talloc(talloc_tos(), struct file_id);
474         if (fid == NULL) {
475                 DEBUG(1, ("talloc failed\n"));
476                 return;
477         }
478
479         ndr_err = ndr_pull_struct_blob_all(
480                 data, fid, fid, (ndr_pull_flags_fn_t)ndr_pull_file_id);
481         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
482                 DEBUG(10, ("%s: ndr_pull_file_id failed: %s\n", __func__,
483                            ndr_errstr(ndr_err)));
484                 goto done;
485         }
486
487         files_forall(sconn, smbd_notify_cancel_deleted_fn, fid);
488
489 done:
490         TALLOC_FREE(fid);
491 }
492
493 /****************************************************************************
494  Delete entries by fnum from the change notify pending queue.
495 *****************************************************************************/
496
497 void remove_pending_change_notify_requests_by_fid(files_struct *fsp,
498                                                   NTSTATUS status)
499 {
500         if (fsp->notify == NULL) {
501                 return;
502         }
503
504         while (fsp->notify->requests != NULL) {
505                 change_notify_reply(fsp->notify->requests->req,
506                                     status, 0, NULL,
507                                     fsp->notify->requests->reply_fn);
508                 change_notify_remove_request(fsp->conn->sconn,
509                                              fsp->notify->requests);
510         }
511 }
512
513 void notify_fname(connection_struct *conn, uint32_t action, uint32_t filter,
514                   const char *path)
515 {
516         struct notify_context *notify_ctx = conn->sconn->notify_ctx;
517
518         if (path[0] == '.' && path[1] == '/') {
519                 path += 2;
520         }
521
522         notify_trigger(notify_ctx, action, filter, conn->connectpath, path);
523 }
524
525 static void notify_fsp(files_struct *fsp, struct timespec when,
526                        uint32_t action, const char *name)
527 {
528         struct notify_change_event *change, *changes;
529         char *tmp;
530
531         if (fsp->notify == NULL) {
532                 /*
533                  * Nobody is waiting, don't queue
534                  */
535                 return;
536         }
537
538         /*
539          * Someone has triggered a notify previously, queue the change for
540          * later.
541          */
542
543         if ((fsp->notify->num_changes > 1000) || (name == NULL)) {
544                 /*
545                  * The real number depends on the client buf, just provide a
546                  * guard against a DoS here.  If name == NULL the CN backend is
547                  * alerting us to a problem.  Possibly dropped events.  Clear
548                  * queued changes and send the catch-all response to the client
549                  * if a request is pending.
550                  */
551                 TALLOC_FREE(fsp->notify->changes);
552                 fsp->notify->num_changes = -1;
553                 if (fsp->notify->requests != NULL) {
554                         change_notify_reply(fsp->notify->requests->req,
555                                             NT_STATUS_OK,
556                                             fsp->notify->requests->max_param,
557                                             fsp->notify,
558                                             fsp->notify->requests->reply_fn);
559                         change_notify_remove_request(fsp->conn->sconn,
560                                                      fsp->notify->requests);
561                 }
562                 return;
563         }
564
565         /* If we've exceeded the server side queue or received a NULL name
566          * from the underlying CN implementation, don't queue up any more
567          * requests until we can send a catch-all response to the client */
568         if (fsp->notify->num_changes == -1) {
569                 return;
570         }
571
572         if (!(changes = talloc_realloc(
573                       fsp->notify, fsp->notify->changes,
574                       struct notify_change_event,
575                       fsp->notify->num_changes+1))) {
576                 DEBUG(0, ("talloc_realloc failed\n"));
577                 return;
578         }
579
580         fsp->notify->changes = changes;
581
582         change = &(fsp->notify->changes[fsp->notify->num_changes]);
583
584         if (!(tmp = talloc_strdup(changes, name))) {
585                 DEBUG(0, ("talloc_strdup failed\n"));
586                 return;
587         }
588
589         string_replace(tmp, '/', '\\');
590         change->name = tmp;     
591
592         change->when = when;
593         change->action = action;
594         fsp->notify->num_changes += 1;
595
596         if (fsp->notify->requests == NULL) {
597                 /*
598                  * Nobody is waiting, so don't send anything. The ot
599                  */
600                 return;
601         }
602
603         if (action == NOTIFY_ACTION_OLD_NAME) {
604                 /*
605                  * We have to send the two rename events in one reply. So hold
606                  * the first part back.
607                  */
608                 return;
609         }
610
611         /*
612          * Someone is waiting for the change, trigger the reply immediately.
613          *
614          * TODO: do we have to walk the lists of requests pending?
615          */
616
617         change_notify_reply(fsp->notify->requests->req,
618                             NT_STATUS_OK,
619                             fsp->notify->requests->max_param,
620                             fsp->notify,
621                             fsp->notify->requests->reply_fn);
622
623         change_notify_remove_request(fsp->conn->sconn, fsp->notify->requests);
624 }
625
626 char *notify_filter_string(TALLOC_CTX *mem_ctx, uint32_t filter)
627 {
628         char *result = NULL;
629
630         result = talloc_strdup(mem_ctx, "");
631
632         if (filter & FILE_NOTIFY_CHANGE_FILE_NAME)
633                 result = talloc_asprintf_append(result, "FILE_NAME|");
634         if (filter & FILE_NOTIFY_CHANGE_DIR_NAME)
635                 result = talloc_asprintf_append(result, "DIR_NAME|");
636         if (filter & FILE_NOTIFY_CHANGE_ATTRIBUTES)
637                 result = talloc_asprintf_append(result, "ATTRIBUTES|");
638         if (filter & FILE_NOTIFY_CHANGE_SIZE)
639                 result = talloc_asprintf_append(result, "SIZE|");
640         if (filter & FILE_NOTIFY_CHANGE_LAST_WRITE)
641                 result = talloc_asprintf_append(result, "LAST_WRITE|");
642         if (filter & FILE_NOTIFY_CHANGE_LAST_ACCESS)
643                 result = talloc_asprintf_append(result, "LAST_ACCESS|");
644         if (filter & FILE_NOTIFY_CHANGE_CREATION)
645                 result = talloc_asprintf_append(result, "CREATION|");
646         if (filter & FILE_NOTIFY_CHANGE_EA)
647                 result = talloc_asprintf_append(result, "EA|");
648         if (filter & FILE_NOTIFY_CHANGE_SECURITY)
649                 result = talloc_asprintf_append(result, "SECURITY|");
650         if (filter & FILE_NOTIFY_CHANGE_STREAM_NAME)
651                 result = talloc_asprintf_append(result, "STREAM_NAME|");
652         if (filter & FILE_NOTIFY_CHANGE_STREAM_SIZE)
653                 result = talloc_asprintf_append(result, "STREAM_SIZE|");
654         if (filter & FILE_NOTIFY_CHANGE_STREAM_WRITE)
655                 result = talloc_asprintf_append(result, "STREAM_WRITE|");
656
657         if (result == NULL) return NULL;
658         if (*result == '\0') return result;
659
660         result[strlen(result)-1] = '\0';
661         return result;
662 }
663
664 struct sys_notify_context *sys_notify_context_create(TALLOC_CTX *mem_ctx,
665                                                      struct tevent_context *ev)
666 {
667         struct sys_notify_context *ctx;
668
669         if (!(ctx = talloc(mem_ctx, struct sys_notify_context))) {
670                 DEBUG(0, ("talloc failed\n"));
671                 return NULL;
672         }
673
674         ctx->ev = ev;
675         ctx->private_data = NULL;
676         return ctx;
677 }