Ejemplo n.º 1
0
static void cilservertest()
{
  long fd;
  long type;

  type = CIL_TEST;

  fd = socketconnect( servername );
  if ( fd >= 0 )
    {
      socketwrite( fd, (char *)&type, sizeof( long ) );
      socketclose( fd );
      fprintf( stderr, "CIL-SERVER may be running.\n" );
      exit( 1 );
    }
  fprintf( stderr, "CIL-SERVER is starting.\n" );

  fd = socketconnect( xservername );
  if ( fd >= 0 )
    {
      socketwrite( fd, (char *)&type, sizeof( long ) );
      socketclose( fd );
      fprintf( stderr, "XCIL-SERVER may be running.\n" );
      exit( 1 );
    }
  fprintf( stderr, "XCIL-SERVER is starting.\n" );

  if ( fork() != 0 ) exit( 0 );
}
Ejemplo n.º 2
0
static void cilserverexit
  _P0 (void)
{
  long fd;

  fd = socketconnect( servername );
  if ( fd >= 0 )
    {
      long type = CIL_EXIT;
      fprintf( stderr, "CIL-SERVER exit.\n" );
      socketwrite( fd, (char *)&type, sizeof( long ) );
      socketclose( fd );
    }
  else
    {
      fprintf( stderr, "CIL-SERVER wasn't running.\n" );
    }

  fd = socketconnect( xservername );
  if ( fd >= 0 )
    {
      long type = CIL_EXIT;
      fprintf( stderr, "XCIL-SERVER exit.\n" );
      socketwrite( fd, (char *)&type, sizeof( long ) );
      socketclose( fd );
    }
  else
    {
      fprintf( stderr, "XCIL-SERVER wasn't running.\n" );
    }

  exit( 1 );
}
Ejemplo n.º 3
0
// DHM - Nerve
void I_ShutdownNetwork( void ) {
	if ( globalNetworking && gameLocal != NULL ) {
		
		int curPlayer = DoomLib::GetPlayer();

		for (int player = 0; player < gameLocal->Interface.GetNumPlayers(); ++player)
		{
			DoomLib::SetPlayer( player );

			if ( IsValidSocket( ::g->insocket ) ) {
				I_Printf( "[-] Shut down insocket for player %d\n", DoomLib::GetPlayer() );
				shutdown( ::g->insocket, SHUT_RDWR );
				socketclose( ::g->insocket );
			}
			if ( IsValidSocket( ::g->sendsocket ) ) {
				I_Printf( "[-] Shut down sendsocket for player %d\n", DoomLib::GetPlayer() );
				shutdown( ::g->sendsocket, SHUT_RDWR );
				socketclose( ::g->sendsocket );
			}
		}

		DoomLib::SetPlayer(curPlayer);

		globalNetworking = false;
	}
}
Ejemplo n.º 4
0
void TCPServer::CloseSockets(){
    if (this->sockfd != -1){
        socketclose(this->sockfd);
    }
    if (this->clientfd != -1){
        socketclose(this->clientfd);
    }
    this->sockfd = -1;
    this->clientfd = -1;
}
Ejemplo n.º 5
0
void TcpReceiver::executeThread()
{
	serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
	if (serverSocket < 0)
		return;

    u32 enable = 1;
	setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));

	struct sockaddr_in bindAddress;
	memset(&bindAddress, 0, sizeof(bindAddress));
	bindAddress.sin_family = AF_INET;
	bindAddress.sin_port = serverPort;
	bindAddress.sin_addr.s_addr = INADDR_ANY;

	s32 ret;
	if ((ret = bind(serverSocket, (struct sockaddr *)&bindAddress, sizeof(bindAddress))) < 0) {
		socketclose(serverSocket);
		return;
	}

	if ((ret = listen(serverSocket, 3)) < 0) {
		socketclose(serverSocket);
		return;
	}

	struct sockaddr_in clientAddr;
	s32 addrlen = sizeof(struct sockaddr);

    while(!exitRequested)
    {
        s32 clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &addrlen);
        if(clientSocket >= 0)
        {
            u32 ipAddress = clientAddr.sin_addr.s_addr;
            serverReceiveStart(this, ipAddress);
            int result = loadToMemory(clientSocket, ipAddress);
            serverReceiveFinished(this, ipAddress, result);
            socketclose(clientSocket);

            if(result > 0)
                break;
        }
        else
        {
            os_usleep(100000);
        }
    }

    socketclose(serverSocket);
}
Ejemplo n.º 6
0
void cafiine_connect(int *psock) {
	extern unsigned int server_ip;
	struct sockaddr_in addr;
	int sock, ret;

	socket_lib_init();

	sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	CHECK_ERROR(sock == -1);

	addr.sin_family = AF_INET;
	addr.sin_port = 7332;
	addr.sin_addr.s_addr = server_ip;

	ret = connect(sock, (void *)&addr, sizeof(addr));
	CHECK_ERROR(ret < 0);
	ret = cafiine_handshake(sock);
	CHECK_ERROR(ret < 0);
	CHECK_ERROR(ret == BYTE_NORMAL);

	*psock = sock;
	return;
error:
	if (sock != -1)
		socketclose(sock);
	*psock = -1;
}
void udp_marker_rec_close(struct my_data_t *my_data) {
#   ifdef WIN32
    socketclose(my_data->socket_id);
#   else
    close(my_data->socket_id);
#   endif
}
Ejemplo n.º 8
0
int
udp_secho_close(void * pio)
{
   int   e=0;
   SOCKTYPE sock;

   sock = es_sock;
   es_sock = INVALID_SOCKET;

   if ( sock != INVALID_SOCKET )
   {
      ns_printf(pio,"udp echo - closing server socket\n");
      e = socketclose(sock);
      if (e)
      {
         e = t_errno(sock);
         ns_printf(pio,"udp echo: close error %d\n", e);
      }
   }

   if ( e )
      return UDPE_SRV_CLOSE_ERR ;
   else
      return SUCCESS ;
}
Ejemplo n.º 9
0
void log_close() {
#ifdef ENABLE_LOG
  if(socket_fd != -1) {
    socketclose(socket_fd);
  }
#endif
}
Ejemplo n.º 10
0
/***********************************************************************
* destroy a udp/tcp connection
* 	int *s = socket to close
***********************************************************************/
void close_conn(int32_t *s)
{
	if(*s != -1){
		shutdown(*s, SHUT_RDWR);
		socketclose(*s);
		*s = -1;
	}
}
Ejemplo n.º 11
0
void log_deinit(void)
{
    if(log_socket >= 0)
    {
        socketclose(log_socket);
        log_socket = -1;
    }
}
Ejemplo n.º 12
0
void sclose(int *socket_e)
{
	if(*socket_e != -1)
	{
		shutdown(*socket_e, SHUT_RDWR);
		socketclose(*socket_e);
		*socket_e = -1;
	}
}
Ejemplo n.º 13
0
void fs_disconnect(int sock) {
    CHECK_ERROR(sock == -1);

    char byte = BYTE_DISCONNECT;
    sendwait(sock, &byte, 1);

    socketclose(sock);
error:
    return;
}
Ejemplo n.º 14
0
int 
tcp_client_del(TCPCLIENT tcpclient)
{
   int   e;
   TCPCLIENT tmpclient, prevclient;

   /* Close the underlying socket */
   if (tcpclient->sock != INVALID_SOCKET)
   {  
      e = socketclose(tcpclient->sock);
      if (e)
      {
         e = t_errno(tcpclient->sock);
         ns_printf(tcpclient->pio,"tcp echo: close error %d\n", e);
      }
   }

   /* Remove from the q */
   if (tcpq == tcpclient)
   {
      /* It is the first node */
      tcpq = tcpq->next;
   }
   else
   {
      prevclient=tcpq;
      tmpclient=tcpq->next;
      while (tmpclient)
      {
         if (tmpclient == tcpclient)
         {
            /* Found the node in the list */
            prevclient->next=tmpclient->next ;
            break;
         }
         else
         {
            prevclient=tmpclient;
            tmpclient=tmpclient->next ;
         }
      }

      /* Was the node found in Q ? */
      if (tmpclient == NULL)
      {
         /* Node not found in Q !! */
         dtrap();
         return TCPE_NODE_NOT_FOUND ;
      }
   }

   npfree(tcpclient);

   return SUCCESS;
}
Ejemplo n.º 15
0
int socket_close(int fd)
{ 
#if defined(_WIN32) && !defined(_XBOX360)
   /* WinSock has headers from the stone age. */
   return closesocket(fd);
#elif defined(__CELLOS_LV2__)
   return socketclose(fd);
#else
   return close(fd);
#endif
}
Ejemplo n.º 16
0
int
tcp_secho_close(void * pio)
{
   int   e  =  0;       /* scratch error holder */
   int   retval   =  0; /* return last non-zero error */

   if (esvr_sock != INVALID_SOCKET)
   {
      e = socketclose(esvr_sock);
      if (e)
      {
         retval = e = t_errno(esvr_sock);
         ns_printf(pio,"tcp echo server: close error %d %s\n", e, so_perror(e));
      }
      else
      {
         ns_printf(pio,"tcp echo srv - closing.\n");
         esvr_sock = INVALID_SOCKET;
      }
   }

   if (srv_inbuf)
   {
      npfree(srv_inbuf);
      srv_inbuf=NULL;
   }
   if (elisten_sock == INVALID_SOCKET)
      return e;

   e = socketclose(elisten_sock);
   if (e)
   {
      retval = e = t_errno(elisten_sock);
      ns_printf(pio,"tcp echo: server close error %d %s\n", e, so_perror(e));
   }
   elisten_sock = INVALID_SOCKET;

   return retval;
}
Ejemplo n.º 17
0
/*----------------------------------------------------------------------*
                          rtp_net_closesocket
 *----------------------------------------------------------------------*/
