This repository has been archived by the owner on Jul 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
.goutputstream-3QI8TZ
945 lines (746 loc) · 32.3 KB
/
.goutputstream-3QI8TZ
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
/*
* S E R V I D O R
*
* This is an example program that demonstrates the use of
* sockets TCP and UDP as an IPC mechanism.
*
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "tftp.h"
#include "debugging.h"
#define PUERTO 6356
#define ADDRNOTFOUND 0xffffffff /* return address for unfound host */
#define BUFFERSIZE 1024 /* maximum size of packets to be received */
#define TAM_BUFFER 1024
#define MAXHOST 128
extern int errno;
/*
* M A I N
*
* This routine starts the server. It forks, leaving the child
* to do all the work, so it does not have to be run in the
* background. It sets up the sockets. It
* will loop forever, until killed by a signal.
*
*/
void serverTCP(int s, struct sockaddr_in peeraddr_in);
void serverUDP(int s, char * buffer, struct sockaddr_in clientaddr_in);
void errout(char *); /* declare error out routine */
int FIN = 0; /* Para el cierre ordenado */
void finalizar(){ FIN = 1; }
int main(argc, argv)
int argc;
char *argv[];
{
int s_TCP, s_UDP; /* connected socket descriptor */
int ls_TCP; /* listen socket descriptor */
int cc; /* contains the number of bytes read */
struct sigaction sa = {.sa_handler = SIG_IGN}; /* used to ignore SIGCHLD */
struct sockaddr_in myaddr_in; /* for local socket address */
struct sockaddr_in clientaddr_in; /* for peer socket address */
int addrlen;
fd_set readmask;
int numfds,s_mayor;
char buffer[BUFFERSIZE]; /* buffer for packets to be read into */
struct sigaction vec;
int udp_value = 0;
int u_UDP;
struct sockaddr_in servaddr_in;
struct addrinfo hints, *res;
long errcode;
/* Create the listen socket. */
ls_TCP = socket (AF_INET, SOCK_STREAM, 0);
if (ls_TCP == -1) {
perror(argv[0]);
fprintf(stderr, "%s: unable to create socket TCP\n", argv[0]);
exit(1);
}
/* clear out address structures */
memset ((char *)&myaddr_in, 0, sizeof(struct sockaddr_in));
memset ((char *)&clientaddr_in, 0, sizeof(struct sockaddr_in));
addrlen = sizeof(struct sockaddr_in);
/* Set up address structure for the listen socket. */
myaddr_in.sin_family = AF_INET;
/* The server should listen on the wildcard address,
* rather than its own internet address. This is
* generally good practice for servers, because on
* systems which are connected to more than one
* network at once will be able to have one server
* listening on all networks at once. Even when the
* host is connected to only one network, this is good
* practice, because it makes the server program more
* portable.
*/
myaddr_in.sin_addr.s_addr = INADDR_ANY;
myaddr_in.sin_port = htons(PUERTO);
/* Bind the listen address to the socket. */
if (bind(ls_TCP, (const struct sockaddr *) &myaddr_in, sizeof(struct sockaddr_in)) == -1) {
perror(argv[0]);
fprintf(stderr, "%s: unable to bind address TCP\n", argv[0]);
exit(1);
}
/* Initiate the listen on the socket so remote users
* can connect. The listen backlog is set to 5, which
* is the largest currently supported.
*/
if (listen(ls_TCP, 5) == -1) {
perror(argv[0]);
fprintf(stderr, "%s: unable to listen on socket\n", argv[0]);
exit(1);
}
/* Create the socket UDP. */
s_UDP = socket (AF_INET, SOCK_DGRAM, 0);
if (s_UDP == -1) {
perror(argv[0]);
printf("%s: unable to create socket UDP\n", argv[0]);
exit(1);
}
/* Bind the server's address to the socket. */
if (bind(s_UDP, (struct sockaddr *) &myaddr_in, sizeof(struct sockaddr_in)) == -1) {
perror(argv[0]);
printf("%s: unable to bind address UDP\n", argv[0]);
exit(1);
}
/* Now, all the initialization of the server is
* complete, and any user errors will have already
* been detected. Now we can fork the daemon and
* return to the user. We need to do a setpgrp
* so that the daemon will no longer be associated
* with the user's control terminal. This is done
* before the fork, so that the child will not be
* a process group leader. Otherwise, if the child
* were to open a terminal, it would become associated
* with that terminal as its control terminal. It is
* always best for the parent to do the setpgrp.
*/
setpgrp();
switch (fork()) {
case -1: /* Unable to fork, for some reason. */
perror(argv[0]);
fprintf(stderr, "%s: unable to fork daemon\n", argv[0]);
exit(1);
case 0: /* The child process (daemon) comes here. */
/* Close stdin and stderr so that they will not
* be kept open. Stdout is assumed to have been
* redirected to some logging file, or /dev/null.
* From now on, the daemon will not report any
* error messages. This daemon will loop forever,
* waiting for connections and forking a child
* server to handle each one.
*/
fclose(stdin);
fclose(stderr);
/* Set SIGCLD to SIG_IGN, in order to prevent
* the accumulation of zombies as each child
* terminates. This means the daemon does not
* have to make wait calls to clean them up.
*/
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror(" sigaction(SIGCHLD)");
fprintf(stderr,"%s: unable to register the SIGCHLD signal\n", argv[0]);
exit(1);
}
/* Registrar SIGTERM para la finalizacion ordenada del programa servidor */
vec.sa_handler = (void *) finalizar;
vec.sa_flags = 0;
if (sigaction(SIGTERM, &vec, (struct sigaction *) 0) == -1) {
perror(" sigaction(SIGTERM)");
fprintf(stderr,"%s: unable to register the SIGTERM signal\n", argv[0]);
exit(1);
}
while (!FIN) {
/* Meter en el conjunto de sockets los sockets UDP y TCP */
FD_ZERO(&readmask);
FD_SET(ls_TCP, &readmask);
FD_SET(s_UDP, &readmask);
/*
Seleccionar el descriptor del socket que ha cambiado. Deja una marca en
el conjunto de sockets (readmask)
*/
if (ls_TCP > s_UDP) s_mayor=ls_TCP;
else s_mayor=s_UDP;
if ( (numfds = select(s_mayor+1, &readmask, (fd_set *)0, (fd_set *)0, NULL)) < 0) {
if (errno == EINTR) {
FIN=1;
close (ls_TCP);
close (s_UDP);
perror("\nFinalizando el servidor. SeÃal recibida en elect\n ");
}
} else {
/* Comprobamos si el socket seleccionado es el socket TCP */
if (FD_ISSET(ls_TCP, &readmask)) {
s_TCP = accept(ls_TCP, (struct sockaddr *) &clientaddr_in, &addrlen);
if (s_TCP == -1) exit(1);
switch (fork()) {
case -1: /* Can't fork, just exit. */
exit(1);
case 0: /* Child process comes here. */
close(ls_TCP); /* Close the listen socket inherited from the daemon. */
serverTCP(s_TCP, clientaddr_in);
exit(0);
default: /* Daemon process comes here. */
/* The daemon needs to remember
* to close the new accept socket
* after forking the child. This
* prevents the daemon from running
* out of file descriptor space. It
* also means that when the server
* closes the socket, that it will
* allow the socket to be destroyed
* since it will be the last close.
*/
close(s_TCP);
}
} /* De TCP*/
/* Comprobamos si el socket seleccionado es el socket UDP */
if (FD_ISSET(s_UDP, &readmask)) {
/* This call will block until a new
* request arrives. Then, it will
* return the address of the client,
* and a buffer containing its request.
* BUFFERSIZE - 1 bytes are read so that
* room is left at the end of the buffer
* for a null character.
*/
printmtof("ESPERO AL RECV_FROM",
"debug.txt");
cc = recvfrom(s_UDP, buffer, TAM_BUFFER - 1, 0,
(struct sockaddr *)&clientaddr_in, &addrlen);
if (cc == -1) {
perror(argv[0]);
printf("%s: recvfrom error\n", argv[0]);
exit (1);
}
printmtof("RECIBIDO AL RECV_FROM",
"debug.txt");
/* Make sure the message received is
* null terminated.
*/
buffer[cc]='\0';
switch (fork()) {
case -1: /* Can't fork, just exit. */
exit(1);
case 0: /* Child process comes here. */
close(s_UDP); /* Close the listen socket inherited from the daemon. */
memset ((char *)&myaddr_in, 0, sizeof(struct sockaddr_in));
memset ((char *)&servaddr_in, 0, sizeof(struct sockaddr_in));
myaddr_in.sin_family = AF_INET;
myaddr_in.sin_port = 0;
myaddr_in.sin_addr.s_addr = INADDR_ANY;
/* Create a new socket for the child. */
u_UDP = socket (AF_INET, SOCK_DGRAM, 0);
if (u_UDP == -1) {
perror(argv[0]);
printf("%s: unable to create child\'s UDP socket\n", argv[0]);
exit(1);
}
/* Bind the child's address to the socket. Configuration correctly
* inherited from father after fork
*/
if (bind(u_UDP, (struct sockaddr *) &myaddr_in, sizeof(struct sockaddr_in)) == -1) {
perror(argv[0]);
printf("%s: unable to bind address UDP\n", argv[0]);
exit(1);
}
addrlen = sizeof(struct sockaddr_in);
if (getsockname(u_UDP, (struct sockaddr *)&myaddr_in, &addrlen) == -1) {
perror(argv[0]);
fprintf(stderr, "%s: unable to read socket address\n", argv[0]);
exit(1);
}
servaddr_in.sin_family = AF_INET;
memset (&hints, 0, sizeof (hints));
hints.ai_family = AF_INET;
errcode = getaddrinfo ("localhost", NULL, &hints, &res);
if (errcode != 0){
fprintf(stderr, "%s: No es posible resolver la IP de %s\n",
argv[0], argv[1]);
exit(1);
} else {
servaddr_in.sin_addr = ((struct sockaddr_in *) res->ai_addr)->sin_addr;
}
freeaddrinfo(res);
serverUDP(u_UDP, buffer, clientaddr_in);
exit(0);
}
}/* De UDP */
}/* Fin if-else */
}/* Fin del bucle infinito de atención a clientes */
/* Cerramos los sockets UDP y TCP */
printmtof("Cierro la conexión", "debug.txt");
close(ls_TCP);
close(s_UDP);
printf("\nFin de programa servidor!\n");
default: /* Parent process comes here. */
exit(0);
}
}
/*
* S E R V E R T C P
*
* This is the actual server routine that the daemon forks to
* handle each individual connection. Its purpose is to receive
* the request packets from the remote client, process them,
* and return the results to the client. It will also write some
* logging information to stdout.
*
*/
void serverTCP(int s, struct sockaddr_in clientaddr_in)
{
/* Estas variables son para la gestion de los ficheros.
* Realmente habria que cambiarlas para trabajar con arrays dinamicos
* pero por ahora vamos a tener un unico fichero (y solo pa' leer)
*/
int nreadbytes = 0; /* Keeps the number of bytes read from file */
int nwrittenbytes = 0;
int rreqcnt = 1; /* Keeps count of read requests */
char filename[100];
//rw_msg_t rw_msg;
//data_msg_t *data_msg = NULL;
//data_msg_t data_msg_rcv;
//ack_msg_t ack_msg;
//ack_msg_t *ack_msg_send = NULL;
char str[1000];
short msg_type = 0;
FILE *ptr = NULL;
char last_block[3] = "00";//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
int lastblock = 0;
int eof_flag;
/*******************************************************************/
int reqcnt = 0; /* keeps count of number of requests */
char buf[TAM_BUFFER]; /* This example uses TAM_BUFFER byte messages. */
char hostname[MAXHOST]; /* remote host's name string */
int len, len1, status;
struct hostent *hp; /* pointer to host info for remote host */
long timevar; /* contains time returned by time() */
struct linger linger; /* allow a lingering, graceful close; */
/* used when setting SO_LINGER */
/* Look up the host information for the remote host
* that we have connected with. Its internet address
* was returned by the accept call, in the main
* daemon loop above.
*/
status = getnameinfo((struct sockaddr *)&clientaddr_in,sizeof(clientaddr_in),
hostname,MAXHOST,NULL,0,0);
if(status){
/* The information is unavailable for the remote
* host. Just format its internet address to be
* printed out in the logging information. The
* address will be shown in "internet dot format".
*/
/* inet_ntop para interoperatividad con IPv6 */
if (inet_ntop(AF_INET, &(clientaddr_in.sin_addr), hostname, MAXHOST) == NULL)
perror(" inet_ntop \n");
}
/* Log a startup message. */
time (&timevar);
/* The port number must be converted first to host byte
* order before printing. On most hosts, this is not
* necessary, but the ntohs() call is included here so
* that this program could easily be ported to a host
* that does require it.
*/
printf("Startup from %s port %u at %s",
hostname, ntohs(clientaddr_in.sin_port), (char *) ctime(&timevar));
/* Set the socket for a lingering, graceful close.
* This will cause a final close of this socket to wait until all of the
* data sent on it has been received by the remote host.
*/
linger.l_onoff =1;
linger.l_linger =1;
if (setsockopt(s, SOL_SOCKET, SO_LINGER, &linger,
sizeof(linger)) == -1) {
errout(hostname);
}
/* Go into a loop, receiving requests from the remote
* client. After the client has sent the last request,
* it will do a shutdown for sending, which will cause
* an end-of-file condition to appear on this end of the
* connection. After all of the client's requests have
* been received, the next recv call will return zero
* bytes, signalling an end-of-file condition. This is
* how the server will know that no more requests will
* follow, and the loop will be exited.
*/
while (len = recv(s, buf, TAM_BUFFER, 0)) {
if (len == -1) errout(hostname); /* error from recv */
/* The reason this while loop exists is that there
* is a remote possibility of the above recv returning
* less than TAM_BUFFER bytes. This is because a recv returns
* as soon as there is some data, and will not wait for
* all of the requested data to arrive. Since TAM_BUFFER bytes
* is relatively small compared to the allowed TCP
* packet sizes, a partial receive is unlikely. If
* this example had used 2048 bytes requests instead,
* a partial receive would be far more likely.
* This loop will keep receiving until all TAM_BUFFER bytes
* have been received, thus guaranteeing that the
* next recv at the top of the loop will start at
* the begining of the next request.
*/
while (len < TAM_BUFFER) {
len1 = recv(s, &buf[len], TAM_BUFFER-len, 0);
if (len1 == -1) errout(hostname);
len += len1;
}
if (buf[0] == '0' && buf[1] == '1') {
printmtof("EN R_REQUEST SERVERS\n",
"debug.txt");
strcpy(filename, buf + 2);
char *data;
data = calloc(1, TFTP_DATA_SIZE);
if ((lastblock = read_from_file(data, filename, nreadbytes)) == -1){
printmtof("servidor.c: serverTCP: READ_TYPE: error in read_from_file",
"debug.txt");
return;
}
int n_block = atoi("01");
char *data_msg = create_data_msg(n_block, data);
nreadbytes += TFTP_DATA_SIZE;
reqcnt++;
sleep(1);
if (send(s, data_msg, TAM_BUFFER, 0) != TAM_BUFFER) errout(hostname);
} else if (buf[0] == '0' && buf[1] == '2') {
printmtof("EN W_REQUEST SERVERS\n",
"debug.txt");
strcpy(filename, buf + 2);
char *ack_msg = create_ack_msg("00");
reqcnt++;
sleep(1);
if (send(s, ack_msg, TAM_BUFFER, 0) != TAM_BUFFER) errout(hostname);
} else if (buf[0] == '0' && buf[1] == '4') { //ACK
printmtof("EN ACK_TYPE SERVERS\n",
"debug.txt");
char nblock[3];
strncpy(nblock, buf + 2, 2);
nblock[2] = '\0';
char *data;
data = calloc(1, TFTP_DATA_SIZE);
if (('0' == last_block[0] && '0' != last_block[1]) && (nblock[0] == last_block[0] && nblock[1] == last_block[1])){
fprintf(stderr,"\nReached end of file\n\n");
goto END_OF_FILE;
}
/*
* Para el ACK X:
* 1- Enviar bloque X + 1
*/
if ((lastblock = read_from_file(data, filename, nreadbytes)) == -1){//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< &buf???
fprintf(stderr, "servidor.c: DATA_TYPE: error in read_from_file\n");
return;
}
if (lastblock == 1){
strncpy(last_block, buf + 2, 2);
last_block[2] = '\0';
}
printf("El buffer es %s\n", data);
int n_block = atoi(nblock);
char *data_msg = create_data_msg(n_block, data);
nreadbytes += TFTP_DATA_SIZE;
reqcnt++;
sleep(1);
if (send(s, data_msg, TAM_BUFFER, 0) != TAM_BUFFER) errout(hostname);
} else if (buf[0] == '0' && buf[1] == '3') { // DATA
printmtof("EN DATA_TYPE SERVERS\n",
"debug.txt");
char data[TFTP_DATA_SIZE + 1];
strcpy(data, buf + 5);
data[TFTP_DATA_SIZE] = '\0';
char nblock[3];
strncpy(nblock, buf + 2, 2);
nblock[2] = '\0';
int n_block = atoi(nblock);
/*
* Para el bloque X
* 1- Escribir DATA X
* 2- Mandar ACK (n = X)
*/
if (TFTP_DATA_SIZE == (sizeof(data) - 1)) { // DATA = 512 //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
if ((write_data_into_file(data, filename, nwrittenbytes)) == -1){
fprintf(stderr, "servidor.c: DATA_TYPE: error in write_data_into_file\n");
return;
}
char *ack_msg = create_ack_msg(nblock);
nwrittenbytes += TFTP_DATA_SIZE;
reqcnt++;
sleep(1);
if (send(s, ack_msg, TAM_BUFFER, 0) != TAM_BUFFER) errout(hostname);
} else if (TFTP_DATA_SIZE > (sizeof(data) - 1)) { // DATA < 512 //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
if ((write_data_into_file(data, filename, nwrittenbytes)) == -1){
fprintf(stderr, "servidor.c: DATA_TYPE: error in write_data_into_file\n");
return;
}
char *ack_msg = create_ack_msg(nblock);
nwrittenbytes += strlen(data);
reqcnt++;
sleep(1);
if (send(s, ack_msg, TAM_BUFFER, 0) != TAM_BUFFER) errout(hostname);
goto END_OF_FILE;
} else if (0 == sizeof(data)) { // DATA = 0
printf("Received block number %d\n", n_block);
char *ack_msg = create_ack_msg(nblock);
reqcnt++;
sleep(1);
if (send(s, ack_msg, TAM_BUFFER, 0) != TAM_BUFFER) errout(hostname);
goto END_OF_FILE;
}
} else {
printf("servidor: default: Invalid type of message\n");
return;
}
// Vamo a aserlo con 1 fixero
// Ya si eso luego bien (arrays dinamicos con structs para cada fichero)
/*
switch(msg_type) {
case READ_TYPE:
memcpy((void *)&rw_msg, (const void *)&buf, sizeof(rw_msg));
data_msg = create_data_msg(1);
if ((last_block = read_from_file(data_msg, rw_msg.filename, nreadbytes)) == -1){
printmtof("servidor.c: serverTCP: READ_TYPE: error in read_from_file",
"debug.txt");
return;
}
memcpy((void *)buf, (const void *)data_msg, sizeof(*data_msg));
strncpy(filename,(const char*) &(rw_msg.filename), sizeof(filename));
nreadbytes += TFTP_DATA_SIZE;
break;
case WRITE_TYPE:
memcpy((void *)&rw_msg, (const void *)&buf, sizeof(rw_msg));
strncpy(filename,(const char*) &(rw_msg.filename), sizeof(filename));
ack_msg_send = create_ack_msg(0);
memcpy((void *)buf, (const void *)ack_msg_send, sizeof(*ack_msg_send));
break;
case ACK_TYPE:
memcpy((void *)&ack_msg, (const void *)&buf, sizeof(ack_msg));
if (0 != last_block && last_block == ack_msg.n_block){
printmtof("GOTO ",
"debug.txt");
goto END_OF_FILE;
}
data_msg = create_data_msg(ack_msg.n_block + 1);
if ((last_block = read_from_file(data_msg, filename, nreadbytes)) == -1){
printmtof("servidor.c: serverTCP: ACK_TYPE: error in read_from_file",
"debug.txt");
return;
}
memcpy((void *)buf, (const void *)data_msg, sizeof(*data_msg));
nreadbytes += TFTP_DATA_SIZE;
break;
case DATA_TYPE:
memcpy((void *)&data_msg_rcv, (const void *)&buf, sizeof(data_msg_rcv));
if (TFTP_DATA_SIZE == strlen(data_msg_rcv.data)) {
if ((write_data_into_file(data_msg_rcv, filename, nwrittenbytes)) == -1){
printmtof("servidor.c: serverTCP: DATA_TYPE: data = 512: error in write_data_into_file",
"debug.txt");
return;
}
ack_msg_send = create_ack_msg(data_msg_rcv.n_block);
memcpy((void *)buf, (const void *)ack_msg_send, sizeof(*ack_msg_send));
nwrittenbytes += TFTP_DATA_SIZE;
} else if (TFTP_DATA_SIZE > strlen(data_msg_rcv.data)) {
if ((write_data_into_file(data_msg_rcv, filename, nwrittenbytes)) == -1){
printmtof("servidor.c: serverTCP: DATA_TYPE: data < 512: error in write_data_into_file",
"debug.txt");
return;
}
ack_msg_send = create_ack_msg(data_msg_rcv.n_block);
memcpy((void *)buf, (const void *)ack_msg_send, sizeof(*ack_msg_send));
nwrittenbytes += strlen(data_msg_rcv.data);
printmtof("GOTO menos que 52 ",
"debug.txt");
eof_flag = 1;
} else if (0 == strlen(data_msg_rcv.data)) {
ack_msg_send = create_ack_msg(data_msg_rcv.n_block);
memcpy((void *)buf, (const void *)ack_msg_send, sizeof(*ack_msg_send));
printmtof("GOTO igual a 0 ",
"debug.txt");
eof_flag = 1;
}
printmtof("Salgo de DataType",
"debug.txt");
break;
case ERROR_TYPE:
break;
default:
printmtof("servidor.c: serverTCP: default: invalid message type\n",
"debug.txt");
return;
break;
}
*/
}
END_OF_FILE:
close(s);
time (&timevar);
printf("Completed %s port %u, %d requests, at %s\n",
hostname, ntohs(clientaddr_in.sin_port), reqcnt, (char *) ctime(&timevar));
}
/*
* This routine aborts the child process attending the client.
*/
void errout(char *hostname)
{
printf("Connection with %s aborted on error\n", hostname);
exit(1);
}
/*
* S E R V E R U D P
*
* This is the actual server routine that the daemon forks to
* handle each individual connection. Its purpose is to receive
* the request packets from the remote client, process them,
* and return the results to the client. It will also write some
* logging information to stdout.
*
*/
void serverUDP(int s, char *buffer, struct sockaddr_in clientaddr_in)
{
struct in_addr reqaddr; /* for requested host's address */
struct hostent *hp; /* pointer to host info for requested host */
struct addrinfo hints, *res;
int nc, errcode;
int addrlen;
/* Estas variables son para la gestion de los ficheros.
* Realmente habria que cambiarlas para trabajar con arrays dinamicos
* pero por ahora vamos a tener un unico fichero (y solo pa' leer)
*/
static int nreadbytes = 0; /* Keeps the number of bytes read from file */
//static int nwrittenbytes = 0;
int rreqcnt = 1; /* Keeps count of read requests */
char filename[100];
//rw_msg_t rw_msg;
//data_msg_t *data_msg = NULL;
//data_msg_t data_msg_rcv;
//ack_msg_t ack_msg;
//ack_msg_t *ack_msg_send = NULL;
char str[1000];
//FILE *ptr = NULL;
static int last_block = 0;
int eof_flag;
int numbytes;
/*******************************************************************/
addrlen = sizeof(struct sockaddr_in);
// Vamo a aserlo con 1 fixero
// Ya si eso luego bien (arrays dinamicos con structs para cada fichero)
if (buffer[0] == '0' && buffer[1] == '1'){ // READ REQUEST
printmtof("ENTRO EN READ",
"debug.txt");
/*
* 1- Check if file exists
* + If it does not, error message and exit
* 2- Send file
* + Get file size
* + Loop until size is reached
* * fread() filtering by remaining size
* * Add \0 so that create_data_msg works fine
* * Create data packet and send
* * Wait for ACK (with a number of retries)
* > If timeout, try to resend
* * Increment block number
* + Close file
*/
FILE *ptr = NULL;
char filename[128];
strcpy(filename, buffer + 2);
printmtof("oh Bloody hell",
"debug.txt");
if ((ptr = fopen(filename, "r")) == NULL) {
perror("serverUDP: fopen");
// TODO <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Send error message
exit(1);
}
// Look for file size to see how much to read
int bytes_left;
fseek(ptr, 0, SEEK_END);
bytes_left = ftell(ptr);
fseek(ptr, 0, SEEK_SET);
int nblock = 1;
while (bytes_left > 0) {
char read_data[TFTP_DATA_SIZE + 1];
if (bytes_left > TFTP_DATA_SIZE) {
if (1 != fread(read_data, TFTP_DATA_SIZE, 1, ptr)){
// Print nice message
}
read_data[TFTP_DATA_SIZE] = '\0';
bytes_left -= TFTP_DATA_SIZE;
} else {
if (1 != fread(read_data, bytes_left, 1, ptr)){
// Print nice message
}
read_data[bytes_left] = '\0';
bytes_left = 0;
}
char *data_msg = create_data_msg(nblock, read_data);
if (numbytes = sendto(s, data_msg, strlen(data_msg), 0, (struct sockaddr *)&clientaddr_in, addrlen)){
// Print nice message
}
if (numbytes == -1 ) {
perror("serverUDP: Read Request: sendto");
exit(1);
}
int times;
for (times = 0; times <= 5; times++) {
if (times == 5){
printf("Server: Max number of Tries %d reached \n", times);
exit(1);
}
numbytes = wait_ack(s, buffer, clientaddr_in, addrlen);
if (numbytes == -1) { // ERROR
perror("serverUDP: recvfrom after check_timeout");
exit(1);
} else if (numbytes == -2) { // TIMEOUT
printf("ServerUDP: Nº %d of try \n", times + 1);
// TODO <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Send error message
continue;
} else { // MESSAGE RECEIVED
break;
}
}
++nblock;
}
fclose(ptr);
/*
printmtof("EN READ_TYPE",
"debug.txt");
memcpy((void *)&rw_msg, (const void *)buffer, sizeof(rw_msg));
data_msg = create_data_msg(1);
if ((last_block = read_from_file(data_msg, rw_msg.filename, nreadbytes)) == -1){
printmtof("servidor.c: serverUDP: READ_TYPE: error in read_from_file",
"debug.txt");
return-1;
}
memcpy(buffer, (const void *)data_msg, sizeof(*data_msg));
strncpy(filename,(const char*) &(rw_msg.filename), sizeof(filename));
nreadbytes += TFTP_DATA_SIZE;
*/
} else if (buffer[0] == '0' && buffer[1] == '2') { // WRITE REQUEST
/*
* 1- Sends ACK
* + If it does not, error message and exit
* 2- Send file
* + Get file size
* + Loop until size is reached
* * fread() filtering by remaining size
* * Add \0 so that create_data_msg works fine
* * Create data packet and send
* * Wait for ACK (with a number of retries)
* > If timeout, try to resend
* * Increment block number
* + Close file
*/
char *ack_msg = create_ack_msg("00"); // First is ACK 0
//char last_data_msg[TFTP_DATA_SIZE + 1];
//strcpy(last_data_msg, buffer);
//char last_ack_msg[10];
//strcpy(last_ack_msg, ack_msg);
printmtof("Fuck this shit , I