Пример #1
0
void telnet_init(int vdefd)
{
	int sockfd;
	struct sockaddr_in  serv_addr;
	vdehist_termread=lwip_read;
	vdehist_termwrite=lwip_write;
	vdehist_logincmd=telnet_logincmd;
	sockfd=lwip_socket(AF_INET, SOCK_STREAM, 0);

	if (!sockfd) {
		printlog(LOG_ERR,"telnet socket err: %s",strerror(errno));
	}

	bzero((char *) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family      = AF_INET;
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	serv_addr.sin_port        = htons(TELNET_TCP_PORT);

	if (lwip_bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
		printlog(LOG_ERR,"telnet bind err: %s",strerror(errno));
	}

	lwip_listen(sockfd, 5);

	addpfd(sockfd,telnetaccept);
}
Пример #2
0
int32_t trcSocketInitializeListener()
{
  if (sock >= 0)
	return 0;
  
  sock = lwip_socket(AF_INET, SOCK_STREAM, 0);

  if (sock < 0)
    return -1;

  address.sin_family = AF_INET;
  address.sin_port = htons( TRC_TCPIP_PORT );
  address.sin_addr.s_addr = INADDR_ANY;

  if (bind(sock, (struct sockaddr *)&address, sizeof (address)) < 0)
  {
    closesocket(sock);
    sock = -1;
    return -1;
  }

  if (lwip_listen(sock, 5) < 0)
  {
    closesocket(sock);
    sock = -1;
    return -1;
  }

  return 0;
}
Пример #3
0
void echo_application_thread()
{
	int sock, new_sd;
	struct sockaddr_in address, remote;
	int size;

	if ((sock = lwip_socket(AF_INET, SOCK_STREAM, 0)) < 0)
		return;

	address.sin_family = AF_INET;
	address.sin_port = htons(echo_port);
	address.sin_addr.s_addr = INADDR_ANY;

	if (lwip_bind(sock, (struct sockaddr *)&address, sizeof (address)) < 0)
		return;

	lwip_listen(sock, 0);

	size = sizeof(remote);

	while (1) {
		if ((new_sd = lwip_accept(sock, (struct sockaddr *)&remote, (socklen_t *)&size)) > 0) {
			sys_thread_new("echos", process_echo_request,
				(void*)new_sd,
				THREAD_STACKSIZE,
				DEFAULT_THREAD_PRIO);
		}
	}
}
Пример #4
0
int
main(int argc, char **argv)
{
      int sock, length;
      struct sockaddr_in server;
      int msgsock;
      int i;
	// intalization 
	lwip_tcpip_init();
	/* DHCP */
	//enum { BUF_SIZE = Nic::Packet_allocator::DEFAULT_PACKET_SIZE * 128 };
 	int  BUF_SIZE= 200000;
	if (lwip_nic_init(0, 0, 0, BUF_SIZE, BUF_SIZE)) {
		printf("ERROR: We got no IP address!\n");
		return 1;
	}

      /* Create socket */
      sock = lwip_socket(AF_INET, SOCK_STREAM, 0);
      if (sock < 0) {
            perror("opening stream socket");
            exit(1);
      }

      /* Name socket using wildcards */
      server.sin_family = AF_INET;
      server.sin_addr.s_addr = INADDR_ANY;
      server.sin_port = htons(SRV_PORT);
      if (lwip_bind(sock, (struct sockaddr *)&server, sizeof(server))) {
            perror("binding stream socket");
            exit(1);
      }

      /* Find out assigned port number and print it out */
      //length = sizeof(server);
      //if (getsockname(sock, (struct sockaddr *)&server, &length)) {
      //      perror("getting socket name");
      //      exit(1);
     // }

     // printf("Socket has port #%d\n", ntohs(server.sin_port));
	printf("Socket has port #%d\n",3333);

      /* Start accepting connections */
      lwip_listen(sock, 5);
      do {
		msgsock = lwip_accept(sock, 0, 0);
		if (msgsock == -1)
			perror("accept");
                printf("process message  on msgsock %d \n ",msgsock);
		process_client(msgsock);
	        close(msgsock);
      } while (TRUE);
/*
 * Since this program has an infinite loop, the socket "sock" is
 * never explicitly closed.  However, all sockets will be closed
 * automatically when a process is killed or terminates normally.
 */
}
Пример #5
0
int32_t OsNetworkListen(THandle aHandle, uint32_t aSlots)
{
    if ( OsNetworkHandle_IsInterrupted(aHandle) )
        return -1;

    LOGFUNCIN();

    int result = lwip_listen ( HANDLE_TO_SOCKET(aHandle), (int) aSlots );
    
    LOGFUNCOUT();
    return result;
}
Пример #6
0
static void socketCreate(uint16 sockNr)
{
    int sockFd;
    int sockType;
    struct sockaddr_in sLocalAddr;

    if (SocketAdminList[sockNr].SocketProtocolIsTcp) {
    	sockType = SOCK_STREAM;
    } else {
    	sockType = SOCK_DGRAM;
    }


    sockFd = lwip_socket(AF_INET, sockType, 0);
    if (sockFd >= 0) {
    	memset((char *)&sLocalAddr, 0, sizeof(sLocalAddr));

    	int on = 1;
    	lwip_ioctl(sockFd, FIONBIO, &on);
//    	lwip_setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int) );		// shuzhou add
    	lwip_setsockopt(sockFd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(int));	// Set socket to no delay

    	/*Source*/
    	sLocalAddr.sin_family = AF_INET;
    	sLocalAddr.sin_len = sizeof(sLocalAddr);

    	sLocalAddr.sin_addr.s_addr = htonl(INADDR_ANY);		// TODO: Use IP from configuration instead
    	sLocalAddr.sin_port = htons(SocketAdminList[sockNr].SocketConnectionRef->SocketLocalPort);

    	if(lwip_bind(sockFd, (struct sockaddr *)&sLocalAddr, sizeof(sLocalAddr)) >= 0) {

            if (!SocketAdminList[sockNr].SocketProtocolIsTcp) {
            	// Now the UDP socket is ready for receive/transmit
            	SocketAdminList[sockNr].SocketHandle = sockFd;
            	SocketAdminList[sockNr].SocketState = SOCKET_UDP_READY;
            } else {
                if  ( lwip_listen(sockFd, 20) == 0 ){	// TODO: What number of the backlog?
                	// Now the TCP socket is ready for receive/transmit
                	SocketAdminList[sockNr].SocketHandle = sockFd;
                	SocketAdminList[sockNr].SocketState = SOCKET_TCP_LISTENING;
                } else {
                	lwip_close(sockFd);
                }
            }
    	} else {
    		lwip_close(sockFd);
    	}
    } else {
    	// Socket creation failed
    	// Do nothing, try again later
    }
}
Пример #7
0
void rx_application_thread()
{
	int sock, new_sd;
	struct sockaddr_in address, remote;
	int size;

	if ((sock = lwip_socket(AF_INET, SOCK_STREAM, 0)) < 0)
		return;

	address.sin_family = AF_INET;
	address.sin_port = htons(rxperf_port);
	address.sin_addr.s_addr = INADDR_ANY;

	if (lwip_bind(sock, (struct sockaddr *)&address, sizeof (address)) < 0) {
#ifdef OS_IS_FREERTOS
		vTaskDelete(NULL);
#endif
		return;
	}

	lwip_listen(sock, 0);

	size = sizeof(remote);
	new_sd = lwip_accept(sock, (struct sockaddr *)&remote, (socklen_t*)&size);

	while (1) {
#if (USE_JUMBO_FRAMES==1)
		char recv_buf[9700];
		/* keep reading data */
		if (lwip_read(new_sd, recv_buf, 8000) <= 0)
			break;
#else
		char recv_buf[1500];
		/* keep reading data */
		if (lwip_read(new_sd, recv_buf, 1460) <= 0)
			break;
#endif
	}

	print("Connection closed. RXPERF exiting.\r\n");

    lwip_close(new_sd);
#ifdef OS_IS_FREERTOS
	xil_printf("Rx IPERF Thread is being DELETED\r\n");
    vTaskDelete(NULL);
#endif
}
Пример #8
0
int listen(int sockfd, int backlog)
{
    struct fdtab_entry *e = fdtab_get(sockfd);

    switch(e->type) {
    case FDTAB_TYPE_UNIX_SOCKET:
        POSIXCOMPAT_DEBUG("listen(%d, %d)\n", sockfd, backlog);
        struct _unix_socket *us = e->handle;

        errval_t err =
            unixsock_export(us, unixsock_listening, unixsock_connected,
                            get_default_waitset(), IDC_EXPORT_FLAGS_DEFAULT);
        if(err_is_fail(err)) {
            DEBUG_ERR(err, "unixsock_export failed");
            return -1;
        }
        while(us->u.passive.listen_iref == NULL_IREF) {
            // XXX: Should wait only on monitor
            event_dispatch(get_default_waitset());
        }

        us->passive = true;
        us->u.passive.max_backlog = backlog;
        us->u.passive.backlog = calloc(backlog, sizeof(struct unixsock_binding *));

        char str[128];
        snprintf(str, 128, "%"PRIuIREF, us->u.passive.listen_iref);
        err = vfs_write(us->vfs_handle, str, strlen(str), NULL);
        if(err_is_fail(err)) {
            USER_PANIC_ERR(err, "vfs_write");
        }
        break;

    case FDTAB_TYPE_LWIP_SOCKET:
        lwip_mutex_lock();
        int ret = lwip_listen(e->fd, backlog);
        lwip_mutex_unlock();
        return ret;

    default:
        return -1;
    }

    return 0;
}
Пример #9
0
/* ------------------------------------------------------------------------------------------------------
 *									   sockex_nonblocking_connect()
 *
 * Description : Handing socket receive data.
 *
 * Argument(s) : none.
 *
 */
void sockex_testrecv(void *arg)
{
//	int ret;
	struct sockaddr_in servaddr, cliaddr;
//	struct timeval tv;
	unsigned long cliaddr_len;
	
	LWIP_UNUSED_ARG(arg);

	memset(&servaddr, 0, sizeof(servaddr));							/* set up address to connect to */
	servaddr.sin_len = sizeof(servaddr);
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = PP_HTONS(SOCK_HOSR_PORT);
	servaddr.sin_addr.s_addr = lwIPLocalIPAddrGet();				/* Set local IP address.*/

	listenfd = lwip_socket(AF_INET, SOCK_STREAM, 0);

	lwip_bind(listenfd, (struct sockaddr *)&servaddr, sizeof(struct sockaddr));

	lwip_listen(listenfd, SOCK_HOSR_PORT);

	RS232printf("Accepting connections ...\n");
	
	cliaddr_len = sizeof(cliaddr);
	
	for(;;)
	{
		connfd = lwip_accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddr_len);
		if(connfd <= 0)
		{
			OSTimeDly(2);
			continue;
		}
		else
		{
			connfd = connfd;
			RS232printf("cli is ok!");
		}
//		lwip_select();
		
		OSTimeDly(2);
	}
}
Пример #10
0
/* http server */
int
web_application_thread()
{
    int sock, new_sd;
    struct sockaddr_in address, remote;
    socklen_t size;

    /* create a TCP socket */
    if ((sock = lwip_socket(AF_INET, SOCK_STREAM, 0)) < 0)
        return 0;

    /* bind to port 80 at any interface */
    address.sin_family = AF_INET;
    address.sin_port = htons(http_port);
    address.sin_addr.s_addr = INADDR_ANY;
    if (lwip_bind(sock, (struct sockaddr *) &address, sizeof(address)) < 0)
        return 0;

    /* listen for incoming connections */
    lwip_listen(sock, 5);

    size = sizeof(remote);
    while (1) {
    	sys_thread_t new_thread;

        new_sd =
            lwip_accept(sock, (struct sockaddr *) &remote,
                        &size);

        /* spawn a separate handler for each request */
        new_thread = sys_thread_new("httpd", (void (*)(void *)) process_http_request,
                       (void *) new_sd, THREAD_STACKSIZE, DEFAULT_THREAD_PRIO);

        /* close connection if no new threads available */
        if (new_thread == 0) {
            close(new_sd);
        }
    }

    return 0;
}
Пример #11
0
/* http server */
int
web_application_thread()
{
    int sock, new_sd;
    struct sockaddr_in address, remote;
    int size;

    /* create a TCP socket */
    if ((sock = lwip_socket(AF_INET, SOCK_STREAM, 0)) < 0) {
#ifdef OS_IS_FREERTOS
    vTaskDelete(NULL);
#endif
        return -1;
    }

    /* bind to port 80 at any interface */
    address.sin_family = AF_INET;
    address.sin_port = htons(http_port);
    address.sin_addr.s_addr = INADDR_ANY;
    if (lwip_bind(sock, (struct sockaddr *)&address, sizeof (address)) < 0) {
#ifdef OS_IS_FREERTOS
    vTaskDelete(NULL);
#endif
        return -1;
    }

    /* listen for incoming connections */
    lwip_listen(sock, 0);

    size = sizeof(remote);
    while (1) {
        new_sd = lwip_accept(sock, (struct sockaddr *)&remote, (socklen_t *)&size);
        /* spawn a separate handler for each request */
        process_http_request((void*)new_sd);
        //sys_thread_new("httpd", (void(*)(void*))process_http_request, (void*)new_sd,
        //                THREAD_STACKSIZE,
        //                DEFAULT_THREAD_PRIO);
    }
    return 0;
}
Пример #12
0
void Test_lwIP()
{
    int server;
    int client;   
    int acceptSock;
    int nonblock;
    int recvd;

    struct sockaddr_in addr, acceptAddr;
    socklen_t len;

    // tcp interface variables 
    struct ip_addr IpAddrLB;
    
    IP4_ADDR( &IpAddrLB, 127,0,0,1); //Loopback  

    addr.sin_family = AF_INET;
    addr.sin_port = 8080;
    addr.sin_addr.s_addr = *(u32_t*)&IpAddrLB;
    addr.sin_len = sizeof(struct sockaddr_in);

    server = lwip_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    client = lwip_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    nonblock = 1;

    if(server == -1 || client == -1) lcd_printf("Sockets were not created!\n");

    if(-1 == lwip_ioctl(server, FIONBIO, (void*)&nonblock)) lcd_printf("Error ioctl 1\n");
    if(-1 == lwip_ioctl(client, FIONBIO, (void*)&nonblock)) lcd_printf("Error ioctl 2\n");

    len = sizeof(addr);

    if(-1 == lwip_bind( server, (const struct sockaddr*)&addr, len ))lcd_printf("Error bind\n");

    if(-1 == lwip_listen( server, 2 )) lcd_printf("Error listen\n");

   / / Set up a tcp connection for client: Bind, Connect
Пример #13
0
int OTAClass::beginLocal(uint16_t port, bool reboot_when_success) {

    int ret = -1;

    // variables for image processing
    flash_t flash;
    uint32_t img2_addr, img2_len, img3_addr, img3_len;
    uint32_t img_upper_bound;
    uint32_t checksum = 0;
    uint32_t signature1, signature2;

    // variables for network processing
    int server_socket = -1;
    int client_socket = -1;
    struct sockaddr_in localHost;
    struct sockaddr_in client_addr;
    int socket_error, socket_timeout;
    socklen_t optlen;

    // variables for OTA
    unsigned char *buf = NULL;
    int read_bytes = 0, processed_len;
    uint32_t file_info[3];
    uint32_t ota_len;
    uint32_t ota_blk_size = 0;

    int i, n;

    do {
        sync_ota_addr();

        get_image_info(&img2_addr, &img2_len, &img3_addr, &img3_len);
        img_upper_bound = img2_addr + 0x10 + img2_len; // image2 base + header + len
        if (img3_len > 0) {
            img_upper_bound += 0x10 + img3_len; // image 3 header + len
        }

        if ((ota_addr & 0xfff != 0) || (ota_addr == ~0x0) || (ota_addr < img_upper_bound)) {
            OTA_PRINTF("Invalid OTA address: %08X\r\n", ota_addr);
            break;
        }

        buf = (unsigned char *) malloc (BUFSIZE);
        if (buf == NULL) {
            OTA_PRINTF("Fail to allocate memory\r\n");
            break;
        }

        server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (server_socket < 0) {
            OTA_PRINTF("Fail to create socket\r\n");
            break;
        }

        memset(&localHost, 0, sizeof(localHost));
        localHost.sin_family = AF_INET;
        localHost.sin_port = htons(port);
        localHost.sin_addr.s_addr = INADDR_ANY;

        if (lwip_bind(server_socket, (struct sockaddr *)&localHost, sizeof(localHost)) < 0) {
            OTA_PRINTF("Bind fail\r\n");
            break;
        }

        if (lwip_listen(server_socket , 1) < 0) {
            OTA_PRINTF("Listen fail\r\n");
            break;
        }

        OTA_PRINTF("Wait for client\r\n");
        n = (int) sizeof( client_addr );
        memset(&client_addr, 0, sizeof(client_addr));
        client_socket = lwip_accept(server_socket, (struct sockaddr *) &client_addr, (socklen_t *)&n);
        OTA_PRINTF("Client connected. IP:%s port:%d\r\n\r\n", inet_ntoa(client_addr.sin_addr.s_addr), ntohs(client_addr.sin_port));

        socket_timeout = DEFAULT_IMAGE_DOWNLOAD_TIMEOUT;
        lwip_setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &socket_timeout, sizeof(socket_timeout));        

        OTA_PRINTF("Read OTA info...\r\n");
        read_bytes = read(client_socket, file_info, sizeof(file_info));
        if (read_bytes < 0) {
           OTA_PRINTF("Fail to read OTA info\r\n");
           break;
        }

        if (file_info[2] == 0) {
            OTA_PRINTF("OTA image len is 0\r\n");
            break;
        }

        ota_len = file_info[2];
        ota_blk_size = ((ota_len - 1) / 4096) + 1;
        for (i = 0; i < ota_blk_size; i++) {
            flash_erase_sector(&flash, ota_addr + i * 4096);
        }

        OTA_PRINTF("Start download\r\n");

        // Now download OTA image
        processed_len = 0;
        while( processed_len < ota_len ) {
            memset(buf, 0, BUFSIZE);
            read_bytes = read(client_socket, buf, BUFSIZE);

            if (read_bytes < 0) {
                optlen = sizeof(socket_error);
                getsockopt(client_socket, SOL_SOCKET, SO_ERROR, &socket_error, &optlen);
                if (socket_error == EAGAIN) {
                    // socket timeout
                }
                break;
            }

            if (flash_stream_write(&flash, ota_addr + processed_len, read_bytes, buf) < 0) {
                OTA_PRINTF("Write sector fail\r\n");
                break;
            }

            processed_len += read_bytes;
        }

        if (processed_len != ota_len) {
            OTA_PRINTF("Download fail\r\n");
            break;
        }

        // Read OTA image from flash and calculate checksum
        checksum = processed_len = 0;
        while ( processed_len < ota_len ) {
            n = (processed_len + BUFSIZE < ota_len) ? BUFSIZE : (ota_len - processed_len);
            flash_stream_read(&flash, ota_addr + processed_len, n, buf);
            for (i=0; i<n; i++) checksum += (buf[i] & 0xFF);
            processed_len += n;
        }

        if (checksum != file_info[0]) {
            OTA_PRINTF("Bad checksum:%d expected:%d\r\n", checksum, file_info[0]);
            break;
        }

        // Put signature for OTA image
        flash_write_word(&flash, ota_addr +  8, 0x35393138);
        flash_write_word(&flash, ota_addr + 12, 0x31313738);
        flash_read_word(&flash, ota_addr +  8, &signature1);
        flash_read_word(&flash, ota_addr + 12, &signature2);
        if (signature1 != 0x35393138 || signature2 != 0x31313738) {
            OTA_PRINTF("Put signature fail\r\n");
            break;
        }

        // Mark image 2 as old image
        flash_write_word(&flash, img2_addr + 8, 0x35393130);

        ret = 0;
        OTA_PRINTF("OTA success\r\n");

    } while (0);

    if (buf != NULL) {
        free(buf);
    }

    if (server_socket >= 0) {
        close(server_socket);
    }

    if (client_socket >= 0) {
        close(client_socket);
    }

    if (ret < 0) {
        OTA_PRINTF("OTA fail\r\n");
    } else {
        if (reboot_when_success) {
            sys_reset();
        }
    }

    return ret;
}
Пример #14
0
int Socket::Listen()
{
    return lwip_listen(socket_->fd, 5); /*todo 5?*/
}
Пример #15
0
int LWIP_SOCKETS_Driver::Listen(SOCK_SOCKET socket, int backlog)
{    
    NATIVE_PROFILE_PAL_NETWORK();
    
    return lwip_listen(socket, backlog);
}
Пример #16
0
void vBasicSocketsCommandInterpreterTask( void *pvParameters )
{
    long lSocket, lClientFd, lBytes, lAddrLen = sizeof( struct sockaddr_in ), lInputIndex;
    struct sockaddr_in sLocalAddr;
    struct sockaddr_in client_addr;
    const char *pcWelcomeMessage = "FreeRTOS command server - connection accepted.\r\nType Help to view a list of registered commands.\r\n\r\n>";
    char cInChar;
    static char cInputString[ cmdMAX_INPUT_SIZE ], cOutputString[ cmdMAX_OUTPUT_SIZE ];
    portBASE_TYPE xReturned;
    extern void vRegisterSampleCLICommands( void );

    ( void ) pvParameters;

    /* Register the standard CLI commands. */
    vRegisterSampleCLICommands();

    lSocket = lwip_socket(AF_INET, SOCK_STREAM, 0);

    if( lSocket >= 0 )
    {
        memset((char *)&sLocalAddr, 0, sizeof(sLocalAddr));
        sLocalAddr.sin_family = AF_INET;
        sLocalAddr.sin_len = sizeof(sLocalAddr);
        sLocalAddr.sin_addr.s_addr = htonl(INADDR_ANY);
        sLocalAddr.sin_port = ntohs( ( ( unsigned short ) 23 ) );

        if( lwip_bind( lSocket, ( struct sockaddr *) &sLocalAddr, sizeof( sLocalAddr ) ) < 0 )
        {
            lwip_close( lSocket );
            vTaskDelete( NULL );
        }

        if( lwip_listen( lSocket, 20 ) != 0 )
        {
            lwip_close( lSocket );
            vTaskDelete( NULL );
        }

        for( ;; )
        {

            lClientFd = lwip_accept(lSocket, ( struct sockaddr * ) &client_addr, ( u32_t * ) &lAddrLen );

            if( lClientFd > 0L )
            {
                lwip_send( lClientFd, pcWelcomeMessage, strlen( ( const char * ) pcWelcomeMessage ), 0 );

                lInputIndex = 0;
                memset( cInputString, 0x00, cmdMAX_INPUT_SIZE );

                do
                {
                    lBytes = lwip_recv( lClientFd, &cInChar, sizeof( cInChar ), 0 );

                    if( lBytes > 0L )
                    {
                        if( cInChar == '\n' )
                        {
                            /* The input string has been terminated.  Was the
                            input a quit command? */
                            if( strcmp( "quit", ( const char * ) cInputString ) == 0 )
                            {
                                /* Set lBytes to 0 to close the connection. */
                                lBytes = 0L;
                            }
                            else
                            {
                                /* The input string was not a quit command.
                                Pass the string to the command interpreter. */
                                do
                                {
                                    /* Get the next output string from the command interpreter. */
                                    xReturned = FreeRTOS_CLIProcessCommand( cInputString, cOutputString, cmdMAX_INPUT_SIZE );
                                    lwip_send( lClientFd, cOutputString, strlen( ( const char * ) cOutputString ), 0 );

                                } while( xReturned != pdFALSE );


                                /* All the strings generated by the input
                                command have been sent.  Clear the input
                                string ready to receive the next command. */
                                lInputIndex = 0;
                                memset( cInputString, 0x00, cmdMAX_INPUT_SIZE );
                                lwip_send( lClientFd, "\r\n>", strlen( "\r\n>" ), 0 );
                            }
                        }
                        else
                        {
                            if( cInChar == '\r' )
                            {
                                /* Ignore the character. */
                            }
                            else if( cInChar == '\b' )
                            {
                                /* Backspace was pressed.  Erase the last
                                character in the string - if any. */
                                if( lInputIndex > 0 )
                                {
                                    lInputIndex--;
                                    cInputString[ lInputIndex ] = '\0';
                                }
                            }
                            else
                            {
                                /* A character was entered.  Add it to the string
                                entered so far.  When a \n is entered the complete
                                string will be passed to the command interpreter. */
                                if( lInputIndex < cmdMAX_INPUT_SIZE )
                                {
                                    cInputString[ lInputIndex ] = cInChar;
                                    lInputIndex++;
                                }
                            }
                        }
                    }

                } while( lBytes > 0L );

                lwip_close( lClientFd );
            }
        }
    }

    /* Will only get here if a listening socket could not be created. */
    vTaskDelete( NULL );
}
Пример #17
0
int zts_listen(int fd, int backlog)
{
	return (!_run_service || !_run_lwip_tcpip) ? ZTS_ERR_SERVICE : lwip_listen(fd, backlog);
}
Пример #18
0
static void   SC_Listen(__SYSCALL_PARAM_BLOCK*  pspb)
{
	pspb->lpRetValue = (LPVOID)lwip_listen((INT)PARAM(0),(INT)PARAM(1));
}
Пример #19
0
END_TEST

