Beispiel #1
0
int ParseToken(HttpState* state, int *bytesRead)
{
	int i;
	int retval;
	int len;
	for (i = 0; i < (sizeof(FORMSpec)/sizeof(FORMType)); i++) {
		if (!strcmp(FORMSpec[i].name, state->buffer)) {
			parsePtr = FORMSpec[i].value;
			len = 0;
			retval = sock_fastread(&state->s, parsePtr, 1);
			while ((*bytesRead < (state->content_length - 2)) &&
			       (tcp_tick(&state->s) != 0) &&
			       (*parsePtr != '&')) {
				if (retval != 0) {
					(*bytesRead)++;
					if (len < (FORMSpec[i].len - 1)) {
						parsePtr++;
						len++;
					}
				}
				retval = sock_fastread(&state->s, parsePtr, 1);
			}
			*parsePtr = '\0';
		}
		if (i < (sizeof(FORMSpec)/sizeof(FORMType) - 1) && (tcp_tick(&state->s) == 0)) {
			return -1;
		}
	}
	return 1;
}
Beispiel #2
0
/*
 * Receive a message.  The socket is re-opened and message read.  The need
 * for a response is indicated.  tcp_tick() fails if peer closed socket.
 */
void RecvMessage(tcp_Socket* tcpSock, int* respond)
{
	auto char buffer[500];
	auto int numBytes;

	tcp_listen(tcpSock, PORT, 0, 0, NULL, 0);
	dispClear();

	/* Wait for connection. */
	while( ! tcp_established( tcpSock ) ) {
		if( ! tcp_tick( (sock_type *) tcpSock ) ) {
			dispPrintf( "ERROR: listening: %s\n", tcpSock->err_msg );
			exit( 99 );
		}
	}

	/*  Wait for some data to appear, or an error... */
	while( 0 == (numBytes = sock_fastread(tcpSock, buffer, sizeof(buffer))) ) {
		if( ! tcp_tick( tcpSock ) ) {
	bad_read:
			dispPrintf( "ERROR: read: %s\n", tcpSock->err_msg );
			exit( 99 );
		}
	}
	if (numBytes == -1) {
		goto bad_read;
	}

	buffer[numBytes] = '\0';
	dispPrintf("%s", buffer);
	*respond = 1;	// Indicate the need for a response

}   /* end RecvMessage() */
Beispiel #3
0
static int udpdom( byte dtype, unpacker_funct unpacker, void *data )
{
    int i,uret;

    uret = sock_fastread((sock_type*)dom_sock, (byte*)question, sizeof(struct useek ));
    /* this does not happen */
    if (uret < 0) {
	/*		netputevent(USERCLASS,DOMFAIL,-1);  */
   return(0);  /* ?? why'd I change this? -md */
//	return(-1);
    }

 /* num = intel16(question->h.ident); */     /* get machine number */
/*
 *  check to see if the necessary information was in the UDP response
 */

    i = (int) ddextract(question, dtype, unpacker, data);
    switch (i) {
        case 0: return(1); /* we got a response */
        case 3:	return(0);		/* name does not exist */
        case -1:return( 0 );		/* strange return code from ddextract */
	default:return( 0 );            /* dunno */
    }
}
Beispiel #4
0
/*
 * Parse the url-encoded POST data into the FORMSpec struct
 * (ie: parse 'foo=bar&baz=qux' into the struct).  Return -1
 * on error.
 */
int ParsePost(HttpState* state)
{
	int retval;
	int bytesRead;

	bytesRead = 0;

	while ((bytesRead < (state->content_length - 2)) && (tcp_tick(&state->s) != 0)) {
		retval = sock_fastread(&state->s, state->p, 1);

		if (retval != 0) {
			bytesRead++;
			if (*state->p == '=') {
				*state->p = '\0';
				state->p = state->buffer;
				if (ParseToken(state, &bytesRead) == -1) {
					return -1;
				}
			} else {
				state->p++;
			}
		}
	}
	if (bytesRead == (state->content_length - 2)) {
		return 1;
	} else {
		return -1;
	}
}
Beispiel #5
0
void main()
{
	int bytes_read;
	char	buffer[100]; 	/* Currently (DC 7.30), printf() has max 127 bytes it can output. */
	tcp_Socket socket;
	
	sock_init();
	
	while(1) {
		tcp_listen(&socket,PORT,0,0,NULL,0);

		printf("Waiting for connection...\n");
		while(!sock_established(&socket) && sock_bytesready(&socket)==-1)
			tcp_tick(NULL);

		printf("Connection received...\n");

		do {
			bytes_read=sock_fastread(&socket,buffer,sizeof(buffer)-1);

			if(bytes_read>0) {
				buffer[bytes_read]=0;
				printf("%s",buffer);
				sock_write(&socket,buffer,bytes_read);
			}
		} while(tcp_tick(&socket));

		printf("Connection closed...\n");
	}
}
Beispiel #6
0
static int udp_read (_udp_Socket *sock, u_char *buf, int len,
                     ERROR_TYPE *error, DWORD timeout)
{
  int status = _ip_delay1 ((sock_type*)sock, (int)timeout, NULL, NULL);

  if (status == -1)
  {
    *error = ETIMEDOUT;
    return (0);
  }
  *error = 0;
  return sock_fastread ((sock_type*)sock, (BYTE*)buf, len);
}
Beispiel #7
0
/*********************************************************************************
 This function reads the xml socket, if there is no data it returns 2 so the
  My_Handler function calls state 2 again (state 2 is the receive state).
********************************************************************************/
int My_Rcv_Pkt(My_Socket_Type *my_sock)
{
	/* receive the packet */
	my_sock->rxbytes = sock_fastread(&my_sock->sock,my_sock->buff,BUFF_SIZE);
	switch(my_sock->rxbytes)
	{
		case -1:
			return 4; // there was an error go to state 4 (NO_WAIT_CLOSE)
		case  0:
			return 2; // connection is okay, but no data received
		default:
			(my_sock->statetime) = MS_TIMER+TCP_TIMEOUT;	// reset time to be in the SEND state
			return 3;	//now go to state 3 (SEND)
	}
}
Beispiel #8
0
int receive_packet(void)
{
	/* receive the packet */
	bytes = sock_fastread(&sock,buff,BUFF_SIZE);
	
	switch(bytes)
	{
		case -1:
			return 4; // there was an error go to state 4 (NO_WAIT_CLOSE)
		case  0:
			return 2; // connection is okay, but no data received
		default:
			statetime = MS_TIMER+TIME_OUT;	// reset time to be in the SEND state
			return 3;	//now go to state 3 (SEND)
	}
}
Beispiel #9
0
/*
 * getresult() - read answer and extract host name
 *               return 0 on error, 1 on success
 */
