summaryrefslogtreecommitdiff
path: root/tests/network/test2.c
blob: 5192bb2eabcc686ae57a37ee2ac816dfcefe559f (plain)
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/* Unix traditional and most portable way of a TCP/IP server using select().
 *
 * Also tests asynchrononous accept (to avoid DoSAs on blocking accepts).
 */

#include "port/netdb.h"			/* for getaddrinfo, getnameinfo */
#include "network/network.h"		/* for networking stuff */
#include "port/stdlib.h"		/* for EXIT_XXX */
#include "port/stdio.h"			/* for fprintf */
#include "port/string.h"		/* for memset */
#include "port/stdbool.h"		/* for bool, true, false */
#include "port/unused.h"		/* for WOLF_UNUSED */

#include <unistd.h>			/* for close */
#include <errno.h>			/* for errno */
#include <fcntl.h>			/* for fcntl */
#include <sys/select.h>			/* for select */
#include <assert.h>			/* for assertions */
#include <signal.h>			/* for signal */

#define DEBUG 0

#define ACCEPT_TIMEOUT 5

static bool wolf_network_sock_nonblocking( int fd ) {
	int flags;

	flags = fcntl( fd, F_GETFL, 0 /* ignored */ );
	if( flags < 0 ) return false;
	flags |= O_NONBLOCK;
	flags = fcntl( fd, F_SETFL, flags );
	if( flags < 0 ) return false;
	return true;
}

