File: network.c

package info (click to toggle)
mbuffer 20140310-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,084 kB
  • ctags: 838
  • sloc: ansic: 15,070; sh: 2,768; makefile: 173
file content (418 lines) | stat: -rw-r--r-- 12,228 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/*
 *  Copyright (C) 2000-2009, Thomas Maier-Komor
 *
 *  This is the source code of mbuffer.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"

#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#elif defined __GNUC__
#define alloca __builtin_alloca
#elif defined _AIX
#define alloca __alloca
#else
#include <stddef.h>
void *alloca(size_t);
#endif


#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "dest.h"
#include "network.h"
#include "log.h"

extern int In;
int32_t TCPBufSize = 1 << 20;
#if defined(PF_INET6) && defined(PF_UNSPEC)
int AddrFam = PF_UNSPEC;
#else
int AddrFam = PF_INET;
#endif


static void setTCPBufferSize(int sock, unsigned buffer)
{
	int err;
	int32_t osize, size;
	socklen_t bsize = sizeof(osize);

	assert(buffer == SO_RCVBUF || buffer == SO_SNDBUF);
	err = getsockopt(sock,SOL_SOCKET,buffer,&osize,&bsize);
	assert((err == 0) && (bsize == sizeof(osize)));
	if (osize < TCPBufSize) {
		size = TCPBufSize;
		do {
			err = setsockopt(sock,SOL_SOCKET,buffer,(void *)&size,sizeof(size));
			size >>= 1;
		} while ((-1 == err) && (errno == ENOMEM) && (size > osize));
		if (err == -1) {
			warningmsg("unable to set the socket buffer size: %s\n",strerror(errno));
			return;
		}
	}
	bsize = sizeof(size);
	err = getsockopt(sock,SOL_SOCKET,buffer,&size,&bsize);
	assert(err != -1);
	if (buffer == SO_RCVBUF) 
		infomsg("set the TCP receive buffer size to %d\n",size);
	else
		infomsg("set the TCP send buffer size to %d\n",size);
}


#ifdef HAVE_GETADDRINFO

void initNetworkInput(const char *addr)
{
	char *host, *port;
	struct addrinfo hint, *pinfo = 0, *x, *cinfo = 0;
	int err, sock = -1, l;

	debugmsg("initNetworkInput(\"%s\")\n",addr);
	l = strlen(addr) + 1;
	host = alloca(l);
	memcpy(host,addr,l);
	port = strrchr(host,':');
	if (port == 0) {
		port = host;
		host = 0;
	} else if (port == host) {
		port = host + 1;
		host = 0;
	} else {
		*port = 0;
		++port;
		bzero(&hint,sizeof(hint));
		hint.ai_family = AddrFam;
		hint.ai_protocol = IPPROTO_TCP;
		hint.ai_socktype = SOCK_STREAM;
#ifdef __FreeBSD__
		hint.ai_flags = AI_ADDRCONFIG;
#else
		hint.ai_flags = AI_ADDRCONFIG | AI_V4MAPPED;
#endif
		err = getaddrinfo(host,0,&hint,&cinfo);
		if (err != 0) 
			fatal("unable to resolve the address information for the expected host '%s': %s\n",host,gai_strerror(err));
	}
	bzero(&hint,sizeof(hint));
	hint.ai_family = AddrFam;
	hint.ai_protocol = IPPROTO_TCP;
	hint.ai_socktype = SOCK_STREAM;
	hint.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
	err = getaddrinfo(0,port,&hint,&pinfo);
	if (err != 0)
		fatal("unable to get the address information for port/service '%s': %s\n",port,gai_strerror(err));
	assert(pinfo);
	for (x = pinfo; x; x = x->ai_next) {
		int reuse_addr = 1;
		debugmsg("creating the socket for address family %d\n",x->ai_family);
		sock = socket(x->ai_family, SOCK_STREAM, 0);
		if (sock == -1) {
			warningmsg("unable to create the socket for input: %s\n",strerror(errno));
			continue;
		}
		if (-1 == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr)))
			warningmsg("cannot set the socket to reuse address: %s\n",strerror(errno));
		if (0 == bind(sock, x->ai_addr, x->ai_addrlen)) {
			debugmsg("successfully bound the socket - address length %d\n",x->ai_addrlen);
			break;
		}
		warningmsg("could not bind to the socket for network input: %s\n",strerror(errno));
		(void) close(sock);
	}
	if (x == 0)
		fatal("Unable to initialize network input.\n");
	infomsg("listening on the socket...\n");
	if (0 > listen(sock,0))		/* accept only 1 incoming connection */
		fatal("could not listen on the socket for network input: %s\n",strerror(errno));
	for (;;) {
		char chost[NI_MAXHOST], serv[NI_MAXSERV];
		struct sockaddr_in6 caddr;
		struct addrinfo *c;
		socklen_t len = sizeof(caddr);
		int err;

		debugmsg("waiting for an incoming connection\n");
		In = accept(sock, (struct sockaddr *) &caddr, &len);
		if (0 > In)
			fatal("Unable to accept the connection for network input: %s\n",strerror(errno));
		err = getnameinfo((struct sockaddr *) &caddr,len,chost,sizeof(chost),serv,sizeof(serv),NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN);
		if (0 != err) {
			fatal("unable to get the name information for the hostname of the incoming connection: %s\n",gai_strerror(err));
		}
		infomsg("incoming connection from %s:%s\n",chost,serv);
		if (host == 0)
			break;
		for (c = cinfo; c; c = c->ai_next) {
			char xhost[NI_MAXHOST];
			if (0 == getnameinfo((struct sockaddr *)c->ai_addr,c->ai_addrlen,xhost,sizeof(xhost),0,0,NI_NUMERICHOST|NI_NOFQDN)) {
				debugmsg("checking against host '%s'\n",xhost);
				if (0 == strcmp(xhost,chost))
					break;
			}
		}
		if (c)
			break;
		warningmsg("rejected connection from %s\n",chost);
		if (-1 == close(In))
			warningmsg("error closing the rejected input: %s\n",strerror(errno));
	}
	freeaddrinfo(pinfo);
	if (cinfo)
		freeaddrinfo(cinfo);
	debugmsg("input connection accepted\n");
	setTCPBufferSize(In,SO_RCVBUF);
	(void) close(sock);
}


