-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgateway.c
276 lines (205 loc) · 7.37 KB
/
gateway.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
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
//#include <time.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <pthread.h>
#include "global.h"
#include "Estruturas/headed_list.h"
#include "serializer.h"
// Interrupções
int isInterrupted = FALSE ;
void interruptionHandler(){
isInterrupted = TRUE;
}
void setInterruptionHandler(){
struct sigaction sa;
memset (&sa, 0, sizeof(sa));
sa.sa_handler = interruptionHandler;
sigaction(SIGINT, &sa, NULL);
}
// Variáveis globais
List * peer_list;
int CURRENT_PEER_ID = 0;
uint32_t CURRENT_IMAGE_ID = 0;
typedef struct peer_info{
int id;
int n_connections;
//time_t last_msg;
struct in_addr addr;
in_port_t tcp_port;
in_port_t udp_port;
} PeerInfo;
int comparePeerWithPeerId(void * peer, void * id){
if (((PeerInfo *)peer)->id == *(int *)id){
return EQUAL;
}
return ((PeerInfo *)peer)->id > *(int *)id ? GREATER : SMALLER;
}
int isPeerAlive(int fd, PeerInfo * peer){
struct sockaddr_in addr;
int msg_id = MSG_GATEWAY_IS_ALIVE;
int n_connections;
// Define propriedades da socket
addr.sin_family = AF_INET;
addr.sin_port = peer->udp_port;
addr.sin_addr = peer->addr;
printf("Checking if selected peer %d is alive...\n", peer->id);
sendto(fd, &msg_id, sizeof(int), 0, (struct sockaddr *) &addr, sizeof(struct sockaddr));
if (UDPRead(fd, &n_connections, sizeof(int), TIMEOUT) == TRUE){
peer->n_connections = n_connections + 1; // Nº de conexões atual + conexão que receberá já de seguida por ter sido selecionado
return TRUE;
}
printf("Peer doesn't answer... Removing from list!\n");
removeListItem(peer_list, &peer->id);
return FALSE;
}
PeerInfo * getAvailablePeer(int fd){
ListNode * current_node;
PeerInfo * best_peer;
PeerInfo * current_peer;
do {
current_node = getFirstListNode(peer_list);
best_peer = getListNodeItem(current_node); // best_peer começa por ser o primeiro elemento da lista
current_node = getNextListNode(current_node); // current_node o segundo elemento da lista
while(current_node != NULL){
current_peer = getListNodeItem(current_node);
current_node = getNextListNode(current_node); // Iteração pela lista com a variavel current_node
if (current_peer->n_connections < best_peer->n_connections){
best_peer = current_peer;
}
}
} while(best_peer != NULL && isPeerAlive(fd, best_peer) != TRUE);
return best_peer; // Pode ser NULL, caso não existam servidores na lista
}
void * handleClients(void * arg){
int fd, check;
struct sockaddr_in client_addr;
PeerInfo * peer;
char buffer[CHUNK_SIZE];
socklen_t size;
fd = *(int *)arg;
while(!isInterrupted){
size = sizeof(client_addr);
check = recvfrom(fd, buffer, CHUNK_SIZE, 0, (struct sockaddr *) &client_addr, &size);
if (isInterrupted) return NULL;
if (check == -1) {perror(NULL); continue;}
printf("Novo pedido de cliente...\n");
// Não é importante o que os clientes enviam
// (eles apenas contactam a gateway para obter um servidor)
// Obtem peer disponivel e serializa a sua informação
peer = getAvailablePeer(fd);
if (peer != NULL){
serializePeerInfo(fd, client_addr, peer->id, peer->tcp_port, peer->addr);
printf("Indicando peer com id %d em %s@%d\n", peer->id, inet_ntoa(peer->addr), (int) ntohs(peer->tcp_port));
} else {
serializeInteger(fd, client_addr, FALSE);
printf("Não há peers disponiveis\n");
}
}
return NULL;
}
void * handlePeersUDP(void * arg){
int fd, msg_id, peer_id;
struct sockaddr_in peer_addr;
PeerInfo * peer;
char buffer[CHUNK_SIZE];
socklen_t size;
fd = *(int *)arg;
while(!isInterrupted){
// Recebe mensagem
size = sizeof(peer_addr);
if ( recvfrom(fd, buffer, CHUNK_SIZE, 0, (struct sockaddr *) &peer_addr, &size) == ERROR) { perror(NULL); close(fd); return NULL;};
// Obtem identificador da mensagem
memcpy(&msg_id, buffer, sizeof(int));
switch(msg_id){
case MSG_GATEWAY_NEW_PEER_ID:
printf("Pedido de novo ID para peer\n");
serializeInteger(fd, peer_addr, CURRENT_PEER_ID++);
break;
case MSG_GATEWAY_NEW_PHOTO_ID:
printf("Pedido de novo ID para foto\n");
serializeUint32(fd, peer_addr, CURRENT_IMAGE_ID++);
break;
case MSG_GATEWAY_PEER_INFO: // Novo Peer!
printf("Novo peer...\n");
// Aloca nova estrutura que representa o servidor
peer = (PeerInfo *) malloc(sizeof(PeerInfo));
peer->n_connections = 0;
peer->udp_port = peer_addr.sin_port; // Neste momento a gateway foi contactada via socket UDP do peer
if (deserializePeerInfo(buffer, &peer->id, &peer->tcp_port, &peer->addr) == TRUE){
insertListItem(peer_list, peer, &peer->id); // Insere na lista de servidores
serializeInteger(fd, peer_addr, TRUE); // Confirma que o peer foi inserido
} else {
serializeInteger(fd, peer_addr, ERROR); // Informa o peer que ocorreu um erro na sua inserção
}
break;
case MSG_GATEWAY_PEER_DEATH: // Eliminar Peer
printf("Remover Peer...\n");
deserializePeerDeath(buffer, &peer_id);
removeListItem(peer_list, &peer_id);
// Não é necessário responder
}
}
return NULL;
}
void sendPeerList(int fd, int peer_id){
ListNode * current_node;
PeerInfo * peer;
int size;
size = getListSize(peer_list) - 1; // O próprio peer não é contabilizado
if (send(fd, &size, sizeof(int), 0) == ERROR) return;
current_node = getFirstListNode(peer_list);
while(current_node != NULL){
peer = getListNodeItem(current_node);
current_node = getNextListNode(current_node);
if (peer->id == peer_id) continue; //Evita enviar o próprio peer
if ( send(fd, &peer->tcp_port, sizeof(in_port_t), 0) == ERROR) return;
if ( send(fd, &peer->addr, sizeof(struct in_addr), 0) == ERROR) return;
}
}
void handlePeersTCP(int fd){
int new_fd, peer_id;
//check = listen(fd, MAX_QUEUED_CONNECTIONS) != -1;
//if (check == -1) { perror(NULL); close(fd); return;}
while(!isInterrupted){
new_fd = accept(fd, NULL, NULL);
if (isInterrupted) break;
if (new_fd == -1) { perror(NULL); close(fd); return;}; // Continua à espera de novas liações em caso de erro
printf("Sending all available peers...\n");
TCPRead(new_fd, &peer_id, sizeof(int), TIMEOUT);
sendPeerList(new_fd, peer_id);
close(new_fd);
}
}
int main(int argc, char *argv[]){
pthread_t clients_thread, peers_thread;
struct in_addr gateway_addr;
int fd_peers_udp, fd_peers_tcp, fd_clients;
assert(argc > 3);
assert(inet_aton(argv[1], &gateway_addr) != 0); // Garante que a address introduzida é válida
// Abre todas as sockets necessárias
fd_clients = getBindedUDPSocket(htons(atoi(argv[2])), gateway_addr);
if (fd_clients == ERROR) {perror(NULL); return 1;}
fd_peers_udp = getBindedUDPSocket(htons(atoi(argv[3])), gateway_addr);
if (fd_peers_udp == ERROR) {close(fd_clients); perror(NULL); return 1;}
fd_peers_tcp = getBindedTCPSocket(htons(atoi(argv[3])), gateway_addr);
if (fd_peers_tcp == ERROR) {close(fd_clients); close(fd_peers_udp); perror(NULL); return 1;}
setInterruptionHandler();
// Cria lista de peers
peer_list = newList(comparePeerWithPeerId, free);
pthread_create(&clients_thread, NULL, handleClients, &fd_clients);
pthread_create(&peers_thread, NULL, handlePeersUDP, &fd_peers_udp);
handlePeersTCP(fd_peers_tcp);
// Termina threads
pthread_cancel(clients_thread);
pthread_cancel(peers_thread);
pthread_join(clients_thread, NULL);
pthread_join(peers_thread, NULL);
close(fd_clients);
close(fd_peers_udp);
close(fd_peers_tcp);
freeList(peer_list);
}