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