]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/fce_api.c
Fixes, from Riccardo Magliocchetti
[netatalk.git] / etc / afpd / fce_api.c
1 /*
2  * Copyright (c) 2010 Mark Williams
3  *
4  * File change event API for netatalk
5  *
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.
15  *
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
18  * 
19  * All Rights Reserved.  See COPYRIGHT.
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif /* HAVE_CONFIG_H */
25
26 #include <stdio.h>
27
28 #include <string.h>
29 #include <stdlib.h>
30 #include <errno.h>
31 #include <time.h>
32
33
34 #include <sys/param.h>
35 #include <sys/socket.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
38 #include <netdb.h>
39
40 #include <netatalk/at.h>
41
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>
51
52 #include "fork.h"
53 #include "file.h"
54 #include "directory.h"
55 #include "desktop.h"
56 #include "volume.h"
57
58 // ONLY USED IN THIS FILE
59 #include "fce_api_internal.h"
60
61 #define FCE_TRUE 1
62 #define FCE_FALSE 0
63
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);
74
75 static uint64_t tm_used;          /* used for passing to event handler */
76 #define MAXIOBUF 1024
77 static char iobuf[MAXIOBUF];
78 static const char *skip_files[] = 
79 {
80         ".DS_Store",
81         NULL
82 };
83 static struct fce_close_event last_close_event;
84
85 /*
86  *
87  * Initialize network structs for any listeners
88  * We dont give return code because all errors are handled internally (I hope..)
89  *
90  * */
91 void fce_init_udp()
92 {
93     int rv;
94     struct addrinfo hints, *servinfo, *p;
95
96     if (udp_initialized == FCE_TRUE)
97         return;
98
99     memset(&hints, 0, sizeof hints);
100     hints.ai_family = AF_UNSPEC;
101     hints.ai_socktype = SOCK_DGRAM;
102
103     for (int i = 0; i < udp_sockets; i++) {
104         struct udp_entry *udp_entry = udp_socket_list + i;
105
106         /* Close any pending sockets */
107         if (udp_entry->sock != -1)
108             close(udp_entry->sock);
109
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));
113             continue;
114         }
115
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));
121                 continue;
122             }
123             break;
124         }
125
126         if (p == NULL) {
127             LOG(log_error, logtype_afpd, "fce_init_udp: no socket for %s:%s",
128                 udp_entry->addr, udp_entry->port);
129         }
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);
134     }
135
136     udp_initialized = FCE_TRUE;
137 }
138
139 void fce_cleanup()
140 {
141     if (udp_initialized == FCE_FALSE )
142         return;
143
144     for (int i = 0; i < udp_sockets; i++)
145     {
146         struct udp_entry *udp_entry = udp_socket_list + i;
147
148         /* Close any pending sockets */
149         if (udp_entry->sock != -1)
150         {
151             close( udp_entry->sock );
152             udp_entry->sock = -1;
153         }
154     }
155     udp_initialized = FCE_FALSE;
156 }
157
158 /*
159  * Construct a UDP packet for our listeners and return packet size
160  * */
161 static ssize_t build_fce_packet( struct fce_packet *packet, char *path, int mode, uint32_t event_id )
162 {
163     size_t pathlen = 0;
164     ssize_t data_len = 0;
165     uint64_t *t;
166
167     /* Set content of packet */
168     memcpy(packet->magic, FCE_PACKET_MAGIC, sizeof(packet->magic) );
169     packet->version = FCE_PACKET_VERSION;
170     packet->mode = mode;
171    
172     packet->event_id = event_id; 
173
174     pathlen = strlen(path); /* exclude string terminator */
175     
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;
179
180     packet->datalen = pathlen;
181
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;
184
185     switch (mode) {
186     case FCE_TM_SIZE:
187         t = (uint64_t *)packet->data;
188         *t = hton64(tm_used);
189         memcpy(packet->data + sizeof(tm_used), path, pathlen);
190         
191         packet->datalen = pathlen + sizeof(tm_used);
192         data_len += sizeof(tm_used);
193         break;
194     default:
195         memcpy(packet->data, path, pathlen);
196         break;
197     }
198
199     /* return the packet len */
200     return data_len;
201 }
202
203 /*
204  * Handle Endianess and write into buffer w/o padding
205  **/ 
206 static void pack_fce_packet(struct fce_packet *packet, unsigned char *buf, int maxlen)
207 {
208     unsigned char *p = buf;
209
210     memcpy(p, &packet->magic[0], sizeof(packet->magic));
211     p += sizeof(packet->magic);
212
213     *p = packet->version;
214     p++;
215     
216     *p = packet->mode;
217     p++;
218     
219     uint32_t *id = (uint32_t*)p;
220     *id = htonl(packet->event_id);
221     p += sizeof(packet->event_id);
222
223     uint16_t *l = ( uint16_t *)p;
224     *l = htons(packet->datalen);
225     p += sizeof(packet->datalen);
226
227     if (((p - buf) +  packet->datalen) < maxlen) {
228         memcpy(p, &packet->data[0], packet->datalen);
229     }
230 }
231
232 /*
233  * Send the fce information to all (connected) listeners
234  * We dont give return code because all errors are handled internally (I hope..)
235  * */
236 static void send_fce_event( char *path, int mode )
237 {    
238     static int first_event = FCE_TRUE;
239
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);
244
245     LOG(log_debug, logtype_afpd, "send_fce_event: start");
246
247     /* initialized ? */
248     if (first_event == FCE_TRUE) {
249         first_event = FCE_FALSE;
250         fce_init_udp();
251         /* Notify listeners the we start from the beginning */
252         send_fce_event( "", FCE_CONN_START );
253     }
254
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);
258
259     for (int i = 0; i < udp_sockets; i++)
260     {
261         int sent_data = 0;
262         struct udp_entry *udp_entry = udp_socket_list + i;
263
264         /* we had a problem earlier ? */
265         if (udp_entry->sock == -1)
266         {
267             /* We still have to wait ?*/
268             if (now < udp_entry->next_try_on_error)
269                 continue;
270
271             /* Reopen socket */
272             udp_entry->sock = socket(udp_entry->addrinfo.ai_family,
273                                      udp_entry->addrinfo.ai_socktype,
274                                      udp_entry->addrinfo.ai_protocol);
275             
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  );
279
280                 udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;
281                 continue;
282             }
283
284             udp_entry->next_try_on_error = 0;
285
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);
289
290             sendto(udp_entry->sock,
291                    iobuf,
292                    data_len,
293                    0,
294                    (struct sockaddr *)&udp_entry->sockaddr,
295                    udp_entry->addrinfo.ai_addrlen);
296
297             /* Rebuild our original data packet */
298             data_len = build_fce_packet( &packet, path, mode, event_id );
299             pack_fce_packet(&packet, iobuf, MAXIOBUF);
300         }
301
302         sent_data = sendto(udp_entry->sock,
303                            iobuf,
304                            data_len,
305                            0,
306                            (struct sockaddr *)&udp_entry->sockaddr,
307                            udp_entry->addrinfo.ai_addrlen);
308
309         /* Problems ? */
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));
314
315             close( udp_entry->sock );
316             udp_entry->sock = -1;
317             udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;
318         }
319     }
320 }
321
322 static int add_udp_socket(const char *target_ip, const char *target_port )
323 {
324     if (target_port == NULL)
325         target_port = FCE_DEFAULT_PORT_STRING;
326
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 );
329         return AFPERR_PARAM;
330     }
331
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;
338
339     udp_sockets++;
340
341     return AFP_OK;
342 }
343
344 static void save_close_event(const char *path)
345 {
346     time_t now = time(NULL);
347
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);
353     }
354
355     LOG(log_debug, logtype_afpd, "save_close_event: %s", path);
356
357     last_close_event.time = now;
358     strncpy(last_close_event.path, path, MAXPATHLEN);
359 }
360
361 /*
362  *
363  * Dispatcher for all incoming file change events
364  *
365  * */
366 static int register_fce(const char *u_name, int is_dir, int mode)
367 {
368     static int first_event = FCE_TRUE;
369
370     if (udp_sockets == 0)
371         /* No listeners configured */
372         return AFP_OK;
373
374     if (u_name == NULL)
375         return AFPERR_PARAM;
376
377         /* do some initialization on the fly the first time */
378         if (first_event) {
379                 fce_initialize_history();
380         first_event = FCE_FALSE;
381         }
382
383         /* handle files which should not cause events (.DS_Store atc. ) */
384         for (int i = 0; skip_files[i] != NULL; i++)
385         {
386                 if (!strcmp( u_name, skip_files[i]))
387                         return AFP_OK;
388         }
389
390
391         char full_path_buffer[MAXPATHLEN + 1] = {""};
392         const char *cwd = getcwdpath();
393
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 );
399                         return AFPERR_PARAM;
400                 }
401                 sprintf( full_path_buffer, "%s/%s", cwd, u_name );
402         } else {
403                 if (strlen( cwd ) >= MAXPATHLEN) {
404                         LOG(log_error, logtype_afpd, "FCE directory name too long: %s", cwd);
405                         return AFPERR_PARAM;
406                 }
407                 strcpy( full_path_buffer, cwd);
408         }
409
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 ))
412         {
413                 LOG(log_debug9, logtype_afpd, "Coalesced fc event <%d> for <%s>", mode, full_path_buffer );
414                 return AFP_OK;
415         }
416
417         LOG(log_debug9, logtype_afpd, "Detected fc event <%d> for <%s>", mode, full_path_buffer );
418
419     if (mode & FCE_FILE_MODIFY) {
420         save_close_event(full_path_buffer);
421         return AFP_OK;
422     }
423
424     send_fce_event( full_path_buffer, mode );
425
426     return AFP_OK;
427 }
428
429 static void check_saved_close_events(int fmodwait)
430 {
431     time_t now = time(NULL);
432
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;
440     }
441 }
442
443 /******************** External calls start here **************************/
444
445 /*
446  * API-Calls for file change api, called form outside (file.c directory.c ofork.c filedir.c)
447  * */
448 #ifndef FCE_TEST_MAIN
449
450 void fce_pending_events(AFPObj *obj)
451 {
452     vol_fce_tm_event();
453     check_saved_close_events(obj->options.fce_fmodwait);
454 }
455
456 int fce_register_delete_file( struct path *path )
457 {
458     int ret = AFP_OK;
459
460     if (path == NULL)
461         return AFPERR_PARAM;
462
463     if (!(fce_ev_enabled & (1 << FCE_FILE_DELETE)))
464         return ret;
465         
466     ret = register_fce( path->u_name, false, FCE_FILE_DELETE );
467
468     return ret;
469 }
470 int fce_register_delete_dir( char *name )
471 {
472     int ret = AFP_OK;
473
474     if (name == NULL)
475         return AFPERR_PARAM;
476
477     if (!(fce_ev_enabled & (1 << FCE_DIR_DELETE)))
478         return ret;
479         
480     ret = register_fce( name, true, FCE_DIR_DELETE);
481
482     return ret;
483 }
484
485 int fce_register_new_dir( struct path *path )
486 {
487     int ret = AFP_OK;
488
489     if (path == NULL)
490         return AFPERR_PARAM;
491
492     if (!(fce_ev_enabled & (1 << FCE_DIR_CREATE)))
493         return ret;
494
495     ret = register_fce( path->u_name, true, FCE_DIR_CREATE );
496
497     return ret;
498 }
499
500
501 int fce_register_new_file( struct path *path )
502 {
503     int ret = AFP_OK;
504
505     if (path == NULL)
506         return AFPERR_PARAM;
507
508     if (!(fce_ev_enabled & (1 << FCE_FILE_CREATE)))
509         return ret;
510
511     ret = register_fce( path->u_name, false, FCE_FILE_CREATE );
512
513     return ret;
514 }
515
516 int fce_register_file_modification( struct ofork *ofork )
517 {
518     char *u_name = NULL;
519     struct vol *vol;
520     int ret = AFP_OK;
521
522     if (ofork == NULL || ofork->of_vol == NULL)
523         return AFPERR_PARAM;
524
525     if (!(fce_ev_enabled & (1 << FCE_FILE_MODIFY)))
526         return ret;
527
528     vol = ofork->of_vol;
529
530     if (NULL == (u_name = mtoupath(vol, of_name(ofork), ofork->of_did, utf8_encoding()))) 
531     {
532         return AFPERR_MISC;
533     }
534     
535     ret = register_fce( u_name, false, FCE_FILE_MODIFY );
536     
537     return ret;    
538 }
539
540 int fce_register_tm_size(const char *vol, size_t used)
541 {
542     int ret = AFP_OK;
543
544     if (vol == NULL)
545         return AFPERR_PARAM;
546
547     if (!(fce_ev_enabled & (1 << FCE_TM_SIZE)))
548         return ret;
549
550     tm_used = used;             /* oh what a hack */
551     ret = register_fce(vol, false, FCE_TM_SIZE);
552
553     return ret;
554 }
555 #endif
556
557 /*
558  *
559  * Extern connect to afpd parameter, can be called multiple times for multiple listeners (up to MAX_UDP_SOCKS times)
560  *
561  * */
562 int fce_add_udp_socket(const char *target)
563 {
564         const char *port = FCE_DEFAULT_PORT_STRING;
565         char target_ip[256] = {""};
566
567         strncpy(target_ip, target, sizeof(target_ip) -1);
568
569         char *port_delim = strchr( target_ip, ':' );
570         if (port_delim) {
571                 *port_delim = 0;
572                 port = port_delim + 1;
573         }
574         return add_udp_socket(target_ip, port);
575 }
576
577 int fce_set_events(const char *events)
578 {
579     char *e;
580     char *p;
581     
582     if (events == NULL)
583         return AFPERR_PARAM;
584
585     e = strdup(events);
586
587     fce_ev_enabled = 0;
588
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);
602         }
603     }
604
605     free(e);
606
607     return AFP_OK;
608 }
609
610 #ifdef FCE_TEST_MAIN
611
612
613 void shortsleep( unsigned int us )
614 {    
615     usleep( us );
616 }
617 int main( int argc, char*argv[] )
618 {
619     int c,ret;
620
621     char *port = FCE_DEFAULT_PORT_STRING;
622     char *host = "localhost";
623     int delay_between_events = 1000;
624     int event_code = FCE_FILE_MODIFY;
625     char pathbuff[1024];
626     int duration_in_seconds = 0; // TILL ETERNITY
627     char target[256];
628     char *path = getcwd( pathbuff, sizeof(pathbuff) );
629
630     // FULLSPEED TEST IS "-s 1001" -> delay is 0 -> send packets without pause
631
632     while ((c = getopt(argc, argv, "d:e:h:p:P:s:")) != -1) {
633         switch(c) {
634         case '?':
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]);
636             exit(1);
637             break;
638         case 'd':
639             duration_in_seconds = atoi(optarg);
640             break;
641         case 'e':
642             event_code = atoi(optarg);
643             break;
644         case 'h':
645             host = strdup(optarg);
646             break;
647         case 'p':
648             port = strdup(optarg);
649             break;
650         case 'P':
651             path = strdup(optarg);
652             break;
653         case 's':
654             delay_between_events = atoi(optarg);
655             break;
656         }
657     }
658
659     sprintf(target, "%s:%s", host, port);
660     if (fce_add_udp_socket(target) != 0)
661         return 1;
662
663     int ev_cnt = 0;
664     time_t start_time = time(NULL);
665     time_t end_time = 0;
666
667     if (duration_in_seconds)
668         end_time = start_time + duration_in_seconds;
669
670     while (1)
671     {
672         time_t now = time(NULL);
673         if (now > start_time)
674         {
675             start_time = now;
676             fprintf( stdout, "%d events/s\n", ev_cnt );
677             ev_cnt = 0;
678         }
679         if (end_time && now >= end_time)
680             break;
681
682         register_fce( path, 0, event_code );
683         ev_cnt++;
684
685         
686         shortsleep( delay_between_events );
687     }
688 }
689 #endif /* TESTMAIN*/