dest_t *createNetworkOutput(const char *addr)
{
	char *host, *port;
	struct addrinfo hint, *ret = 0, *x;
	int err, fd = -1;
	dest_t *d;

	assert(addr);
	host = strdup(addr);
	assert(host);
	port = strrchr(host,':');
	if (port == 0) {
		fatal("syntax error - the target must be given in the form <host>:<port>\n");
	}
	*port++ = 0;
	bzero(&hint,sizeof(hint));
	hint.ai_family = AddrFam;
	hint.ai_protocol = IPPROTO_TCP;
	hint.ai_socktype = SOCK_STREAM;
	hint.ai_flags = AI_ADDRCONFIG;
	debugmsg("getting address info for %s\n",addr);
	err = getaddrinfo(host,port,&hint,&ret);
	if (err != 0)
		fatal("unable to resolve the address information for '%s': %s\n",addr,gai_strerror(err));
	for (x = ret; x; x = x->ai_next) {
		fd = socket(x->ai_family, SOCK_STREAM, 0);
		if (fd == -1) {
			errormsg("unable to create a socket: %s\n",strerror(errno));
			continue;
		}
		if (0 == connect(fd, x->ai_addr, x->ai_addrlen)) {
			debugmsg("successfully connected to %s\n",addr);
			break;
		}
		(void) close(fd);
		fd = -1;
		warningmsg("error connecting to %s: %s\n",addr,strerror(errno));
	}
	if ((x == 0) || (fd == -1))
		errormsg("unable to connect to %s\n",addr);
	freeaddrinfo(ret);
	if (fd != -1)
		setTCPBufferSize(fd,SO_SNDBUF);
	d = (dest_t *) malloc(sizeof(dest_t));
	d->arg = addr;
	d->name = host;
	d->port = port;
	d->fd = fd;
	bzero(&d->thread,sizeof(d->thread));
	d->result = 0;
	d->next = 0;
	return d;
}


#else	/* HAVE_GETADDRINFO */