static __inline int getresult (udp_Socket *s, char *name)
{
  answer_t a;
  struct   rrpart *rr;
  char    *c;
  int      len = sock_fastread ((sock_type*)s, (BYTE*)&a, sizeof(a));

  if (len < sizeof(struct dhead) ||
      a.h.qdcount != intel16(1) || a.h.ancount == 0)
     return (0);

  /* Skip question */
  c = a.x;
  while (*c)
        ++c;
  c += 5;

  /* Skip name */
  while (*c)
  {
    if ((*c & 0xC0) == 0xC0)
    {
      c += 2;
      break;
    }
    else
      ++c;
  }
  rr = (struct rrpart *) c;
  if (rr->rtype != intel16(DTYPEPTR))
     return (0);

  c = (char*) &rr->rdata;
  while (*c)
  {
    if ((*c & 0xC0) == 0xC0)
        c = a.x + (*(int*)c & 0x3FFF);
    strncpy (name,c+1,*c);
    name += *c;
    c += *c + 1;
    if (*c)
        *name++ = '.';
  }
  *name = 0;
  return (1);
}
Beispiel #10
0
void do_reception(void)
{
    unsigned int maxtransfer;
#ifdef OLD
    unsigned int newtransfer;
    int status;
    unsigned int chars_avail, i;
#endif

    sock_tick( s, &status );

#ifdef OLD
    if ( sock_dataready( s )) {
	if (rec_out > rec_in ) {
	    /* we can fill intermediate portion of buffer */
	    maxtransfer = rec_out - rec_in;
	} else {
	    /* we fill end of buffer and leave start for next attempt */
	    maxtransfer = RECEIVE_BUF_SIZE - rec_in;
	}
	if (maxtransfer) {
	    rec_in += sock_fastread( s, &receive_buffer[ rec_in ], maxtransfer );
	    if ( rec_in >= RECEIVE_BUF_SIZE )
		rec_in -= RECEIVE_BUF_SIZE;
	}
    }
#else
    maxtransfer = RECEIVE_BUF_SIZE - rec_in;
    if (rec_out > rec_in) maxtransfer = rec_out - rec_in;
    maxtransfer = sock_recv( s, &receive_buffer[ rec_in ], maxtransfer );
    if (maxtransfer)
	rec_in = (rec_in + maxtransfer) % RECEIVE_BUF_SIZE ;
#endif OLD
/*    return( 0 ); */
    return;

sock_err:
    switch (status) {
	case 1 : outs("\n\r\7[??Host closed connection??]\n\r");
		 break;
	case-1 : outs("\n\r\7[??Host reset connection??]\n\r");
		 break;
    }
    s = NULL;
    sock_status = 0;
}
Beispiel #11
0
void set_nist_time(){
	int dst, health;
	struct tm	t;
	unsigned long	longsec;
	char response[100];
	int bytes_read,total_bytes;
	tcp_Socket sock;
	longword nist_server;
	printf("Trying to set time from NIST server...\n");
	//get the time
	if (!(nist_server = resolve(NIST_SERVER))) {
        printf(" ! Could not resolve time host\n");
        exit( 3 );
    }
	if( !tcp_open(&sock,0,nist_server,NIST_PORT,NULL)){
		printf(" ! Unable to connect to time server\n");
		exit( 3 );
	}
	while (!sock_established(&sock) && sock_bytesready(&sock)==-1){
       tcp_tick(NULL);
    }
	sock_mode(&sock, TCP_MODE_ASCII);
	total_bytes=0;
	do{
		bytes_read=sock_fastread(&sock,response+total_bytes,sizeof(response)-1-total_bytes);
		total_bytes+=bytes_read;
	} while(tcp_tick(&sock) && (total_bytes < sizeof(response)-2));
	//parse it
	t.tm_year = 100 + 10*(response[7]-'0') + (response[8]-'0');	
	t.tm_mon  = 10*(response[10]-'0') + (response[11]-'0');
	t.tm_mday = 10*(response[13]-'0') + (response[14]-'0');
	t.tm_hour = 10*(response[16]-'0') + (response[17]-'0');
	t.tm_min  = 10*(response[19]-'0') + (response[20]-'0');
	t.tm_sec  = 10*(response[22]-'0') + (response[23]-'0');
	dst       = 10*(response[25]-'0') + (response[26]-'0');
	health    = response[28]-'0';
	longsec = mktime(&t);
	longsec += 3600ul * NIST_TIMEZONE;		// adjust for timezone
	if (dst != 0) longsec += 3600ul;	// DST is in effect
	if (health < 2) write_rtc(longsec);
	printf("  Time set to : ");
	print_time(read_rtc());
}
Beispiel #12
0
void recv_tick(void)
{
	auto int retval;
	
	tcp_tick(state->s);
	
	switch(state->state) {
	case STATE_INIT:
		if(sock_established(state->s)) {
			printf("Connection Established.\n");
			state->state = STATE_STEADY;
		}
		break;

	case STATE_STEADY:
		if(!sock_established(state->s)) {
			/* connection died; reset */
			printf("Connection lost.\n\n");
			init_recv(state->lport);
			break;
		}

		retval = sock_fastread(state->s, state->buf, MAX_BUFLEN);
		if(retval) {
			/* we got data */
#ifdef INPUT_COOKED
			retval = cook_input(retval);
#endif
			receive_data(state->buf, retval); /* give it to the user */
		}
		break;

	default:
		/* shouldn't ever get here */
		/* reset the conroller */
		exit(-1);
	}
}
Beispiel #13
0
/*
 * Receive a message.  The connected socket and is sent back, and the need
 * for a response is indicated.
 */
