void Server::incomingConnection(int socketDescriptor) {
    qDebug() << "Incoming connection";
    socket = new QTcpSocket(this);
    socket->setSocketDescriptor(socketDescriptor);
    connect(socket, SIGNAL(readyRead()), this, SLOT(processClient()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(removeClient()));
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(socketError(QAbstractSocket::SocketError)));
}
void* startRoutine(void* arg)
{
    ARG* info = (ARG*)arg;
    processClient(info->connectfd, info->client);
    // Release arg
    free(info);               
    echo("[SERVICE] thread %d terminated\n", pthread_self());
    pthread_exit(NULL);
}
Exemple #3
0
void Visualight::update(){
	if(isServer){
    	processServer();
  	}
  	else{
    	processClient();
  	}
  	processButton(); //TODO: test to see how much blockage this has...
    if(alerting && (millis() % 5)==0) alert();
}
bool FwmarkServer::onDataAvailable(SocketClient* client) {
    int socketFd = -1;
    int error = processClient(client, &socketFd);
    if (socketFd >= 0) {
        close(socketFd);
    }

    // Always send a response even if there were connection errors or read errors, so that we don't
    // inadvertently cause the client to hang (which always waits for a response).
    client->sendData(&error, sizeof(error));

    // Always close the client connection (by returning false). This prevents a DoS attack where
    // the client issues multiple commands on the same connection, never reading the responses,
    // causing its receive buffer to fill up, and thus causing our client->sendData() to block.
    return false;
}
int Server::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QTcpServer::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: processClient(); break;
        case 1: processComplete((*reinterpret_cast< Reply*(*)>(_a[1]))); break;
        case 2: socketError((*reinterpret_cast< QAbstractSocket::SocketError(*)>(_a[1]))); break;
        default: ;
        }
        _id -= 3;
    }
    return _id;
}
void runloop(server_t* server) {
	struct pollfd pollDescriptors[kMaxClients + 1];
	int socksToHandle;
	
	memset(pollDescriptors, 0, sizeof(struct pollfd)*kMaxClients + 1);
	int pollNumDescriptors = 1;
	pollDescriptors[0].fd = server->socket;
	pollDescriptors[0].events = POLLIN | POLLHUP;
	{
		int i = 1;
		for (int j = 0; j < kMaxClients; j++) {
			if (server->clients[j] != NULL) {
				pollDescriptors[i].fd = server->clients[j]->socket;
				pollDescriptors[i].events = POLLIN | POLLHUP;
				i++;
				pollNumDescriptors = i;
			}
		}
	}
	
	socksToHandle = poll(pollDescriptors, pollNumDescriptors, kPollTimeout);

	if (socksToHandle < 0) {
		server->running = false;
		perror("poll");
		return;
	}
	else if (socksToHandle > 0) {
		for (int i = 0; i < pollNumDescriptors; i++) {
			if ((pollDescriptors[i].revents & POLLIN) > 0) {
				if (pollDescriptors[i].fd == server->socket) {
					if (!acceptNewClient(server)) {
						server->running = false;
						return;
					}
				}
				else {
					for (int j = 0; j < kMaxClients; j++) {
						if (server->clients[j] && server->clients[j]->socket == pollDescriptors[i].fd) {
							if (!processClient(server->clients[j])) {
								CloseClient(server->clients[j]);
							}
						}
					}
				}
			}
			if ((pollDescriptors[i].revents & POLLHUP) > 0) {
				if (pollDescriptors[i].fd == server->socket) {
						server->running = false;
						return;
				}
				else {
					for (int j = 0; j < kMaxClients; j++) {
						if (server->clients[j] && server->clients[j]->socket == pollDescriptors[i].fd) {
							CloseClient(server->clients[j]);
						}
					}
				}
			}
		}
	}
}
Exemple #7
0
	void DNServer::mainLoop()
	{
        #ifdef __linux
            typedef int SOCKET;
            typedef sockaddr SOCKADDR;
            typedef sockaddr_in SOCKADDR_IN;
            const int INVALID_SOCKET = -1;
            #define closesocket(X) close(X)
        #endif
		SOCKET servSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
		if (servSock == INVALID_SOCKET)
			throw logic_error("DNServer: socket error");

		SOCKET cliSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
		if (cliSock == INVALID_SOCKET)
		{
			closesocket(servSock);
			throw logic_error("DNServer: socket error");
		}

		try
		{
			SOCKADDR_IN ssin = { 0 };
			ssin.sin_family = AF_INET;
			ssin.sin_addr.s_addr = inet_addr(cfpars["main"]["bindaddr"].c_str());
			ssin.sin_port = htons(stoi(cfpars["main"]["bindport"]));

			SOCKADDR_IN assin = { 0 };
			assin.sin_family = AF_INET;
			assin.sin_addr.s_addr = inet_addr(cfpars["main"]["rootdns"].c_str());
			assin.sin_port = htons(stoi(cfpars["main"]["rootdnsport"]));

			if (::bind(servSock, reinterpret_cast<SOCKADDR*>(&ssin), sizeof(ssin)))
					throw logic_error("DNServer: bind error");

			unsigned char packet[BUFSIZE];
			while (1)
			{
				memset(packet, 0, sizeof(packet));
				size_t recSize;
				SOCKADDR_IN ssinf = { 0 };
                #ifdef _WIN32
                    int ssinsz = sizeof(ssinf);
                #elif __linux
                    socklen_t ssinsz = sizeof(ssinf);
                #endif
				if ((recSize = recvfrom(servSock, reinterpret_cast<char*>(packet), sizeof(packet), 0, reinterpret_cast<SOCKADDR*>(&ssinf), &ssinsz)) > 0)
				{
					DnsResponse response(packet);
					if (filter(inet_ntoa(ssinf.sin_addr)) && processClient(response))
					{
						// обработать запрос и отдать ответ
						size_t respsize = response.size();

						response.setTruncated(respsize >= 512);

						if (respsize > sizeof(packet))
						{
							unique_ptr<unsigned char[]> uptr(new unsigned char[respsize]);
							response.dump(uptr.get());
							sendto(servSock, reinterpret_cast<char*>(uptr.get()), respsize, 0, reinterpret_cast<SOCKADDR*>(&ssinf), sizeof(ssinf));
						}
						else
						{
							memset(packet, 0, sizeof(packet));
							response.dump(packet);
							sendto(servSock, reinterpret_cast<char*>(packet), respsize, 0, reinterpret_cast<SOCKADDR*>(&ssinf), sizeof(ssinf));
						}
					}
					else
					{
						// данный тип запроса не поддерживаетс¤
						// отправить запрос основному серверу
						sendto(cliSock, reinterpret_cast<char*>(packet), recSize, 0, reinterpret_cast<SOCKADDR*>(&assin), sizeof(assin));
						memset(packet, 0, sizeof(packet));
						int rfms = recvfrom(cliSock, reinterpret_cast<char*>(packet), sizeof(packet), 0, NULL, NULL);
						sendto(servSock, reinterpret_cast<char*>(packet), rfms, 0, reinterpret_cast<SOCKADDR*>(&ssinf), sizeof(ssinf));
					}
				}
			}
		}
		catch (...)
		{
			closesocket(servSock);
			closesocket(cliSock);
			throw;
		}
		
		closesocket(servSock);
		closesocket(cliSock);
	}
