Fixed timeout-related crashes.
[udpgate.git] / src / network.c
1 /* $Id$
2  * UDP Gateway utility network layer
3  * Copyright (C) 2004 Jan Kratochvil <project-udpgate@jankratochvil.net>
4  * 
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; exactly version 2 of June 1991 is required
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18
19
20 #include "config.h"
21
22 #include <glib/gmessages.h>
23 #include <glib/gmain.h>
24 #include <sys/socket.h>
25 #include <netinet/in.h>
26 #include <glib/glist.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <sys/types.h>
30 #include <signal.h>
31 #include <errno.h>
32 #include <glib/giochannel.h>
33 #include <sys/ioctl.h>
34 #include <string.h>
35 #include <glib/galloca.h>
36 #include <glib/gprintf.h>
37 #include <glib/grand.h>
38
39 #include "network.h"
40 #include "packet.h"
41 #include "main.h"       /* for optarg_verbose */
42
43
44 /* Config: */
45 #define NETWORK_PATHNAME_PID "/var/run/udpgate.pid"
46 #define SOCK_SOURCE_CHECK_EVENTS (G_IO_IN)      /* |G_IO_PRI */
47 #define SOCK_SOURCE_CHECK_REVENTS (SOCK_SOURCE_CHECK_EVENTS)    /* |G_IO_ERR|G_IO_HUP|G_IO_NVAL */
48 #define SERVER_INADDR 0x7F000001
49 #undef  SERVER_INADDR
50 #define SERVER_INADDR 0x511F02EA        /* paulina.vellum.cz = 81.31.2.234; host order */
51 #define SERVER_PORT   9201      /* host order */
52 #define PROBE_INADDR  SERVER_INADDR     /* host order */
53 #define PROBE_PORT    8201      /* host order */
54 #define CLIENT_TIMEOUT_SEC (5*60)
55 #define PROBE_TIMEOUT_SEC (5)
56
57
58 void (*network_notify_hostip)(guint32 hostip_guint32);
59
60
61 struct client {
62         GPollFD gpollfd;
63         struct sockaddr_in sockaddr_in_from;
64         guint timeout_id;
65         };
66
67 static GSource *sock_gsource;
68
69 static GList *sock_client_list; /* of 'struct client *', incl. 'master' and 'probe' */
70 static struct client *master;   /* no 'timeout' permitted */
71 static struct client *probe;    /* 'timeout' permitted */
72 static guint32 probe_unique;
73
74 static gboolean write_daemon_running(pid_t pid);
75
76 pid_t is_daemon_running(void)
77 {
78 FILE *f;
79 char buf[LINE_MAX],*got;
80 int pid_int;
81
82         if (sock_gsource)
83                 return getpid();
84
85         if (!(f=fopen(NETWORK_PATHNAME_PID,"r")))
86                 goto err;
87         got=fgets(buf,sizeof(buf),f);
88         fclose(f);      /* FIXME: error ignored */
89         if (got!=buf) {
90 err_unlink:
91                 write_daemon_running((pid_t)-1);        /* unlink */
92 err:
93                 return (pid_t)-1;
94                 }
95         pid_int=atoi(buf);
96         if (pid_int<=1)
97                 goto err_unlink;
98         if (kill((pid_t)pid_int,0)) {
99                 if (errno==ESRCH)
100                         goto err_unlink;
101                 goto err;
102                 }
103         return (pid_t)pid_int;
104 }
105
106 static gboolean write_daemon_running(pid_t pid)
107 {
108 FILE *f;
109
110         if (pid==(pid_t)-1) {
111                 if (unlink(NETWORK_PATHNAME_PID)) {
112                         if (errno!=ENOENT)
113                                 g_warning(_("Error removing PID file \"%s\": %m"),NETWORK_PATHNAME_PID);
114                         return FALSE;
115                         }
116                 return TRUE;
117                 }
118         if (!(f=fopen(NETWORK_PATHNAME_PID,"w"))) {
119                 g_warning(_("Error writing PID %d to \"%s\": %m"),(int)pid,NETWORK_PATHNAME_PID);
120                 return FALSE;
121                 }
122         fprintf(f,"%d\n",(int)pid);     /* errors ignored */
123         fclose(f);      /* FIXME: error ignored */
124         return TRUE;
125 }
126
127 static void client_timeout_remove(struct client *client)
128 {
129         g_return_if_fail(client!=NULL);
130         g_return_if_fail(client!=master);
131
132         if (client->timeout_id) {
133 gboolean errgboolean;
134
135                 if (optarg_verbose)
136                         g_message(_("Client fd %d removed timeout id %d"),client->gpollfd.fd,client->timeout_id);
137                 errgboolean=g_source_remove(client->timeout_id);
138                 g_assert(errgboolean==TRUE);
139                 client->timeout_id=0;
140                 }
141 }
142
143 static gboolean client_touch_timeout(struct client *client);
144
145 static void client_touch(struct client *client)
146 {
147         g_return_if_fail(client!=NULL);
148         g_return_if_fail(client!=master);
149
150         client_timeout_remove(client);
151         client->timeout_id=g_timeout_add(
152                         (client==probe ? PROBE_TIMEOUT_SEC*1000 : CLIENT_TIMEOUT_SEC*1000),     /* interval; msec */
153                         (GSourceFunc)client_touch_timeout,      /* function */
154                         client);        /* data */
155         if (optarg_verbose)
156                 g_message(_("Client fd %d new timeout id %d"),client->gpollfd.fd,client->timeout_id);
157         g_assert(client->timeout_id!=0);
158 }
159
160 static void client_destroy(struct client *client);
161
162 static gboolean client_touch_timeout(struct client *client)
163 {
164         g_return_val_if_fail(client!=NULL,FALSE);       /* FALSE=>should be removed */
165         g_return_val_if_fail(client!=master,FALSE);     /* FALSE=>should be removed */
166
167         if (optarg_verbose)
168                 g_message(_("Client fd %d timeout id %d occured/entered"),client->gpollfd.fd,client->timeout_id);
169
170         /* Do not destroy the timeout in client_destroy().
171          * It would crash GLib - we remove it be returning FALSE from here.
172          */
173         g_assert(client->timeout_id!=0);
174         client->timeout_id=0;
175
176         if (client==probe) {
177                 network_stop();
178                 /* Never destroy 'client' now - it has been destroyed by network_stop()! */
179                 if (network_notify_hostip)
180                         (*network_notify_hostip)(0);
181                 }
182         else {
183                 client_destroy(client);
184                 }
185
186         if (optarg_verbose)
187                 g_message(_("Client timeout occurance finish"));
188
189         return FALSE;   /* GSource should be removed */
190 }
191
192 static void handle_master_probe(const void *packet,size_t gotlen,const struct sockaddr_in *sockaddr_in_from)
193 {
194 GHashTable *got_hash;
195 gpointer got_unique_gpointer;
196 gpointer hostip_gpointer;
197 guint32 hostip_guint32;
198
199         g_return_if_fail(packet!=NULL);
200         g_return_if_fail(sockaddr_in_from!=NULL);
201
202         if (!probe)
203                 return;
204
205         if (!(got_hash=packet_disassembly(packet,gotlen)))
206                 return;
207         if (!(g_hash_table_lookup_extended(
208                         got_hash,       /* hash_table */
209                         GUINT_TO_POINTER(PACKET_ELEM_TYPE_DATA_GUINT32),        /* lookup_key */
210                         NULL,   /* orig_key */
211                         &got_unique_gpointer))) {
212 err_packet_disassembly_destroy_got_hash:
213                 packet_disassembly_destroy(got_hash);
214                 return;
215                 }
216         if (GPOINTER_TO_UINT(got_unique_gpointer)!=probe_unique)
217                 goto err_packet_disassembly_destroy_got_hash;
218         if (!(g_hash_table_lookup_extended(
219                         got_hash,       /* hash_table */
220                         GUINT_TO_POINTER(PACKET_ELEM_TYPE_CLIENT_INADDR),       /* lookup_key */
221                         NULL,   /* orig_key */
222                         &hostip_gpointer)))
223                 goto err_packet_disassembly_destroy_got_hash;
224         hostip_guint32=GPOINTER_TO_UINT(hostip_gpointer);
225         packet_disassembly_destroy(got_hash);
226
227         client_destroy(probe);
228         if (network_notify_hostip)
229                 (*network_notify_hostip)(hostip_guint32);
230 }
231
232 static struct client *client_new(void);
233
234 static void handle_master(struct client *master)
235 {
236 ssize_t gotlen;
237 struct sockaddr_in sockaddr_in_from;
238 char packet[0x10000];
239 struct client *client;
240 struct sockaddr_in sockaddr_in_server;
241 socklen_t sockaddr_in_from_length;
242
243         g_return_if_fail(master!=NULL);
244
245         sockaddr_in_from_length=sizeof(sockaddr_in_from);
246         while (-1!=(gotlen=recvfrom(
247                         master->gpollfd.fd,     /* s */
248                         packet, /* buf */
249                         sizeof(packet), /* len */
250                         0,      /* flags */
251                         (struct sockaddr *)&sockaddr_in_from,   /* from */
252                         &sockaddr_in_from_length))) {   /* fromlen */
253 GList *clientl;
254
255                 if (sockaddr_in_from_length!=sizeof(sockaddr_in_from))  /* FIXME: errors reporting */
256                         continue;
257
258                 if (packet_recognized(packet,gotlen)) {
259                         handle_master_probe(packet,gotlen,&sockaddr_in_from);
260                         continue;
261                         }
262
263                 /* FIXME: Performance: Ugly search... */
264                 for (clientl=sock_client_list;clientl;clientl=clientl->next) {
265                         client=clientl->data;
266                         if (client==master)
267                                 continue;
268                         if (1
269                                         && client->sockaddr_in_from.sin_family     ==sockaddr_in_from.sin_family
270                                         && client->sockaddr_in_from.sin_port       ==sockaddr_in_from.sin_port
271                                         && client->sockaddr_in_from.sin_addr.s_addr==sockaddr_in_from.sin_addr.s_addr)
272                                 break;
273                         }
274                 if (!clientl) {
275                         client=client_new();
276                         client->sockaddr_in_from=sockaddr_in_from;
277                         }
278                 client_touch(client);
279                 UDPGATE_MEMZERO(&sockaddr_in_server);
280                 sockaddr_in_server.sin_family=AF_INET;
281                 sockaddr_in_server.sin_port=htons(SERVER_PORT);
282                 sockaddr_in_server.sin_addr.s_addr=htonl(SERVER_INADDR);
283                 /* FIXME: errors checking */
284                 sendto(
285                                 client->gpollfd.fd,     /* s */
286                                 packet, /* msg */
287                                 gotlen, /* len */
288                                 0,      /* flags */
289                                 (struct sockaddr *)&sockaddr_in_server, /* to */
290                                 sizeof(sockaddr_in_server));    /* tolen */
291                 }
292 }
293
294 static void handle_probe(struct client *probe)
295 {
296 ssize_t gotlen;
297 struct sockaddr_in sockaddr_in_from;
298 char packet[0x10000];
299 socklen_t sockaddr_in_from_length;
300
301         g_return_if_fail(probe!=NULL);
302
303         sockaddr_in_from_length=sizeof(sockaddr_in_from);
304         while (-1!=(gotlen=recvfrom(
305                         master->gpollfd.fd,     /* s */
306                         packet, /* buf */
307                         sizeof(packet), /* len */
308                         0,      /* flags */
309                         (struct sockaddr *)&sockaddr_in_from,   /* from */
310                         &sockaddr_in_from_length))) {   /* fromlen */
311                 if (sockaddr_in_from_length!=sizeof(sockaddr_in_from))  /* FIXME: errors reporting */
312                         continue;
313
314                 /* Probe socket should have no response; maybe some ICMP errors - ignored. */
315                 }
316 }
317
318 static void handle_client(struct client *client)
319 {
320 ssize_t gotlen;
321 struct sockaddr_in sockaddr_in_from;
322 char packet [0x10000];
323 socklen_t sockaddr_in_from_length;
324
325         g_return_if_fail(client!=NULL);
326         g_return_if_fail(master!=NULL);
327
328         while (-1!=(gotlen=recvfrom(
329                         client->gpollfd.fd,     /* s */
330                         packet, /* buf */
331                         sizeof(packet), /* len */
332                         0,      /* flags */
333                         (struct sockaddr *)&sockaddr_in_from,   /* from */
334                         &sockaddr_in_from_length))) {   /* fromlen */
335                 if (sockaddr_in_from_length!=sizeof(sockaddr_in_from))  /* FIXME: errors reporting */
336                         continue;
337                 client_touch(client);
338                 /* FIXME: errors checking */
339                 sendto(
340                                 master->gpollfd.fd,     /* s */
341                                 packet, /* msg */
342                                 gotlen, /* len */
343                                 0,      /* flags */
344                                 (struct sockaddr *)&client->sockaddr_in_from,   /* to */
345                                 sizeof(client->sockaddr_in_from));      /* tolen */
346                 }
347 }
348
349 static gboolean sock_source_callback(gpointer data /* unused */)
350 {
351 GList *clientl;
352
353         for (clientl=sock_client_list;clientl;clientl=clientl->next) {
354 struct client *client=clientl->data;
355
356                 if (client->gpollfd.revents&SOCK_SOURCE_CHECK_REVENTS) {
357                         /**/ if (client==master)
358                                 handle_master(client);
359                         else if (client==probe)
360                                 handle_probe(client);
361                         else
362                                 handle_client(client);
363                         }
364                 }
365
366         return TRUE; /* the source should be kept active */
367 }
368
369 static gboolean sock_source_prepare(GSource *source,gint *timeout)
370 {
371         *timeout=-1;
372
373         return FALSE;
374 }
375
376 static gboolean sock_source_check(GSource *source)
377 {
378 GList *clientl;
379
380         for (clientl=sock_client_list;clientl;clientl=clientl->next) {
381 struct client *client=clientl->data;
382
383                 if (client->gpollfd.revents&SOCK_SOURCE_CHECK_REVENTS)
384                         return TRUE;
385                 }
386         return FALSE;
387 }
388
389 static gboolean sock_source_dispatch(GSource *source,GSourceFunc callback,gpointer user_data)
390 {
391         g_assert(callback!=NULL);
392         return (*callback)(user_data);
393 }
394
395 static GSourceFuncs sock_source_watch_funcs={
396                 sock_source_prepare,
397                 sock_source_check,
398                 sock_source_dispatch,
399                 NULL, /* finalize */
400                 };
401
402 static void sock_gsource_destroy(void)
403 {
404         while (sock_client_list)
405                 client_destroy(sock_client_list->data);
406
407         g_assert(master==NULL);
408
409         if (sock_gsource) {
410                 g_source_destroy(sock_gsource);
411                 sock_gsource=NULL;
412                 }
413
414         write_daemon_running((pid_t)-1);        /* unlink */
415 }
416
417 static gboolean sock_gsource_new(void)
418 {
419         if (sock_gsource)
420                 return TRUE;
421
422         g_assert(sock_client_list==NULL);
423
424         /* attach sock_source_callback() to watch for any abnormalities
425          * on our open pipe 'parentheart_fds' and terminate the child if parent dies.
426          */
427         if (!(sock_gsource=g_source_new(&sock_source_watch_funcs,sizeof(GSource)))) {
428                 g_warning("g_source_new(): %m");
429                 return FALSE;
430                 }
431         g_source_set_callback(
432                         sock_gsource,  /* source */
433                         sock_source_callback,  /* func */
434                         NULL, /* data */
435                         NULL);  /* notify */
436         if (!g_source_attach(   /* returns 'guint' id */
437                         sock_gsource,  /* source */
438                         NULL)) {        /* context; NULL means 'default context' */
439                 g_warning("g_source_attach(gsource,NULL): %m");
440                 sock_gsource_destroy();
441                 return FALSE;
442                 }
443         return TRUE;
444 }
445
446 static struct client *client_new(void)
447 {
448 struct client *client;
449 static unsigned long oneul=1;
450 int sock;
451
452         if (!sock_gsource_new())
453                 return FALSE;
454
455         if (-1==(sock=socket(AF_INET,SOCK_DGRAM,0))) {
456                 g_warning("socket(AF_INET,SOCK_DGRAM): %m");
457                 return NULL;
458                 }
459         if (ioctl(sock,FIONBIO,&oneul)) {       /* non-blocking mode */
460                 g_warning("ioctl(sock,FIONBIO,&1): %m");
461                 close(sock);    /* errors ignored */
462                 return NULL;
463                 }
464
465         udpgate_new(client);
466         client->gpollfd.fd=sock;
467         client->gpollfd.events=SOCK_SOURCE_CHECK_EVENTS;
468         client->gpollfd.revents=0;
469         client->timeout_id=0;
470         sock_client_list=g_list_prepend(sock_client_list,client);
471         g_source_add_poll(sock_gsource,&client->gpollfd);
472
473         if (optarg_verbose)
474                 g_message(_("Client fd %d created"),client->gpollfd.fd);
475
476         return client;
477 }
478
479 static void client_destroy(struct client *client)
480 {
481         g_return_if_fail(client!=NULL);
482
483         if (!sock_gsource_new())
484                 return;
485
486         if (optarg_verbose)
487                 g_message(_("Client fd %d timeout id %d destroy enter"),client->gpollfd.fd,client->timeout_id);
488
489         if (client==master) {
490                 master=NULL;
491                 g_assert(client->timeout_id==0);
492                 }
493         else {
494                 if (client==probe)
495                         probe=NULL;
496                 client_timeout_remove(client);
497                 }
498
499         g_source_remove_poll(sock_gsource,&client->gpollfd);
500         sock_client_list=g_list_remove(sock_client_list,client);
501         close(client->gpollfd.fd);      /* errors ignored */
502
503         if (optarg_verbose)
504                 g_message(_("Client fd %d timeout id %d destroy finish"),client->gpollfd.fd,client->timeout_id);
505
506         g_free(client);
507 }
508
509 static gboolean probe_send(struct client *probe,gint port_local)
510 {
511 struct sockaddr_in sockaddr_in_server;
512 GHashTable *probe_hash;
513 gpointer packet;
514 size_t packet_length;
515
516         g_return_val_if_fail(probe!=NULL,FALSE);
517
518         probe_unique=g_random_int();
519
520         probe_hash=g_hash_table_new(
521                         g_direct_hash,  /* hash_func */
522                         g_direct_equal);        /* key_equal_func */
523         g_hash_table_insert(probe_hash,GUINT_TO_POINTER(PACKET_ELEM_TYPE_CLIENT_PORT) ,GUINT_TO_POINTER(port_local));
524         g_hash_table_insert(probe_hash,GUINT_TO_POINTER(PACKET_ELEM_TYPE_DATA_GUINT32),GUINT_TO_POINTER(probe_unique));
525         packet=packet_assembly(&packet_length,probe_hash);
526         g_hash_table_destroy(probe_hash);
527         if (!packet)
528                 return FALSE;
529
530         UDPGATE_MEMZERO(&sockaddr_in_server);
531         sockaddr_in_server.sin_family=AF_INET;
532         sockaddr_in_server.sin_port=htons(PROBE_PORT);
533         sockaddr_in_server.sin_addr.s_addr=htonl(PROBE_INADDR);
534         /* FIXME: errors checking */
535         sendto(
536                         probe->gpollfd.fd,      /* s */
537                         packet, /* msg */
538                         packet_length,  /* len */
539                         0,      /* flags */
540                         (struct sockaddr *)&sockaddr_in_server, /* to */
541                         sizeof(sockaddr_in_server));    /* tolen */
542
543         return TRUE;
544 }
545
546 gboolean network_start(gint port)
547 {
548 pid_t daemon_pid;
549 struct sockaddr_in sockaddr_in;
550
551         g_return_val_if_fail(port>=0,FALSE);
552
553         if ((pid_t)-1!=(daemon_pid=is_daemon_running())) {
554                 g_warning(_("Cannot start network daemon: Daemon is already running on PID %d"),(int)daemon_pid);
555                 return FALSE;
556                 }
557
558         /* Setup 'master': */
559         g_assert(master==NULL);
560         if (!(master=client_new()))
561                 return FALSE;
562         UDPGATE_MEMZERO(&sockaddr_in);
563         sockaddr_in.sin_family=AF_INET;
564         sockaddr_in.sin_port=htons(port);
565         sockaddr_in.sin_addr.s_addr=htonl(INADDR_ANY);
566         if (bind(master->gpollfd.fd,(struct sockaddr *)&sockaddr_in,sizeof(sockaddr_in))) {
567                 g_warning("bind(sock,{AF_INET,INADDR_ANY:%d}): %m",(int)port);
568 err_sock_gsource_destroy:
569                 sock_gsource_destroy();
570                 return FALSE;
571                 }
572
573         /* Setup 'probe': */
574         if (!(probe=client_new()))
575                 goto err_sock_gsource_destroy;
576         probe_send(probe,port);
577         client_touch(probe);    /* timeout */
578
579         write_daemon_running(getpid());
580         return TRUE;
581 }
582
583 gboolean network_stop(void)
584 {
585 pid_t daemon_pid;
586 int errno_save;
587
588         if ((pid_t)-1==(daemon_pid=is_daemon_running())) {
589                 g_warning(_("Cannot stop network daemon: Daemon is not running"));
590                 return FALSE;
591                 }
592         if (daemon_pid==getpid()) {
593                 sock_gsource_destroy();
594                 return TRUE;
595                 }
596         errno=0;
597         kill(daemon_pid,SIGKILL);
598         errno_save=errno;
599         if (errno_save)  {
600                 g_warning(udpgate_printf_alloca(_("Unable to stop the daemon at PID %d: %s"),
601                                 (int)daemon_pid,strerror(errno_save)));
602                 return FALSE;
603                 }
604         return TRUE;
605 }