Пример #1
0
int main(int argc, char **argv)
{
    int server_socket;
    int port;

    if (argc != 2) {
        print_usage();
        return 0;
    }

    port = atoi(argv[1]);
    if (!port) {
        printf("Invalid port number %s\n", argv[1]);
        print_usage();
        return 0;
    }

    if (setup_crypt() < 0)
        return 0;

    signal(SIGINT, sigint);

    server_socket = start_server_sock(port);
    if (server_socket < 0)  {
        printf("Could not create and bind listener socket\n");
        cleanup_crypt();
    }
    else
        accept_connections(server_socket);

    return 0;
}
Пример #2
0
void ConnectionServer::accept_connections() {
    acceptor.async_accept(socket, [this](const boost::system::error_code& err_code) {
        if(!err_code) {
            handler(new Connection(conn_id_gen++, std::move(socket)));
        }
        accept_connections();
    });
}
Пример #3
0
/*!
  This function is to be run in a separate thread. There it attaches itself
  to the given context and waits for incoming MB calls. These are passed on
  to __verify_MB_call().

  \param ctx the CMPIContext to attach to.

  \sa accept_connections()
 */
static void __start_proxy_daemon(CMPIContext * ctx)
{
    if (ctx != NULL) {
        CBAttachThread(__init_broker, ctx);
    }
    accept_connections(CIMOM_LISTEN_PORT, __verify_MB_call, 0);
    CBDetachThread(__init_broker, ctx);
}
Пример #4
0
int main(int argc, char **argv) {
	int listen_fd;

	read_conf();
	if ((listen_fd = listen_socket()) < 0)
		return 1;
	setgid(use_gid);
	setuid(use_uid);
	return accept_connections(listen_fd);
}
Пример #5
0
void connect(Uint16 port)
{
  IPaddress ip;

  if(SDLNet_ResolveHost(&ip,NULL,port)==-1) {
    printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError());
    exit(1);
  }
  serversock = SDLNet_TCP_Open(&ip);
  if(!serversock) {
    printf("SDLNet_TCP_Open: %s\n", SDLNet_GetError());
    exit(2);
  }

  socketset = SDLNet_AllocSocketSet(32);
  if (!socketset) {
    printf("SDLNet_AllocSocketSet: %s\n", SDLNet_GetError());
    exit(1); //most of the time this is a major error, but do what you want.
  }

  SDLNet_TCP_AddSocket(socketset, serversock);

  while(true)
    {
      int num = 0;
      if ((num = SDLNet_CheckSockets(socketset, 10000)) == -1)
        {
          printf("SDLNet_CheckSockets: %s\n", SDLNet_GetError());
          //most of the time this is a system error, where perror might help you.
          perror("SDLNet_CheckSockets");
        }
      else
        {
          accept_connections();

          for(int i = 0; i < int(clients.size()); ++i)
            {
              if (clients[i])
                clients[i]->update();
            }

          for(int i = 0; i < int(clients.size()); ++i)
            {
              if (clients[i] && clients[i]->is_invalid())
                {
                  std::cout << "# client " << clients[i]->id << " got disconnected" << std::endl;
                  SDLNet_TCP_DelSocket(socketset, clients[i]->tcpsock);
                  SDLNet_TCP_Close(clients[i]->tcpsock);
                  delete clients[i];
                  clients[i] = 0;
                }
            }
        }
    }
}
Пример #6
0
ConnectionServer::ConnectionServer(NewConnectionHandler handler, std::string address, unsigned short port)
    : socket(io_service),
      endpoint(asio::ip::address().from_string(address), port),
      acceptor(io_service, endpoint),
      conn_id_gen(0),
      handler(handler) {
    BOOST_LOG_TRIVIAL(info) << "cbattleship-server listening on " << address << ":" << port << " ...";
    accept_connections();

    boost::thread thread(boost::bind(&boost::asio::io_service::run, &io_service));
}
Пример #7
0
// Wenn ein Kindprozess beendet wird, der einen
// wartenden Server Prozess bedient hat, dann
// schmeiss den Socket wieder auf die select()
// Liste
void sig_child(int code)
{
  inetd *inetd;
  int status = -1;
  pid_t pid = wait(&status);

  if( ((inetd = search_child(pid)) != NULL) && (!strcmp(inetd->type,"wait")) )
    {
      FD_SET(inetd->socket, &readfds);
      accept_connections();
    }
}
Пример #8
0
void acceptor::handle_accept(const boost::system::error_code& error)
{
  BLOG(trace) << VIEW_FUNCTION;
  if (!error) {
    session_->start(upstream_host_, upstream_port_);
    if (!accept_connections()) {
      BLOG(error) << "Failure during call to accept.";
    }
  } else {
    BLOG(error) << "Error: " << error.message();
  }
}
Пример #9
0
/******************************************************************************\
 Poll connections and dispatch any messages that arrive.
\******************************************************************************/
void N_poll_server(void)
{
        int i;

        if (n_client_id != N_HOST_CLIENT_ID)
                return;
        accept_connections();

        /* Send to and receive from clients */
        for (i = 0; i < N_CLIENTS_MAX; i++)
                if (!N_send_buffer(i) || !N_receive(i))
                        N_drop_client(i);
}
Пример #10
0
 void handle_accept(const boost::system::error_code& error)
 {
    if (!error)
    {
       session_->start(remote_host_,remote_port_);
       if (!accept_connections())
       {
          std::cerr << "Failed to accept." << std::endl;
       }
    }
    else
    {
       std::cerr << error.message() << std::endl;
    }
 }
         void handle_accept(const boost::system::error_code& error)
         {

            if (!error) 
            {
               session_->start(upstream_host_,upstream_port_);
               if (!accept_connections())
               {
                  std::cerr << "Failure during call to accept." << std::endl;
               }
            }
            else
            {
               std::cerr << "Error: " << error.message() << std::endl;
            }
         }