START_TEST(test_sockets_recv_after_rst)
{
  int sl, sact;
  int spass = -1;
  int ret;
  struct sockaddr_in sa_listen;
  const u16_t port = 1234;
  int arg;
  const char txbuf[] = "something";
  char rxbuf[16];
  struct lwip_sock *sact_sock;
  int err;
  LWIP_UNUSED_ARG(_i);

  fail_unless(test_sockets_get_used_count() == 0);

  memset(&sa_listen, 0, sizeof(sa_listen));
  sa_listen.sin_family = AF_INET;
  sa_listen.sin_port = PP_HTONS(port);
  sa_listen.sin_addr.s_addr = PP_HTONL(INADDR_LOOPBACK);

  /* set up the listener */
  sl = lwip_socket(AF_INET, SOCK_STREAM, 0);
  fail_unless(sl >= 0);
  fail_unless(test_sockets_get_used_count() == 0);

  ret = lwip_bind(sl, (struct sockaddr *)&sa_listen, sizeof(sa_listen));
  fail_unless(ret == 0);
  ret = lwip_listen(sl, 0);
  fail_unless(ret == 0);

  /* set up the client */
  sact = lwip_socket(AF_INET, SOCK_STREAM, 0);
  fail_unless(sact >= 0);
  fail_unless(test_sockets_get_used_count() == 0);
  /* set the client to nonblocking to simplify this test */
  arg = 1;
  ret = lwip_ioctl(sact, FIONBIO, &arg);
  fail_unless(ret == 0);
  /* connect */
  do {
    ret = lwip_connect(sact, (struct sockaddr *)&sa_listen, sizeof(sa_listen));
    err = errno;
    fail_unless((ret == 0) || (ret == -1));
    if (ret != 0) {
      if (err == EISCONN) {
        /* Although this is not valid, use EISCONN as an indicator for successful connection.
           This marks us as "connect phase is done". On error, we would either have a different
           errno code or "send" fails later... -> good enough for this test. */
        ret = 0;
      } else {
        fail_unless(err == EINPROGRESS);
        if (err != EINPROGRESS) {
          goto cleanup;
        }
        /* we're in progress: little side check: test for EALREADY */
        ret = lwip_connect(sact, (struct sockaddr *)&sa_listen, sizeof(sa_listen));
        err = errno;
        fail_unless(ret == -1);
        fail_unless(err == EALREADY);
        if ((ret != -1) || (err != EALREADY)) {
          goto cleanup;
        }
      }
      tcpip_thread_poll_one();
      tcpip_thread_poll_one();
      tcpip_thread_poll_one();
      tcpip_thread_poll_one();
    }
  } while (ret != 0);
  fail_unless(ret == 0);

  /* accept the server connection part */
  spass = lwip_accept(sl, NULL, NULL);
  fail_unless(spass >= 0);

  /* write data from client */
  ret = lwip_send(sact, txbuf, sizeof(txbuf), 0);
  fail_unless(ret == sizeof(txbuf));

  tcpip_thread_poll_one();
  tcpip_thread_poll_one();

  /* issue RST (This is a HACK, don't try this in your own app!) */
  sact_sock = lwip_socket_dbg_get_socket(sact);
  fail_unless(sact_sock != NULL);
  if (sact_sock != NULL) {
    struct netconn *sact_conn = sact_sock->conn;
    fail_unless(sact_conn != NULL);
    if (sact_conn != NULL) {
      struct tcp_pcb *pcb = sact_conn->pcb.tcp;
      fail_unless(pcb != NULL);
      if (pcb != NULL) {
        tcp_rst(pcb, pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
                     pcb->local_port, pcb->remote_port);
      }
    }
  }
  tcpip_thread_poll_one();
  tcpip_thread_poll_one();

  /* expect to receive data first */
  ret = lwip_recv(spass, rxbuf, sizeof(rxbuf), 0);
  fail_unless(ret > 0);
  tcpip_thread_poll_one();
  tcpip_thread_poll_one();

  /* expect to receive RST indication */
  ret = lwip_recv(spass, rxbuf, sizeof(rxbuf), 0);
  fail_unless(ret == -1);
  err = errno;
  fail_unless(err == ECONNRESET);
  tcpip_thread_poll_one();
  tcpip_thread_poll_one();

  /* expect to receive ENOTCONN indication */
  ret = lwip_recv(spass, rxbuf, sizeof(rxbuf), 0);
  fail_unless(ret == -1);
  err = errno;
  fail_unless(err == ENOTCONN);
  tcpip_thread_poll_one();
  tcpip_thread_poll_one();

  /* expect to receive ENOTCONN indication */
  ret = lwip_recv(spass, rxbuf, sizeof(rxbuf), 0);
  fail_unless(ret == -1);
  err = errno;
  fail_unless(err == ENOTCONN);
  tcpip_thread_poll_one();
  tcpip_thread_poll_one();

cleanup:
  ret = lwip_close(sl);
  fail_unless(ret == 0);
  ret = lwip_close(sact);
  fail_unless(ret == 0);
  if (spass >= 0) {
    ret = lwip_close(spass);
    fail_unless(ret == 0);
  }
}
Пример #20
0
/* ------------------------------------------------------------------------------------------------------
 *									      sockex_selects()
 *
 * Description : socket selects test.
 *
 * Argument(s) : none.
 *
 */
