-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.c
More file actions
709 lines (590 loc) · 23.8 KB
/
client.c
File metadata and controls
709 lines (590 loc) · 23.8 KB
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <netdb.h>
#include "packet.h"
#include "types/error_packet.h"
#define TIMEOUT 5 //Default timeout
#define MAX_TRIES 5
#define BUF_SIZE 516
#define DATA_SIZE 512
#define SRV_PORT "69"
#define CLI_PORT "0"
int request_mode; //The mode of connection - read or write
unsigned short source_tid; //The source tid or source port number
unsigned short dest_tid = 69; //The destination tid or destination port number
void print_error(const char *); //prints an error and exits
void print_buffer(char *, int); //print the buffer . For Testing purposes
in_port_t get_in_port(struct sockaddr_storage *); //get port number from sockaddr *
int ports_match(unsigned short, unsigned short); //check if two port numbers match
int start_client(int opcode, char* filename, int mode, char *server_addr, char *port){
//Called in main() -> starts the client.
//Starts the client according to the request type and request mode
//A connection can be started with a WRQ or an RRQ
/*Data size*/
int data_size=0;
/*result value*/
int rv;
int rv1;
/*address family*/
int addr_family;
/*extra pointers*/
struct sockaddr *otr;
/*Timeout purposes*/
int timeout_tries = MAX_TRIES;
int err_blck_tries = MAX_TRIES;
/*socket declarations*/
int me;
struct sockaddr_storage other_addr, my_addr;
struct addrinfo hints, *res, *p;
int other_addrlen;
int reclength;
/*buffer declarations*/
char send_buffer[BUF_SIZE];
char recv_buffer[BUF_SIZE];
/*File tp read from or write to*/
FILE *fp;
/*File statistics*/
struct stat file_buffer;
/*The expected block number*/
int expected_blck_num;
/*timeval struct for timeouts*/
struct timeval timeout;
timeout.tv_sec=TIMEOUT;
timeout.tv_usec=0;
/*actual filename*/
char *temp_filename, *temp;
/*packet structure initializations*/
packet *pckt;
pckt = (packet *) malloc(sizeof(packet));
init_packet(pckt);
char *errmsgs[] = {"Error Occured", "File not found", "Access violation",
"Disk full", "Illegal TFTP Operation", "Unknown TID", "File Already Exists", "No user"};
/*Error messages*/
if(is_read_request(opcode) || is_write_request(opcode)){
if(is_read_request(opcode)){
rv1 = stat(filename, &file_buffer);
if(rv1 == 0){
finish(NULL, me);
print_error("File already exits");
}
}
temp_filename = filename;
for(rv=0;rv<strlen(filename);rv++){
if(filename[rv] == '\0')
break;
if(filename[rv] =='/')
temp_filename=filename+rv+1;
}
if(*temp_filename == '\0'){
print_error("Invalid filename");
}
if(is_read_request(opcode)){
temp = temp_filename;
temp_filename = filename;
filename = temp;
}
/*Networking aspect starts here*/
//Configure the socket for timeouts
//setsockopt(me, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof(struct timeval) );
memset(&hints, 0 , sizeof(hints) ); //Initialize hints to zero
hints.ai_family = AF_UNSPEC; //Handle any family of sockets
hints.ai_socktype = SOCK_DGRAM; //Socket is of Datagram type
if(port != NULL){
if(invalid_port(port))
print_error("Invalid port");
if(rv = getaddrinfo(server_addr, port, &hints, &res) != 0){
fprintf(stderr, "getaddrinfo:\t%s\n", gai_strerror(rv) );
exit(1);
}
}
else{
if(rv = getaddrinfo(server_addr, SRV_PORT, &hints, &res) != 0){
fprintf(stderr, "getaddrinfo:\t%s\n", gai_strerror(rv) );
exit(1);
}
}
if(res == NULL){
print_error("Failed to fetch valid interfaces");
}
memcpy(&other_addr, res->ai_addr, res->ai_addrlen );
other_addrlen = res->ai_addrlen;
addr_family = res->ai_family;
freeaddrinfo(res);
otr = (struct sockaddr*) &other_addr;
//Try to bind the socket to a random port
//Fill up hints
memset( &hints, 0 , sizeof( hints ) ); //Fill in hints with 0s
hints.ai_family = addr_family;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
//listout all addresses
if( (rv = getaddrinfo(NULL, CLI_PORT, &hints, &res)) != 0 ){ //do dns lookups and fetch all the possible interfaces
fprintf(stderr, "getaddrinfo:\t%s\n", gai_strerror(rv) ); //so we can bind
exit(1);
}
//Try to create socket and bind to a one address
for(p = res; p != NULL ; p = p->ai_next ){
if( (me = socket( p->ai_family, p->ai_socktype, p->ai_protocol )) < 0 ){
perror("socket");
continue;
}
if( bind(me, p->ai_addr, p->ai_addrlen ) < 0 ){
perror("bind");
continue;
}
addr_family = p->ai_family;
break;
}
if(p == NULL){
fprintf(stderr, "Failed to bind\n");
exit(1);
}
source_tid = get_in_port(&my_addr); //save source tid
printf("Socket created successfully\n");
printf("Socket bound to port %hu\n", source_tid);
//Configure socket for timeouts
//default timeout TIMEOUT
if(setsockopt(me, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof(struct timeval) ) == -1){
perror("setsockopt timeout");
finish(NULL, me);
exit(1);
}
memcpy(&my_addr, p->ai_addr, p->ai_addrlen );
freeaddrinfo(res);
reclength = -1;
if(is_read_request(opcode)){
//handle the operations needed to be done for a read request
expected_blck_num = 1;
copy_request_header_to_buffer(opcode,temp_filename,mode,send_buffer); //Raw header now in buffer
do{
reclength = -1;
timeout_tries=MAX_TRIES; //tries for timeout
while(reclength == -1 && timeout_tries > 0){
if(send_packet(me, send_buffer, BUF_SIZE , otr , other_addrlen ) == -1){
finish(NULL, me);
perror("sendto");
exit(1);
}
reclength = recv_packet(me, recv_buffer, otr , &other_addrlen );
if(reclength == -1){
print_read_timeout();
}
timeout_tries--;
}
//If maximum timeout tries reached
if(timeout_tries == 0){
break;
}
//Strip the raw packet from buffer and put the values in pckt structure
if(!strip_raw_packet(recv_buffer, reclength, pckt)){
copy_err_header_to_buffer(ILLEGAL_OPERATION, errmsgs[ILLEGAL_OPERATION], send_buffer);
send_packet(me, send_buffer, BUF_SIZE, otr , other_addrlen );
finish(NULL, me);
print_error("Malformed packet encountered. Exiting");
}
//if not datapacket, then it maybe error packet or some other packet
//if error packet print error message and exit
//otherwise send ILLEGAL_OPERATION error to server and exit
if(!is_data_packet(pckt->opcode)){
if(is_error_packet(pckt->opcode)){
finish(NULL, me);
print_error(pckt->err_message);
}
else{
copy_err_header_to_buffer(ILLEGAL_OPERATION, errmsgs[ILLEGAL_OPERATION], send_buffer);
send_packet(me, send_buffer, BUF_SIZE, otr, other_addrlen );
finish(NULL, me);
print_error("Unexpected packet encountered");
}
}
err_blck_tries--; //decrement the block number error tries
} while(expected_blck_num != pckt->block_number && err_blck_tries > 0);
if(err_blck_tries == 0 || timeout_tries == 0){
copy_err_header_to_buffer(NOT_DEFINED, "Maximum Tries reached",send_buffer);
send_packet(me, send_buffer, BUF_SIZE, otr, other_addrlen );
finish(NULL, me);
print_error("Maximum tries reached");
}
dest_tid = get_in_port(&other_addr); //set the destination port as chosen by the server
//Connection established
//Yay!
data_size = reclength-4; //First four bytes are headers
if( is_netascii(mode) ){
fp = fopen(filename, "w");
}
else if(is_octet(mode)){
fp = fopen(filename, "wb");
}
if(fp == NULL){
rv1 = find_error();
copy_err_header_to_buffer(rv1 ,errmsgs[rv1], send_buffer );
send_packet( me, send_buffer, BUF_SIZE, otr , other_addrlen );
finish(NULL, me);
perror("fopen");
exit(1);
}
fwrite(pckt->data_buffer, 1 ,data_size, fp );
//fwrite treates error and eof as the same thing
//so we need to call ferror() specifically to know if
//an error has occured
if(ferror(fp) != 0){
//error is set
rv1 = find_error();
copy_err_header_to_buffer( rv1, errmsgs[rv1] , send_buffer );
send_packet( me , send_buffer, BUF_SIZE , otr , other_addrlen );
finish(fp, me);
perror("fwrite");
exit(1);
}
copy_ack_header_to_buffer(expected_blck_num, send_buffer);
rv = 0;
while(data_size == 512){
reclength=-1;
if(!rv){
err_blck_tries = MAX_TRIES;
}
else{
//previous receive fetched a duplicate packet
//so decrement err_blck_tries
err_blck_tries--;
rv=0;
}
//error block tries maximum
if( err_blck_tries == 0 )
break;
timeout_tries = MAX_TRIES;
while(reclength == -1 && timeout_tries > 0){
//As it keeps timing out keep trying
if(send_packet(me, send_buffer,4, otr , other_addrlen ) == -1){
finish(fp, me);
perror("sendto");
exit(1);
}
printf("ACK sent: Block number = %d\n", pckt->block_number);
reclength = recv_packet(me, recv_buffer, otr , &other_addrlen );
if(reclength == -1){
print_ack_wait_timeout(expected_blck_num);
}
timeout_tries--;
}
if(timeout_tries == 0)
break;
if(dest_tid != get_in_port(&other_addr)){
//Send error packet with errtype UNKNOWN_TID
//since the destination ids dont match
//send error packet and drop the current packet as it might be
//from some other service and retransmit the previous packet
copy_err_header_to_buffer(UNKNOWN_TID, errmsgs[UNKNOWN_TID], recv_buffer);
if(send_packet(me, recv_buffer, BUF_SIZE, otr, other_addrlen ) == -1){
perror("sendto");
finish(fp, me);
exit(1);
}
rv=1;
continue; //skip this packet and retransmit
}
//Need to send an error packet
if(!strip_raw_packet(recv_buffer, reclength, pckt)){
copy_err_header_to_buffer(ILLEGAL_OPERATION, errmsgs[ILLEGAL_OPERATION], send_buffer);
send_packet( me, send_buffer , BUF_SIZE, otr , other_addrlen );
finish(fp, me);
print_error("Malformed packet encountered. Exiting");
}
//If not data packet and do the same thing
//done above
if(!is_data_packet(pckt->opcode)){
if(is_error_packet(pckt->opcode)){
if(pckt->error_code == UNKNOWN_TID){
//Unknown tid error
//skip current packet and retransmit previous
continue;
}
print_error(pckt->err_message);
}
else{
copy_err_header_to_buffer(ILLEGAL_OPERATION, errmsgs[ILLEGAL_OPERATION], send_buffer);
send_packet( me, send_buffer, BUF_SIZE, otr, other_addrlen );
finish(fp, me);
print_error("Unexpected packet encountered");
}
}
//If packet block numbers dont match then
//dont increment the expected_blck_num
//and dont copy new headers into send_buffer so that
//the previous packet is resent
if(pckt->block_number == (expected_blck_num+1)%65536 ){
data_size = reclength-4;
//fprintf(fp, "%s", pckt->data_buffer );
fwrite(pckt->data_buffer, 1 ,data_size, fp );
if(ferror(fp) != 0){
rv1 = find_error();
copy_err_header_to_buffer( rv1, errmsgs[rv1], send_buffer );
send_packet( me, send_buffer, BUF_SIZE, otr , other_addrlen );
perror("fwrite");
finish(fp, me);
exit(1);
}
expected_blck_num = (expected_blck_num+1) % 65536;
printf("Data packet of size %d and block number %d received\n", data_size, pckt->block_number);
copy_ack_header_to_buffer(expected_blck_num, send_buffer);
}
else{
rv=1;
printf("%d received %d expected\n", pckt->block_number, expected_blck_num);
}
}
//Max tries reached
if(timeout_tries == 0 || err_blck_tries == 0){
copy_err_header_to_buffer(NOT_DEFINED, "Maximum tries reached", send_buffer);
send_packet(me, send_buffer, BUF_SIZE, otr, other_addrlen);
finish(fp, me);
print_error("Maximum tries reached");
}
//The final ack
printf("Sending the final ACK\n");
copy_ack_header_to_buffer(pckt->block_number, send_buffer);
if(send_packet(me, send_buffer,4, otr , other_addrlen ) == -1){
finish(fp, me);
print_error("Unable to send packet");
}
}
else{
//handle the operations needed to be done for a write request
expected_blck_num = 0;
reclength = -1;
data_size = DATA_SIZE;
printf("Write request \n");
err_blck_tries = MAX_TRIES;
copy_request_header_to_buffer(opcode, temp_filename, mode, send_buffer);
do{
timeout_tries = MAX_TRIES;
while(reclength == -1 && timeout_tries > 0){
if(send_packet(me, send_buffer, BUF_SIZE , otr, other_addrlen ) == -1 ){
//Unable to send for some reason
finish(NULL, me);
perror("sendto");
exit(1);
}
reclength = recv_packet( me, recv_buffer, otr , &other_addrlen );
if(reclength == -1){
print_data_wait_timeout(expected_blck_num);
}
timeout_tries--;
}
if(timeout_tries == 0)
break;
if(!strip_raw_packet(recv_buffer, reclength, pckt)){
copy_err_header_to_buffer(ILLEGAL_OPERATION, errmsgs[ILLEGAL_OPERATION], send_buffer);
send_packet( me, send_buffer , BUF_SIZE, otr , other_addrlen );
finish(fp, me);
print_error("Malformed Packet"); //Malformed packet , so send error packet and exit
}
if(!is_ack_packet(pckt->opcode)){
if(is_error_packet(pckt->opcode)){
finish(NULL, me);
print_error(pckt->err_message); //Error packet received
}
copy_err_header_to_buffer(ILLEGAL_OPERATION, errmsgs[ILLEGAL_OPERATION], send_buffer);
send_packet( me , send_buffer, BUF_SIZE, otr, other_addrlen );
finish(NULL, me);
print_error("Unexpected packet received"); //Not an expected packet
}
err_blck_tries--;
}while( (pckt->block_number != expected_blck_num) && err_blck_tries > 0);
//Max timeouts
if(timeout_tries == 0 || err_blck_tries == 0){
copy_err_header_to_buffer(NOT_DEFINED, "Maximum tries reached", send_buffer);
send_packet( me, send_buffer, BUF_SIZE, otr, other_addrlen );
finish(NULL, me);
print_error("Maximum tries reached");
}
dest_tid = get_in_port(&other_addr); //Save destination port number
//intialize file pointer
if(is_netascii(mode))
fp = fopen(filename, "r");
else if(is_octet(mode))
fp = fopen(filename, "rb");
if(fp == NULL){
//Unable to open file for some reason
rv1 = find_error();
copy_err_header_to_buffer( rv1 , errmsgs[rv1], send_buffer );
send_packet( me , send_buffer, BUF_SIZE, otr , other_addrlen );
finish(fp, me);
perror("fopen");
exit(1);
}
//Now the connection is established
//Start sending the data
//printf("Connection established\n");
data_size = fread(recv_buffer, 1 , DATA_SIZE, fp);
// printf("%d\n", data_size);
if(ferror(fp) != 0){
//Some file read error occured
rv1 = find_error();
copy_err_header_to_buffer(rv1 , errmsgs[rv1], send_buffer);
send_packet( me, send_buffer, BUF_SIZE, otr , other_addrlen );
finish(fp, me);
perror(NULL);
exit(1);
}
expected_blck_num++;
copy_data_header_to_buffer(expected_blck_num,recv_buffer, data_size, send_buffer); //copy data header to buffer
rv=0;
while(data_size > 0){
//Read the data in blocks of DATA_SIZE bytes
//Send the data packet
//Receive the acks
reclength = -1;
if(!rv){
err_blck_tries = MAX_TRIES;
}
else{
err_blck_tries--;
rv=0;
}
if(err_blck_tries == 0)
break;
timeout_tries = MAX_TRIES;
while(reclength == -1 && timeout_tries > 0){
//as it keeps timing out keep trying
if(send_packet(me, send_buffer, data_size+4, otr , other_addrlen ) == -1){
finish(fp, me);
perror("sendto");
exit(1);
}
printf("Sent data packet no. %d of size %d\n", expected_blck_num, data_size);
reclength = recv_packet(me , recv_buffer, otr , &other_addrlen );
if(reclength == -1){
print_data_wait_timeout(expected_blck_num);
}
timeout_tries--;
}
//Max tries reached
if(timeout_tries == 0)
break;
if(dest_tid != get_in_port(&other_addr)){
//Send error packet with errtype UNKNOWN_TID
//skip current and resend previous packets
copy_err_header_to_buffer(UNKNOWN_TID, errmsgs[UNKNOWN_TID], recv_buffer);
if(send_packet(me, recv_buffer, BUF_SIZE, otr , other_addrlen ) == -1){
perror("sento");
finish(fp, me);
exit(1);
}
rv=1;
continue;
}
//Some error checking
//check if port numbers match
//check if its a valid packet
//check if the packet is the expected one
//check if block numbers match etc
if(!strip_raw_packet(recv_buffer, reclength, pckt)){
//Send error packet to server and exit
copy_err_header_to_buffer(ILLEGAL_OPERATION, errmsgs[ILLEGAL_OPERATION], send_buffer);
send_packet( me, send_buffer, BUF_SIZE, otr , other_addrlen );
finish(fp, me);
print_error("Malformed Packet received");
}
if(!is_ack_packet(pckt->opcode)){
if(is_error_packet(pckt->opcode)){
if(pckt->error_code == UNKNOWN_TID){
//unknown tid error from server
//dont quit just discard packet and resend data packet
continue;
}
else{
finish(fp, me);
print_error(pckt->err_message);
}
}
else{
//Unexpected packet
//Consider it as illegal operation
copy_err_header_to_buffer(ILLEGAL_OPERATION, errmsgs[ILLEGAL_OPERATION], send_buffer);
send_packet( me, send_buffer, BUF_SIZE, otr, other_addrlen );
finish(fp, me);
print_error("Unexpected packet encountered");
}
}
if( pckt->block_number == expected_blck_num ){
printf("Received ack for packet no. %d\n", pckt->block_number);
if(data_size < DATA_SIZE) //End of write request
break;
expected_blck_num = (expected_blck_num + 1) % 65536;
data_size = fread(recv_buffer, 1 , DATA_SIZE, fp);
// printf("%d\n", data_size);
if(ferror(fp) != 0){
//Some file read error occured
rv1 = find_error();
copy_err_header_to_buffer(rv1 , errmsgs[rv1], send_buffer);
send_packet( me, send_buffer, BUF_SIZE, otr , other_addrlen );
finish(fp, me);
perror(NULL);
exit(1);
}
//data for the next block
copy_data_header_to_buffer(expected_blck_num,recv_buffer, data_size, send_buffer);
}
else{
printf("%d received %d expected\n", pckt->block_number , expected_blck_num);
}
}
//max tries reached
if(timeout_tries == 0 || err_blck_tries == 0){
copy_err_header_to_buffer( NOT_DEFINED, "Maximum tries reached", send_buffer );
send_packet(me, send_buffer, BUF_SIZE, otr, other_addrlen);
finish(fp, me);
print_error("Maximum tries reached");
}
}
finish(fp,me);
}
else printf("Invalid request\n");
return 0;
}
/*Additional functions for error printing and stuff*/
void print_error(const char *s){
fprintf(stderr, "%s\n", s);
exit(1);
}
/*calls sento()*/
int send_packet(int fd, char *buffer, int size, struct sockaddr* addr, int slen){
return sendto(fd, buffer, size, 0, addr, slen );
}
/*calls recvfrom()*/
int recv_packet(int fd, char *buffer, struct sockaddr* addr, int *slen){
return recvfrom(fd, buffer, BUF_SIZE, 0 , addr, slen);
}
/*Print Buffer -- for testing purpose*/
void print_buffer(char *buffer, int length){
int i=0;
for(i=0;i<length;i++)
printf("%c", buffer[i]);
}
/*Get port number from sockstorage structure*/
unsigned short get_in_port(struct sockaddr_storage *ss)
{
if (ss->ss_family == AF_INET) {
return ntohs(((struct sockaddr_in*)ss)->sin_port);
}
return ntohs(((struct sockaddr_in6*)ss)->sin6_port);
}
/*Close the file and socket if open*/
finish(FILE * f, int s){
if(f != NULL)
fclose(f);
close(s);
}
int invalid_port(char *port){
int i = atoi(port);
return ((i > 65535) || (i <= 0));
}