void RecvMessage(tcp_Socket* tcpSock)
{
    auto char buffer[500];
    auto int numBytes;

    tcp_listen(tcpSock, PORT, 0, 0, NULL, 0);

    /* Wait for connection. */
    while( ! tcp_established( tcpSock ) )
    {
        if( ! tcp_tick( (sock_type *) tcpSock ) )
        {
            TextGotoXY(&wholewindow, 0, 0 );
            TextPrintf(&wholewindow, "Error: listen");
            return;
        }
    }

    /*  Wait for some data to appear, or an error... */
    while((numBytes = sock_fastread(tcpSock, buffer, sizeof(buffer))) == 0 )
    {
        if( ! tcp_tick( tcpSock ) || numBytes == -1 )
        {
            TextGotoXY(&wholewindow, 0, 0 );
            TextPrintf(&wholewindow, "Error: read");
            return;
        }
    }
    // Display received from other controller
    glBlankScreen();
    TextGotoXY(&wholewindow, 0, 0 );
    TextPrintf(&wholewindow, "Message received:");
    buffer[numBytes] = '\0';
    TextGotoXY(&wholewindow, 0, 1 );
    TextPrintf(&wholewindow, "%s", buffer);

}   /* end RecvMessage() */
Beispiel #14
0
int cookie( longword host )
{
	static udp_Socket sock;
    	udp_Socket *s;
    	char buffer[ 2049 ];
    	int status;
	int i;
	int fortunelen;

    	s = &sock;
    	status = 0;

	if ( host != 0 )
	{
		status=udp_open( s, 0, host, COOKIE_PORT, NULL );
	}
	else
	{
		if (_last_cookie == 0)
		{
			puts("Sorry, I can't seem to remember where my cookie jars are. ");
			puts("Could you tell me where one is? (Hint: host on the comand line)");
			exit(3);
		}
		for (i=0; i < _last_cookie; i++)
		{
			if ( (status=udp_open( s, 0, _cookie[i], COOKIE_PORT, NULL )) != 0 )
			{
				break;
			}
		}
	}

	if ( status == 0 )
	{
		puts("None of the cookie jars are open!");
		return( 1 );
	}

	sock_write( s, "\n", 1 );


    	while ( 1 )
	{
		sock_tick( s, &status );

		if (sock_dataready( s ) )
		{
			fortunelen=sock_fastread( s, buffer, sizeof( buffer ));
			buffer[fortunelen]='\0';
			printf("%s\n", buffer);
			sock_close(s);
			return(0);
		}
    	}

sock_err:
    switch (status)
	{
		case 1 : /* foreign host closed */
			 return(0);
		case -1: /* timeout */
			 printf("\nConnection timed out!");
             printf("ERROR: %s\n\r", sockerr( s ));
			 return(1);
    	}
        return (0);
}
Beispiel #15
0
int ftpsession(struct Url *url,struct HTTPrecord *cache,char *uploadfile)
{
 longword host;
 char str[256];
 char buffer[BUFLEN+2];
 tcp_Socket datasocket;
 word dataport=0;
 int rv=0,len;
 char *ptr,*datahostptr,datahost[80];
 char isdir=0,retry=0;//,ascii=0;
 long total=0;

//!!glennmcc: Nov 11, 2007 -- for 'dblp code' below
 int dblp=0;
//!!glennmcc: end

//!!glennmcc: Nov 13, 2007 -- for EZNOS2 fix below
int eznos2=0;
//!!glennmcc: end
int log;

 if(!tcpip)return 0;
 free_socket();

 if((!url->file[0] || url->file[strlen(url->file)-1]=='/') && !uploadfile)
  isdir=1;

 sprintf(str,msg_askdns,url->host);
 outs(str);

 GlobalLogoStyle=0;			//SDL set resolve animation
 host=resolve_fn( url->host, (sockfunct_t) TcpIdleFunc ); //SDL
// host=resolve( url->host );
 if(!host)
 {
  DNSerr(url->host);
  return 0;
 }

// if(!uploadfile) //!glennmcc: Oct 20, 2012 - commented-out to make upload log more verbose
   log=a_open("FTP.LOG",O_BINARY|O_WRONLY|O_CREAT|O_TRUNC,S_IREAD|S_IWRITE);

 GlobalLogoStyle=2;			//SDL set connect animation
 if (!tcp_open( socket, locport(), host, url->port, NULL ))
 {
  sprintf(str,msg_errcon,url->host);
  outs(str);
  return 0;
 }
 sprintf(str,msg_con,url->host,url->port);
 outs(str);
 write(log,str,strlen(str));
 write(log,"\r\n",2);
 sock_wait_established(socket, sock_delay, (sockfunct_t) TcpIdleFunc,
		       &status);		//SDL

 GlobalLogoStyle=1;		//SDL set data animation
 sock_mode( socket, TCP_MODE_ASCII );
 outs(MSG_LOGIN);

 do
 {
  sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc,
		   &status );		//SDL
  sock_gets( socket, (unsigned char *)buffer, sizeof( buffer ));
  outs(buffer);
  write(log,buffer,strlen(buffer));
  write(log,"\r\n",2);


//  printf("FTP daemon said>");
//  puts(buffer);
  if ( *buffer != '2' && buffer[0]!=' ') goto quit;
 }
 while(buffer[3]=='-' || buffer[0]==' '); //continued message!

 if(!url->user[0])
  ptr="anonymous";
 else
  ptr=url->user;

 sprintf( str, "USER %s", ptr);
 write(log,str,strlen(str));
 write(log,"\r\n",2);
 sock_puts(socket,(unsigned char *)str);
 sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc,
		  &status );		//SDL
 sock_gets( socket, (unsigned char *)buffer, sizeof( buffer ));
 outs(buffer);
 write(log,buffer,strlen(buffer));
 write(log,"\r\n",2);

//  printf("FTP daemon said>");
//  puts(buffer);

//!!glennmcc: May 11, 2005
//removed due to the fact that not all sites use '3'
//see additional info below with respect to anonymous password
// if ( *buffer != '3' ) goto quit;
//!!glennmcc: end

 //open cache filename:

//!glennmcc: Oct 20, 2012 - commented-out to make upload log more verbose
// if(uploadfile)
//  strcpy(cache->locname,"FTP.LOG");
// else
//!glennmcc end: Oct 20, 2012

 {
//!!glennmcc: Oct 22, 2008 -- strchr() was preventing the use of 'CachePath .\cache\'
//  ptr=strchr(cache->locname,'.');
  ptr=strrchr(cache->locname,'.');
//!!glennmcc: end
  if(ptr)
  {
   strcpy(&ptr[1],"FTP");
   strcpy(cache->rawname,cache->locname);
  }
 }

 cache->handle=a_open(cache->locname,O_BINARY|O_WRONLY|O_CREAT|O_TRUNC,S_IREAD|S_IWRITE);
 if(cache->handle<0)
  goto quit;

 strcpy(cache->mime,"text/plain");

 if(url->password[0])
  ptr=url->password;
 else
 {
  if(url->user[0] && !strcmp(url->host,AUTHENTICATION->host)
		  && !strcmp(AUTHENTICATION->realm,"$ftp"))
   ptr=AUTHENTICATION->password;
  else
  {
   ptr=configvariable(&ARACHNEcfg,"FakeFTPeMail",NULL);
   if(!ptr || !strchr(ptr,'@'))
   {
    ptr=configvariable(&ARACHNEcfg,"eMail",NULL);
    if(!ptr)
     ptr="@";
   }
  }
 }

//!!glennmcc: May 11, 2005
//some sites do not require a password after 'anonymous'
//therefer, this entire block is now within this 'if()' so that
//the password (email address), will only be sent if asked for
//!!glennmcc: Nov 13, 2007 -- EZNOS2 says "Enter PASS command"
if (strstr(buffer,"sword") || strstr(buffer,"Enter PASS command"))
//if (strstr(buffer,"sword"))//original line
{
 sprintf( str, "PASS %s", ptr);
 sock_puts(socket,(unsigned char *)str);
 write(log,str,strlen(str));
 write(log,"\r\n",2);
}//!!glennmcc: inserted Mar 02, 2008
//Some servers need the following 'do/while' section,
//therefore, only the section above for sending the password needs to be
//'blocked' when no password was requested.

 do
 {
  sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc,
		   &status );		//SDL
  sock_gets( socket, (unsigned char *)buffer, sizeof( buffer ));
  outs(buffer);
  write(log,buffer,strlen(buffer));
  write(log,"\r\n",2);