void sockex_selects(void *arg)
{
	int sock_fd, new_fd;
	struct sockaddr_in server_addr;
	struct sockaddr_in client_addr;
	socklen_t sin_size;
	int yes;
	INT8U buf[BUF_SIZE];
	int ret;
	int i;
	
	fd_set fdsr;													/* Create file descriptor.*/
	int maxsock;
	struct timeval tv;
	
	conn_amount = 0;
	LWIP_UNUSED_ARG(arg);
	
	sock_fd = lwip_socket(AF_INET, SOCK_STREAM, 0);
	
	yes = 1;
	ret = lwip_setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
	if(ret == -1)
	{
		return;
	}
	
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_len = sizeof(server_addr);
	server_addr.sin_port = PP_HTONS(SOCK_HOSR_PORT);
	server_addr.sin_addr.s_addr = lwIPLocalIPAddrGet();				/* IP_ADDR_ANY is '0.0.0.0'.*/
	
	lwip_bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
	lwip_listen(sock_fd, BACKLOG + 1);								/* MAX TCP client is BACKLOG.*/
	
	sin_size = sizeof(client_addr);
	maxsock = sock_fd;
	

	
	while(1)
	{
		FD_ZERO(&fdsr);												/* Initialize file descriptor set.*/
		FD_SET(sock_fd, &fdsr);

		tv.tv_sec = 10;												/* Timeout setting.*/
		tv.tv_usec = 0;
		
		for (i = 0; i < BACKLOG; i++)								/* Add active connection to fd set.*/
		{								
			if (fd_A[i] != 0) {
				FD_SET(fd_A[i], &fdsr);
			}
		}
		
		ret = lwip_select(maxsock + 1, &fdsr, NULL, NULL, &tv);
		if(ret < 0)
		{
			break;
		}
		else if(ret == 0)
		{
			continue;
		}
		
		for (i = 0; i < conn_amount; i++)							/* Check every fd in the set.*/
		{
			if (FD_ISSET(fd_A[i], &fdsr))
			{
				int opt = 100;										/* set recv timeout (100 ms) */
				lwip_setsockopt(fd_A[i], SOL_SOCKET, SO_RCVTIMEO, &opt, sizeof(int));

				ret = lwip_read(fd_A[i], buf, 8);
				if (ret <= 0)
				{
// 					lwip_close(fd_A[i]);
// 					FD_CLR(fd_A[i], &fdsr);
// 					fd_A[i] = 0;
				}
				else        										/* receive data.*/
				{
					if((buf[0] == 'C')&&(buf[1] == 'o'))
					{
// 						address_t addr;
// 						INT8U mac[8] = {0x00, 0x12, 0x4B, 0x00, 0x01, 0xC0, 0xB7, 0xE0};
// 						addr.mode = LONG_ADDR;
// 						utilReverseBuf(mac, 8);
// 						memcpy(addr.long_addr, mac, 8);
// 						mac_tx_handle(&addr, &buf[7], 1, MAC_DATA);
					}
					if (ret < BUF_SIZE)
						memset(&buf[ret], '\0', 1);
				}
			}
		}

		if(FD_ISSET(sock_fd, &fdsr))								/* Check whether a new connection comes.*/
		{
			new_fd = lwip_accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size);
			if(new_fd <= 0)
			{
				continue;
			}
//			lwip_send(new_fd, "con", 4, 0);
			if(conn_amount < BACKLOG)								/* Add to fd queue.*/
			{
				fd_A[conn_amount++] = new_fd;
				
				if(new_fd > maxsock)
					maxsock = new_fd;
			}
			else
			{
//				conn_amount = 0;
				lwip_close(fd_A[conn_amount-1]);
				fd_A[conn_amount-1] = new_fd;
				if(new_fd > maxsock)
					maxsock = new_fd;
//				lwip_send(new_fd, "bye", 4, 0);
//				lwip_close(new_fd);									/* Close larger than 5 socket.*/
			}
		}
		
// 		for (i = 0; i < BACKLOG; i++)								/* Close other connections.*/
// 		{
// 			if (fd_A[i] != 0) {
// 				lwip_close(fd_A[i]);
// 			}
// 		}
	}
}
Пример #21
0
void net_listen_thread_entry(void *p)
{
    int listenfd;
    struct sockaddr_in saddr;
    fd_set readset;

    // check mode first.
    if( !((getWorkingMode() == TCP_SERVER) || (getWorkingMode() == TCP_AUTO)) )
        return;
    // Acquire our socket for listening for connections
    listenfd = lwip_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if( listenfd == -1 )
    {
        rt_kprintf("Can not create socket!\n");
        return;
    }

    memset(&saddr, 0, sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = htonl(INADDR_ANY);
    saddr.sin_port = htons(getListenPort());     //server port

    if (lwip_bind(listenfd, (struct sockaddr *) &saddr, sizeof(saddr)) == -1)
    {
        lwip_close(listenfd);
        rt_kprintf("Socket bind failed!\n");
        return;
    }

    /* Put socket into listening mode */
    if (lwip_listen(listenfd, MAX_LISTEN_SOCK) == -1)
    {
        lwip_close(listenfd);
        rt_kprintf("Listen failed.\n");
        return;
    }

    /* Wait for data or a new connection */
    while(1)
    {
        /* Determine what sockets need to be in readset */
        FD_ZERO(&readset);
        FD_SET(listenfd, &readset);

        // wait forever.
        if( lwip_select(listenfd+1, &readset, 0, 0, 0) == 0 )
            continue;

        if (FD_ISSET(listenfd, &readset))
        {
            int i;
            socklen_t clilen = sizeof(struct sockaddr_in);

            for( i = 0 ; i < SOCKET_LIST_SIZE ; i++ )
            {
                // we don't block here.
                rt_err_t ret = rt_mutex_take(&(socket_list[i].mu_sock),RT_WAITING_NO);
                if( ret == -RT_ETIMEOUT )
                    continue;

                // we already took the mutex here.
                if( socket_list[i].used )
                {
                    rt_mutex_release(&(socket_list[i].mu_sock));
                    continue;
                }

                // it's an empty slot.
                socket_list[i].socket = lwip_accept(listenfd,
                        (struct sockaddr *)&(socket_list[i].cliaddr),&clilen);
                // if accept failed.
                if( socket_list[i].socket < 0 )
                {
                    rt_kprintf("Accept failed!\n");
                }
                // accept successfully.
                else
                {
                    int optval = 1;
                    // set keepalive.
                    lwip_setsockopt(socket_list[i].socket,SOL_SOCKET,SO_KEEPALIVE,&optval,sizeof(optval));
                    // set used flag.
                    socket_list[i].used = 1;
                    rt_kprintf("Accept connection.\n");
                }
                rt_mutex_release(&(socket_list[i].mu_sock));
                break;
            }

            // check if not enough slot.
            if( i == SOCKET_LIST_SIZE )
            {
                // just accept and disconnect.
                int sock;
                struct sockaddr cliaddr;
                socklen_t clilen;
                sock = lwip_accept(listenfd, &cliaddr, &clilen);
                if (sock >= 0)
                    lwip_close(sock);
                rt_kprintf("Not enough slot, accept and close connection.\n");
            }
        }
        else
        {
            rt_kprintf("ERROR,should not reach here!\n");
        }
    }
}
Пример #22
0
static void test_sockets_msgapi_tcp(int domain)
{
  #define BUF_SZ          (TCP_SND_BUF/4)
  #define TOTAL_DATA_SZ   (BUF_SZ*8) /* ~(TCP_SND_BUF*2) that accounts for integer rounding */
  #define NEED_TRAILER    (BUF_SZ % 4 != 0)
  int listnr, s1, s2, i, ret, opt;
  int bytes_written, bytes_read;
  struct sockaddr_storage addr_storage;
  socklen_t addr_size;
  struct iovec siovs[8];
  struct msghdr smsg;
  u8_t * snd_buf;
  struct iovec riovs[5];
  struct iovec riovs_tmp[5];
  struct msghdr rmsg;
  u8_t * rcv_buf;
  int    rcv_off;
  int    rcv_trailer = 0;
  u8_t val;

  test_sockets_init_loopback_addr(domain, &addr_storage, &addr_size);

  listnr = test_sockets_alloc_socket_nonblocking(domain, SOCK_STREAM);
  fail_unless(listnr >= 0);
  s1 = test_sockets_alloc_socket_nonblocking(domain, SOCK_STREAM);
  fail_unless(s1 >= 0);

  /* setup a listener socket on loopback with ephemeral port */
  ret = lwip_bind(listnr, (struct sockaddr*)&addr_storage, addr_size);
  fail_unless(ret == 0);
  ret = lwip_listen(listnr, 0);
  fail_unless(ret == 0);

  /* update address with ephemeral port */
  ret = lwip_getsockname(listnr, (struct sockaddr*)&addr_storage, &addr_size);
  fail_unless(ret == 0);

  /* connect, won't complete until we accept it */
  ret = lwip_connect(s1, (struct sockaddr*)&addr_storage, addr_size);
  fail_unless(ret == -1);
  fail_unless(errno == EINPROGRESS);

  while (tcpip_thread_poll_one());

  /* accept, creating the other side of the connection */
  s2 = lwip_accept(listnr, NULL, NULL);
  fail_unless(s2 >= 0);

  /* double check s1 is connected */
  ret = lwip_connect(s1, (struct sockaddr*)&addr_storage, addr_size);
  fail_unless(ret == -1);
  fail_unless(errno == EISCONN);

  /* set s2 to non-blocking, not inherited from listener */
  opt = lwip_fcntl(s2, F_GETFL, 0);
  fail_unless(opt == 6);
  opt = O_NONBLOCK;
  ret = lwip_fcntl(s2, F_SETFL, opt);
  fail_unless(ret == 0);

  /* we are done with listener, close it */
  ret = lwip_close(listnr);
  fail_unless(ret == 0);

  /* allocate a buffer for a stream of incrementing hex (0x00..0xFF) which we will use
     to create an input vector set that is larger than the TCP's send buffer. This will
     force execution of the partial IO vector send case */
  snd_buf = (u8_t*)mem_malloc(BUF_SZ);
  val = 0x00;
  fail_unless(snd_buf != NULL);
  for (i = 0; i < BUF_SZ; i++,val++) {
    snd_buf[i] = val;
  }

  /* send the buffer 8 times in one message, equating to TOTAL_DATA_SZ */
  for (i = 0; i < 8; i++) {
    siovs[i].iov_base = snd_buf;
    siovs[i].iov_len = BUF_SZ;
  }

  /* allocate a receive buffer, same size as snd_buf for easy verification */
  rcv_buf = (u8_t*)mem_calloc(1, BUF_SZ);
  fail_unless(rcv_buf != NULL);
  /* split across iovs */
  for (i = 0; i < 4; i++) {
    riovs[i].iov_base = &rcv_buf[i*(BUF_SZ/4)];
    riovs[i].iov_len = BUF_SZ/4;
  }
  /* handling trailing bytes if buffer doesn't evenly divide by 4 */
#if NEED_TRAILER
  if ((BUF_SZ % 4) != 0) {
    riovs[5].iov_base = &rcv_buf[4*(BUF_SZ/4)];
    riovs[5].iov_len = BUF_SZ - (4*(BUF_SZ/4));
    rcv_trailer = 1;
  }
#endif /* NEED_TRAILER */

  /* we use a copy of riovs since we'll be modifying base and len during
     receiving. This gives us an easy way to reset the iovs for next recvmsg */
  memcpy(riovs_tmp, riovs, sizeof(riovs));

  memset(&smsg, 0, sizeof(smsg));
  smsg.msg_iov = siovs;
  smsg.msg_iovlen = 8;

  memset(&rmsg, 0, sizeof(rmsg));
  rmsg.msg_iov = riovs_tmp;
  rmsg.msg_iovlen = (rcv_trailer ? 5 : 4);

  bytes_written = 0;
  bytes_read = 0;
  rcv_off = 0;

  while (bytes_written < TOTAL_DATA_SZ && (bytes_read < TOTAL_DATA_SZ)) {
    /* send data */
    if (bytes_written < TOTAL_DATA_SZ) {
      ret = lwip_sendmsg(s1, &smsg, 0);
      /* note: since we always receive after sending, there will be open
         space in the send buffer */
      fail_unless(ret > 0);
    
      bytes_written += ret;
      if (bytes_written < TOTAL_DATA_SZ) {
        test_sockets_msgapi_update_iovs(&smsg, (size_t)ret);
      }
    }

    while (tcpip_thread_poll_one());

    /* receive and verify data */
    do {
      if (bytes_read < TOTAL_DATA_SZ) {
        ret = lwip_recvmsg(s2, &rmsg, 0);
        fail_unless(ret > 0 || (ret == -1 && errno == EWOULDBLOCK));

        if (ret > 0) {
          rcv_off += ret;
          /* we have received a full buffer */
          if (rcv_off == BUF_SZ) {
            /* note: since iovs are just pointers, compare underlying buf */
            fail_unless(!memcmp(snd_buf, rcv_buf, BUF_SZ));
            bytes_read += BUF_SZ;
            /* reset receive state for next buffer */
            rcv_off = 0;
            memset(rcv_buf, 0, BUF_SZ);
            memcpy(riovs_tmp, riovs, sizeof(riovs));
            rmsg.msg_iov = riovs_tmp;
            rmsg.msg_iovlen = (rcv_trailer ? 5 : 4);
          } else { /* partial read */
            test_sockets_msgapi_update_iovs(&rmsg, (size_t)ret);
          }
        }
      } else {
        break;
      }
    } while(ret > 0);
  }
  
  ret = lwip_close(s1);
  fail_unless(ret == 0);
  ret = lwip_close(s2);
  fail_unless(ret == 0);
  mem_free(snd_buf);
  mem_free(rcv_buf);
}
Пример #23
0
static void echo_run()
{
	int lSocket;
	struct sockaddr_in sLocalAddr;

	lSocket = lwip_socket(AF_INET, SOCK_STREAM, 0);
	if (lSocket < 0) {
		puts("lSocket < 0");
		return;
	}

	memset((char *)&sLocalAddr, 0, sizeof(sLocalAddr));
	sLocalAddr.sin_family = AF_INET;
	sLocalAddr.sin_len = sizeof(sLocalAddr);
	sLocalAddr.sin_addr.s_addr = 0L; //htonl(IP_ADDR_ANY);
	sLocalAddr.sin_port = 23;

	if (lwip_bind(lSocket, (struct sockaddr *)&sLocalAddr, sizeof(sLocalAddr)) < 0) {
		lwip_close(lSocket);
		puts("bind failed");
		return;
	}

	if ( lwip_listen(lSocket, 20) != 0 ) {
		lwip_close(lSocket);
		puts("listen failed");
		return;
	}

	while (1) {
		int clientfd;
		struct sockaddr_in client_addr;
		int addrlen=sizeof(client_addr);
		char buffer[1024];
		int nbytes;

		clientfd = lwip_accept(lSocket, (struct sockaddr*)&client_addr, (socklen_t *)&addrlen);
		if (clientfd > 0) {
			puts("Accepted Echo Connection");

/*
		    int flags = fcntl(clientfd, F_GETFL, 0);
		    printf("flags = %d\n", flags);
		    fcntl(clientfd, F_SETFL, flags | O_NONBLOCK);

		    flags = fcntl(clientfd, F_GETFL, 0);
			if ((flags & O_NONBLOCK) == O_NONBLOCK) {
				printf("it's nonblocking");
			}
			else {
				printf("it's blocking.");
			}
*/
			struct timeval tv;
			tv.tv_sec = 500;
			tv.tv_usec = 500;
			setsockopt(clientfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval));

			do {
				nbytes = lwip_recv(clientfd, buffer, sizeof(buffer),0);

				if (nbytes > 0)
					lwip_send(clientfd, buffer, nbytes, 0);
				else
					lwip_send(clientfd, "#", 1, 0);
			}  while (nbytes != 0);

			puts("Closing connection.");
			lwip_close(clientfd);
		}
	}
	lwip_close(lSocket);
	puts("Socked closed.");
}
Пример #24
0
int listen(int s, int backlog) {
	BT_HANDLE hSocket = (BT_HANDLE)s;

	return lwip_listen(hSocket->socket, backlog);
}
Пример #25
0
/**
 * webnet thread entry
 */
