2 * UDP Gateway utility network layer
3 * Copyright (C) 2004 Jan Kratochvil <project-udpgate@jankratochvil.net>
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
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.
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
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>
29 #include <sys/types.h>
32 #include <glib/giochannel.h>
33 #include <sys/ioctl.h>
35 #include <glib/galloca.h>
36 #include <glib/gprintf.h>
37 #include <glib/grand.h>
41 #include "main.h" /* for optarg_verbose */
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 0xC37AD054 /* mms2.org = 195.122.208.84; host order */
49 #define SERVER_PORT 9201 /* host order */
50 #define PROBE_INADDR SERVER_INADDR /* host order */
51 #define PROBE_PORT 8201 /* host order */
52 #define CLIENT_TIMEOUT_SEC (5*60)
53 #define PROBE_TIMEOUT_SEC_BASE 5
54 #define PROBE_TIMEOUT_SEC_MAX 3500
57 void (*network_notify_hostip)(guint32 hostip_guint32);
62 struct sockaddr_in sockaddr_in_from;
66 static GSource *sock_gsource;
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 static guint probe_timeout_sec_now;
73 guint probe_timeout_sec_max=G_MAXUINT;
74 static gint port_local; /* for 'probe' resends */
76 static gboolean write_daemon_running(pid_t pid);
78 pid_t is_daemon_running(void)
81 char buf[LINE_MAX],*got;
87 if (!(f=fopen(NETWORK_PATHNAME_PID,"r")))
89 got=fgets(buf,sizeof(buf),f);
90 fclose(f); /* FIXME: error ignored */
93 write_daemon_running((pid_t)-1); /* unlink */
100 if (kill((pid_t)pid_int,0)) {
105 return (pid_t)pid_int;
108 static gboolean write_daemon_running(pid_t pid)
112 if (pid==(pid_t)-1) {
113 if (unlink(NETWORK_PATHNAME_PID)) {
115 g_warning(_("Error removing PID file \"%s\": %m"),NETWORK_PATHNAME_PID);
120 if (!(f=fopen(NETWORK_PATHNAME_PID,"w"))) {
121 static gboolean once=TRUE;
125 g_warning(_("Error writing PID %d to \"%s\": %m"),(int)pid,NETWORK_PATHNAME_PID);
129 fprintf(f,"%d\n",(int)pid); /* errors ignored */
130 fclose(f); /* FIXME: error ignored */
134 static void client_timeout_remove(struct client *client)
136 g_return_if_fail(client!=NULL);
137 g_return_if_fail(client!=master);
139 if (client->timeout_id) {
140 gboolean errgboolean;
143 g_message(_("Client fd %d removed timeout id %d"),client->gpollfd.fd,client->timeout_id);
144 errgboolean=g_source_remove(client->timeout_id);
145 g_assert(errgboolean==TRUE);
146 client->timeout_id=0;
150 static gboolean client_touch_timeout(struct client *client);
152 static void client_touch(struct client *client,guint timeout_sec)
154 g_return_if_fail(client!=NULL);
155 g_return_if_fail(client!=master);
156 g_return_if_fail(timeout_sec>0);
158 client_timeout_remove(client);
159 client->timeout_id=g_timeout_add(
160 timeout_sec*1000, /* interval; msec */
161 (GSourceFunc)client_touch_timeout, /* function */
164 g_message(_("Client fd %d new timeout id %d"),client->gpollfd.fd,client->timeout_id);
165 g_assert(client->timeout_id!=0);
168 static void client_destroy(struct client *client);
169 static gboolean probe_send(struct client *probe,gint port_local);
171 static gboolean client_touch_timeout(struct client *client)
173 g_return_val_if_fail(client!=NULL,FALSE); /* FALSE=>should be removed */
174 g_return_val_if_fail(client!=master,FALSE); /* FALSE=>should be removed */
177 g_message(_("Client fd %d timeout id %d occured/entered"),client->gpollfd.fd,client->timeout_id);
179 /* Do not destroy the timeout in client_destroy().
180 * It would crash GLib - we remove it be returning FALSE from here.
182 g_assert(client->timeout_id!=0);
183 client->timeout_id=0;
186 if (probe_timeout_sec_now<probe_timeout_sec_max) {
187 probe_timeout_sec_now*=PROBE_TIMEOUT_SEC_BASE;
188 g_assert(probe_timeout_sec_max==G_MAXUINT || probe_timeout_sec_max<PROBE_TIMEOUT_SEC_MAX);
189 probe_timeout_sec_now=MIN(probe_timeout_sec_now,probe_timeout_sec_max);
190 probe_timeout_sec_now=MIN(probe_timeout_sec_now,PROBE_TIMEOUT_SEC_MAX);
191 if (probe_send(probe,port_local)) {
192 client_touch(probe,probe_timeout_sec_now); /* timeout */
193 return FALSE; /* GSource should be removed */
195 /* failure FALLTHRU */
198 /* Never destroy 'client' now - it has been destroyed by network_stop()! */
199 g_warning(_("No probe response from the server, stopping the daemon. Please check your public Internet connectivity."));
202 client_destroy(client);
206 g_message(_("Client timeout occurance finish"));
208 return FALSE; /* GSource should be removed */
211 static void handle_master_probe(const void *packet,size_t gotlen,const struct sockaddr_in *sockaddr_in_from)
213 GHashTable *got_hash;
214 gpointer got_unique_gpointer;
215 gpointer hostip_gpointer;
216 guint32 hostip_guint32;
218 g_return_if_fail(packet!=NULL);
219 g_return_if_fail(sockaddr_in_from!=NULL);
224 if (!(got_hash=packet_disassembly(packet,gotlen)))
226 if (!(g_hash_table_lookup_extended(
227 got_hash, /* hash_table */
228 GUINT_TO_POINTER(PACKET_ELEM_TYPE_DATA_GUINT32), /* lookup_key */
230 &got_unique_gpointer))) {
231 err_packet_disassembly_destroy_got_hash:
232 packet_disassembly_destroy(got_hash);
235 if (GPOINTER_TO_UINT(got_unique_gpointer)!=probe_unique)
236 goto err_packet_disassembly_destroy_got_hash;
237 if (!(g_hash_table_lookup_extended(
238 got_hash, /* hash_table */
239 GUINT_TO_POINTER(PACKET_ELEM_TYPE_CLIENT_INADDR), /* lookup_key */
242 goto err_packet_disassembly_destroy_got_hash;
243 hostip_guint32=GPOINTER_TO_UINT(hostip_gpointer);
244 packet_disassembly_destroy(got_hash);
246 client_destroy(probe);
247 if (network_notify_hostip)
248 (*network_notify_hostip)(hostip_guint32);
251 static struct client *client_new(void);
253 static void handle_master(struct client *master)
255 g_return_if_fail(master!=NULL);
258 char packet[0x10000];
260 struct sockaddr_in sockaddr_in_from;
261 struct client *client=NULL /* Prevent false positive: might be used uninitialized */;
262 struct sockaddr_in sockaddr_in_server;
263 socklen_t sockaddr_in_from_length;
266 sockaddr_in_from_length=sizeof(sockaddr_in_from);
267 if (-1==(gotlen=recvfrom(
268 master->gpollfd.fd, /* s */
270 sizeof(packet), /* len */
272 (struct sockaddr *)&sockaddr_in_from, /* from */
273 &sockaddr_in_from_length))) /* fromlen */
276 if (sockaddr_in_from_length!=sizeof(sockaddr_in_from)) /* FIXME: errors reporting */
279 if (packet_recognized(packet,gotlen)) {
280 handle_master_probe(packet,gotlen,&sockaddr_in_from);
283 /* Not yet initialized by 'probe' reply - drop it. */
286 g_message(_("Data packet received from %s but no probe reply yet; dropping packet."),
287 SOCKADDR_IN_TO_STRING(&sockaddr_in_from));
291 /* FIXME: Performance: Ugly search... */
292 for (clientl=sock_client_list;clientl;clientl=clientl->next) {
293 client=clientl->data;
297 && client->sockaddr_in_from.sin_family ==sockaddr_in_from.sin_family
298 && client->sockaddr_in_from.sin_port ==sockaddr_in_from.sin_port
299 && client->sockaddr_in_from.sin_addr.s_addr==sockaddr_in_from.sin_addr.s_addr)
304 client->sockaddr_in_from=sockaddr_in_from;
306 client_touch(client,CLIENT_TIMEOUT_SEC);
307 UDPGATE_MEMZERO(&sockaddr_in_server);
308 sockaddr_in_server.sin_family=AF_INET;
309 sockaddr_in_server.sin_port=htons(SERVER_PORT);
310 sockaddr_in_server.sin_addr.s_addr=htonl(SERVER_INADDR);
311 /* FIXME: errors checking */
313 client->gpollfd.fd, /* s */
317 (struct sockaddr *)&sockaddr_in_server, /* to */
318 sizeof(sockaddr_in_server)); /* tolen */
322 static void handle_probe(struct client *probe)
324 g_return_if_fail(probe!=NULL);
328 struct sockaddr_in sockaddr_in_from;
329 char packet[0x10000];
330 socklen_t sockaddr_in_from_length;
332 sockaddr_in_from_length=sizeof(sockaddr_in_from);
333 if (-1==(gotlen=recvfrom(
334 master->gpollfd.fd, /* s */
336 sizeof(packet), /* len */
338 (struct sockaddr *)&sockaddr_in_from, /* from */
339 &sockaddr_in_from_length))) /* fromlen */
341 if (sockaddr_in_from_length!=sizeof(sockaddr_in_from)) /* FIXME: errors reporting */
344 /* Probe socket should have no response; maybe some ICMP errors - ignored. */
348 static void handle_client(struct client *client)
350 g_return_if_fail(client!=NULL);
351 g_return_if_fail(master!=NULL);
355 struct sockaddr_in sockaddr_in_from;
356 char packet [0x10000];
357 socklen_t sockaddr_in_from_length;
359 sockaddr_in_from_length=sizeof(sockaddr_in_from);
360 if (-1==(gotlen=recvfrom(
361 client->gpollfd.fd, /* s */
363 sizeof(packet), /* len */
365 (struct sockaddr *)&sockaddr_in_from, /* from */
366 &sockaddr_in_from_length))) /* fromlen */
368 if (sockaddr_in_from_length!=sizeof(sockaddr_in_from)) /* FIXME: errors reporting */
370 client_touch(client,CLIENT_TIMEOUT_SEC);
371 /* FIXME: errors checking */
373 master->gpollfd.fd, /* s */
377 (struct sockaddr *)&client->sockaddr_in_from, /* to */
378 sizeof(client->sockaddr_in_from)); /* tolen */
382 static gboolean sock_source_callback(gpointer data /* unused */)
386 for (clientl=sock_client_list;clientl;clientl=clientl->next) {
387 struct client *client=clientl->data;
389 if (client->gpollfd.revents&SOCK_SOURCE_CHECK_REVENTS) {
390 /**/ if (client==master)
391 handle_master(client);
392 else if (client==probe)
393 handle_probe(client);
395 handle_client(client);
399 return TRUE; /* the source should be kept active */
402 static gboolean sock_source_prepare(GSource *source,gint *timeout)
409 static gboolean sock_source_check(GSource *source)
413 for (clientl=sock_client_list;clientl;clientl=clientl->next) {
414 struct client *client=clientl->data;
416 if (client->gpollfd.revents&SOCK_SOURCE_CHECK_REVENTS)
422 static gboolean sock_source_dispatch(GSource *source,GSourceFunc callback,gpointer user_data)
424 g_assert(callback!=NULL);
425 return (*callback)(user_data);
428 static GSourceFuncs sock_source_watch_funcs={
431 sock_source_dispatch,
435 static void sock_gsource_destroy(void)
437 while (sock_client_list)
438 client_destroy(sock_client_list->data);
440 g_assert(master==NULL);
441 g_assert(probe==NULL);
444 g_source_destroy(sock_gsource);
448 write_daemon_running((pid_t)-1); /* unlink; errors ignored */
451 static gboolean sock_gsource_new(void)
456 g_assert(sock_client_list==NULL);
458 /* attach sock_source_callback() to watch for any abnormalities
459 * on our open pipe 'parentheart_fds' and terminate the child if parent dies.
461 if (!(sock_gsource=g_source_new(&sock_source_watch_funcs,sizeof(GSource)))) {
462 g_warning("g_source_new(): %m");
465 g_source_set_callback(
466 sock_gsource, /* source */
467 sock_source_callback, /* func */
470 if (!g_source_attach( /* returns 'guint' id */
471 sock_gsource, /* source */
472 NULL)) { /* context; NULL means 'default context' */
473 g_warning("g_source_attach(gsource,NULL): %m");
474 sock_gsource_destroy();
480 static struct client *client_new(void)
482 struct client *client;
483 static unsigned long oneul=1;
486 if (!sock_gsource_new())
489 if (-1==(sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))) {
490 g_warning("socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP): %m");
493 if (ioctl(sock,FIONBIO,&oneul)) { /* non-blocking mode */
494 g_warning("ioctl(sock,FIONBIO,&1): %m");
495 close(sock); /* errors ignored */
500 client->gpollfd.fd=sock;
501 client->gpollfd.events=SOCK_SOURCE_CHECK_EVENTS;
502 client->gpollfd.revents=0;
503 client->timeout_id=0;
504 sock_client_list=g_list_prepend(sock_client_list,client);
505 g_source_add_poll(sock_gsource,&client->gpollfd);
508 g_message(_("Client fd %d created"),client->gpollfd.fd);
513 static void client_destroy(struct client *client)
515 g_return_if_fail(client!=NULL);
517 if (!sock_gsource_new())
521 g_message(_("Client fd %d timeout id %d destroy enter"),client->gpollfd.fd,client->timeout_id);
523 if (client==master) {
525 g_assert(client->timeout_id==0);
530 client_timeout_remove(client);
533 g_source_remove_poll(sock_gsource,&client->gpollfd);
534 sock_client_list=g_list_remove(sock_client_list,client);
535 close(client->gpollfd.fd); /* errors ignored */
538 g_message(_("Client fd %d timeout id %d destroy finish"),client->gpollfd.fd,client->timeout_id);
543 static gboolean probe_send(struct client *probe,gint port_local)
545 struct sockaddr_in sockaddr_in_server;
546 GHashTable *probe_hash;
548 size_t packet_length;
550 g_return_val_if_fail(probe!=NULL,FALSE);
552 probe_unique=g_random_int();
554 probe_hash=g_hash_table_new(
555 g_direct_hash, /* hash_func */
556 g_direct_equal); /* key_equal_func */
557 g_hash_table_insert(probe_hash,GUINT_TO_POINTER(PACKET_ELEM_TYPE_CLIENT_PORT) ,GUINT_TO_POINTER(port_local));
558 g_hash_table_insert(probe_hash,GUINT_TO_POINTER(PACKET_ELEM_TYPE_DATA_GUINT32),GUINT_TO_POINTER(probe_unique));
559 packet=packet_assembly(&packet_length,probe_hash);
560 g_hash_table_destroy(probe_hash);
564 UDPGATE_MEMZERO(&sockaddr_in_server);
565 sockaddr_in_server.sin_family=AF_INET;
566 sockaddr_in_server.sin_port=htons(PROBE_PORT);
567 sockaddr_in_server.sin_addr.s_addr=htonl(PROBE_INADDR);
568 /* FIXME: errors checking */
570 probe->gpollfd.fd, /* s */
572 packet_length, /* len */
574 (struct sockaddr *)&sockaddr_in_server, /* to */
575 sizeof(sockaddr_in_server)); /* tolen */
580 static gboolean master_start(gint port)
582 struct sockaddr_in sockaddr_in;
584 g_return_val_if_fail(port>=0,FALSE);
585 g_return_val_if_fail(master==NULL,FALSE);
587 /* Setup 'master': */
588 if (!(master=client_new()))
590 UDPGATE_MEMZERO(&sockaddr_in);
591 sockaddr_in.sin_family=AF_INET;
592 sockaddr_in.sin_port=htons(port);
593 sockaddr_in.sin_addr.s_addr=htonl(INADDR_ANY);
594 if (bind(master->gpollfd.fd,(struct sockaddr *)&sockaddr_in,sizeof(sockaddr_in))) {
595 g_warning("bind(sock,{AF_INET,INADDR_ANY:%d}): %m",(int)port);
601 static gboolean probe_start(gint port)
603 g_return_val_if_fail(port>=0,FALSE);
604 g_return_val_if_fail(probe==NULL,FALSE);
607 if (!(probe=client_new()))
610 if (!probe_send(probe,port)) {
611 client_destroy(probe);
614 probe_timeout_sec_now=PROBE_TIMEOUT_SEC_BASE;
615 client_touch(probe,probe_timeout_sec_now); /* timeout */
619 gboolean network_start(gint port)
623 g_return_val_if_fail(port>=0,FALSE);
625 if ((pid_t)-1!=(daemon_pid=is_daemon_running())) {
626 g_warning(_("Cannot start network daemon: Daemon is already running on PID %d"),(int)daemon_pid);
629 if (!master_start(port)) {
630 sock_gsource_destroy();
633 if (!probe_start(port)) {
634 sock_gsource_destroy();
637 write_daemon_running(getpid()); /* errors ignored */
638 if (network_notify_hostip)
639 (*network_notify_hostip)(0);
643 gboolean optarg_port_set_string(const gchar *port_string)
648 g_return_val_if_fail(port_string!=NULL,FALSE);
650 port_long=strtol(port_string,&endp,0);
652 g_warning(_("Invalid port specification, offending string: %s"),endp);
655 if (port_long<1 || port_long>=G_MAXINT || (endp && *endp)) {
656 g_warning(_("Invalid port integer number specification (%ld)"),port_long);
659 optarg_port=port_long;
663 gboolean network_stop(void)
668 if ((pid_t)-1==(daemon_pid=is_daemon_running())) {
669 g_warning(_("Cannot stop network daemon: Daemon is not running"));
672 if (daemon_pid==getpid()) {
673 sock_gsource_destroy();
677 kill(daemon_pid,SIGKILL);
679 write_daemon_running((pid_t)-1); /* unlink; errors ignored */
681 g_warning(udpgate_printf_alloca(_("Unable to stop the daemon at PID %d: %s"),
682 (int)daemon_pid,strerror(errno_save)));
686 if (network_notify_hostip)
687 (*network_notify_hostip)(0);
691 static GMainLoop *gmainloop;
692 static void network_detach_network_notify_hostip(guint32 hostip_guint32)
695 g_main_loop_quit(gmainloop);
698 gboolean network_detach(void)
700 pid_t daemon_pid,forked_pid;
702 if ((pid_t)-1==(daemon_pid=is_daemon_running()))
704 if (getpid()!=daemon_pid)
706 if (!optarg_no_fork) {
707 if ((pid_t)-1==(forked_pid=fork())) {
708 g_warning("fork(2): %m");
715 write_daemon_running(getpid()); /* errors ignored */
718 close(STDOUT_FILENO);
719 close(STDERR_FILENO);
724 network_notify_hostip=network_detach_network_notify_hostip;
725 gmainloop=g_main_loop_new(
727 TRUE); /* is_running; ignored */
728 g_main_loop_run(gmainloop); /* loop */
729 /* Unable to contact the server, aborting. */