コード例 #1
0
bool NetSerial::checkAndRestoreConnection(bool throttle)
{
	if (is_stopped_) {
		return false;
	}
	if (sockfd_ < 0 && throttle) {
		clock_t now = clock();
		// Only attempt to establish the connection every 5 seconds
		if (((now - lastConnectAttempt_) / CLOCKS_PER_SEC) < 5) {
			return false;
		}
	}
	lastConnectAttempt_ = clock();
	if (is_server_) {
		if (!startServerSocket()) {
			return false;
		}
		if (!acceptClient()) {
			return false;
		}
	} else {
		if (!startClientSocket()) {
			return false;
		}
	}
	return true;
}
コード例 #2
0
ファイル: daemon.c プロジェクト: Frozenhorns/project
int
runDaemon(int debug)
{
  char			packetPtr[PACKETLEN];
  size_t	       	packetSize;
  struct sockaddr_in	sa;

  if (checkOtherProcess())
    return (EXIT_FAILURE);
  signal(SIGTERM, sigHandler);
  signal(SIGINT, sigHandler);
  signal(SIGUSR1, sigHandler);

  if (!debug) {
    daemon(1, 1);
    if (savePid())
      return EXIT_FAILURE;
  }

  fprintf(stderr, "Daemon started\n");

  initConnection(&sa);
  while (1) {
    setClient(acceptClient(&sa));
    bzero(packetPtr, PACKETLEN);
    getPacket(packetPtr, &packetSize);
    handlePacket(packetPtr, packetSize);
    setClient(-1);
  }
  setSock(-1);
  return EXIT_SUCCESS;
}
コード例 #3
0
ファイル: main_server.cpp プロジェクト: 343829084/IM-server
int main()
{
    init();
    createListenCmd();
    acceptClient();
    
    exit(0);
}
コード例 #4
0
// Initialize Networking Sockets
void initPeerSocket(void) {
	#ifdef SERVERMODE
	fdPeerSock = acceptClient();
	#endif

	#ifdef CLIENTMODE
	fdPeerSock = connectServer();
	#endif
}
コード例 #5
0
ファイル: Server.cpp プロジェクト: Nozog/final
bool Server::start(const std::string& host, uint16_t port){
	createMasterSocket();
	bindMasterSocket(host, port);
	listenMasterSocket();
	LoggerST::Instance()->Msg("run ok, goto accept clients...");
	while(1){
		acceptClient();
	}
	return true;
}
コード例 #6
0
ファイル: Host.cpp プロジェクト: aljazk/bubbletruble
sf::Packet Host::receive(){
	sf::Packet packet;
	if (client.receive(packet) != sf::Socket::Done){
		if (sf::Socket::Error == 3){
			acceptClient();
		} else {
			std::cout << "Error with reciving data | Error " << sf::Socket::Error << std::endl;
		}
	}
	return packet;
}
コード例 #7
0
void ClusterServer::start(void)
{
    OSG::FieldContainerType *fct;

    // reset conneciton

    delete _connection;

    _connection = NULL;

    // create aspect
    _aspect = new RemoteAspect();

    // register interrest for all changed cluster windows
    for(UInt32 i = 1;
            i < OSG::TypeFactory::the()->getNumTypes();
            ++i)
    {
        fct = OSG::FieldContainerFactory::the()->findType(i);

        if(fct && fct->isDerivedFrom(ClusterWindow::getClassType()))
        {
            _aspect->registerChanged(
                *fct,
                boost::bind(&ClusterServer::windowChanged, this, _1, _2));
        }
    }

    // accept incomming connections
    try
    {
        UInt8                    forceNetworkOrder;
#if BYTE_ORDER == LITTLE_ENDIAN
        UInt8                    littleEndian = true;
#else
        UInt8                    littleEndian = false;
#endif

        // accept
        acceptClient();

        // determine network order
        _connection->putValue(littleEndian);
        _connection->flush();
        _connection->selectChannel();
        _connection->getValue(forceNetworkOrder);
        _connection->setNetworkOrder((forceNetworkOrder != 0));
    }
    catch(...)
    {
        throw;
    }
}
コード例 #8
0
ファイル: tcpserver.cpp プロジェクト: mloy/devscan
		int TcpServer::process()
		{
			workerSocket_t worker = acceptClient();
			if (!worker) {
				return 0;
			}

			if (m_acceptCb) {
				m_acceptCb(std::move(worker));
			}
			return 0;
		}