static void openNetworkInput(const char *host, unsigned short port)
{
	struct sockaddr_in saddr;
	struct hostent *h = 0, *r = 0;
	const int reuse_addr = 1;
	int sock;

	debugmsg("openNetworkInput(\"%s\",%hu)\n",host,port);
	sock = socket(AF_INET, SOCK_STREAM, 6);
	if (0 > sock)
		fatal("could not create a socket for network input: %s\n",strerror(errno));
	if (-1 == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr)))
		warningmsg("cannot set the socket to reuse address: %s\n",strerror(errno));
	setTCPBufferSize(sock,SO_RCVBUF);
	if (host[0]) {
		debugmsg("resolving the hostname '%s' of input...\n",host);
		if (0 == (h = gethostbyname(host)))
#ifdef HAVE_HSTRERROR
			fatal("could not resolve the server hostname: %s\n",hstrerror(h_errno));
#else
			fatal("could not resolve the server hostname: error code %d\n",h_errno);
#endif
	}
	bzero((void *) &saddr, sizeof(saddr));
	saddr.sin_family = AF_INET;
	saddr.sin_addr.s_addr = htonl(INADDR_ANY);
	saddr.sin_port = htons(port);
	debugmsg("binding the socket to port %d...\n",port);
	if (0 > bind(sock, (struct sockaddr *) &saddr, sizeof(saddr)))
		fatal("could not bind to the socket for network input: %s\n",strerror(errno));
	debugmsg("listening on the socket...\n");
	if (0 > listen(sock,1))		/* accept only 1 incoming connection */
		fatal("could not listen on the socket for network input: %s\n",strerror(errno));
	for (;;) {
		struct sockaddr_in caddr;
		socklen_t clen = sizeof(caddr);
		char **p;
		debugmsg("waiting to accept a connection...\n");
		In = accept(sock, (struct sockaddr *)&caddr, &clen);
		if (0 > In)
			fatal("could not accept a connection for network input: %s\n",strerror(errno));
		if (host[0] == 0) {
			infomsg("accepted a connection from %s\n",inet_ntoa(caddr.sin_addr));
			(void) close(sock);
			return;
		}
		for (p = h->h_addr_list; *p; ++p) {
			if (0 == memcmp(&caddr.sin_addr,*p,h->h_length)) {
				infomsg("accepted a connection from %s\n",inet_ntoa(caddr.sin_addr));
				(void) close(sock);
				return;
			}
		}
		r = gethostbyaddr((char *)&caddr.sin_addr,sizeof(caddr.sin_addr.s_addr),AF_INET);
		if (r)
			warningmsg("rejected a connection from %s (%s)\n",r->h_name,inet_ntoa(caddr.sin_addr));
		else
			warningmsg("rejected a connection from %s\n",inet_ntoa(caddr.sin_addr));
		if (-1 == close(In))
			warningmsg("error closing the rejected input: %s\n",strerror(errno));
	}
}


void initNetworkInput(const char *addr)
{
	char *host, *portstr;
	unsigned pnr;
	size_t l;

	debugmsg("initNetworkInput(\"%s\")\n",addr);
	l = strlen(addr) + 1;
	host = alloca(l);
	memcpy(host,addr,l);
	portstr = strrchr(host,':');
	if (portstr == 0) {
		portstr = host;
		host = "";
	} else if (portstr == host) {
		portstr = host + 1;
		host = "";
		*portstr = 0;
	} else {
		*portstr = 0;
		++portstr;
	}
	if (1 != sscanf(portstr,"%u",&pnr))
		fatal("invalid port string '%s' - the port must be given by its number, not service name\n", portstr);
	openNetworkInput(host,pnr);
}


static void openNetworkOutput(dest_t *dest)
{
	struct sockaddr_in saddr;
	struct hostent *h = 0;
	int out;
	unsigned short pnr;

	debugmsg("creating a socket for output to %s:%d...\n",dest->name,dest->port);
	if (1 != sscanf(dest->port,"%hu",&pnr))
		fatal("the port must be given by its number, not service name\n");
	out = socket(PF_INET, SOCK_STREAM, 0);
	if (0 > out) {
		errormsg("could not create a socket for network output: %s\n",strerror(errno));
		return;
	}
	setTCPBufferSize(out,SO_SNDBUF);
	bzero((void *) &saddr, sizeof(saddr));
	saddr.sin_port = htons(pnr);
	infomsg("resolving host %s...\n",dest->name);
	if (0 == (h = gethostbyname(dest->name))) {
#ifdef HAVE_HSTRERROR
		dest->result = hstrerror(h_errno);
		errormsg("could not resolve the hostname %s: %s\n",dest->name,dest->result);
#else
		dest->result = "unable to resolve the hostname";
		errormsg("could not resolve the hostname %s: error code %d\n",dest->name,h_errno);
#endif
		dest->fd = -1;
		(void) close(out);
		return;
	}
	saddr.sin_family = h->h_addrtype;
	assert(h->h_length <= sizeof(saddr.sin_addr));
	(void) memcpy(&saddr.sin_addr,h->h_addr_list[0],h->h_length);
	infomsg("connecting to the server at %s...\n",inet_ntoa(saddr.sin_addr));
	if (0 > connect(out, (struct sockaddr *) &saddr, sizeof(saddr))) {
		dest->result = strerror(errno);
		errormsg("could not connect to %s:%d: %s\n",dest->name,dest->port,dest->result);
		(void) close(out);
		out = -1;
	}
	dest->fd = out;
}


dest_t *createNetworkOutput(const char *addr)
{
	char *host, *portstr;
	dest_t *d = (dest_t *) malloc(sizeof(dest_t));

	debugmsg("createNetworkOutput(\"%s\")\n",addr);
	host = strdup(addr);
	portstr = strrchr(host,':');
	if ((portstr == 0) || (portstr == host))
		fatal("argument '%s' doesn't match <host>:<port> format\n",addr);
	*portstr++ = 0;
	bzero(d, sizeof(dest_t));
	d->fd = -1;
	d->arg = addr;
	d->name = host;
	d->port = portstr;
	openNetworkOutput(d);
	return d;
}


#endif /* HAVE_GETADDRINFO */


/* vim:tw=0
 */