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 <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"
62 /* We store our connection data here */
63 static struct udp_entry udp_socket_list[FCE_MAX_UDP_SOCKS];
64 static int udp_sockets = 0;
65 static int udp_initialized = FCE_FALSE;
66 static unsigned long fce_ev_enabled =
67 (1 << FCE_FILE_MODIFY) |
68 (1 << FCE_FILE_DELETE) |
69 (1 << FCE_DIR_DELETE) |
70 (1 << FCE_FILE_CREATE) |
71 (1 << FCE_DIR_CREATE);
73 static uint64_t tm_used; /* used for passing to event handler */
75 static char iobuf[MAXIOBUF];
76 static const char *skip_files[] =
81 static struct fce_close_event last_close_event;
83 static char *fce_event_names[] = {
95 * Initialize network structs for any listeners
96 * We dont give return code because all errors are handled internally (I hope..)
102 struct addrinfo hints, *servinfo, *p;
104 if (udp_initialized == FCE_TRUE)
107 memset(&hints, 0, sizeof hints);
108 hints.ai_family = AF_UNSPEC;
109 hints.ai_socktype = SOCK_DGRAM;
111 for (int i = 0; i < udp_sockets; i++) {
112 struct udp_entry *udp_entry = udp_socket_list + i;
114 /* Close any pending sockets */
115 if (udp_entry->sock != -1)
116 close(udp_entry->sock);
118 if ((rv = getaddrinfo(udp_entry->addr, udp_entry->port, &hints, &servinfo)) != 0) {
119 LOG(log_error, logtype_fce, "fce_init_udp: getaddrinfo(%s:%s): %s",
120 udp_entry->addr, udp_entry->port, gai_strerror(rv));
124 /* loop through all the results and make a socket */
125 for (p = servinfo; p != NULL; p = p->ai_next) {
126 if ((udp_entry->sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
127 LOG(log_error, logtype_fce, "fce_init_udp: socket(%s:%s): %s",
128 udp_entry->addr, udp_entry->port, strerror(errno));
135 LOG(log_error, logtype_fce, "fce_init_udp: no socket for %s:%s",
136 udp_entry->addr, udp_entry->port);
138 udp_entry->addrinfo = *p;
139 memcpy(&udp_entry->addrinfo, p, sizeof(struct addrinfo));
140 memcpy(&udp_entry->sockaddr, p->ai_addr, sizeof(struct sockaddr_storage));
141 freeaddrinfo(servinfo);
144 udp_initialized = FCE_TRUE;
149 if (udp_initialized == FCE_FALSE )
152 for (int i = 0; i < udp_sockets; i++)
154 struct udp_entry *udp_entry = udp_socket_list + i;
156 /* Close any pending sockets */
157 if (udp_entry->sock != -1)
159 close( udp_entry->sock );
160 udp_entry->sock = -1;
163 udp_initialized = FCE_FALSE;
167 * Construct a UDP packet for our listeners and return packet size
169 static ssize_t build_fce_packet( struct fce_packet *packet, char *path, int mode, uint32_t event_id )
172 ssize_t data_len = 0;
175 /* Set content of packet */
176 memcpy(packet->magic, FCE_PACKET_MAGIC, sizeof(packet->magic) );
177 packet->version = FCE_PACKET_VERSION;
180 packet->event_id = event_id;
182 pathlen = strlen(path); /* exclude string terminator */
184 /* This should never happen, but before we bust this server, we send nonsense, fce listener has to cope */
185 if (pathlen >= MAXPATHLEN)
186 pathlen = MAXPATHLEN - 1;
188 packet->datalen = pathlen;
190 /* This is the payload len. Means: the packet has len bytes more until packet is finished */
191 data_len = FCE_PACKET_HEADER_SIZE + pathlen;
195 t = (uint64_t *)packet->data;
196 *t = hton64(tm_used);
197 memcpy(packet->data + sizeof(tm_used), path, pathlen);
199 packet->datalen = pathlen + sizeof(tm_used);
200 data_len += sizeof(tm_used);
203 memcpy(packet->data, path, pathlen);
207 /* return the packet len */
212 * Handle Endianess and write into buffer w/o padding
214 static void pack_fce_packet(struct fce_packet *packet, unsigned char *buf, int maxlen)
216 unsigned char *p = buf;
218 memcpy(p, &packet->magic[0], sizeof(packet->magic));
219 p += sizeof(packet->magic);
221 *p = packet->version;
227 uint32_t *id = (uint32_t*)p;
228 *id = htonl(packet->event_id);
229 p += sizeof(packet->event_id);
231 uint16_t *l = ( uint16_t *)p;
232 *l = htons(packet->datalen);
233 p += sizeof(packet->datalen);
235 if (((p - buf) + packet->datalen) < maxlen) {
236 memcpy(p, &packet->data[0], packet->datalen);
241 * Send the fce information to all (connected) listeners
242 * We dont give return code because all errors are handled internally (I hope..)
244 static void send_fce_event( char *path, int mode )
246 static int first_event = FCE_TRUE;
248 struct fce_packet packet;
249 void *data = &packet;
250 static uint32_t event_id = 0; /* the unique packet couter to detect packet/data loss. Going from 0xFFFFFFFF to 0x0 is a valid increment */
251 time_t now = time(NULL);
253 LOG(log_debug, logtype_fce, "send_fce_event: start");
256 if (first_event == FCE_TRUE) {
257 first_event = FCE_FALSE;
259 /* Notify listeners the we start from the beginning */
260 send_fce_event( "", FCE_CONN_START );
263 /* build our data packet */
264 ssize_t data_len = build_fce_packet( &packet, path, mode, ++event_id );
265 pack_fce_packet(&packet, iobuf, MAXIOBUF);
267 for (int i = 0; i < udp_sockets; i++)
270 struct udp_entry *udp_entry = udp_socket_list + i;
272 /* we had a problem earlier ? */
273 if (udp_entry->sock == -1)
275 /* We still have to wait ?*/
276 if (now < udp_entry->next_try_on_error)
280 udp_entry->sock = socket(udp_entry->addrinfo.ai_family,
281 udp_entry->addrinfo.ai_socktype,
282 udp_entry->addrinfo.ai_protocol);
284 if (udp_entry->sock == -1) {
285 /* failed again, so go to rest again */
286 LOG(log_error, logtype_fce, "Cannot recreate socket for fce UDP connection: errno %d", errno );
288 udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;
292 udp_entry->next_try_on_error = 0;
294 /* Okay, we have a running socket again, send server that we had a problem on our side*/
295 data_len = build_fce_packet( &packet, "", FCE_CONN_BROKEN, 0 );
296 pack_fce_packet(&packet, iobuf, MAXIOBUF);
298 sendto(udp_entry->sock,
302 (struct sockaddr *)&udp_entry->sockaddr,
303 udp_entry->addrinfo.ai_addrlen);
305 /* Rebuild our original data packet */
306 data_len = build_fce_packet( &packet, path, mode, event_id );
307 pack_fce_packet(&packet, iobuf, MAXIOBUF);
310 sent_data = sendto(udp_entry->sock,
314 (struct sockaddr *)&udp_entry->sockaddr,
315 udp_entry->addrinfo.ai_addrlen);
318 if (sent_data != data_len) {
319 /* Argh, socket broke, we close and retry later */
320 LOG(log_error, logtype_fce, "send_fce_event: error sending packet to %s:%s, transfered %d of %d: %s",
321 udp_entry->addr, udp_entry->port, sent_data, data_len, strerror(errno));
323 close( udp_entry->sock );
324 udp_entry->sock = -1;
325 udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;
330 static int add_udp_socket(const char *target_ip, const char *target_port )
332 if (target_port == NULL)
333 target_port = FCE_DEFAULT_PORT_STRING;
335 if (udp_sockets >= FCE_MAX_UDP_SOCKS) {
336 LOG(log_error, logtype_fce, "Too many file change api UDP connections (max %d allowed)", FCE_MAX_UDP_SOCKS );
340 udp_socket_list[udp_sockets].addr = strdup(target_ip);
341 udp_socket_list[udp_sockets].port = strdup(target_port);
342 udp_socket_list[udp_sockets].sock = -1;
343 memset(&udp_socket_list[udp_sockets].addrinfo, 0, sizeof(struct addrinfo));
344 memset(&udp_socket_list[udp_sockets].sockaddr, 0, sizeof(struct sockaddr_storage));
345 udp_socket_list[udp_sockets].next_try_on_error = 0;
352 static void save_close_event(const char *path)
354 time_t now = time(NULL);
356 /* Check if it's a close for the same event as the last one */
357 if (last_close_event.time /* is there any saved event ? */
358 && (strcmp(path, last_close_event.path) != 0)) {
359 /* no, so send the saved event out now */
360 send_fce_event(last_close_event.path, FCE_FILE_MODIFY);
363 LOG(log_debug, logtype_fce, "save_close_event: %s", path);
365 last_close_event.time = now;
366 strncpy(last_close_event.path, path, MAXPATHLEN);
371 * Dispatcher for all incoming file change events
374 static int register_fce(const char *u_name, int is_dir, int mode)
376 static int first_event = FCE_TRUE;
378 AFP_ASSERT(mode >= FCE_FIRST_EVENT && mode <= FCE_LAST_EVENT);
380 LOG(log_debug, logtype_fce, "register_fce(path: %s, type: %s, event: %s",
381 fullpathname(u_name), is_dir ? "dir" : "file", fce_event_names[mode]);
383 if (udp_sockets == 0)
384 /* No listeners configured */
390 /* do some initialization on the fly the first time */
392 fce_initialize_history();
393 first_event = FCE_FALSE;
396 /* handle files which should not cause events (.DS_Store atc. ) */
397 for (int i = 0; skip_files[i] != NULL; i++)
399 if (!strcmp( u_name, skip_files[i]))
404 char full_path_buffer[MAXPATHLEN + 1] = {""};
405 const char *cwd = getcwdpath();
407 if (mode == FCE_TM_SIZE) {
408 strlcpy(full_path_buffer, u_name, MAXPATHLEN);
409 } else if (!is_dir || mode == FCE_DIR_DELETE) {
410 if (strlen( cwd ) + strlen( u_name) + 1 >= MAXPATHLEN) {
411 LOG(log_error, logtype_fce, "FCE file name too long: %s/%s", cwd, u_name );
414 sprintf( full_path_buffer, "%s/%s", cwd, u_name );
416 if (strlen( cwd ) >= MAXPATHLEN) {
417 LOG(log_error, logtype_fce, "FCE directory name too long: %s", cwd);
420 strcpy( full_path_buffer, cwd);
423 /* Can we ignore this event based on type or history? */
424 if (!(mode & FCE_TM_SIZE) && fce_handle_coalescation( full_path_buffer, is_dir, mode ))
426 LOG(log_debug9, logtype_fce, "Coalesced fc event <%d> for <%s>", mode, full_path_buffer );
430 LOG(log_debug9, logtype_fce, "Detected fc event <%d> for <%s>", mode, full_path_buffer );
432 if (mode & FCE_FILE_MODIFY) {
433 save_close_event(full_path_buffer);
437 send_fce_event( full_path_buffer, mode );
442 static void check_saved_close_events(int fmodwait)
444 time_t now = time(NULL);
446 /* check if configured holdclose time has passed */
447 if (last_close_event.time && ((last_close_event.time + fmodwait) < now)) {
448 LOG(log_debug, logtype_fce, "check_saved_close_events: sending event: %s", last_close_event.path);
449 /* yes, send event */
450 send_fce_event(&last_close_event.path[0], FCE_FILE_MODIFY);
451 last_close_event.path[0] = 0;
452 last_close_event.time = 0;
456 /******************** External calls start here **************************/
459 * API-Calls for file change api, called form outside (file.c directory.c ofork.c filedir.c)
461 #ifndef FCE_TEST_MAIN
463 void fce_pending_events(AFPObj *obj)
466 check_saved_close_events(obj->options.fce_fmodwait);
469 int fce_register_delete_file( struct path *path )
476 if (!(fce_ev_enabled & (1 << FCE_FILE_DELETE)))
479 ret = register_fce( path->u_name, false, FCE_FILE_DELETE );
483 int fce_register_delete_dir( char *name )
490 if (!(fce_ev_enabled & (1 << FCE_DIR_DELETE)))
493 ret = register_fce( name, true, FCE_DIR_DELETE);
498 int fce_register_new_dir( struct path *path )
505 if (!(fce_ev_enabled & (1 << FCE_DIR_CREATE)))
508 ret = register_fce( path->u_name, true, FCE_DIR_CREATE );
514 int fce_register_new_file( struct path *path )
521 if (!(fce_ev_enabled & (1 << FCE_FILE_CREATE)))
524 ret = register_fce( path->u_name, false, FCE_FILE_CREATE );
529 int fce_register_file_modification( struct ofork *ofork )
536 if (!(fce_ev_enabled & (1 << FCE_FILE_MODIFY)))
539 ret = register_fce(of_name(ofork), false, FCE_FILE_MODIFY );
544 int fce_register_tm_size(const char *vol, size_t used)
551 if (!(fce_ev_enabled & (1 << FCE_TM_SIZE)))
554 tm_used = used; /* oh what a hack */
555 ret = register_fce(vol, false, FCE_TM_SIZE);
563 * Extern connect to afpd parameter, can be called multiple times for multiple listeners (up to MAX_UDP_SOCKS times)
566 int fce_add_udp_socket(const char *target)
568 const char *port = FCE_DEFAULT_PORT_STRING;
569 char target_ip[256] = {""};
571 strncpy(target_ip, target, sizeof(target_ip) -1);
573 char *port_delim = strchr( target_ip, ':' );
576 port = port_delim + 1;
578 return add_udp_socket(target_ip, port);
581 int fce_set_events(const char *events)
593 for (p = strtok(e, ", "); p; p = strtok(NULL, ", ")) {
594 if (strcmp(p, "fmod") == 0) {
595 fce_ev_enabled |= (1 << FCE_FILE_MODIFY);
596 } else if (strcmp(p, "fdel") == 0) {
597 fce_ev_enabled |= (1 << FCE_FILE_DELETE);
598 } else if (strcmp(p, "ddel") == 0) {
599 fce_ev_enabled |= (1 << FCE_DIR_DELETE);
600 } else if (strcmp(p, "fcre") == 0) {
601 fce_ev_enabled |= (1 << FCE_FILE_CREATE);
602 } else if (strcmp(p, "dcre") == 0) {
603 fce_ev_enabled |= (1 << FCE_DIR_CREATE);
604 } else if (strcmp(p, "tmsz") == 0) {
605 fce_ev_enabled |= (1 << FCE_TM_SIZE);
617 void shortsleep( unsigned int us )
621 int main( int argc, char*argv[] )
625 char *port = FCE_DEFAULT_PORT_STRING;
626 char *host = "localhost";
627 int delay_between_events = 1000;
628 int event_code = FCE_FILE_MODIFY;
630 int duration_in_seconds = 0; // TILL ETERNITY
632 char *path = getcwd( pathbuff, sizeof(pathbuff) );
634 // FULLSPEED TEST IS "-s 1001" -> delay is 0 -> send packets without pause
636 while ((c = getopt(argc, argv, "d:e:h:p:P:s:")) != -1) {
639 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]);
643 duration_in_seconds = atoi(optarg);
646 event_code = atoi(optarg);
649 host = strdup(optarg);
652 port = strdup(optarg);
655 path = strdup(optarg);
658 delay_between_events = atoi(optarg);
663 sprintf(target, "%s:%s", host, port);
664 if (fce_add_udp_socket(target) != 0)
668 time_t start_time = time(NULL);
671 if (duration_in_seconds)
672 end_time = start_time + duration_in_seconds;
676 time_t now = time(NULL);
677 if (now > start_time)
680 fprintf( stdout, "%d events/s\n", ev_cnt );
683 if (end_time && now >= end_time)
686 register_fce( path, 0, event_code );
690 shortsleep( delay_between_events );