コード例 #9
0
ファイル: TcpServer.cpp プロジェクト: wosiu/eognisko
TcpServer::TcpServer(boost::asio::io_service& io_service,
		ServerController& _controller) :
			controller(_controller),
			acceptor_(io_service, tcp::endpoint(tcp::v6(), _controller.port)),
			socket_(io_service),
			timer_(io_service, boost::posix_time::seconds(REPORT_INTERVAL_S)) {

	INFO("TCP server started.");
	controller.turnOnTcpSever();
	acceptClient();
	timer_.async_wait(boost::bind(&TcpServer::sendReports, this));
}
コード例 #10
0
  void Server::process( fd_set& read_set, fd_set& write_set ){
    if(!valid)
      return;

    if( FD_ISSET( socket, &read_set ) )
      if( acceptClient() )
        std::cout << "New connection" << std::endl;

    for( auto client : clients )
      client->process( read_set, write_set );

  }
コード例 #11
0
ファイル: main.c プロジェクト: ulia22/projetReseaux
int main(int argc, char** argv) {
    printf("Server is running...\n");
    init();
    initFileData();
    //Definition des variables pour ouvrir les connections.
    int sdServerAccept;
    //Initialisation de la socket d'ecoute du server.
    sdServerAccept = initListeningSocket();
    //Accepte les connections entrante et laisse la gestion à un nouveau thread.
    while (1) {
        acceptClient(sdServerAccept);
    }
    return (EXIT_SUCCESS);
}
コード例 #12
0
ファイル: ThreadPoolServer.hpp プロジェクト: aholic/paekdusan
        bool start() {
            sockaddr_in clientAddr;
            int nSize = sizeof(clientAddr);
            int clientSock;

            while (true) {
                if (-1 == (clientSock = acceptClient(_hostSocket, (struct sockaddr*) &clientAddr, &nSize))) {
                    LogError("accept failed: %d", getLastErrorNo());
                    break;
                }
                LogInfo("accept client: %s", inet_ntoa(clientAddr.sin_addr));
                _threadPool.add(new KeepAliveWorker(clientSock, _httpRequestHandler));
            }
            return true;
        }