static void webnet_thread(void *parameter)
{
    int listenfd;
    fd_set readset, tempfds;
    fd_set writeset;
    int i, maxfdp1;
    struct sockaddr_in webnet_saddr;

    /* First acquire our socket for listening for connections */
    listenfd = lwip_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    LWIP_ASSERT("webnet_thread(): Socket create failed.", listenfd >= 0);

    memset(&webnet_saddr, 0, sizeof(webnet_saddr));
    webnet_saddr.sin_family = AF_INET;
    webnet_saddr.sin_addr.s_addr = htonl(INADDR_ANY);
    webnet_saddr.sin_port = htons(WEBNET_PORT);     /* webnet server port */

    if (lwip_bind(listenfd, (struct sockaddr *) &webnet_saddr, sizeof(webnet_saddr)) == -1)
        LWIP_ASSERT("webnet_thread(): socket bind failed.", 0);

    /* Put socket into listening mode */
    if (lwip_listen(listenfd, MAX_SERV) == -1)
        LWIP_ASSERT("webnet_thread(): listen failed.", 0);

	/* initalize module (no session at present) */
	webnet_module_handle_event(RT_NULL, WEBNET_EVENT_INIT);

    /* Wait forever for network input: This could be connections or data */
    for (;;)
    {
        /* Determine what sockets need to be in readset */
        FD_ZERO(&readset);
        FD_ZERO(&writeset);
        FD_SET(listenfd, &readset);

		/* set fds in each sessions */
		maxfdp1 = webnet_sessions_set_fds(&readset, &writeset);
		if (maxfdp1 < listenfd + 1) maxfdp1 = listenfd + 1;

		/* use temporary fd set in select */
		tempfds = readset;
        /* Wait for data or a new connection */
        i = lwip_select(maxfdp1, &tempfds, 0, 0, 0);
        if (i == 0) continue;

        /* At least one descriptor is ready */
        if (FD_ISSET(listenfd, &tempfds))
        {
        	struct webnet_session* accept_session;
            /* We have a new connection request */
			accept_session = webnet_session_create(listenfd);
			if (accept_session == RT_NULL)
			{
                /* create session failed, just accept and then close */
                int sock;
                struct sockaddr cliaddr;
                socklen_t clilen;

				clilen = sizeof(struct sockaddr_in);
                sock = lwip_accept(listenfd, &cliaddr, &clilen);
                if (sock >= 0) lwip_close(sock);
            }
			else
			{
				/* add read fdset */
				FD_SET(accept_session->socket, &readset);
			}
        }

		webnet_sessions_handle_fds(&tempfds, &writeset);
    }
}
Пример #26
0
void tcp_setup_thread_entry(void *p)
{
    int listenfd;
    struct sockaddr_in saddr;
    fd_set readset;

    listenfd = lwip_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if( listenfd == -1 )
    {
        rt_kprintf("TCP setup can not create socket!\n");
        return;
    }

    memset(&saddr, 0, sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = htonl(INADDR_ANY);
    saddr.sin_port = htons(SETUP_TCP_PORT);

    if( lwip_bind(listenfd, (struct sockaddr *)&saddr, sizeof(saddr)) == -1 )
    {
        lwip_close(listenfd);
        rt_kprintf("TCP setup thread socket bind failed!\n");
        return;
    }

    /* Put socket into listening mode */
    if (lwip_listen(listenfd,2) == -1)
    {
        lwip_close(listenfd);
        rt_kprintf("Listen failed.\n");
        return;
    }

    /* Wait for data or a new connection */
    while(1)
    {
        /* Determine what sockets need to be in readset */
        FD_ZERO(&readset);
        FD_SET(listenfd, &readset);
        // wait forever.
        if( lwip_select(listenfd+1, &readset, 0, 0, 0) == 0 )
            continue;

        if (FD_ISSET(listenfd, &readset))
        {
            int ret,optval = 1;
            struct sockaddr_in addrin;
            u32_t sockaddrLen = sizeof(addrin);
            int socket = lwip_accept(listenfd,(struct sockaddr*)&addrin,&sockaddrLen);
            if( socket < 0 ) // accept failed.
            {
                rt_kprintf("TCP setup accept failed.\n");
                continue;
            }
            rt_kprintf("TCP setup accept connection.\n");
            // set socket keep alive.
            lwip_setsockopt(socket,SOL_SOCKET,SO_KEEPALIVE,&optval ,sizeof(optval));

            // begin to recv & send.
            while(1)
            {
                int dataLen,bytesRet;
                ret = blocking_lwip_recv(socket,setup_data_buf,P2X_HEADER_LEN,500);
                if( ret == 0 )
                    continue;
                if( ret != P2X_HEADER_LEN )
                    break;

                dataLen = P2X_GET_LENGTH(setup_data_buf);
                if( dataLen > 0 )
                {
                    int gotDataLen = blocking_lwip_recv(socket,setup_data_buf+P2X_HEADER_LEN,dataLen,500);
                    if( gotDataLen != dataLen )
                        break;
                }
                bytesRet = processCMD(setup_data_buf,P2X_HEADER_LEN+dataLen);
                if( lwip_send(socket,setup_data_buf,bytesRet,0) < 0 )
                    break;
            }
            rt_kprintf("TCP setup disconnected.\n");
            lwip_close(socket);
        }
    }// while(1) listen.
}
Пример #27
0
static void
serve_thread(uint32_t a) {
	struct st_args *args = (struct st_args *)a;
	union Nsipc *req = args->req;
	int r;

	switch (args->reqno) {
	case NSREQ_ACCEPT:
	{
		struct Nsret_accept ret;
		r = lwip_accept(req->accept.req_s, &ret.ret_addr,
				&ret.ret_addrlen);
		memmove(req, &ret, sizeof ret);
		break;
	}
	case NSREQ_BIND:
		r = lwip_bind(req->bind.req_s, &req->bind.req_name,
			      req->bind.req_namelen);
		break;
	case NSREQ_SHUTDOWN:
		r = lwip_shutdown(req->shutdown.req_s, req->shutdown.req_how);
		break;
	case NSREQ_CLOSE:
		r = lwip_close(req->close.req_s);
		break;
	case NSREQ_CONNECT:
		r = lwip_connect(req->connect.req_s, &req->connect.req_name,
				 req->connect.req_namelen);
		break;
	case NSREQ_LISTEN:
		r = lwip_listen(req->listen.req_s, req->listen.req_backlog);
		break;
	case NSREQ_RECV:
		// Note that we read the request fields before we
		// overwrite it with the response data.
		r = lwip_recv(req->recv.req_s, req->recvRet.ret_buf,
			      req->recv.req_len, req->recv.req_flags);
		break;
	case NSREQ_SEND:
		r = lwip_send(req->send.req_s, &req->send.req_buf,
			      req->send.req_size, req->send.req_flags);
		break;
	case NSREQ_SOCKET:
		r = lwip_socket(req->socket.req_domain, req->socket.req_type,
				req->socket.req_protocol);
		break;
	case NSREQ_INPUT:
		jif_input(&nif, (void *)&req->pkt);
		r = 0;
		break;
	default:
		cprintf("Invalid request code %d from %08x\n", args->whom, args->req);
		r = -E_INVAL;
		break;
	}

	if (r == -1) {
		char buf[100];
		snprintf(buf, sizeof buf, "ns req type %d", args->reqno);
		perror(buf);
	}

	if (args->reqno != NSREQ_INPUT)
		ipc_send(args->whom, r, 0, 0);

	put_buffer(args->req);
	sys_page_unmap(0, (void*) args->req);
	free(args);
}
Пример #28
0
/**************************************************************
 * void chargen_thread(void *arg)
 *
 * chargen task. This server will wait for connections on well
 * known TCP port number: 19. For every connection, the server will
 * write as much data as possible to the tcp port.
 **************************************************************/
static void chargen_thread(void *arg)
{
    int listenfd;
    struct sockaddr_in chargen_saddr;
    fd_set readset;
    fd_set writeset;
    int i, maxfdp1;
    struct charcb *p_charcb;

    /* First acquire our socket for listening for connections */
    listenfd = lwip_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    LWIP_ASSERT("chargen_thread(): Socket create failed.", listenfd >= 0);
    memset(&chargen_saddr, 0, sizeof(chargen_saddr));
    chargen_saddr.sin_family = AF_INET;
    chargen_saddr.sin_addr.s_addr = htonl(INADDR_ANY);
    chargen_saddr.sin_port = htons(19);     // Chargen server port

    if (lwip_bind(listenfd, (struct sockaddr *) &chargen_saddr, sizeof(chargen_saddr)) == -1)
        LWIP_ASSERT("chargen_thread(): Socket bind failed.", 0);

    /* Put socket into listening mode */
    if (lwip_listen(listenfd, MAX_SERV) == -1)
        LWIP_ASSERT("chargen_thread(): Listen failed.", 0);

    /* Wait forever for network input: This could be connections or data */
    for (;;) {
        maxfdp1 = listenfd+1;

        /* Determine what sockets need to be in readset */
        FD_ZERO(&readset);
        FD_ZERO(&writeset);
        FD_SET(listenfd, &readset);
        for (p_charcb = charcb_list; p_charcb; p_charcb = p_charcb->next) {
            if (maxfdp1 < p_charcb->socket + 1)
                maxfdp1 = p_charcb->socket + 1;
            FD_SET(p_charcb->socket, &readset);
            FD_SET(p_charcb->socket, &writeset);
        }

        /* Wait for data or a new connection */
        i = lwip_select(maxfdp1, &readset, &writeset, 0, 0);

        if (i == 0) continue;

        /* At least one descriptor is ready */
        if (FD_ISSET(listenfd, &readset)) {
            /* We have a new connection request!!! */
            /* Lets create a new control block */
            p_charcb = (struct charcb *)rt_calloc(1, sizeof(struct charcb));
            if (p_charcb) {
                p_charcb->socket = lwip_accept(listenfd,
                                               (struct sockaddr *) &p_charcb->cliaddr,
                                               &p_charcb->clilen);
                if (p_charcb->socket < 0)
                    rt_free(p_charcb);
                else {
                    /* Keep this tecb in our list */
                    p_charcb->next = charcb_list;
                    charcb_list = p_charcb;
                    p_charcb->nextchar = 0x21;
                }
            } else {
                /* No memory to accept connection. Just accept and then close */
                int sock;
                struct sockaddr cliaddr;
                socklen_t clilen;

                sock = lwip_accept(listenfd, &cliaddr, &clilen);
                if (sock >= 0)
                    lwip_close(sock);
            }
        }
        /* Go through list of connected clients and process data */
        for (p_charcb = charcb_list; p_charcb; p_charcb = p_charcb->next) {
            if (FD_ISSET(p_charcb->socket, &readset)) {
                /* This socket is ready for reading. This could be because someone typed
                 * some characters or it could be because the socket is now closed. Try reading
                 * some data to see. */
                if (do_read(p_charcb) < 0)
                    break;
            }
            if (FD_ISSET(p_charcb->socket, &writeset)) {
                char line[80];
                char setchar = p_charcb->nextchar;

                for( i = 0; i < 59; i++) {
                    line[i] = setchar;
                    if (++setchar == 0x7f)
                        setchar = 0x21;
                }
                line[i] = 0;
                strcat(line, "\n\r");
                if (lwip_write(p_charcb->socket, line, strlen(line)) < 0) {
                    close_chargen(p_charcb);
                    break;
                }
                if (++p_charcb->nextchar == 0x7f)
                    p_charcb->nextchar = 0x21;
            }
        }
    }
}
Пример #29
0
//--------------------------------------------------------------
void serverThread(void *args) // Server thread: Handle Client & packets
{
	int tcp_socket;
	struct sockaddr_in peer;
	int peerlen, r, err;

conn_retry:

	peer.sin_family = AF_INET;
	peer.sin_port = htons(SERVER_TCP_PORT);
	peer.sin_addr.s_addr = htonl(INADDR_ANY);
#ifdef _NETLOG
	netlog_send("%s: server init starting...\n", MODNAME);
#endif
	// create the socket
	tcp_socket = lwip_socket(AF_INET, SOCK_STREAM, 0);
	if (tcp_socket < 0) {
		err = -1;
		goto error;
	}
#ifdef _NETLOG
	netlog_send("%s: server socket created.\n", MODNAME);
#endif
	r = lwip_bind(tcp_socket,(struct sockaddr *)&peer,sizeof(peer));
	if (r < 0) {
		err = -2;
		goto error;
	}
#ifdef _NETLOG
	netlog_send("%s: bind OK.\n", MODNAME);
#endif
	r = lwip_listen(tcp_socket, 3);
	if (r < 0) {
		err = -3;
		goto error;
	}
#ifdef _NETLOG
	netlog_send("%s: server ready!\n", MODNAME);
#endif
	while(1) {
		peerlen = sizeof(peer);
		r = lwip_accept(tcp_socket,(struct sockaddr *)&peer, &peerlen);
		if (r < 0) {
			err = -4;
			goto error;
		}

		client_socket = r;

		r = handleClient(client_socket);
		if (r < 0) {
			lwip_close(client_socket);
#ifdef _NETLOG
			netlog_send("%s: Client Connection closed - error %d\n", MODNAME, r);
#endif
		}
	}

error:
	lwip_close(client_socket);
#ifdef _NETLOG
	netlog_send("%s: Client Connection closed - error %d\n", MODNAME, err);
#endif
	goto conn_retry;
}
Пример #30
0
int listen(int sockfd, int backlog)
{
  int sock = socket_for_fd(sockfd);
  return lwip_listen(sock, backlog);
}