コード例 #1
0
ファイル: Main.cpp プロジェクト: ccosmin/eventloop
int main()
{
  /*
  StdWriteRead stdWriteRead;
  runloop.registerReadIntent(fileno(stdin), &stdWriteRead);
  runloop.run();
  */
  /*
  try
  {
    RunLoop runloop;
    Socket socket;
    socket.connect("localhost", 22, false);
    int sock = socket.getSocket();
    StdWriteRead stdWriteRead(sock);
    runloop.registerReadIntent(sock, &stdWriteRead);
    runloop.run();
  } 
  catch ( std::runtime_error r )
  {
    fprintf(stderr, r.what());
  }
  */
  ServerSocket serverSocket;
  serverSocket.listen("0.0.0.0", 3000, 10);
  std::string ip;
  serverSocket.accept(&ip, NULL);
  printf("socket: %s\n", ip.c_str());
}
コード例 #2
0
ファイル: TelnetServer.cpp プロジェクト: benpayne/jhcommon
void TelnetServer::start( int port )
{
	Socket::Address addr( port );
	mSocket.bind( addr );
	mSocket.listen( 5 );
	mSocket.setSelector( this, &mSelector );
}
コード例 #3
0
ファイル: IOUtil.cpp プロジェクト: denofiend/code-lib
void IOUtil::createSocketPair(int pair[2]) throw (IOException&)
{
#if defined(WIN32)
	Socket connectSocket;
	Socket serverClientSocket;
	ServerSocket listenSocket;

	SocketAddress loopback = SocketAddress::loopback(AF_INET, 0);
	listenSocket.listen(loopback, 5, false);
	connectSocket.connect(listenSocket.getLocalAddress(), true);

	if (!listenSocket.accept(serverClientSocket))
	{
		THROW2(IOException, "Can't accept for socket pair");
	}

	pair[0] = connectSocket.detach();
	pair[1] = serverClientSocket.detach();
#else
	if (0 != ::socketpair(AF_LOCAL, SOCK_STREAM, 0, pair))
	{
		THROW2(IOException, "Can't create socket pair");
	}
#endif
}
コード例 #4
0
void SocketTest::testConnect()
{
	ServerSocket serv;
	serv.bind(SocketAddress());
	serv.listen();
	StreamSocket ss;
	Timespan timeout(250000);
	ss.connect(SocketAddress("localhost", serv.address().port()), timeout);
}
コード例 #5
0
void KeyValueStore::InternalThread::incomingRoutine()
{
  const Config::ServerInformation& info = config.getServerInformation();
  Config::ThreadControl& control = config.getThreadControl();
  Mutex& inMutex = control.getInMutex();
  Condition& cond = control.getInCondition();
  Thread incoming;
  Incoming inTask;
  int currId = -1;
  static bool first = true;

  // Init connection info
  SocketAddress sock(info.address, info.internalPort);
  ServerSocket server;
  try {
    server.bind(sock, true);
    server.listen(5);
  } catch(Exception& e) {
    printKv("Could not initialize internal thread, please restart server ("<< e.displayText()<< ")");
  }

  StreamSocket client;

  while(control.isLive()) {
    inMutex.lock();
    cond.wait(inMutex);
    unsigned nextId = control.getConnectedId();
    inMutex.unlock();

    // NOTE: From a security perspective this is not safe.
    //  if someone tries to connect at the same time a rejoin
    //  was initiated, they could easily perform a MITM attack.
    //  However, since this is an academic exercise, I am not too
    //  concerned with security (as can be seen by many other components
    //  in this system as well).
    if(currId != (int)nextId) {
      currId = nextId;
      // TODO: Update processing thread somehow
      printKv("Told a new server should be connecting...");
      try {
        client = server.acceptConnection();
        printKv("Incoming server connected: "<< currId);
        inTask.cancel();
        if(!first)
          incoming.join();
        first = false;
        inTask = Incoming(client, &config.getThreadControl());
        incoming.start(inTask);
        printKv("Handling new server");
      } catch(TimeoutException& e) {
        printKv("Server did not connect in time - we don't want the system to be hung up, though ("<< e.displayText() <<")");
      }
    }
  }

  server.close();
}
コード例 #6
0
ファイル: Receiver.cpp プロジェクト: hexq/wdt
WdtTransferRequest Receiver::init() {
  vector<ServerSocket> successfulSockets;
  for (size_t i = 0; i < threadServerSockets_.size(); i++) {
    ServerSocket socket = std::move(threadServerSockets_[i]);
    int max_retries = WdtOptions::get().max_retries;
    for (int retries = 0; retries < max_retries; retries++) {
      if (socket.listen() == OK) {
        break;
      }
    }
    if (socket.listen() == OK) {
      successfulSockets.push_back(std::move(socket));
    } else {
      LOG(ERROR) << "Couldn't listen on port " << socket.getPort();
    }
  }
  LOG(INFO) << "Registered " << successfulSockets.size() << " sockets";
  ErrorCode code = OK;
  if (threadServerSockets_.size() != successfulSockets.size()) {
    code = FEWER_PORTS;
    if (successfulSockets.size() == 0) {
      code = ERROR;
    }
  }
  threadServerSockets_ = std::move(successfulSockets);
  WdtTransferRequest transferRequest(getPorts());
  transferRequest.protocolVersion = protocolVersion_;
  transferRequest.transferId = transferId_;
  LOG(INFO) << "Transfer id " << transferRequest.transferId;
  if (transferRequest.hostName.empty()) {
    char hostName[1024];
    int ret = gethostname(hostName, sizeof(hostName));
    if (ret == 0) {
      transferRequest.hostName.assign(hostName);
    } else {
      PLOG(ERROR) << "Couldn't find the host name";
      code = ERROR;
    }
  }
  transferRequest.directory = destDir_;
  transferRequest.errorCode = code;
  return transferRequest;
}
コード例 #7
0
void SocketTest::testAddress()
{
	ServerSocket serv;
	serv.bind(SocketAddress());
	serv.listen();
	StreamSocket ss;
	ss.connect(SocketAddress("localhost", serv.address().port()));
	StreamSocket css = serv.acceptConnection();
	assert (css.peerAddress().host() == ss.address().host());
	assert (css.peerAddress().port() == ss.address().port());
}
コード例 #8
0
ファイル: main.cpp プロジェクト: guolilong2012/study
int main(int argc, char *argv[])
{
  QApplication app(argc, argv);
  ServerSocket s;

  ClientSocket::loadPasswd();
  QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
  if (!s.listen(QHostAddress::Any, 4869)) {
    qDebug() << "cannot bind address";
    exit(1);
  }
  return app.exec();
}
コード例 #9
0
void LocalSocketTest::testAddress()
{
	SocketAddress sas("/tmp/poco.server.tcp.sock");
	ServerSocket serv;
	serv.bind(sas);
	serv.listen();
	StreamSocket ss;
	SocketAddress sac("/tmp/poco.client.tcp.sock");
	ss.connect(sas, &sac);
	StreamSocket css = serv.acceptConnection();
	assert (css.peerAddress().host() == ss.address().host());
	assert (css.peerAddress().port() == ss.address().port());
}
コード例 #10
0
/** Public thread methods (clients connect here) */
void KeyValueStore::PublicThread::run()
{
  Thread threads[MAX_CLIENT_THREADS];
  HandleClient threadInst[MAX_CLIENT_THREADS];
  const Config::ServerInformation& info = config.getServerInformation();
  Config::ThreadControl& control = config.getThreadControl();
  int id = 0;
  char full = Protocol::SRV_FULL;
  char conn = Protocol::SRV_CONN;

  ServerSocket server;
  SocketAddress sock(info.address, info.pubPort);
  server.bind(sock, true);
  server.listen(5);

  printKv("Listening for clients on "<< info.address <<":"<< info.pubPort);

  while(control.isLive()) {
    // Simply do thread per client
    StreamSocket client = server.acceptConnection();
    printKv("Received client connection request - waiting for thread to free up");
    
    // Wait five seconds
    try {
      freeThreads.wait(5000); // This beats busy waiting
    } catch(TimeoutException& notUsed(e)) {
      printKv("Server full - closing connection to client");
      client.sendBytes(&full, sizeof(full));
      client.close();
      continue;
    }

    // Send success
    client.sendBytes(&conn, sizeof(conn));

    // tryJoin() doesn't work properly in linux, using isRunning() instead
    // actively search for the next available thread
    while(threads[id].isRunning()){ // Try to get an available thread
      id = (id + 1) % MAX_CLIENT_THREADS;
      Thread::sleep(250); // 250ms between each check
    }

    printKv("Serving client");
    threadInst[id] = HandleClient(client, control);
    threads[id].start(threadInst[id]);
  }

  server.close();
  freeThreads.set(); // Free a thread with semaphore
}
コード例 #11
0
void SocketTest::testConnectRefused()
{
	ServerSocket serv;
	serv.bind(SocketAddress());
	serv.listen();
	Poco::UInt16 port = serv.address().port();
	serv.close();
	StreamSocket ss;
	Timespan timeout(250000);
	try
	{
		ss.connect(SocketAddress("localhost", port));
		fail("connection refused - must throw");
	}
	catch (ConnectionRefusedException&)
	{
	}
}
コード例 #12
0
void LocalSocketTest::testConnectRefusedNB()
{
	SocketAddress sas("/tmp/poco.server.tcp.sock");
	ServerSocket serv;
	serv.bind(sas);
	serv.listen();
	serv.close();
	StreamSocket ss;
	Timespan timeout(10000);
	SocketAddress sac("/tmp/poco.client.tcp.sock");
	try
	{
		ss.connect(sas, timeout, &sac);
		fail("connection refused - must throw");
	}
	catch (TimeoutException&)
	{
	}
	catch (ConnectionRefusedException&)
	{
	}
}
コード例 #13
0
ファイル: main.cpp プロジェクト: BaseOfTheClick/SETIJam
int main(int argc, char *argv[])
{
    LogFile log("test.log");

    log << "**************************"
        << "New server session started";

    Address addr(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(!addr.getHost(HOST, PORT))
    {
        logHost(log, "Unable to resolve");
        return 1;
    }
    else
    {
        logHost(log, "Resolved");
    }

    ServerSocket server;
    if(server.bind(addr) <= 0)
    {
        logHost(log, "Unable to bind to");
        return 2;
    }
    else
    {
        logHost(log, "Bound to");
    }

    cout << "Server FD: " << server << endl;

    if(!server.listen(10))
    {
        logHost(log, "Unable to listen on");
        return 3;
    }
    else
    {
        logHost(log, "Listening on");
        cout << "Listening on " << HOST << ":" << PORT << endl;
    }

    // Client and select poll structure setup
    //vector<ClientSocket> clients;
    map<int, unique_ptr<ClientSocket>> table;
    map<int, string> names;
    Multiplexer select;

    server.setNonBlock(1);
    select.insert(server);

    Galaxy galaxy;

    while(true)
    {
        if(select.poll() == -1)
        {
            cerr << "select.poll() error\n";
            break;
        }

        for(int i = 0; i < FD_SETSIZE; ++i)
        {
            if(select.setRead(i))
            {
                if(server == i)
                {
                    ClientSocket *client = new ClientSocket(server.accept());

                    if(client)
                    {
                        client->setNonBlock(1);
                        select.insert(*client);
                        table[*client] = unique_ptr<ClientSocket>(client);
                    }
                    else
                        log << "A client was rejected from the server";

                    continue;
                }

                char buf[256];
                int bytes = recv(i, &buf[0], 255, 0);
                if(bytes <= 0)
                {
                    table[i]->close();
                    galaxy.rmPlayer(names[i]);
                    select.eradicate(i);
                    continue;
                }

                buf[bytes] = '\0';
                string buffer(buf);

                cout << "Client: " << buffer;
                auto pos = buffer.find(':');
                if(buffer.substr(0, pos) == "Login")
                {
                    string name = buffer.substr(pos + 1,
                                                buffer.size() - pos);

                    Player *p;
                    try { p = &galaxy.newPlayer(name); }
                    catch(...)
                    {
                        table[i]->close();
                        select.eradicate(i);
                    } 

                    names[i] = name;

                    string planet = "Planet:" + to_string(p->world().x())
                                    + ":" + to_string(p->world().y()) + "\n";
                    table[i]->write(planet.c_str());

                }
                // End of client handler block
            }
        }
    }

    for(auto& client : table)
    {
        if(client.second > 0)
            client.second->close();
    }

    return 0;
}
コード例 #14
0
void FileTransferSocketThread::execute()
{
    if(info.hostType == eServer)
    {
        ServerSocket serverSocket;
        serverSocket.bind(this->info.serverPort);
        serverSocket.listen(1);
        Socket *clientSocket = serverSocket.accept();

        char data[513]="";
        memset(data, 0, 256);

        clientSocket->receive(data,256, true);
        if(*data == SEND_FILE)
        {
            FileInfo file;

            memcpy(&file, data+1, sizeof(file));

            *data=ACK;
            clientSocket->send(data,256);

            Checksum checksum;
            checksum.addFile(file.fileName);
            file.filecrc  = checksum.getSum();

            ifstream infile(file.fileName.c_str(), ios::in | ios::binary | ios::ate);
            if(infile.is_open() == true)
            {
                file.filesize = infile.tellg();
                infile.seekg (0, ios::beg);

                memset(data, 0, 256);
                *data=SEND_FILE;
                memcpy(data+1,&file,sizeof(file));

                clientSocket->send(data,256);
                clientSocket->receive(data,256, true);
                if(*data != ACK) {
                   //transfer error
                }

                int remain=file.filesize % 512 ;
                int packs=(file.filesize-remain)/512;

                while(packs--)
                {
                    infile.read(data,512);
                    //if(!ReadFile(file,data,512,&read,NULL))
                    //    ; //read error
                    //if(written!=pack)
                    //    ; //read error
                    clientSocket->send(data,512);
                    clientSocket->receive(data,256, true);
                    if(*data!=ACK) {
                           //transfer error
                    }
                }

                infile.read(data,remain);
                //if(!ReadFile(file,data,remain,&read,NULL))
                //   ; //read error
                //if(written!=pack)
                //   ; //read error

                clientSocket->send(data,remain);
                clientSocket->receive(data,256, true);
                if(*data!=ACK) {
                   //transfer error
                }

                infile.close();
            }
        }

        delete clientSocket;
    }
    else
    {
        Ip ip(this->info.serverIP);
        ClientSocket clientSocket;
        clientSocket.connect(this->info.serverIP, this->info.serverPort);

        if(clientSocket.isConnected() == true)
        {
            FileInfo file;
            file.fileName = this->info.fileName;
            //file.filesize =
            //file.filecrc  = this->info.

            string path = extractDirectoryPathFromFile(file.fileName);
            createDirectoryPaths(path);
            ofstream outFile(file.fileName.c_str(), ios_base::binary | ios_base::out);
            if(outFile.is_open() == true)
            {
                char data[513]="";
                memset(data, 0, 256);
                *data=SEND_FILE;
                memcpy(data+1,&file,sizeof(file));

                clientSocket.send(data,256);
                clientSocket.receive(data,256, true);
                if(*data!=ACK) {
                  //transfer error
                }

                clientSocket.receive(data,256,true);
                if(*data == SEND_FILE)
                {
                   memcpy(&file, data+1, sizeof(file));
                   *data=ACK;
                   clientSocket.send(data,256);

                   int remain = file.filesize % 512 ;
                   int packs  = (file.filesize-remain) / 512;

                   while(packs--)
                   {
                      clientSocket.receive(data,512,true);

                      outFile.write(data, 512);
                      if(outFile.bad())
                      {
                          //int ii = 0;
                      }
                      //if(!WriteFile(file,data,512,&written,NULL))
                      //   ; //write error
                      //if(written != pack)
                      //   ; //write error
                      *data=ACK;
                      clientSocket.send(data,256);
                    }
                    clientSocket.receive(data,remain,true);

                    outFile.write(data, remain);
                    if(outFile.bad())
                    {
                        //int ii = 0;
                    }

                    //if(!WriteFile(file,data,remain,&written,NULL))
                    //    ; //write error
                    //if(written!=pack)
                    //    ; //write error
                    *data=ACK;
                    clientSocket.send(data,256);

                    Checksum checksum;
                    checksum.addFile(file.fileName);
                    uint32 crc = checksum.getSum();
                    if(file.filecrc != crc)
                    {
                        //int ii = 0;
                    }

                    //if(calc_crc(file)!=info.crc)
                    //   ; //transfeer error
                }

                outFile.close();
            }
        }
    }
}
コード例 #15
0
ファイル: hermes.cpp プロジェクト: jjguti/hermes
int
#ifdef WIN32_SERVICE
hermes_main
#else
main
#endif //WIN32_SERVICE
(int argc,char *argv[])
{
  /* TODO:think of this again
  if(argc>2)
  {
    for(unsigned i=1;i<argc;i++)
    {
      argv++
  }
  */

  #ifdef HAVE_SSL
    CRYPTO_set_locking_callback(ssl_locking_function);
    #ifndef WIN32 //getpid() returns different values for threads on windows, therefor this is not needed
    CRYPTO_set_id_callback(pthread_self);
    #endif //WIN32
  #endif //HAVE_SSL
  try
  {
    if(2==argc)
    {
      if(!Utils::file_exists(argv[1]))
        throw Exception(string(_("Config file "))+argv[1]+_(" doesn't exist or is not readable."),__FILE__,__LINE__);
      cfg.parse(argv[1]);
    }
    else
      throw Exception(_("Config file not specified"), __FILE__, __LINE__);
    cfg.validateConfig();
  }
  catch(Exception &e)
  {
    LERR(e);
    return -1;
  }

  unsigned long nconns=0;

  signal(SIGTERM,exit_requested);
  signal(SIGINT,exit_requested);
  #ifndef WIN32
  signal(SIGCHLD,SIG_IGN);
  signal(SIGPIPE,SIG_IGN);
  #endif //WIN32

  //we have to create the server socket BEFORE chrooting, because if we don't,
  //SSL cannot initialize because it's missing libz
  ServerSocket server;
  pthread_t cleaner_thread;
  string peer_address;

  #ifndef WIN32
    if(cfg.getBackground())
    {
      int retval;

      retval=fork();
      if(retval>0)
        exit(0); //succesful fork

      if(retval<0)
      {
        LERR(_("Error forking into the background") + Utils::errnotostrerror(errno));
        return -1;
      }
    }
    
    if(cfg.getPidFile()!="")
    {
      try
      {
        Utils::write_pid(cfg.getPidFile(),getpid());
      }
      catch(Exception &e)
      {
        LERR(e);
      }
    }

    if(cfg.getChroot()!="")
    {
      //this is needed to get hermes to load the dns resolver BEFORE chrooting
      (void)gethostbyname("hermes-project.com");
      if(-1 == chdir(cfg.getChroot().c_str()))
      {
        LERR(_("Couldn't chdir into ") + cfg.getChroot() + " " + Utils::errnotostrerror(errno) );
        return -1;
      }
      if(-1==chroot(cfg.getChroot().c_str()))
      {
        LERR(_("Couldn't chroot ") + Utils::errnotostrerror(errno));
        return -1;
      }
      if(-1 == chdir("/"))
      {
        LERR(_("Couldn't chdir into /, this shouldn't happen: " + Utils::errnotostrerror(errno)) );
        return -1;
      }
    }
  #endif //WIN32

  LINF("Starting hermes with pid "+Utils::inttostr(getpid()));
  try
  {
    server.init();
    server.setPort(cfg.getListeningPort());
    server.listen(cfg.getListeningPort(),cfg.getBindTo());
  }
  catch(Exception &e)
  {
    LERR(e);
    return -1; //couldn't bind, exit
  }

  #ifndef WIN32
  if(cfg.getDropPrivileges())
  {
    //drop privileges once we have opened the listening port
    if(-1 == setgroups(0,NULL))
    {
      LERR(_("Error dropping priviledges " + Utils::errnotostrerror(errno)) );
      return -1;
    }
    if(-1 == setgid(cfg.getGid()))
    {
      LERR(_("Error setting gid " + Utils::inttostr(cfg.getGid()) + " " + Utils::errnotostrerror(errno)) );
      return -1;
    }
    if(-1 == setuid(cfg.getUid()))
    {
      LERR(_("Error setting uid " + Utils::inttostr(cfg.getUid()) + " " + Utils::errnotostrerror(errno)) );
      return -1;
    }
    if(-1 == setuid(cfg.getUid()))
    {
      LERR(_("Error setting uid " + Utils::inttostr(cfg.getUid()) + " " + Utils::errnotostrerror(errno)) );
      return -1;
    }
  }
  #endif //WIN32

  /* start our cleaner thread */
  if(cfg.getCleanDb())
    pthread_create(&cleaner_thread,NULL,cleaner_thread_run,NULL);

  new_conn_info info;
  stack<new_conn_info> info_stack;
  while(!quit)
  {
    if(server.canRead(1)) //wait one second for incoming connections, if none then loop again(allows us to check for SIGTERM and SIGINT)
    {
      pthread_t thread;
      pthread_attr_t thread_attr;
      pthread_attr_init(&thread_attr);
      pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

      int retval;
      int fd=server.accept(&peer_address);
      info.new_fd=fd;
      info.peer_address=peer_address;
      info.connection_id=++nconns;
      pthread_mutex_lock(&info_stack_mutex);
      info_stack.push(info);
      pthread_mutex_unlock(&info_stack_mutex);
      retval=pthread_create(&thread,&thread_attr,thread_main,(void *)&info_stack);
      if(retval)
      {
        LERR(_("Error creating thread: ") + Utils::errnotostrerror(retval) + _(". Sleeping 5 seconds before continuing..."));
        sleep(5);
      }
      else
      {
        #ifdef WIN32
        LDEB("New thread created [" + Utils::ulongtostr(nconns) + "] thread_id: " + Utils::ulongtostr((unsigned long)thread.p) + ":" + Utils::ulongtostr(thread.x));
        #else
        LDEB("New thread created [" + Utils::ulongtostr(nconns) + "] thread_id: " + Utils::ulongtostr(thread));
        #endif //WIN32
        pthread_mutex_lock(&childrenlist_mutex);
        children.push_back(nconns);
        pthread_mutex_unlock(&childrenlist_mutex);
      }
    }
  }

  //close connection so that the port is no longer usable
  server.close();

  // wait for all threads to finish
  LINF("Waiting for threads to finish");
  #ifndef WIN32
  while(children.size())
  {
    if(false==cfg.getBackground())
    {
      cout << "Threads active:" << children.size() << (char)13;
      fflush(stdout);
    }
    sleep(1);
  }
  #endif //WIN32
  if(cfg.getCleanDb())
    pthread_join(cleaner_thread,NULL);

  #ifndef WIN32
  if(false==cfg.getBackground())
    cout << endl;
  #endif //WIN32

  #ifdef HAVE_SPF
  Spf::deinitialize();
  #endif //HAVE_SPF
  return 0;
}