int main( int argc, char* argv[] ) {
	int error;
	int serv_fd;
	int res;
	char *host;
	char *service;
	struct addrinfo hints;
	struct addrinfo *result;
	wolf_network_sockaddr_union_t client_addr;
	socklen_t client_addr_len;
	fd_set read_set;
	struct timeval timeout;
	char client_hostname[NI_MAXHOST] = "";
	char client_service[NI_MAXSERV] = "";
	int on;
	int client_fd;

	if( argc != 3 ) {
		fprintf( stderr, "usage: test2 <host> <port>\n" );
		goto FAIL;
	}

	host = argv[1];
	service = argv[2];

#ifdef _WIN32
	WSADATA wsa_data;
	WSAStartup( MAKEWORD( 2, 2 ), &wsa_data );
#endif

	/* tell getaddrinfo what we want */
	memset( &hints, 0, sizeof( struct addrinfo ) );
	hints.ai_flags = AI_PASSIVE;
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
 
	/* resolve the domain name into a list of addresses */
	error = getaddrinfo( host, service, &hints, &result );
	if( error != 0 ) {
		fprintf( stderr, "getaddrinfo failed: %s (%d)\n",
			gai_strerror( error ), error );
		goto FAIL;
	}

	/* open the server endpoint */
	serv_fd = socket( result->ai_family, result->ai_socktype, result->ai_protocol );
	if( serv_fd < 0 ) {
		fprintf( stderr, "socket failed: %s (%d)\n", strerror( errno ), errno );
		goto FAIL;
	}

	/* setsockopt SO_REUSEADDR, this is handy while testing or deployment, in
	 * production in can lead to a certain type of rerouting packets to wrong
	 * servers
	 */
	on = 1;
	res = setsockopt( serv_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof( on ) );
	if( res < 0 ) {
		(void)close( serv_fd );
		fprintf( stderr, "setsockopt(SO_REUSEADDR) failed: %s (%d)\n", strerror( errno ), errno );
		goto FAIL;
	}

	/* bind server socket */
	res = bind( serv_fd, result->ai_addr, result->ai_addrlen );
	if( res < 0 ) {
		(void)close( serv_fd );
		fprintf( stderr, "bind failed: %s (%d)\n", strerror( errno ), errno );
		goto FAIL;
	}

	/* listen to the socket */
	res = listen( serv_fd, 10 );
	if( res < 0 ) {
		(void)close( serv_fd );
		fprintf( stderr, "listen failed: %s (%d)\n", strerror( errno ), errno );
		goto FAIL;
	}

	/* set socket non-blocking for accepts (Stevens 15.6) */
	if( !wolf_network_sock_nonblocking( serv_fd ) ) {
		(void)close( serv_fd );
		fprintf( stderr, "set nonblocking failed for server socket: %s (%d)\n", strerror( errno ), errno );
		goto FAIL;
	}

	/* accept the connection in the kernel, select ready for ready tells us there
	 * is a connection ready. Then we have to call accept again and check the result
	 */
FIRST_ACCEPT_AGAIN:
	client_addr_len = sizeof( client_addr );
	client_fd = accept( serv_fd, &client_addr.addr, &client_addr_len );
	if( client_fd < 0 ) {
		if( errno  == EAGAIN || errno == EWOULDBLOCK ) {
			/* as expected, skip */
		} else {
			(void)close( serv_fd );
			fprintf( stderr, "first non-blocking accept failed: %s (%d)\n", strerror( errno ), errno );
			goto FAIL;
		}
	}

	/* go into a select and wait till we are ready for read (this indicates a
	 * possibly new connection)
	 */
ACCEPT_SELECT_AGAIN:
	FD_ZERO( &read_set );
	FD_SET( serv_fd, &read_set );
	timeout.tv_sec = ACCEPT_TIMEOUT;
	timeout.tv_usec = 0;

	res = select( serv_fd + 1, &read_set, NULL, NULL, &timeout );
	if( res < 0 ) {
		if( errno == EINTR || errno == EAGAIN ) {
			goto ACCEPT_SELECT_AGAIN;
		} else {
			/* fatal errors */
			fprintf( stderr, "accept/select failed: %s (%d)\n",
				strerror( errno ), errno );
			(void)close( serv_fd );
			goto FAIL;
		}
	} else if( res == 0 ) {
		/* accept timeout, here we could to periodic stuff, also if we
		 * get blocked somewhere above we could recover..
		 */
		fprintf( stderr, "Idle. No new connections..\n" );
		goto ACCEPT_SELECT_AGAIN;
	} else {
		if( FD_ISSET( serv_fd, &read_set ) ) {
			/* this is a new connection */
		} else {
			/* can't happen! */
			assert( false );
		}
	}

	/* second accept, now we have to check for possible "short-and-run-away"
	 * connects.
	 */
ACCEPT_AGAIN:
	client_addr_len = sizeof( client_addr );
	client_fd = accept( serv_fd, &client_addr.addr, &client_addr_len );
	if( client_fd < 0 ) {
		if( errno == EINTR ) {
			/* interrupted, again */
			goto ACCEPT_AGAIN;
		} else if( errno == ECONNABORTED ) {
			/* connection run away */
			goto FIRST_ACCEPT_AGAIN;
		} else {
			(void)close( serv_fd );
			fprintf( stderr, "second non-blocking accept failed: %s (%d)\n", strerror( errno ), errno );
			goto FAIL;
		}
	}

	/* determine where the request came from */
	res = getnameinfo( &client_addr.addr, client_addr_len,
		client_hostname, NI_MAXHOST,
		client_service, NI_MAXSERV,
		 NI_NUMERICSERV | NI_NUMERICHOST );
	if( res < 0 ) {
		(void)close( serv_fd );
		fprintf( stderr, "getnameinfo failed: %s (%d)\n",
			gai_strerror( error ), error );
		goto FAIL;
	}

	fprintf( stderr, "New connection from %s, port %s\n", client_hostname, client_service );

	(void)close( client_fd );

	goto FIRST_ACCEPT_AGAIN;

FAIL:
	freeaddrinfo( result );

#ifdef _WIN32
	WSACleanup( );
#endif

	return EXIT_FAILURE;

//OK:
	freeaddrinfo( result );

#ifdef _WIN32
	WSACleanup( );
#endif

	return EXIT_SUCCESS;
}

#if 0

#if DEBUG
static char *fd_set_to_string( fd_set *fd, int min_fd, int max_fd, char *buf, size_t buflen ) {
	int i;
	size_t j;

	assert( min_fd <= max_fd );

	for( i = min_fd, j = 0; i <= max_fd && j < buflen; i++, j++ ) {
		if( FD_ISSET( i, fd ) ) {
                                buf[j] = '1';
		} else {
			buf[j] = '0';
		}
	}

	buf[j] = '\0';

	return buf;
}
#endif

#define MAX_IDLE_TIMEOUT 10
#define WRITE_BUFFER_SIZE 4096
#define READ_BUFFER_SIZE 4096
#define CONNECT_TIMEOUT 2

#define max(a,b) ((a) < (b) ? (b) : (a))

static volatile bool terminate = false;

