1 /* cvm/client_xfer_udp.c - CVM client UDP transmission library
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 <sys/types.h>
19 #include <netdb.h>
20 #include <signal.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/wait.h>
24 #include <unistd.h>
25
26 #include <bglibs/sysdeps.h>
27 #include <bglibs/socket.h>
28
29 #include "v1client.h"
30 #include "protocol.h"
31
32 /* UDP module invocation *****************************************************/
udp_sendrecv(int sock,ipv4addr * ip,ipv4port port,const struct cvm_packet * request,struct cvm_packet * response)33 static int udp_sendrecv(int sock, ipv4addr* ip, ipv4port port,
34 const struct cvm_packet* request,
35 struct cvm_packet* response)
36 {
37 int timeout;
38 int try;
39 iopoll_fd ifd;
40
41 ifd.fd = sock;
42 ifd.events = IOPOLL_READ;
43 for (timeout = 2, try = 0; try < 4; timeout *= 2, ++try) {
44 if ((unsigned)socket_send4(sock, (char*)request->data, request->length,
45 ip, port) != request->length)
46 return 0;
47 if (iopoll(&ifd, 1, timeout*1000) != 0)
48 return (response->length = socket_recv4(sock, (char*)response->data,
49 CVM_BUFSIZE, ip,
50 &port)) != (unsigned)-1;
51 }
52 return 0;
53 }
54
cvm_xfer_udp_packets(const char * hostport,const struct cvm_packet * request,struct cvm_packet * response)55 unsigned cvm_xfer_udp_packets(const char* hostport,
56 const struct cvm_packet* request,
57 struct cvm_packet* response)
58 {
59 static char* hostname;
60 char* portstr;
61 ipv4port port;
62 int sock;
63 struct hostent* he;
64 ipv4addr ip;
65
66 if ((portstr = strchr(hostport, ':')) == 0) return CVME_GENERAL;
67 if (hostname) free(hostname);
68 hostname = malloc(portstr-hostport+1);
69 memcpy(hostname, hostport, portstr-hostport);
70 hostname[portstr-hostport] = 0;
71 port = strtoul(portstr+1, &portstr, 10);
72 if (*portstr != 0) return CVME_GENERAL;
73 if ((he = gethostbyname(hostname)) == 0) return CVME_GENERAL;
74 memcpy(&ip, he->h_addr_list[0], 4);
75
76 if ((sock = socket_udp()) == -1) return CVME_IO;
77 if (!udp_sendrecv(sock, &ip, port, request, response)) {
78 close(sock);
79 return CVME_IO;
80 }
81 close(sock);
82 return 0;
83 }
84