74208be8f0d4f3e9ded2e187894d429d6208b992
[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
42
43 /* Config: */
44 #define NETWORK_PATHNAME_PID "/var/run/udpgate.pid"
45 #define SOCK_SOURCE_CHECK_EVENTS (G_IO_IN)      /* |G_IO_PRI */
46 #define SOCK_SOURCE_CHECK_REVENTS (SOCK_SOURCE_CHECK_EVENTS)    /* |G_IO_ERR|G_IO_HUP|G_IO_NVAL */
47 #define SERVER_INADDR 0x7F000001
48 #undef  SERVER_INADDR
49 #define SERVER_INADDR 0x511F02EA        /* paulina.vellum.cz = 81.31.2.234; host order */
50 #define SERVER_PORT   9201      /* host order */
51 #define PROBE_INADDR  SERVER_INADDR     /* host order */
52 #define PROBE_PORT    8201      /* host order */
53 #define CLIENT_TIMEOUT_SEC (5*60)
54 #define PROBE_TIMEOUT_SEC (5)
55
56
57 void (*network_notify_hostip)(guint32 hostip_guint32,const gchar *hostip_string);
58
59
60 struct client {
61         GPollFD gpollfd;
62         struct sockaddr_in sockaddr_in_from;
63         guint timeout_id;
64         };
65
66 static GSource *sock_gsource;
67
68 static GList *sock_client_list; /* of 'struct client *', incl. 'master' and 'probe' */
69 static struct client *master;   /* no 'timeout' permitted */
70 static struct client *probe;    /* 'timeout' permitted */
71 static guint32 probe_unique;
72
73 static gboolean write_daemon_running(pid_t pid);
74
75 pid_t is_daemon_running(void)
76 {
77 FILE *f;
78 char buf[LINE_MAX],*got;
79 int pid_int;
80
81         if (sock_gsource)
82                 return getpid();
83
84         if (!(f=fopen(NETWORK_PATHNAME_PID,"r")))
85                 goto err;
86         got=fgets(buf,sizeof(buf),f);
87         fclose(f);      /* FIXME: error ignored */
88         if (got!=buf) {
89 err_unlink:
90                 write_daemon_running((pid_t)-1);        /* unlink */
91 err:
92                 return (pid_t)-1;
93                 }
94         pid_int=atoi(buf);
95         if (pid_int<=1)
96                 goto err_unlink;
97         if (kill((pid_t)pid_int,0)) {
98                 if (errno==ESRCH)
99                         goto err_unlink;
100                 goto err;
101                 }
102         return (pid_t)pid_int;
103 }
104
105 static gboolean write_daemon_running(pid_t pid)
106 {
107 FILE *f;
108
109         if (pid==(pid_t)-1) {
110                 if (unlink(NETWORK_PATHNAME_PID)) {
111                         if (errno!=ENOENT)
112                                 g_warning(_("Error removing PID file \"%s\": %m"),NETWORK_PATHNAME_PID);
113                         return FALSE;
114                         }
115                 return TRUE;
116                 }
117         if (!(f=fopen(NETWORK_PATHNAME_PID,"w"))) {
118                 g_warning(_("Error writing PID %d to \"%s\": %m"),(int)pid,NETWORK_PATHNAME_PID);
119                 return FALSE;
120                 }
121         fprintf(f,"%d\n",(int)pid);     /* errors ignored */
122         fclose(f);      /* FIXME: error ignored */
123         return TRUE;
124 }
125
126 static void client_timeout_remove(struct client *client)
127 {
128         g_return_if_fail(client!=NULL);
129         g_return_if_fail(client!=master);
130
131         if (client->timeout_id) {
132 gboolean errgboolean;
133
134                 errgboolean=g_source_remove(client->timeout_id);
135                 g_assert(errgboolean==TRUE);
136                 client->timeout_id=0;
137                 }
138 }
139
140 static gboolean client_touch_timeout(struct client *client);
141
142 static void client_touch(struct client *client)
143 {
144         g_return_if_fail(client!=NULL);
145         g_return_if_fail(client!=master);
146
147         client_timeout_remove(client);
148         client->timeout_id=g_timeout_add(
149                         (client==probe ? PROBE_TIMEOUT_SEC*1000 : CLIENT_TIMEOUT_SEC*1000),     /* interval; msec */
150                         (GSourceFunc)client_touch_timeout,      /* function */
151                         client);        /* data */
152         g_assert(client->timeout_id!=0);
153 }
154
155 static void client_destroy(struct client *client);
156
157 static gboolean client_touch_timeout(struct client *client)
158 {
159         g_return_val_if_fail(client!=NULL,FALSE);       /* FALSE=>should be removed */
160         g_return_val_if_fail(client!=master,FALSE);     /* FALSE=>should be removed */
161
162         if (client==probe) {
163                 network_stop();
164                 if (network_notify_hostip)
165                         (*network_notify_hostip)(0,NULL);
166                 }
167
168         client_destroy(client);
169
170         return FALSE;   /* GSource should be removed */
171 }
172
173 static struct client *client_new(void);
174
175 static void handle_master(struct client *master)
176 {
177 ssize_t gotlen;
178 struct sockaddr_in sockaddr_in_from;
179 char packet[0x10000];
180 struct client *client;
181 struct sockaddr_in sockaddr_in_server;
182 socklen_t sockaddr_in_from_length;
183
184         g_return_if_fail(master!=NULL);
185
186         sockaddr_in_from_length=sizeof(sockaddr_in_from);
187         while (-1!=(gotlen=recvfrom(
188                         master->gpollfd.fd,     /* s */
189                         packet, /* buf */
190                         sizeof(packet), /* len */
191                         0,      /* flags */
192                         (struct sockaddr *)&sockaddr_in_from,   /* from */
193                         &sockaddr_in_from_length))) {   /* fromlen */
194 GList *clientl;
195
196                 if (sockaddr_in_from_length!=sizeof(sockaddr_in_from))  /* FIXME: errors reporting */
197                         continue;
198                 /* FIXME: Performance: Ugly search... */
199                 for (clientl=sock_client_list;clientl;clientl=clientl->next) {
200                         client=clientl->data;
201                         if (client==master)
202                                 continue;
203                         if (1
204                                         && client->sockaddr_in_from.sin_family     ==sockaddr_in_from.sin_family
205                                         && client->sockaddr_in_from.sin_port       ==sockaddr_in_from.sin_port
206                                         && client->sockaddr_in_from.sin_addr.s_addr==sockaddr_in_from.sin_addr.s_addr)
207                                 break;
208                         }
209                 if (!clientl) {
210                         client=client_new();
211                         client->sockaddr_in_from=sockaddr_in_from;
212                         }
213                 client_touch(client);
214                 UDPGATE_MEMZERO(&sockaddr_in_server);
215                 sockaddr_in_server.sin_family=AF_INET;
216                 sockaddr_in_server.sin_port=htons(SERVER_PORT);
217                 sockaddr_in_server.sin_addr.s_addr=htonl(SERVER_INADDR);
218                 /* FIXME: errors checking */
219                 sendto(
220                                 client->gpollfd.fd,     /* s */
221                                 packet, /* msg */
222                                 gotlen, /* len */
223                                 0,      /* flags */
224                                 (struct sockaddr *)&sockaddr_in_server, /* to */
225                                 sizeof(sockaddr_in_server));    /* tolen */
226                 }
227 }
228
229 static void handle_probe(struct client *probe)
230 {
231 ssize_t gotlen;
232 struct sockaddr_in sockaddr_in_from;
233 char packet[0x10000];
234 socklen_t sockaddr_in_from_length;
235
236         g_return_if_fail(probe!=NULL);
237
238         sockaddr_in_from_length=sizeof(sockaddr_in_from);
239         while (-1!=(gotlen=recvfrom(
240                         master->gpollfd.fd,     /* s */
241                         packet, /* buf */
242                         sizeof(packet), /* len */
243                         0,      /* flags */
244                         (struct sockaddr *)&sockaddr_in_from,   /* from */
245                         &sockaddr_in_from_length))) {   /* fromlen */
246 static GHashTable *got_hash;
247 static gpointer got_unique_gpointer;
248 static gpointer hostip_gpointer;
249 static guint32 hostip_guint32;
250
251                 if (sockaddr_in_from_length!=sizeof(sockaddr_in_from))  /* FIXME: errors reporting */
252                         continue;
253                 if (!(got_hash=packet_disassembly(packet,gotlen)))
254                         continue;
255                 if (!(g_hash_table_lookup_extended(
256                                 got_hash,       /* hash_table */
257                                 GUINT_TO_POINTER(PACKET_ELEM_TYPE_DATA_GUINT32),        /* lookup_key */
258                                 NULL,   /* orig_key */
259                                 &got_unique_gpointer))) {
260 err_packet_disassembly_destroy_got_hash:
261                         packet_disassembly_destroy(got_hash);
262                         continue;
263                         }
264                 if (GPOINTER_TO_UINT(got_unique_gpointer)!=probe_unique)
265                         goto err_packet_disassembly_destroy_got_hash;
266                 if (!(g_hash_table_lookup_extended(
267                                 got_hash,       /* hash_table */
268                                 GUINT_TO_POINTER(PACKET_ELEM_TYPE_CLIENT_INADDR),       /* lookup_key */
269                                 NULL,   /* orig_key */
270                                 &hostip_gpointer)))
271                         goto err_packet_disassembly_destroy_got_hash;
272                 hostip_guint32=GPOINTER_TO_UINT(hostip_gpointer);
273                 packet_disassembly_destroy(got_hash);
274
275                 client_destroy(probe);
276                 if (network_notify_hostip)
277                         (*network_notify_hostip)(hostip_guint32,HOSTIP_GUINT32_TO_STRING(hostip_guint32));
278                 }
279 }
280
281 static void handle_client(struct client *client)
282 {
283 ssize_t gotlen;
284 struct sockaddr_in sockaddr_in_from;
285 char packet [0x10000];
286 socklen_t sockaddr_in_from_length;
287
288         g_return_if_fail(client!=NULL);
289         g_return_if_fail(master!=NULL);
290
291         while (-1!=(gotlen=recvfrom(
292                         client->gpollfd.fd,     /* s */
293                         packet, /* buf */
294                         sizeof(packet), /* len */
295                         0,      /* flags */
296                         (struct sockaddr *)&sockaddr_in_from,   /* from */
297                         &sockaddr_in_from_length))) {   /* fromlen */
298                 if (sockaddr_in_from_length!=sizeof(sockaddr_in_from))  /* FIXME: errors reporting */
299                         continue;
300                 client_touch(client);
301                 /* FIXME: errors checking */
302                 sendto(
303                                 master->gpollfd.fd,     /* s */
304                                 packet, /* msg */
305                                 gotlen, /* len */
306                                 0,      /* flags */
307                                 (struct sockaddr *)&client->sockaddr_in_from,   /* to */
308                                 sizeof(client->sockaddr_in_from));      /* tolen */
309                 }
310 }
311
312 static gboolean sock_source_callback(gpointer data /* unused */)
313 {
314 GList *clientl;
315
316         for (clientl=sock_client_list;clientl;clientl=clientl->next) {
317 struct client *client=clientl->data;
318
319                 if (client->gpollfd.revents&SOCK_SOURCE_CHECK_REVENTS) {
320                         /**/ if (client==master)
321                                 handle_master(client);
322                         else if (client==probe)
323                                 handle_probe(client);
324                         else
325                                 handle_client(client);
326                         }
327                 }
328
329         return TRUE; /* the source should be kept active */
330 }
331
332 static gboolean sock_source_prepare(GSource *source,gint *timeout)
333 {
334         *timeout=-1;
335
336         return FALSE;
337 }
338
339 static gboolean sock_source_check(GSource *source)
340 {
341 GList *clientl;
342
343         for (clientl=sock_client_list;clientl;clientl=clientl->next) {
344 struct client *client=clientl->data;
345
346                 if (client->gpollfd.revents&SOCK_SOURCE_CHECK_REVENTS)
347                         return TRUE;
348                 }
349         return FALSE;
350 }
351
352 static gboolean sock_source_dispatch(GSource *source,GSourceFunc callback,gpointer user_data)
353 {
354         g_assert(callback!=NULL);
355         return (*callback)(user_data);
356 }
357
358 static GSourceFuncs sock_source_watch_funcs={
359                 sock_source_prepare,
360                 sock_source_check,
361                 sock_source_dispatch,
362                 NULL, /* finalize */
363                 };
364
365 static void sock_gsource_destroy(void)
366 {
367         while (sock_client_list)
368                 client_destroy(sock_client_list->data);
369
370         g_assert(master==NULL);
371
372         if (sock_gsource) {
373                 g_source_destroy(sock_gsource);
374                 sock_gsource=NULL;
375                 }
376
377         write_daemon_running((pid_t)-1);        /* unlink */
378 }
379
380 static gboolean sock_gsource_new(void)
381 {
382         if (sock_gsource)
383                 return TRUE;
384
385         g_assert(sock_client_list==NULL);
386
387         /* attach sock_source_callback() to watch for any abnormalities
388          * on our open pipe 'parentheart_fds' and terminate the child if parent dies.
389          */
390         if (!(sock_gsource=g_source_new(&sock_source_watch_funcs,sizeof(GSource)))) {
391                 g_warning("g_source_new(): %m");
392                 return FALSE;
393                 }
394         g_source_set_callback(
395                         sock_gsource,  /* source */
396                         sock_source_callback,  /* func */
397                         NULL, /* data */
398                         NULL);  /* notify */
399         if (!g_source_attach(   /* returns 'guint' id */
400                         sock_gsource,  /* source */
401                         NULL)) {        /* context; NULL means 'default context' */
402                 g_warning("g_source_attach(gsource,NULL): %m");
403                 sock_gsource_destroy();
404                 return FALSE;
405                 }
406         return TRUE;
407 }
408
409 static struct client *client_new(void)
410 {
411 struct client *client;
412 static unsigned long oneul=1;
413 int sock;
414
415         if (!sock_gsource_new())
416                 return FALSE;
417
418         if (-1==(sock=socket(AF_INET,SOCK_DGRAM,0))) {
419                 g_warning("socket(AF_INET,SOCK_DGRAM): %m");
420                 return NULL;
421                 }
422         if (ioctl(sock,FIONBIO,&oneul)) {       /* non-blocking mode */
423                 g_warning("ioctl(sock,FIONBIO,&1): %m");
424                 close(sock);    /* errors ignored */
425                 return NULL;
426                 }
427
428         udpgate_new(client);
429         client->gpollfd.fd=sock;
430         client->gpollfd.events=SOCK_SOURCE_CHECK_EVENTS;
431         client->gpollfd.revents=0;
432         client->timeout_id=0;
433         sock_client_list=g_list_prepend(sock_client_list,client);
434         g_source_add_poll(sock_gsource,&client->gpollfd);
435
436         return client;
437 }
438
439 static void client_destroy(struct client *client)
440 {
441         g_return_if_fail(client!=NULL);
442
443         if (!sock_gsource_new())
444                 return;
445
446         if (client==master) {
447                 master=NULL;
448                 g_assert(client->timeout_id==0);
449                 }
450         else {
451                 if (client==probe)
452                         probe=NULL;
453                 client_timeout_remove(client);
454                 }
455
456         g_source_remove_poll(sock_gsource,&client->gpollfd);
457         sock_client_list=g_list_remove(sock_client_list,client);
458         close(client->gpollfd.fd);      /* errors ignored */
459         g_free(client);
460 }
461
462 static gboolean probe_send(struct client *probe,gint port_local)
463 {
464 struct sockaddr_in sockaddr_in_server;
465 GHashTable *probe_hash;
466 gpointer packet;
467 size_t packet_length;
468
469         g_return_val_if_fail(probe!=NULL,FALSE);
470
471         probe_unique=g_random_int();
472
473         probe_hash=g_hash_table_new(
474                         g_direct_hash,  /* hash_func */
475                         g_direct_equal);        /* key_equal_func */
476         g_hash_table_insert(probe_hash,GUINT_TO_POINTER(PACKET_ELEM_TYPE_CLIENT_PORT) ,GUINT_TO_POINTER(port_local));
477         g_hash_table_insert(probe_hash,GUINT_TO_POINTER(PACKET_ELEM_TYPE_DATA_GUINT32),GUINT_TO_POINTER(probe_unique));
478         packet=packet_assembly(&packet_length,probe_hash);
479         g_hash_table_destroy(probe_hash);
480         if (!packet)
481                 return FALSE;
482
483         UDPGATE_MEMZERO(&sockaddr_in_server);
484         sockaddr_in_server.sin_family=AF_INET;
485         sockaddr_in_server.sin_port=htons(PROBE_PORT);
486         sockaddr_in_server.sin_addr.s_addr=htonl(PROBE_INADDR);
487         /* FIXME: errors checking */
488         sendto(
489                         probe->gpollfd.fd,      /* s */
490                         packet, /* msg */
491                         packet_length,  /* len */
492                         0,      /* flags */
493                         (struct sockaddr *)&sockaddr_in_server, /* to */
494                         sizeof(sockaddr_in_server));    /* tolen */
495
496         return TRUE;
497 }
498
499 gboolean network_start(gint port)
500 {
501 pid_t daemon_pid;
502 struct sockaddr_in sockaddr_in;
503
504         g_return_val_if_fail(port>=0,FALSE);
505
506         if ((pid_t)-1!=(daemon_pid=is_daemon_running())) {
507                 g_warning(_("Cannot start network daemon: Daemon is already running on PID %d"),(int)daemon_pid);
508                 return FALSE;
509                 }
510
511         /* Setup 'master': */
512         g_assert(master==NULL);
513         if (!(master=client_new()))
514                 return FALSE;
515         UDPGATE_MEMZERO(&sockaddr_in);
516         sockaddr_in.sin_family=AF_INET;
517         sockaddr_in.sin_port=htons(port);
518         sockaddr_in.sin_addr.s_addr=INADDR_ANY;
519         if (bind(master->gpollfd.fd,(struct sockaddr *)&sockaddr_in,sizeof(sockaddr_in))) {
520                 g_warning("bind(sock,{AF_INET,INADDR_ANY:%d}): %m",(int)port);
521 err_sock_gsource_destroy:
522                 sock_gsource_destroy();
523                 return FALSE;
524                 }
525
526         /* Setup 'probe': */
527         if (!(probe=client_new()))
528                 goto err_sock_gsource_destroy;
529         probe_send(probe,port);
530         client_touch(probe);    /* timeout */
531
532         write_daemon_running(getpid());
533         return TRUE;
534 }
535
536 gboolean network_stop(void)
537 {
538 pid_t daemon_pid;
539 int errno_save;
540
541         if ((pid_t)-1==(daemon_pid=is_daemon_running())) {
542                 g_warning(_("Cannot stop network daemon: Daemon is not running"));
543                 return FALSE;
544                 }
545         if (daemon_pid==getpid()) {
546                 sock_gsource_destroy();
547                 return TRUE;
548                 }
549         errno=0;
550         kill(daemon_pid,SIGKILL);
551         errno_save=errno;
552         if (errno_save)  {
553                 g_warning(udpgate_printf_alloca(_("Unable to stop the daemon at PID %d: %s"),
554                                 (int)daemon_pid,strerror(errno_save)));
555                 return FALSE;
556                 }
557         return TRUE;
558 }