static void term_handler( int sig ) {
	WOLF_UNUSED( sig );
	terminate = true;
}

 
int main( int argc, char *argv[] ) {
	int res;
	int idle_secs;
	char read_buffer[READ_BUFFER_SIZE];
	char write_buffer[WRITE_BUFFER_SIZE];
	size_t stdout_to_write;
	size_t stdout_written;
	size_t fd_to_write;
	size_t fd_written;
	size_t total_stdin_read;
	size_t total_fd_read;
	size_t total_fd_written;
	size_t total_stdout_written;
	int count;
	bool stdin_eof;
	bool fd_write_closed;
	bool fd_eof;

CONNECT_SELECT_AGAIN:
			sock_error_len = sizeof( int );
			res = getsockopt( fd, SOL_SOCKET, SO_ERROR, &sock_error, &sock_error_len );
			if( res < 0 ) {
				fprintf( stderr, "getsockopt for connection check failed: %s (%d)\n",
					strerror( errno ), errno );
				(void)close( fd );
				goto FAIL;
			} else {
				if( error == 0 ) {
					goto CONNECTED;
				} else {
					fprintf( stderr, "SO_ERROR is not ok: %s (%d)\n",
						strerror( error ), error );
					(void)close( fd );
					goto FAIL;
				}
			}
		} else {
			fprintf( stderr, "Socket not ready after select\n" );
			(void)close( fd );
			goto FAIL;
		}
	}

