r20433: Work in progress: Survive more of RAW-NOTIFY.
[tprouty/samba.git] / source / 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
26 /****************************************************************************
27  This is the structure to queue to implement NT change
28  notify. It consists of smb_size bytes stored from the
29  transact command (to keep the mid, tid etc around).
30  Plus the fid to examine and notify private data.
31 *****************************************************************************/
32
33 struct change_notify {
34         struct change_notify *next, *prev;
35         files_struct *fsp;
36         uint32 flags;
37         uint32 max_param_count;
38         char request_buf[smb_size];
39         void *change_data;
40 };
41
42 static struct change_notify *change_notify_list;
43
44 static BOOL notify_marshall_changes(struct notify_changes *changes,
45                                     prs_struct *ps)
46 {
47         int i;
48         UNISTR uni_name;
49
50         for (i=0; i<changes->num_changes; i++) {
51                 struct notify_change *c = &changes->changes[i];
52                 size_t namelen;
53                 uint32 u32_tmp; /* Temp arg to prs_uint32 to avoid
54                                  * signed/unsigned issues */
55
56                 namelen = convert_string_allocate(
57                         NULL, CH_UNIX, CH_UTF16LE, c->name, strlen(c->name)+1,
58                         &uni_name.buffer, True);
59                 if ((namelen == -1) || (uni_name.buffer == NULL)) {
60                         goto fail;
61                 }
62
63                 namelen -= 2;   /* Dump NULL termination */
64
65                 /*
66                  * Offset to next entry, only if there is one
67                  */
68
69                 u32_tmp = (i == changes->num_changes-1) ? 0 : namelen + 12;
70                 if (!prs_uint32("offset", ps, 1, &u32_tmp)) goto fail;
71
72                 u32_tmp = c->action;
73                 if (!prs_uint32("action", ps, 1, &u32_tmp)) goto fail;
74
75                 u32_tmp = namelen;
76                 if (!prs_uint32("namelen", ps, 1, &u32_tmp)) goto fail;
77
78                 if (!prs_unistr("name", ps, 1, &uni_name)) goto fail;
79
80                 /*
81                  * Not NULL terminated, decrease by the 2 UCS2 \0 chars
82                  */
83                 prs_set_offset(ps, prs_offset(ps)-2);
84
85                 SAFE_FREE(uni_name.buffer);
86         }
87
88         return True;
89
90  fail:
91         SAFE_FREE(uni_name.buffer);
92         return False;
93 }
94
95 /****************************************************************************
96  Setup the common parts of the return packet and send it.
97 *****************************************************************************/
98
99 static void change_notify_reply_packet(const char *request_buf,
100                                        NTSTATUS error_code)
101 {
102         char outbuf[smb_size+38];
103
104         memset(outbuf, '\0', sizeof(outbuf));
105         construct_reply_common(request_buf, outbuf);
106
107         ERROR_NT(error_code);
108
109         /*
110          * Seems NT needs a transact command with an error code
111          * in it. This is a longer packet than a simple error.
112          */
113         set_message(outbuf,18,0,False);
114
115         show_msg(outbuf);
116         if (!send_smb(smbd_server_fd(),outbuf))
117                 exit_server_cleanly("change_notify_reply_packet: send_smb failed.");
118 }
119
120 void change_notify_reply(const char *request_buf, uint32 max_param_count,
121                          files_struct *fsp)
122 {
123         char *outbuf = NULL;
124         prs_struct ps;
125         size_t buflen = smb_size+38+max_param_count;
126
127         if (!prs_init(&ps, 0, NULL, False)
128             || !notify_marshall_changes(fsp->notify, &ps)) {
129                 change_notify_reply_packet(request_buf, NT_STATUS_NO_MEMORY);
130                 goto done;
131         }
132
133         if (prs_offset(&ps) > max_param_count) {
134                 /*
135                  * We exceed what the client is willing to accept. Send
136                  * nothing.
137                  */
138                 change_notify_reply_packet(request_buf, NT_STATUS_OK);
139                 goto done;
140         }
141
142         if (!(outbuf = SMB_MALLOC_ARRAY(char, buflen))) {
143                 change_notify_reply_packet(request_buf, NT_STATUS_NO_MEMORY);
144                 goto done;
145         }
146
147         construct_reply_common(request_buf, outbuf);
148
149         if (send_nt_replies(outbuf, buflen, NT_STATUS_OK, prs_data_p(&ps),
150                             prs_offset(&ps), NULL, 0) == -1) {
151                 exit_server("change_notify_reply_packet: send_smb failed.");
152         }
153
154  done:
155         SAFE_FREE(outbuf);
156         prs_mem_free(&ps);
157         fsp->notify->num_changes = 0;
158         TALLOC_FREE(fsp->notify->changes);
159 }
160
161 /****************************************************************************
162  Remove an entry from the list and free it, also closing any
163  directory handle if necessary.
164 *****************************************************************************/
165
166 static void change_notify_remove(struct change_notify *cnbp)
167 {
168         cnotify->remove_notify(cnbp->change_data);
169         DLIST_REMOVE(change_notify_list, cnbp);
170         ZERO_STRUCTP(cnbp);
171         SAFE_FREE(cnbp);
172 }
173
174 /****************************************************************************
175  Delete entries by fnum from the change notify pending queue.
176 *****************************************************************************/
177
178 void remove_pending_change_notify_requests_by_fid(files_struct *fsp, NTSTATUS status)
179 {
180         struct change_notify *cnbp, *next;
181
182         for (cnbp=change_notify_list; cnbp; cnbp=next) {
183                 next=cnbp->next;
184                 if (cnbp->fsp->fnum == fsp->fnum) {
185                         change_notify_reply_packet(cnbp->request_buf, status);
186                         change_notify_remove(cnbp);
187                 }
188         }
189 }
190
191 /****************************************************************************
192  Delete entries by mid from the change notify pending queue. Always send reply.
193 *****************************************************************************/
194
195 void remove_pending_change_notify_requests_by_mid(int mid)
196 {
197         struct change_notify *cnbp, *next;
198
199         for (cnbp=change_notify_list; cnbp; cnbp=next) {
200                 next=cnbp->next;
201                 if(SVAL(cnbp->request_buf,smb_mid) == mid) {
202                         change_notify_reply_packet(cnbp->request_buf,
203                                                    NT_STATUS_CANCELLED);
204                         change_notify_remove(cnbp);
205                 }
206         }
207 }
208
209 /****************************************************************************
210  Delete entries by filename and cnum from the change notify pending queue.
211  Always send reply.
212 *****************************************************************************/
213
214 void remove_pending_change_notify_requests_by_filename(files_struct *fsp, NTSTATUS status)
215 {
216         struct change_notify *cnbp, *next;
217
218         for (cnbp=change_notify_list; cnbp; cnbp=next) {
219                 next=cnbp->next;
220                 /*
221                  * We know it refers to the same directory if the connection number and
222                  * the filename are identical.
223                  */
224                 if((cnbp->fsp->conn == fsp->conn) && strequal(cnbp->fsp->fsp_name,fsp->fsp_name)) {
225                         change_notify_reply_packet(cnbp->request_buf, status);
226                         change_notify_remove(cnbp);
227                 }
228         }
229 }
230
231 /****************************************************************************
232  Set the current change notify timeout to the lowest value across all service
233  values.
234 ****************************************************************************/
235
236 void set_change_notify_timeout(int val)
237 {
238         if (val > 0) {
239                 cnotify->select_time = MIN(cnotify->select_time, val);
240         }
241 }
242
243 /****************************************************************************
244  Longest time to sleep for before doing a change notify scan.
245 ****************************************************************************/
246
247 int change_notify_timeout(void)
248 {
249         return cnotify->select_time;
250 }
251
252 /****************************************************************************
253  Process the change notify queue. Note that this is only called as root.
254  Returns True if there are still outstanding change notify requests on the
255  queue.
256 *****************************************************************************/
257
258 BOOL process_pending_change_notify_queue(time_t t)
259 {
260         struct change_notify *cnbp, *next;
261         uint16 vuid;
262
263         for (cnbp=change_notify_list; cnbp; cnbp=next) {
264                 next=cnbp->next;
265
266                 vuid = (lp_security() == SEC_SHARE) ? UID_FIELD_INVALID : SVAL(cnbp->request_buf,smb_uid);
267
268                 if (cnbp->fsp->notify->num_changes != 0) {
269                         DEBUG(10,("process_pending_change_notify_queue: %s "
270                                   "has %d changes!\n", cnbp->fsp->fsp_name,
271                                   cnbp->fsp->notify->num_changes));
272                         change_notify_reply(cnbp->request_buf,
273                                             cnbp->max_param_count,
274                                             cnbp->fsp);
275                         change_notify_remove(cnbp);
276                         continue;
277                 }
278
279                 if (cnotify->check_notify(cnbp->fsp->conn, vuid,
280                                           cnbp->fsp->fsp_name, cnbp->flags,
281                                           cnbp->change_data, t)) {
282                         DEBUG(10,("process_pending_change_notify_queue: dir "
283                                   "%s changed !\n", cnbp->fsp->fsp_name ));
284                         change_notify_reply(cnbp->request_buf,
285                                             cnbp->max_param_count,
286                                             cnbp->fsp);
287                         change_notify_remove(cnbp);
288                 }
289         }
290
291         return (change_notify_list != NULL);
292 }
293
294 /****************************************************************************
295  Now queue an entry on the notify change list.
296  We only need to save smb_size bytes from this incoming packet
297  as we will always by returning a 'read the directory yourself'
298  error.
299 ****************************************************************************/
300
301 BOOL change_notify_set(char *inbuf, files_struct *fsp, connection_struct *conn,
302                        uint32 flags, uint32 max_param_count)
303 {
304         struct change_notify *cnbp;
305
306         if((cnbp = SMB_MALLOC_P(struct change_notify)) == NULL) {
307                 DEBUG(0,("change_notify_set: malloc fail !\n" ));
308                 return False;
309         }
310
311         ZERO_STRUCTP(cnbp);
312
313         memcpy(cnbp->request_buf, inbuf, smb_size);
314         cnbp->fsp = fsp;
315         cnbp->flags = flags;
316         cnbp->max_param_count = max_param_count;
317         cnbp->change_data = cnotify->register_notify(conn, fsp->fsp_name,
318                                                      flags);
319         
320         if (!cnbp->change_data) {
321                 SAFE_FREE(cnbp);
322                 return False;
323         }
324
325         DLIST_ADD(change_notify_list, cnbp);
326
327         /* Push the MID of this packet on the signing queue. */
328         srv_defer_sign_response(SVAL(inbuf,smb_mid));
329
330         return True;
331 }
332
333 int change_notify_fd(void)
334 {
335         if (cnotify) {
336                 return cnotify->notification_fd;
337         }
338
339         return -1;
340 }
341
342 /* notify message definition
343
344 Offset  Data                    length.
345 0       SMB_DEV_T dev           8
346 8       SMB_INO_T inode         8
347 16      uint32 action           4
348 20..    name
349 */
350
351 #define MSG_NOTIFY_MESSAGE_SIZE 21 /* Includes at least the '\0' terminator */
352
353 struct notify_message {
354         SMB_DEV_T dev;
355         SMB_INO_T inode;
356         uint32_t action;
357         char *name;
358 };
359
360 static DATA_BLOB notify_message_to_buf(const struct notify_message *msg)
361 {
362         DATA_BLOB result;
363         size_t len;
364
365         len = strlen(msg->name);
366
367         result = data_blob(NULL, MSG_NOTIFY_MESSAGE_SIZE + len);
368         if (!result.data) {
369                 return result;
370         }
371
372         SDEV_T_VAL(result.data, 0, msg->dev);
373         SINO_T_VAL(result.data, 8, msg->inode);
374         SIVAL(result.data, 16, msg->action);
375         memcpy(result.data+20, msg->name, len+1);
376
377         return result;
378 }
379
380 static BOOL buf_to_notify_message(void *buf, size_t len,
381                                   struct notify_message *msg)
382 {
383         if (len < MSG_NOTIFY_MESSAGE_SIZE) {
384                 DEBUG(0, ("Got invalid notify message of len %d\n", len));
385                 return False;
386         }
387
388         msg->dev     = DEV_T_VAL(buf, 0);
389         msg->inode   = INO_T_VAL(buf, 8);
390         msg->action  = IVAL(buf, 16);
391         msg->name    = ((char *)buf)+20;
392         return True;
393 }
394
395 void notify_action(connection_struct *conn, const char *parent,
396                    const char *name, uint32_t action)
397 {
398         struct share_mode_lock *lck;
399         SMB_STRUCT_STAT sbuf;
400         int i;
401         struct notify_message msg;
402         DATA_BLOB blob;
403
404         struct process_id *pids;
405         int num_pids;
406
407         DEBUG(10, ("notify_action: parent=%s, name=%s, action=%u\n",
408                    parent, name, (unsigned)action));
409
410         if (SMB_VFS_STAT(conn, parent, &sbuf) != 0) {
411                 /*
412                  * Not 100% critical, ignore failure
413                  */
414                 return;
415         }
416
417         if (!(lck = get_share_mode_lock(NULL, sbuf.st_dev, sbuf.st_ino,
418                                         NULL, NULL))) {
419                 return;
420         }
421
422         msg.dev = sbuf.st_dev;
423         msg.inode = sbuf.st_ino;
424         msg.action = action;
425         msg.name = CONST_DISCARD(char *, name);
426
427         blob = notify_message_to_buf(&msg);
428         if (blob.data == NULL) {
429                 DEBUG(0, ("notify_message_to_buf failed\n"));
430                 return;
431         }
432
433         pids = NULL;
434         num_pids = 0;
435
436         become_root_uid_only();
437
438         for (i=0; i<lck->num_share_modes; i++) {
439                 struct share_mode_entry *e = &lck->share_modes[i];
440                 int j;
441                 struct process_id *tmp;
442
443                 for (j=0; j<num_pids; j++) {
444                         if (procid_equal(&e->pid, &pids[j])) {
445                                 break;
446                         }
447                 }
448
449                 if (j < num_pids) {
450                         /*
451                          * Already sent to that process, skip it
452                          */
453                         continue;
454                 }
455
456                 message_send_pid(lck->share_modes[i].pid, MSG_SMB_NOTIFY,
457                                  blob.data, blob.length, True);
458
459                 if (!(tmp = TALLOC_REALLOC_ARRAY(lck, pids, struct process_id,
460                                                  num_pids+1))) {
461                         DEBUG(0, ("realloc failed\n"));
462                         break;
463                 }
464                 pids = tmp;
465                 pids[num_pids] = e->pid;
466                 num_pids += 1;
467         }
468
469         unbecome_root_uid_only();
470
471         data_blob_free(&blob);
472         TALLOC_FREE(lck);
473 }
474
475 static void notify_message_callback(int msgtype, struct process_id pid,
476                                     void *buf, size_t len)
477 {
478         struct notify_message msg;
479         files_struct *fsp;
480         struct notify_change *changes, *change;
481         struct change_notify *cnbp;
482
483         if (!buf_to_notify_message(buf, len, &msg)) {
484                 return;
485         }
486
487         DEBUG(10, ("Received notify_message for 0x%x/%.0f: %d\n",
488                    (unsigned)msg.dev, (double)msg.inode, msg.action));
489
490         fsp = NULL;
491
492         for (cnbp = change_notify_list; cnbp != NULL; cnbp = cnbp->next) {
493                 if ((cnbp->fsp->dev == msg.dev)
494                     && (cnbp->fsp->inode == msg.inode)) {
495                         break;
496                 }
497         }
498
499         if (cnbp != NULL) {
500                 DEBUG(10, ("Found pending change notify for %s\n",
501                            cnbp->fsp->fsp_name));
502                 fsp = cnbp->fsp;
503                 SMB_ASSERT(fsp->notify->num_changes == 0);
504         }
505
506         if ((fsp == NULL)
507             && !(fsp = file_find_dir_lowest_id(msg.dev, msg.inode))) {
508                 DEBUG(10, ("notify_message: did not find fsp\n"));
509                 return;
510         }
511
512         if (!(changes = TALLOC_REALLOC_ARRAY(
513                       fsp->notify, fsp->notify->changes,
514                       struct notify_change, fsp->notify->num_changes+1))) {
515                 DEBUG(0, ("talloc_realloc failed\n"));
516                 return;
517         }
518
519         fsp->notify->changes = changes;
520
521         change = &(fsp->notify->changes[fsp->notify->num_changes]);
522
523         if (!(change->name = talloc_strdup(changes, msg.name))) {
524                 DEBUG(0, ("talloc_strdup failed\n"));
525                 return;
526         }
527         change->action = msg.action;
528         fsp->notify->num_changes += 1;
529
530         if (cnbp != NULL) {
531                 /*
532                  * Respond directly, we have a someone waiting for this change
533                  */
534                 DEBUG(10, ("Found pending cn for %s, responding directly\n",
535                            cnbp->fsp->fsp_name));
536                 change_notify_reply(cnbp->request_buf, cnbp->max_param_count,
537                                     cnbp->fsp);
538                 change_notify_remove(cnbp);
539                 return;
540         }
541 }
542
543 /****************************************************************************
544  Initialise the change notify subsystem.
545 ****************************************************************************/
546
547 BOOL init_change_notify(void)
548 {
549         cnotify = NULL;
550
551 #if HAVE_KERNEL_CHANGE_NOTIFY
552         if (cnotify == NULL && lp_kernel_change_notify())
553                 cnotify = kernel_notify_init();
554 #endif
555 #if HAVE_FAM_CHANGE_NOTIFY
556         if (cnotify == NULL && lp_fam_change_notify())
557                 cnotify = fam_notify_init();
558 #endif
559         if (!cnotify) cnotify = hash_notify_init();
560         
561         if (!cnotify) {
562                 DEBUG(0,("Failed to init change notify system\n"));
563                 return False;
564         }
565
566         message_register(MSG_SMB_NOTIFY, notify_message_callback);
567
568         return True;
569 }