コード例 #13
0
void runProvider(int argc, char **argv)
{
   int port;

   ember_init(onThrowError, onFailAssertion, malloc, free);
   initializePpmStreams();
   buildTree(&_root);

   if(argc >= 2)
   {
      port = atoi(argv[1]);

      printf_s("accepting client on port %d\n", port);
      acceptClient(port);
   }

   sampleNode_free(&_root);
   freePpmStreams();
}
コード例 #14
0
ファイル: server.c プロジェクト: WangDrop/WangDropExercise
static void handleClient(int srvfd)
{
    int clifd = -1;
    int retval = 0;
    fd_set * readfds = &serverContext->allfds;
    struct timeval tm;
    int i = 0;
    while(1){
        //注意,每次使用Select之前都应该设置文件描述符以及时间,因为事件发生之后,这些信息又都会被修改了
        FD_ZERO(readfds);
        FD_SET(srvfd, readFds);
        serverContext->maxfd = srvfd;

        tv.tv_sec = 30;
        tv_tv_usec = 0;
        for(i = 0; i < serverContext->cliCnt; i++){
            clifd = serverContext->clifds[i];
            FD_SET(clifd, readFds);
            serverContext->maxfd = (clifd > serverContext->maxfd ? clifd : serverContext->maxfd);
        }
        retval = select(serverContext->maxfd + 1, readFds,NULL, NULL, NULL, &tv);
        if(retval == -1){
            fprintf(stderr, "Select error %s .\n", strerror(errno));
            exit(0);
        }

        if(retval == 0){
            fprintf(stdout, "select is tomeout.\n ");
            continue;
        }

        if(FD_ISSET(servfd, readFds)){
            acceptClient(srvfd);
        }else{
            recvClientMsg(readFds);
        }
    }
}
コード例 #15
0
ファイル: TcpServer.cpp プロジェクト: wosiu/eognisko
void TcpServer::acceptClient() {
	acceptor_.async_accept(socket_, [this](boost::system::error_code ec)
	{
		if (!ec) {
			if ( controller.clients.size() > controller.MAX_CLIENT_NO ) {
				socket_.close(ec);
				if (!ec) {
					WARN("Client disconnected by server - too much clients.");
				} else {
					ERR(ec);
				}
			} else {
				// dodaje kleinta, zwraca referencje na kontekst z nim zwiazany
				auto cc = controller.addClient(std::move(socket_));
				sendId(cc);
				INFO("Client joined, sending id: " + _(cc->getId()) );
			}
		} else {
			ERR(ec);
		}

		acceptClient();
	});
}
コード例 #16
0
ファイル: main.c プロジェクト: canboat/canboat
void acceptJSONClient(int i)
{
    acceptClient(stream[i].fd, CLIENT_JSON);
}
コード例 #17
0
ファイル: shairport.c プロジェクト: flyingtime/boxee
int shairport_loop(void)
{
    if (!m_running || tServerSock <= 0)
        return 0;

    int tClientSock = 0;

    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(tServerSock, &fds);

    struct timeval timeout;
    timeout.tv_sec = 1;
    timeout.tv_usec = 0;

    int readsock;

    slog(LOG_DEBUG_V, "Waiting for clients to connect\n");

    while(m_running)
    {
      int rc = select(tServerSock + 1, &fds, 0, 0, &timeout);
      if (rc == -1 && errno != EINTR)
        return 0;

      readsock = -1;
      if (FD_ISSET(tServerSock, &fds))
      {
        readsock = tServerSock;
      }

      FD_ZERO(&fds);
      FD_SET(tServerSock, &fds);
      timeout.tv_sec = 1;
      timeout.tv_usec = 0;

      if (readsock == -1)
        continue;

      tClientSock = acceptClient(tServerSock, tAddrInfo);
      if(tClientSock > 0)
      {
#ifndef BOXEE
        int tPid = 0;
        fork();
        if(tPid == 0)
        {
          freeaddrinfo(tAddrInfo);
          tAddrInfo = NULL;
          slog(LOG_DEBUG, "...Accepted Client Connection..\n");
          close(tServerSock);
          handleClient(tClientSock, tPassword, tHWID);
          //close(tClientSock);
          return 0;
        }
        else
        {
          slog(LOG_DEBUG_VV, "Child now busy handling new client\n");
          close(tClientSock);
        }
#else
      slog(LOG_DEBUG, "...Accepted Client Connection..\n");
      handleClient(tClientSock, tPassword, tHWID);
#endif
      }
      else
      {
          return 0;
      }
  }

  slog(LOG_DEBUG_VV, "Finished\n");
  if(tAddrInfo != NULL)
  {
    freeaddrinfo(tAddrInfo);
  }
  return 1;
}
コード例 #18
0
ファイル: server.c プロジェクト: thetopor/linux-awesomness
int main(int argc, char *argv[])
{
	// Handle SIGPIPE
	struct sigaction pipeAct;
	memset(&pipeAct, 0, sizeof(struct sigaction));
	pipeAct.sa_handler = pipeHandler;
	if (sigaction(SIGPIPE, &pipeAct, NULL) < 0) {
		f**k(FUCK_HARDCORE, "sigaction error: %s\n", fuckerror());
	}

	init_socket();
	init_pins();

    while (1) {
		if (acceptClient() < 0) continue; // Error on accept

		// Read resolution
		read(clientSock_fd, &xres, sizeof(uint32_t));
		read(clientSock_fd, &yres, sizeof(uint32_t));

		// Create input events
		struct input_eventx ev_x;		// Relative on the x axis
		ev_x.type = EV_REL;
		ev_x.code = REL_X;
		struct input_eventx ev_y;		// Relative on the y axis
		ev_y.type = EV_REL;
		ev_y.code = REL_Y;
		struct input_eventx ev_l;		// Left mouse button
		ev_l.type = EV_KEY;
		ev_l.code = BTN_LEFT;
		struct input_eventx ev_r;		// Right mouse button
		ev_r.type = EV_KEY;
		ev_r.code = BTN_RIGHT;
		struct input_eventx ev_syn;		// Sync event
		ev_syn.type = EV_SYN;
		ev_syn.code = SYN_REPORT;
		ev_syn.value = 0;

		// Set mouse to (0,0)
		ev_x.value = -xres;
		ev_y.value = -yres;
		if (sendEvent(&ev_x) < 0 || sendEvent(&ev_y) < 0 || sendEvent(&ev_syn) < 0) continue;

		int lmb_state = 0, rmb_state = 0;
		int x_old = 0, y_old = 0, x = 0, y = 0, px = 0, py = 0, a, b;
		int sync, tolerance = 3; // Avoids unwanted mouse jitter

		while (1) {
			sync = 0;
			// Handle button clicks
			if (digitalRead(GPIO_LMB) == HIGH && lmb_state == 0) {
				ev_l.value = lmb_state = 1;
				if (sendEvent(&ev_l) < 0) break;
				sync = 1;
			}
			if (digitalRead(GPIO_LMB) == LOW && lmb_state == 1) {
				ev_l.value = lmb_state = 0;
				if (sendEvent(&ev_l) < 0) break;
				sync = 1;
			}
			if (digitalRead(GPIO_RMB) == HIGH && rmb_state == 0) {
				ev_r.value = rmb_state = 1;
				if (sendEvent(&ev_r) < 0) break;
				sync = 1;
			}
			if (digitalRead(GPIO_RMB) == LOW && rmb_state == 1) {
				ev_r.value = rmb_state = 0;
				if (sendEvent(&ev_r) < 0) break;
				sync = 1;
			}

			// Handle mouse move
		 	a = analogRead(MCP3008_PIN_BASE);
		 	b = analogRead(MCP3008_PIN_BASE + 1);
			if ((a - px) > tolerance || (px - a) > tolerance || a == 0 || a == ANALOG_MAX) {
				px = a;
				x = (int)(px * (xres - 1) / (double)ANALOG_MAX);
				ev_x.value = x - x_old;
				x_old = x;
				if (sendEvent(&ev_x) < 0) break;
				sync = 1;
			}
			if ((b - py) > tolerance || (py - b) > tolerance || b == 0 || b == ANALOG_MAX) {
				py = b;
				y = (int)(py * (yres - 1) / (double)ANALOG_MAX);
				ev_y.value = y - y_old;
				y_old = y;
				if (sendEvent(&ev_y) < 0) break;
				sync = 1;
			}

			// If anything sent, sync
			if (sync && sendEvent(&ev_syn) < 0) break;

			usleep(20000);
		}

		// If any of the code from the while above breaks, move to the next client
		continue;
	}

	// Clean shit
	close(clientSock_fd);
 	close(sock_fd);

 	return 0;
}
コード例 #19
0
bool TcpServer::acceptClient(TcpClient * pTcpClient, int index)     
{
    return(acceptClient(pTcpClient, index, NULL));
}
コード例 #20
0
bool TcpServer::acceptClient(TcpClient * pTcpClient, DNETcK::STATUS * pStatus)
{
    return(acceptClient(pTcpClient, 0, pStatus));
}
コード例 #21
0
ファイル: shairport.c プロジェクト: tommy99/shairport
int main(int argc, char **argv)
{
  char tHWID[HWID_SIZE] = {0,51,52,53,54,55};
  char tHWID_Hex[HWID_SIZE * 2];

  char tServerName[56] = "ShairPort";
  char tPassword[56] = "";

  struct addrinfo *tAddrInfo;
  int  tSimLevel = 0;
  int  tUseKnownHWID = FALSE;
  int  tDaemonize = FALSE;
  int  tPort = PORT;

  char *arg;
  while ( (arg = *++argv) ) {
    if(!strcmp(arg, "-a"))
    {
       strncpy(tServerName, *++argv, 55);
       argc--;
    }
    else if(!strcmp(arg, "--apname="))
    {
      strncpy(tServerName, arg+9, 55);
    }
    else if(!strcmp(arg, "-p"))
    {
      strncpy(tPassword, *++argv, 55);
      argc--;
    }
    else if(!strcmp(arg, "--password="******"-o"))
    {
      tPort = atoi(*++argv);
      argc--;
    }
    else if(!strcmp(arg, "--server_port="))
    {
      tPort = atoi(arg+14);
    }
    else if(!strcmp(arg, "-k"))
    {
      tUseKnownHWID = TRUE;
    }
    else if(!strcmp(arg, "-q") || !strcmp(arg, "--quiet"))
    {
      kCurrentLogLevel = 0;
    }
    else if(!strcmp(arg, "-d"))
    {
      tDaemonize = TRUE;
      kCurrentLogLevel = 0;
    }
    else if(!strcmp(arg, "-v"))
    {
      kCurrentLogLevel = LOG_DEBUG;
    }
    else if(!strcmp(arg, "-v2"))
    {
      kCurrentLogLevel = LOG_DEBUG_V;
    }
    else if(!strcmp(arg, "-vv") || !strcmp(arg, "-v3"))
    {
      kCurrentLogLevel = LOG_DEBUG_VV;
    }    
    else if(!strcmp(arg, "-h") || !strcmp(arg, "--help"))
    {
      slog(LOG_INFO, "ShairPort version 0.05 C port - Airport Express emulator\n");
      slog(LOG_INFO, "Usage:\nshairport [OPTION...]\n\nOptions:\n");
      slog(LOG_INFO, "  -a, --apname=AirPort    Sets Airport name\n");
      slog(LOG_INFO, "  -p, --password=secret   Sets Password (not working)\n");
      slog(LOG_INFO, "  -o, --server_port=5000  Sets Port for Avahi/dns-sd\n");
      slog(LOG_INFO, "  -d                      Daemon mode\n");
      slog(LOG_INFO, "  -q, --quiet             Supresses all output.\n");
      slog(LOG_INFO, "  -v,-v2,-v3,-vv          Various debugging levels\n");
      slog(LOG_INFO, "\n");
      return 0;
    }    
  }

  if(tDaemonize)
  {
    int tPid = fork();
    if(tPid < 0)
    {
      exit(1); // Error on fork
    }
    else if(tPid > 0)
    {
      exit(0);
    }
    else
    {
      setsid();
      int tIdx = 0;
      for(tIdx = getdtablesize(); tIdx >= 0; --tIdx)
      {
        close(tIdx);
      }
      tIdx = open(DEVNULL, O_RDWR);
      dup(tIdx);
      dup(tIdx);
    }
  }
  srand ( time(NULL) );
  // Copy over empty 00's
  //tPrintHWID[tIdx] = tAddr[0];

  int tIdx = 0;
  for(tIdx=0;tIdx<HWID_SIZE;tIdx++)
  {
    if(tIdx > 0)
    {
      if(!tUseKnownHWID)
      {
        int tVal = ((random() % 80) + 33);
        tHWID[tIdx] = tVal;
      }
      //tPrintHWID[tIdx] = tAddr[tIdx];
    }
    sprintf(tHWID_Hex+(tIdx*2), "%02X",tHWID[tIdx]);
  }
  //tPrintHWID[HWID_SIZE] = '\0';

  slog(LOG_INFO, "LogLevel: %d\n", kCurrentLogLevel);
  slog(LOG_INFO, "AirName: %s\n", tServerName);
  slog(LOG_INFO, "HWID: %.*s\n", HWID_SIZE, tHWID+1);
  slog(LOG_INFO, "HWID_Hex(%d): %s\n", strlen(tHWID_Hex), tHWID_Hex);

  if(tSimLevel >= 1)
  {
    #ifdef SIM_INCL
    sim(tSimLevel, tTestValue, tHWID);
    #endif
    return(1);
  }
  else
  {
    startAvahi(tHWID_Hex, tServerName, tPort);
    slog(LOG_DEBUG_V, "Starting connection server: specified server port: %d\n", tPort);
    int tServerSock = setupListenServer(&tAddrInfo, tPort);
    if(tServerSock < 0)
    {
      freeaddrinfo(tAddrInfo);
      slog(LOG_INFO, "Error setting up server socket on port %d, try specifying a different port\n", tPort);
      exit(1);
    }

    int tClientSock = 0;
    while(1)
    {
      slog(LOG_DEBUG_V, "Waiting for clients to connect\n");
      tClientSock = acceptClient(tServerSock, tAddrInfo);
      if(tClientSock > 0)
      {
        int tPid = fork();
        if(tPid == 0)
        {
          freeaddrinfo(tAddrInfo);
          tAddrInfo = NULL;
          slog(LOG_DEBUG, "...Accepted Client Connection..\n");
          close(tServerSock);
          handleClient(tClientSock, tPassword, tHWID);
          //close(tClientSock);
          return 0;
        }
        else
        {
          slog(LOG_DEBUG_VV, "Child now busy handling new client\n");
          close(tClientSock);
        }
      }
      else
      {
        // failed to init server socket....try waiting a moment...
        sleep(2);
      }
    }
  }

  slog(LOG_DEBUG_VV, "Finished, and waiting to clean everything up\n");
  sleep(1);
  if(tAddrInfo != NULL)
  {
    freeaddrinfo(tAddrInfo);
  }
  return 0;
}
コード例 #22
0
/***	bool TcpServer::acceptClient(TcpClient * pTcpClient)
**      bool TcpServer::acceptClient(TcpClient * pTcpClient, int index) 
**      bool TcpServer::acceptClient(TcpClient * pTcpClient, DNETcK::STATUS * pStatus)
**      bool TcpServer::acceptClient(TcpClient * pTcpClient, int index, DNETcK::STATUS * pStatus)
**
**	Synopsis:   
**      Removes a pending TcpClient by accepting it from the server.
**
**	Parameters:
**      pTcpClient  A pointer to a newly constructed client TcpClient
**
**      index       This is the zero based index of the client you want to accept. index must be less
**                      than what AvailableClients.
**
**      pStatus     A pointer to receive the status of AcceptClient
**      
**	Return Values:
**      true if the TcpClient was returned
**      false if the TcpClient could not be created
**
**	Errors:
**      None
**
**  Notes:
**
**     This call should be made immediately after AvailableClients or GetAvailableClientsRemoteEndPoint.
**      Do not run PeriodicTasks between AvailableClients and this call because the client count could change.
**      In order to keep the indexes within the range of AvailableClients and consistent with what GetAvailableClientsRemoteEndPoint
**      returned, do not run AvailableClients or PeriodicTasks inbetween them. That is, do not run any stack task as that 
**      would change the AvailableClients count and order.
**      
*/
bool TcpServer::acceptClient(TcpClient * pTcpClient)
{
    return(acceptClient(pTcpClient, 0, NULL));
}
コード例 #23
0
ファイル: main.c プロジェクト: canboat/canboat
void acceptJSONStreamClient(int i)
{
    acceptClient(stream[i].fd, CLIENT_JSON_STREAM);
}
コード例 #24
0
ファイル: main.c プロジェクト: canboat/canboat
void acceptNMEA0183StreamClient(int i)
{
    acceptClient(stream[i].fd, CLIENT_NMEA0183_STREAM);
}
コード例 #25
0
ファイル: shairport.c プロジェクト: aircross/ray
int main(int argc, char **argv)
{
  // unfortunately we can't just IGN on non-SysV systems
  struct sigaction sa;
  sa.sa_handler = handle_sigchld;
  sa.sa_flags = 0;
  sigemptyset(&sa.sa_mask);
  if (sigaction(SIGCHLD, &sa, NULL) < 0) {
      perror("sigaction");
      return 1;
  }
  // EZP_XXX: Using LAN MAC
  char buf[SHORT_BUF_LEN];
  unsigned int mac[6]={0,0,0,0,0,0};
  ezplib_get_attr_val("lan_hwaddr_rule_default", 0, "hwaddr", buf, sizeof(buf), EZPLIB_USE_CLI);
  sscanf(buf,"%2X:%2X:%2X:%2X:%2X:%2X", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
    
  unsigned char tHWID[HWID_SIZE] = {mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]};
  char tHWID_Hex[HWID_SIZE * 2 + 1];
  memset(tHWID_Hex, 0, sizeof(tHWID_Hex));

  char tServerName[56] = "ShairPort";
  char tPassword[56] = "";

  struct addrinfo *tAddrInfo;
  int  tSimLevel = 0;
  int  tUseKnownHWID = FALSE;
  int  tDaemonize = FALSE;
  int  tPort = PORT;

  char *arg;
  while ( (arg = *++argv) ) {
    if(!strcmp(arg, "-a"))
    {
       strncpy(tServerName, *++argv, 55);
       argc--;
    }
    else if(!strncmp(arg, "--apname=", 9))
    {
      strncpy(tServerName, arg+9, 55);
    }
    else if(!strcmp(arg, "-p"))
    {
      strncpy(tPassword, *++argv, 55);
      argc--;
    }
    else if(!strncmp(arg, "--password="******"-o"))
    {
      tPort = atoi(*++argv);
      argc--;
    }
    else if(!strncmp(arg, "--server_port=", 14))
    {
      tPort = atoi(arg+14);
    }
    else if(!strcmp(arg, "-b")) 
    {
      bufferStartFill = atoi(*++argv);
      argc--;
    }
    else if(!strncmp(arg, "--buffer=", 9))
    {
      bufferStartFill = atoi(arg + 9);
    }
    else if(!strcmp(arg, "-k"))
    {
      tUseKnownHWID = TRUE;
    }
    else if(!strcmp(arg, "-q") || !strncmp(arg, "--quiet", 7))
    {
      kCurrentLogLevel = 0;
    }
    else if(!strcmp(arg, "-d"))
    {
      tDaemonize = TRUE;
      kCurrentLogLevel = 0;
    }
    else if(!strcmp(arg, "-v"))
    {
      kCurrentLogLevel = LOG_DEBUG;
    }
    else if(!strcmp(arg, "-v2"))
    {
      kCurrentLogLevel = LOG_DEBUG_V;
    }
    else if(!strcmp(arg, "-vv") || !strcmp(arg, "-v3"))
    {
      kCurrentLogLevel = LOG_DEBUG_VV;
    }    
    else if(!strcmp(arg, "-h") || !strcmp(arg, "--help"))
    {
      slog(LOG_INFO, "ShairPort version 0.05 C port - Airport Express emulator\n");
      slog(LOG_INFO, "Usage:\nshairport [OPTION...]\n\nOptions:\n");
      slog(LOG_INFO, "  -a, --apname=AirPort    Sets Airport name\n");
      slog(LOG_INFO, "  -p, --password=secret   Sets Password (not working)\n");
      slog(LOG_INFO, "  -o, --server_port=5002  Sets Port for Avahi/dns-sd/howl\n");
      slog(LOG_INFO, "  -b, --buffer=282        Sets Number of frames to buffer before beginning playback\n");
      slog(LOG_INFO, "  -d                      Daemon mode\n");
      slog(LOG_INFO, "  -q, --quiet             Supresses all output.\n");
      slog(LOG_INFO, "  -v,-v2,-v3,-vv          Various debugging levels\n");
      slog(LOG_INFO, "\n");
      return 0;
    }    
  }

  /*
  if ( bufferStartFill < 30 || bufferStartFill > BUFFER_FRAMES ) {
     fprintf(stderr, "buffer value must be > 30 and < %d\n", BUFFER_FRAMES);
     return(0);
  }
  */

  if(tDaemonize)
  {
    int tPid = fork();
    if(tPid < 0)
    {
      exit(1); // Error on fork
    }
    else if(tPid > 0)
    {
      exit(0);
    }
    else
    {
      setsid();
      int tIdx = 0;
      for(tIdx = getdtablesize(); tIdx >= 0; --tIdx)
      {
        close(tIdx);
      }
      tIdx = open(DEVNULL, O_RDWR);
      dup(tIdx);
      dup(tIdx);
    }
  }
  srandom ( time(NULL) );

  int tIdx = 0;
  for(tIdx=0;tIdx<HWID_SIZE;tIdx++)
  {
    if(tIdx > 0)
    {
      if(!tUseKnownHWID)
      {
        int tVal = ((random() % 80) + 33);
        tHWID[tIdx] = tVal;
      }
    }
    sprintf(tHWID_Hex+(tIdx*2), "%02X",tHWID[tIdx]);
  }

  slog(LOG_INFO, "LogLevel: %d\n", kCurrentLogLevel);
  slog(LOG_INFO, "AirName: %s\n", tServerName);
  slog(LOG_INFO, "HWID: %.*s\n", HWID_SIZE, tHWID+1);
  slog(LOG_INFO, "HWID_Hex(%d): %s\n", strlen(tHWID_Hex), tHWID_Hex);

    loadKey();
  if(tSimLevel >= 1)
  {
    #ifdef SIM_INCL
    sim(tSimLevel, tTestValue, tHWID);
    #endif
    return(1);
  }
  else
  {
    slog(LOG_DEBUG_V, "Starting connection server: specified server port: %d\n", tPort);
    int tServerSock = setupListenServer(&tAddrInfo, tPort);
    if(tServerSock < 0)
    {
      freeaddrinfo(tAddrInfo);
      slog(LOG_INFO, "Error setting up server socket on port %d, try specifying a different port\n", tPort);
      exit(1);
    }

    int tClientSock = 0;
    while(1)
    {
      slog(LOG_DEBUG_V, "Waiting for clients to connect\n");
      tClientSock = acceptClient(tServerSock, tAddrInfo);
      if(tClientSock > 0)
      {
        int tPid = fork();
        if(tPid == 0)
        {
          freeaddrinfo(tAddrInfo);
          tAddrInfo = NULL;
          slog(LOG_DEBUG, "...Accepted Client Connection..\n");
          close(tServerSock);
          handleClient(tClientSock, tPassword, (char*)tHWID);
          //close(tClientSock);
          return 0;
        }
        else
        {
          slog(LOG_DEBUG_VV, "Child now busy handling new client\n");
          wait(NULL);
          close(tClientSock);
        }
      }
      else
      {
        // failed to init server socket....try waiting a moment...
        sleep(2);
      }
    }
  }

  slog(LOG_DEBUG_VV, "Finished, and waiting to clean everything up\n");
  sleep(1);
  if(tAddrInfo != NULL)
  {
    freeaddrinfo(tAddrInfo);
  }
  return 0;
}
コード例 #26
0
ファイル: mTerm_server.c プロジェクト: PeterMartini/openbmc
static void connectServer(const char *stty, const char *dev) {
  int fdmax, newfd;

  fd_set master, read_fds;
  FD_ZERO(&master);
  FD_ZERO(&read_fds);

  int serverfd;
  serverfd = createServerSocket(dev);
  if (serverfd < 0) {
    syslog(LOG_ERR, "mTerm_server: Failed to create server socket\n");
    return;
  }

  struct ttyRaw* tty_sol;
  tty_sol = setTty(openTty(stty), 1);
  if (!tty_sol) {
    syslog(LOG_ERR, "mTerm_server: Failed to set tty to raw mode\n");
    close(serverfd);
    return;
  }

  struct bufStore* buf;
  buf = createBuffer(dev, FILE_SIZE_BYTES);
  if (!buf || (buf->buf_fd < 0)) {
    syslog(LOG_ERR, "mTerm_server: Failed to create the log file\n");
    closeTty(tty_sol);
    close(serverfd);
    return;
  }

  FD_SET(serverfd, &master);
  FD_SET(tty_sol->fd,&master);
  fdmax = (serverfd > tty_sol->fd) ? serverfd : tty_sol->fd;

  for(;;) {
    read_fds = master;
    if (select(fdmax + 1, &read_fds, NULL, NULL, NULL) == -1) {
      syslog(LOG_ERR, "mTerm_server: Server socket: select error\n");
      break;
    }
    if (FD_ISSET(serverfd, &read_fds)) {
      newfd = acceptClient(serverfd);
      if (newfd < 0) {
        syslog(LOG_ERR, "mTerm_server: Error on accepting client\n");
      } else {
        FD_SET(newfd, &master);
        if (newfd > fdmax) {
          fdmax = newfd;
        }
      }
    }
    if (FD_ISSET(tty_sol->fd, &read_fds)) {
      if ( processSol(&master, serverfd, fdmax, tty_sol->fd, buf) < 0) {
        break;
      }
    }
    int i;
    for(i = 0; i <= fdmax; i++) {
      if (FD_ISSET(i, &read_fds)) {
        if ((i == serverfd) || (i == tty_sol->fd)) {
          continue;
        } else {
          processClient(&master, i, tty_sol->fd, buf);
        }
      }
    }
  }
  closeTty(tty_sol);
  close(serverfd);
  closeBuffer(buf);
}
コード例 #27
0
ファイル: UdpServer.cpp プロジェクト: alaneve/SeniorDesign
bool UdpServer::acceptClient(UdpClient * pUdpClient, DNETcK::STATUS * pStatus)      
{
    return(acceptClient(pUdpClient, 0, pStatus));
}
コード例 #28
0
ファイル: UdpServer.cpp プロジェクト: alaneve/SeniorDesign
bool UdpServer::acceptClient(UdpClient * pUdpClient, int index)
{
    return(acceptClient(pUdpClient, index, NULL));
}
コード例 #29
0
ファイル: UdpServer.cpp プロジェクト: alaneve/SeniorDesign
/***	bool UdpServer::acceptClient(UdpClient * pUdpClient)
**      bool UdpServer::acceptClient(UdpClient * pUdpClient, int index) 
**      bool UdpServer::acceptClient(UdpClient * pUdpClient, DNETcK::STATUS * pStatus) 
**      bool UdpServer::acceptClient(UdpClient * pUdpClient, int index, DNETcK::STATUS * pStatus)
**
**	Synopsis:   
**      Removes a pending UdpClient by accepting it from the server.
**
**	Parameters:
**      pUdpClient  A pointer to a newly constructed client UdpClient; the datagram cache must have
**                  been specified when the UdpClient was instantiated.
**
**      index       This is the zero based index of the client you want to accept. index must be less
**                      than what AvailableClients.
**
**      pStatus     A pointer to receive the status of AcceptClient
**      
**	Return Values:
**      true if the UdpClient was returned
**      false if the UdpClient could not be created
**
**	Errors:
**      None
**
**  Notes:
**
**     This call should be made immediately after AvailableClients or GetAvailableClientsRemoteEndPoint.
**      Do not run PeriodicTasks between AvailableClients and this call because the client count could change.
**      In order to keep the indexes within the range of AvailableClients and consistent with what GetAvailableClientsRemoteEndPoint
**      returned, do not run AvailableClients or PeriodicTasks inbetween them. That is, do not run any stack task as that 
**      would change the AvailableClients count and order.
**  
**      When a UdpClient is accepted, the datagram cache is copied from the server datagram cache space to UdpClient's
**      datagram cache space. If the client's space is less than the server space, some datagrams may be discarded. However
**      any remaining datagrams will be full unchopped datagrams. It is possible in extreme cases where all datagrams were
**      discarded that your client will have an Available ready to read datagram byte count of zero.
*/
bool UdpServer::acceptClient(UdpClient * pUdpClient)
{
    return(acceptClient(pUdpClient, 0, NULL));
}