]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/fce_api.c
Allow enabling/disabling notifications on a per event type basis
[netatalk.git] / etc / afpd / fce_api.c
1 /*\r
2  * Copyright (c) 2010 Mark Williams\r
3  *\r
4  * File change event API for netatalk\r
5  *\r
6  * for every detected filesystem change a UDP packet is sent to an arbitrary list\r
7  * of listeners. Each packet contains unix path of modified filesystem element,\r
8  * event reason, and a consecutive event id (32 bit). Technically we are UDP client and are sending\r
9  * out packets synchronuosly as they are created by the afp functions. This should not affect\r
10  * performance measurably. The only delaying calls occur during initialization, if we have to\r
11  * resolve non-IP hostnames to IP. All numeric data inside the packet is network byte order, so use\r
12  * ntohs / ntohl to resolve length and event id. Ideally a listener receives every packet with\r
13  * no gaps in event ids, starting with event id 1 and mode FCE_CONN_START followed by\r
14  * data events from id 2 up to 0xFFFFFFFF, followed by 0 to 0xFFFFFFFF and so on.\r
15  *\r
16  * A gap or not starting with 1 mode FCE_CONN_START or receiving mode FCE_CONN_BROKEN means that\r
17  * the listener has lost at least one filesystem event\r
18  * \r
19  * All Rights Reserved.  See COPYRIGHT.\r
20  */\r
21 \r
22 #ifdef HAVE_CONFIG_H\r
23 #include "config.h"\r
24 #endif /* HAVE_CONFIG_H */\r
25 \r
26 #include <stdio.h>\r
27 \r
28 #include <string.h>\r
29 #include <stdlib.h>\r
30 #include <errno.h>\r
31 #include <time.h>\r
32 \r
33 \r
34 #include <sys/param.h>\r
35 #include <sys/socket.h>\r
36 #include <netinet/in.h>\r
37 #include <arpa/inet.h>\r
38 #include <netdb.h>\r
39 \r
40 #include <netatalk/at.h>\r
41 \r
42 #include <atalk/adouble.h>\r
43 #include <atalk/vfs.h>\r
44 #include <atalk/logger.h>\r
45 #include <atalk/afp.h>\r
46 #include <atalk/util.h>\r
47 #include <atalk/cnid.h>\r
48 #include <atalk/unix.h>\r
49 #include <atalk/fce_api.h>\r
50 \r
51 #include "fork.h"\r
52 #include "file.h"\r
53 #include "globals.h"\r
54 #include "directory.h"\r
55 #include "desktop.h"\r
56 #include "volume.h"\r
57 \r
58 // ONLY USED IN THIS FILE\r
59 #include "fce_api_internal.h"\r
60 \r
61 #define FCE_TRUE 1\r
62 #define FCE_FALSE 0\r
63 \r
64 /* We store our connection data here */\r
65 static struct udp_entry udp_socket_list[FCE_MAX_UDP_SOCKS];\r
66 static int udp_sockets = 0;\r
67 static int udp_initialized = FCE_FALSE;\r
68 static unsigned long fce_ev_enabled = 0;\r
69 static size_t tm_used;          /* used for passing to event handler */\r
70 static const char *skip_files[] = \r
71 {\r
72         ".DS_Store",\r
73         NULL\r
74 };\r
75 \r
76 /*\r
77  *\r
78  * Initialize network structs for any listeners\r
79  * We dont give return code because all errors are handled internally (I hope..)\r
80  *\r
81  * */\r
82 void fce_init_udp()\r
83 {\r
84     int rv;\r
85     struct addrinfo hints, *servinfo, *p;\r
86 \r
87     if (udp_initialized == FCE_TRUE)\r
88         return;\r
89 \r
90     memset(&hints, 0, sizeof hints);\r
91     hints.ai_family = AF_UNSPEC;\r
92     hints.ai_socktype = SOCK_DGRAM;\r
93 \r
94     for (int i = 0; i < udp_sockets; i++) {\r
95         struct udp_entry *udp_entry = udp_socket_list + i;\r
96 \r
97         /* Close any pending sockets */\r
98         if (udp_entry->sock != -1)\r
99             close(udp_entry->sock);\r
100 \r
101         if ((rv = getaddrinfo(udp_entry->addr, udp_entry->port, &hints, &servinfo)) != 0) {\r
102             LOG(log_error, logtype_afpd, "fce_init_udp: getaddrinfo(%s:%s): %s",\r
103                 udp_entry->addr, udp_entry->port, gai_strerror(rv));\r
104             continue;\r
105         }\r
106 \r
107         /* loop through all the results and make a socket */\r
108         for (p = servinfo; p != NULL; p = p->ai_next) {\r
109             if ((udp_entry->sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {\r
110                 LOG(log_error, logtype_afpd, "fce_init_udp: socket(%s:%s): %s",\r
111                     udp_entry->addr, udp_entry->port, strerror(errno));\r
112                 continue;\r
113             }\r
114             break;\r
115         }\r
116 \r
117         if (p == NULL) {\r
118             LOG(log_error, logtype_afpd, "fce_init_udp: no socket for %s:%s",\r
119                 udp_entry->addr, udp_entry->port);\r
120         }\r
121         memcpy(&udp_entry->addrinfo, p, sizeof(struct addrinfo));\r
122         freeaddrinfo(servinfo);\r
123     }\r
124 \r
125     udp_initialized = FCE_TRUE;\r
126 }\r
127 \r
128 void fce_cleanup()\r
129 {\r
130     if (udp_initialized == FCE_FALSE )\r
131         return;\r
132 \r
133     for (int i = 0; i < udp_sockets; i++)\r
134     {\r
135         struct udp_entry *udp_entry = udp_socket_list + i;\r
136 \r
137         /* Close any pending sockets */\r
138         if (udp_entry->sock != -1)\r
139         {\r
140             close( udp_entry->sock );\r
141             udp_entry->sock = -1;\r
142         }\r
143     }\r
144     udp_initialized = FCE_FALSE;\r
145 }\r
146 \r
147 \r
148 /*\r
149  * Construct a UDP packet for our listeners and return packet size\r
150  * */\r
151 static unsigned short build_fce_packet( struct fce_packet *packet, char *path, int mode, uint32_t event_id )\r
152 {\r
153     unsigned short data_len = 0;\r
154 \r
155     strncpy(packet->magic, FCE_PACKET_MAGIC, sizeof(packet->magic) );\r
156     packet->version = FCE_PACKET_VERSION;\r
157     packet->mode = mode;\r
158 \r
159     data_len = strlen( path );\r
160 \r
161     /* This should never happen, but before we bust this server, we send nonsense, fce listener has to cope */\r
162     if (data_len >= FCE_MAX_PATH_LEN)\r
163     {\r
164         data_len = FCE_MAX_PATH_LEN - 1;\r
165     }\r
166 \r
167     /* This is the payload len. Means: the stream has len bytes more until packet is finished */\r
168     /* A server should read the first 16 byte, decode them and then fetch the rest */\r
169     packet->len = htons( data_len);\r
170     packet->event_id = htonl( event_id );\r
171 \r
172     strncpy( packet->data, path, data_len );\r
173 \r
174     /* return the packet len */\r
175     return sizeof(struct fce_packet) - FCE_MAX_PATH_LEN + data_len;\r
176 }\r
177 \r
178 /*\r
179  * Send the fce information to all (connected) listeners\r
180  * We dont give return code because all errors are handled internally (I hope..)\r
181  * */\r
182 static void send_fce_event( char *path, int mode )\r
183 {    \r
184     struct fce_packet packet;\r
185     void *data = &packet;\r
186     static uint32_t event_id = 0; /* the unique packet couter to detect packet/data loss. Going from 0xFFFFFFFF to 0x0 is a valid increment */\r
187 \r
188     time_t now = time(NULL);\r
189 \r
190     /* build our data packet */\r
191     int data_len = build_fce_packet( &packet, path, mode, ++event_id );\r
192 \r
193 \r
194     for (int i = 0; i < udp_sockets; i++)\r
195     {\r
196         int sent_data = 0;\r
197         struct udp_entry *udp_entry = udp_socket_list + i;\r
198 \r
199         /* we had a problem earlier ? */\r
200         if (udp_entry->sock == -1)\r
201         {\r
202             /* We still have to wait ?*/\r
203             if (now < udp_entry->next_try_on_error)\r
204                 continue;\r
205 \r
206             /* Reopen socket */\r
207             udp_entry->sock = socket( AF_INET, SOCK_DGRAM, 0 );\r
208 \r
209             if (udp_entry->sock == -1)\r
210             {\r
211                 /* failed again, so go to rest again */\r
212                 LOG(log_error, logtype_afpd, "Cannot recreate socket for fce UDP connection: errno %d", errno  );\r
213 \r
214                 udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;\r
215                 continue;\r
216             }\r
217 \r
218             udp_entry->next_try_on_error = 0;\r
219 \r
220             /* Okay, we have a running socket again, send server that we had a problem on our side*/\r
221             data_len = build_fce_packet( &packet, "", FCE_CONN_BROKEN, 0 );\r
222 \r
223             sendto(udp_entry->sock,\r
224                    data,\r
225                    data_len,\r
226                    0,\r
227                    udp_entry->addrinfo.ai_addr,\r
228                    udp_entry->addrinfo.ai_addrlen);\r
229 \r
230             /* Rebuild our original data packet */\r
231             data_len = build_fce_packet( &packet, path, mode, event_id );\r
232         }\r
233 \r
234         sent_data = sendto(udp_entry->sock,\r
235                            data,\r
236                            data_len,\r
237                            0,\r
238                            udp_entry->addrinfo.ai_addr,\r
239                            udp_entry->addrinfo.ai_addrlen);\r
240 \r
241         /* Problems ? */\r
242         if (sent_data != data_len)\r
243         {\r
244             /* Argh, socket broke, we close and retry later */\r
245             LOG(log_error, logtype_afpd, "Error while sending packet to %s for fce UDP connection: transfered: %d of %d errno %d",\r
246                     udp_entry->port, sent_data, data_len, errno  );\r
247 \r
248             close( udp_entry->sock );\r
249             udp_entry->sock = -1;\r
250             udp_entry->next_try_on_error = now + FCE_SOCKET_RETRY_DELAY_S;\r
251         }\r
252     }\r
253 }\r
254 \r
255 static int add_udp_socket(const char *target_ip, const char *target_port )\r
256 {\r
257     if (target_port == NULL)\r
258         target_port = FCE_DEFAULT_PORT_STRING;\r
259 \r
260     if (udp_sockets >= FCE_MAX_UDP_SOCKS) {\r
261         LOG(log_error, logtype_afpd, "Too many file change api UDP connections (max %d allowed)", FCE_MAX_UDP_SOCKS );\r
262         return AFPERR_PARAM;\r
263     }\r
264 \r
265     udp_socket_list[udp_sockets].addr = strdup(target_ip);\r
266     udp_socket_list[udp_sockets].port = strdup(target_port);\r
267     udp_socket_list[udp_sockets].sock = -1;\r
268     memset( &udp_socket_list[udp_sockets].addrinfo, 0, sizeof(struct sockaddr_in) );\r
269     udp_socket_list[udp_sockets].next_try_on_error = 0;\r
270 \r
271     udp_sockets++;\r
272 \r
273     return AFP_OK;\r
274 }\r
275 \r
276 /*\r
277  *\r
278  * Dispatcher for all incoming file change events\r
279  *\r
280  * */\r
281 static int register_fce(const char *u_name, int is_dir, int mode)\r
282 {\r
283     if (udp_sockets == 0)\r
284         /* No listeners configured */\r
285         return AFP_OK;\r
286 \r
287     if (u_name == NULL)\r
288         return AFPERR_PARAM;\r
289 \r
290     static int first_event = FCE_TRUE;\r
291 \r
292         /* do some initialization on the fly the first time */\r
293         if (first_event)\r
294         {\r
295                 fce_initialize_history();\r
296         fce_ev_enabled =\r
297             (1 << FCE_FILE_MODIFY) |\r
298             (1 << FCE_FILE_DELETE) |\r
299             (1 << FCE_DIR_DELETE) |\r
300             (1 << FCE_FILE_CREATE) |\r
301             (1 << FCE_DIR_CREATE);\r
302         }\r
303 \r
304 \r
305         /* handle files which should not cause events (.DS_Store atc. ) */\r
306         for (int i = 0; skip_files[i] != NULL; i++)\r
307         {\r
308                 if (!strcmp( u_name, skip_files[i]))\r
309                         return AFP_OK;\r
310         }\r
311 \r
312 \r
313         char full_path_buffer[FCE_MAX_PATH_LEN + 1] = {""};\r
314         const char *cwd = getcwdpath();\r
315 \r
316     if (mode & FCE_TM_SIZE) {\r
317         strncpy(full_path_buffer, u_name, FCE_MAX_PATH_LEN);\r
318     } else if (!is_dir || mode == FCE_DIR_DELETE) {\r
319                 if (strlen( cwd ) + strlen( u_name) + 1 >= FCE_MAX_PATH_LEN) {\r
320                         LOG(log_error, logtype_afpd, "FCE file name too long: %s/%s", cwd, u_name );\r
321                         return AFPERR_PARAM;\r
322                 }\r
323                 sprintf( full_path_buffer, "%s/%s", cwd, u_name );\r
324         } else {\r
325                 if (strlen( cwd ) >= FCE_MAX_PATH_LEN) {\r
326                         LOG(log_error, logtype_afpd, "FCE directory name too long: %s", cwd);\r
327                         return AFPERR_PARAM;\r
328                 }\r
329                 strcpy( full_path_buffer, cwd);\r
330         }\r
331 \r
332         /* Can we ignore this event based on type or history? */\r
333         if (!(mode & FCE_TM_SIZE) && fce_handle_coalescation( full_path_buffer, is_dir, mode ))\r
334         {\r
335                 LOG(log_debug9, logtype_afpd, "Coalesced fc event <%d> for <%s>", mode, full_path_buffer );\r
336                 return AFP_OK;\r
337         }\r
338 \r
339         LOG(log_debug9, logtype_afpd, "Detected fc event <%d> for <%s>", mode, full_path_buffer );\r
340 \r
341 \r
342     /* we do initilization on the fly, no blocking calls in here \r
343      * (except when using FQDN in broken DNS environment)\r
344      */\r
345     if (first_event == FCE_TRUE)\r
346     {\r
347         fce_init_udp();\r
348         \r
349         /* Notify listeners the we start from the beginning */\r
350         send_fce_event( "", FCE_CONN_START );\r
351         \r
352         first_event = FCE_FALSE;\r
353     }\r
354 \r
355         /* Handle UDP transport */\r
356     send_fce_event( full_path_buffer, mode );\r
357 \r
358     return AFP_OK;\r
359 }\r
360 \r
361 \r
362 /******************** External calls start here **************************/\r
363 \r
364 /*\r
365  * API-Calls for file change api, called form outside (file.c directory.c ofork.c filedir.c)\r
366  * */\r
367 #ifndef FCE_TEST_MAIN\r
368 \r
369 int fce_register_delete_file( struct path *path )\r
370 {\r
371     int ret = AFP_OK;\r
372 \r
373     if (path == NULL)\r
374         return AFPERR_PARAM;\r
375 \r
376     if (!(fce_ev_enabled & (1 << FCE_FILE_DELETE)))\r
377         return ret;\r
378         \r
379     ret = register_fce( path->u_name, FALSE, FCE_FILE_DELETE );\r
380 \r
381     return ret;\r
382 }\r
383 int fce_register_delete_dir( char *name )\r
384 {\r
385     int ret = AFP_OK;\r
386 \r
387     if (name == NULL)\r
388         return AFPERR_PARAM;\r
389 \r
390     if (!(fce_ev_enabled & (1 << FCE_DIR_DELETE)))\r
391         return ret;\r
392         \r
393     ret = register_fce( name, TRUE, FCE_DIR_DELETE);\r
394 \r
395     return ret;\r
396 }\r
397 \r
398 int fce_register_new_dir( struct path *path )\r
399 {\r
400     int ret = AFP_OK;\r
401 \r
402     if (path == NULL)\r
403         return AFPERR_PARAM;\r
404 \r
405     if (!(fce_ev_enabled & (1 << FCE_DIR_CREATE)))\r
406         return ret;\r
407 \r
408     ret = register_fce( path->u_name, TRUE, FCE_DIR_CREATE );\r
409 \r
410     return ret;\r
411 }\r
412 \r
413 \r
414 int fce_register_new_file( struct path *path )\r
415 {\r
416     int ret = AFP_OK;\r
417 \r
418     if (path == NULL)\r
419         return AFPERR_PARAM;\r
420 \r
421     if (!(fce_ev_enabled & (1 << FCE_FILE_CREATE)))\r
422         return ret;\r
423 \r
424     ret = register_fce( path->u_name, FALSE, FCE_FILE_CREATE );\r
425 \r
426     return ret;\r
427 }\r
428 \r
429 int fce_register_file_modification( struct ofork *ofork )\r
430 {\r
431     char *u_name = NULL;\r
432     struct vol *vol;\r
433     int ret = AFP_OK;\r
434 \r
435     if (ofork == NULL || ofork->of_vol == NULL)\r
436         return AFPERR_PARAM;\r
437 \r
438     if (!(fce_ev_enabled & (1 << FCE_FILE_MODIFY)))\r
439         return ret;\r
440 \r
441     vol = ofork->of_vol;\r
442 \r
443     if (NULL == (u_name = mtoupath(vol, of_name(ofork), ofork->of_did, utf8_encoding()))) \r
444     {\r
445         return AFPERR_MISC;\r
446     }\r
447     \r
448     ret = register_fce( u_name, FALSE, FCE_FILE_MODIFY );\r
449     \r
450     return ret;    \r
451 }\r
452 \r
453 int fce_register_tm_size(const char *vol, size_t used)\r
454 {\r
455     int ret = AFP_OK;\r
456 \r
457     if (vol == NULL)\r
458         return AFPERR_PARAM;\r
459 \r
460     if (!(fce_ev_enabled & (1 << FCE_TM_SIZE)))\r
461         return ret;\r
462 \r
463     tm_used = used;             /* oh what a hack */\r
464     ret = register_fce(vol, FALSE, FCE_TM_SIZE);\r
465 \r
466     return ret;\r
467 }\r
468 #endif\r
469 \r
470 /*\r
471  *\r
472  * Extern connect to afpd parameter, can be called multiple times for multiple listeners (up to MAX_UDP_SOCKS times)\r
473  *\r
474  * */\r
475 int fce_add_udp_socket(const char *target)\r
476 {\r
477         const char *port = FCE_DEFAULT_PORT_STRING;\r
478         char target_ip[256] = {""};\r
479 \r
480         strncpy(target_ip, target, sizeof(target_ip) -1);\r
481 \r
482         char *port_delim = strchr( target_ip, ':' );\r
483         if (port_delim) {\r
484                 *port_delim = 0;\r
485                 port = port_delim + 1;\r
486         }\r
487         return add_udp_socket(target_ip, port);\r
488 }\r
489 \r
490 int fce_set_events(const char *events)\r
491 {\r
492     char *e;\r
493     char *p;\r
494     \r
495     if (events == NULL)\r
496         return AFPERR_PARAM;\r
497 \r
498     e = strdup(events);\r
499     fce_ev_enabled = 0;\r
500 \r
501     for (p = strtok(e, ","); p; p = strtok(NULL, ",")) {\r
502         if (strcmp(e, "fmod") == 0) {\r
503             fce_ev_enabled |= FCE_FILE_MODIFY;\r
504         } else if (strcmp(e, "fdel") == 0) {\r
505             fce_ev_enabled |= FCE_FILE_DELETE;\r
506         } else if (strcmp(e, "ddel") == 0) {\r
507             fce_ev_enabled |= FCE_DIR_DELETE;\r
508         } else if (strcmp(e, "fcre") == 0) {\r
509             fce_ev_enabled |= FCE_FILE_CREATE;\r
510         } else if (strcmp(e, "dcre") == 0) {\r
511             fce_ev_enabled |= FCE_DIR_CREATE;\r
512         } else if (strcmp(e, "tmsz") == 0) {\r
513             fce_ev_enabled |= FCE_TM_SIZE;\r
514         }\r
515     }\r
516 \r
517     free(e);\r
518 }\r
519 \r
520 #ifdef FCE_TEST_MAIN\r
521 \r
522 \r
523 void shortsleep( unsigned int us )\r
524 {    \r
525     usleep( us );\r
526 }\r
527 int main( int argc, char*argv[] )\r
528 {\r
529     int c,ret;\r
530 \r
531     char *port = FCE_DEFAULT_PORT_STRING;\r
532     char *host = "localhost";\r
533     int delay_between_events = 1000;\r
534     int event_code = FCE_FILE_MODIFY;\r
535     char pathbuff[1024];\r
536     int duration_in_seconds = 0; // TILL ETERNITY\r
537     char target[256];\r
538     char *path = getcwd( pathbuff, sizeof(pathbuff) );\r
539 \r
540     // FULLSPEED TEST IS "-s 1001" -> delay is 0 -> send packets without pause\r
541 \r
542     while ((c = getopt(argc, argv, "d:e:h:p:P:s:")) != -1) {\r
543         switch(c) {\r
544         case '?':\r
545             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]);\r
546             exit(1);\r
547             break;\r
548         case 'd':\r
549             duration_in_seconds = atoi(optarg);\r
550             break;\r
551         case 'e':\r
552             event_code = atoi(optarg);\r
553             break;\r
554         case 'h':\r
555             host = strdup(optarg);\r
556             break;\r
557         case 'p':\r
558             port = strdup(optarg);\r
559             break;\r
560         case 'P':\r
561             path = strdup(optarg);\r
562             break;\r
563         case 's':\r
564             delay_between_events = atoi(optarg);\r
565             break;\r
566         }\r
567     }\r
568 \r
569     sprintf(target, "%s:%s", host, port);\r
570     if (fce_add_udp_socket(target) != 0)\r
571         return 1;\r
572 \r
573     int ev_cnt = 0;\r
574     time_t start_time = time(NULL);\r
575     time_t end_time = 0;\r
576 \r
577     if (duration_in_seconds)\r
578         end_time = start_time + duration_in_seconds;\r
579 \r
580     while (1)\r
581     {\r
582         time_t now = time(NULL);\r
583         if (now > start_time)\r
584         {\r
585             start_time = now;\r
586             fprintf( stdout, "%d events/s\n", ev_cnt );\r
587             ev_cnt = 0;\r
588         }\r
589         if (end_time && now >= end_time)\r
590             break;\r
591 \r
592         register_fce( path, 0, event_code );\r
593         ev_cnt++;\r
594 \r
595         \r
596         shortsleep( delay_between_events );\r
597     }\r
598 }\r
599 #endif /* TESTMAIN*/\r