-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTFTPCE.c
956 lines (825 loc) · 26.1 KB
/
TFTPCE.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
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
946
947
948
949
950
951
952
953
// TFTPCE.cpp : Defines the entry point for the console application.
//
#include <windows.h>
//#include <commctrl.h>
/**********************************************************
Date: OCT 28th, 2006
Project : NET4900 Project: tftpd.c TFTP Server
Programers:
Craig Holmes
Reza Rahmanian
File: TFTP Server (main)
Purpose: A TFTP server that will accept a connections from
a client and transefet files.
Notes: Here we are using the sendto and recvfrom
functions so the server and client can exchange data.
***********************************************************************/
//original source avaliable http://tftp.sourceforge.net/
/* Include our header which contains libaries and defines */
#include "tftp.h"
/* Function prototypes */
void tsend (char *, struct sockaddr_in, char *, int);
void tget (char *, struct sockaddr_in, char *, int);
int isnotvaliddir (char *);
void usage (void);
/* default values which can be controlled by command line */
int debug = 0;
char path[64] = "\\";
int port = 69;
unsigned short int ackfreq = 1;
int datasize = 512;
/* global variables */
struct sockaddr_in server, client; /*the address structure for both the server and client */
WSADATA wsaData;
int g_quit=0;
int i;
int error_number = 0;
extern char *optsarg;
int sock = 0;
int n, client_len, pid, opt, tid;
char opcode, *bufindex, filename[196], mode[12];
unsigned long nonblocking = 1; /* Flag to make socket nonblocking */
DWORD WINAPI WaitingForConnectionThread(LPVOID args)
{
int set[2];
/*endless loop to get connections from the client */
while (g_quit == 0)
{
if (sock!=0)
closesocket(sock);
/*Create the socket, a -1 will show us an error */
if ((sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
{
printf ("Server Socket could not be created");
return 0;
}
/*set the address values for the server */
server.sin_family = AF_INET; /*address family for TCP and UDP */
server.sin_addr.s_addr = htonl (INADDR_ANY); /*use any address */
server.sin_port = htons (port); /*pick a free port */
FD_ZERO(set);
FD_SET(sock,set) ;
/*Bind the socket */
if (bind (sock, (struct sockaddr *) &server, sizeof (server)) < 0)
{
printf ("Server bind failed. Server already running? Proper permissions?\n");
error_number = 2;
goto quit;
}
//if (!debug)
//{
// //pid = fork ();
// pid = 0;
// if (pid != 0) /* if pid != 0 then we are the parent */
// {
// if (pid == -1)
// {
// printf ("Error: Fork failed!\n");
// error_number = 0;
// goto quit;
// }
// else
// {
// printf ("Daemon Successfully forked (pid: %d)\n", pid);
// error_number = 1;
// goto quit;
// }
// }
//}
//else
//{
printf ("Server is bound to port %d and awaiting connections\nfile path: %s\n",
ntohs (server.sin_port), path);
//}
client_len = sizeof (client); /*get the length of the client */
memset (buf, 0, BUFSIZ); /*clear the buffer */
/*the fs message */
n = -1;
/* Set the socket to nonblocking */
if (ioctlsocket(sock, FIONBIO, &nonblocking) != 0)
{
printf("ioctlsocket() failed");
goto quit;
}
while (n < 0) /* This loop is required because on linux we have to acknowledge complete children with waitpid. Ugh. */
{
//waitpid (-1, &status, WNOHANG);
n =
recvfrom (sock, buf, BUFSIZ, MSG_DONTWAIT,
(struct sockaddr *) &client,
(socklen_t *) & client_len);
if (g_quit==1)
{
printf ("Quit Requested\n");
error_number = 10;
goto quit;
}
if ((n < 0) && (errno != WSAEWOULDBLOCK))
{
printf ("The server could not receive from the client");
error_number = 0;
goto quit;
}
//printf ("usleep\n");
usleep (100);
}
if (debug)
printf ("Connection from %s, port %d\n",
inet_ntoa (client.sin_addr), ntohs (client.sin_port));
bufindex = buf; //start our pointer going
if (bufindex++[0] != 0x00)
{ //first TFTP packet byte needs to be null. Once the value is taken increment it.
if (debug)
printf ("Malformed tftp packet.\n");
return 0;
}
tid = ntohs (client.sin_port); /* record the tid */
opcode = *bufindex++; //opcode is in the second byte.
if (opcode == 1 || opcode == 2) // RRQ or WRQ. The only two really valid packets on port 69
{
strncpy (filename, bufindex, sizeof (filename) - 1); /* Our pointer has been nudged along the recieved string so the first char is the beginning of the filename. This filename is null deliimited so we can use the str family of functions */
bufindex += strlen (filename) + 1; /* move the pointer to after the filename + null byte in the string */
strncpy (mode, bufindex, sizeof (mode) - 1); /* like the filename, we are at the beginning of the null delimited mode */
bufindex += strlen (mode) + 1; /* move pointer... */
if (debug)
printf ("opcode: %x filename: %s packet size: %d mode: %s\n", opcode, filename, n, mode); /*show the message to the server */
}
else
{
if (debug)
printf ("opcode: %x size: %d \n", opcode, sizeof (n)); /*show the message to the server */
}
switch (opcode) /* case one and two are valid on port 69 or server port... no other codes are */
{
case 1:
if (debug)
{
printf ("Opcode indicates file read request\n");
tsend (filename, client, mode, tid);
}
else
{
// pid = fork ();
pid = 0;
if (pid == 0)
{ /* if we are pid != 0 then we are the parent */
tsend (filename, client, mode, tid);
error_number = 1;
goto quit;
}
}
break;
case 2:
if (debug)
{
printf ("Opcode indicates file write request\n");
tget (filename, client, mode, tid);
}
else
{
// pid = fork ();
pid = 0;
if (pid == 0) /* if we are pid != 0 then we are the parent */
{
tget (filename, client, mode, tid);
//exit (1);
}
}
break;
default:
if (debug)
printf ("Invalid opcode detected. Ignoring packet.");
break;
} //end of switch
} //end of while
quit:
printf("Waiting Thread finished");
return error_number;
}
int _tmain(int argc, _TCHAR* argv[])
{
/*local variables */
char **argvA;
HANDLE hWaitingThread;
DWORD threadId;
argvA = (char**)malloc(argc*sizeof(char*));
for (i=0;i<argc;i++)
{
argvA[i] = malloc (_tcslen(argv[i])+1);
wcstombs(argvA[i],argv[i],MAX_PATH);
}
/* All of the following deals with command line switches */
//while ((opt = getopt (argc, argv, "dh:p:P:a:s:")) != -1) /* this function is handy */
while ((opt = optsopt (argc, argvA, "dh:p:P:a:s:")) != -1) /* this function is handy */
{
switch (opt)
{
case 'p': /* path (opt required) */
if (!isnotvaliddir (optsarg))
{
printf
("Sorry, you specified an invalid/non-existant directory. Make sure the directory exists.\n");
return 0;
}
strncpy (path, optsarg, sizeof (path) - 1);
break;
case 'd': /* debug mode (no opts) */
debug = 1;
break;
case 'P': /* Port (opt required) */
port = atoi (optsarg);
break;
case 'a': /* ack frequency (opt required) */
ackfreq = atoi (optsarg);
if (ackfreq > MAXACKFREQ)
{
printf
("Sorry, you specified an ack frequency higher than the maximum allowed (Requested: %d Max: %d)\n",
ackfreq, MAXACKFREQ);
return 0;
}
else if (ackfreq == 0)
{
printf ("Sorry, you have to ack sometime.\n");
return 0;
}
break;
case 's': /* File chunk size (opt required) */
datasize = atoi (optsarg);
if (datasize > MAXDATASIZE)
{
printf
("Sorry, you specified a data size higher than the maximum allowed (Requested: %d Max: %d)\n",
datasize, MAXDATASIZE);
return 0;
}
break;
case 'h': /* Help (no opts) */
usage ();
return (0);
break;
default: /* everything else */
usage ();
return (0);
break;
}
}
/* Done dealing with switches */
WSAStartup(MAKEWORD( 2, 2 ),&wsaData);
hWaitingThread = CreateThread(NULL,
0,
WaitingForConnectionThread,
NULL,
0,
&threadId);
getchar();
g_quit = 1;
closesocket(socket);
WaitForSingleObject(hWaitingThread,INFINITE);
WSACleanup();
for (i=0;i<argc;i++)
{
free(argvA[i]);
argvA[i]=NULL;
}
free(argvA);
argvA=NULL;
WSACleanup();
}
void
tget (char *pFilename, struct sockaddr_in client, char *pMode, int tid)
{
/* local variables */
int sock, len, client_len, opcode, i, j, n, flag = 1;
unsigned short int count = 0, rcount = 0;
unsigned char filebuf[MAXDATASIZE + 1];
unsigned char packetbuf[MAXDATASIZE + 12];
//extern int errno;
char filename[128], mode[12], fullpath[196], *bufindex, ackbuf[512];
struct sockaddr_in data;
FILE *fp; /* pointer to the file we will be getting */
strcpy (filename, pFilename); //copy the pointer to the filename into a real array
strcpy (mode, pMode); //same as above
if (debug)
printf ("branched to file receive function\n");
if ((sock = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) //startup a socket
{
printf ("Server reconnect for getting did not work correctly\n");
return;
}
if (!strncmp (mode, "octet", 5) && !strncmp (mode, "netascii", 8)) /* these two are the only modes we accept */
{
if (!strncmp (mode, "mail", 4))
len = sprintf ((char *) packetbuf,
"%c%c%c%cThis tftp server will not operate as a mail relay%c",
0x00, 0x05, 0x00, 0x04, 0x00);
else
len = sprintf ((char *) packetbuf,
"%c%c%c%cUnrecognized mode (%s)%c",
0x00, 0x05, 0x00, 0x04, mode, 0x00);
if (sendto (sock, packetbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */
{
printf
("Mismatch in number of sent bytes while trying to send mode error packet\n");
}
return;
}
/*
if (strchr (filename, 0x5C) || strchr (filename, 0x2F)) //look for illegal characters in the filename string these are \ and /
{
if (debug)
printf ("Client requested to upload bad file: forbidden name\n");
len =
sprintf ((char *) packetbuf,
"%c%c%c%cIllegal filename.(%s) You may not attempt to descend or ascend directories.%c",
0x00, 0x05, 0x00, 0x00, filename, 0x00);
if (sendto (sock, packetbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) // send the data packet
{
printf
("Mismatch in number of sent bytes while trying to send error packet\n");
}
return;
}
*/
strcpy (fullpath, path);
strncat (fullpath, filename, sizeof (fullpath) - 1); //build the full file path by appending filename to path
fp = fopen (fullpath, "wb"); /* open the file for writing */
if (fp == NULL)
{ //if the pointer is null then the file can't be opened - Bad perms
if (debug)
printf ("Server requested bad file: cannot open for writing (%s)\n",
fullpath);
len =
sprintf ((char *) packetbuf,
"%c%c%c%cFile cannot be opened for writing (%s)%c", 0x00,
0x05, 0x00, 0x02, fullpath, 0x00);
if (sendto (sock, packetbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */
{
printf
("Mismatch in number of sent bytes while trying to send error packet\n");
}
return;
}
else /* everything worked fine */
{
if (debug)
printf ("Getting file... (destination: %s) \n", fullpath);
}
/* zero the buffer before we begin */
memset (filebuf, 0, sizeof (filebuf));
n = datasize + 4;
do
{
/* zero buffers so if there are any errors only NULLs will be exposed */
memset (packetbuf, 0, sizeof (packetbuf));
memset (ackbuf, 0, sizeof (ackbuf));
if (debug)
printf ("== just entered do-while count: %d n: %d\n", count, n);
if (count == 0 || (count % ackfreq) == 0 || n != (datasize + 4)) /* ack the first packet, count % ackfreq will make it so we only ACK everyone ackfreq ACKs, ack the last packet */
{
len = sprintf (ackbuf, "%c%c%c%c", 0x00, 0x04, 0x00, 0x00);
ackbuf[2] = (count & 0xFF00) >> 8; //fill in the count (top number first)
ackbuf[3] = (count & 0x00FF); //fill in the lower part of the count
if (debug)
printf ("Sending ack # %04d (length: %d)\n", count, len);
if (sendto
(sock, ackbuf, len, 0, (struct sockaddr *) &client,
sizeof (client)) != len)
{
if (debug)
printf ("Mismatch in number of sent bytes\n");
return;
}
}
else if (debug)
{
printf ("No ack required on packet count %d\n", count);
}
if (n != (datasize + 4)) /* remember if our datasize is less than a full packet this was the last packet to be received */
{
if (debug)
printf
("Last chunk detected (file chunk size: %d). exiting while loop\n",
n - 4);
goto done; /* gotos are not optimal, but a good solution when exiting a multi-layer loop */
}
memset (filebuf, 0, sizeof (filebuf));
count++;
for (j = 0; j < RETRIES; j++) /* this allows us to loop until we either break out by getting the correct ack OR time out because we've looped more than RETRIES times */
{
client_len = sizeof (data);
// errno = EAGAIN; /* this allows us to enter the loop */
n = -1;
//for (i = 0; errno == EAGAIN && i <= TIMEOUT && n < 0; i++) /* this for loop will just keep checking the non-blocking socket until timeout */
i=0;
do
{
n =
recvfrom (sock, packetbuf, sizeof (packetbuf) - 1,
MSG_DONTWAIT, (struct sockaddr *) &data,
(socklen_t *) & client_len);
/*if (debug)
printf ("The value recieved is n: %d\n",n); */
//usleep (1000);
//usleep (10);
//usleep (1);
i++;
}
while((errno == EAGAIN) && (i <= TIMEOUT) && (n < 0));
if ((n < 0) && (errno != EAGAIN)) /* this will be true when there is an error that isn't the WOULD BLOCK error */
{
if (debug)
printf
("The server could not receive from the client (errno: %d n: %d)\n",
errno, n);
//resend packet
}
else if ((n < 0) && (errno == EAGAIN)) /* this is true when the error IS would block. This means we timed out */
{
if (debug)
printf ("Timeout waiting for data (errno: %d == %d n: %d)\n",
errno, EAGAIN, n);
//resend packet
}
else
{
if (client.sin_addr.s_addr != data.sin_addr.s_addr) /* checks to ensure get from ip is same from ACK IP */
{
if (debug)
printf
("Error recieving file (data from invalid address)\n");
j--;
continue; /* we aren't going to let another connection spoil our first connection */
}
if (tid != ntohs (client.sin_port)) /* checks to ensure get from the correct TID */
{
if (debug)
printf ("Error recieving file (data from invalid tid)\n");
len = sprintf ((char *) packetbuf,
"%c%c%c%cBad/Unknown TID%c",
0x00, 0x05, 0x00, 0x05, 0x00);
if (sendto (sock, packetbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */
{
printf
("Mismatch in number of sent bytes while trying to send mode error packet\n");
}
j--;
continue; /* we aren't going to let another connection spoil our first connection */
}
/* this formatting code is just like the code in the main function */
bufindex = (char *) packetbuf; //start our pointer going
if (bufindex++[0] != 0x00)
printf ("bad first nullbyte!\n");
opcode = *bufindex++;
rcount = *bufindex++ << 8;
rcount &= 0xff00;
rcount += (*bufindex++ & 0x00ff);
memcpy ((char *) filebuf, bufindex, n - 4); /* copy the rest of the packet (data portion) into our data array */
if (debug)
printf
("Remote host sent data packet #%d (Opcode: %d packetsize: %d filechunksize: %d)\n",
rcount, opcode, n, n - 4);
if (flag)
{
if (n > 516)
datasize = n - 4;
flag = 0;
}
if (opcode != 3 || rcount != count) /* ack packet should have code 3 (data) and should be ack+1 the packet we just sent */
{
if (debug)
printf
("Badly ordered/invalid data packet (Got OP: %d Block: %d) (Wanted Op: 3 Block: %d)\n",
opcode, rcount, count);
/* sending error message */
if (opcode > 5)
{
len = sprintf ((char *) packetbuf,
"%c%c%c%cIllegal operation%c",
0x00, 0x05, 0x00, 0x04, 0x00);
if (sendto (sock, packetbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */
{
printf
("Mismatch in number of sent bytes while trying to send mode error packet\n");
}
}
}
else
{
break;
}
}
if (sendto
(sock, ackbuf, len, 0, (struct sockaddr *) &client,
sizeof (client)) != len)
{
if (debug)
printf ("Mismatch in number of sent bytes\n");
return;
}
}
if (j == RETRIES)
{
if (debug)
printf ("Data recieve Timeout. Aborting transfer\n");
fclose (fp);
return;
}
}
while (fwrite (filebuf, 1, n - 4, fp) == n - 4); /* if it doesn't write the file the length of the packet received less 4 then it didn't work */
fclose (fp);
//sync ();
if (debug)
printf ("fclose and sync successful. File failed to recieve properly\n");
return;
done:
fclose (fp);
//sync ();
if (debug)
printf ("fclose and sync successful. File received successfully\n");
printf("Received file %s\n",fullpath);
return;
}
void
tsend (char *pFilename, struct sockaddr_in client, char *pMode, int tid)
{
int sock, len, client_len, opcode, ssize = 0, n, i, j, bcount = 0;
unsigned short int count = 0, rcount = 0, acked = 0;
unsigned char filebuf[MAXDATASIZE + 1];
unsigned char packetbuf[MAXACKFREQ][MAXDATASIZE + 12],
recvbuf[MAXDATASIZE + 12];
char filename[128], mode[12], fullpath[196], *bufindex;
struct sockaddr_in ack;
FILE *fp; /* pointer to the file we will be sending */
strcpy (filename, pFilename); //copy the pointer to the filename into a real array
strcpy (mode, pMode); //same as above
if (debug)
printf ("branched to file send function\n");
if ((sock = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) //startup a socket
{
printf ("Server reconnect for sending did not work correctly\n");
return;
}
if (!strncmp (mode, "octet", 5) && !strncmp (mode, "netascii", 8)) /* these two are the only modes we accept */
{
if (!strncmp (mode, "mail", 4))
len = sprintf ((char *) packetbuf[0],
"%c%c%c%cThis tftp server will not operate as a mail relay%c",
0x00, 0x05, 0x00, 0x04, 0x00);
else
len = sprintf ((char *) packetbuf[0],
"%c%c%c%cUnrecognized mode (%s)%c",
0x00, 0x05, 0x00, 0x04, mode, 0x00);
if (sendto (sock, packetbuf[0], len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */
{
printf
("Mismatch in number of sent bytes while trying to send mode error packet\n");
}
return;
}
if (strchr (filename, 0x5C) || strchr (filename, 0x2F)) //look for illegal characters in the filename string these are \ and /
{
if (debug)
printf ("Server requested bad file: forbidden name\n");
len =
sprintf ((char *) packetbuf[0],
"%c%c%c%cIllegal filename.(%s) You may not attempt to descend or ascend directories.%c",
0x00, 0x05, 0x00, 0x00, filename, 0x00);
if (sendto (sock, packetbuf[0], len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */
{
printf
("Mismatch in number of sent bytes while trying to send error packet\n");
}
return;
}
strcpy (fullpath, path);
strncat (fullpath, filename, sizeof (fullpath) - 1); //build the full file path by appending filename to path
fp = fopen (fullpath, "rb");
if (fp == NULL)
{ //if the pointer is null then the file can't be opened - Bad perms OR no such file
if (debug)
printf ("Server requested bad file: file not found (%s)\n", fullpath);
len =
sprintf ((char *) packetbuf[0], "%c%c%c%cFile not found (%s)%c", 0x00,
0x05, 0x00, 0x01, fullpath, 0x00);
if (sendto (sock, packetbuf[0], len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */
{
printf
("Mismatch in number of sent bytes while trying to send error packet\n");
}
return;
}
else
{
if (debug)
printf ("Sending file... (source: %s)\n", fullpath);
}
memset (filebuf, 0, sizeof (filebuf));
while (1) /* our break statement will escape us when we are done */
{
acked = 0;
ssize = fread (filebuf, 1, datasize, fp);
count++; /* count number of datasize byte portions we read from the file */
if (count == 1) /* we always look for an ack on the FIRST packet */
bcount = 0;
else if (count == 2) /* The second packet will always start our counter at zreo. This special case needs to exist to avoid a DBZ when count = 2 - 2 = 0 */
bcount = 0;
else
bcount = (count - 2) % ackfreq;
sprintf ((char *) packetbuf[bcount], "%c%c%c%c", 0x00, 0x03, 0x00, 0x00); /* build data packet but write out the count as zero */
memcpy ((char *) packetbuf[bcount] + 4, filebuf, ssize);
len = 4 + ssize;
packetbuf[bcount][2] = (count & 0xFF00) >> 8; //fill in the count (top number first)
packetbuf[bcount][3] = (count & 0x00FF); //fill in the lower part of the count
if (debug)
printf ("Sending packet # %04d (length: %d file chunk: %d)\n",
count, len, ssize);
if (sendto (sock, packetbuf[bcount], len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */
{
if (debug)
printf ("Mismatch in number of sent bytes\n");
return;
}
if ((count - 1) == 0 || ((count - 1) % ackfreq) == 0
|| ssize != datasize)
{
/* The following 'for' loop is used to recieve/timeout ACKs */
for (j = 0; j < RETRIES; j++)
{
client_len = sizeof (ack);
//errno = EAGAIN;
n = -1;
//for (i = 0; errno == EAGAIN && i <= TIMEOUT && n < 0; i++)
i=0;
do
{
n =
recvfrom (sock, recvbuf, sizeof (recvbuf), MSG_DONTWAIT,
(struct sockaddr *) &ack,
(socklen_t *) & client_len);
usleep (1000);
i++;
}
while ((errno == EAGAIN) && (i <= TIMEOUT) && (n < 0));
if ((n < 0) && (errno != EAGAIN))
{
if (debug)
printf
("The server could not receive from the client (errno: %d n: %d)\n",
errno, n);
//resend packet
}
else if ((n < 0) && (errno == EAGAIN))
{
if (debug)
printf ("Timeout waiting for ack (errno: %d n: %d)\n",
errno, n);
//resend packet
}
else
{
if (client.sin_addr.s_addr != ack.sin_addr.s_addr) /* checks to ensure send to ip is same from ACK IP */
{
if (debug)
printf
("Error recieving ACK (ACK from invalid address)\n");
j--; /* in this case someone else connected to our port. Ignore this fact and retry getting the ack */
continue;
}
if (tid != ntohs (client.sin_port)) /* checks to ensure get from the correct TID */
{
if (debug)
printf
("Error recieving file (data from invalid tid)\n");
len =
sprintf ((char *) recvbuf,
"%c%c%c%cBad/Unknown TID%c", 0x00, 0x05,
0x00, 0x05, 0x00);
if (sendto (sock, recvbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */
{
printf
("Mismatch in number of sent bytes while trying to send mode error packet\n");
}
j--;
continue; /* we aren't going to let another connection spoil our first connection */
}
/* this formatting code is just like the code in the main function */
bufindex = (char *) recvbuf; //start our pointer going
if (bufindex++[0] != 0x00)
printf ("bad first nullbyte!\n");
opcode = *bufindex++;
rcount = *bufindex++ << 8;
rcount &= 0xff00;
rcount += (*bufindex++ & 0x00ff);
if (opcode != 4 || rcount != count) /* ack packet should have code 4 (ack) and should be acking the packet we just sent */
{
if (debug)
printf
("Remote host failed to ACK proper data packet # %d (got OP: %d Block: %d)\n",
count, opcode, rcount);
/* sending error message */
if (opcode > 5)
{
len = sprintf ((char *) recvbuf,
"%c%c%c%cIllegal operation%c",
0x00, 0x05, 0x00, 0x04, 0x00);
if (sendto (sock, recvbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */
{
printf
("Mismatch in number of sent bytes while trying to send mode error packet\n");
}
}
/* from here we will loop back and resend */
}
else
{
if (debug)
printf ("Remote host successfully ACK'd (#%d)\n",
rcount);
break;
}
}
for (i = 0; i <= bcount; i++)
{
if (sendto (sock, packetbuf[i], len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* resend the data packet */
{
if (debug)
printf ("Mismatch in number of sent bytes\n");
return;
}
if (debug)
printf ("Ack(s) lost. Resending: %d\n",
count - bcount + i);
}
if (debug)
printf ("Ack(s) lost. Resending complete.\n");
}
/* The ack sending 'for' loop ends here */
}
else if (debug)
{
printf ("Not attempting to recieve ack. Not required. count: %d\n",
count);
n = recvfrom (sock, recvbuf, sizeof (recvbuf), MSG_DONTWAIT, (struct sockaddr *) &ack, (socklen_t *) & client_len); /* just do a quick check incase the remote host is trying with ackfreq = 1 */
}
if (j == RETRIES)
{
if (debug)
printf ("Ack Timeout. Aborting transfer\n");
fclose (fp);
return;
}
if (ssize != datasize)
break;
memset (filebuf, 0, sizeof (filebuf)); /* fill the filebuf with zeros so that when the fread fills it, it is a null terminated string */
}
fclose (fp);
if (debug)
printf ("File sent successfully\n");
return;
}
int
isnotvaliddir (char *pPath) /* this function just makes sure that the directory passed to the server is valid and adds a trailing slash if not present */
{
TCHAR pPathA[MAX_PATH];
mbstowcs(pPathA,pPath,MAX_PATH);
if ((GetFileAttributes(pPathA) & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
{
int len;
len = strlen (pPath);
if (pPath[len - 1] != '\\')
{
pPath[len] = '\\';
pPath[len + 1] = 0;
}
return 1;
}
return 0;
#if 0
DIR *dp;
int len;
dp = opendir (pPath);
if (dp == NULL)
{
return (0);
}
else
{
len = strlen (pPath);
closedir (dp);
if (pPath[len - 1] != '/')
{
pPath[len] = '/';
pPath[len + 1] = 0;
}
return (1);
}
#endif
}
void
usage (void) /* prints program usage */
{
printf
("Usage: tftpd [options] [path]\nOptions:\n-d (debug mode)\n-h (help; this message)\n-P <port>\n-a <ack freqency. Default 1>\n-s <data chunk size in bytes. Default 512>\n");
return;
}