//  printf("FTP daemon said>");
//  puts(buffer);
if (strstr(buffer,"Enter PASS command")) eznos2=1;

  if (*buffer != '2' && buffer[0]!=' ' && !eznos2)
  {
   write(cache->handle,buffer,strlen(buffer));
   rv=1;
   goto quit;
  }
  else if ((buffer[3]=='-' || buffer[0]==' ') && (isdir || uploadfile))
  {
   strcat(buffer,"\r\n");
   rv=1;
   write(cache->handle,buffer,strlen(buffer));
  }
 }
 while(buffer[3]=='-' || buffer[0]==' ' || buffer[0]=='3'); //continued message!
//}//!!glennmcc: end May 11, 2005 -- removed on Mar 02, 2008

 //ask server where we have to connect:

 sock_puts(socket,(unsigned char *)"PASV");
 sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc,
		  &status );		//SDL
 sock_gets( socket, (unsigned char *)buffer, sizeof( buffer ));
 outs(buffer);
 write(log,buffer,strlen(buffer));
 write(log,"\r\n",2);



//  printf("FTP daemon said>");
//  puts(buffer);

 //2xx Entering passive mode (a,b,c,d,x,y)

 if ( *buffer != '2' ) goto quit;
 datahostptr=strchr(buffer,'(');
//!!glennmcc: Nov 13, 2007 -- EZNOS2 doesn't enclose the info in ()
//therefore, if '(' is not found... look for the last 'space'.
 if(!datahostptr) {datahostptr=strrchr(buffer,' '); eznos2=1;}
//if that still fails... 'quit'
//!!glennmcc: end
 if(!datahostptr) goto quit;//original line

 ptr=++datahostptr;
 {
  int carka=0;
  char *portptr=NULL;

  while(*ptr)
  {
   if(*ptr==',')
   {
    carka++;
    if(carka<4)
     *ptr='.';
    else if(carka==4)
    {
     *ptr='\0';
     portptr=ptr+1;
    }
    else if (carka==5)
    {
     *ptr='\0';
     dataport=256*(word)atoi(portptr);  // ,x,y -> 256*x+y
     portptr=ptr+1;
//!!glennmcc: Nov 13, 2007 -- part of above fix for EZNO2 info not in ()
 if(eznos2) dataport+=atoi(portptr);      // ,x,y -> 256*x+y
//!!glennmcc: end
    }
   }
   else if(*ptr==')' && portptr)
   {
//!!glennmcc: Nov 11, 2007 -- some servers have double ')'
// at the end of the port address info...
// this 'dblp code' will prevent that from adding the final set twice
//eg: (99,167,219,186,234,255)) instead of.... (99,167,219,186,234,255)
//without this fix ... 255 gets added a 2nd time and
//we end-up-with... port 60414 instead of the correct port of 60159
    *ptr='\0';
    if(!dblp)//!!glennmcc: Nov 11, 2007
    dataport+=atoi(portptr);      // ,x,y -> 256*x+y
    dblp=1;//!!glennmcc: Nov 11, 2007
   }
   ptr++;
  }
 }

 if(!dataport)
  goto quit;

//!!glennmcc: Aug 31, 2009
//EZNOS2 sends the IP of the machine on a router as datahost
//therefore we need to go back to the original host
if(eznos2)
{
makestr(datahost,url->host,79);
outs(datahost);
Piip();
}
else
//!!glennmcc:end

 makestr(datahost,datahostptr,79);//original line

 retry:

 if(isdir)
 {
  if(url->file[0])
  {
//!!glennmcc: Oct 15, 2007 -- fix problems with CWD on FTP servers
//which interpret the leading '/' as an attempted CD to 'root'
   if(url->file[0]=='/')
   sprintf( str, "CWD %s", url->file+1);
   else
//!!glennmcc: end Oct 15, 2007
   sprintf( str, "CWD %s", url->file);
   sock_puts(socket,(unsigned char *)str);
   do
   {
    sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc,
		     &status );		//SDL
    sock_gets( socket, (unsigned char *)buffer, sizeof( buffer ));
    outs(buffer);

//!!glennmcc: Apr 08, 2005 -- commented-out this block
// to fix the problem of 'broken dir listing' when the
// 'FTP welcome message' contains linefeeds
// such as at ftp://ftp.cdrom.com/.2/simtelnet/
/*
    if ( *buffer != '2' && buffer[0]!=' ')
    {
     write(cache->handle,buffer,strlen(buffer));
     rv=1;
     goto quit;
    }
    else if (buffer[3]=='-' || buffer[0]==' ')
*/
//!!glennmcc: end
    {
     strcat(buffer,"\r\n");
     rv=1;
     write(cache->handle,buffer,strlen(buffer));
    }
   }
//!!glennmcc: Apr 08, 2005 -- added a test for !=' ' which is also
// needed for the same fix at ftp://ftp.cdrom.com/.2/simtelnet/
   while(buffer[3]=='-' || buffer[3]!=' ' || buffer[0]==' '); //continued message!
//   while(buffer[3]=='-' || buffer[0]==' '); //continued message!
//!!glennmcc: end

  }
  strcpy(cache->mime,"ftp/list");
  sprintf( str, "LIST");
 }
 else
 {
  char *fnameptr;
  char mimestr[80]="ftp/binary";

  fnameptr=strrchr(url->file,'/');
  if(!fnameptr)
  {
   fnameptr=strrchr(url->file,'\\');
   if(!fnameptr)
    fnameptr=url->file;
   else
    fnameptr++;
   }
   else
    fnameptr++;

  sprintf( str, "TYPE I");
  if(fnameptr)
  {
   char ext[5];
   strcpy(mimestr,"file/");
   strncat(mimestr,fnameptr,70);
   mimestr[79]='\0';
   get_extension(mimestr,ext);
   if(!strncmpi(ext,"TXT",3) || !strncmpi(ext,"HTM",3))
   {
//!!glennmcc: begin June 09, 2002
//optionally upload TXT and HTM in binary mode
    ptr=configvariable(&ARACHNEcfg,"UseBinaryFTP",NULL);
    if(!ptr || toupper(*ptr)=='N')
//!!glennmcc: end
    sprintf( str, "TYPE A");
//    ascii=1;
   }
  }
  strcpy(cache->mime,mimestr);

  sock_puts(socket,(unsigned char *)str);
  write(log,str,strlen(str));
  write(log,"\r\n",2);
  sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc,
		  &status );		//SDL
  sock_gets( socket, (unsigned char *)buffer, sizeof( buffer ));
  outs(buffer);
  write(log,buffer,strlen(buffer));
  write(log,"\r\n",2);
//  printf("FTP daemon said>");
//  puts(buffer);
  if ( *buffer != '2' || uploadfile)
  {
   strcat(buffer,"\n");
   write(cache->handle,buffer,strlen(buffer));
  }
  if ( *buffer != '2' )
  {
   rv=1;
   goto quit;
  }
  if(!uploadfile)

//!!glennmcc: Oct 17, 2007 -- fix problems with FTP servers
//which interpret the leading '/' as an attempted CD to 'root'
   if(url->file[0]=='/')
   sprintf( str, "RETR %s", url->file+1);
   else
   sprintf( str, "RETR %s", url->file);
