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