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