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