int rtp_net_closesocket (RTP_HANDLE sockHandle)
{
    if (socketclose((int) sockHandle) == -1)
    {
	  	  int errVal = _rtp_get_last_socket_error(sockHandle);

#ifdef RTP_DEBUG
        RTP_DEBUG_OUTPUT_STR("rtp_net_closesocket: error returned ");
        RTP_DEBUG_OUTPUT_INT(errVal);
        RTP_DEBUG_OUTPUT_STR(".\n");
#endif
        return (-1);
    }

	rtpnetOpenSockets--;
    
    return (0);
}
Ejemplo n.º 18
0
void log_init(const char * ipString, int port)
{
	log_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (log_socket < 0)
		return;

	struct sockaddr_in connect_addr;
	memset(&connect_addr, 0, sizeof(connect_addr));
	connect_addr.sin_family = AF_INET;
	connect_addr.sin_port = port;
	inet_aton(ipString, &connect_addr.sin_addr);

	if(connect(log_socket, (struct sockaddr*)&connect_addr, sizeof(connect_addr)) < 0)
	{
	    socketclose(log_socket);
	    log_socket = -1;
	}
}
Ejemplo n.º 19
0
int 
udp_secho_init(void * pio)
{
   int   e;    /* error holder */
   struct sockaddr_in   me;   /* my IP info, for bind() */
   SOCKTYPE sock;

   if ( es_sock != INVALID_SOCKET )
   {
      ns_printf(pio,"udp echo server is already running.\n" );
      return SUCCESS;
   }
   ns_printf(pio,"udp echo server is starting.\n" );

   /* open UDP socket */
   sock = socket(AF_INET, SOCK_DGRAM, 0);
   if (sock == INVALID_SOCKET)
   {
      ns_printf(pio,"udp_echo: bad socket: %d\n", sock);
      return UDPE_SRV_BAD_SOCKET;
   }

   me.sin_family = AF_INET;
   me.sin_addr.s_addr = INADDR_ANY;
   me.sin_port = htons(ECHO_PORT);

   e = bind(sock, (struct sockaddr*)&me, sizeof(me));
   if (e != 0)
   {
      e = t_errno(sock);
      ns_printf(pio,"udp_echo: bind error: %d\n", e);
      socketclose(sock);
      return UDPE_SRV_BIND_FAILED;
   }

   es_sock = sock;

   /* put socket into non-blocking mode */
   setsockopt(sock, SOL_SOCKET, SO_NBIO, NULL, 0);

   return SUCCESS;
}
Ejemplo n.º 20
0
void log_init(void)
{
    if(log_socket > 0)
        return;

	log_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (log_socket < 0)
		return;

	struct sockaddr_in connect_addr;
	memset(&connect_addr, 0, sizeof(connect_addr));
	connect_addr.sin_family = AF_INET;
	connect_addr.sin_port = 4405;
	inet_aton("192.168.0.44", &connect_addr.sin_addr);

	if(connect(log_socket, (struct sockaddr*)&connect_addr, sizeof(connect_addr)) < 0)
	{
	    socketclose(log_socket);
	    log_socket = -1;
	}
}
Ejemplo n.º 21
0
static int network_interface_down(struct sockaddr_in *target, int *s)
{
   int ret = 0;
#if defined(_WIN32) && !defined(_XBOX360)
   /* WinSock has headers from the stone age. */
   ret = closesocket(*s);
#elif defined(__CELLOS_LV2__)
   ret = socketclose(*s);
#elif defined(VITA)
   if (net_memory)
      free(net_memory);
   sceNetSocketClose(*s);
#else
   ret = close(*s);
#endif
#if defined(__CELLOS_LV2__) && !defined(__PSL1GHT__)
   cellNetCtlTerm();
#elif defined(GEKKO) && !defined(HW_DOL)
   net_deinit();
#endif
   return ret;
}
Ejemplo n.º 22
0
int fs_connect(int *psock) {
    extern unsigned int server_ip;
    struct sockaddr_in addr;
    int sock, ret;

    // No ip means that we don't have any server running, so no logs
    if (server_ip == 0) {
        *psock = -1;
        return 0;
    }

    socket_lib_init();

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    CHECK_ERROR(sock == -1);

    addr.sin_family = AF_INET;
    addr.sin_port = 7332;
    addr.sin_addr.s_addr = server_ip;

    ret = connect(sock, (void *)&addr, sizeof(addr));
    CHECK_ERROR(ret < 0);

    ret = recvbyte(sock);
    CHECK_ERROR(ret < 0);

    *psock = sock;
    return 0;

error:
    if (sock != -1)
        socketclose(sock);

    *psock = -1;
    return -1;
}
Ejemplo n.º 23
0
int 
tcp_secho_init(void * pio)
{
   int   e;    /* error holder */
   struct sockaddr_in   me;   /* my IP info, for bind() */
   int   opt;

   if (tcpecho_server)
   {
      ns_printf(pio,"tcp echo srv - starting.\n");

      /* open TCP socket */
      elisten_sock = socket(AF_INET, SOCK_STREAM, 0);
      if (elisten_sock == INVALID_SOCKET)
      {
         ns_printf(pio,"TCP echo: bad socket: %d\n", elisten_sock);
         return TCPE_BAD_SOCKET ;
      }

      opt = 1;
      e = t_setsockopt(elisten_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
      if (e != 0)
      {
         e = t_errno(elisten_sock);
         dtrap();
         dprintf("error %d setting SO_REUSEADDR on port %d\n", e, ECHO_PORT);
         return SYS_SOCKETNULL;
      }

      me.sin_family = AF_INET;
      me.sin_addr.s_addr = INADDR_ANY;
      me.sin_port = htons(ECHO_PORT);

      e = bind(elisten_sock, (struct sockaddr*)&me, sizeof(me));
      if (e != 0)
      {
         e = t_errno(elisten_sock);
         ns_printf(pio,"tcp_echo: bad socket bind: %d, %s\n", e, so_perror(e));
         socketclose(elisten_sock);
         elisten_sock = INVALID_SOCKET;
         return TCPE_BIND_FAILED ;
      }
      e = listen(elisten_sock, 3);
      if (e != 0)
      {
         e = t_errno(elisten_sock);
         ns_printf(pio,"tcp_echo: bad socket listen: %d %s\n", e, so_perror(e));
         socketclose(elisten_sock);
         elisten_sock = INVALID_SOCKET;
         return TCPE_LISTEN_FAILED;
      }
      /* for listen socket into Non-blocking mode so we can poll accept */
      sock_noblock(elisten_sock, TRUE);
   }
   else
      ns_printf(pio,"tcp echo server not enabled\n");

   srv_inbuf = (char *)npalloc(ECHOBUFSIZE);
   if (srv_inbuf == NULL)
   {
      ns_printf(pio, "tcp server: alloc failed\n");
      socketclose(elisten_sock);
      elisten_sock = INVALID_SOCKET;
      return TCPE_LISTEN_FAILED;
   }

   return SUCCESS;
}
Ejemplo n.º 24
0
/*
 * SSSSimpleSocketServerTask()
 * 
 * This MicroC/OS-II thread spins forever after first establishing a listening
 * socket for our sss connection, binding it, and listening. Once setup,
 * it perpetually waits for incoming data to either the listening socket, or
 * (if a connection is active), the sss data socket. When data arrives, 
 * the approrpriate routine is called to either accept/reject a connection 
 * request, or process incoming data.
 */
void SSSSimpleSocketServerTask()
{
  // Объявления используемых переменных
	int errcode;
	int is_alive;
	int flag_exit = 0;
	char buffer_in[1024];
	char buffer_out[3] = {'1','\r','\n'};
	int len_buff = 1024;
	int fd_listen;
	struct sockaddr_in addr;
	edge_capture = 0xF;

    // Регистрируем обработчик прерываний от кнопок
	init_button_pio();

  while (1)
  {
	  // Создаем сокет, если не удалось создать, выдаем сообщение в консоль
	  if ((fd_listen = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	  {
	      alt_NetworkErrorHandler(EXPANDED_DIAGNOSIS_CODE,"[sss_task] Socket creation failed");
	  }
	  // Инициализируем структуру sockaddr_in, указав семейство адресов,
	  // IP-адрес и номер порта серверного приложения
	  // (для примера см. simple_socket_server)
	  addr.sin_family = AF_INET;
	  addr.sin_port = htons(SSS_PORT);
	  addr.sin_addr.s_addr = inet_addr("192.168.21.171");

	  // Устанавливаем соединение с сервером
	  errcode = connect(fd_listen, (struct sockaddr *)&addr, sizeof(addr));
	  if (errcode)
	  {
		  printf("Unable to connect to server!\n");
		  return;
	  }

	  // Получаем меню от сервера, выводим в консоль
	  errcode = recv(fd_listen, &buffer_in, len_buff, 0);
	  if (errcode == SOCKET_ERROR)
	  {
		  printf("Unable to get data from server!\n");
	 	  return;
	  }

	  printf(buffer_in);

	  is_alive = 1;
	  do
	  {
		  // Ожидаем сообщение о нажатии кнопки от обработчика прерывания

		  if (edge_capture != NONE_PRESSED)  // if button pressed
		  {
			  switch(edge_capture) {
		      	  case (BTN_RIGHT_PRESSED):
		      			buffer_out[0] = 'q';
		      	  	  	flag_exit = 1;
		      	  	  	break;
		          case (BTN_LEFT_PRESSED):
						buffer_out[0] = '1';
		        		break;
		          case (BTN_CNTR_LEFT):
						buffer_out[0] = '2';
		                break;
		          case (BTN_CNTR_RIGHT):
						buffer_out[0] = '3';
		        		break;
		      }


		  // Отправляем соответствующую команду на сервер
		  errcode = send(fd_listen, &buffer_out, 3, 0);
      	  if (errcode == SOCKET_ERROR)
      	  {
      		  printf("Unable to send data to server!\n");
      		  return;
      	  }
	       edge_capture = 0xF;
		  // Если была отправлена команда 'q', выходим из внутреннего
		  // цикла
	      if (flag_exit) {
	    	  flag_exit = 0;
	    	  break;
	      }
	      // В противном случае получаем ответ от сервера, выводим его
		  // в консоль
	      errcode = recv(fd_listen, &buffer_in, len_buff, 0);
	      if (errcode == SOCKET_ERROR)
	      {
	    	  printf("Unable to get data from server!\n");
	      	  return;
	      }
	      printf(buffer_in);
		  }
	  }
	  while (is_alive);

	  // Разрываем соединение
	  errcode = socketclose(fd_listen);
	  if (errcode == SOCKET_ERROR)
	  {
		  printf("Unable to close connection!\n");
	  	  return;
	  }

	  printf("Connection closed.\n");

	  // Ожидаем сообщение о нажатии кнопки от обработчика прерывания
	  // Перед повторным установлением соединения
	  while (edge_capture == NONE_PRESSED);
  } /* while (1) */

}
Ejemplo n.º 25
0
void TCPServer::DoTCPThreadInternal(){
    s32 ret;
    s32 len;
    while (1) {
        if(exitThread) break;
        memset(&(this->sock_addr),0,sizeof(sock_addr));
		sock_addr.sin_family = AF_INET;
		sock_addr.sin_port = DEFAULT_TCP_PORT;
		sock_addr.sin_addr.s_addr = 0;

		this->sockfd = ret = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		if(ret == -1){ ErrorHandling(); continue;}
        s32 enable = 1;

        setsockopt(this->sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));

		ret = bind(this->sockfd, (sockaddr *)&sock_addr, 16);
		if(ret < 0) { ErrorHandling(); continue;}
		ret = listen(this->sockfd, 1);
		if(ret < 0){ ErrorHandling(); continue;}

        do{
            if(HID_DEBUG){ printf("TCPServer::DoTCPThreadInternal(line %d): Waiting for a connection\n",__LINE__); }
            if(exitThread) break;
            len = 16;

            /**
                Handshake
                1. At first this server sends his protocol version
                2. The network clients answers with his preferred version (which needs to be equals or lower the version this server sent him) or an abort command.
                    3a. If the client sent a abort, close the connection and wait for another connection
                    3b. If the client sent his highest supported version, the server confirm that he is able to use this version (by sending the version back) or sending a abort command to disconnect.
            **/

            clientfd = ret = (s32)accept(sockfd, (sockaddr *)&(sock_addr),(socklen_t *) &len);

            if(ret == -1){ ErrorHandling(); break;}
            printf("TCPServer::DoTCPThreadInternal(line %d): TCP Connection accepted! Sending my protocol version: %d (0x%02X)\n",__LINE__, (WIIU_CP_TCP_HANDSHAKE - WIIU_CP_TCP_HANDSHAKE_VERSION_1)+1,WIIU_CP_TCP_HANDSHAKE);

            gUDPClientip = sock_addr.sin_addr.s_addr;
            UDPClient::createInstance();

            s32 ret;
            ret = ControllerPatcherNet::sendbyte(clientfd, WIIU_CP_TCP_HANDSHAKE); //Hey I'm a WiiU console!
            if(ret < 0){ printf("TCPServer::DoTCPThreadInternal(line %d): Error sendbyte: %02X\n",__LINE__,WIIU_CP_TCP_HANDSHAKE); ErrorHandling(); break;}

            u8 clientProtocolVersion = ControllerPatcherNet::recvbyte(clientfd);
            if(ret < 0){ printf("TCPServer::DoTCPThreadInternal(line %d): Error recvbyte: %02X\n",__LINE__,WIIU_CP_TCP_HANDSHAKE); ErrorHandling(); break;}

            if(clientProtocolVersion == WIIU_CP_TCP_HANDSHAKE_ABORT){
                 printf("TCPServer::DoTCPThreadInternal(line %d): The network client wants to abort.\n",__LINE__);
                 ErrorHandling(); break;
            }

            printf("TCPServer::DoTCPThreadInternal(line %d): received protocol version: %d (0x%02X)\n",__LINE__,(clientProtocolVersion - WIIU_CP_TCP_HANDSHAKE_VERSION_1)+1,clientProtocolVersion);

            if(clientProtocolVersion >= WIIU_CP_TCP_HANDSHAKE_VERSION_MIN && clientProtocolVersion <= WIIU_CP_TCP_HANDSHAKE_VERSION_MAX){
                printf("TCPServer::DoTCPThreadInternal(line %d): We support this protocol version. Let's confirm it to the network client.\n",__LINE__);
                gUsedProtocolVersion = clientProtocolVersion;
                ret = ControllerPatcherNet::sendbyte(clientfd, clientProtocolVersion);
                if(ret < 0){ printf("TCPServer::DoTCPThreadInternal(line %d): Error sendbyte: %02X\n",__LINE__,clientProtocolVersion); ErrorHandling(); break;}
            }else{
                printf("TCPServer::DoTCPThreadInternal(line %d): We don't support this protocol version. We need to abort =(.\n",__LINE__);
                ret = ControllerPatcherNet::sendbyte(clientfd, WIIU_CP_TCP_HANDSHAKE_ABORT);
                ErrorHandling(); break;
            }

            printf("TCPServer::DoTCPThreadInternal(line %d): Handshake done! Success!\n",__LINE__);

            TCPServer::DetachAndDelete(); //Clear connected controller
            RunTCP();

            if(clientfd != -1){
                socketclose(clientfd);
            }
            clientfd = -1;
        }while(0);
        printf("TCPServer::DoTCPThreadInternal(line %d): Connection closed\n",__LINE__);
        gUDPClientip = 0;
        UDPClient::destroyInstance();
        TCPServer::DetachAndDelete(); //Clear connected controller
        CloseSockets();
		continue;
	}

}
Ejemplo n.º 26
0
void cafiine_disconnect(int sock) {
	CHECK_ERROR(sock == -1);
	socketclose(sock);
error:
	return;
}
Ejemplo n.º 27
0
int
tcp_sendecho(void * pio,
   ip_addr  fhost,      /* already in net endian */
   long     len,
   long     times)
{
   struct sockaddr_in   sa;
   int   e;
   SOCKTYPE tmp;
   TCPCLIENT tcpclient;

   /* If client socket isn't open or host has changed, open it */
   tcpclient = tcp_client_from_pio(pio);
   if (tcpclient == NULL)   /* not found */
   {
      if ((e=tcp_client_add(pio)) != SUCCESS)
      {
         if (e == TCPE_ALL_SOCKS_USED)
         {
            ns_printf(pio,"All TCP Echo Client connections are in use.\n");
            ns_printf(pio,"Please try at a later time.\n");
         }
         return e;
      }
      tcpclient = tcp_client_from_pio(pio);
   }

   if (tcpclient->sock == INVALID_SOCKET || fhost != tcpclient->rhost)
   {
      int opt;

      if (tcpclient->sock != INVALID_SOCKET) /* host changed */
      {
         socketclose(tcpclient->sock);
         tcpclient->sock=INVALID_SOCKET;
      }

      /* (re)open new socket to client for echo */
      tmp = socket(AF_INET, SOCK_STREAM, 0);
      if (tmp == INVALID_SOCKET)
      {
         ns_printf(pio,"tcp echo: can't open socket\n");
         tcp_client_del(tcpclient);
         return TCPE_CANT_OPEN_SOCKET ;
      }

      e = t_setsockopt(tmp, SOL_SOCKET, SO_KEEPALIVE, &opt, sizeof(opt));

      sa.sin_family = AF_INET;
      /* host is already in network endian */
      sa.sin_addr.s_addr = tcpclient->rhost = fhost;
      sa.sin_port = htons(ECHO_PORT);

      e = connect(tmp, (struct sockaddr*)&sa, sizeof(sa));
      if (e != 0)
      {
         e = t_errno(tmp);
         ns_printf(pio,"tcp_echo: bad socket connect: %d %s\n", e, so_perror(e));
         tcp_client_del(tcpclient);
         return TCPE_CONNECT_FAILED ;
      }
      /* Put in non-block mode */
      sock_noblock(tmp, TRUE);      
      tcpclient->sock = tmp;
   }


   tcpclient->replies   = 0;
   tcpclient->times     = times;
   tcpclient->delay     = pingdelay;
   tcpclient->ticks     = cticks;
   tcpclient->state     = TCP_BUSY ;
   tcpclient->len       = len ;
   tcpclient->send_cnt  = 0 ;

   return tcp_send_an_echo(tcpclient);
}
Ejemplo n.º 28
0
void
tcp_echo_recv(void)
{
   int   len;        /* length of recv data */
   int   e;          /* error holder */
   unsigned i;       /* generic index */
   int   count;      /* select return */
   fd_set fd_recv;   /* fd for recv */
   fd_set fd_accept; /* fd for accept */
   TCPCLIENT tmpclient = tcpq;
   struct sockaddr_in client;
   SOCKTYPE tmpsock; /* scratch socket */

   if (elisten_sock == INVALID_SOCKET && tcpq == NULL)
      return;  /* Echo not set up, don't bother */

#ifdef USE_FDS
   FD_ZERO(&fd_recv);
   FD_ZERO(&fd_accept);
#endif

   /* select on all open data sockets */
   i = 0;
   count = 0;
#ifdef USE_FDS
   while (tmpclient)
   {
      if (tmpclient->sock != INVALID_SOCKET)
      {
         FD_SET(tmpclient->sock, &fd_recv);
         i++;
      }
      tmpclient=tmpclient->next;
   }
#else
   while (tmpclient)
   {
      if (tmpclient->sock != INVALID_SOCKET)
         fd_recv.fd_array[i++] = tmpclient->sock ;
      tmpclient=tmpclient->next;
   }
#endif  /* USE_FDS */

#ifndef TCP_ZEROCOPY
   /* if we need to listen for server receives too */
#ifdef USE_FDS
   if (tcpecho_server && (esvr_sock != INVALID_SOCKET))
   {
      FD_SET(esvr_sock, &fd_recv);
   }
#else
   if (tcpecho_server)
   {
      if (esvr_sock != INVALID_SOCKET)
         fd_recv.fd_array[i++] = esvr_sock;
   }
#endif  /* USE_FDS */
#else
   /* if we need to close the server's active socket */
   if (esvr_sock_close != FALSE)
   {
      if (esvr_sock != INVALID_SOCKET)
      {
         socketclose(esvr_sock);
         esvr_sock = INVALID_SOCKET;
      }
      esvr_sock_close = FALSE;
   }
#endif   /* TCP_ZEROCOPY */

#ifndef USE_FDS
   fd_recv.fd_count = i;
#endif

   /* make this a short timeout since elisten may create soon */
   if (elisten_sock != INVALID_SOCKET)
   {
#ifdef USE_FDS
      FD_SET(elisten_sock, &fd_accept);
#else
      fd_accept.fd_array[0] = elisten_sock;
      fd_accept.fd_count = 1;
#endif  /* USE_FDS */
      count = t_select(&fd_recv, NULL, &fd_accept, 1);
   }
   else 
   {
      if (i)   /* if no fd_set sockets filled in, don't bother */
         count = t_select(&fd_recv, NULL, NULL, 1);
   }

   /* While the t_select() was executing, commands can be 
    * executed from cmd-prompt and sockets can be cleaned up. 
    * Check for that. 
    */
   if (elisten_sock == INVALID_SOCKET && tcpq == NULL)
      return;  /* Echo not set up, don't bother */

   for (i = 0; i < fd_recv.fd_count; i++)
   {
#ifdef USE_FDS
      tmpsock = FD_GET(i, &fd_recv);
      if (tmpsock == INVALID_SOCKET)
         continue;
#else
      tmpsock = fd_recv.fd_array[i];
#endif  /* USE_FDS */

      /* Find out the client connection corresponding to this socket */
      tmpclient = tcp_client_from_sock(tmpsock);

      /* try a receive. Pick buffer according to client or server */
      if (tmpclient)    /* found a client for this one */
         len = recv(tmpsock, tmpclient->inbuf, ECHOBUFSIZE, 0);
#ifndef TCP_ZEROCOPY
      else if (tmpsock == esvr_sock)
         len = recv(tmpsock, srv_inbuf, ECHOBUFSIZE, 0);
#endif   /* TCP_ZEROCOPY */
      else
      {
         continue;
      }

      if (len < 0)
      {
         e = t_errno(tmpsock);
         if (e != EWOULDBLOCK)
         {
            if (tmpsock != esvr_sock)
               ns_printf(tmpclient->pio,"TCP echo recv error %d\n", e);
            else
               ns_printf(NULL,"TCP echo recv error %d\n", e);
         }
      }
      else if (len == 0)
      {
         ns_printf(NULL,"TCPECHO:socket closed by other side\n");
         if (tmpsock == esvr_sock)
         {
            socketclose (tmpsock);
            esvr_sock = INVALID_SOCKET;
         }
         else
         {
            if (tmpclient == NULL)
            {
               dtrap();
            }          
            else
            {
               tmpclient->sock = INVALID_SOCKET ;
               tcp_client_del(tmpclient);
            }
         }
      }
      else  /* if (len > 0) - got some echo data */
      {
#ifndef TCP_ZEROCOPY
         if (tmpsock == esvr_sock)
         {
            /* we must be server, send echo reply */
            if (tcpecho_server)
            {
               e = send(esvr_sock, srv_inbuf, len, 0);
               if (e < 0)
               {
                  /* Print the error to console */
                  e = t_errno(esvr_sock);
                  ns_printf(NULL,
                   "TCP echo server, error %d sending reply\n", e);
               }
            }
         }
         else     /* not the server socket, must be client */
#endif   /* TCP_ZEROCOPY */
         {
            /* If not a bulk test, print info */
            if (tmpclient->len <= ECHOBUFSIZE)
            {
               ns_printf(tmpclient->pio,"TCP echo reply from:%s, len:%d, reply:%lu", 
                print_ipad(tmpclient->rhost), len, tmpclient->replies);
               ns_printf(tmpclient->pio,"\n%s",prompt);
            }
            else
            {
               u_long   dataval;
               u_long * rxbuf =  (u_long*)(tmpclient->inbuf);
               u_long * rxend =  (u_long*)(tmpclient->inbuf +  (len  &  ~3));

               dataval = tmpclient->tot_rcvd/4;

               /* adjust for odd sized previous receives */
               if (tmpclient->tot_rcvd & 3)
               {
                  MEMMOVE(rxbuf, tmpclient->inbuf + (len & 3), len);
                  rxend--;
                  dataval++;     /* ignore sliced word */
               }

               while (rxbuf < rxend)
               {
                  if (*rxbuf != dataval)
                  {
                     ns_printf(tmpclient->pio,
                      "tcp_echo data error; got %lu, expected %lu\n",
                      *rxbuf, dataval);
                  }
                  rxbuf++;
                  dataval++;
               }
            }
            tmpclient->replies++;
            tmpclient->tot_rcvd += len;
         }
      }
   }

   /* if no server listen to poll, return now */
   if (elisten_sock == INVALID_SOCKET)
      return;

#ifdef NOTDEF
   MEMSET(&client, 0, sizeof(client));
   client.sin_family = AF_INET;
   client.sin_addr.s_addr = INADDR_ANY;
   client.sin_port = htons(ECHO_PORT);
#endif

   /* check for received echo connection on server */
   len = sizeof(client);
   tmpsock = accept(elisten_sock, (struct sockaddr*)&client, &len);
   if (tmpsock != INVALID_SOCKET)
   {
      if (esvr_sock == INVALID_SOCKET)
      {
         esvr_sock = tmpsock;
#ifdef TCP_ZEROCOPY
         t_setsockopt(esvr_sock, SOL_SOCKET, SO_CALLBACK, (void*)echo_svr_upcall, 0);
#endif   /* TCP_ZEROCOPY */
      }
      else  /* we already have a connection */
      {
         dprintf("tcpecho: rejected extra connection\n");
         socketclose(tmpsock);   /* refuse to serve another */
      }
   }
}
Ejemplo n.º 29
0
int 
udp_client_del(UDPCLIENT udpclient)
{
   int   e;
   UDPCLIENT tmpclient,prevclient;

   in_udpechoq++;

   if ( udpclient->sock != INVALID_SOCKET )
   {
      /* Close the underlying socket */
      e = socketclose(udpclient->sock);
      if (e)
      {
         /* socketclose() must have free'd the socket. Hence we
          * can't do
          * e = t_errno(udpclient->sock);
          */
         ns_printf(udpclient->pio,"udp echo: close error %d\n", e);
      }
   }

   /* Remove from the q */
   if ( udpq == udpclient )
   {
      /* It is the first node */
      udpq = udpq->next;
   }
   else
   {
      prevclient=udpq;
      tmpclient=udpq->next;
      while ( tmpclient )
      {
         if ( tmpclient == udpclient )
         {
            /* Found the node in the list */
            prevclient->next=tmpclient->next ;
            break;
         }
         else
         {
            prevclient=tmpclient;
            tmpclient=tmpclient->next ;
         }
      }

      /* Was the node found in Q ? */
      if (tmpclient == NULL )
      {
         /* Node not found in Q !! */
         dtrap();
         in_udpechoq--;
         return UDPE_NODE_NOT_FOUND ;
      }
   }

   npfree(udpclient);

   in_udpechoq--;   
   return SUCCESS;
}
Ejemplo n.º 30
0
int 
udp_cecho_init(void * pio)
{
   int   e;    /* error holder */
   struct sockaddr_in   me;   /* my IP info, for bind() */
   struct sockaddr_in   him;  /* server's IP info, for client connect() */
   SOCKTYPE sock;

   UDPCLIENT udpclient;

   udpclient=udp_client_from_pio(pio);
   if (udpclient != NULL )
   {
      ns_printf(pio,"UDP Echo Client has already been started.\n");
      return UDPE_CLIENT_EXISTS ;
   }

   ns_printf(pio,"udp echo client is starting.\n");

   /* open UDP socket */
   sock = socket(AF_INET, SOCK_DGRAM, 0);
   if (sock == INVALID_SOCKET)
   {
      ns_printf(pio,"udp_echo: bad socket: %d\n", sock);
      return UDPE_BAD_SOCKET ;
   }

   me.sin_family = AF_INET;
   me.sin_addr.s_addr = INADDR_ANY;
   me.sin_port = 0;  /* let UDP pick a client port */

   e = bind(sock, (struct sockaddr*)&me, sizeof(me));
   if (e != 0)
   {
      e = t_errno(sock);
      ns_printf(pio,"udp_echo: bind error: %d\n", e);
      socketclose(sock);
      return UDPE_BIND_FAILED;
   }

   /* make client socket a connected socket */
   him.sin_family = AF_INET;
   if (activehost)
      him.sin_addr.s_addr = activehost;
   else
      him.sin_addr.s_addr = 0x0100007f;   /* for testing */

   him.sin_port = htons(ECHO_PORT);
   e = connect(sock, (struct sockaddr *)&him, sizeof(him));
   if (e != 0)
   {
      e = t_errno(sock);
      ns_printf(pio,"udp_echo: client connect error: %d\n", e);
      return UDPE_CONNECT_FAILED;
   }

   /* put socket into non-blocking mode */
   setsockopt(sock, SOL_SOCKET, SO_NBIO, NULL, 0);

   udp_client_add(pio,sock,activehost);

   return SUCCESS;
}