]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/fce_api.c
Spotlight: use async Tracker SPARQL API
[netatalk.git] / etc / afpd / fce_api.c
1 /*
2  * Copyright (c) 2010 Mark Williams
3  * Copyright (c) 2012 Frank Lahm <franklahm@gmail.com>
4  *
5  * File change event API for netatalk
6  *
7  * for every detected filesystem change a UDP packet is sent to an arbitrary list
8  * of listeners. Each packet contains unix path of modified filesystem element,
9  * event reason, and a consecutive event id (32 bit). Technically we are UDP client and are sending
10  * out packets synchronuosly as they are created by the afp functions. This should not affect
11  * performance measurably. The only delaying calls occur during initialization, if we have to
12  * resolve non-IP hostnames to IP. All numeric data inside the packet is network byte order, so use
13  * ntohs / ntohl to resolve length and event id. Ideally a listener receives every packet with
14  * no gaps in event ids, starting with event id 1 and mode FCE_CONN_START followed by
15  * data events from id 2 up to 0xFFFFFFFF, followed by 0 to 0xFFFFFFFF and so on.
16  *
17  * A gap or not starting with 1 mode FCE_CONN_START or receiving mode FCE_CONN_BROKEN means that
18  * the listener has lost at least one filesystem event
19  * 
20  * All Rights Reserved.  See COPYRIGHT.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif /* HAVE_CONFIG_H */
26
27 #include <stdio.h>
28
29 #include <string.h>
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <time.h>
33 #include <sys/param.h>
34 #include <sys/socket.h>
35 #include <netinet/in.h>
36 #include <arpa/inet.h>
37 #include <netdb.h>
38 #include <stdbool.h>
39
40 #include <atalk/adouble.h>
41 #include <atalk/vfs.h>
42 #include <atalk/logger.h>
43 #include <atalk/afp.h>
44 #include <atalk/util.h>
45 #include <atalk/cnid.h>
46 #include <atalk/unix.h>
47 #include <atalk/fce_api.h>
48 #include <atalk/globals.h>
49
50 #include "fork.h"
51 #include "file.h"
52 #include "directory.h"
53 #include "desktop.h"
54 #include "volume.h"
55
56 // ONLY USED IN THIS FILE
57 #include "fce_api_internal.h"
58
59 extern int afprun_bg(int root, char *cmd);
60
61 /* We store our connection data here */
62 static struct udp_entry udp_socket_list[FCE_MAX_UDP_SOCKS];
63 static int udp_sockets = 0;
64 static bool udp_initialized = false;
65 static unsigned long fce_ev_enabled =
66     (1 << FCE_FILE_MODIFY) |
67     (1 << FCE_FILE_DELETE) |
68     (1 << FCE_DIR_DELETE) |
69     (1 << FCE_FILE_CREATE) |
70     (1 << FCE_DIR_CREATE) |
71     (1 << FCE_FILE_MOVE) |
72     (1 << FCE_DIR_MOVE) |
73     (1 << FCE_LOGIN) |
74     (1 << FCE_LOGOUT);
75
76 static uint8_t fce_ev_info;    /* flags of additional info to send in events */
77
78 #define MAXIOBUF 4096
79 static unsigned char iobuf[MAXIOBUF];
80 static const char **skip_files;
81 static struct fce_close_event last_close_event;
82
83 /*
84  * This only initializes consecutive events beginning at 1, high
85  * numbered events must be initialized in the code
86  */
87 static char *fce_event_names[FCE_LAST_EVENT + 1] = {
88     "",
89     "FCE_FILE_MODIFY",
90     "FCE_FILE_DELETE",
91     "FCE_DIR_DELETE",
92     "FCE_FILE_CREATE",
93     "FCE_DIR_CREATE",
94     "FCE_FILE_MOVE",
95     "FCE_DIR_MOVE",
96     "FCE_LOGIN",
97     "FCE_LOGOUT"
98 };
99
100 /*
101  *
102  * Initialize network structs for any listeners
103  * We dont give return code because all errors are handled internally (I hope..)
104  *
105  * */
106 void fce_init_udp()
107 {
108     int rv;
109     struct addrinfo hints, *servinfo, *p;
110
111     if (udp_initialized == true)
112         return;
113
114     memset(&hints, 0, sizeof hints);
115     hints.ai_family = AF_UNSPEC;
116     hints.ai_socktype = SOCK_DGRAM;
117
118     for (int i = 0; i < udp_sockets; i++) {
119         struct udp_entry *udp_entry = udp_socket_list + i;
120
121         /* Close any pending sockets */
122         if (udp_entry->sock != -1)
123             close(udp_entry->sock);
124
125         if ((rv = getaddrinfo(udp_entry->addr, udp_entry->port, &hints, &servinfo)) != 0) {
126             LOG(log_error, logtype_fce, "fce_init_udp: getaddrinfo(%s:%s): %s",
127                 udp_entry->addr, udp_entry->port, gai_strerror(rv));
128             continue;
129         }
130
131         /* loop through all the results and make a socket */
132         for (p = servinfo; p != NULL; p = p->ai_next) {
133             if ((udp_entry->sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
134                 LOG(log_error, logtype_fce, "fce_init_udp: socket(%s:%s): %s",
135                     udp_entry->addr, udp_entry->port, strerror(errno));
136                 continue;
137             }
138             break;
139         }
140
141         if (p == NULL) {
142             LOG(log_error, logtype_fce, "fce_init_udp: no socket for %s:%s",
143                 udp_entry->addr, udp_entry->port);
144         }
145         udp_entry->addrinfo = *p;
146         memcpy(&udp_entry->addrinfo, p, sizeof(struct addrinfo));
147         memcpy(&udp_entry->sockaddr, p->ai_addr, sizeof(struct sockaddr_storage));
148         freeaddrinfo(servinfo);
149     }
150
151     udp_initialized = true;
152 }
153
154 void fce_cleanup()
155 {
156     if (udp_initialized == false )
157         return;
158
159     for (int i = 0; i < udp_sockets; i++)
160     {
161         struct udp_entry *udp_entry = udp_socket_list + i;
162
163         /* Close any pending sockets */
164         if (udp_entry->sock != -1)
165         {
166             close( udp_entry->sock );
167             udp_entry->sock = -1;
168         }
169     }
170     udp_initialized = false;
171 }
172
173 /*
174  * Construct a UDP packet for our listeners and return packet size
175  * */
176 static ssize_t build_fce_packet(const AFPObj *obj,
177                                 char *iobuf,
178                                 fce_ev_t event,
179                                 const char *path,
180                                 const char *oldpath,
181                                 pid_t pid,
182                                 const char *user,
183                                 uint32_t event_id)
184 {
185     char *p = iobuf;
186     size_t pathlen;
187     ssize_t datalen = 0;
188     uint16_t uint16;
189     uint32_t uint32;
190     uint64_t uint64;
191     uint8_t packet_info = fce_ev_info;
192
193     /* FCE magic */
194     memcpy(p, FCE_PACKET_MAGIC, 8);
195     p += 8;
196     datalen += 8;
197
198     /* version */
199     *p = FCE_PACKET_VERSION;
200     p += 1;
201     datalen += 1;
202
203     /* optional: options */
204     if (FCE_PACKET_VERSION > 1) {
205         if (oldpath)
206             packet_info |= FCE_EV_INFO_SRCPATH;
207         *p = packet_info;
208         p += 1;
209         datalen += 1;
210     }
211
212     /* event */
213     *p = event;
214     p += 1;
215     datalen += 1;
216
217     /* optional: padding */
218     if (FCE_PACKET_VERSION > 1) {
219         p += 1;
220         datalen += 1;
221     }
222
223     /* optional: reserved */
224     if (FCE_PACKET_VERSION > 1) {
225         p += 8;
226         datalen += 8;
227     }
228
229     /* event ID */
230     uint32 = htonl(event_id);
231     memcpy(p, &uint32, sizeof(uint32));
232     p += sizeof(uint32);
233     datalen += sizeof(uint32);
234
235     /* optional: pid */
236     if (packet_info & FCE_EV_INFO_PID) {
237         uint64 = pid;
238         uint64 = hton64(uint64);
239         memcpy(p, &uint64, sizeof(uint64));
240         p += sizeof(uint64);
241         datalen += sizeof(uint64);
242     }
243
244     /* optional: username */
245     if (packet_info & FCE_EV_INFO_USER) {
246         uint16 = strlen(user);
247         uint16 = htons(uint16);
248         memcpy(p, &uint16, sizeof(uint16));
249         p += sizeof(uint16);
250         datalen += sizeof(uint16);
251         memcpy(p, user, strlen(user));
252         p += strlen(user);
253         datalen += strlen(user);
254     }
255
256     /* path */
257     if ((pathlen = strlen(path)) >= MAXPATHLEN)
258         pathlen = MAXPATHLEN - 1;
259     uint16 = pathlen;
260     uint16 = htons(uint16);
261     memcpy(p, &uint16, sizeof(uint16));
262     p += sizeof(uint16);
263     datalen += sizeof(uint16);
264     memcpy(p, path, pathlen);
265     p += pathlen;
266     datalen += pathlen;
267
268     /* optional: source path */
269     if (packet_info & FCE_EV_INFO_SRCPATH) {
270         if ((pathlen = strlen(oldpath)) >= MAXPATHLEN)
271             pathlen = MAXPATHLEN - 1;
272         uint16 = pathlen;
273         uint16 = htons(uint16);
274         memcpy(p, &uint16, sizeof(uint16));
275         p += sizeof(uint16);
276         datalen += sizeof(uint16);
277         memcpy(p, oldpath, pathlen);
278         p += pathlen;
279         datalen += pathlen;
280     }
281
282     /* return the packet len */
283     return datalen;
284 }
285
286 /*
287  * Send the fce information to all (connected) listeners
288  * We dont give return code because all errors are handled internally (I hope..)
289  * */
290 static void send_fce_event(const AFPObj *obj, int event, const char *path, const char *oldpath)
291 {    
292     static bool first_event = true;
293     static uint32_t event_id = 0; /* the unique packet couter to detect packet/data loss. Going from 0xFFFFFFFF to 0x0 is a valid increment */
294     static char *user;
295     time_t now = time(NULL);
296     ssize_t data_len;
297
298     /* initialized ? */
299     if (first_event == true) {
300         first_event = false;
301
302         fce_event_names[FCE_CONN_START] = "FCE_CONN_START";
303         fce_event_names[FCE_CONN_BROKEN] = "FCE_CONN_BROKEN";
304
305         struct passwd *pwd = getpwuid(obj->uid);
306         user = strdup(pwd->pw_name);
307
308         switch (obj->fce_version) {
309         case 1:
310             /* fce_ev_info unused */
311             break;
312         case 2:
313             fce_ev_info = FCE_EV_INFO_PID | FCE_EV_INFO_USER;
314             break;
315         default:
316             fce_ev_info = 0;
317             LOG(log_error, logtype_fce, "Unsupported FCE protocol version %d", obj->fce_version);
318             break;
319         }
320
321         fce_init_udp();
322         /* Notify listeners the we start from the beginning */
323         send_fce_event(obj, FCE_CONN_START, "", NULL);
324     }
325
326     /* run script */
327     if (obj->fce_notify_script) {
328         static bstring quote = NULL;
329         static bstring quoterep = NULL;
330         static bstring slash = NULL;
331         static bstring slashrep = NULL;
332
333         if (!quote) {
334             quote = bfromcstr("'");
335             quoterep = bfromcstr("'\\''");
336             slash = bfromcstr("\\");
337             slashrep = bfromcstr("\\\\");
338         }
339
340         bstring cmd = bformat("%s -v %d -e %s -i %" PRIu32 "",
341                               obj->fce_notify_script,
342                               FCE_PACKET_VERSION,
343                               fce_event_names[event],
344                               event_id);
345
346         if (path[0]) {
347             bstring bpath = bfromcstr(path);
348             bfindreplace(bpath, slash, slashrep, 0);
349             bfindreplace(bpath, quote, quoterep, 0);
350             bformata(cmd, " -P '%s'", bdata(bpath));
351             bdestroy(bpath);
352         }
353         if (fce_ev_info | FCE_EV_INFO_PID)
354             bformata(cmd, " -p %" PRIu64 "", (uint64_t)getpid());
355         if (fce_ev_info | FCE_EV_INFO_USER)
356             bformata(cmd, " -u %s", user);
357         if (oldpath) {
358             bstring boldpath = bfromcstr(oldpath);
359             bfindreplace(boldpath, slash, slashrep, 0);
360             bfindreplace(boldpath, quote, quoterep, 0);
361             bformata(cmd, " -S '%s'", bdata(boldpath));
362             bdestroy(boldpath);
363         }
364         (void)afprun_bg(1, bdata(cmd));
365         bdestroy(cmd);
366     }
367
368     for (int i = 0; i < udp_sockets; i++) {
369         int sent_data = 0;
370         struct udp_entry *udp_entry = udp_socket_list + i;
371
372         /* we had a problem earlier ? */
373         if (udp_entry->sock == -1) {
374             /* We still have to wait ?*/
375             if (now < udp_entry->next_try_on_error)
376                 continue;
377
378             /* Reopen socket */
379             udp_entry->sock = socket(udp_entry->addrinfo.ai_family,
380                                      udp_entry->addrinfo.ai_socktype,
381                                      udp_entry->addrinfo.ai_protocol);
382             
383             if (udp_entry->sock == -1) {
384                 /* failed again, so go to rest again */
385                 LOG(log_error, logtype_fce, "Cannot recreate socket for fce UDP connection: errno %d", errno  );
386
387                 udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;
388                 continue;
389             }
390
391             udp_entry->next_try_on_error = 0;
392
393             /* Okay, we have a running socket again, send server that we had a problem on our side*/
394             data_len = build_fce_packet(obj, iobuf, FCE_CONN_BROKEN, "", NULL, getpid(), user, 0);
395
396             sendto(udp_entry->sock,
397                    iobuf,
398                    data_len,
399                    0,
400                    (struct sockaddr *)&udp_entry->sockaddr,
401                    udp_entry->addrinfo.ai_addrlen);
402         }
403
404         /* build our data packet */
405         data_len = build_fce_packet(obj, iobuf, event, path, oldpath, getpid(), user, event_id);
406
407         sent_data = sendto(udp_entry->sock,
408                            iobuf,
409                            data_len,
410                            0,
411                            (struct sockaddr *)&udp_entry->sockaddr,
412                            udp_entry->addrinfo.ai_addrlen);
413
414         /* Problems ? */
415         if (sent_data != data_len) {
416             /* Argh, socket broke, we close and retry later */
417             LOG(log_error, logtype_fce, "send_fce_event: error sending packet to %s:%s, transfered %d of %d: %s",
418                 udp_entry->addr, udp_entry->port, sent_data, data_len, strerror(errno));
419
420             close( udp_entry->sock );
421             udp_entry->sock = -1;
422             udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;
423         }
424     }
425
426     event_id++;
427 }
428
429 static int add_udp_socket(const char *target_ip, const char *target_port )
430 {
431     if (target_port == NULL)
432         target_port = FCE_DEFAULT_PORT_STRING;
433
434     if (udp_sockets >= FCE_MAX_UDP_SOCKS) {
435         LOG(log_error, logtype_fce, "Too many file change api UDP connections (max %d allowed)", FCE_MAX_UDP_SOCKS );
436         return AFPERR_PARAM;
437     }
438
439     udp_socket_list[udp_sockets].addr = strdup(target_ip);
440     udp_socket_list[udp_sockets].port = strdup(target_port);
441     udp_socket_list[udp_sockets].sock = -1;
442     memset(&udp_socket_list[udp_sockets].addrinfo, 0, sizeof(struct addrinfo));
443     memset(&udp_socket_list[udp_sockets].sockaddr, 0, sizeof(struct sockaddr_storage));
444     udp_socket_list[udp_sockets].next_try_on_error = 0;
445
446     udp_sockets++;
447
448     return AFP_OK;
449 }
450
451 static void save_close_event(const AFPObj *obj, const char *path)
452 {
453     time_t now = time(NULL);
454
455     /* Check if it's a close for the same event as the last one */
456     if (last_close_event.time   /* is there any saved event ? */
457         && (strcmp(path, last_close_event.path) != 0)) {
458         /* no, so send the saved event out now */
459         send_fce_event(obj, FCE_FILE_MODIFY,last_close_event.path, NULL);
460     }
461
462     LOG(log_debug, logtype_fce, "save_close_event: %s", path);
463
464     last_close_event.time = now;
465     strncpy(last_close_event.path, path, MAXPATHLEN);
466 }
467
468 static void fce_init_ign_names(const char *ignores)
469 {
470     int count = 0;
471     char *names = strdup(ignores);
472     char *p;
473     int i = 0;
474
475     while (names[i]) {
476         count++;
477         for (; names[i] && names[i] != '/'; i++)
478             ;
479         if (!names[i])
480             break;
481         i++;
482     }
483
484     skip_files = calloc(count + 1, sizeof(char *));
485
486     for (i = 0, p = strtok(names, "/"); p ; p = strtok(NULL, "/"))
487         skip_files[i++] = strdup(p);
488
489     free(names);
490 }
491
492 /*
493  *
494  * Dispatcher for all incoming file change events
495  *
496  * */
497 int fce_register(const AFPObj *obj, fce_ev_t event, const char *path, const char *oldpath)
498 {
499     static bool first_event = true;
500     const char *bname;
501
502     if (!(fce_ev_enabled & (1 << event)))
503         return AFP_OK;
504
505     AFP_ASSERT(event >= FCE_FIRST_EVENT && event <= FCE_LAST_EVENT);
506     AFP_ASSERT(path);
507
508     LOG(log_debug, logtype_fce, "register_fce(path: %s, event: %s)",
509         path, fce_event_names[event]);
510
511     bname = basename_safe(path);
512
513     if ((udp_sockets == 0) && (obj->fce_notify_script == NULL)) {
514         /* No listeners configured */
515         return AFP_OK;
516     }
517
518         /* do some initialization on the fly the first time */
519         if (first_event) {
520                 fce_initialize_history();
521         fce_init_ign_names(obj->fce_ign_names);
522         first_event = false;
523         }
524
525         /* handle files which should not cause events (.DS_Store atc. ) */
526     for (int i = 0; skip_files[i] != NULL; i++) {
527         if (strcmp(bname, skip_files[i]) == 0)
528                         return AFP_OK;
529         }
530
531         /* Can we ignore this event based on type or history? */
532         if (fce_handle_coalescation(event, path)) {
533                 LOG(log_debug9, logtype_fce, "Coalesced fc event <%d> for <%s>", event, path);
534                 return AFP_OK;
535         }
536
537     switch (event) {
538     case FCE_FILE_MODIFY:
539         save_close_event(obj, path);
540         break;
541     default:
542         send_fce_event(obj, event, path, oldpath);
543         break;
544     }
545
546     return AFP_OK;
547 }
548
549 static void check_saved_close_events(const AFPObj *obj)
550 {
551     time_t now = time(NULL);
552
553     /* check if configured holdclose time has passed */
554     if (last_close_event.time && ((last_close_event.time + obj->options.fce_fmodwait) < now)) {
555         LOG(log_debug, logtype_fce, "check_saved_close_events: sending event: %s", last_close_event.path);
556         /* yes, send event */
557         send_fce_event(obj, FCE_FILE_MODIFY, &last_close_event.path[0], NULL);
558         last_close_event.path[0] = 0;
559         last_close_event.time = 0;
560     }
561 }
562
563 /******************** External calls start here **************************/
564
565 /*
566  * API-Calls for file change api, called form outside (file.c directory.c ofork.c filedir.c)
567  * */
568 void fce_pending_events(const AFPObj *obj)
569 {
570     if (!udp_sockets)
571         return;
572     check_saved_close_events(obj);
573 }
574
575 /*
576  *
577  * Extern connect to afpd parameter, can be called multiple times for multiple listeners (up to MAX_UDP_SOCKS times)
578  *
579  * */
580 int fce_add_udp_socket(const char *target)
581 {
582         const char *port = FCE_DEFAULT_PORT_STRING;
583         char target_ip[256] = {""};
584
585         strncpy(target_ip, target, sizeof(target_ip) -1);
586
587         char *port_delim = strchr( target_ip, ':' );
588         if (port_delim) {
589                 *port_delim = 0;
590                 port = port_delim + 1;
591         }
592         return add_udp_socket(target_ip, port);
593 }
594
595 int fce_set_events(const char *events)
596 {
597     char *e;
598     char *p;
599     
600     if (events == NULL)
601         return AFPERR_PARAM;
602
603     e = strdup(events);
604
605     fce_ev_enabled = 0;
606
607     for (p = strtok(e, ", "); p; p = strtok(NULL, ", ")) {
608         if (strcmp(p, "fmod") == 0) {
609             fce_ev_enabled |= (1 << FCE_FILE_MODIFY);
610         } else if (strcmp(p, "fdel") == 0) {
611             fce_ev_enabled |= (1 << FCE_FILE_DELETE);
612         } else if (strcmp(p, "ddel") == 0) {
613             fce_ev_enabled |= (1 << FCE_DIR_DELETE);
614         } else if (strcmp(p, "fcre") == 0) {
615             fce_ev_enabled |= (1 << FCE_FILE_CREATE);
616         } else if (strcmp(p, "dcre") == 0) {
617             fce_ev_enabled |= (1 << FCE_DIR_CREATE);
618         } else if (strcmp(p, "fmov") == 0) {
619             fce_ev_enabled |= (1 << FCE_FILE_MOVE);
620         } else if (strcmp(p, "dmov") == 0) {
621             fce_ev_enabled |= (1 << FCE_DIR_MOVE);
622         } else if (strcmp(p, "login") == 0) {
623             fce_ev_enabled |= (1 << FCE_LOGIN);
624         } else if (strcmp(p, "logout") == 0) {
625             fce_ev_enabled |= (1 << FCE_LOGOUT);
626         }
627     }
628
629     free(e);
630
631     return AFP_OK;
632 }