]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/fce_api.c
Convert to getaddrinfo
[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 \r
69 \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( 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         }\r
297 \r
298 \r
299         /* handle files which should not cause events (.DS_Store atc. ) */\r
300         for (int i = 0; skip_files[i] != NULL; i++)\r
301         {\r
302                 if (!strcmp( u_name, skip_files[i]))\r
303                         return AFP_OK;\r
304         }\r
305 \r
306 \r
307         char full_path_buffer[FCE_MAX_PATH_LEN + 1] = {""};\r
308         const char *cwd = getcwdpath();\r
309 \r
310         if (!is_dir || mode == FCE_DIR_DELETE)\r
311         {\r
312                 if (strlen( cwd ) + strlen( u_name) + 1 >= FCE_MAX_PATH_LEN)\r
313                 {\r
314                         LOG(log_error, logtype_afpd, "FCE file name too long: %s/%s", cwd, u_name );\r
315                         return AFPERR_PARAM;\r
316                 }\r
317                 sprintf( full_path_buffer, "%s/%s", cwd, u_name );\r
318         }\r
319         else\r
320         {\r
321                 if (strlen( cwd ) >= FCE_MAX_PATH_LEN)\r
322                 {\r
323                         LOG(log_error, logtype_afpd, "FCE directory name too long: %s", cwd);\r
324                         return AFPERR_PARAM;\r
325                 }\r
326                 strcpy( full_path_buffer, cwd);\r
327         }\r
328 \r
329         /* Can we ignore this event based on type or history? */\r
330         if (fce_handle_coalescation( full_path_buffer, is_dir, mode ))\r
331         {\r
332                 LOG(log_debug9, logtype_afpd, "Coalesced fc event <%d> for <%s>", mode, full_path_buffer );\r
333                 return AFP_OK;\r
334         }\r
335 \r
336         LOG(log_debug9, logtype_afpd, "Detected fc event <%d> for <%s>", mode, full_path_buffer );\r
337 \r
338 \r
339     /* we do initilization on the fly, no blocking calls in here \r
340      * (except when using FQDN in broken DNS environment)\r
341      */\r
342     if (first_event == FCE_TRUE)\r
343     {\r
344         fce_init_udp();\r
345         \r
346         /* Notify listeners the we start from the beginning */\r
347         send_fce_event( "", FCE_CONN_START );\r
348         \r
349         first_event = FCE_FALSE;\r
350     }\r
351 \r
352         /* Handle UDP transport */\r
353     send_fce_event( full_path_buffer, mode );\r
354 \r
355     return AFP_OK;\r
356 }\r
357 \r
358 \r
359 /******************** External calls start here **************************/\r
360 \r
361 /*\r
362  * API-Calls for file change api, called form outside (file.c directory.c ofork.c filedir.c)\r
363  * */\r
364 #ifndef FCE_TEST_MAIN\r
365 \r
366 \r
367 int fce_register_delete_file( struct path *path )\r
368 {\r
369     int ret = AFP_OK;\r
370 \r
371     if (path == NULL)\r
372         return AFPERR_PARAM;\r
373 \r
374         \r
375     ret = register_fce( path->u_name, FALSE, FCE_FILE_DELETE );\r
376 \r
377     return ret;\r
378 }\r
379 int fce_register_delete_dir( char *name )\r
380 {\r
381     int ret = AFP_OK;\r
382 \r
383     if (name == NULL)\r
384         return AFPERR_PARAM;\r
385 \r
386         \r
387     ret = register_fce( name, TRUE, FCE_DIR_DELETE);\r
388 \r
389     return ret;\r
390 }\r
391 \r
392 int fce_register_new_dir( struct path *path )\r
393 {\r
394     int ret = AFP_OK;\r
395 \r
396     if (path == NULL)\r
397         return AFPERR_PARAM;\r
398 \r
399     ret = register_fce( path->u_name, TRUE, FCE_DIR_CREATE );\r
400 \r
401     return ret;\r
402 }\r
403 \r
404 \r
405 int fce_register_new_file( struct path *path )\r
406 {\r
407     int ret = AFP_OK;\r
408 \r
409     if (path == NULL)\r
410         return AFPERR_PARAM;\r
411 \r
412     ret = register_fce( path->u_name, FALSE, FCE_FILE_CREATE );\r
413 \r
414     return ret;\r
415 }\r
416 \r
417 \r
418 int fce_register_file_modification( struct ofork *ofork )\r
419 {\r
420     char *u_name = NULL;\r
421     struct vol *vol;\r
422     int ret = AFP_OK;\r
423 \r
424     if (ofork == NULL || ofork->of_vol == NULL)\r
425         return AFPERR_PARAM;\r
426 \r
427     vol = ofork->of_vol;\r
428 \r
429     if (NULL == (u_name = mtoupath(vol, of_name(ofork), ofork->of_did, utf8_encoding()))) \r
430     {\r
431         return AFPERR_MISC;\r
432     }\r
433     \r
434     ret = register_fce( u_name, FALSE, FCE_FILE_MODIFY );\r
435     \r
436     return ret;    \r
437 }\r
438 #endif\r
439 \r
440 /*\r
441  *\r
442  * Extern connect to afpd parameter, can be called multiple times for multiple listeners (up to MAX_UDP_SOCKS times)\r
443  *\r
444  * */\r
445 int fce_add_udp_socket(const char *target)\r
446 {\r
447         const char *port = FCE_DEFAULT_PORT_STRING;\r
448         char target_ip[256] = {""};\r
449 \r
450         strncpy(target_ip, target, sizeof(target_ip) -1);\r
451 \r
452         char *port_delim = strchr( target_ip, ':' );\r
453         if (port_delim) {\r
454                 *port_delim = 0;\r
455                 port = port_delim + 1;\r
456         }\r
457         return add_udp_socket(target_ip, port);\r
458 }\r
459 \r
460 \r
461 \r
462 #ifdef FCE_TEST_MAIN\r
463 \r
464 \r
465 void shortsleep( unsigned int us )\r
466 {    \r
467     usleep( us );\r
468 }\r
469 int main( int argc, char*argv[] )\r
470 {\r
471     int c,ret;\r
472 \r
473     char *port = FCE_DEFAULT_PORT_STRING;\r
474     char *host = "localhost";\r
475     int delay_between_events = 1000;\r
476     int event_code = FCE_FILE_MODIFY;\r
477     char pathbuff[1024];\r
478     int duration_in_seconds = 0; // TILL ETERNITY\r
479     char target[256];\r
480     char *path = getcwd( pathbuff, sizeof(pathbuff) );\r
481 \r
482     // FULLSPEED TEST IS "-s 1001" -> delay is 0 -> send packets without pause\r
483 \r
484     while ((c = getopt(argc, argv, "d:e:h:p:P:s:")) != -1) {\r
485         switch(c) {\r
486         case '?':\r
487             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
488             exit(1);\r
489             break;\r
490         case 'd':\r
491             duration_in_seconds = atoi(optarg);\r
492             break;\r
493         case 'e':\r
494             event_code = atoi(optarg);\r
495             break;\r
496         case 'h':\r
497             host = strdup(optarg);\r
498             break;\r
499         case 'p':\r
500             port = strdup(optarg);\r
501             break;\r
502         case 'P':\r
503             path = strdup(optarg);\r
504             break;\r
505         case 's':\r
506             delay_between_events = atoi(optarg);\r
507             break;\r
508         }\r
509     }\r
510 \r
511     sprintf(target, "%s:%s", host, port);\r
512     if (fce_add_udp_socket(target) != 0)\r
513         return 1;\r
514 \r
515     int ev_cnt = 0;\r
516     time_t start_time = time(NULL);\r
517     time_t end_time = 0;\r
518 \r
519     if (duration_in_seconds)\r
520         end_time = start_time + duration_in_seconds;\r
521 \r
522     while (1)\r
523     {\r
524         time_t now = time(NULL);\r
525         if (now > start_time)\r
526         {\r
527             start_time = now;\r
528             fprintf( stdout, "%d events/s\n", ev_cnt );\r
529             ev_cnt = 0;\r
530         }\r
531         if (end_time && now >= end_time)\r
532             break;\r
533 \r
534         register_fce( path, 0, event_code );\r
535         ev_cnt++;\r
536 \r
537         \r
538         shortsleep( delay_between_events );\r
539     }\r
540 }\r
541 #endif /* TESTMAIN*/\r