/
requester.c
366 lines (315 loc) · 12.1 KB
/
requester.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
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <time.h>
#include <strings.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include "utilities.h"
#include "tracker.h"
#include "newpacket.h"
int main(int argc, char **argv) {
// ------------------------------------------------------------------------
// Handle commandline arguments
if (argc != 11) {
printf("usage: requester -p <port> -f <f_hostname> -h <f_port> ");
printf("-o <file option> -w <window>\n");
exit(1);
}
char *portStr = NULL;
char *fileOption = NULL;
char *emuHost = NULL;
char *emuPortStr = NULL;
char *windowStr = NULL;
int cmd;
while ((cmd = getopt(argc, argv, "p:o:f:h:w:")) != -1) {
switch(cmd) {
case 'p': portStr = optarg; break;
case 'o': fileOption = optarg; break;
case 'f': emuHost = optarg; break;
case 'h': emuPortStr = optarg; break;
case 'w': windowStr = optarg; break;
case '?':
if (optopt == 'p' || optopt == 'o' || optopt == 'f'
|| optopt == 'h' || optopt == 'w')
fprintf(stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint(optopt))
fprintf(stderr, "Unknown option -%c.\n", optopt);
else
fprintf(stderr, "Unknown option character '\\x%x'.\n", optopt);
exit(EXIT_FAILURE);
break;
default:
printf("Unhandled argument: %d\n", cmd);
exit(EXIT_FAILURE);
}
}
// DEBUG
printf("Port: %s\n", portStr);
printf("File: %s\n", fileOption);
printf("Emu Name: %s\n", emuHost);
printf("Emu Port: %s\n", emuPortStr);
printf("Window: %s\n", windowStr);
// Convert program args to values
int requesterPort = atoi(portStr);
int windowSize = atoi(windowStr);
// TODO: uncomment these once they are used
//int emuPort = atoi(emuPortStr);
// Validate the argument values
if (requesterPort <= 1024 || requesterPort >= 65536)
ferrorExit("Invalid requester port");
if (windowSize <= 0 || windowSize >= 65536) // upper bound is arbitrary
ferrorExit("Invalid window size");
puts("");
// ------------------------------------------------------------------------
// Parse the tracker file for parts corresponding to the specified file
struct file_info *fileParts = parseTracker(fileOption);
assert(fileParts != NULL && "Invalid file_info struct");
// ------------------------------------------------------------------------
// Setup requester address info
struct addrinfo rhints;
bzero(&rhints, sizeof(struct addrinfo));
rhints.ai_family = AF_INET;
rhints.ai_socktype = SOCK_DGRAM;
rhints.ai_flags = AI_PASSIVE;
// Get the requester's address info
struct addrinfo *requesterinfo;
int errcode = getaddrinfo(NULL, portStr, &rhints, &requesterinfo);
if (errcode != 0) {
fprintf(stderr, "requester getaddrinfo: %s\n", gai_strerror(errcode));
exit(EXIT_FAILURE);
}
// Loop through all the results of getaddrinfo and try to create a socket for requester
int sockfd;
struct addrinfo *rp;
for(rp = requesterinfo; rp != NULL; rp = rp->ai_next) {
// Try to create a new socket
sockfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sockfd == -1) {
perror("Socket error");
continue;
}
// Try to bind the socket
if (bind(sockfd, rp->ai_addr, rp->ai_addrlen) == -1) {
perror("Bind error");
close(sockfd);
continue;
}
break;
}
if (rp == NULL) perrorExit("Request socket creation failed");
else { printf("Requester socket: "); printNameInfo(rp); }
// ------------------------------------------------------------------------
// Emulator hints
struct addrinfo ehints;
bzero(&ehints, sizeof(struct addrinfo));
ehints.ai_family = AF_INET;
ehints.ai_socktype = SOCK_DGRAM;
ehints.ai_flags = 0;
FILE *file = fopen("recvd.txt", "at");
if (file == NULL) perrorExit("File open error");
struct file_part *part = fileParts->parts;
//while (part != NULL) {
// Convert the sender's port # to a string
/*
char senderPortStr[6] = "\0\0\0\0\0\0";
sprintf(senderPortStr, "%d", part->sender_port);
*/
// Setup emulator address info
struct addrinfo *emuinfo;
errcode = getaddrinfo(emuHost, emuPortStr, &ehints, &emuinfo);
if (errcode != 0) {
fprintf(stderr, "emulator getaddrinfo: %s\n", gai_strerror(errcode));
exit(EXIT_FAILURE);
}
// Loop through all the results of getaddrinfo and try to create a socket for emulator
// NOTE: this is done so that we can find which of the getaddrinfo results is the emulator
int emusockfd;
struct addrinfo *ep;
for(ep = emuinfo; ep != NULL; ep = ep->ai_next) {
emusockfd = socket(ep->ai_family, ep->ai_socktype, ep->ai_protocol);
if (emusockfd == -1) {
perror("Socket error");
continue;
}
break;
}
if (ep == NULL) perrorExit("Emulator socket creation failed");
else close(emusockfd);
// ------------------------------------------------------------------------
struct addrinfo shints;
bzero(&shints, sizeof(struct addrinfo));
shints.ai_family = AF_INET;
shints.ai_socktype = SOCK_DGRAM;
shints.ai_flags = 0;
int sendersockfd = 0;
// Setup variables for statistics
unsigned long numPacketsRecvd = 0;
unsigned long numBytesRecvd = 0;
time_t startTime = time(NULL);
char str[6];
sprintf(str, "%d", part->sender_port);
struct addrinfo *senderinfo;
errcode = getaddrinfo(part->sender_hostname, str, &shints, &senderinfo);
if (errcode != 0) {
fprintf(stderr, "emulator getaddrinfo %s\n", gai_strerror(errcode));
exit(EXIT_FAILURE);
}
struct addrinfo *sp;
for(sp = senderinfo; sp != NULL; sp = ep->ai_next){
sendersockfd = socket(sp->ai_family, sp->ai_socktype, sp->ai_protocol);
if (sendersockfd == -1){
perror("Socket error");
continue;
}
break;
}
if (sp == NULL) perrorExit("Sender socket creation failed");
else close(sendersockfd);
// ------------------------------------------------------------------------
// Construct a REQUEST packet and send it to the emulator
struct new_packet *pkt = NULL;
pkt = malloc(sizeof(struct new_packet));
bzero(pkt, sizeof(struct new_packet));
pkt->priority = 1;
pkt->src_ip = ((struct sockaddr_in*)rp)->sin_addr.s_addr; // TODO
pkt->src_port = requesterPort; // TODO
pkt->dst_ip = ((struct sockaddr_in*)sp)->sin_addr.s_addr; // TODO
pkt->dst_port = part->sender_port; // TODO
pkt->len = sizeof(struct packet) - MAX_PAYLOAD + strlen(fileOption) + 1;
// encapsulated packet
pkt->pkt.type = 'R';
pkt->pkt.seq = 0;
pkt->pkt.len = windowSize;
strcpy(pkt->pkt.payload, fileOption);
sendPacketTo(sockfd, pkt, (struct sockaddr *)ep->ai_addr);
free(pkt);
// ------------------------------------------------------------------------
// Connect to emulator to receive all parts of requested file
// Start a recv loop here to get all packets for the given part
//
struct new_packet *buffer = malloc(windowSize * sizeof(struct new_packet));
unsigned int *acked = malloc(windowSize * sizeof(unsigned int));
int l;
for( l = 0; l < windowSize; ++l){
acked[l] = 0;
}
for (;;) {
// Receive a message
struct new_packet msg;
bzero(&msg, sizeof(struct new_packet));
size_t bytesRecvd = recvfrom(sockfd, &msg, sizeof(struct new_packet), 0,
(struct sockaddr *)ep->ai_addr, &ep->ai_addrlen);
if (bytesRecvd == -1) perrorExit("Receive error");
// Deserialize the message into a packet
struct new_packet p;
bzero(&p, sizeof(struct new_packet));
deserializePacket(&msg, &p);
// Handle DATA packet
if (p.pkt.type == 'D') {
// Update statistics
++numPacketsRecvd;
numBytesRecvd += p.len;
/* FOR DEBUG
printf("[Packet Details]\n------------------\n");
printf("type : %c\n", p.type);
printf("seq : %lu\n", p.seq);
printf("len : %lu\n", p.len);
printf("payload: %s\n\n", p.payload);
*/
// Print details about the received packet
//printf("<- [Received DATA packet] ");
//printPacketInfo(&p, (struct sockaddr_storage *)ep->ai_addr);
// See if this packet has already been received
int i;
int found = 0;
for(i = 0; i < windowSize; ++i){
if(buffer[i].pkt.seq == p.pkt.seq){
found = 1;
}
}
if(found == 0){
buffer[(p.pkt.seq - 1) % windowSize] = p;
}
// Save the data so the file can be reassembled later
//size_t bytesWritten = fprintf(file, "%s", p.pkt.payload);
//fflush(file);
//if (bytesWritten == -1) {
// fprintf(stderr,
// "Incomplete file write: %d bytes written, %lu p len",
// (int)bytesWritten, p.pkt.len);
//}
// Requester now ACK's this packet
struct new_packet *ack = NULL;
ack = malloc(sizeof(struct new_packet));
bzero(ack, sizeof(struct new_packet));
ack->priority = 1;
ack->src_ip = ((struct sockaddr_in*)rp)->sin_addr.s_addr; // TODO
ack->src_port = requesterPort; // TODO
ack->dst_ip = ((struct sockaddr_in*)sp)->sin_addr.s_addr; // TODO
ack->dst_port = part->sender_port; // TODO
ack->len = sizeof(struct packet) - MAX_PAYLOAD + strlen(fileOption) + 1;
// encapsulated packet
ack->pkt.type = 'A';
ack->pkt.seq = p.pkt.seq;
ack->pkt.len = windowSize;
strcpy(ack->pkt.payload, fileOption);
sendPacketTo(sockfd, ack, (struct sockaddr *)ep->ai_addr);
acked[(p.pkt.seq - 1) % windowSize] = 1;
free(ack);
}
int j;
int doneAcking = 1;
for(j = 0; j < windowSize; ++j){
if(acked[j] == 0){
doneAcking = 0;
}
}
if(doneAcking){
// write out to file in order
int k;
for(k = 0; k < windowSize; ++k){
acked[k] = 0;
size_t bytesWritten = fprintf(file, "%s", buffer[k].pkt.payload);
fflush(file);
if (bytesWritten == -1) {
fprintf(stderr,
"Incomplete file write: %d bytes written, %lu p len",
(int)bytesWritten, buffer[k].pkt.len);
}
}
}
// Handle END packet
if (p.pkt.type == 'E') {
printf("<- *** [Received END packet] ***");
double dt = difftime(time(NULL), startTime);
if (dt <= 1) dt = 1;
// Print statistics
printf("\n---------------------------------------\n");
printf("Total packets recvd: %lu\n", numPacketsRecvd);
printf("Total payload bytes recvd: %lu\n", numBytesRecvd);
printf("Average packets/second: %d\n", (int)(numPacketsRecvd / dt));
printf("Duration of test: %f sec\n\n", dt);
break;
}
}
part = part->next_part;
freeaddrinfo(emuinfo);
// TODO: this crashes the program... figure out why
//fclose(file);
// Got what we came for, shut it down
if (close(sockfd) == -1) perrorExit("Close error");
else puts("Connection closed.\n");
// Cleanup address and file info data
freeaddrinfo(requesterinfo);
freeFileInfo(fileParts);
// All done!
exit(EXIT_SUCCESS);
}