//original single line above this comment
//!!glennmcc: end
  else
   sprintf( str, "STOR %s", url->file);
 }
 sock_puts(socket,(unsigned char *)str);
 write(log,str,strlen(str));
 write(log,"\r\n",2);

//!!glennmcc: Oct 19, 2008 -- back to original fix
//!!glennmcc: Nov 15, 2007 -- always 'close' the connection when done
//with both dir listings and file downloads
//Apr 10, 2007 fix did it only for dir listings
if(isdir || strstr(str,"RETR"))
//if(isdir)
 sock_puts(socket,(unsigned char *)"QUIT");//!!glennmcc: Apr 10, 2007
//!!glennmcc: end

 if(!retry)
 {
  //get file using datahost & dataport
  GlobalLogoStyle=0;		//SDL set resolve animation
  host=resolve_fn( datahost, (sockfunct_t) TcpIdleFunc );	//SDL
//  host=resolve( datahost );
  if(!host)
   goto quit;

  GlobalLogoStyle=2;		//SDL set connect animation
  if (!tcp_open( &datasocket, locport(), host, dataport, NULL ))
  {
   sprintf(str,msg_errcon,datahost);
   outs(str);
   goto quit;
  }
  sprintf(str,msg_con,datahost,dataport);
  outs(str);
  write(log,str,strlen(str));
  write(log,"\r\n",2);

  //wait for datasocket to open:
  sock_wait_established(&datasocket, sock_delay, (sockfunct_t) TcpIdleFunc,
			&status);	//SDL

//!!glennmcc: Sep 27, 2008 -- increase D/L speed on cable & DSL
//many thanks to 'mik' for pointing me in the right direction. :)
{
#ifdef DEBUG
 char sp[80];
 sprintf(sp,"Available stack = %u bytes",_SP);
 outs(sp);
 Piip(); Piip();
#endif
 if(_SP>(1024*SETBUFSIZE))
 {
  char setbuf[1024*SETBUFSIZE];
  sock_setbuf(&datasocket, (unsigned char *)setbuf, 1024*SETBUFSIZE);
 }
}
//!!glennmcc: end

  GlobalLogoStyle=1;		//SDL set data animation
 }
 //wait for "110 openning connection" (or "550 ....error....")
 sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc,
		  &status );		//SDL

 sock_gets( socket, (unsigned char *)buffer, sizeof( buffer ));
 outs(buffer);
 write(log,buffer,strlen(buffer));
 write(log,"\r\n",2);


// printf("FTP daemon said>");
// puts(buffer);
 if ( *buffer != '1' || uploadfile)
 {
  strcat(buffer,"\n");
  write(cache->handle,buffer,strlen(buffer));
 }

 if ( *buffer != '1' )
 {
  if(!strncmp(buffer,"550",3) && !retry)
  {
   retry=1;
   isdir=1-isdir;
   if(isdir)
    strcat(url->file,"/");
   else
   {
    int i=strlen(url->file);
    if(i>0 && url->file[i-1]=='/')
     url->file[i-1]='\0';
   }
   goto retry;
  }

  strcpy(cache->mime,"text/plain");
  rv=1;
  goto dataquit;
 }

 if(!uploadfile) //-------------------------------------- download ---------------
 {
  while ( 1 )
  {
   xChLogoTICK(1);
   if(GUITICK())
    if(GLOBAL.gotolocation || GLOBAL.abort)
     goto dataquit;

   if (sock_dataready( &datasocket ))
   {
    len = sock_fastread( &datasocket, (unsigned char*)buffer, BUFLEN );
    write(cache->handle,buffer,len);
    total+=len;
    sprintf(str,MSG_BYTESR,MSG_DOWNLD,total);
    outs(str);
   }
   else
    sock_tick( &datasocket, &status ); //shift TCP/IP
  }
 }
 else //-------------------------------------- upload ------------------
 {
  int f,lenread,done;
  long length;
  char pom[256];

/*  if(ascii)
   f=a_sopen(uploadfile,O_RDONLY|O_TEXT, SH_DENYNO, S_IREAD);
  else*/
   f=a_sopen(uploadfile,O_RDONLY|O_BINARY, SH_DENYNO, S_IREAD);

  if(f<0)
   goto dataquit;

  lenread=done=0;
  length=0l;

  {
   long filel=a_filelength(f);
   while(1)
   {
    sprintf(pom,MSG_UPLOAD,length,filel);
    outs(pom);
//!!glennmcc:Oct 23, 2008 -- 'reversed the logic'
// to keep from overflowing at 21megs
    if(filel>100)
    percentbar((int)(length/(filel/100)));
//  percentbar((int)(100*length/filel));
    lenread=a_read(f,buffer,BUFLEN);
    length+=lenread;
    if(lenread<=0)
     done=1;

    //wait until we can write to socket:
    while(sock_tbleft(&datasocket)<lenread) //SDL
//    while( datasocket.datalen > 1024)
    {
     sock_tick(&datasocket,&status);
     xChLogoTICK(1); // animation of logo
     if(GUITICK())
      goto dataquit;
    }

    if(done)
    {
     sock_close( &datasocket );
     a_close(f);
     goto dataclose;
    }

    sock_fastwrite(&datasocket,(unsigned char *)buffer,lenread);
    sock_tick(&datasocket,&status);
   }//loop
  }
 }


dataquit:
//!!glennmcc: Nov 15,  2007 -- removed sock_abort because it was
// sometimes preventing the connection from being closed,
// therefore preventing access to several files within a short time
// due to too many connections open from the same IP
// sock_abort( &datasocket );//original line
//!!glennmcc: end

dataclose:
 outs(MSG_CLOSE);

 sock_puts(socket,(unsigned char *)"QUIT");//!!glennmcc: Dec 04, 2006
 sock_wait_closed( &datasocket, sock_delay, (sockfunct_t) TcpIdleFunc,
		   &status );		//SDL

 if(uploadfile)
 {
  sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc,
		   &status );		//SDL
  sock_gets( socket, (unsigned char *)buffer, sizeof( buffer ));
  outs(buffer);
 }

quit:
  sock_puts(socket,(unsigned char *)"QUIT");
  sock_close( socket );
  closing[socknum]=1;
  sock_keepalive[socknum][0]='\0';
//    sock_wait_closed( socket, sock_delay, NULL, &status );

//we will better wait because we are about to deallocate datasocket

