Пример #1
0
static void acceptClient(int port)
{
   SOCKET listenSock, clientSock;
   struct sockaddr_in localAddr;

   initSockets();

   listenSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

   localAddr.sin_family = AF_INET;
   localAddr.sin_addr.s_addr = INADDR_ANY;
   localAddr.sin_port = htons((unsigned short)port);

   bind(listenSock, (struct sockaddr *)&localAddr, sizeof(localAddr));

   listen(listenSock, 1);

   clientSock = accept(listenSock, NULL, NULL);

   if(clientSock > 0)
   {
      printf_s("client accepted\n");
      handleClient(clientSock);
   }

   closesocket(listenSock);

   shutdownSockets();
}
Пример #2
0
static void* redisLocalServerLoop(void* notUsed) {
  traceEvent(TRACE_NORMAL, "[Redis Server] %s() started", __FUNCTION__);

  readOnlyGlobals.redis.local_server_running = 0;

  while(!readWriteGlobals->shutdownInProgress) {
    fd_set mask;

    FD_ZERO(&mask);
    FD_SET(readOnlyGlobals.redis.local_server_socket, &mask);

    if(select(readOnlyGlobals.redis.local_server_socket+1, &mask, 0, 0, NULL) > 0) {
      struct sockaddr_in from;
      int rx_sock, from_len, rc;
      char aChar;

      rx_sock = accept(readOnlyGlobals.redis.local_server_socket, (struct sockaddr*)&from, (socklen_t*)&from_len);
      if((rx_sock < 0) || (errno != 0)) {
	traceEvent(TRACE_ERROR, "Unable to accept connection [%s/%d]", strerror(errno), errno);
      }

      traceEvent(TRACE_NORMAL, "[Redis Server] New client connected [socket %d]", rx_sock);
      handleClient(rx_sock);
      close(rx_sock);
    }
  }

  readOnlyGlobals.redis.local_server_running = 1;

  return(NULL);
}
Пример #3
0
int main(int argc, const char * argv[])
{
    struct sockaddr_in serverAddr, clientAddr;
    
    _serverSock = socket(AF_INET, SOCK_STREAM, 0);
    if (_serverSock < 0) {
        perror("Failed to create socket");
        return errno;
    }
    
    memset(&serverAddr, 0, sizeof(struct sockaddr_in));
    serverAddr.sin_port = htons(5555);
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    
    if (bind(_serverSock, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr_in)) < 0) {
        perror("Failed to bind");
        return errno;
    }
    
    listen(_serverSock, 5);
    while (1) {
        socklen_t l;
        memset(&clientAddr, 0, sizeof(struct sockaddr_in));
        l = sizeof(clientAddr);
        _clientSock = accept(_serverSock, (struct sockaddr *)&clientAddr, (socklen_t *)&l);
        
        if (fork() == 0) {
            handleClient();
        }
    }
    
    return 0;
}
Пример #4
0
void
Remote::loop()
{
    BridgeClient client = m_bridgeServer.accept();

    if (client) {
        handleClient(client);
    }
}
Пример #5
0
void checkActiveClientsAfterSelect(fd_set *fdSet)
{
	struct ClientNode *activeClient = clientList->firstClient;
	while(activeClient != NULL) {
		if(FD_ISSET(activeClient->clientSocket, fdSet)) {
			handleClient(activeClient);
		}
		activeClient = activeClient->nextClient;
	}
}
Пример #6
0
void TCPServer::start()
{

	struct timeval tv;
	fd_set read_fds;

	m_running = true;

	while (m_running) {
		tv.tv_sec = 0;
		tv.tv_usec = 250000;
		read_fds = m_socks;

		int select_return = select(m_maxfd + 1, &read_fds, NULL, NULL, &tv);

		if (select_return == -1) {
			perror("Select failed!");

			switch(errno) {
			case EBADF:
				// An invalid file descriptor was given in one of the sets. (Perhaps a file descriptor that was already closed, or one on which an error has occurred.)
				std::cout << "An invalid file descriptor was given in one of the sets. (Perhaps a file descriptor that was already closed, or one on which an error has occurred.)\n";
				break;
			case EINTR:
				// A signal was caught; see signal(7).
				break;
			case EINVAL:
				// nfds is negative or the value contained within timeout is invalid.
				break;
			case ENOMEM:
				// unable to allocate memory for internal tables.
				throw Common::DisCODeException("TCPServe: Unable to allocate memory for internal tables");
			}
		}
		if (select_return == 0) {
			//std::cout << "Select timed out." << std::endl;
			continue;
		}

		// run through the existing connections looking for data to read
		for (int i = 0; i <= m_maxfd; i++) {
			if (FD_ISSET(i, &read_fds)) { // we got one!!
				// check, if server listening socket is ready
				if (i == m_sock) {
					acceptNewClient();
				} else {
					handleClient(i);
				} // END handle data from client
			} // END got new incoming connection

		}
	}

}
Пример #7
0
int main(int argc, char* argv[]){
	srand(time(NULL));
	int port = 6013;
	if(argc == 2)
	{
		if(!sscanf(argv[1],"%d",&port)){
			fprintf(stderr,"Error in server: Port was not a number.\n");
			printUsage();
			return;
		}
	}
	puts("Starting server...");
	if(0 > (sd = socket(AF_INET, SOCK_STREAM, 0))) { // get socket int
		puts("Error creating socket.");
		fprintf(stderr,"\n Error : Connect Failed \nReason: %s\n", strerror(errno));
		return;
	}
	atexit(cleanup); // now that socket has been created, at exit is set.
	struct sockaddr_in saddr;
	memset(&saddr,'\0',sizeof(saddr)); // zero structure out
	saddr.sin_family = AF_INET; // match the socket() call
	saddr.sin_addr.s_addr = htonl(INADDR_ANY); // bind to any local addr
	saddr.sin_port = htons(port); // specify port to listen on
	if((bind(sd, (struct sockaddr*)&saddr, sizeof(saddr)) < 0)){ // bind!
		fprintf(stderr,"Error in server: Error binding\nReason: %s\n", strerror(errno));
		return;
	}
	if(listen(sd,5)!=0){ // listen for connections
		fprintf(stderr,"Error in server: Error listening\nReason: %s\n", strerror(errno));
		return;
	}
	struct sockaddr clientaddr; // places for accept to put data (not actually used)
	socklen_t addrlen;
	int clientsd;
	struct pollfd fds; // Polling stuff
	int ret;
	fds.fd = sd;
	fds.events = POLLIN;
	printf("Server successfully started on port: %d\n",port);
	// Infinite loop for server
	while(1){
		poll(&fds,1,-1); // Poll the socket
		if(~(clientsd = accept(sd, &clientaddr, &addrlen))){ // Handle the request
			puts("Connection request received...");
			int childPID = fork();
			if(childPID == 0){
				puts("\tforked child and sent to handler...");
				handleClient(clientsd);
			}
		}
	}
}
Пример #8
0
void *handshake ( void *clisoc ) {
    int *ptr = (int *)clisoc;
    int a_soc = *ptr;
    signal(SIGINT, SIG_DFL);
    if ((WEBSOChandshake(a_soc)) > 0) {
        handleClient(&a_soc);
    } else {
        logEvent("Handshake failed.");
        perror("Handshake failed.");
    }
    close(a_soc);
    pthread_exit(NULL);
    return NULL;
}
Пример #9
0
int main(int argc, char *argv[]){
	if (argc != 2){
		err_n_die("Parameters: <Port>");
	}
	in_port_t servPort = atoi(argv[1]);
	// create socket
	int serverSocket;
	serverSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(serverSocket < 0){
		err_n_die("Could not create socket");
	}
	// local address struct
	struct sockaddr_in servAddr;
	memset(&servAddr,0,sizeof(servAddr));
	servAddr.sin_family = AF_INET;
	servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servAddr.sin_port = htons(servPort);
	// bind and listen
	if(bind(serverSocket,(struct sockaddr*) &servAddr,sizeof(servAddr)) < 0){
		err_n_die("Could not bind ServerSocket");
	}

	if (listen(serverSocket, 5) < 0){
		err_n_die("Could not listen");
	}

	while(1){
		//
		struct sockaddr_in clntAddr;
		socklen_t clntAddrLen = sizeof(clntAddr);

		int client = accept(serverSocket,(struct sockaddr *) &clntAddr,&clntAddrLen);
		if(client < 0){
			err_n_die("Could not accept connection");
		}

		char clientName[INET_ADDRSTRLEN];
		if(inet_ntop(AF_INET, &clntAddr.sin_addr.s_addr,clientName,sizeof(clientName)) != NULL){
			printf("Connected to client %s on port %d \n",clientName, ntohs(clntAddr.sin_port));
		}
		else {
			printf("Unable to get client address");
		}

		handleClient(client);

	}
}
int AndroidInputServer::handleConnectionRequest(const int acceptedFromListeningSocket) {
	pid_t pid = fork();
	if ( pid == -1 ) {
		logger->error("08.12.2011 23:28:27 fork() error",errno);
		return -1;
	}
	if ( pid == 0 ) { // child
		child = true;
		close(keyboardListeningSocket);
		close(mouseListeningSocket);
		handleClient(acceptedFromListeningSocket);
		return 0;
	}
	// parent
	close(clientSocket);
	return 1;
}
Пример #11
0
//! This is a simple server to test the ntee program.
//! The server simply sends back to the client the number of bytes it
//! just recieved from the client.
//!
int main(int argc, char** argv)
{
   std::string USAGE("Usage: testSrv <server port>\n");
   ErrIf( argc < 2 ).info(USAGE);

   // Convert the port number arg to an int
   in_port_t port;
   ErrIfCatch(boost::bad_lexical_cast,
              port = boost::lexical_cast<in_port_t>( argv[1] ))
             .info("%s is not a port number!\n",argv[1]);
   
   // Put the supplied ip addr into the sockaddr_in struct, we will reuse this
   // memory later to store client addresses in it as they connect.
   sockaddr_in addr;
   memset( &addr, 0, sizeof(addr) );
   addr.sin_family = AF_INET;
   addr.sin_addr.s_addr = htonl(INADDR_ANY);  // Wildcard address kernel picks best bind     
   addr.sin_port = htons(port);
      
   
   //** Get the server to accept stage
   Socket sock;
   SysErrIf( (sock=socket(AF_INET, SOCK_STREAM, 0)) == -1 );
   SysErrIf( bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == -1 );
   SysErrIf( listen(sock, 5) == -1 );
   
   //** Forever accept new connections and reply
   for( ;; ) {
     Socket cliSock;
     memset( &addr, 0, sizeof(addr) );
     socklen_t len = sizeof(addr);
     SysErrIf( (cliSock=accept(sock,reinterpret_cast<sockaddr*>(&addr),&len)) == -1 );
     
     char cliName[INET_ADDRSTRLEN];
     WarnIf( inet_ntop(AF_INET, &addr, cliName, sizeof(cliName) ) == 0 );
     std::cout << "CONNECTED to: " << ((cliName)?cliName:"Unknown") 
               << ":" << addr.sin_port << "\n";
               
     handleClient( cliSock );
  
   }
   
   return 0;
}
Пример #12
0
void* client_loop (void* arg) 
{
    session sess = *((session*) arg);
    pthread_mutex_unlock (&ses_mutex);

    printEvent(&sess, "Client connected"); 

    handleClient(&sess);

    printEvent(&sess, "Client disconnected");

    close (sess.csck);
    pthread_mutex_lock (&sock_mutex);
    for (unsigned i = 0; i < connectionLimit; i++)
        if (cln_sockets [i] == sess.csck) {
            cln_sockets [i] = 0;
            break;
        } 
    pthread_mutex_unlock (&sock_mutex);

    pthread_exit (NULL);
}
Пример #13
0
void *openspy_mod_run(modLoadOptions *options) {
  int sd;
  int len;
  char buf[MAX_DATA_SIZE + 1];
  #ifndef _WIN32
  gi = GeoIP_new(GEOIP_STANDARD);
  #else
  WSADATA ws;
  WSAStartup(MAKEWORD(1,0),&ws);
  #endif
  struct sockaddr si_other;
  memcpy(&servoptions,options,sizeof(modLoadOptions));
  socklen_t slen = sizeof(si_other);
  struct sockaddr_in si_me;
  if((sd=socket(AF_INET,SOCK_DGRAM, IPPROTO_UDP)) == -1)
   return NULL;
  memset((char *)&si_me, 0, sizeof(si_me));
  si_me.sin_family = AF_INET;
  si_me.sin_port = htons(QRPORT);
  si_me.sin_addr.s_addr = options->bindIP;
  if(bind(sd,(struct sockaddr *)&si_me,sizeof(si_me)) == -1)
   return NULL;
	struct timeval tv;
  for(;;) {
    memset((char *)&buf,0, sizeof(buf));
    tv.tv_sec = 60;
    tv.tv_usec = 0;
    setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,  sizeof tv);
    len = recvfrom(sd,(char *)&buf,sizeof(buf), 0, (struct sockaddr *)&si_other, &slen);
    if(len < 0) { //timeout, do keep alives and delete clients who have expired
	checkTimeouts();
	continue;
    }
    buf[len] = 0;
//  makeStringSafe((char *)&buf, sizeof(buf));
    handleClient(sd,(struct sockaddr_in *)&si_other,(char *)&buf,len);
  }
	return NULL;
}
Пример #14
0
void startServer(void) {
    int pidfd;
    char pidpath[PATH_MAX];
    int lfd, cfd;
    socklen_t addrlen;
    struct sockaddr claddr;

    lfd = inetListen(config.port, 0, &addrlen);
    if (lfd == -1) {
        errMsg(LOG_ERR, "Could not listen on port %s.", config.port);
        return;
    }

    snprintf(pidpath, PATH_MAX, "/var/run/syncedfs/server/%s.pid",
            config.resource);
    pidfd = createPidFile(config.ident, pidpath, 0);
    if (pidfd == -1) {
        errMsg(LOG_ERR, "Could not create pid file %s, Exiting server.", pidpath);
        return;
    }

    errMsg(LOG_INFO, "Server booted.");

    //setup signal handler to stop handling requests
    for (;;) {
        cfd = accept(lfd, (struct sockaddr *) &claddr, &addrlen);

        if (cfd == -1) {
            errnoMsg(LOG_ERR, "Error accepting client.");
            continue;
        }
        handleClient(cfd, &claddr, &addrlen);
    }

    // delete pid file
    if (deletePidFile(pidfd, pidpath) == -1)
        errExit(LOG_ERR, "Deleting PID file '%s'", pidpath);
}
void server::start(int port, int constraint)
{
	
	constraintType = constraint;
	
	// create listener socket
	if(catchSignal(SIGINT, server::handleShutdown) == -1)
		error("Can't set the SIGINT handler");
	if(catchSignal(SIGPIPE, server::handleClientClosed) == -1)
		error("Can't set the SIGPIPE pipe handler");
	if(catchSignal(SIGCHLD, SIG_IGN) == -1)
		cerr << "Can't set the SIGCHLD handler" << endl;

	staticListenerD = openListenerSocket();

	bindToPort(staticListenerD, port);
	if(listen(staticListenerD, 30) < 0)
		error("Can't listen");
	

	struct sockaddr_in client_addr; /* the from address of a client*/
	unsigned int address_size = sizeof(client_addr);

	cout << "Start listen" << endl;
	
	while(1){
		int newsockfd = accept(staticListenerD, (struct sockaddr *) &client_addr, (socklen_t*)&address_size);
		//cout << newsockfd << endl;
		
		// no new socket received
		if (newsockfd < 0){ 
			close(newsockfd);
			continue;
		}
		
		
		char clntIP[INET_ADDRSTRLEN];
		inet_ntop(AF_INET, &(client_addr.sin_addr),clntIP,sizeof(clntIP));
		//cout << "<S_IP>:\t" << clntIP << endl;
		//cout << "<S_Port>:\t" << (int) ntohs(client_addr.sin_port) << endl;
		srcIP = clntIP;
		srcPort = to_string((int) ntohs(client_addr.sin_port));
		
		int childpid;
		if ( (childpid = fork()) < 0) cerr << "server: fork error" << endl;
		else if (childpid == 0) { // child process
			
			// process the request
			// ignore SIGCHLD
			signal(SIGCHLD, NULL);
			
			handleClient(newsockfd);
				
			if(staticListenerD) close(staticListenerD); 
			exit(0);
		}else{// parent process
			// do nothing
			close(newsockfd);
		}
	}
	
}
Пример #16
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;
}
Пример #17
0
// Gator data flow: collector -> collector fifo -> sender
int main(int argc, char** argv) {
	// Ensure proper signal handling by making gatord the process group leader
	//   e.g. it may not be the group leader when launched as 'sudo gatord'
	setsid();

  // Set up global thread-safe logging
	logg = new Logging(hasDebugFlag(argc, argv));
	// Global data class
	gSessionData = new SessionData();
	// Set up global utility class
	util = new OlyUtility();

	// Initialize drivers
	new CCNDriver();

	prctl(PR_SET_NAME, (unsigned long)&"gatord-main", 0, 0, 0);
	pthread_mutex_init(&numSessions_mutex, NULL);

	signal(SIGINT, handler);
	signal(SIGTERM, handler);
	signal(SIGABRT, handler);

	// Set to high priority
	if (setpriority(PRIO_PROCESS, syscall(__NR_gettid), -19) == -1) {
		logg->logMessage("setpriority() failed");
	}

	// Parse the command line parameters
	struct cmdline_t cmdline = parseCommandLine(argc, argv);

	if (cmdline.update) {
		return update(argv[0]);
	}

	// Verify root permissions
	uid_t euid = geteuid();
	if (euid) {
		logg->logError(__FILE__, __LINE__, "gatord must be launched with root privileges");
		handleException();
	}

	// Call before setting up the SIGCHLD handler, as system() spawns child processes
	if (!setupFilesystem(cmdline.module)) {
		logg->logMessage("Unable to setup gatorfs, trying perf");
		if (!gSessionData->perf.setup()) {
			logg->logError(__FILE__, __LINE__,
				       "Unable to locate gator.ko driver:\n"
				       "  >>> gator.ko should be co-located with gatord in the same directory\n"
				       "  >>> OR insmod gator.ko prior to launching gatord\n"
				       "  >>> OR specify the location of gator.ko on the command line\n"
				       "  >>> OR run Linux 3.4 or later with perf (CONFIG_PERF_EVENTS and CONFIG_HW_PERF_EVENTS) and tracing (CONFIG_TRACING and CONFIG_CONTEXT_SWITCH_TRACER) support to collect data via userspace only");
			handleException();
		}
	}

	{
		EventsXML eventsXML;
		mxml_node_t *xml = eventsXML.getTree();
		// Initialize all drivers
		for (Driver *driver = Driver::getHead(); driver != NULL; driver = driver->getNext()) {
			driver->readEvents(xml);
		}
		mxmlDelete(xml);
	}

	// Handle child exit codes
	signal(SIGCHLD, child_exit);

	// Ignore the SIGPIPE signal so that any send to a broken socket will return an error code instead of asserting a signal
	// Handling the error at the send function call is much easier than trying to do anything intelligent in the sig handler
	signal(SIGPIPE, SIG_IGN);

	// If the command line argument is a session xml file, no need to open a socket
	if (gSessionData->mSessionXMLPath) {
		child = new Child();
		child->run();
		delete child;
	} else {
		gSessionData->annotateListener.setup();
		sock = new OlyServerSocket(cmdline.port);
		udpListener.setup(cmdline.port);
		if (!monitor.init() ||
				!monitor.add(sock->getFd()) ||
				!monitor.add(udpListener.getReq()) ||
				!monitor.add(gSessionData->annotateListener.getFd()) ||
				false) {
			logg->logError(__FILE__, __LINE__, "Monitor setup failed");
			handleException();
		}
		// Forever loop, can be exited via a signal or exception
		while (1) {
			struct epoll_event events[2];
			logg->logMessage("Waiting on connection...");
			int ready = monitor.wait(events, ARRAY_LENGTH(events), -1);
			if (ready < 0) {
				logg->logError(__FILE__, __LINE__, "Monitor::wait failed");
				handleException();
			}
			for (int i = 0; i < ready; ++i) {
				if (events[i].data.fd == sock->getFd()) {
					handleClient();
				} else if (events[i].data.fd == udpListener.getReq()) {
					udpListener.handle();
				} else if (events[i].data.fd == gSessionData->annotateListener.getFd()) {
					gSessionData->annotateListener.handle();
				}
			}
		}
	}

	cleanUp();
	return 0;
}
Пример #18
0
int main(int argc, char **argv) {
   struct sockaddr_in sa;
   struct sockaddr_in ca;
   int clen = 16;
   int one = 1;
   struct timeval timeout = {3, 0};
   struct passwd *pw;
   int u = 0;
   int g = 0;
   
   signal(SIGINT, sig_int_handler);
   signal(SIGCHLD, SIG_IGN);
   
   memset(&sa, 0, sizeof(sa));
   sa.sin_family = AF_INET;
   sa.sin_port = htons(SERVER_PORT);

   serv = socket(AF_INET, SOCK_STREAM, 0);
   if (serv == -1) {perror("socket"); exit(1);}

   setsockopt(serv, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
   
   if (bind(serv, (struct sockaddr*)&sa, sizeof(sa))) {
      perror("bind"); 
      exit(1);
   }

   if (listen(serv, 10)) {
      perror("listen"); 
      exit(1);
   }

   //drop privs
   pw = getpwnam("cs4678");
   if (pw) {
      u = pw->pw_uid;
      g = pw->pw_gid;
      chdir(pw->pw_dir);
   }
   else {
      fprintf(stderr, "Unable to drop privs to cs4678\n");
      exit(1);
   }
   setresgid(g, g, g);
   setresuid(u, u, u);

   daemon(1, 0);
   
   memset(&ca, 0, sizeof(ca));
   ca.sin_family = AF_INET;
   while (!done) {
      int csock;
      csock = accept(serv, NULL, NULL);
      if (fork() == 0) {
         close(serv);
         handleClient(csock);
         exit(0);
      }
      else {
         close(csock);
      }
   }
   close(serv);
}
Пример #19
0
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;
}
Пример #20
0
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;
}
Пример #21
0
// Gator data flow: collector -> collector fifo -> sender
int main(int argc, char** argv) {
	// Ensure proper signal handling by making gatord the process group leader
	//   e.g. it may not be the group leader when launched as 'sudo gatord'
	setsid();

	// Set up global thread-safe logging
	logg.setDebug(hasDebugFlag(argc, argv));
	gSessionData.initialize();

	prctl(PR_SET_NAME, (unsigned long)&"gatord-main", 0, 0, 0);
	pthread_mutex_init(&numSessions_mutex, NULL);

	signal(SIGINT, handler);
	signal(SIGTERM, handler);
	signal(SIGABRT, handler);

	// Set to high priority
	if (setpriority(PRIO_PROCESS, syscall(__NR_gettid), -19) == -1) {
		logg.logMessage("setpriority() failed");
	}

	// Try to increase the maximum number of file descriptors
	{
		struct rlimit rlim;
		memset(&rlim, 0, sizeof(rlim));
		if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
			logg.logMessage("Unable to get the maximum number of files");
			// Not good, but not a fatal error either
		} else {
			rlim.rlim_cur = max(((rlim_t)1)<<15, rlim.rlim_cur);
			rlim.rlim_max = max(rlim.rlim_cur, rlim.rlim_max);
			if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
				logg.logMessage("Unable to increase the maximum number of files");
				// Not good, but not a fatal error either
			}
		}
	}

	// Parse the command line parameters
	struct cmdline_t cmdline = parseCommandLine(argc, argv);

	// Verify root permissions
	uid_t euid = geteuid();
	if (euid) {
		logg.logError("gatord must be launched with root privileges");
		handleException();
	}

	PmuXML::read(cmdline.pmuPath);

	// Call before setting up the SIGCHLD handler, as system() spawns child processes
	if (setupFilesystem(cmdline.module)) {
		DriverSource::checkVersion();
		PmuXML::writeToKernel();
	} else {
		logg.logMessage("Unable to set up gatorfs, trying perf");
		if (!gSessionData.mPerf.setup()) {
			logg.logError(
				       "Unable to locate gator.ko driver:\n"
				       "  >>> gator.ko should be co-located with gatord in the same directory\n"
				       "  >>> OR insmod gator.ko prior to launching gatord\n"
				       "  >>> OR specify the location of gator.ko on the command line\n"
				       "  >>> OR run Linux 3.4 or later with perf (CONFIG_PERF_EVENTS and CONFIG_HW_PERF_EVENTS) and tracing (CONFIG_TRACING and CONFIG_CONTEXT_SWITCH_TRACER) support to collect data via userspace only");
			handleException();
		}
	}

	{
		EventsXML eventsXML;
		mxml_node_t *xml = eventsXML.getTree();
		// Initialize all drivers
		for (Driver *driver = Driver::getHead(); driver != NULL; driver = driver->getNext()) {
			driver->readEvents(xml);
		}
		mxmlDelete(xml);
	}

	// Handle child exit codes
	signal(SIGCHLD, child_exit);

	// Ignore the SIGPIPE signal so that any send to a broken socket will return an error code instead of asserting a signal
	// Handling the error at the send function call is much easier than trying to do anything intelligent in the sig handler
	signal(SIGPIPE, SIG_IGN);

	// If the command line argument is a session xml file, no need to open a socket
	if (gSessionData.mSessionXMLPath) {
		child = new Child();
		child->run();
		delete child;
	} else {
		annotateListener.setup();
		int pipefd[2];
		if (pipe_cloexec(pipefd) != 0) {
			logg.logError("Unable to set up annotate pipe");
			handleException();
		}
		gSessionData.mAnnotateStart = pipefd[1];
		sock = new OlyServerSocket(cmdline.port);
		udpListener.setup(cmdline.port);
		if (!monitor.init() ||
				!monitor.add(sock->getFd()) ||
				!monitor.add(udpListener.getReq()) ||
				!monitor.add(annotateListener.getSockFd()) ||
				!monitor.add(annotateListener.getUdsFd()) ||
				!monitor.add(pipefd[0]) ||
				false) {
			logg.logError("Monitor setup failed");
			handleException();
		}
		// Forever loop, can be exited via a signal or exception
		while (1) {
			struct epoll_event events[2];
			logg.logMessage("Waiting on connection...");
			int ready = monitor.wait(events, ARRAY_LENGTH(events), -1);
			if (ready < 0) {
				logg.logError("Monitor::wait failed");
				handleException();
			}
			for (int i = 0; i < ready; ++i) {
				if (events[i].data.fd == sock->getFd()) {
					handleClient();
				} else if (events[i].data.fd == udpListener.getReq()) {
					udpListener.handle();
				} else if (events[i].data.fd == annotateListener.getSockFd()) {
					annotateListener.handleSock();
				} else if (events[i].data.fd == annotateListener.getUdsFd()) {
					annotateListener.handleUds();
				} else if (events[i].data.fd == pipefd[0]) {
					uint64_t val;
					if (read(pipefd[0], &val, sizeof(val)) != sizeof(val)) {
						logg.logMessage("Reading annotate pipe failed");
					}
					annotateListener.signal();
				}
			}
		}
	}

	cleanUp();
	return 0;
}
Пример #22
0
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;
}
Пример #23
0
void PixelFlutTCPSource::receiveLoop()
{
	struct pollfd fds[MAX_NUM_CLIENTS + 1]; // Reserve on additional slot for the server socket
	int nfds = 1;
	int timeoutMs = 250; // More or less educated guess
	bool rebuildFdMap = false;

	fds[0].fd = _serverSocket;
	fds[0].events = POLLIN;

	for(uint32_t i = 0; i < MAX_NUM_CLIENTS; i++)
	{
		fds[i + 1].events = POLLIN;
	}

	while(_run)
	{
		if(rebuildFdMap)
		{
			nfds = 1;

			// This client cache thing makes it possible to access the std::map only if a client connects or disconnects. Otherwise only simple array dereferencing is done.

			for(auto client : _clients)
			{
				if(client.second != nullptr)
				{
					_clientCache[nfds - 1] = client.second;
					fds[nfds].fd = _clientCache[nfds - 1]->clientSocket;

					nfds++;
				}
				else
				{
					continue;
				}
			}

			rebuildFdMap = false;
		}

		int rc = poll(fds, nfds, timeoutMs);

		if(rc > 0)
		{
			for(uint32_t i = 0; i < (uint32_t)nfds; i++)
			{
				int pfd = fds[i].fd;

				if(pfd < 0)
					continue;

				if(fds[i].revents & POLLIN)
				{
					fds[i].revents = 0;

					if(i == 0)
					{
						int clientSocket = accept(_serverSocket, NULL, NULL);

						if(_clients.size() == MAX_NUM_CLIENTS)
						{
							close(clientSocket);
						}
						else
						{
							ClientInfo* client = new ClientInfo();

							client->clientSocket = clientSocket;

							LOG("Client connected: %d", clientSocket);

							_clients.insert(std::make_pair(clientSocket, client));

							rebuildFdMap = true;
						}
					}
					else
					{
						ClientInfo* client = _clientCache[i - 1];

						uint8_t buffer[NET_BUFFER_SIZE];
						int readStatus = 0;

						readStatus = recv(pfd, buffer, NET_BUFFER_SIZE, 0);

						if(readStatus == 0)
						{
							LOG("Client disconnected: %d", pfd);

							std::map<int, ClientInfo*>::iterator clientIt = _clients.find(pfd);

							close(pfd);

							_clients.erase(clientIt);

							delete client;

							rebuildFdMap = true;
						}
						else if(readStatus > 0)
						{
							client->dataBuffer.append((const char*)buffer, readStatus);

							//LOG("client %d data: %s", client->clientSocket, client->dataBuffer.c_str());

							handleClient(client);
						}
					}
				}
			}
		}
	}
}