Пример #12
0
void* trsender_thread_routine(void *arg) {
    SSL_CTX* ctx=NULL;    
    SSL* ssl;
    char buf[BUF_SIZE];
    size_t read=0;
    
    /*The sender acts as a server, so we perform the standard procedure to accept and verify SSL connection*/
    peer_socket = accept_connections(server_socket);
    if (peer_socket==ERROR) {
        syslog(LOG_NOTICE,"ERROR accepting connection\n");
        finished_transfer=FINISHED_ERR_SSL;
        pthread_exit(NULL);
    }
    if (!(ctx=fijar_contexto_SSL(MYCERTS, CACERT, &SSLv23_method, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT))) {
        syslog(LOG_NOTICE,"ERROR al fijar contexto\n");
        finished_transfer=FINISHED_ERR_SSL;
        pthread_exit(NULL);
    }
    if (!(ssl=aceptar_canal_seguro_SSL(ctx, peer_socket))) {
        close(peer_socket);
        SSL_CTX_free(ctx);
        finished_transfer=FINISHED_ERR_SSL;
        pthread_exit(NULL);
    }
    transfer_ssl=ssl;
    if (evaluar_post_conectar_SSL(ssl)!=OK) {
        syslog(LOG_NOTICE,"El certificado del peer no es valido\n");
        finished_transfer=FINISHED_ERR_SSL;
        cerrar_canal_SSL(transfer_ssl);
        pthread_exit(NULL);
    }
    /*connection succesful, sending file*/
    if (!(transfer_file=fopen((char*)arg, "r"))) {
        finished_transfer=FINISHED_ERR;
        pthread_exit(NULL);
    }
    while (!feof(transfer_file) && !finished_transfer) {/* get request */
        read=fread(buf, sizeof(char), BUF_SIZE, transfer_file);
        enviar_datos_SSL(transfer_ssl, buf, read, BUF_SIZE);
    }
    fclose(transfer_file);
    finished_transfer=FINISHED_OK;
    pthread_exit(NULL);
}
Пример #13
0
int main(int argc, char **argv) {

    int socket, client_socket;
    int port = IRC_DEFAULT_PORT;

    /*Parameters processing*/
    if (argc != 1 && argc != 2) {
        printf("%s <port (optional)>\n", argv[0]);
        return (EXIT_FAILURE);
    } else if (argc == 2) {
        port = atoi(argv[1]);
    }

    /*Runs in background*/
    if (daemonize(SERVER_LOG_IDENT) == ERROR) {
        irc_exit_message();
        return (EXIT_FAILURE);
    }

    /*Initializes server*/
    socket = init_server(port, SERVER_MAX_CONNECTIONS);
    if (socket <= 0) {
        irc_exit_message();
        exit(EXIT_FAILURE);
    }

    /*Initializes IRC server data*/
    irc_server_data_init();
    
    /*Accepts connexions and takes charge of them*/
    while (1) {
        client_socket = accept_connections(socket);
        nbjoin_threads();
        if (launch_thread(client_socket, irc_thread_routine) != OK) {
            syslog(LOG_ERR, "Server: Failed while launching a thread: %s", strerror(errno));
        }
    }

    return (EXIT_SUCCESS);
}
int _cdecl
main(int argc, char *argv[]) {

#ifdef WIN32
  WSADATA	wsa_data ;

  /* Initialize the winsock lib do we still want version 2.2? */
  if ( WSAStartup(MAKEWORD(2,2), &wsa_data) == SOCKET_ERROR ){
    printf("WSAStartup() failed : %lu\n", GetLastError()) ;
    return -1 ;
  }
#endif /* WIN32 */

  /* Save away the program name */
  program = (char *)malloc(strlen(argv[0]) + 1);
  if (program == NULL) {
    printf("malloc for program name failed!\n");
    return -1 ;
  }
  strcpy(program, argv[0]);

  init_netserver_globals();

  netlib_init();

  strncpy(local_host_name,"",sizeof(local_host_name));
  local_address_family = AF_UNSPEC;
  strncpy(listen_port,TEST_PORT,sizeof(listen_port));

  scan_netserver_args(argc, argv);

  check_if_inetd();

  if (child) {
    /* we are the child of either an inetd or parent netserver via
       spawning (Windows) rather than fork()ing. if we were fork()ed
       we would not be coming through this way. set_server_sock() must
       be called before open_debug_file() or there is a chance that
       we'll toast the descriptor when we do not wish it. */
    set_server_sock();
    open_debug_file();
    process_requests();
  }
  else if (daemon_parent) {
    /* we are the parent daemonized netserver
       process. accept_connections() will decide if we want to spawn a
       child process */
    accept_connections();
  }
  else {
    /* we are the top netserver process, so we have to create the
       listen endpoint(s) and decide if we want to daemonize */
    setup_listens(local_host_name,listen_port,local_address_family);
    if (want_daemonize) {
      daemonize();
    }
    accept_connections();
  }

  unlink_empty_debug_file();

#ifdef WIN32
  WSACleanup();
#endif

  return 0;

}
void
daemonize() {
#if defined(HAVE_FORK)

  if (debug) {
    fprintf(where,
	    "%s: enter\n",
	    __FUNCTION__);
    fflush(where);
  }

  /* flush the usual suspects */
  fflush(stdin);
  fflush(stdout);
  fflush(stderr);

  switch (fork()) {
  case -1:
    fprintf(stderr,
	    "%s: fork() error %s (errno %d)\n",
	    __FUNCTION__,
	    strerror(errno),
	    errno);
    fflush(stderr);
    exit(1);
  case 0:

    /* perhaps belt and suspenders, but if we dump core, perhaps
       better to do so here. we won't worry about the call being
       successful though. raj 2011-07-08 */
    chdir(DEBUG_LOG_FILE_DIR);

    /* we are the child. we should get a new "where" to match our new
       pid */

    open_debug_file();

#ifdef HAVE_SETSID
      setsid();
#else
      setpgrp();
#endif /* HAVE_SETSID */

      signal(SIGCLD, SIG_IGN);

      /* ok, we can start accepting control connections now */
      accept_connections();

  default:
    /* we are the parent, nothing to do but exit? */
    exit(0);
  }

#else
  fprintf(where,
	  "%s called on platform which cannot daemonize\n",
	  __FUNCTION__);
  fflush(where);
  exit(1);
#endif /* HAVE_FORK */
}
Пример #16
0
int main(void)
{
  FILE *fh;
  char line[1024];
  struct sockaddr_in server;
  struct protoent *proto;
  struct servent *service;
  inetd *last = NULL;
  register inetd *inetd;

  // Biste root?
  if(getuid() != 0)
    {
      printf("You must be root!\n");
      exit(1);
    }

  // Initialisiere readfds Array fuer select()
  FD_ZERO(&readfds);

  // Oeffne die Config Datei zum lesen
  if( (fh = fopen(CONF,"r")) == NULL)
    {
      perror("open");
      exit(1);
    }

  // Verarbeite die Eingabe zeilenweise
  while(fgets(line,1024,fh) != NULL)
    {
      // Leerzeichen am Anfang der Zeile auslassen
      while(*zeiger == ' '){ zeiger++; }

      // Auskommentierte Zeilen auslassen
      if(*line != '#')
	{
	  // Reserviere Speicher fuer eine neue inetd Struktur
	  inetd = get_new_inetd();

	  // Ist das die erste inetd Struktur?
	  // Dann merke sie Dir als den Anfang
	  if(last == NULL)
	    {
	      anfang = inetd;
	    }
	  
	  // Ansonsten zeigt der letzte Pointer auf den aktuellen
	  else
	    {
	      last->next = inetd;
	    }
	  
	  last = inetd;
	  
	  // Zerlege jede Zeile in ihre Bestandteile
	  sscanf(line,"%10s %10s %10s %8s %20s %256s %256s %256s",
		 inetd->name, 
		 inetd->type, 
		 inetd->prot, 
		 inetd->wait, 
		 inetd->user, 
		 inetd->path, 
		 inetd->prog, 
		 inetd->args);
	  
	  // Finde das Transport Protokoll heraus
	  if( (proto = getprotobyname(inetd->prot)) == NULL)
	    {
	      snprintf(msg,256,"Unkown protocol %s!\n",inetd->prot);
	      log(msg);
	      exit(1);
	    }
	  
	  // Finde das Application Layer Protokoll heraus
	  if( (service = getservbyname(inetd->name,proto->p_name)) == NULL)
	    {
	      snprintf(msg,256,"Unkown protocol %s!\n",inetd->name);
	      log(msg);
	      exit(1);
	    }
	  
	  // Adresse des Sockets
	  server.sin_family = AF_INET;
	  server.sin_port = service->s_port;
	  server.sin_addr.s_addr = INADDR_ANY;
	  
	  // Oeffne einen Socket
	  // TCP
	  if(!strcmp(inetd->type,"stream"))
	    {
	      if( (inetd->socket = socket(AF_INET,SOCK_STREAM,proto->p_proto)) < 0)
		{
		  perror("socket");
		  exit(1);
		}
	    }

	  // UDP
	  else
	    {
	      if( (inetd->socket = socket(AF_INET,SOCK_DGRAM,proto->p_proto)) < 0)
		{
		  perror("socket");
		  exit(1);
		}
	    }
	  
	  // Binde den Socket an die Adresse
	  if( (bind(inetd->socket, (struct sockaddr *)&server, sizeof(server))) < 0)
	    {
	      perror("bind");
	      exit(1);
	    }
	  
	  // Setze die Listen Queue bei TCP Sockets
	  if(!strcmp(inetd->type,"stream"))
	    {
	      listen(inetd->socket,QUEUE);
	    }

	  // Setze den Socket auf die select() Liste
	  FD_SET(inetd->socket,&readfds);
	  nfds = inetd->socket;
	}
    }

  fclose(fh);

  // Warte auf Verbindungsanfragen
  accept_connections();
  return 0;
}
Пример #17
0
static void *CR_Loop(void *arg)
{

#ifdef CR_FTB
    if (cr_ftb_init(nprocs))
        exit(EXIT_FAILURE);
#else
    char cr_msg_buf[MAX_CR_MSG_LEN];
    char valstr[CRU_MAX_VAL_LEN];
    fd_set set;
    int i, n, nfd = 0, ret;

    if (USE_LINEAR_SSH) {
        if (!show_on) {
            // This call is blocking (in case of error)
            // It must be kept in the CR thread
            int rv = accept_connections();
            if ( rv != 0 ) {
                m_state_fail();
                pthread_exit(NULL);
            }
        }
    }
#endif

    CR_state_transition( CR_READY );

#ifdef CR_FTB
    // The main thread of mpirun_rsh is waiting for the CR thread to connect to FTB
    // before starting the mpispawn processes
    // Make the transition to the M_LAUNCH state
    // Use to signal the main thread of mpirun_rsh
    // This should be removed once we remove the use of FTB for this
    if (M_LAUNCH != m_state_transition(M_INITIALIZE|M_RESTART, M_LAUNCH)) {
        PRINT_ERROR("Internal error: transition failed\n");
        m_state_fail();
        pthread_exit(NULL);
    }
#endif

    if ( checkpoint_interval > 0 ) {
        PRINT_DEBUG( DEBUG_FT_verbose, "Checkpoint interval = %d s\n", checkpoint_interval );
    }

    while (1) {

        // Check if CR_thread_stop() has been called
        CR_state_lock();
        if (cr_state == CR_STOPPED) {
            CR_state_unlock();
            PRINT_DEBUG( DEBUG_FT_verbose, "Exit CR thread\n" );
            pthread_exit(NULL);
        }
        CR_state_unlock();

#ifdef CR_FTB
        sleep(1);
        if (cr_ftb_app_ckpt_req || cr_ftb_finalize_ckpt)
#else
        nfd = 0;
        FD_ZERO(&set);
        for (i = 0; i < nspawns; i++) {
            FD_SET(mpirun_fd[i], &set);
            nfd = (nfd >= mpirun_fd[i]) ? nfd : mpirun_fd[i];
        }
        nfd += 1;

        struct timeval tv;
        do {
            tv.tv_sec = 1;
            tv.tv_usec = 0;
            ret = select(nfd, &set, NULL, NULL, &tv);
        } while ( ret==-1 && errno==EINTR );
            
        if (ret < 0) {
            PRINT_ERROR_ERRNO("select(nfd=%d, set, NULL, NULL, tv={%lu,%lu}) failed", errno, nfd, tv.tv_sec, tv.tv_usec);
            return ((void *) -1);
        } else if (ret > 0)
#endif
        {

            // Do not go further if not ready
            // This avoid bad interactions on file descriptors with the CR_Callback thread
            CR_state_lock();
            if (cr_state != CR_READY) {
                CR_state_unlock();
                continue;
            }
            CR_state_unlock();

#ifdef CR_FTB
            if (cr_ftb_app_ckpt_req)
#else
            for (i = 0; i < nspawns; i++) {

                if (!FD_ISSET(mpirun_fd[i], &set))
                    continue;

                n = CR_MPDU_readline(mpirun_fd[i], cr_msg_buf, MAX_CR_MSG_LEN);
                if (n == 0)
                    continue;

                if (CR_MPDU_parse_keyvals(cr_msg_buf) < 0)
                    break;

                CR_MPDU_getval("cmd", valstr, CRU_MAX_VAL_LEN);

                if (strcmp(valstr, "app_ckpt_req") == 0)
#endif
                {
#ifdef CR_FTB
                    cr_ftb_app_ckpt_req = 0;
#endif
                    unsigned int current_version = checkpoint_version;
                    char buf[CR_MAX_FILENAME];
                    sprintf(buf, "%s.%d.sync", ckpt_filename, current_version);
                    PRINT_DEBUG( DEBUG_FT_verbose, "Checkpoint request from the application\n" );
                    int rv = request_checkpoint( buf );
                    if ( rv < 0 ) {
                        PRINT_ERROR( "Checkpoint failed\n" );
                    } else if ( rv > 0 ) {
                        PRINT_DEBUG( DEBUG_FT_verbose, "Restarting from checkpoint\n" );
                        // Terminate the thread
                        pthread_exit(NULL);
                    }
                }
#ifdef CR_FTB
                else if (cr_ftb_finalize_ckpt)
#else
                else if (strcmp(valstr, "finalize_ckpt") == 0)
#endif
                {
                    // One process called MPI_finalize()
#ifdef CR_FTB
                    cr_ftb_finalize_ckpt = 0;
#endif
                    // Terminate the CR_thread
                    CR_state_transition( CR_STOPPED );
                    pthread_exit(NULL);
                }
#ifndef CR_FTB
            }
#endif
        } else {
Пример #18
0
int select_on_sockets(){

	//set of socket descriptors
	fd_set readfds;
	int max_clients = 30, activity, addrlen, i, valread;
	SOCKET client_socket[30], socket, new_socket;
	struct sockaddr_in address;


	for (i = 0; i < max_clients; i++)
	{
		client_socket[i] = 0;
	}

	while (TRUE)
	{

		FD_ZERO(&readfds);
		FD_SET(listen_socket, &readfds);

		//add child sockets
		for (i = 0; i < max_clients; i++)
		{
			socket = client_socket[i];
			if (socket > 0)
			{
				FD_SET(socket, &readfds);
			}
		}

		//Accept and incoming connection
		puts("Waiting for incoming connections...\n");

		//wait for an activity on any of the sockets
		activity = select(0, &readfds, NULL, NULL, NULL);

		if (activity == SOCKET_ERROR)
		{
			printf("select call failed with error code : %d", WSAGetLastError());
			exit(EXIT_FAILURE);
		}

		//If something happened
		if (FD_ISSET(listen_socket, &readfds))
		{
			if (accept_connections(&new_socket) != 0)
			{
				perror("accept");
				exit(EXIT_FAILURE);
			}

			printf("New connection , socket fd is %d , ip is : %s , port : %d \n", new_socket, inet_ntoa(address.sin_addr), ntohs(address.sin_port));

			//add new socket to array of sockets
			for (i = 0; i < max_clients; i++)
			{
				if (client_socket[i] == 0)
				{
					client_socket[i] = new_socket;
					printf("Adding to list of sockets at index %d \n", i);
					break;
				}
			}
		}

		//else its some IO operation on some other socket :)
		for (i = 0; i < max_clients; i++)
		{
			socket = client_socket[i];
			//if client presend in read sockets             
			if (FD_ISSET(socket, &readfds))
			{
				//get details of the client
				getpeername(socket, (struct sockaddr*)&address, (int*)&addrlen);

				//Check if it was for closing , and also read the incoming message
				valread = receive(socket);
				if (valread <= 0){
					closesocket(socket);
					client_socket[i] = 0;
				
				}

			}
		}
	}


}