CONNECTED:

	idle_secs = 0;
	count = 0;
	stdout_to_write = 0;
	stdout_written = 0;
	fd_to_write = 0;
	fd_written = 0;
	total_stdin_read = 0;
	total_fd_read = 0;
	total_fd_written = 0;
	total_stdout_written = 0;
	stdin_eof = false;
	fd_write_closed = false;
	fd_eof = false;

	signal( SIGTERM, term_handler );
	signal( SIGINT, term_handler );
	signal( SIGPIPE, SIG_IGN );

	do {
		ssize_t rres;
#if DEBUG
		char buf[10];
		char buf2[10];
#endif

		FD_ZERO( &read_set );
		FD_ZERO( &write_set );
		timeout.tv_sec = 1;
		timeout.tv_usec = 0;

		/* set up select mask and compute highest file descriptor number */
		max_fd = 0;
		max_fd = max( max_fd, STDIN_FILENO );
		max_fd = max( max_fd, STDOUT_FILENO );
		max_fd = max( max_fd, fd );

		if( !stdin_eof && fd_to_write == 0 ) {
			FD_SET( STDIN_FILENO, &read_set );
		}
		if( stdout_to_write > 0 ) {
			FD_SET( STDOUT_FILENO, &write_set );
		}
		if( stdout_to_write == 0 ) {
			FD_SET( fd, &read_set );
		}
		if( fd_to_write > 0 ) {
			FD_SET( fd, &write_set );
		}

		/* wait for events or timeout */
#if DEBUG
fprintf( stderr, "select call read_fd: %s write_fd: %s wbuf: %d rbuf: %d stdin_eof: %d fdwcl: %d\n",
	fd_set_to_string( &read_set, 0, max_fd, buf, 10 ),
	fd_set_to_string( &write_set, 0, max_fd, buf2, 10 ),
	fd_to_write, stdout_to_write, stdin_eof, fd_write_closed );
#endif

		res = select( max_fd + 1, &read_set, &write_set, NULL, &timeout );

#if DEBUG
fprintf( stderr, "select %04d read_fd: %s write_fd: %s wbuf: %d rbuf: %d stdin_eof: %d fdwcl: %d\n",
	res, fd_set_to_string( &read_set, 0, max_fd, buf, 10 ),
	fd_set_to_string( &write_set, 0, max_fd, buf2, 10 ),
	fd_to_write, stdout_to_write, stdin_eof, fd_write_closed );
#endif

		if( res < 0 ) {
			if( errno == EINTR || errno == EAGAIN ) {
				/* skip */
			} else {
				/* fatal errors */
				fprintf( stderr, "select failed: %s (%d)\n",
					strerror( errno ), errno );
				(void)close( fd );
				goto FAIL;
			}
		} else if( res == 0 ) {
			/* timeout */
			idle_secs++;
			if( idle_secs > MAX_IDLE_TIMEOUT ) {
				fprintf( stderr, "Idle connection after %d seconds..terminating\n",
					idle_secs );
				goto END;
			}
		} else {
			/* something happened */
			idle_secs = 0;

			/* empty the socket read buffer to stdout */
			if( FD_ISSET( STDOUT_FILENO, &write_set ) ) {
				assert( stdout_to_write > 0 );
				rres = write( STDOUT_FILENO, read_buffer + stdout_written, stdout_to_write );
				if( rres < 0 ) {
					if( errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR ) {
						/* skip */
					} else {
						fprintf( stderr, "write to stdout failed: %s (%d)\n",
							strerror( errno ), errno );
						(void)close( fd );
						goto FAIL;
					}
				} else {
					assert( rres >= 0 );
					stdout_written += (size_t)rres;
					assert( stdout_to_write >= (size_t)rres );
					stdout_to_write -= (size_t)rres;
					total_stdout_written += (size_t)rres;
				}
			}

			/* empty the socket write buffer writing to fd */
			if( FD_ISSET( fd, &write_set ) ) {
				assert( fd_to_write > 0 );
				rres = write( fd, write_buffer + fd_written, fd_to_write );
				if( rres < 0 ) {
					if( errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR ) {
						/* skip */
					} else {
						fprintf( stderr, "write to socket failed: %s (%d)\n",
							strerror( errno ), errno );
						(void)close( fd );
						goto FAIL;
					}
				} else {
					assert( rres >= 0 );
					fd_written += (size_t)rres;
					assert( fd_to_write >= (size_t)rres );
					fd_to_write -= (size_t)rres;
					total_fd_written += (size_t)rres;
				}
			}

			/* read from socket, fill socket read buffer */
			if( FD_ISSET( fd, &read_set ) ) {
				assert( stdout_to_write == 0 );
				rres = read( fd, read_buffer, READ_BUFFER_SIZE );
				if( rres < 0 ) {
					if( errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR ) {
						/* skip */
					} else {
						fprintf( stderr, "read from socket failed: %s (%d)\n",
							strerror( errno ), errno );
						(void)close( fd );
						goto FAIL;
					}
				} else if( rres == 0 ) {
					/* EOF on socket */
					shutdown( fd, SHUT_RD );
					fd_eof = true;
#if DEBUG
					fprintf( stderr, "EOF on socket\n" );
#endif
				} else {
					assert( rres > 0 );
					stdout_written = 0;
					stdout_to_write = (size_t)rres;
					total_fd_read += (size_t)rres;
				}
			}

			/* read from stdin, fill socket write buffer */
			if( FD_ISSET( STDIN_FILENO, &read_set ) ) {
				assert( fd_to_write == 0 );
				rres = read( STDIN_FILENO, write_buffer, WRITE_BUFFER_SIZE );
				if( rres < 0 ) {
					if( errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR ) {
						/* skip */
					} else {
						fprintf( stderr, "read from stdin failed: %s (%d)\n",
							strerror( errno ), errno );
						(void)close( fd );
						goto FAIL;
					}
				} else if( rres == 0 ) {
					/* EOF on STDIN */
					stdin_eof = true;
					fclose( stdin );

#if DEBUG
					fprintf( stderr, "EOF on stdin\n" );
#endif
				} else {
					assert( rres > 0 );
					fd_written = 0;
					fd_to_write = (size_t)rres;
					total_stdin_read += (size_t)rres;
				}
			}

			/* close writing side of the socket if we have emptied
			 * the socket write buffer and there is nothing more on
			 * the input (stdin)
			 */
			if( fd_to_write == 0 && stdin_eof && !fd_write_closed ) {
#if DEBUG
				fprintf( stderr, "socket SHUT_WR\n" );
#endif
				shutdown( fd, SHUT_WR );
				fd_write_closed = true;
			}
		}

		count++;
		if( count % 10000 == 0 ) {
			fprintf( stderr, "Transfered nof_selects: %d, stdin: %zd, stdout: %zd, fd-in: %zd, fd-out: %zd\n",
				count, total_stdin_read, total_stdout_written, total_fd_read, total_fd_written );
		}
	} while( !terminate && !( stdin_eof && fd_eof ) );

END:
	fprintf( stderr, "Terminated stdin: %zd, stdout: %zd, fd-in: %zd, fd-out: %zd\n",
		total_stdin_read, total_stdout_written, total_fd_read, total_fd_written );

	res = close( fd );
	if( res < 0 ) {
		fprintf( stderr, "close failed: %s (%d)\n", strerror( errno ), errno );
		goto FAIL;
	}
 
	freeaddrinfo( result );

	goto OK;


}
#endif