1 /* cvm/module_udp.c - UDP CVM server module loop
2 * Copyright (C) 2010 Bruce Guenter <bruce@untroubled.org>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
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 #include <netdb.h>
19 #include <signal.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23
24 #include <bglibs/msg.h>
25 #include <bglibs/socket.h>
26
27 #include "module.h"
28
29 static int sock;
30 static ipv4addr ip;
31 static ipv4port port;
32
read_input(void)33 static int read_input(void)
34 {
35 cvm_module_inbuflen = socket_recv4(sock, (char*)cvm_module_inbuffer, BUFSIZE,
36 &ip, &port);
37 if (cvm_module_inbuflen == (unsigned)-1) return CVME_IO;
38 return 0;
39 }
40
write_output(void)41 static void write_output(void)
42 {
43 socket_send4(sock, (char*)cvm_module_outbuffer, cvm_module_outbuflen,
44 &ip, port);
45 }
46
exitfn()47 static void exitfn()
48 {
49 cvm_module_log_shutdown();
50 exit(0);
51 }
52
53 extern void usage(void);
54
udp_main(const char * hostname,const char * portname)55 int udp_main(const char* hostname, const char* portname)
56 {
57 int code;
58 struct hostent* he;
59 char* tmp;
60
61 signal(SIGINT, exitfn);
62 signal(SIGTERM, exitfn);
63
64 if ((he = gethostbyname(hostname)) == 0) usage();
65 memcpy(&ip, he->h_addr_list[0], 4);
66 if ((port = strtoul(portname, &tmp, 10)) == 0 ||
67 port >= 0xffff || *tmp != 0) usage();
68 if ((sock = socket_udp()) == -1) {
69 error1sys("Could not create socket");
70 return CVME_IO;
71 }
72 if (!socket_bind4(sock, &ip, port)) {
73 error1sys("Could not bind socket");
74 return CVME_IO;
75 }
76 if ((code = cvm_module_init()) != 0)
77 return code;
78 cvm_module_log_startup();
79
80 code = 0;
81 do {
82 if ((code = read_input()) != 0) continue;
83 code = cvm_module_handle_request();
84 cvm_module_fact_end(code & CVME_MASK);
85 cvm_module_log_request();
86 write_output();
87 } while ((code & CVME_FATAL) == 0);
88 cvm_module_stop();
89 return 0;
90 }
91