sock_err:
    switch (status) {
	case 1 : /* foreign host closed */
		 write(log,MSG_CLOSE,strlen(MSG_CLOSE));
		 write(log,"\r\n",2);
		 close(log);
		 break;
	case -1: /* timeout */
		 sprintf(str,MSG_TCPERR, sockerr(socket));
		 outs(str);
		 write(log,str,strlen(str));
		 write(log,"\r\n",2);
		 close(log);
		 break;
    }

 if(total)
 {
  cache->knowsize=1;
  cache->size=total;
  rv=1;
 }
 if(cache->handle>=0)
 {
  a_close(cache->handle);
  rv=1;
 }

 return rv;
}
Beispiel #16
0
static int get_headlines(char *rss_site,char *rss_page){
	longword rss_server;	//holds resolve(RSS_SERVER)
	int bytes_read,total_bytes;		//for sock_fastread
	int count;
	tcp_Socket socket;		//for comm
	char rssCode[6500];		//7kb max downloaded file limit
	unsigned int pos;
	char temp[500];
	char* newStr;
	char otherStr[500];
	printf("Fetching headlines...\n");
	if (!tcp_tick(NULL)) {
        printf(" ! No network");
        return 0;
	}
	//connect to the server
	if (!(rss_server = resolve(rss_site))) {
        printf(" ! Could not resolve host");
        return 0;
    }
	if( !tcp_open(&socket,0,rss_server,HTTP_PORT,NULL)){
		printf(" ! Unable to connect to remote server");
		return 0;
	}
	//wait for the connection to be established
	while (!sock_established(&socket) && sock_bytesready(&socket)==-1){
       tcp_tick(NULL);
    }
	printf("  connected! sending request\n");
	//get the RSS code
	memset(rssCode,0,sizeof(rssCode));	//empty it first!
	sock_puts(&socket,"GET ");
	sock_puts(&socket,rss_page);
	sock_puts(&socket," HTTP/1.0\n");
	sock_puts(&socket,"Accept: text/xml\nAccept: text/plain\nAccept: application/rss+xml\n\n");
	sock_puts(&socket,"User-Agent: Mozilla/5.0 (Windows; U; Win98; en-US; m18) Gecko/20001108 Netscape6/6.0 \r\n\r\n");
	total_bytes=0;
	do{
		//this should be changed to parse as we receive each set of
		//bytes, so we don't need to waste 10k of memory with the big
		//rssCode array...
		bytes_read=sock_fastread(&socket,rssCode+total_bytes,sizeof(rssCode)-1-total_bytes);
		total_bytes+=bytes_read;
	} while(tcp_tick(&socket) && (total_bytes < sizeof(rssCode)-2));
	printf("  Connection closed (received %d bytes)...\n",total_bytes);
	if(total_bytes<600) printf(rssCode);
	//parse out the headlines
	memset(headlines,0,sizeof(headlines));
	strcat(headlines,"** ");
	newStr = strstr(rssCode,"<title>");
	newStr = strstr(newStr,">");
	count=0;
	while((newStr!= NULL)){
		pos = strcspn(newStr,"<");
		temp[0] = 0;
		strncat(temp,newStr,pos);
		substr(otherStr,temp,1,strlen(temp));
		printf("  - \"%s\"\n",otherStr);	//debug - print out the headline
		strcat(headlines,otherStr);
		strcat(headlines,"...  ");
		newStr = strstr(newStr,"</title>");
		newStr = strstr(newStr,"<title>");
		newStr = strstr(newStr,">");
		count++;
	}
	printf("Parsed out %d headlines.\n\n",count);
	return 1;
}
Beispiel #17
0
/*
 * Receive a TFTP data packet
 */
