2 * Copyright (c) 2010 Mark Williams
3 * Copyright (c) 2012 Frank Lahm <franklahm@gmail.com>
5 * File change event API for netatalk
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.
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
20 * All Rights Reserved. See COPYRIGHT.
25 #endif /* HAVE_CONFIG_H */
33 #include <sys/param.h>
34 #include <sys/socket.h>
35 #include <netinet/in.h>
36 #include <arpa/inet.h>
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>
52 #include "directory.h"
56 // ONLY USED IN THIS FILE
57 #include "fce_api_internal.h"
59 extern int afprun_bg(int root, char *cmd);
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) |
76 static uint8_t fce_ev_info; /* flags of additional info to send in events */
79 static unsigned char iobuf[MAXIOBUF];
80 static const char **skip_files;
81 static struct fce_close_event last_close_event;
83 static char *fce_event_names[] = {
98 * Initialize network structs for any listeners
99 * We dont give return code because all errors are handled internally (I hope..)
105 struct addrinfo hints, *servinfo, *p;
107 if (udp_initialized == true)
110 memset(&hints, 0, sizeof hints);
111 hints.ai_family = AF_UNSPEC;
112 hints.ai_socktype = SOCK_DGRAM;
114 for (int i = 0; i < udp_sockets; i++) {
115 struct udp_entry *udp_entry = udp_socket_list + i;
117 /* Close any pending sockets */
118 if (udp_entry->sock != -1)
119 close(udp_entry->sock);
121 if ((rv = getaddrinfo(udp_entry->addr, udp_entry->port, &hints, &servinfo)) != 0) {
122 LOG(log_error, logtype_fce, "fce_init_udp: getaddrinfo(%s:%s): %s",
123 udp_entry->addr, udp_entry->port, gai_strerror(rv));
127 /* loop through all the results and make a socket */
128 for (p = servinfo; p != NULL; p = p->ai_next) {
129 if ((udp_entry->sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
130 LOG(log_error, logtype_fce, "fce_init_udp: socket(%s:%s): %s",
131 udp_entry->addr, udp_entry->port, strerror(errno));
138 LOG(log_error, logtype_fce, "fce_init_udp: no socket for %s:%s",
139 udp_entry->addr, udp_entry->port);
141 udp_entry->addrinfo = *p;
142 memcpy(&udp_entry->addrinfo, p, sizeof(struct addrinfo));
143 memcpy(&udp_entry->sockaddr, p->ai_addr, sizeof(struct sockaddr_storage));
144 freeaddrinfo(servinfo);
147 udp_initialized = true;
152 if (udp_initialized == false )
155 for (int i = 0; i < udp_sockets; i++)
157 struct udp_entry *udp_entry = udp_socket_list + i;
159 /* Close any pending sockets */
160 if (udp_entry->sock != -1)
162 close( udp_entry->sock );
163 udp_entry->sock = -1;
166 udp_initialized = false;
170 * Construct a UDP packet for our listeners and return packet size
172 static ssize_t build_fce_packet(const AFPObj *obj,
187 uint8_t packet_info = fce_ev_info;
190 memcpy(p, FCE_PACKET_MAGIC, 8);
195 *p = FCE_PACKET_VERSION;
199 /* optional: options */
200 if (FCE_PACKET_VERSION > 1) {
202 packet_info |= FCE_EV_INFO_SRCPATH;
213 /* optional: padding */
214 if (FCE_PACKET_VERSION > 1) {
219 /* optional: reserved */
220 if (FCE_PACKET_VERSION > 1) {
226 uint32 = htonl(event_id);
227 memcpy(p, &uint32, sizeof(uint32));
229 datalen += sizeof(uint32);
232 if (packet_info & FCE_EV_INFO_PID) {
234 uint64 = hton64(uint64);
235 memcpy(p, &uint64, sizeof(uint64));
237 datalen += sizeof(uint64);
240 /* optional: username */
241 if (packet_info & FCE_EV_INFO_USER) {
242 uint16 = strlen(user);
243 uint16 = htons(uint16);
244 memcpy(p, &uint16, sizeof(uint16));
246 datalen += sizeof(uint16);
247 memcpy(p, user, strlen(user));
249 datalen += strlen(user);
253 if ((pathlen = strlen(path)) >= MAXPATHLEN)
254 pathlen = MAXPATHLEN - 1;
256 uint16 = htons(uint16);
257 memcpy(p, &uint16, sizeof(uint16));
259 datalen += sizeof(uint16);
260 memcpy(p, path, pathlen);
264 /* optional: source path */
265 if (packet_info & FCE_EV_INFO_SRCPATH) {
266 if ((pathlen = strlen(oldpath)) >= MAXPATHLEN)
267 pathlen = MAXPATHLEN - 1;
269 uint16 = htons(uint16);
270 memcpy(p, &uint16, sizeof(uint16));
272 datalen += sizeof(uint16);
273 memcpy(p, oldpath, pathlen);
278 /* return the packet len */
283 * Send the fce information to all (connected) listeners
284 * We dont give return code because all errors are handled internally (I hope..)
286 static void send_fce_event(const AFPObj *obj, int event, const char *path, const char *oldpath)
288 static bool first_event = true;
289 static uint32_t event_id = 0; /* the unique packet couter to detect packet/data loss. Going from 0xFFFFFFFF to 0x0 is a valid increment */
291 time_t now = time(NULL);
295 if (first_event == true) {
298 struct passwd *pwd = getpwuid(obj->uid);
299 user = strdup(pwd->pw_name);
301 switch (obj->fce_version) {
303 /* fce_ev_info unused */
306 fce_ev_info = FCE_EV_INFO_PID | FCE_EV_INFO_USER;
310 LOG(log_error, logtype_fce, "Unsupported FCE protocol version %d", obj->fce_version);
315 /* Notify listeners the we start from the beginning */
316 send_fce_event(obj, FCE_CONN_START, "", NULL);
320 if (obj->fce_notify_script) {
321 static bstring quote = NULL;
322 static bstring quoterep = NULL;
323 static bstring slash = NULL;
324 static bstring slashrep = NULL;
327 quote = bfromcstr("'");
328 quoterep = bfromcstr("'\\''");
329 slash = bfromcstr("\\");
330 slashrep = bfromcstr("\\\\");
333 bstring cmd = bformat("%s -v %d -e %s -i %" PRIu32 "",
334 obj->fce_notify_script,
336 fce_event_names[event],
340 bstring bpath = bfromcstr(path);
341 bfindreplace(bpath, slash, slashrep, 0);
342 bfindreplace(bpath, quote, quoterep, 0);
343 bformata(cmd, " -P '%s'", bdata(bpath));
346 if (fce_ev_info | FCE_EV_INFO_PID)
347 bformata(cmd, " -p %" PRIu64 "", (uint64_t)getpid());
348 if (fce_ev_info | FCE_EV_INFO_USER)
349 bformata(cmd, " -u %s", user);
351 bstring boldpath = bfromcstr(oldpath);
352 bfindreplace(boldpath, slash, slashrep, 0);
353 bfindreplace(boldpath, quote, quoterep, 0);
354 bformata(cmd, " -S '%s'", bdata(boldpath));
357 (void)afprun_bg(1, bdata(cmd));
361 for (int i = 0; i < udp_sockets; i++) {
363 struct udp_entry *udp_entry = udp_socket_list + i;
365 /* we had a problem earlier ? */
366 if (udp_entry->sock == -1) {
367 /* We still have to wait ?*/
368 if (now < udp_entry->next_try_on_error)
372 udp_entry->sock = socket(udp_entry->addrinfo.ai_family,
373 udp_entry->addrinfo.ai_socktype,
374 udp_entry->addrinfo.ai_protocol);
376 if (udp_entry->sock == -1) {
377 /* failed again, so go to rest again */
378 LOG(log_error, logtype_fce, "Cannot recreate socket for fce UDP connection: errno %d", errno );
380 udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;
384 udp_entry->next_try_on_error = 0;
386 /* Okay, we have a running socket again, send server that we had a problem on our side*/
387 data_len = build_fce_packet(obj, iobuf, FCE_CONN_BROKEN, "", NULL, getpid(), user, 0);
389 sendto(udp_entry->sock,
393 (struct sockaddr *)&udp_entry->sockaddr,
394 udp_entry->addrinfo.ai_addrlen);
397 /* build our data packet */
398 data_len = build_fce_packet(obj, iobuf, event, path, oldpath, getpid(), user, event_id);
400 sent_data = sendto(udp_entry->sock,
404 (struct sockaddr *)&udp_entry->sockaddr,
405 udp_entry->addrinfo.ai_addrlen);
408 if (sent_data != data_len) {
409 /* Argh, socket broke, we close and retry later */
410 LOG(log_error, logtype_fce, "send_fce_event: error sending packet to %s:%s, transfered %d of %d: %s",
411 udp_entry->addr, udp_entry->port, sent_data, data_len, strerror(errno));
413 close( udp_entry->sock );
414 udp_entry->sock = -1;
415 udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;
422 static int add_udp_socket(const char *target_ip, const char *target_port )
424 if (target_port == NULL)
425 target_port = FCE_DEFAULT_PORT_STRING;
427 if (udp_sockets >= FCE_MAX_UDP_SOCKS) {
428 LOG(log_error, logtype_fce, "Too many file change api UDP connections (max %d allowed)", FCE_MAX_UDP_SOCKS );
432 udp_socket_list[udp_sockets].addr = strdup(target_ip);
433 udp_socket_list[udp_sockets].port = strdup(target_port);
434 udp_socket_list[udp_sockets].sock = -1;
435 memset(&udp_socket_list[udp_sockets].addrinfo, 0, sizeof(struct addrinfo));
436 memset(&udp_socket_list[udp_sockets].sockaddr, 0, sizeof(struct sockaddr_storage));
437 udp_socket_list[udp_sockets].next_try_on_error = 0;
444 static void save_close_event(const AFPObj *obj, const char *path)
446 time_t now = time(NULL);
448 /* Check if it's a close for the same event as the last one */
449 if (last_close_event.time /* is there any saved event ? */
450 && (strcmp(path, last_close_event.path) != 0)) {
451 /* no, so send the saved event out now */
452 send_fce_event(obj, FCE_FILE_MODIFY,last_close_event.path, NULL);
455 LOG(log_debug, logtype_fce, "save_close_event: %s", path);
457 last_close_event.time = now;
458 strncpy(last_close_event.path, path, MAXPATHLEN);
461 static void fce_init_ign_names(const char *ignores)
464 char *names = strdup(ignores);
470 for (; names[i] && names[i] != '/'; i++)
477 skip_files = calloc(count + 1, sizeof(char *));
479 for (i = 0, p = strtok(names, "/"); p ; p = strtok(NULL, "/"))
480 skip_files[i++] = strdup(p);
487 * Dispatcher for all incoming file change events
490 int fce_register(const AFPObj *obj, fce_ev_t event, const char *path, const char *oldpath)
492 static bool first_event = true;
495 if (!(fce_ev_enabled & (1 << event)))
498 AFP_ASSERT(event >= FCE_FIRST_EVENT && event <= FCE_LAST_EVENT);
501 LOG(log_debug, logtype_fce, "register_fce(path: %s, event: %s)",
502 path, fce_event_names[event]);
504 bname = basename_safe(path);
506 if ((udp_sockets == 0) && (obj->fce_notify_script == NULL)) {
507 /* No listeners configured */
511 /* do some initialization on the fly the first time */
513 fce_initialize_history();
514 fce_init_ign_names(obj->fce_ign_names);
518 /* handle files which should not cause events (.DS_Store atc. ) */
519 for (int i = 0; skip_files[i] != NULL; i++) {
520 if (strcmp(bname, skip_files[i]) == 0)
524 /* Can we ignore this event based on type or history? */
525 if (fce_handle_coalescation(event, path)) {
526 LOG(log_debug9, logtype_fce, "Coalesced fc event <%d> for <%s>", event, path);
531 case FCE_FILE_MODIFY:
532 save_close_event(obj, path);
535 send_fce_event(obj, event, path, oldpath);
542 static void check_saved_close_events(const AFPObj *obj)
544 time_t now = time(NULL);
546 /* check if configured holdclose time has passed */
547 if (last_close_event.time && ((last_close_event.time + obj->options.fce_fmodwait) < now)) {
548 LOG(log_debug, logtype_fce, "check_saved_close_events: sending event: %s", last_close_event.path);
549 /* yes, send event */
550 send_fce_event(obj, FCE_FILE_MODIFY, &last_close_event.path[0], NULL);
551 last_close_event.path[0] = 0;
552 last_close_event.time = 0;
556 /******************** External calls start here **************************/
559 * API-Calls for file change api, called form outside (file.c directory.c ofork.c filedir.c)
561 void fce_pending_events(const AFPObj *obj)
565 check_saved_close_events(obj);
570 * Extern connect to afpd parameter, can be called multiple times for multiple listeners (up to MAX_UDP_SOCKS times)
573 int fce_add_udp_socket(const char *target)
575 const char *port = FCE_DEFAULT_PORT_STRING;
576 char target_ip[256] = {""};
578 strncpy(target_ip, target, sizeof(target_ip) -1);
580 char *port_delim = strchr( target_ip, ':' );
583 port = port_delim + 1;
585 return add_udp_socket(target_ip, port);
588 int fce_set_events(const char *events)
600 for (p = strtok(e, ", "); p; p = strtok(NULL, ", ")) {
601 if (strcmp(p, "fmod") == 0) {
602 fce_ev_enabled |= (1 << FCE_FILE_MODIFY);
603 } else if (strcmp(p, "fdel") == 0) {
604 fce_ev_enabled |= (1 << FCE_FILE_DELETE);
605 } else if (strcmp(p, "ddel") == 0) {
606 fce_ev_enabled |= (1 << FCE_DIR_DELETE);
607 } else if (strcmp(p, "fcre") == 0) {
608 fce_ev_enabled |= (1 << FCE_FILE_CREATE);
609 } else if (strcmp(p, "dcre") == 0) {
610 fce_ev_enabled |= (1 << FCE_DIR_CREATE);
611 } else if (strcmp(p, "fmov") == 0) {
612 fce_ev_enabled |= (1 << FCE_FILE_MOVE);
613 } else if (strcmp(p, "dmov") == 0) {
614 fce_ev_enabled |= (1 << FCE_DIR_MOVE);
615 } else if (strcmp(p, "login") == 0) {
616 fce_ev_enabled |= (1 << FCE_LOGIN);
617 } else if (strcmp(p, "logout") == 0) {
618 fce_ev_enabled |= (1 << FCE_LOGOUT);