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;
160 * Construct a UDP packet for our listeners and return packet size
162 static ssize_t build_fce_packet( struct fce_packet *packet, char *path, int mode, uint32_t event_id )
165 ssize_t data_len = 0;
167 strncpy(packet->magic, FCE_PACKET_MAGIC, sizeof(packet->magic) );
168 packet->version = FCE_PACKET_VERSION;
170 packet->event_id = event_id;
172 pathlen = strlen(path) + 1; /* include string terminator */
174 /* This should never happen, but before we bust this server, we send nonsense, fce listener has to cope */
175 if (pathlen >= MAXPATHLEN)
176 pathlen = MAXPATHLEN - 1;
178 /* This is the payload len. Means: the stream has len bytes more until packet is finished */
179 /* A server should read the first 16 byte, decode them and then fetch the rest */
180 data_len = FCE_PACKET_HEADER_SIZE + pathlen;
181 packet->datalen = pathlen;
185 tm_used = hton64(tm_used);
186 memcpy(packet->data, &tm_used, sizeof(tm_used));
187 strncpy(packet->data + sizeof(tm_used), path, pathlen);
189 packet->datalen += sizeof(tm_used);
190 data_len += sizeof(tm_used);
193 strncpy(packet->data, path, pathlen);
197 /* return the packet len */
201 static int pack_fce_packet(struct fce_packet *packet, unsigned char *buf)
203 unsigned char *p = buf;
205 memcpy(p, &packet->magic[0], sizeof(packet->magic));
206 p += sizeof(packet->magic);
208 *p = packet->version;
214 uint32_t id = htonl(packet->event_id);
215 memcpy(p, &id, sizeof(id));
216 p += sizeof(packet->event_id);
218 uint16_t l = htons(packet->datalen);
219 memcpy(p, &l, sizeof(l));
222 memcpy(p, &packet->data[0], packet->datalen);
223 p += packet->datalen;
229 * Send the fce information to all (connected) listeners
230 * We dont give return code because all errors are handled internally (I hope..)
232 static void send_fce_event( char *path, int mode )
234 static int first_event = FCE_TRUE;
236 struct fce_packet packet;
237 void *data = &packet;
238 static uint32_t event_id = 0; /* the unique packet couter to detect packet/data loss. Going from 0xFFFFFFFF to 0x0 is a valid increment */
239 time_t now = time(NULL);
241 LOG(log_debug, logtype_afpd, "send_fce_event: start");
244 if (first_event == FCE_TRUE) {
245 first_event = FCE_FALSE;
247 /* Notify listeners the we start from the beginning */
248 send_fce_event( "", FCE_CONN_START );
251 /* build our data packet */
252 ssize_t data_len = build_fce_packet( &packet, path, mode, ++event_id );
253 pack_fce_packet(&packet, iobuf);
255 for (int i = 0; i < udp_sockets; i++)
258 struct udp_entry *udp_entry = udp_socket_list + i;
260 /* we had a problem earlier ? */
261 if (udp_entry->sock == -1)
263 /* We still have to wait ?*/
264 if (now < udp_entry->next_try_on_error)
268 udp_entry->sock = socket(udp_entry->addrinfo.ai_family,
269 udp_entry->addrinfo.ai_socktype,
270 udp_entry->addrinfo.ai_protocol);
272 if (udp_entry->sock == -1) {
273 /* failed again, so go to rest again */
274 LOG(log_error, logtype_afpd, "Cannot recreate socket for fce UDP connection: errno %d", errno );
276 udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;
280 udp_entry->next_try_on_error = 0;
282 /* Okay, we have a running socket again, send server that we had a problem on our side*/
283 data_len = build_fce_packet( &packet, "", FCE_CONN_BROKEN, 0 );
284 pack_fce_packet(&packet, iobuf);
286 sendto(udp_entry->sock,
290 (struct sockaddr *)&udp_entry->sockaddr,
291 udp_entry->addrinfo.ai_addrlen);
293 /* Rebuild our original data packet */
294 data_len = build_fce_packet( &packet, path, mode, event_id );
295 pack_fce_packet(&packet, iobuf);
298 sent_data = sendto(udp_entry->sock,
302 (struct sockaddr *)&udp_entry->sockaddr,
303 udp_entry->addrinfo.ai_addrlen);
306 if (sent_data != data_len) {
307 /* Argh, socket broke, we close and retry later */
308 LOG(log_error, logtype_afpd, "send_fce_event: error sending packet to %s:%s, transfered %d of %d: %s",
309 udp_entry->addr, udp_entry->port, sent_data, data_len, strerror(errno));
311 close( udp_entry->sock );
312 udp_entry->sock = -1;
313 udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;
318 static int add_udp_socket(const char *target_ip, const char *target_port )
320 if (target_port == NULL)
321 target_port = FCE_DEFAULT_PORT_STRING;
323 if (udp_sockets >= FCE_MAX_UDP_SOCKS) {
324 LOG(log_error, logtype_afpd, "Too many file change api UDP connections (max %d allowed)", FCE_MAX_UDP_SOCKS );
328 udp_socket_list[udp_sockets].addr = strdup(target_ip);
329 udp_socket_list[udp_sockets].port = strdup(target_port);
330 udp_socket_list[udp_sockets].sock = -1;
331 memset(&udp_socket_list[udp_sockets].addrinfo, 0, sizeof(struct addrinfo));
332 memset(&udp_socket_list[udp_sockets].sockaddr, 0, sizeof(struct sockaddr_storage));
333 udp_socket_list[udp_sockets].next_try_on_error = 0;
340 static void save_close_event(const char *path)
342 time_t now = time(NULL);
344 /* Check if it's a close for the same event as the last one */
345 if (last_close_event.time /* is there any saved event ? */
346 && (strcmp(path, last_close_event.path) != 0)) {
347 /* no, so send the saved event out now */
348 send_fce_event(last_close_event.path, FCE_FILE_MODIFY);
351 LOG(log_debug, logtype_afpd, "save_close_event: %s", path);
353 last_close_event.time = now;
354 strncpy(last_close_event.path, path, MAXPATHLEN);
359 * Dispatcher for all incoming file change events
362 static int register_fce(const char *u_name, int is_dir, int mode)
364 static int first_event = FCE_TRUE;
366 if (udp_sockets == 0)
367 /* No listeners configured */
373 /* do some initialization on the fly the first time */
375 fce_initialize_history();
376 first_event = FCE_FALSE;
379 /* handle files which should not cause events (.DS_Store atc. ) */
380 for (int i = 0; skip_files[i] != NULL; i++)
382 if (!strcmp( u_name, skip_files[i]))
387 char full_path_buffer[MAXPATHLEN + 1] = {""};
388 const char *cwd = getcwdpath();
390 if (mode == FCE_TM_SIZE) {
391 strlcpy(full_path_buffer, u_name, MAXPATHLEN);
392 } else if (!is_dir || mode == FCE_DIR_DELETE) {
393 if (strlen( cwd ) + strlen( u_name) + 1 >= MAXPATHLEN) {
394 LOG(log_error, logtype_afpd, "FCE file name too long: %s/%s", cwd, u_name );
397 sprintf( full_path_buffer, "%s/%s", cwd, u_name );
399 if (strlen( cwd ) >= MAXPATHLEN) {
400 LOG(log_error, logtype_afpd, "FCE directory name too long: %s", cwd);
403 strcpy( full_path_buffer, cwd);
406 /* Can we ignore this event based on type or history? */
407 if (!(mode & FCE_TM_SIZE) && fce_handle_coalescation( full_path_buffer, is_dir, mode ))
409 LOG(log_debug9, logtype_afpd, "Coalesced fc event <%d> for <%s>", mode, full_path_buffer );
413 LOG(log_debug9, logtype_afpd, "Detected fc event <%d> for <%s>", mode, full_path_buffer );
415 if (mode & FCE_FILE_MODIFY) {
416 save_close_event(full_path_buffer);
420 send_fce_event( full_path_buffer, mode );
425 static void check_saved_close_events(int fmodwait)
427 time_t now = time(NULL);
429 /* check if configured holdclose time has passed */
430 if (last_close_event.time && ((last_close_event.time + fmodwait) < now)) {
431 LOG(log_debug, logtype_afpd, "check_saved_close_events: sending event: %s", last_close_event.path);
432 /* yes, send event */
433 send_fce_event(&last_close_event.path[0], FCE_FILE_MODIFY);
434 last_close_event.path[0] = 0;
435 last_close_event.time = 0;
439 /******************** External calls start here **************************/
442 * API-Calls for file change api, called form outside (file.c directory.c ofork.c filedir.c)
444 #ifndef FCE_TEST_MAIN
446 void fce_pending_events(AFPObj *obj)
449 check_saved_close_events(obj->options.fce_fmodwait);
452 int fce_register_delete_file( struct path *path )
459 if (!(fce_ev_enabled & (1 << FCE_FILE_DELETE)))
462 ret = register_fce( path->u_name, false, FCE_FILE_DELETE );
466 int fce_register_delete_dir( char *name )
473 if (!(fce_ev_enabled & (1 << FCE_DIR_DELETE)))
476 ret = register_fce( name, true, FCE_DIR_DELETE);
481 int fce_register_new_dir( struct path *path )
488 if (!(fce_ev_enabled & (1 << FCE_DIR_CREATE)))
491 ret = register_fce( path->u_name, true, FCE_DIR_CREATE );
497 int fce_register_new_file( struct path *path )
504 if (!(fce_ev_enabled & (1 << FCE_FILE_CREATE)))
507 ret = register_fce( path->u_name, false, FCE_FILE_CREATE );
512 int fce_register_file_modification( struct ofork *ofork )
518 if (ofork == NULL || ofork->of_vol == NULL)
521 if (!(fce_ev_enabled & (1 << FCE_FILE_MODIFY)))
526 if (NULL == (u_name = mtoupath(vol, of_name(ofork), ofork->of_did, utf8_encoding())))
531 ret = register_fce( u_name, false, FCE_FILE_MODIFY );
536 int fce_register_tm_size(const char *vol, size_t used)
543 if (!(fce_ev_enabled & (1 << FCE_TM_SIZE)))
546 tm_used = used; /* oh what a hack */
547 ret = register_fce(vol, false, FCE_TM_SIZE);
555 * Extern connect to afpd parameter, can be called multiple times for multiple listeners (up to MAX_UDP_SOCKS times)
558 int fce_add_udp_socket(const char *target)
560 const char *port = FCE_DEFAULT_PORT_STRING;
561 char target_ip[256] = {""};
563 strncpy(target_ip, target, sizeof(target_ip) -1);
565 char *port_delim = strchr( target_ip, ':' );
568 port = port_delim + 1;
570 return add_udp_socket(target_ip, port);
573 int fce_set_events(const char *events)
585 for (p = strtok(e, ","); p; p = strtok(NULL, ",")) {
586 if (strcmp(p, "fmod") == 0) {
587 fce_ev_enabled |= (1 << FCE_FILE_MODIFY);
588 } else if (strcmp(p, "fdel") == 0) {
589 fce_ev_enabled |= (1 << FCE_FILE_DELETE);
590 } else if (strcmp(p, "ddel") == 0) {
591 fce_ev_enabled |= (1 << FCE_DIR_DELETE);
592 } else if (strcmp(p, "fcre") == 0) {
593 fce_ev_enabled |= (1 << FCE_FILE_CREATE);
594 } else if (strcmp(p, "dcre") == 0) {
595 fce_ev_enabled |= (1 << FCE_DIR_CREATE);
596 } else if (strcmp(p, "tmsz") == 0) {
597 fce_ev_enabled |= (1 << FCE_TM_SIZE);
607 void shortsleep( unsigned int us )
611 int main( int argc, char*argv[] )
615 char *port = FCE_DEFAULT_PORT_STRING;
616 char *host = "localhost";
617 int delay_between_events = 1000;
618 int event_code = FCE_FILE_MODIFY;
620 int duration_in_seconds = 0; // TILL ETERNITY
622 char *path = getcwd( pathbuff, sizeof(pathbuff) );
624 // FULLSPEED TEST IS "-s 1001" -> delay is 0 -> send packets without pause
626 while ((c = getopt(argc, argv, "d:e:h:p:P:s:")) != -1) {
629 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]);
633 duration_in_seconds = atoi(optarg);
636 event_code = atoi(optarg);
639 host = strdup(optarg);
642 port = strdup(optarg);
645 path = strdup(optarg);
648 delay_between_events = atoi(optarg);
653 sprintf(target, "%s:%s", host, port);
654 if (fce_add_udp_socket(target) != 0)
658 time_t start_time = time(NULL);
661 if (duration_in_seconds)
662 end_time = start_time + duration_in_seconds;
666 time_t now = time(NULL);
667 if (now > start_time)
670 fprintf( stdout, "%d events/s\n", ev_cnt );
673 if (end_time && now >= end_time)
676 register_fce( path, 0, event_code );
680 shortsleep( delay_between_events );