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