Example #1
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");
	}
}
Example #2
0
/*********************************************************************************
 This function handles and controls the xml socket.
********************************************************************************/
void My_Handler(My_Socket_Type *my_sock)
{
	static char ipaddr[25],DispStrOut[100];

	switch(my_sock->nextstate)
	{
		case 0:/*INITIALIZATION*/										// listen for incoming connection
			inet_ntoa( ipaddr, my_ip_addr );
			sprintf(DispStrOut,"OFFLINE\nCONNECT TO\nIP: %s\nPORT: %d",
					  ipaddr, MY_PORT);
			while(!btnMsgBox(40,0,240,90,&fi14x16,DispStrOut,1,1));
			if(tcp_listen(&my_sock->sock,MY_PORT,INCOMING_IP,INCOMING_PORT,NULL,0))
			{
				my_sock->rxbytes = my_sock->txbytes = 0;
				my_sock->statetime = 0L;
				(my_sock->nextstate)++;										// init complete move onto next state
				my_sock->statetime = MS_TIMER+TCP_TIMEOUT;				// reset the statetime
			}
			else
				exit(0);
			break;
		case 1://LISTEN//
			if(sock_established(&my_sock->sock))						// check for a connection
			{
				inet_ntoa(ipaddr,my_sock->sock.hisaddr);
				sprintf(DispStrOut,"CONNECTED\nIP: %s",ipaddr);
				while(!btnMsgBox(40,0,240,90,&fi14x16,DispStrOut,1,0));
				//printf("%s\nConnection Established.\n",BLACK);
				(my_sock->statetime) = MS_TIMER+TCP_TIMEOUT;			// reset statetime for RECEIVE state
				(my_sock->nextstate)++;										//  we have connection so move on
			}
			else if ((long)(MS_TIMER-(my_sock->statetime)) > 0)	// if X sec and no sock
				my_sock->nextstate = 4;										//	  abort and re-init
			break;
		case 2://RECEIVE//
			my_sock->nextstate = My_Rcv_Pkt(my_sock);					// see function for details
			if ((long)(MS_TIMER-(my_sock->statetime)) > 0)			// if X sec and still waiting
				my_sock->nextstate = 4;										//	  abort and re-init
			break;
		case 3://SEND//
			my_sock->nextstate = My_Snd_Pkt(my_sock);					// see function for details
			if ((long)(MS_TIMER-(my_sock->statetime)) > 0)			// if X sec and still waiting
				my_sock->nextstate = 4;										//	  abort and re-init
			break;
		case 4://NO WAIT_CLOSE//
			sock_abort(&my_sock->sock);									// close the socket
			my_sock->nextstate = 0;											// go back to the INIT state
	}
	if(!tcp_tick(&my_sock->sock))
		my_sock->nextstate = 0;
}
Example #3
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);
	}
}
Example #4
0
void main()
{
	int state,status;
	state = 0;
	
	sock_init();
	
	while(1)
	{
		switch(state)
		{
			case 0:/*INITIALIZATION*/					// listen for incoming connection
				if(!tcp_listen(&sock,MY_PORT,INCOMING_IP,INCOMING_PORT,NULL,0))
					printf("%sERROR OPENNING SOCKET!\n",RED);
				else
				{
					printf("%swaiting for incomming session\n",GREEN);
					statetime = MS_TIMER+TIME_OUT;		// setup the time to be in LISTEN state
					state++;										// init complete move onto next state
				}
				break;
			case 1:/*LISTEN*/
				if(sock_established(&sock))			// check for a connection
				{
					printf("%ssocket established\n",BLUE);
					statetime = MS_TIMER+TIME_OUT;	// reset time to be in the RECEIVE state
					state++;									//   we have connection so move on
				}
				else if ((long)(MS_TIMER-statetime) > 0)	// if X millisecs and still waiting
					state = 4;										//	  abort and re-init
				break;
			case 2:/*RECEIVE*/
				state = receive_packet();				// see function for details
				if ((long)(MS_TIMER-statetime) > 0)	// if X millisecs and still waiting
					state = 4;								//	  abort and re-init
				break;
			case 3:/*SEND*/
				state = send_packet();					// see function for details
				if ((long)(MS_TIMER-statetime) > 0) // if X millisecs and still waiting
					state = 4;								//	  abort and re-init
				break;
			case 4:/*NO WAIT_CLOSE*/
				printf("%sABORT SOCKET\n",RED);
				sock_abort(&sock);						// close the socket
				state = 0;									// go back to the INIT state
		}
		status = tcp_tick(&sock);
	}	
}
Example #5
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());
}
Example #6
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;
}
Example #7
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;
		}
	}
}
Example #8
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);
    	}
 	}
}
Example #9
0
void vs_handler(VsState* state)
{
	auto tcp_Socket* socket;
	auto int ch, bytes_written;
	auto int bytes_to_write;

	if(vs_info.mode==VS_MODEOFF)
		return;

	socket=&state->socket;

	/*
	 *		was the connection reset?
	 */
	if(state->state!=VS_INIT && tcp_tick(socket)==0) {
#ifdef VERBOSE
		printf("Connection closed\n");
#endif
		state->state=VS_INIT;
		state->open_timeout=vs_info.open_timeout;
	}

	switch(state->state)
	{
		case VS_INIT:
			/*
			 *		passive open on the socket port
			 */

			if(state->open_timeout && vs_info.mode == VS_MODEACTIVE) {
				costate {
					waitfor(DelayMs(state->open_timeout));
					state->open_timeout=0;
				}

				if(state->open_timeout)
					break;
			}

			serYopen(vs_info.baud);

			if(vs_info.mode == VS_MODEPASSIVE) {
				if (tcp_listen(socket,vs_info.port,0,0,NULL,0) != 0) {
					state->state=VS_LISTEN;
#ifdef VERBOSE
					printf("\nListening on socket\n");
#endif
				}
				else {
					printf("\nError listening on socket!\n");
				}
			} else if(vs_info.mode == VS_MODEACTIVE) {
				if (tcp_open(socket,0,vs_info.dest_ip,vs_info.dest_port,NULL) != 0) {
					state->state=VS_OPENING;
#ifdef VERBOSE
					printf("\nOpening socket\n");
#endif
				}
				else {
					printf("\nError opening socket!\n");
				}
			}
			break;

		case VS_LISTEN:
		case VS_OPENING:
			/*
			 *		wait for a connection
			 */

			if(sock_established(socket) || sock_bytesready(socket) >= 0) {
				state->state=VS_OPEN;
				sock_mode(socket,vs_info.binary);

#ifdef VERBOSE
				printf("New Connection\n");
#endif
			}
			break;

		case VS_OPEN:
			if(vs_info.timeout!=0 &&
				state->offset &&
				(long) ((state->last_character+vs_info.timeout) - MS_TIMER) < 0) {
				bytes_written=sock_fastwrite(socket,state->buffer,state->offset);
				if (bytes_written < 0) {
					state->state = VS_WAITCLOSE;
					sock_close(socket);
#ifdef VERBOSE
					printf("Connection closed\n");
#endif
					break;
				}

				/*
				 *		Hmmm... We weren't able to write all the bytes out.
				 *		Since we don't want to loose any characters, we will
				 *		shift everything over and hopefully write it soon.
				 *
				 */

				if(bytes_written!=state->offset) {
					memcpy(state->buffer,state->buffer+bytes_written,state->offset-bytes_written);
					state->offset = bytes_written;
					break;
				} else
					state->offset = 0;
			}

			/*
			 *		process any characters.
			 */

			bytes_to_write=sock_bytesready(socket);
			if(bytes_to_write>serYwrFree())
				bytes_to_write=serYwrFree();

			if(bytes_to_write>(int)sizeof(state->buffer))
				bytes_to_write=sizeof(state->buffer);

			if(bytes_to_write>0) {
				sock_read(socket,state->buffer,bytes_to_write);
				serYwrite(state->buffer,bytes_to_write);
			}

			/*
			 *		If we aren't worried about interpacket delay
			 *		just send the characters if there is room in
			 *		the buffer.
			 *
			 */

			if(vs_info.timeout==0) {
				bytes_to_write=serYrdUsed();

				if(bytes_to_write>sock_tbleft(socket))
					bytes_to_write=sock_tbleft(socket);

				if(bytes_to_write>(int)sizeof(state->buffer))
					bytes_to_write=sizeof(state->buffer);

				if(bytes_to_write>0) {
					serYread(state->buffer,bytes_to_write,0);
					sock_write(socket,state->buffer,bytes_to_write);
				}
			} else {
				while(state->offset<VS_MAXOFFSET && (ch=serYgetc())!=-1) {
#ifdef USE_STDIO
					printf("%c",ch);
#endif
					state->buffer[state->offset++]=ch;
					state->last_character=MS_TIMER;
				}
			}

			/*
			 *		We should immediately flush characters if the buffer
			 *		is full.
			 *
			 */

			if(state->offset==VS_MAXOFFSET) {
				bytes_written=sock_fastwrite(socket,state->buffer,state->offset);
				if (bytes_written < 0) {
					state->state = VS_WAITCLOSE;
					sock_close(socket);
#ifdef VERBOSE
					printf("Connection closed\n");
#endif
					break;
				}

				/*
				 *		Hmmm... We weren't able to write all the bytes out.
				 *		Since we don't want to loose any characters, we will
				 *		shift everything over and hopefully write it soon.
				 *
				 */

				if(bytes_written!=state->offset) {
					memcpy(state->buffer,state->buffer+bytes_written,state->offset-bytes_written);
					state->offset = bytes_written;
				} else
					state->offset = 0;
			}

			break;

		case VS_WAITCLOSE:
			break;

		default:
			/*
			 *		how did we get here?  programming error?
			 */

			state->state=VS_INIT;
			break;
	}
Example #10
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;
		}
	}
}