-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpProxy.c
executable file
·539 lines (455 loc) · 18.8 KB
/
tcpProxy.c
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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h>
#include "logger.h"
#include "tcpServerUtil.h"
#include "buffer.h"
#include "addressUtility.h"
#define max(n1,n2) ((n1)>(n2) ? (n1) : (n2))
#define TRUE 1
#define FALSE 0
#define PORT 8888
#define MAX_SOCKETS 30
#define BUFFSIZE 20
#define PORT_UDP 8888
#define MAX_PENDING_CONNECTIONS 3 // un valor bajo, para realizar pruebas
#define MAX_ADDR_BUFFER 128
#define N(x) (sizeof(x)/sizeof((x)[0]))
// typedef struct buffer buffer;
// struct buffer {
// char * buffer;
// size_t len; // longitud del buffer
// size_t from; // desde donde falta escribir
// };
/**
Se encarga de escribir la respuesta faltante en forma no bloqueante
*/
void handleWrite(int socket, struct buffer * buffer, fd_set * writefds);
/**
Limpia el buffer de escritura asociado a un socket
*/
void clear( struct buffer * buffer);
/**
Crea y "bindea" el socket server UDP
*/
int udpSocket(int port);
/**
Lee el datagrama del socket, obtiene info asociado con getaddrInfo y envia la respuesta
*/
void handleAddrInfo(int socket);
int main(int argc , char *argv[])
{
int opt = TRUE;
int master_socket[2]; // IPv4 e IPv6 (si estan habilitados)
int master_socket_size=0;
int addrlen , new_socket , client_socket[MAX_SOCKETS], server_socket[MAX_SOCKETS] , max_clients = MAX_SOCKETS , activity, i , sd, servSd;
long valread;
int max_sd;
struct sockaddr_in address;
struct sockaddr_storage clntAddr; // Client address
socklen_t clntAddrLen = sizeof(clntAddr);
unsigned char buffer[BUFFSIZE + 1]; //data buffer of 1K
//set of socket descriptors
fd_set readfds;
// Agregamos un buffer de escritura asociado a cada socket, para no bloquear por escritura
struct buffer bufferWrite[MAX_SOCKETS];
struct buffer serverBufferWrite[MAX_SOCKETS];
memset(bufferWrite, 0, sizeof bufferWrite);
memset(serverBufferWrite,0,sizeof serverBufferWrite);
// y tambien los flags para writes
fd_set writefds;
//initialise all client_socket[] to 0 so not checked
memset(client_socket, 0, sizeof(client_socket));
//initialise all server_socket[] to 0 so not checked
memset(server_socket, 0, sizeof(server_socket));
// TODO adaptar setupTCPServerSocket para que cree socket para IPv4 e IPv6 y ademas soporte opciones
// socket para IPv4 y para IPv6 (si estan disponibles)
///////////////////////////////////////////////////////////// IPv4
if( (master_socket[master_socket_size] = socket(AF_INET , SOCK_STREAM , 0)) == 0)
{
log(ERROR, "socket IPv4 failed");
} else {
//set master socket to allow multiple connections , this is just a good habit, it will work without this
if( setsockopt(master_socket[master_socket_size], SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 )
{
log(ERROR, "set IPv4 socket options failed");
}
//type of socket created
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// bind the socket to localhost port 8888
if (bind(master_socket[master_socket_size], (struct sockaddr *)&address, sizeof(address))<0)
{
log(ERROR, "bind for IPv4 failed");
close(master_socket[master_socket_size]);
}
else {
if (listen(master_socket[0], MAX_PENDING_CONNECTIONS) < 0)
{
log(ERROR, "listen on IPv4 socket failes");
close(master_socket[master_socket_size]);
} else {
log(DEBUG, "Waiting for TCP IPv4 connections on socket %d\n", master_socket[master_socket_size]);
master_socket_size++;
}
}
}
///////////////////////////////////////////////////////////// IPv6
struct sockaddr_in6 server6addr;
if ((master_socket[master_socket_size] = socket(AF_INET6, SOCK_STREAM, 0)) < 0)
{
log(ERROR, "socket IPv6 failed");
} else {
if (setsockopt(master_socket[master_socket_size], SOL_SOCKET, SO_REUSEADDR, (char *)&opt,sizeof(opt)) < 0)
{
log(ERROR, "set IPv6 socket options failed");
}
memset(&server6addr, 0, sizeof(server6addr));
server6addr.sin6_family = AF_INET6;
server6addr.sin6_port = htons(PORT);
server6addr.sin6_addr = in6addr_any;
if (bind(master_socket[master_socket_size], (struct sockaddr *)&server6addr,sizeof(server6addr)) < 0)
{
log(ERROR, "bind for IPv6 failed");
close(master_socket[master_socket_size]);
} else {
if (listen(master_socket[master_socket_size], MAX_PENDING_CONNECTIONS) < 0)
{
log(ERROR, "listen on IPv6 failed");
close(master_socket[master_socket_size]);
} else {
log(DEBUG, "Waiting for TCP IPv6 connections on socket %d\n", master_socket[master_socket_size]);
master_socket_size++;
}
}
}
///////////////////////////////////////////////////////////// Socket UDP para responder en base a addrInfo
int udpSock = udpSocket(PORT);
if ( udpSock < 0) {
log(FATAL, "UDP socket failed");
// exit(EXIT_FAILURE);
} else {
log(DEBUG, "Waiting for UDP IPv4 on socket %d\n", udpSock);
}
// Limpiamos el conjunto de escritura
FD_ZERO(&writefds);
while(TRUE)
{
//clear the socket set
FD_ZERO(&readfds);
//add masters sockets to set
for (int sdMaster=0; sdMaster < master_socket_size; sdMaster++)
FD_SET(master_socket[sdMaster], &readfds);
FD_SET(udpSock, &readfds);
max_sd = udpSock;
// add child sockets to set
for ( i = 0 ; i < max_clients ; i++)
{
// socket descriptor
sd = client_socket[i];
servSd = server_socket[i];
// if valid socket descriptor then add to read list
if(sd > 0)
FD_SET( sd , &readfds);
if(servSd > 0)
FD_SET(servSd,&readfds);
// highest file descriptor number, need it for the select function
max_sd = max(max_sd,max(sd,servSd));
}
//wait for an activity on one of the sockets , timeout is NULL , so wait indefinitely
activity = select( max_sd + 1 , &readfds , &writefds , NULL , NULL);
log(DEBUG, "select has something...");
if ((activity < 0) && (errno!=EINTR))
{
log(ERROR, "select error, errno=%d",errno);
continue;
}
// Servicio UDP
if(FD_ISSET(udpSock, &readfds)) {
handleAddrInfo(udpSock);
}
//If something happened on the TCP master socket , then its an incoming connection
for (int sdMaster=0; sdMaster < master_socket_size; sdMaster++) {
int mSock = master_socket[sdMaster];
if (FD_ISSET(mSock, &readfds))
{
if ((new_socket = acceptTCPConnection(mSock)) < 0)
{
log(ERROR, "Accept error on master socket %d", mSock);
continue;
}
// add new socket to array of sockets
for (i = 0; i < max_clients; i++)
{
// if position is empty
if( client_socket[i] == 0 /*&& server_socket[i] == 0*/)
{
client_socket[i] = new_socket;
log(DEBUG, "Adding to list of client sockets as %d - socket %d\n" , i, new_socket);
new_socket = socket(AF_INET , SOCK_STREAM | SOCK_NONBLOCK, 0);
if (new_socket < 0)
{
client_socket[i] = 0;
log(ERROR, "Server socket error on master socket %d\nClient socket %d deleted\n", mSock, i);
break; //TODO: chequear
}
server_socket[i] = new_socket;
log(DEBUG, "Adding to list of server sockets as %d - socket %d\n" , i, new_socket);
struct sockaddr_in server_address;
memset(&server_address,0,sizeof server_address);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = htons(9999);
int len = sizeof(server_address);
char addrBuffer[MAX_ADDR_BUFFER];
printSocketAddress((struct sockaddr *) &server_address, addrBuffer);
log(INFO, "Handling server %s", addrBuffer);
if( connect(new_socket, (struct sockaddr *) &server_address, len) < 0 && errno != EINPROGRESS) {
client_socket[i] = 0;
server_socket[i] = 0;
log(ERROR, "Server connect error on master socket %d\nClient and server sockets %d deleted\n", mSock, i);
break; //TODO: chequear
}
FD_SET(new_socket, &writefds);
buffer_init(&bufferWrite[i], N(buffer), buffer);
buffer_init(&serverBufferWrite[i],N(buffer),buffer);
break;
}
}
}
}
//Verifico si se pudo realizar la conexion a un server o no
for(i = 0; i<max_clients;i++){
servSd = server_socket[i];
sd = client_socket[i];
if (FD_ISSET(servSd, &writefds)) {
if(getpeername(servSd , (struct sockaddr*)&address , (socklen_t*)&addrlen)<0) {
if (errno == ENOTCONN)
log(INFO, "Connection to server socket %d failed %d\n", servSd);
//Close the socket and mark as 0 in list for reuse
close( sd );
client_socket[i] = 0;
close( servSd );
server_socket[i] = 0;
FD_CLR(servSd, &writefds);
FD_CLR(sd,&writefds);
// Limpiamos el buffer asociado, para que no lo "herede" otra sesión
clear(&bufferWrite[i]);
clear(&serverBufferWrite[i]);
log(INFO, "Closing client socket %d\n", sd);
}
}
}
//TODO: revisar este bloque de codigo
for(i =0; i < max_clients; i++) {
sd = client_socket[i];
servSd = server_socket[i];
if (FD_ISSET(servSd, &writefds)) {
handleWrite(servSd, &bufferWrite[i], &writefds);
}
if(FD_ISSET(sd,&writefds)){
handleWrite(sd,&serverBufferWrite[i],&writefds);
}
}
//else its some IO operation on some other socket :)
for (i = 0; i < max_clients; i++)
{
sd = client_socket[i];
servSd = server_socket[i];
if (FD_ISSET( sd , &readfds))
{
//Check if it was for closing , and also read the incoming message
if ((valread = read( sd , buffer, BUFFSIZE)) <= 0)
{
//Somebody disconnected , get his details and print
getpeername(sd , (struct sockaddr*)&address , (socklen_t*)&addrlen);
log(INFO, "Host disconnected , ip %s , port %d \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
close( sd );
client_socket[i] = 0;
close( servSd );
server_socket[i] = 0;
FD_CLR(servSd, &writefds);
// Limpiamos el buffer asociado, para que no lo "herede" otra sesión
clear(&bufferWrite[i]);
}
else {
log(DEBUG, "Received %zu bytes from socket %d\n", valread, sd);
// activamos el socket para escritura y almacenamos en el buffer de salida
FD_SET(servSd, &writefds);
// Tal vez ya habia datos en el buffer
// TODO: validar realloc != NULL
// bufferWrite[i].data = realloc(bufferWrite[i].data, *bufferWrite[i].limit + valread);
// memcpy(bufferWrite[i].data + *bufferWrite[i].limit, buffer, valread);
// *bufferWrite[i].limit += valread;
size_t wbytes = 0/*, rbytes = 0*/;
uint8_t *ptr = buffer_write_ptr(&bufferWrite[i], &wbytes);
memcpy(ptr, buffer, valread);
buffer_write_adv(&bufferWrite[i], valread);
handleWrite(servSd,&bufferWrite[i],&writefds);
}
}
if(FD_ISSET(servSd,&readfds)){
//Check if it was for closing , and also read the incoming message
if ((valread = read( servSd , buffer, BUFFSIZE)) <= 0)
{
//Somebody disconnected , get his details and print
getpeername(servSd, (struct sockaddr*)&address , (socklen_t*)&addrlen);
log(INFO, "Host disconnected , ip %s , port %d \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
close( sd );
client_socket[i] = 0;
close( servSd );
server_socket[i] = 0;
FD_CLR(sd, &writefds);
// Limpiamos el buffer asociado, para que no lo "herede" otra sesión
clear(&serverBufferWrite[i]);
}
else {
log(DEBUG, "Received %zu bytes from socket %d\n", valread, servSd);
// activamos el socket para escritura y almacenamos en el buffer de salida
FD_SET(sd, &writefds);
// Tal vez ya habia datos en el buffer
// TODO: validar realloc != NULL
// bufferWrite[i].data = realloc(bufferWrite[i].data, *bufferWrite[i].limit + valread);
// memcpy(bufferWrite[i].data + *bufferWrite[i].limit, buffer, valread);
// *bufferWrite[i].limit += valread;
size_t wbytes = 0/*, rbytes = 0*/;
uint8_t *ptr = buffer_write_ptr(&serverBufferWrite[i], &wbytes);
memcpy(ptr, buffer, valread);
buffer_write_adv(&serverBufferWrite[i], valread);
handleWrite(sd,&serverBufferWrite[i],&writefds);
}
}
}
}
return 0;
}
void clear( struct buffer *buffer) { //TODO: lo llama con bufferWrite
//free(buffer->data);
buffer->data = buffer->write = buffer->limit = NULL;
//TODO: buffer->read = NULL???
//TODO: o buffer_reset(buffer) ??
}
// Hay algo para escribir?
// Si está listo para escribir, escribimos. El problema es que a pesar de tener buffer para poder
// escribir, tal vez no sea suficiente. Por ejemplo podría tener 100 bytes libres en el buffer de
// salida, pero le pido que mande 1000 bytes.Por lo que tenemos que hacer un send no bloqueante,
// verificando la cantidad de bytes que pudo consumir TCP.
void handleWrite(int socket, struct buffer * buffer, fd_set * writefds) {
size_t bytesToSend = buffer->write - buffer->read;
if (bytesToSend > 0) { // Puede estar listo para enviar, pero no tenemos nada para enviar
log(INFO, "Trying to send %zu bytes to socket %d\n", bytesToSend, socket);
size_t bytesSent = send(socket, buffer->read, bytesToSend, MSG_DONTWAIT); // | MSG_NOSIGNAL
log(INFO, "Sent %zu bytes\n", bytesSent);
if ( bytesSent < 0) {
// Esto no deberia pasar ya que el socket estaba listo para escritura
// TODO: manejar el error
log(FATAL, "Error sending to socket %d", socket);
} else {
size_t bytesLeft = bytesSent - bytesToSend;
// Si se pudieron mandar todos los bytes limpiamos el buffer y sacamos el fd para el select
if ( bytesLeft == 0) {
//clear(buffer);
buffer_reset(buffer);
FD_CLR(socket, writefds);
} else {
buffer_read_adv(buffer, bytesSent);
}
}
}else {
log(DEBUG, "Nothing to send to socket %d", socket);
FD_CLR(socket, writefds);
}
}
int udpSocket(int port) {
int sock;
struct sockaddr_in serverAddr;
if ( (sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
log(ERROR, "UDP socket creation failed, errno: %d %s", errno, strerror(errno));
return sock;
}
log(DEBUG, "UDP socket %d created", sock);
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET; // IPv4cle
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(port);
if ( bind(sock, (const struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0 )
{
log(ERROR, "UDP bind failed, errno: %d %s", errno, strerror(errno));
close(sock);
return -1;
}
log(DEBUG, "UDP socket bind OK ");
return sock;
}
void handleAddrInfo(int socket) {
// En el datagrama viene el nombre a resolver
// Se le devuelve la informacion asociada
char buffer[BUFFSIZE];
unsigned int len, n;
struct sockaddr_in clntAddr;
// Es bloqueante, deberian invocar a esta funcion solo si hay algo disponible en el socket
n = recvfrom(socket, buffer, BUFFSIZE, 0, ( struct sockaddr *) &clntAddr, &len);
if ( buffer[n-1] == '\n') // Por si lo estan probando con netcat, en modo interactivo
n--;
buffer[n] = '\0';
log(DEBUG, "UDP received:%s", buffer );
// TODO: parsear lo recibido para obtener nombre, puerto, etc. Asumimos viene solo el nombre
// Especificamos solo SOCK_STREAM para que no duplique las respuestas
struct addrinfo addrCriteria; // Criteria for address match
memset(&addrCriteria, 0, sizeof(addrCriteria)); // Zero out structure
addrCriteria.ai_family = AF_UNSPEC; // Any address family
addrCriteria.ai_socktype = SOCK_STREAM; // Only stream sockets
addrCriteria.ai_protocol = IPPROTO_TCP; // Only TCP protocol
// Armamos el datagrama con las direcciones de respuesta, separadas por \r\n
// TODO: hacer una concatenacion segura
// TODO: modificar la funcion printAddressInfo usada en sockets bloqueantes para que sirva
// tanto si se quiere obtener solo la direccion o la direccion mas el puerto
char bufferOut[BUFFSIZE];
bufferOut[0] = '\0';
struct addrinfo *addrList;
int rtnVal = getaddrinfo(buffer, NULL, &addrCriteria, &addrList);
if (rtnVal != 0) {
log(ERROR, "getaddrinfo() failed: %d: %s", rtnVal, gai_strerror(rtnVal));
strcat(strcpy(bufferOut,"Can't resolve "), buffer);
} else {
for (struct addrinfo *addr = addrList; addr != NULL; addr = addr->ai_next) {
struct sockaddr *address = addr->ai_addr;
char addrBuffer[INET6_ADDRSTRLEN];
void *numericAddress = NULL;
switch (address->sa_family) {
case AF_INET:
numericAddress = &((struct sockaddr_in *) address)->sin_addr;
break;
case AF_INET6:
numericAddress = &((struct sockaddr_in6 *) address)->sin6_addr;
break;
}
if ( numericAddress == NULL) {
strcat(bufferOut, "[Unknown Type]");
} else {
// Convert binary to printable address
if (inet_ntop(address->sa_family, numericAddress, addrBuffer, sizeof(addrBuffer)) == NULL)
strcat(bufferOut, "[invalid address]");
else {
strcat(bufferOut, addrBuffer);
}
}
strcat(bufferOut, "\r\n");
}
freeaddrinfo(addrList);
}
// Enviamos respuesta (el sendto no bloquea)
sendto(socket, bufferOut, strlen(bufferOut), 0, (const struct sockaddr *) &clntAddr, len);
log(DEBUG, "UDP sent:%s", bufferOut );
}