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