2 * Copyright (c) 2010 Mark Williams
4 * File change event API for netatalk
6 * for every detected filesystem change a UDP packet is sent to an arbitrary list
7 * of listeners. Each packet contains unix path of modified filesystem element,
8 * event reason, and a consecutive event id (32 bit). Technically we are UDP client and are sending
9 * out packets synchronuosly as they are created by the afp functions. This should not affect
10 * performance measurably. The only delaying calls occur during initialization, if we have to
11 * resolve non-IP hostnames to IP. All numeric data inside the packet is network byte order, so use
12 * ntohs / ntohl to resolve length and event id. Ideally a listener receives every packet with
13 * no gaps in event ids, starting with event id 1 and mode FCE_CONN_START followed by
14 * data events from id 2 up to 0xFFFFFFFF, followed by 0 to 0xFFFFFFFF and so on.
16 * A gap or not starting with 1 mode FCE_CONN_START or receiving mode FCE_CONN_BROKEN means that
17 * the listener has lost at least one filesystem event
19 * All Rights Reserved. See COPYRIGHT.
24 #endif /* HAVE_CONFIG_H */
34 #include <sys/param.h>
35 #include <sys/socket.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
40 #include <netatalk/at.h>
42 #include <atalk/adouble.h>
43 #include <atalk/vfs.h>
44 #include <atalk/logger.h>
45 #include <atalk/afp.h>
46 #include <atalk/util.h>
47 #include <atalk/cnid.h>
48 #include <atalk/unix.h>
49 #include <atalk/fce_api.h>
50 #include <atalk/globals.h>
54 #include "directory.h"
58 // ONLY USED IN THIS FILE
59 #include "fce_api_internal.h"
64 /* We store our connection data here */
65 static struct udp_entry udp_socket_list[FCE_MAX_UDP_SOCKS];
66 static int udp_sockets = 0;
67 static int udp_initialized = FCE_FALSE;
68 static unsigned long fce_ev_enabled =
69 (1 << FCE_FILE_MODIFY) |
70 (1 << FCE_FILE_DELETE) |
71 (1 << FCE_DIR_DELETE) |
72 (1 << FCE_FILE_CREATE) |
73 (1 << FCE_DIR_CREATE);
75 static uint64_t tm_used; /* used for passing to event handler */
77 static char iobuf[MAXIOBUF];
78 static const char *skip_files[] =
83 static struct fce_close_event last_close_event;
87 * Initialize network structs for any listeners
88 * We dont give return code because all errors are handled internally (I hope..)
94 struct addrinfo hints, *servinfo, *p;
96 if (udp_initialized == FCE_TRUE)
99 memset(&hints, 0, sizeof hints);
100 hints.ai_family = AF_UNSPEC;
101 hints.ai_socktype = SOCK_DGRAM;
103 for (int i = 0; i < udp_sockets; i++) {
104 struct udp_entry *udp_entry = udp_socket_list + i;
106 /* Close any pending sockets */
107 if (udp_entry->sock != -1)
108 close(udp_entry->sock);
110 if ((rv = getaddrinfo(udp_entry->addr, udp_entry->port, &hints, &servinfo)) != 0) {
111 LOG(log_error, logtype_afpd, "fce_init_udp: getaddrinfo(%s:%s): %s",
112 udp_entry->addr, udp_entry->port, gai_strerror(rv));
116 /* loop through all the results and make a socket */
117 for (p = servinfo; p != NULL; p = p->ai_next) {
118 if ((udp_entry->sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
119 LOG(log_error, logtype_afpd, "fce_init_udp: socket(%s:%s): %s",
120 udp_entry->addr, udp_entry->port, strerror(errno));
127 LOG(log_error, logtype_afpd, "fce_init_udp: no socket for %s:%s",
128 udp_entry->addr, udp_entry->port);
130 udp_entry->addrinfo = *p;
131 memcpy(&udp_entry->addrinfo, p, sizeof(struct addrinfo));
132 memcpy(&udp_entry->sockaddr, p->ai_addr, sizeof(struct sockaddr_storage));
133 freeaddrinfo(servinfo);
136 udp_initialized = FCE_TRUE;
141 if (udp_initialized == FCE_FALSE )
144 for (int i = 0; i < udp_sockets; i++)
146 struct udp_entry *udp_entry = udp_socket_list + i;
148 /* Close any pending sockets */
149 if (udp_entry->sock != -1)
151 close( udp_entry->sock );
152 udp_entry->sock = -1;
155 udp_initialized = FCE_FALSE;
159 * Construct a UDP packet for our listeners and return packet size
161 static ssize_t build_fce_packet( struct fce_packet *packet, char *path, int mode, uint32_t event_id )
164 ssize_t data_len = 0;
167 /* Set content of packet */
168 memcpy(packet->magic, FCE_PACKET_MAGIC, sizeof(packet->magic) );
169 packet->version = FCE_PACKET_VERSION;
172 packet->event_id = event_id;
174 pathlen = strlen(path); /* exclude string terminator */
176 /* This should never happen, but before we bust this server, we send nonsense, fce listener has to cope */
177 if (pathlen >= MAXPATHLEN)
178 pathlen = MAXPATHLEN - 1;
180 packet->datalen = pathlen;
182 /* This is the payload len. Means: the packet has len bytes more until packet is finished */
183 data_len = FCE_PACKET_HEADER_SIZE + pathlen;
187 t = (uint64_t *)packet->data;
188 *t = hton64(tm_used);
189 memcpy(packet->data + sizeof(tm_used), path, pathlen);
191 packet->datalen = pathlen + sizeof(tm_used);
192 data_len += sizeof(tm_used);
195 memcpy(packet->data, path, pathlen);
199 /* return the packet len */
204 * Handle Endianess and write into buffer w/o padding
206 static void pack_fce_packet(struct fce_packet *packet, unsigned char *buf, int maxlen)
208 unsigned char *p = buf;
210 memcpy(p, &packet->magic[0], sizeof(packet->magic));
211 p += sizeof(packet->magic);
213 *p = packet->version;
219 uint32_t *id = (uint32_t*)p;
220 *id = htonl(packet->event_id);
221 p += sizeof(packet->event_id);
223 uint16_t *l = ( uint16_t *)p;
224 *l = htons(packet->datalen);
225 p += sizeof(packet->datalen);
227 if (((p - buf) + packet->datalen) < maxlen) {
228 memcpy(p, &packet->data[0], packet->datalen);
233 * Send the fce information to all (connected) listeners
234 * We dont give return code because all errors are handled internally (I hope..)
236 static void send_fce_event( char *path, int mode )
238 static int first_event = FCE_TRUE;
240 struct fce_packet packet;
241 void *data = &packet;
242 static uint32_t event_id = 0; /* the unique packet couter to detect packet/data loss. Going from 0xFFFFFFFF to 0x0 is a valid increment */
243 time_t now = time(NULL);
245 LOG(log_debug, logtype_afpd, "send_fce_event: start");
248 if (first_event == FCE_TRUE) {
249 first_event = FCE_FALSE;
251 /* Notify listeners the we start from the beginning */
252 send_fce_event( "", FCE_CONN_START );
255 /* build our data packet */
256 ssize_t data_len = build_fce_packet( &packet, path, mode, ++event_id );
257 pack_fce_packet(&packet, iobuf, MAXIOBUF);
259 for (int i = 0; i < udp_sockets; i++)
262 struct udp_entry *udp_entry = udp_socket_list + i;
264 /* we had a problem earlier ? */
265 if (udp_entry->sock == -1)
267 /* We still have to wait ?*/
268 if (now < udp_entry->next_try_on_error)
272 udp_entry->sock = socket(udp_entry->addrinfo.ai_family,
273 udp_entry->addrinfo.ai_socktype,
274 udp_entry->addrinfo.ai_protocol);
276 if (udp_entry->sock == -1) {
277 /* failed again, so go to rest again */
278 LOG(log_error, logtype_afpd, "Cannot recreate socket for fce UDP connection: errno %d", errno );
280 udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;
284 udp_entry->next_try_on_error = 0;
286 /* Okay, we have a running socket again, send server that we had a problem on our side*/
287 data_len = build_fce_packet( &packet, "", FCE_CONN_BROKEN, 0 );
288 pack_fce_packet(&packet, iobuf, MAXIOBUF);
290 sendto(udp_entry->sock,
294 (struct sockaddr *)&udp_entry->sockaddr,
295 udp_entry->addrinfo.ai_addrlen);
297 /* Rebuild our original data packet */
298 data_len = build_fce_packet( &packet, path, mode, event_id );
299 pack_fce_packet(&packet, iobuf, MAXIOBUF);
302 sent_data = sendto(udp_entry->sock,
306 (struct sockaddr *)&udp_entry->sockaddr,
307 udp_entry->addrinfo.ai_addrlen);
310 if (sent_data != data_len) {
311 /* Argh, socket broke, we close and retry later */
312 LOG(log_error, logtype_afpd, "send_fce_event: error sending packet to %s:%s, transfered %d of %d: %s",
313 udp_entry->addr, udp_entry->port, sent_data, data_len, strerror(errno));
315 close( udp_entry->sock );
316 udp_entry->sock = -1;
317 udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;
322 static int add_udp_socket(const char *target_ip, const char *target_port )
324 if (target_port == NULL)
325 target_port = FCE_DEFAULT_PORT_STRING;
327 if (udp_sockets >= FCE_MAX_UDP_SOCKS) {
328 LOG(log_error, logtype_afpd, "Too many file change api UDP connections (max %d allowed)", FCE_MAX_UDP_SOCKS );
332 udp_socket_list[udp_sockets].addr = strdup(target_ip);
333 udp_socket_list[udp_sockets].port = strdup(target_port);
334 udp_socket_list[udp_sockets].sock = -1;
335 memset(&udp_socket_list[udp_sockets].addrinfo, 0, sizeof(struct addrinfo));
336 memset(&udp_socket_list[udp_sockets].sockaddr, 0, sizeof(struct sockaddr_storage));
337 udp_socket_list[udp_sockets].next_try_on_error = 0;
344 static void save_close_event(const char *path)
346 time_t now = time(NULL);
348 /* Check if it's a close for the same event as the last one */
349 if (last_close_event.time /* is there any saved event ? */
350 && (strcmp(path, last_close_event.path) != 0)) {
351 /* no, so send the saved event out now */
352 send_fce_event(last_close_event.path, FCE_FILE_MODIFY);
355 LOG(log_debug, logtype_afpd, "save_close_event: %s", path);
357 last_close_event.time = now;
358 strncpy(last_close_event.path, path, MAXPATHLEN);
363 * Dispatcher for all incoming file change events
366 static int register_fce(const char *u_name, int is_dir, int mode)
368 static int first_event = FCE_TRUE;
370 if (udp_sockets == 0)
371 /* No listeners configured */
377 /* do some initialization on the fly the first time */
379 fce_initialize_history();
380 first_event = FCE_FALSE;
383 /* handle files which should not cause events (.DS_Store atc. ) */
384 for (int i = 0; skip_files[i] != NULL; i++)
386 if (!strcmp( u_name, skip_files[i]))
391 char full_path_buffer[MAXPATHLEN + 1] = {""};
392 const char *cwd = getcwdpath();
394 if (mode == FCE_TM_SIZE) {
395 strlcpy(full_path_buffer, u_name, MAXPATHLEN);
396 } else if (!is_dir || mode == FCE_DIR_DELETE) {
397 if (strlen( cwd ) + strlen( u_name) + 1 >= MAXPATHLEN) {
398 LOG(log_error, logtype_afpd, "FCE file name too long: %s/%s", cwd, u_name );
401 sprintf( full_path_buffer, "%s/%s", cwd, u_name );
403 if (strlen( cwd ) >= MAXPATHLEN) {
404 LOG(log_error, logtype_afpd, "FCE directory name too long: %s", cwd);
407 strcpy( full_path_buffer, cwd);
410 /* Can we ignore this event based on type or history? */
411 if (!(mode & FCE_TM_SIZE) && fce_handle_coalescation( full_path_buffer, is_dir, mode ))
413 LOG(log_debug9, logtype_afpd, "Coalesced fc event <%d> for <%s>", mode, full_path_buffer );
417 LOG(log_debug9, logtype_afpd, "Detected fc event <%d> for <%s>", mode, full_path_buffer );
419 if (mode & FCE_FILE_MODIFY) {
420 save_close_event(full_path_buffer);
424 send_fce_event( full_path_buffer, mode );
429 static void check_saved_close_events(int fmodwait)
431 time_t now = time(NULL);
433 /* check if configured holdclose time has passed */
434 if (last_close_event.time && ((last_close_event.time + fmodwait) < now)) {
435 LOG(log_debug, logtype_afpd, "check_saved_close_events: sending event: %s", last_close_event.path);
436 /* yes, send event */
437 send_fce_event(&last_close_event.path[0], FCE_FILE_MODIFY);
438 last_close_event.path[0] = 0;
439 last_close_event.time = 0;
443 /******************** External calls start here **************************/
446 * API-Calls for file change api, called form outside (file.c directory.c ofork.c filedir.c)
448 #ifndef FCE_TEST_MAIN
450 void fce_pending_events(AFPObj *obj)
453 check_saved_close_events(obj->options.fce_fmodwait);
456 int fce_register_delete_file( struct path *path )
463 if (!(fce_ev_enabled & (1 << FCE_FILE_DELETE)))
466 ret = register_fce( path->u_name, false, FCE_FILE_DELETE );
470 int fce_register_delete_dir( char *name )
477 if (!(fce_ev_enabled & (1 << FCE_DIR_DELETE)))
480 ret = register_fce( name, true, FCE_DIR_DELETE);
485 int fce_register_new_dir( struct path *path )
492 if (!(fce_ev_enabled & (1 << FCE_DIR_CREATE)))
495 ret = register_fce( path->u_name, true, FCE_DIR_CREATE );
501 int fce_register_new_file( struct path *path )
508 if (!(fce_ev_enabled & (1 << FCE_FILE_CREATE)))
511 ret = register_fce( path->u_name, false, FCE_FILE_CREATE );
516 int fce_register_file_modification( struct ofork *ofork )
522 if (ofork == NULL || ofork->of_vol == NULL)
525 if (!(fce_ev_enabled & (1 << FCE_FILE_MODIFY)))
530 if (NULL == (u_name = mtoupath(vol, of_name(ofork), ofork->of_did, utf8_encoding())))
535 ret = register_fce( u_name, false, FCE_FILE_MODIFY );
540 int fce_register_tm_size(const char *vol, size_t used)
547 if (!(fce_ev_enabled & (1 << FCE_TM_SIZE)))
550 tm_used = used; /* oh what a hack */
551 ret = register_fce(vol, false, FCE_TM_SIZE);
559 * Extern connect to afpd parameter, can be called multiple times for multiple listeners (up to MAX_UDP_SOCKS times)
562 int fce_add_udp_socket(const char *target)
564 const char *port = FCE_DEFAULT_PORT_STRING;
565 char target_ip[256] = {""};
567 strncpy(target_ip, target, sizeof(target_ip) -1);
569 char *port_delim = strchr( target_ip, ':' );
572 port = port_delim + 1;
574 return add_udp_socket(target_ip, port);
577 int fce_set_events(const char *events)
589 for (p = strtok(e, ","); p; p = strtok(NULL, ",")) {
590 if (strcmp(p, "fmod") == 0) {
591 fce_ev_enabled |= (1 << FCE_FILE_MODIFY);
592 } else if (strcmp(p, "fdel") == 0) {
593 fce_ev_enabled |= (1 << FCE_FILE_DELETE);
594 } else if (strcmp(p, "ddel") == 0) {
595 fce_ev_enabled |= (1 << FCE_DIR_DELETE);
596 } else if (strcmp(p, "fcre") == 0) {
597 fce_ev_enabled |= (1 << FCE_FILE_CREATE);
598 } else if (strcmp(p, "dcre") == 0) {
599 fce_ev_enabled |= (1 << FCE_DIR_CREATE);
600 } else if (strcmp(p, "tmsz") == 0) {
601 fce_ev_enabled |= (1 << FCE_TM_SIZE);
613 void shortsleep( unsigned int us )
617 int main( int argc, char*argv[] )
621 char *port = FCE_DEFAULT_PORT_STRING;
622 char *host = "localhost";
623 int delay_between_events = 1000;
624 int event_code = FCE_FILE_MODIFY;
626 int duration_in_seconds = 0; // TILL ETERNITY
628 char *path = getcwd( pathbuff, sizeof(pathbuff) );
630 // FULLSPEED TEST IS "-s 1001" -> delay is 0 -> send packets without pause
632 while ((c = getopt(argc, argv, "d:e:h:p:P:s:")) != -1) {
635 fprintf(stdout, "%s: [ -p Port -h Listener1 [ -h Listener2 ...] -P path -s Delay_between_events_in_us -e event_code -d Duration ]\n", argv[0]);
639 duration_in_seconds = atoi(optarg);
642 event_code = atoi(optarg);
645 host = strdup(optarg);
648 port = strdup(optarg);
651 path = strdup(optarg);
654 delay_between_events = atoi(optarg);
659 sprintf(target, "%s:%s", host, port);
660 if (fce_add_udp_socket(target) != 0)
664 time_t start_time = time(NULL);
667 if (duration_in_seconds)
668 end_time = start_time + duration_in_seconds;
672 time_t now = time(NULL);
673 if (now > start_time)
676 fprintf( stdout, "%d events/s\n", ev_cnt );
679 if (end_time && now >= end_time)
682 register_fce( path, 0, event_code );
686 shortsleep( delay_between_events );