Code:
/*
* Receive a file.
*/
void
recvfile(int fd, char *name, char *mode)
{
register struct tftphdr *ap;
struct tftphdr *dp;
volatile int size = 0;
volatile u_int16_t block = 1;
int n;
volatile unsigned long amount = 0;
struct sockaddr_in from;
socklen_t fromlen;
volatile int firsttrip = 1;
FILE *file;
volatile int convert; /* true if converting crlf -> lf */
size_t len=0, nBufSize=0;
char *testimg = NULL;
startclock();
dp = w_init();
ap = (struct tftphdr *)ackbuf;
file = fdopen(fd, "w");
convert = !strcmp(mode, "netascii");
nBufSize = 8917016;
nBufSize = ((nBufSize / WSTLIB_FTP_ALLOC_UPG_SIZE) + 1) * WSTLIB_FTP_ALLOC_UPG_SIZE;
testimg = (char *)malloc(nBufSize);
if ( !testimg )
{
printf("FtpLib: no memory\n");
return ;
}
mysignal(SIGALRM, timer);
do {
if (firsttrip) {
size = makerequest(RRQ, name, ap, mode);
firsttrip = 0;
} else {
ap->th_opcode = htons((u_short)ACK);
ap->th_block = htons((u_short)(block));
size = 4;
block++;
}
timeout = 0;
(void) sigsetjmp(timeoutbuf, 1);
send_ack:
if (trace)
tpacket("sent", ap, size);
if (sendto(f, ackbuf, size, 0, (struct sockaddr *)&s_inn,
sizeof (s_inn)) != size) {
alarm(0);
perror("tftp: sendto");
goto abort;
}
write_behind(file, convert);
for ( ; ; ) {
alarm(rexmtval);
do {
fromlen = sizeof (from);
n = recvfrom(f, dp, PKTSIZE, 0,
(struct sockaddr *)&from, &fromlen);
} while (n <= 0);
alarm(0);
if (n < 0) {
perror("tftp: recvfrom");
goto abort;
}
s_inn.sin_port = from.sin_port; /* added */
if (trace)
tpacket("received", dp, n);
/* should verify client address */
dp->th_opcode = ntohs(dp->th_opcode);
dp->th_block = ntohs(dp->th_block);
if (dp->th_opcode == ERROR) {
printf("Error code %d: %s\n", dp->th_code,
dp->th_msg);
goto abort;
}
if (dp->th_opcode == DATA) {
volatile int j = 0;
if (dp->th_block == block) {
break; /* have next packet */
}
/* On an error, try to synchronize
* both sides.
*/
j = synchnet(f);
if (j && trace) {
printf("discarded %d packets\n", j);
}
if (dp->th_block == (block-1)) {
goto send_ack; /* resend ack */
}
}
}
/* size = write(fd, dp->th_data, n - 4); */
/* printf(" data %s \n",dp->th_data);*/
/* size = writeit(file, &dp, n - 4, convert);*/
/* changed code for my requirement */
if((n-4) > 0)
{
len = len + n;
if(n == nBufSize)
{
nBufSize = WSTLIB_FTP_ALLOC_UPG_SIZE / 2;
testimg =(int *)realloc(testimg, len + nBufSize);
if (testimg == NULL)
{
printf("FtpLib: no memory\n");
return;
}
}
else
nBufSize -= n;
strncat(testimg,dp->th_data,n-4);
printf("total img %s",testimg);
}
/* changed code for my requirement */
if (size < 0) {
nak(errno + 100);
break;
}
amount += size;
} while (size == SEGSIZE);
abort: /* ok to ack, since user */
ap->th_opcode = htons((u_short)ACK); /* has seen err msg */
ap->th_block = htons((u_short)block);
(void) sendto(f, ackbuf, 4, 0, (struct sockaddr *)&s_inn, sizeof(s_inn));
write_behind(file, convert); /* flush last buffer */
fclose(file);
stopclock();
if (amount > 0)
printstats("Received", amount);
}