static int recv_packet (DWORD block)
{
  int len, status = 0;

  /* Use a callback since first block sent might cause a "ICMP
   * port unreachable" to be sent back. Note that the normal mechanism
   * of detecting ICMP errors (through _udp_cancel) doesn't work since
   * we did set 'sock->udp.hisaddr = 0'.
   *
   * Note: 'block' is 32-bit, but 16-bit in tftp-header.
   *       We allow the header block-counter to wrap (allowing > 32MB files).
   */
  if (block == 1UL)
       sock->udp.icmp_callb = (icmp_upcall) udp_callback;
  else sock->udp.icmp_callb = NULL;

  /* Read packet with timeout
   */
  sock_wait_input (sock, tftp_timeout, NULL, &status);

  len = sock_fastread (sock, (BYTE*)inbuf, TFTP_HEADSIZE+SEGSIZE);

  /* Check that the packet has a correct length
   */
  len -= TFTP_HEADSIZE;
  if (len < 0 || len > SEGSIZE)
  {
    TRACE (("tftp: Invalid packet, len = %d\n", len));
    tftp_errno = ERR_INV;
    return (-1);
  }

  /* Check if we got an error packet
   */
  if (intel16(inbuf->th_opcode) == ERROR)
  {
#if defined(USE_DEBUG)
    int   code = intel16 (inbuf->th_code);
    const char *str = tftp_strerror (code);

    TRACE (("tftp: Error: %s (%d): %.*s\n",
            str, code, SEGSIZE, inbuf->th_data));
#endif
    tftp_errno = ERR_ERR;
    return (-1);
  }

  /* Check if we got a valid data packet at all
   */
  if (intel16(inbuf->th_opcode) != DATA)
  {
    TRACE (("tftp: Invalid opcode %d\n", intel16(inbuf->th_opcode)));
    tftp_errno = ERR_OP;
    return (-1);
  }

  /* Check if the block number of the data packet is correct
   */
  if (intel16(inbuf->th_block) != (WORD)block)
  {
    TRACE (("tftp: Block %u != %u\n", intel16(inbuf->th_block), (WORD)block));
    tftp_errno = ERR_BLOCK;
    return (-1);
  }

  tftp_errno = 0;
  if (debug_on)
     (*_outch) ('#');  /* Write 1 hash-mark per block */

  return (len);

sock_err:
  if (status == -1)
  {
    if (debug_on)
       (*_outch) ('T');

    tftp_errno = ERR_TIMEOUT;
    return (-1);
  }

  /* most likely "Port unreachable"
   */
  TRACE (("tftp: %s\n", sockerr(sock)));
  tftp_errno = ERR_UNKNOWN;
  return (-1);
}
Beispiel #18
0
int main()
{
	auto int if_status;

	printf("Multiple Interface Echo Test\n");
	usage();
	printf("\nPress any key to proceed.\n");
	while (!kbhit());
	getchar();
	printf("Initializing TCP/IP stack...\n");

	for (i = 0; i < IF_MAX; i++)
		ifconfig(i, IFG_IPADDR, oldip+i,
#ifdef USE_IF_CALLBACK
					IFS_IF_CALLBACK, updowncb,
#endif
					IFS_END);

	sock_init();

	// Wait for the interface to come up
		while (IF_COMING_UP == (if_status = ifpending(IF_DEFAULT)) ||
		       IF_COMING_DOWN == if_status)
	{
		tcp_tick(NULL);
	}

	printf("...done.\n");

	memset(state, 0, sizeof(state));
	socknum = -1;
	seq = 1;
	ping_ip = 0;
	act_ip = 0;
	asock = s + (NUM_SOCKS - 1);
	astate = state + (NUM_SOCKS - 1);
	*astate = STATE_DONT_USE;

	if(!udp_extopen(&usock, IF_ANY, ECHO_PORT, -1L, 0, echo_handler, 0, 0)) {
		printf("udp_extopen failed!\n");
		exit(0);
	}


	for (;;) {
		socknum++;
		if (socknum == NUM_SOCKS)
			socknum = 0;

		tcp_tick(NULL);

		if (state[socknum] > STATE_CLOSED &&
		    !sock_alive(s+socknum)) {
		   if (socknum == NUM_LISTEN_SOCKS) {
		   	printf("Active socket closed\n");
				state[socknum] = STATE_DONT_USE;
		   }
		   else {
				printf("Socket %d closed\n", socknum);
				state[socknum] = STATE_CLOSED;
			}
			sock_perror(s+socknum, NULL);
		}

		for (i = 0; i < IF_MAX; i++) {
			ifconfig(i, IFG_IPADDR, &ip, IFS_END);
			if (oldip[i] != ip) {
				printf("IPaddr on i/f %d changed from %08lx to %08lx\n",
					i, oldip[i], ip);
				oldip[i] = ip;
				ifconfig(i, IFS_ICMP_CONFIG_RESET, IFS_END);
			}
		}

		if (kbhit()) {
			kb = getchar();
			if (kb == '?')
				usage();
			else if (kb == 'i')
				ip_print_ifs();
			else if (kb == 'r')
				router_printall();
			else if (kb == 'c')
				arpcache_printall();
			else if (kb == 'p') {
				printf("Press an interface number [TCP/IP now blocked]\n");
				while (!kbhit());
				kb = getchar();
				if (isdigit(kb)) {
					ifconfig(kb - '0', IFG_ROUTER_DEFAULT, &ping_ip, IFS_END);
					if (ping_ip) {
						printf("Pinging router %08lX...\n", ping_ip);
						_send_ping(ping_ip, seq++, 1, IPTOS_DEFAULT, &ping_id);
					}
					else
						printf("No router for interface %d\n", kb - '0');
				}
				else
					printf("No interface selected.\n");
			}
			else if (kb == 'a') {
				if (act_ip && *astate != STATE_DONT_USE) {
					printf("Closing active connection to %s...\n", inet_ntoa(buf, act_ip));
					sock_close(asock);
					while (tcp_tick(asock));
				}
				*astate = STATE_DONT_USE;
				printf("Enter a host name or IP address [TCP/IP now blocked]\n");
				gets(buf);
				printf("Resolving...\n");
				act_ip = resolve(buf);
				if (act_ip) {
					printf("Enter a port number to connect to (0-65535)\n");
					gets(buf);
					aport = (word)atol(buf);
					printf("Opening to %s:%u...\n", inet_ntoa(buf, act_ip), aport);
					*astate = STATE_ACTOPEN;
				}
				else
					printf("Could not resolve %s to IP address.\n", buf);

			}
			else if (isdigit(kb)) {
				// Toggle interface status
				kb -= '0';
	  			if (!(1u<<kb & IF_SET)) {
            	printf("Not a valid interface\n");
					continue;
            }
				if (ifstatus(kb)) {
					printf("Bringing interface %d down...\n", kb);
					ifconfig(kb, IFS_DOWN, IFS_END);
				}
				else {
					printf("Bringing interface %d up...\n", kb);
					ifconfig(kb, IFS_UP, IFS_END);
				}
			}
		}

		if (ping_ip) {
			if (_chk_ping(ping_ip , &ping_id) != 0xffffffffL) {
				printf("Got ping response from %08lX\n", ping_ip);
				ping_ip = 0;
			}
		}

		switch (state[socknum]) {
			case STATE_CLOSED:
				if (!tcp_extlisten(s + socknum, IF_ANY, ECHO_PORT, 0, 0, t_handler, 0, 0, 0)) {
					printf("Listen failed - socket %d\n", socknum);
					state[socknum] = STATE_DONT_USE;
					break;
				}
				printf("Listening on socket %d...\n", socknum);
				state[socknum] = STATE_LISTEN;
				break;
			case STATE_ACTOPEN:
				if (!tcp_extopen(s + socknum, IF_ANY, 0, act_ip, aport, t_handler, 0, 0)) {
					printf("Active open failed\n");
					state[socknum] = STATE_DONT_USE;
					break;
				}
				state[socknum] = STATE_LISTEN;
				break;
			case STATE_LISTEN:
				if (sock_established(s + socknum)) {
					printf("Connection %d estab.\n", socknum);
					state[socknum] = STATE_ESTAB;
				}
				break;
			case STATE_ESTAB:
				if ((rb = sock_fastread(s + socknum, buf, sizeof(buf))) > 0) {
					sock_fastwrite(s + socknum, buf, rb);
					if (!strncmp(buf, "quit", 4)) {
						printf("Peer on socket %d requests close\n", socknum);
						sock_close(s + socknum);
						state[socknum] = STATE_CLOSING;
					}
				}
				else if (rb < 0) {
					printf("Connection %d closed by peer.\n", socknum);
					sock_close(s + socknum);
					state[socknum] = STATE_CLOSING;
				}
				break;
			default:
				break;
		}
	}
}
Beispiel #19
0
void main(void)
{
	// index is used to loop through the interfaces
	int index;

	// Initialize the TCP/IP stack
  	sock_init();

   // Initialize the state machine structure
   for (index = 0; index <= VIRTUAL_ETH; index++) {
     	socks[index].state = LSTN_STATE;
      socks[index].iface = 0;
      memset(socks[index].buff, 0, sizeof(socks[index].buff));
      socks[index].bytes = 0;
   }

	// Perform network configuration on the main (physical) Ethernet ineterface
   printf("Bringing up Main Interface %2d:\n", socks[0].iface);
   ifconfig(IF_ETH0,
   			IFS_IPADDR, 	aton(LOCAL_IP),
   			IFS_NETMASK,	aton(LOCAL_NETMASK),
           	IFS_ROUTER_SET,aton(LOCAL_GATEWAY),
            IFS_UP,
          	IFS_END);
   // Wait for the interface to come up
   while (ifpending(IF_ETH0) == IF_COMING_UP) {
		tcp_tick(NULL);
	}
   printf("Main Interface %2d: is up!!\n", socks[0].iface);

	// Configure each of the virtual Ethernet interfaces
   for (index = 1; index <= VIRTUAL_ETH; index++) {
		// virtual_eth() creates a new virtual Ethernet interface and returns
		// the new interface number
   	socks[index].iface = virtual_eth(IF_ETH0, aton(LOCAL_IP) + index,
   	                                 aton(LOCAL_NETMASK), NULL);
      if (socks[index].iface != -1) {
      	printf("Created Virtual Interface %2d:\n", socks[index].iface);
      }
      else {
      	exit(0);
      }
		// Wait for the virtual Ethernet interface to come up
      while (ifpending(socks[index].iface) == IF_COMING_UP) {
			tcp_tick(NULL);
		}
      printf("Virtual Interface %2d: is up!!\n", socks[index].iface);
   }

	// Print out information on the interfaces
	ip_print_ifs();

	// Begin the main program loop
   while (1) {
   	// Iterate over the Ethernet interfaces
   	for (index = 0; index <= VIRTUAL_ETH; index++) {
      	switch (socks[index].state) {
      		// Listen on the socket
      		case LSTN_STATE:
      			// Note that the iface number is passed to tcp_extlisten()
               if (tcp_extlisten(&socks[index].s, socks[index].iface,
                                 LOCAL_PORT, 0, 0, NULL, 0, 0, 0)) {
                  socks[index].state = ESTB_STATE;
                  socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer
                  printf("Interface %2d: listening on port: %5d\n",
                         socks[index].iface, LOCAL_PORT);
               }
               else {
               	// tcp_extlisten() failed--let the user know
                  printf("Interface %2d: tcp_extlisten failed\n",
                         socks[index].iface);
               	socks[index].state = CLSE_STATE;
                  socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer
               }
               break;
           	// Check if a connection has been established
            case ESTB_STATE:
              	if (sock_established(&socks[index].s) ||
              	    sock_bytesready(&socks[index].s) >= 0) {
               	socks[index].state = RECV_STATE;
                  socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer
                  printf("Interface %2d: socket established.\n",
                         socks[index].iface);
               }
               break;
				// Check if data has been received.  If so, read it out.
            case RECV_STATE:
            	// Read any incoming data
            	socks[index].bytes = sock_fastread(&socks[index].s,
            	                                   socks[index].buff,
            	                                   sizeof(socks[index].buff));
               if (socks[index].bytes == -1) {
               	// sock_fastread() returned an error--means that the socket is
               	// likely closed
               	printf("Interface %2d: sock_fastread failed\n",
               	       socks[index].iface);
               	socks[index].state = CLSE_STATE;
                  socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer
               }
               // Check if we received any data
               if (socks[index].bytes > 0) {
               	printf("Interface %2d: revd: %2d bytes\n", socks[index].iface,
               	       socks[index].bytes);
						socks[index].state = SEND_STATE;			// send the data back
                  socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer
            	}
            	break;
            // Echo back any received data
         	case SEND_STATE:
            	socks[index].bytes = sock_fastwrite(&socks[index].s,
            	                                    socks[index].buff,
            	                                    socks[index].bytes);
               if (socks[index].bytes == -1) {
               	// sock_fastwrite() returned an error--means that the socket
               	// is likely closed
               	printf("Interface %2d: sock_fastwrite failed\n",
               	       socks[index].iface);
               	socks[index].state = CLSE_STATE;
                  socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer
               }
               // Check how much data was written.  Note that in this program,
               // if not all the data was written, the remaining data will be
               // dropped.  A more realistic program would try sending the rest
               // of the data later, or using sock_awrite() until the data can
               // be sent.
               if (socks[index].bytes > 0) {
               	printf("Interface %2d: sent: %2d bytes\n",
               	       socks[index].iface, socks[index].bytes);
						socks[index].state = RECV_STATE;
                  socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer
            	}
            	break;
				// Close the socket
        		case CLSE_STATE:
               sock_close(&socks[index].s);
               socks[index].state = CLWT_STATE;
               socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer
               break;
				// Wait for the socket to completely close
            case CLWT_STATE:
					if (!sock_alive(&socks[index].s)) {
                  printf("Interface %2d: socket closed.\n",
                         socks[index].iface);
                  socks[index].state = LSTN_STATE;
                  socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer
               }
               break;
				// Abort the socket--used only if a socket has timed out in one of
				// the closing states
            case ABRT_STATE:
               sock_abort(&socks[index].s);     // abort the socket
               socks[index].state = LSTN_STATE; // try to listen again
               socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer
               break;
         }

         // Drive the TCP/IP stack
    		tcp_tick(NULL);

			// Check the timeout on this socket, and close or abort the socket
			// if necessary
         timed_out(index);
    	}
 	}
}
Beispiel #20
0
void main()
{
	int state;
	long timeout;
	int bytes_read;

	static char buffer[64];
	static tcp_Socket socket;

	// Initialize I/O to use PowerCoreFLEX prototyping board
	brdInit();

	serXopen(BAUD_RATE);				// set up serial port
   serMode(0);

	sock_init();						// initialize DCRTCP
	tcp_reserveport(PORT);			// set up PORT for SYN Queueing
											// which will hold a pending connection
											// until we are ready to process it.
	state=CONNECTION_INIT;

	while(1) {
		if(state==CONNECTION_OPEN) {
			if(debounce_key()) {
				sock_close(&socket);
				state=CONNECTION_CLOSED;
			}
		}
		/*
		 *		Make sure that the connection hasn't closed on us.
		 *
		 */

		if(tcp_tick(&socket)==0 && state!=CONNECTION_INIT) {
				sock_close(&socket);
				state=CONNECTION_CLOSED;
		}

		switch(state) {
			case CONNECTION_INIT:
				tcp_listen(&socket,PORT,0,0,NULL,0);
				state=CONNECTION_LISTEN;
				break;

			case CONNECTION_LISTEN:
				if(sock_established(&socket)) {
					state=CONNECTION_OPEN;
					timeout=SEC_TIMER+TIMEOUT;
					serXrdFlush();
					serXwrFlush();
					led(RESET_LED);
 			}
				break;

			case CONNECTION_OPEN:

				/*
				 *		close the socket on a timeout
				 *
				 */
				if((long) (SEC_TIMER-timeout) >= 0) {
					sock_close(&socket);
					state=CONNECTION_CLOSED;
					break;
				}

				/*
				 *		read as many bytes from the socket as we have
				 *		room in the serial buffer. Also strip out the
				 *    telnet commands.
				 */
				bytes_read = 0;
				if(sock_bytesready(&socket) != -1)
				{
					bytes_read=sock_fastread(&socket, buffer, min(sizeof(buffer), serXwrFree()));
					bytes_read=strip_telnet_cmds(buffer, bytes_read);
				}

				/*
				 *		close the socket on an error
				 *
				 */

				if(bytes_read<0) {
					sock_close(&socket);
					state=CONNECTION_CLOSED;
					break;
				}

				/*
				 *		copy any bytes that we read
				 *
				 */

				if(bytes_read > 0) {
					timeout=SEC_TIMER+TIMEOUT;
					serXwrite(buffer, bytes_read);
				}

				/*
				 *		read as many bytes from the serial port as we
				 *		have room in the socket buffer.
				 *
				 */

				bytes_read=serXread(buffer,min(sizeof(buffer),sock_tbleft(&socket)),100);
				if(bytes_read>0) {
					timeout=SEC_TIMER+TIMEOUT;
					if(sock_fastwrite(&socket,buffer,bytes_read)<0) {
						sock_close(&socket);
						state=CONNECTION_CLOSED;
					}
				}
				led(TOGGLE_LED);
				break;

			case CONNECTION_CLOSED:
				serXrdFlush();
				serXwrFlush();
				sprintf(buffer, "\n\rConnection closed\n\r");
				serXwrite(buffer, strlen(buffer));
				led(RESET_LED);
				state=CONNECTION_INIT;
				break;
		}
	}
}