r20856: Make "struct notify_mid_map" private to notify.c
[ddiss/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
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 static struct cnotify_fns *cnotify;
25 static struct notify_mid_map *notify_changes_by_mid;
26
27 /****************************************************************************
28  This is the structure to queue to implement NT change
29  notify. It consists of smb_size bytes stored from the
30  transact command (to keep the mid, tid etc around).
31  Plus the fid to examine and notify private data.
32 *****************************************************************************/
33
34 struct change_notify {
35         struct change_notify *next, *prev;
36         files_struct *fsp;
37         uint32 flags;
38         uint32 max_param_count;
39         char request_buf[smb_size];
40         void *change_data;
41 };
42
43 /*
44  * For NTCancel, we need to find the notify_change_request indexed by
45  * mid. Separate list here.
46  */
47
48 struct notify_mid_map {
49         struct notify_mid_map *prev, *next;
50         struct notify_change_request *req;
51         uint16 mid;
52 };
53
54 static struct change_notify *change_notify_list;
55
56 static BOOL notify_marshall_changes(unsigned num_changes,
57                                     struct notify_change *changes,
58                                     prs_struct *ps)
59 {
60         int i;
61         UNISTR uni_name;
62
63         for (i=0; i<num_changes; i++) {
64                 struct notify_change *c = &changes[i];
65                 size_t namelen;
66                 uint32 u32_tmp; /* Temp arg to prs_uint32 to avoid
67                                  * signed/unsigned issues */
68
69                 namelen = convert_string_allocate(
70                         NULL, CH_UNIX, CH_UTF16LE, c->name, strlen(c->name)+1,
71                         &uni_name.buffer, True);
72                 if ((namelen == -1) || (uni_name.buffer == NULL)) {
73                         goto fail;
74                 }
75
76                 namelen -= 2;   /* Dump NULL termination */
77
78                 /*
79                  * Offset to next entry, only if there is one
80                  */
81
82                 u32_tmp = (i == num_changes-1) ? 0 : namelen + 12;
83                 if (!prs_uint32("offset", ps, 1, &u32_tmp)) goto fail;
84
85                 u32_tmp = c->action;
86                 if (!prs_uint32("action", ps, 1, &u32_tmp)) goto fail;
87
88                 u32_tmp = namelen;
89                 if (!prs_uint32("namelen", ps, 1, &u32_tmp)) goto fail;
90
91                 if (!prs_unistr("name", ps, 1, &uni_name)) goto fail;
92
93                 /*
94                  * Not NULL terminated, decrease by the 2 UCS2 \0 chars
95                  */
96                 prs_set_offset(ps, prs_offset(ps)-2);
97
98                 SAFE_FREE(uni_name.buffer);
99         }
100
101         return True;
102
103  fail:
104         SAFE_FREE(uni_name.buffer);
105         return False;
106 }
107
108 /****************************************************************************
109  Setup the common parts of the return packet and send it.
110 *****************************************************************************/
111
112 void change_notify_reply_packet(const char *request_buf, NTSTATUS error_code)
113 {
114         char outbuf[smb_size+38];
115
116         memset(outbuf, '\0', sizeof(outbuf));
117         construct_reply_common(request_buf, outbuf);
118
119         ERROR_NT(error_code);
120
121         /*
122          * Seems NT needs a transact command with an error code
123          * in it. This is a longer packet than a simple error.
124          */
125         set_message(outbuf,18,0,False);
126
127         show_msg(outbuf);
128         if (!send_smb(smbd_server_fd(),outbuf))
129                 exit_server_cleanly("change_notify_reply_packet: send_smb failed.");
130 }
131
132 void change_notify_reply(const char *request_buf, uint32 max_param_count,
133                          unsigned num_changes, struct notify_change *changes)
134 {
135         char *outbuf = NULL;
136         prs_struct ps;
137         size_t buflen = smb_size+38+max_param_count;
138
139         if (!prs_init(&ps, 0, NULL, False)
140             || !notify_marshall_changes(num_changes, changes, &ps)) {
141                 change_notify_reply_packet(request_buf, NT_STATUS_NO_MEMORY);
142                 goto done;
143         }
144
145         if (prs_offset(&ps) > max_param_count) {
146                 /*
147                  * We exceed what the client is willing to accept. Send
148                  * nothing.
149                  */
150                 change_notify_reply_packet(request_buf, NT_STATUS_OK);
151                 goto done;
152         }
153
154         if (!(outbuf = SMB_MALLOC_ARRAY(char, buflen))) {
155                 change_notify_reply_packet(request_buf, NT_STATUS_NO_MEMORY);
156                 goto done;
157         }
158
159         construct_reply_common(request_buf, outbuf);
160
161         if (send_nt_replies(outbuf, buflen, NT_STATUS_OK, prs_data_p(&ps),
162                             prs_offset(&ps), NULL, 0) == -1) {
163                 exit_server("change_notify_reply_packet: send_smb failed.");
164         }
165
166  done:
167         SAFE_FREE(outbuf);
168         prs_mem_free(&ps);
169 }
170
171 /****************************************************************************
172  Remove an entry from the list and free it, also closing any
173  directory handle if necessary.
174 *****************************************************************************/
175
176 static void change_notify_remove(struct change_notify *cnbp)
177 {
178         cnotify->remove_notify(cnbp->change_data);
179         DLIST_REMOVE(change_notify_list, cnbp);
180         ZERO_STRUCTP(cnbp);
181         SAFE_FREE(cnbp);
182 }
183
184 NTSTATUS change_notify_add_request(const char *inbuf, uint32 max_param_count,
185                                    uint32 filter, struct files_struct *fsp)
186 {
187         struct notify_change_request *request = NULL;
188         struct notify_mid_map *map = NULL;
189
190         if (!(request = SMB_MALLOC_P(struct notify_change_request))
191             || !(map = SMB_MALLOC_P(struct notify_mid_map))) {
192                 SAFE_FREE(request);
193                 return NT_STATUS_NO_MEMORY;
194         }
195
196         request->mid_map = map;
197         map->req = request;
198
199         memcpy(request->request_buf, inbuf, sizeof(request->request_buf));
200         request->max_param_count = max_param_count;
201         request->filter = filter;
202         request->fsp = fsp;
203         DLIST_ADD_END(fsp->notify->requests, request,
204                       struct notify_change_request *);
205
206         map->mid = SVAL(inbuf, smb_mid);
207         DLIST_ADD(notify_changes_by_mid, map);
208
209         /* Push the MID of this packet on the signing queue. */
210         srv_defer_sign_response(SVAL(inbuf,smb_mid));
211
212         return NT_STATUS_OK;
213 }
214
215 static void change_notify_remove_request(struct notify_change_request *remove_req)
216 {
217         files_struct *fsp;
218         struct notify_change_request *req;
219
220         /*
221          * Paranoia checks, the fsp referenced must must have the request in
222          * its list of pending requests
223          */
224
225         fsp = remove_req->fsp;
226         SMB_ASSERT(fsp->notify != NULL);
227
228         for (req = fsp->notify->requests; req; req = req->next) {
229                 if (req == remove_req) {
230                         break;
231                 }
232         }
233
234         if (req == NULL) {
235                 smb_panic("notify_req not found in fsp's requests\n");
236         }
237
238         DLIST_REMOVE(fsp->notify->requests, req);
239         DLIST_REMOVE(notify_changes_by_mid, req->mid_map);
240         SAFE_FREE(req->mid_map);
241         SAFE_FREE(req);
242 }
243
244 /****************************************************************************
245  Delete entries by mid from the change notify pending queue. Always send reply.
246 *****************************************************************************/
247
248 void remove_pending_change_notify_requests_by_mid(uint16 mid)
249 {
250         struct notify_mid_map *map;
251
252         for (map = notify_changes_by_mid; map; map = map->next) {
253                 if (map->mid == mid) {
254                         break;
255                 }
256         }
257
258         if (map == NULL) {
259                 return;
260         }
261
262         change_notify_reply_packet(map->req->request_buf, NT_STATUS_CANCELLED);
263         change_notify_remove_request(map->req);
264 }
265
266 /****************************************************************************
267  Delete entries by fnum from the change notify pending queue.
268 *****************************************************************************/
269
270 void remove_pending_change_notify_requests_by_fid(files_struct *fsp,
271                                                   NTSTATUS status)
272 {
273         if (fsp->notify == NULL) {
274                 return;
275         }
276
277         while (fsp->notify->requests != NULL) {
278                 change_notify_reply_packet(
279                         fsp->notify->requests->request_buf, status);
280                 change_notify_remove_request(fsp->notify->requests);
281         }
282 }
283
284 /****************************************************************************
285  Delete entries by filename and cnum from the change notify pending queue.
286  Always send reply.
287 *****************************************************************************/
288
289 void remove_pending_change_notify_requests_by_filename(files_struct *fsp, NTSTATUS status)
290 {
291         struct change_notify *cnbp, *next;
292
293         for (cnbp=change_notify_list; cnbp; cnbp=next) {
294                 next=cnbp->next;
295                 /*
296                  * We know it refers to the same directory if the connection number and
297                  * the filename are identical.
298                  */
299                 if((cnbp->fsp->conn == fsp->conn) && strequal(cnbp->fsp->fsp_name,fsp->fsp_name)) {
300                         change_notify_reply_packet(cnbp->request_buf, status);
301                         change_notify_remove(cnbp);
302                 }
303         }
304 }
305
306 /****************************************************************************
307  Set the current change notify timeout to the lowest value across all service
308  values.
309 ****************************************************************************/
310
311 void set_change_notify_timeout(int val)
312 {
313         if (val > 0) {
314                 cnotify->select_time = MIN(cnotify->select_time, val);
315         }
316 }
317
318 /****************************************************************************
319  Longest time to sleep for before doing a change notify scan.
320 ****************************************************************************/
321
322 int change_notify_timeout(void)
323 {
324         return cnotify->select_time;
325 }
326
327 /****************************************************************************
328  Process the change notify queue. Note that this is only called as root.
329  Returns True if there are still outstanding change notify requests on the
330  queue.
331 *****************************************************************************/
332
333 BOOL process_pending_change_notify_queue(time_t t)
334 {
335         struct change_notify *cnbp, *next;
336         uint16 vuid;
337
338         for (cnbp=change_notify_list; cnbp; cnbp=next) {
339                 next=cnbp->next;
340
341                 vuid = (lp_security() == SEC_SHARE) ? UID_FIELD_INVALID : SVAL(cnbp->request_buf,smb_uid);
342
343                 if (cnbp->fsp->notify->num_changes != 0) {
344                         DEBUG(10,("process_pending_change_notify_queue: %s "
345                                   "has %d changes!\n", cnbp->fsp->fsp_name,
346                                   cnbp->fsp->notify->num_changes));
347                         change_notify_reply(cnbp->request_buf,
348                                             cnbp->max_param_count,
349                                             cnbp->fsp->notify->num_changes,
350                                             cnbp->fsp->notify->changes);
351                         change_notify_remove(cnbp);
352                         continue;
353                 }
354
355                 if (cnotify->check_notify(cnbp->fsp->conn, vuid,
356                                           cnbp->fsp->fsp_name, cnbp->flags,
357                                           cnbp->change_data, t)) {
358                         DEBUG(10,("process_pending_change_notify_queue: dir "
359                                   "%s changed !\n", cnbp->fsp->fsp_name ));
360                         change_notify_reply(cnbp->request_buf,
361                                             cnbp->max_param_count,
362                                             cnbp->fsp->notify->num_changes,
363                                             cnbp->fsp->notify->changes);
364                         change_notify_remove(cnbp);
365                 }
366         }
367
368         return (change_notify_list != NULL);
369 }
370
371 /****************************************************************************
372  Now queue an entry on the notify change list.
373  We only need to save smb_size bytes from this incoming packet
374  as we will always by returning a 'read the directory yourself'
375  error.
376 ****************************************************************************/
377
378 BOOL change_notify_set(char *inbuf, files_struct *fsp, connection_struct *conn,
379                        uint32 flags, uint32 max_param_count)
380 {
381         struct change_notify *cnbp;
382
383         if((cnbp = SMB_MALLOC_P(struct change_notify)) == NULL) {
384                 DEBUG(0,("change_notify_set: malloc fail !\n" ));
385                 return False;
386         }
387
388         ZERO_STRUCTP(cnbp);
389
390         memcpy(cnbp->request_buf, inbuf, smb_size);
391         cnbp->fsp = fsp;
392         cnbp->flags = flags;
393         cnbp->max_param_count = max_param_count;
394         cnbp->change_data = cnotify->register_notify(conn, fsp->fsp_name,
395                                                      flags);
396         
397         if (!cnbp->change_data) {
398                 SAFE_FREE(cnbp);
399                 return False;
400         }
401
402         DLIST_ADD(change_notify_list, cnbp);
403
404         /* Push the MID of this packet on the signing queue. */
405         srv_defer_sign_response(SVAL(inbuf,smb_mid));
406
407         return True;
408 }
409
410 int change_notify_fd(void)
411 {
412         if (cnotify) {
413                 return cnotify->notification_fd;
414         }
415
416         return -1;
417 }
418
419 /* notify message definition
420
421 Offset  Data                    length.
422 0       SMB_DEV_T dev           8
423 8       SMB_INO_T inode         8
424 16      uint32 filter           4
425 20      uint32 action           4
426 24..    name
427 */
428
429 #define MSG_NOTIFY_MESSAGE_SIZE 25 /* Includes at least the '\0' terminator */
430
431 struct notify_message {
432         SMB_DEV_T dev;
433         SMB_INO_T inode;
434         uint32 filter;
435         uint32 action;
436         char *name;
437 };
438
439 static DATA_BLOB notify_message_to_buf(const struct notify_message *msg)
440 {
441         DATA_BLOB result;
442         size_t len;
443
444         len = strlen(msg->name);
445
446         result = data_blob(NULL, MSG_NOTIFY_MESSAGE_SIZE + len);
447         if (!result.data) {
448                 return result;
449         }
450
451         SDEV_T_VAL(result.data, 0, msg->dev);
452         SINO_T_VAL(result.data, 8, msg->inode);
453         SIVAL(result.data, 16, msg->filter);
454         SIVAL(result.data, 20, msg->action);
455         memcpy(result.data+24, msg->name, len+1);
456
457         return result;
458 }
459
460 static BOOL buf_to_notify_message(void *buf, size_t len,
461                                   struct notify_message *msg)
462 {
463         if (len < MSG_NOTIFY_MESSAGE_SIZE) {
464                 DEBUG(0, ("Got invalid notify message of len %d\n",
465                           (int)len));
466                 return False;
467         }
468
469         msg->dev     = DEV_T_VAL(buf, 0);
470         msg->inode   = INO_T_VAL(buf, 8);
471         msg->filter  = IVAL(buf, 16);
472         msg->action  = IVAL(buf, 20);
473         msg->name    = ((char *)buf)+24;
474         return True;
475 }
476
477 void notify_action(connection_struct *conn, const char *parent,
478                    const char *name, uint32 filter, uint32_t action)
479 {
480         struct share_mode_lock *lck;
481         SMB_STRUCT_STAT sbuf;
482         int i;
483         struct notify_message msg;
484         DATA_BLOB blob;
485
486         struct process_id *pids;
487         int num_pids;
488
489         DEBUG(10, ("notify_action: parent=%s, name=%s, action=%u\n",
490                    parent, name, (unsigned)action));
491
492         if (SMB_VFS_STAT(conn, parent, &sbuf) != 0) {
493                 /*
494                  * Not 100% critical, ignore failure
495                  */
496                 return;
497         }
498
499         if (!(lck = get_share_mode_lock(NULL, sbuf.st_dev, sbuf.st_ino,
500                                         NULL, NULL))) {
501                 return;
502         }
503
504         msg.dev = sbuf.st_dev;
505         msg.inode = sbuf.st_ino;
506         msg.filter = filter;
507         msg.action = action;
508         msg.name = CONST_DISCARD(char *, name);
509
510         blob = notify_message_to_buf(&msg);
511         if (blob.data == NULL) {
512                 DEBUG(0, ("notify_message_to_buf failed\n"));
513                 return;
514         }
515
516         pids = NULL;
517         num_pids = 0;
518
519         become_root_uid_only();
520
521         for (i=0; i<lck->num_share_modes; i++) {
522                 struct share_mode_entry *e = &lck->share_modes[i];
523                 int j;
524                 struct process_id *tmp;
525
526                 for (j=0; j<num_pids; j++) {
527                         if (procid_equal(&e->pid, &pids[j])) {
528                                 break;
529                         }
530                 }
531
532                 if (j < num_pids) {
533                         /*
534                          * Already sent to that process, skip it
535                          */
536                         continue;
537                 }
538
539                 message_send_pid(lck->share_modes[i].pid, MSG_SMB_NOTIFY,
540                                  blob.data, blob.length, True);
541
542                 if (!(tmp = TALLOC_REALLOC_ARRAY(lck, pids, struct process_id,
543                                                  num_pids+1))) {
544                         DEBUG(0, ("realloc failed\n"));
545                         break;
546                 }
547                 pids = tmp;
548                 pids[num_pids] = e->pid;
549                 num_pids += 1;
550         }
551
552         unbecome_root_uid_only();
553
554         data_blob_free(&blob);
555         TALLOC_FREE(lck);
556 }
557
558 void notify_fname(connection_struct *conn, const char *path,
559                   uint32 filter, uint32 action)
560 {
561         char *parent;
562         const char *name;
563
564         if (!parent_dirname_talloc(tmp_talloc_ctx(), path, &parent, &name)) {
565                 return;
566         }
567
568         notify_action(conn, parent, name, filter, action);
569         TALLOC_FREE(parent);
570 }
571
572 static void notify_fsp(files_struct *fsp, struct notify_message *msg)
573 {
574         struct notify_change *change, *changes;
575
576         if (fsp->notify == NULL) {
577                 /*
578                  * Nobody is waiting, don't queue
579                  */
580                 return;
581         }
582
583         if ((fsp->notify->requests != NULL)
584             && (fsp->notify->requests->filter & msg->filter)) {
585                 /*
586                  * Someone is waiting for the change, trigger the reply
587                  * immediately.
588                  *
589                  * TODO: do we have to walk the lists of requests pending?
590                  */
591
592                 struct notify_change_request *req = fsp->notify->requests;
593                 struct notify_change onechange;
594
595                 onechange.action = msg->action;
596                 onechange.name = msg->name;
597
598                 change_notify_reply(req->request_buf, req->max_param_count,
599                                     1, &onechange);
600                 change_notify_remove_request(req);
601                 return;
602         }
603
604         /*
605          * Someone has triggered a notify previously, queue the change for
606          * later. TODO: Limit the number of changes queued, test how filters
607          * apply here. Do we have to store them?
608          */
609
610         if (!(changes = TALLOC_REALLOC_ARRAY(
611                       fsp->notify, fsp->notify->changes,
612                       struct notify_change, fsp->notify->num_changes+1))) {
613                 DEBUG(0, ("talloc_realloc failed\n"));
614                 return;
615         }
616
617         fsp->notify->changes = changes;
618
619         change = &(fsp->notify->changes[fsp->notify->num_changes]);
620
621         if (!(change->name = talloc_strdup(changes, msg->name))) {
622                 DEBUG(0, ("talloc_strdup failed\n"));
623                 return;
624         }
625         change->action = msg->action;
626         fsp->notify->num_changes += 1;
627
628         return;
629 }
630
631 static void notify_message_callback(int msgtype, struct process_id pid,
632                                     void *buf, size_t len)
633 {
634         struct notify_message msg;
635         files_struct *fsp;
636
637         if (!buf_to_notify_message(buf, len, &msg)) {
638                 return;
639         }
640
641         DEBUG(10, ("Received notify_message for 0x%x/%.0f: %d\n",
642                    (unsigned)msg.dev, (double)msg.inode, msg.action));
643
644         for(fsp = fsp_find_di_first(msg.dev, msg.inode); fsp;
645             fsp = fsp_find_di_next(fsp)) {
646                 notify_fsp(fsp, &msg);
647         }
648 }
649
650 /****************************************************************************
651  Initialise the change notify subsystem.
652 ****************************************************************************/
653
654 BOOL init_change_notify(void)
655 {
656         cnotify = NULL;
657
658 #if HAVE_KERNEL_CHANGE_NOTIFY
659         if (cnotify == NULL && lp_kernel_change_notify())
660                 cnotify = kernel_notify_init();
661 #endif
662 #if HAVE_FAM_CHANGE_NOTIFY
663         if (cnotify == NULL && lp_fam_change_notify())
664                 cnotify = fam_notify_init();
665 #endif
666         if (!cnotify) cnotify = hash_notify_init();
667         
668         if (!cnotify) {
669                 DEBUG(0,("Failed to init change notify system\n"));
670                 return False;
671         }
672
673         message_register(MSG_SMB_NOTIFY, notify_message_callback);
674
675         return True;
676 }