Exemple #8
0
void ServerController::run()
{	
	sf::TcpListener listener;
	
	if(listener.listen(60000)!= sf::Socket::Done)
	{
		data.addLog("Could not bind server to the defined network port (60000).");
		return;
	}
		
	selector.add(listener);
	
	for(;;){
		/*
		time_t current = getTimeValue();
		//check if current time is past deadline
		if (current > deadline)
		{
			autoAllocate();
		}
		*/
		
		if (selector.wait()){
			// Test the listener
			if (selector.isReady(listener))
			{
				// The listener is ready: there is a pending connection
				sf::TcpSocket* client = new sf::TcpSocket;
				if (listener.accept(*client) == sf::Socket::Done)
				{
					data.addLog("New connection from " + client->getRemoteAddress().toString());
					// Add the new client to the clients list
					clients.push_back(client);
					// Add the new client to the selector so that we will
					// be notified when he sends something
					selector.add(*client);
				}
				else
				{
					// Error, we won't get a new connection, delete the socket
					delete client;
				}
			}
			else
			{
				// The listener socket is not ready, test all other sockets (the clients)
				std::list<sf::TcpSocket*>::iterator end = clients.end();
				for (std::list<sf::TcpSocket*>::iterator it = clients.begin(); it != end; ++it)
				{
					sf::TcpSocket& client = **it;
					if (selector.isReady(client))
					{
					// The client has sent some data, we can receive it
						sf::Packet packet;
						sf::Socket::Status status;
						status = client.receive(packet);
						if (status == sf::Socket::Done)
						{
							processClient(packet, client);
							packet.clear();
						}
						// The client has disconnected, stop listening to them
						else if (status == sf::Socket::Disconnected)
						{
							data.addLog("Client (" + client.getRemoteAddress().toString() 
								+ ") disconnected");
							packet.clear();
							
							sf::TcpSocket * del = *it;
							clients.erase(it);
							selector.remove(**it);
							delete del;
							it = clients.begin();
							end = clients.end();
						}			
					}
				}
			}
		}
	}
}
Exemple #9
0
int main(int argc, char *argv[]){
  int sock, length, msgsock, status, newsockfd, n;
  struct sockaddr_in server, client;


  // for forking, and cleaning up zombie child state afterwards

  pid_t id;
  signal(SIGCHLD, &eatZombies);

  int sockfd = socket(AF_INET, SOCK_STREAM, 0);//Set up a new socket

  if(sockfd < 0)//If the socket descriptor is negative then it failed to create a new socket
  {
    fprintf(stderr,"Failed creating socket\n");
  }
  else{
    fprintf(stderr,"created socket\n");
  }

  // Next, create the socket addressing structure
  server.sin_family = AF_INET;
  server.sin_addr.s_addr = INADDR_ANY;
  server.sin_port = htons(atoi(argv[1])); // this time 1st arg is port#

  if(bind(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)//Bind the socket to the specified port
  {
    fprintf(stderr,"Failed to bind\n");
    exit(-1);
  }
  else {
    fprintf(stderr,"bound socket\n");//Print to the console saying that we have successfully bound
  }

  // Start by listening
  listen(sockfd, 5);
  fprintf(stderr,"listening\n");

  while(1){//Continue to accept connections until the program is ended

    // you need to accept the connection request
    int clientlen = sizeof(client);//Get the size of the client structure
    newsockfd = accept(sockfd, (struct sockaddr *) &client, &clientlen);//Accept a new connection and return its descriptor
    if(newsockfd < 0)
    {
      fprintf(stderr,"ERROR accepting\n");
      exit(-1);
    }

    // the next call makes a new child process that will actually handle the client.
    id = fork();

    // when id == 0, this is the child and needs to do the work for the server.
    if(id == 0)
    {
    //  close(sockfd);//close the
      processClient(newsockfd);//Read from the new client connection then send a reply
      exit(0);//exit this client after reading and writing
    }

    
    // when id < 0, we had an error.
    if(id < 0)
    {
      fprintf(stderr,"ERROR when trying to accept\n");
    }
// when if > 0, this is the parent, and it should just loop around,
  }

}
Exemple #10
0
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);
}