Command-line version implemented.
[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 0x511F02EA        /* paulina.vellum.cz = 81.31.2.234; host order */
49 #undef  SERVER_INADDR
50 #define SERVER_INADDR 0x7F000001
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                 }
180         else {
181                 client_destroy(client);
182                 }
183
184         if (optarg_verbose)
185                 g_message(_("Client timeout occurance finish"));
186
187         return FALSE;   /* GSource should be removed */
188 }
189
190 static void handle_master_probe(const void *packet,size_t gotlen,const struct sockaddr_in *sockaddr_in_from)
191 {
192 GHashTable *got_hash;
193 gpointer got_unique_gpointer;
194 gpointer hostip_gpointer;
195 guint32 hostip_guint32;
196
197         g_return_if_fail(packet!=NULL);
198         g_return_if_fail(sockaddr_in_from!=NULL);
199
200         if (!probe)
201                 return;
202
203         if (!(got_hash=packet_disassembly(packet,gotlen)))
204                 return;
205         if (!(g_hash_table_lookup_extended(
206                         got_hash,       /* hash_table */
207                         GUINT_TO_POINTER(PACKET_ELEM_TYPE_DATA_GUINT32),        /* lookup_key */
208                         NULL,   /* orig_key */
209                         &got_unique_gpointer))) {
210 err_packet_disassembly_destroy_got_hash:
211                 packet_disassembly_destroy(got_hash);
212                 return;
213                 }
214         if (GPOINTER_TO_UINT(got_unique_gpointer)!=probe_unique)
215                 goto err_packet_disassembly_destroy_got_hash;
216         if (!(g_hash_table_lookup_extended(
217                         got_hash,       /* hash_table */
218                         GUINT_TO_POINTER(PACKET_ELEM_TYPE_CLIENT_INADDR),       /* lookup_key */
219                         NULL,   /* orig_key */
220                         &hostip_gpointer)))
221                 goto err_packet_disassembly_destroy_got_hash;
222         hostip_guint32=GPOINTER_TO_UINT(hostip_gpointer);
223         packet_disassembly_destroy(got_hash);
224
225         client_destroy(probe);
226         if (network_notify_hostip)
227                 (*network_notify_hostip)(hostip_guint32);
228 }
229
230 static struct client *client_new(void);
231
232 static void handle_master(struct client *master)
233 {
234 ssize_t gotlen;
235 struct sockaddr_in sockaddr_in_from;
236 char packet[0x10000];
237 struct client *client;
238 struct sockaddr_in sockaddr_in_server;
239 socklen_t sockaddr_in_from_length;
240
241         g_return_if_fail(master!=NULL);
242
243         sockaddr_in_from_length=sizeof(sockaddr_in_from);
244         while (-1!=(gotlen=recvfrom(
245                         master->gpollfd.fd,     /* s */
246                         packet, /* buf */
247                         sizeof(packet), /* len */
248                         0,      /* flags */
249                         (struct sockaddr *)&sockaddr_in_from,   /* from */
250                         &sockaddr_in_from_length))) {   /* fromlen */
251 GList *clientl;
252
253                 if (sockaddr_in_from_length!=sizeof(sockaddr_in_from))  /* FIXME: errors reporting */
254                         continue;
255
256                 if (packet_recognized(packet,gotlen)) {
257                         handle_master_probe(packet,gotlen,&sockaddr_in_from);
258                         continue;
259                         }
260
261                 /* FIXME: Performance: Ugly search... */
262                 for (clientl=sock_client_list;clientl;clientl=clientl->next) {
263                         client=clientl->data;
264                         if (client==master)
265                                 continue;
266                         if (1
267                                         && client->sockaddr_in_from.sin_family     ==sockaddr_in_from.sin_family
268                                         && client->sockaddr_in_from.sin_port       ==sockaddr_in_from.sin_port
269                                         && client->sockaddr_in_from.sin_addr.s_addr==sockaddr_in_from.sin_addr.s_addr)
270                                 break;
271                         }
272                 if (!clientl) {
273                         client=client_new();
274                         client->sockaddr_in_from=sockaddr_in_from;
275                         }
276                 client_touch(client);
277                 UDPGATE_MEMZERO(&sockaddr_in_server);
278                 sockaddr_in_server.sin_family=AF_INET;
279                 sockaddr_in_server.sin_port=htons(SERVER_PORT);
280                 sockaddr_in_server.sin_addr.s_addr=htonl(SERVER_INADDR);
281                 /* FIXME: errors checking */
282                 sendto(
283                                 client->gpollfd.fd,     /* s */
284                                 packet, /* msg */
285                                 gotlen, /* len */
286                                 0,      /* flags */
287                                 (struct sockaddr *)&sockaddr_in_server, /* to */
288                                 sizeof(sockaddr_in_server));    /* tolen */
289                 }
290 }
291
292 static void handle_probe(struct client *probe)
293 {
294 ssize_t gotlen;
295 struct sockaddr_in sockaddr_in_from;
296 char packet[0x10000];
297 socklen_t sockaddr_in_from_length;
298
299         g_return_if_fail(probe!=NULL);
300
301         sockaddr_in_from_length=sizeof(sockaddr_in_from);
302         while (-1!=(gotlen=recvfrom(
303                         master->gpollfd.fd,     /* s */
304                         packet, /* buf */
305                         sizeof(packet), /* len */
306                         0,      /* flags */
307                         (struct sockaddr *)&sockaddr_in_from,   /* from */
308                         &sockaddr_in_from_length))) {   /* fromlen */
309                 if (sockaddr_in_from_length!=sizeof(sockaddr_in_from))  /* FIXME: errors reporting */
310                         continue;
311
312                 /* Probe socket should have no response; maybe some ICMP errors - ignored. */
313                 }
314 }
315
316 static void handle_client(struct client *client)
317 {
318 ssize_t gotlen;
319 struct sockaddr_in sockaddr_in_from;
320 char packet [0x10000];
321 socklen_t sockaddr_in_from_length;
322
323         g_return_if_fail(client!=NULL);
324         g_return_if_fail(master!=NULL);
325
326         while (-1!=(gotlen=recvfrom(
327                         client->gpollfd.fd,     /* s */
328                         packet, /* buf */
329                         sizeof(packet), /* len */
330                         0,      /* flags */
331                         (struct sockaddr *)&sockaddr_in_from,   /* from */
332                         &sockaddr_in_from_length))) {   /* fromlen */
333                 if (sockaddr_in_from_length!=sizeof(sockaddr_in_from))  /* FIXME: errors reporting */
334                         continue;
335                 client_touch(client);
336                 /* FIXME: errors checking */
337                 sendto(
338                                 master->gpollfd.fd,     /* s */
339                                 packet, /* msg */
340                                 gotlen, /* len */
341                                 0,      /* flags */
342                                 (struct sockaddr *)&client->sockaddr_in_from,   /* to */
343                                 sizeof(client->sockaddr_in_from));      /* tolen */
344                 }
345 }
346
347 static gboolean sock_source_callback(gpointer data /* unused */)
348 {
349 GList *clientl;
350
351         for (clientl=sock_client_list;clientl;clientl=clientl->next) {
352 struct client *client=clientl->data;
353
354                 if (client->gpollfd.revents&SOCK_SOURCE_CHECK_REVENTS) {
355                         /**/ if (client==master)
356                                 handle_master(client);
357                         else if (client==probe)
358                                 handle_probe(client);
359                         else
360                                 handle_client(client);
361                         }
362                 }
363
364         return TRUE; /* the source should be kept active */
365 }
366
367 static gboolean sock_source_prepare(GSource *source,gint *timeout)
368 {
369         *timeout=-1;
370
371         return FALSE;
372 }
373
374 static gboolean sock_source_check(GSource *source)
375 {
376 GList *clientl;
377
378         for (clientl=sock_client_list;clientl;clientl=clientl->next) {
379 struct client *client=clientl->data;
380
381                 if (client->gpollfd.revents&SOCK_SOURCE_CHECK_REVENTS)
382                         return TRUE;
383                 }
384         return FALSE;
385 }
386
387 static gboolean sock_source_dispatch(GSource *source,GSourceFunc callback,gpointer user_data)
388 {
389         g_assert(callback!=NULL);
390         return (*callback)(user_data);
391 }
392
393 static GSourceFuncs sock_source_watch_funcs={
394                 sock_source_prepare,
395                 sock_source_check,
396                 sock_source_dispatch,
397                 NULL, /* finalize */
398                 };
399
400 static void sock_gsource_destroy(void)
401 {
402         while (sock_client_list)
403                 client_destroy(sock_client_list->data);
404
405         g_assert(master==NULL);
406
407         if (sock_gsource) {
408                 g_source_destroy(sock_gsource);
409                 sock_gsource=NULL;
410                 }
411
412         write_daemon_running((pid_t)-1);        /* unlink; errors ignored */
413 }
414
415 static gboolean sock_gsource_new(void)
416 {
417         if (sock_gsource)
418                 return TRUE;
419
420         g_assert(sock_client_list==NULL);
421
422         /* attach sock_source_callback() to watch for any abnormalities
423          * on our open pipe 'parentheart_fds' and terminate the child if parent dies.
424          */
425         if (!(sock_gsource=g_source_new(&sock_source_watch_funcs,sizeof(GSource)))) {
426                 g_warning("g_source_new(): %m");
427                 return FALSE;
428                 }
429         g_source_set_callback(
430                         sock_gsource,  /* source */
431                         sock_source_callback,  /* func */
432                         NULL, /* data */
433                         NULL);  /* notify */
434         if (!g_source_attach(   /* returns 'guint' id */
435                         sock_gsource,  /* source */
436                         NULL)) {        /* context; NULL means 'default context' */
437                 g_warning("g_source_attach(gsource,NULL): %m");
438                 sock_gsource_destroy();
439                 return FALSE;
440                 }
441         return TRUE;
442 }
443
444 static struct client *client_new(void)
445 {
446 struct client *client;
447 static unsigned long oneul=1;
448 int sock;
449
450         if (!sock_gsource_new())
451                 return FALSE;
452
453         if (-1==(sock=socket(AF_INET,SOCK_DGRAM,0))) {
454                 g_warning("socket(AF_INET,SOCK_DGRAM): %m");
455                 return NULL;
456                 }
457         if (ioctl(sock,FIONBIO,&oneul)) {       /* non-blocking mode */
458                 g_warning("ioctl(sock,FIONBIO,&1): %m");
459                 close(sock);    /* errors ignored */
460                 return NULL;
461                 }
462
463         udpgate_new(client);
464         client->gpollfd.fd=sock;
465         client->gpollfd.events=SOCK_SOURCE_CHECK_EVENTS;
466         client->gpollfd.revents=0;
467         client->timeout_id=0;
468         sock_client_list=g_list_prepend(sock_client_list,client);
469         g_source_add_poll(sock_gsource,&client->gpollfd);
470
471         if (optarg_verbose)
472                 g_message(_("Client fd %d created"),client->gpollfd.fd);
473
474         return client;
475 }
476
477 static void client_destroy(struct client *client)
478 {
479         g_return_if_fail(client!=NULL);
480
481         if (!sock_gsource_new())
482                 return;
483
484         if (optarg_verbose)
485                 g_message(_("Client fd %d timeout id %d destroy enter"),client->gpollfd.fd,client->timeout_id);
486
487         if (client==master) {
488                 master=NULL;
489                 g_assert(client->timeout_id==0);
490                 }
491         else {
492                 if (client==probe)
493                         probe=NULL;
494                 client_timeout_remove(client);
495                 }
496
497         g_source_remove_poll(sock_gsource,&client->gpollfd);
498         sock_client_list=g_list_remove(sock_client_list,client);
499         close(client->gpollfd.fd);      /* errors ignored */
500
501         if (optarg_verbose)
502                 g_message(_("Client fd %d timeout id %d destroy finish"),client->gpollfd.fd,client->timeout_id);
503
504         g_free(client);
505 }
506
507 static gboolean probe_send(struct client *probe,gint port_local)
508 {
509 struct sockaddr_in sockaddr_in_server;
510 GHashTable *probe_hash;
511 gpointer packet;
512 size_t packet_length;
513
514         g_return_val_if_fail(probe!=NULL,FALSE);
515
516         probe_unique=g_random_int();
517
518         probe_hash=g_hash_table_new(
519                         g_direct_hash,  /* hash_func */
520                         g_direct_equal);        /* key_equal_func */
521         g_hash_table_insert(probe_hash,GUINT_TO_POINTER(PACKET_ELEM_TYPE_CLIENT_PORT) ,GUINT_TO_POINTER(port_local));
522         g_hash_table_insert(probe_hash,GUINT_TO_POINTER(PACKET_ELEM_TYPE_DATA_GUINT32),GUINT_TO_POINTER(probe_unique));
523         packet=packet_assembly(&packet_length,probe_hash);
524         g_hash_table_destroy(probe_hash);
525         if (!packet)
526                 return FALSE;
527
528         UDPGATE_MEMZERO(&sockaddr_in_server);
529         sockaddr_in_server.sin_family=AF_INET;
530         sockaddr_in_server.sin_port=htons(PROBE_PORT);
531         sockaddr_in_server.sin_addr.s_addr=htonl(PROBE_INADDR);
532         /* FIXME: errors checking */
533         sendto(
534                         probe->gpollfd.fd,      /* s */
535                         packet, /* msg */
536                         packet_length,  /* len */
537                         0,      /* flags */
538                         (struct sockaddr *)&sockaddr_in_server, /* to */
539                         sizeof(sockaddr_in_server));    /* tolen */
540
541         return TRUE;
542 }
543
544 gboolean network_start(gint port)
545 {
546 pid_t daemon_pid;
547 struct sockaddr_in sockaddr_in;
548
549         g_return_val_if_fail(port>=0,FALSE);
550
551         if ((pid_t)-1!=(daemon_pid=is_daemon_running())) {
552                 g_warning(_("Cannot start network daemon: Daemon is already running on PID %d"),(int)daemon_pid);
553                 return FALSE;
554                 }
555
556         /* Setup 'master': */
557         g_assert(master==NULL);
558         if (!(master=client_new()))
559                 return FALSE;
560         UDPGATE_MEMZERO(&sockaddr_in);
561         sockaddr_in.sin_family=AF_INET;
562         sockaddr_in.sin_port=htons(port);
563         sockaddr_in.sin_addr.s_addr=htonl(INADDR_ANY);
564         if (bind(master->gpollfd.fd,(struct sockaddr *)&sockaddr_in,sizeof(sockaddr_in))) {
565                 g_warning("bind(sock,{AF_INET,INADDR_ANY:%d}): %m",(int)port);
566 err_sock_gsource_destroy:
567                 sock_gsource_destroy();
568                 return FALSE;
569                 }
570
571         /* Setup 'probe': */
572         if (!(probe=client_new()))
573                 goto err_sock_gsource_destroy;
574         probe_send(probe,port);
575         client_touch(probe);    /* timeout */
576
577         write_daemon_running(getpid()); /* errors ignored */
578         if (network_notify_hostip)
579                 (*network_notify_hostip)(0);
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                 goto ok;
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 ok:
605         if (network_notify_hostip)
606                 (*network_notify_hostip)(0);
607         return TRUE;
608 }
609
610 static GMainLoop *gmainloop;
611 static void network_detach_network_notify_hostip(guint32 hostip_guint32)
612 {
613         if (!hostip_guint32)
614                 g_main_loop_quit(gmainloop);
615 }
616
617 gboolean network_detach(void)
618 {
619 pid_t daemon_pid,forked_pid;
620
621         if ((pid_t)-1==(daemon_pid=is_daemon_running()))
622                 return TRUE;
623         if (getpid()!=daemon_pid)
624                 return TRUE;
625         if (!optarg_no_fork) {
626                 if ((pid_t)-1==(forked_pid=fork())) {
627                         g_warning("fork(2): %m");
628                         return FALSE;
629                         }
630                 if (forked_pid) {
631                         /* parent */
632                         return TRUE;
633                         }
634                 write_daemon_running(getpid()); /* errors ignored */
635                 optarg_verbose=0;
636                 close(STDIN_FILENO);
637                 close(STDOUT_FILENO);
638                 close(STDERR_FILENO);
639                 setpgrp();
640                 setsid();
641                 }
642
643         network_notify_hostip=network_detach_network_notify_hostip;
644         gmainloop=g_main_loop_new(
645                         NULL,   /* context */
646                         TRUE);  /* is_running; ignored */
647         g_main_loop_run(gmainloop);     /* loop */
648         g_warning(_("Unable to contact the server, aborting"));
649         return FALSE;
650 }