2f07192a92e16f9802eb77399256f8fe8e828701
[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         size_t len = fsp_fullbasepath(fsp, NULL, 0);
255         char fullpath[len+1];
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         fsp_fullbasepath(fsp, fullpath, sizeof(fullpath));
271
272         /*
273          * Avoid /. at the end of the path name. notify can't deal with it.
274          */
275         if (len > 1 && fullpath[len-1] == '.' && fullpath[len-2] == '/') {
276                 fullpath[len-2] = '\0';
277         }
278
279         subdir_filter = recursive ? filter : 0;
280
281         if ((filter != 0) || (subdir_filter != 0)) {
282                 status = notify_add(fsp->conn->sconn->notify_ctx,
283                                     fullpath, filter, subdir_filter,
284                                     notify_callback, fsp);
285         }
286
287         return status;
288 }
289
290 NTSTATUS change_notify_add_request(struct smb_request *req,
291                                 uint32_t max_param,
292                                 uint32_t filter, bool recursive,
293                                 struct files_struct *fsp,
294                                 void (*reply_fn)(struct smb_request *req,
295                                         NTSTATUS error_code,
296                                         uint8_t *buf, size_t len))
297 {
298         struct notify_change_request *request = NULL;
299         struct notify_mid_map *map = NULL;
300         struct smbd_server_connection *sconn = req->sconn;
301
302         DEBUG(10, ("change_notify_add_request: Adding request for %s: "
303                    "max_param = %d\n", fsp_str_dbg(fsp), (int)max_param));
304
305         if (!(request = talloc(NULL, struct notify_change_request))
306             || !(map = talloc(request, struct notify_mid_map))) {
307                 TALLOC_FREE(request);
308                 return NT_STATUS_NO_MEMORY;
309         }
310
311         request->mid_map = map;
312         map->req = request;
313
314         request->req = talloc_move(request, &req);
315         request->max_param = max_param;
316         request->filter = filter;
317         request->fsp = fsp;
318         request->reply_fn = reply_fn;
319         request->backend_data = NULL;
320
321         DLIST_ADD_END(fsp->notify->requests, request);
322
323         map->mid = request->req->mid;
324         DLIST_ADD(sconn->smb1.notify_mid_maps, map);
325
326         return NT_STATUS_OK;
327 }
328
329 static void change_notify_remove_request(struct smbd_server_connection *sconn,
330                                          struct notify_change_request *remove_req)
331 {
332         files_struct *fsp;
333         struct notify_change_request *req;
334
335         /*
336          * Paranoia checks, the fsp referenced must must have the request in
337          * its list of pending requests
338          */
339
340         fsp = remove_req->fsp;
341         SMB_ASSERT(fsp->notify != NULL);
342
343         for (req = fsp->notify->requests; req; req = req->next) {
344                 if (req == remove_req) {
345                         break;
346                 }
347         }
348
349         if (req == NULL) {
350                 smb_panic("notify_req not found in fsp's requests");
351         }
352
353         DLIST_REMOVE(fsp->notify->requests, req);
354         DLIST_REMOVE(sconn->smb1.notify_mid_maps, req->mid_map);
355         TALLOC_FREE(req);
356 }
357
358 static void smbd_notify_cancel_by_map(struct notify_mid_map *map)
359 {
360         struct smb_request *smbreq = map->req->req;
361         struct smbd_server_connection *sconn = smbreq->sconn;
362         struct smbd_smb2_request *smb2req = smbreq->smb2req;
363         NTSTATUS notify_status = NT_STATUS_CANCELLED;
364
365         if (smb2req != NULL) {
366                 if (smb2req->session == NULL) {
367                         notify_status = STATUS_NOTIFY_CLEANUP;
368                 } else if (!NT_STATUS_IS_OK(smb2req->session->status)) {
369                         notify_status = STATUS_NOTIFY_CLEANUP;
370                 }
371                 if (smb2req->tcon == NULL) {
372                         notify_status = STATUS_NOTIFY_CLEANUP;
373                 } else if (!NT_STATUS_IS_OK(smb2req->tcon->status)) {
374                         notify_status = STATUS_NOTIFY_CLEANUP;
375                 }
376         }
377
378         change_notify_reply(smbreq, notify_status,
379                             0, NULL, map->req->reply_fn);
380         change_notify_remove_request(sconn, map->req);
381 }
382
383 /****************************************************************************
384  Delete entries by mid from the change notify pending queue. Always send reply.
385 *****************************************************************************/
386
387 void remove_pending_change_notify_requests_by_mid(
388         struct smbd_server_connection *sconn, uint64_t mid)
389 {
390         struct notify_mid_map *map;
391
392         for (map = sconn->smb1.notify_mid_maps; map; map = map->next) {
393                 if (map->mid == mid) {
394                         break;
395                 }
396         }
397
398         if (map == NULL) {
399                 return;
400         }
401
402         smbd_notify_cancel_by_map(map);
403 }
404
405 void smbd_notify_cancel_by_smbreq(const struct smb_request *smbreq)
406 {
407         struct smbd_server_connection *sconn = smbreq->sconn;
408         struct notify_mid_map *map;
409
410         for (map = sconn->smb1.notify_mid_maps; map; map = map->next) {
411                 if (map->req->req == smbreq) {
412                         break;
413                 }
414         }
415
416         if (map == NULL) {
417                 return;
418         }
419
420         smbd_notify_cancel_by_map(map);
421 }
422
423 static struct files_struct *smbd_notify_cancel_deleted_fn(
424         struct files_struct *fsp, void *private_data)
425 {
426         struct file_id *fid = talloc_get_type_abort(
427                 private_data, struct file_id);
428
429         if (file_id_equal(&fsp->file_id, fid)) {
430                 remove_pending_change_notify_requests_by_fid(
431                         fsp, NT_STATUS_DELETE_PENDING);
432         }
433         return NULL;
434 }
435
436 void smbd_notify_cancel_deleted(struct messaging_context *msg,
437                                 void *private_data, uint32_t msg_type,
438                                 struct server_id server_id, DATA_BLOB *data)
439 {
440         struct smbd_server_connection *sconn = talloc_get_type_abort(
441                 private_data, struct smbd_server_connection);
442         struct file_id *fid;
443         enum ndr_err_code ndr_err;
444
445         fid = talloc(talloc_tos(), struct file_id);
446         if (fid == NULL) {
447                 DEBUG(1, ("talloc failed\n"));
448                 return;
449         }
450
451         ndr_err = ndr_pull_struct_blob_all(
452                 data, fid, fid, (ndr_pull_flags_fn_t)ndr_pull_file_id);
453         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
454                 DEBUG(10, ("%s: ndr_pull_file_id failed: %s\n", __func__,
455                            ndr_errstr(ndr_err)));
456                 goto done;
457         }
458
459         files_forall(sconn, smbd_notify_cancel_deleted_fn, fid);
460
461 done:
462         TALLOC_FREE(fid);
463 }
464
465 /****************************************************************************
466  Delete entries by fnum from the change notify pending queue.
467 *****************************************************************************/
468
469 void remove_pending_change_notify_requests_by_fid(files_struct *fsp,
470                                                   NTSTATUS status)
471 {
472         if (fsp->notify == NULL) {
473                 return;
474         }
475
476         while (fsp->notify->requests != NULL) {
477                 change_notify_reply(fsp->notify->requests->req,
478                                     status, 0, NULL,
479                                     fsp->notify->requests->reply_fn);
480                 change_notify_remove_request(fsp->conn->sconn,
481                                              fsp->notify->requests);
482         }
483 }
484
485 void notify_fname(connection_struct *conn, uint32_t action, uint32_t filter,
486                   const char *path)
487 {
488         struct notify_context *notify_ctx = conn->sconn->notify_ctx;
489
490         if (path[0] == '.' && path[1] == '/') {
491                 path += 2;
492         }
493
494         notify_trigger(notify_ctx, action, filter, conn->connectpath, path);
495 }
496
497 static void notify_fsp(files_struct *fsp, struct timespec when,
498                        uint32_t action, const char *name)
499 {
500         struct notify_change_event *change, *changes;
501         char *tmp;
502
503         if (fsp->notify == NULL) {
504                 /*
505                  * Nobody is waiting, don't queue
506                  */
507                 return;
508         }
509
510         /*
511          * Someone has triggered a notify previously, queue the change for
512          * later.
513          */
514
515         if ((fsp->notify->num_changes > 1000) || (name == NULL)) {
516                 /*
517                  * The real number depends on the client buf, just provide a
518                  * guard against a DoS here.  If name == NULL the CN backend is
519                  * alerting us to a problem.  Possibly dropped events.  Clear
520                  * queued changes and send the catch-all response to the client
521                  * if a request is pending.
522                  */
523                 TALLOC_FREE(fsp->notify->changes);
524                 fsp->notify->num_changes = -1;
525                 if (fsp->notify->requests != NULL) {
526                         change_notify_reply(fsp->notify->requests->req,
527                                             NT_STATUS_OK,
528                                             fsp->notify->requests->max_param,
529                                             fsp->notify,
530                                             fsp->notify->requests->reply_fn);
531                         change_notify_remove_request(fsp->conn->sconn,
532                                                      fsp->notify->requests);
533                 }
534                 return;
535         }
536
537         /* If we've exceeded the server side queue or received a NULL name
538          * from the underlying CN implementation, don't queue up any more
539          * requests until we can send a catch-all response to the client */
540         if (fsp->notify->num_changes == -1) {
541                 return;
542         }
543
544         if (!(changes = talloc_realloc(
545                       fsp->notify, fsp->notify->changes,
546                       struct notify_change_event,
547                       fsp->notify->num_changes+1))) {
548                 DEBUG(0, ("talloc_realloc failed\n"));
549                 return;
550         }
551
552         fsp->notify->changes = changes;
553
554         change = &(fsp->notify->changes[fsp->notify->num_changes]);
555
556         if (!(tmp = talloc_strdup(changes, name))) {
557                 DEBUG(0, ("talloc_strdup failed\n"));
558                 return;
559         }
560
561         string_replace(tmp, '/', '\\');
562         change->name = tmp;     
563
564         change->when = when;
565         change->action = action;
566         fsp->notify->num_changes += 1;
567
568         if (fsp->notify->requests == NULL) {
569                 /*
570                  * Nobody is waiting, so don't send anything. The ot
571                  */
572                 return;
573         }
574
575         if (action == NOTIFY_ACTION_OLD_NAME) {
576                 /*
577                  * We have to send the two rename events in one reply. So hold
578                  * the first part back.
579                  */
580                 return;
581         }
582
583         /*
584          * Someone is waiting for the change, trigger the reply immediately.
585          *
586          * TODO: do we have to walk the lists of requests pending?
587          */
588
589         change_notify_reply(fsp->notify->requests->req,
590                             NT_STATUS_OK,
591                             fsp->notify->requests->max_param,
592                             fsp->notify,
593                             fsp->notify->requests->reply_fn);
594
595         change_notify_remove_request(fsp->conn->sconn, fsp->notify->requests);
596 }
597
598 char *notify_filter_string(TALLOC_CTX *mem_ctx, uint32_t filter)
599 {
600         char *result = NULL;
601
602         result = talloc_strdup(mem_ctx, "");
603
604         if (filter & FILE_NOTIFY_CHANGE_FILE_NAME)
605                 result = talloc_asprintf_append(result, "FILE_NAME|");
606         if (filter & FILE_NOTIFY_CHANGE_DIR_NAME)
607                 result = talloc_asprintf_append(result, "DIR_NAME|");
608         if (filter & FILE_NOTIFY_CHANGE_ATTRIBUTES)
609                 result = talloc_asprintf_append(result, "ATTRIBUTES|");
610         if (filter & FILE_NOTIFY_CHANGE_SIZE)
611                 result = talloc_asprintf_append(result, "SIZE|");
612         if (filter & FILE_NOTIFY_CHANGE_LAST_WRITE)
613                 result = talloc_asprintf_append(result, "LAST_WRITE|");
614         if (filter & FILE_NOTIFY_CHANGE_LAST_ACCESS)
615                 result = talloc_asprintf_append(result, "LAST_ACCESS|");
616         if (filter & FILE_NOTIFY_CHANGE_CREATION)
617                 result = talloc_asprintf_append(result, "CREATION|");
618         if (filter & FILE_NOTIFY_CHANGE_EA)
619                 result = talloc_asprintf_append(result, "EA|");
620         if (filter & FILE_NOTIFY_CHANGE_SECURITY)
621                 result = talloc_asprintf_append(result, "SECURITY|");
622         if (filter & FILE_NOTIFY_CHANGE_STREAM_NAME)
623                 result = talloc_asprintf_append(result, "STREAM_NAME|");
624         if (filter & FILE_NOTIFY_CHANGE_STREAM_SIZE)
625                 result = talloc_asprintf_append(result, "STREAM_SIZE|");
626         if (filter & FILE_NOTIFY_CHANGE_STREAM_WRITE)
627                 result = talloc_asprintf_append(result, "STREAM_WRITE|");
628
629         if (result == NULL) return NULL;
630         if (*result == '\0') return result;
631
632         result[strlen(result)-1] = '\0';
633         return result;
634 }
635
636 struct sys_notify_context *sys_notify_context_create(TALLOC_CTX *mem_ctx,
637                                                      struct tevent_context *ev)
638 {
639         struct sys_notify_context *ctx;
640
641         if (!(ctx = talloc(mem_ctx, struct sys_notify_context))) {
642                 DEBUG(0, ("talloc failed\n"));
643                 return NULL;
644         }
645
646         ctx->ev = ev;
647         ctx->private_data = NULL;
648         return ctx;
649 }