int
query_classification_indexer(const void *vp)
{
    const dns_message *m = vp;
    int x;
    if ((x = malformed(m)))
        return x;
    if ((x = src_port_zero(m)))
        return x;
    if ((x = funny_qclass(m)))
        return x;
    if ((x = funny_qtype(m)))
        return x;
    if ((x = a_for_a(m)))
        return x;
    if ((x = a_for_root(m)))
        return x;
    if ((x = localhost(m)))
        return x;
    if ((x = root_servers_net(m)))
        return x;
    if ((x = nonauth_tld(m)))
        return x;
    if ((x = rfc1918_ptr(m)))
        return x;
    return CLASS_OK;
}
/**
 * Listening and handling incoming requests
 */
void HttpServer::listen()
{

    try
    {
        // Start server
        boost::asio::io_service io_service;
        tcp::endpoint localhost(tcp::v4(), this->port);
        tcp::acceptor acceptor(io_service, localhost);

        std::cout << "Server has started. Listening on address localhost:" << this->port 
            << " (that's 127.0.0.1:" << this->port << " for you Windows folks).\n\n"
            << "Now type this address into your browser." << std::endl;

        // Reply to incoming HTTP requests
        while (1)
        {
            boost::system::error_code error_code;
            
            // Accept connection
            tcp::socket socket(io_service);
            acceptor.accept(socket);

            // Send HTTP response
            std::string filepath = parse_request(socket, error_code);
            boost::asio::write(socket, boost::asio::buffer(build_response(filepath)), error_code);
        }
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }
}
예제 #3
0
/**
  * @brief Contact the service and perform a bi-directional update.
  */
void OpenNIC::connectToService()
{
	if ( !mLocalNet->isLive() )
	{
		mTcpSocket.close();
		QHostAddress localhost(QHostAddress::LocalHost);
		mTcpSocket.connectToHost(localhost,19803,QIODevice::ReadWrite);
	}
}
예제 #4
0
void tst_QUdpSocket::writeToNonExistingPeer_data()
{
    QTest::addColumn<QHostAddress>("peerAddress");
    QHostAddress localhost(QHostAddress::LocalHost);
    QHostAddress remote = QHostInfo::fromName(QtNetworkSettings::serverName()).addresses().first();

    // write (required to be connected)
    QTest::newRow("localhost") << localhost;
    QTest::newRow("remote") << remote;
}
예제 #5
0
파일: talkd.c 프로젝트: millken/zhuxianB30
void
talkd_init (void)
{
  openlog ("talkd", LOG_PID, LOG_FACILITY);
  hostname = localhost ();
  if (!hostname)
    {
      syslog (LOG_ERR, "can't determine my hostname: %m");
      exit (EXIT_FAILURE);
    }
}
예제 #6
0
int
main (int argc, char **argv)
{
  const char *p = localhost ();
  set_program_name (argv[0]);
  if (!p)
    return 1;

  printf ("localhost: %s\n", p);

  return 0;
}
예제 #7
0
void tst_QUdpSocket::writeDatagramToNonExistingPeer_data()
{
    QTest::addColumn<bool>("bind");
    QTest::addColumn<QHostAddress>("peerAddress");
    QHostAddress localhost(QHostAddress::LocalHost);
    QHostAddress remote = QHostInfo::fromName(QtNetworkSettings::serverName()).addresses().first();

    QTest::newRow("localhost-unbound") << false << localhost;
    QTest::newRow("localhost-bound") << true << localhost;

    QTest::newRow("remote-unbound") << false << remote;
    QTest::newRow("remote-bound") << true << remote;
}
예제 #8
0
int
main (int argc, char *argv[])
{
  int index;

  set_program_name (argv[0]);

  /* Parse command line */
  iu_argp_init ("rlogind", program_authors);
  argp_parse (&argp, argc, argv, 0, &index, NULL);

  openlog ("rlogind", LOG_PID | LOG_CONS, LOG_AUTH);
  argc -= index;
  if (argc > 0)
    {
      syslog (LOG_ERR, "%d extra arguments", argc);
      exit (1);
    }

  signal (SIGHUP, SIG_IGN);

  if (!local_domain_name)
    {
      char *p = localhost ();

      if (!p)
	{
	  syslog (LOG_ERR, "can't determine local hostname");
	  exit (1);
	}
      local_dot_count = 2;
      local_domain_name = topdomain (p, local_dot_count);
    }
  else
    {
      char *p;

      local_dot_count = 0;
      for (p = local_domain_name; *p; p++)
	if (*p == '.')
	  local_dot_count++;
    }

  if (mode == MODE_DAEMON)
    rlogin_daemon (maxchildren, port);
  else
    exit (rlogind_mainloop (fileno (stdin), fileno (stdout)));

  return 0;
}
예제 #9
0
int main(int argc, char* argv[])
{
  try
  {
    std::string localhost("192.170.10.100");
    std::string localport("30200");
    std::string remotehost("192.170.10.2");
    std::string remoteport("30200");
  
    std::cout << "argc: " << argc << "\n";
	  /// @todo add default localhost/localport
    if (argc !=5 && argc !=1)
    {
      std::cerr << "Usage: " << argv[0] << " <localip> <localport> <remoteip> <remoteport>\n";
      return 1;
    }
  
    if(argc ==5){
      localhost = std::string(argv[1]);
      localport = std::string(argv[2]);
      remotehost = std::string(argv[3]);
      remoteport = std::string(argv[4]);
    }
    
      std::cout << "using: "  << argv[0] << " " <<  localhost << " " << localport << " " <<  remotehost << " " << remoteport << "\n";

    boost::asio::io_service io_service;

    boost::asio::ip::udp::socket s(io_service, boost::asio::ip::udp::endpoint(boost::asio::ip::address::from_string(localhost), boost::lexical_cast<short>(localport)));

    boost::asio::ip::udp::resolver resolver(io_service);
    boost::asio::ip::udp::endpoint endpoint = *resolver.resolve({boost::asio::ip::udp::v4(), remotehost, remoteport});
	s.connect(endpoint);
	
    SocketTest socket_test(std::move(s));

    socket_test.async_receive(boost::system::error_code(),0,dummy(), []( boost::system::error_code ec, std::size_t bytes_transferred){
        // many cool things accomplished!
    },dummy());
  
    io_service.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}
예제 #10
0
파일: rpc.cpp 프로젝트: chaoaero/rDSN
TEST(core, rpc_perf_test)
{
    ::dsn::rpc_address localhost("localhost", 20101);

    ::dsn::rpc_read_stream response;
    std::mutex lock;
    for (auto concurrency : {10, 100, 1000, 10000})
    {
        std::atomic_int remain_concurrency;
        remain_concurrency = concurrency;
        size_t total_query_count = 1000000;
        std::chrono::steady_clock clock;
        auto tic = clock.now();
        for (auto remain_query_count = total_query_count; remain_query_count--;)
        {
            while(true)
            {
                if (remain_concurrency.fetch_sub(1, std::memory_order_relaxed) <= 0)
                {
                    remain_concurrency.fetch_add(1, std::memory_order_relaxed);
                }
                else
                {
                    break;
                }
            }
            ::dsn::rpc::call(
                localhost,
                RPC_TEST_HASH,
                0,
                nullptr,
                [&remain_concurrency](error_code ec, const std::string&)
                {
                    ec.end_tracking();
                    remain_concurrency.fetch_add(1, std::memory_order_relaxed);
                }
            );
        }
        while(remain_concurrency != concurrency)
        {
            ;
        }
        auto toc = clock.now();
        auto time_us = std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count();
        std::cout << "rpc perf test: concurrency = " << concurrency
            << " throughput = " << total_query_count * 1000000llu / time_us << "call/sec" << std::endl;
    }

}
예제 #11
0
 void testReservedCharsInParameters()
 {
    OsSysLog::add(FAC_SUPERVISOR, PRI_DEBUG, "AlarmServerTest::testReservedCharsInParameters");
    UtlString localhost("localhost");
    UtlString alarmId("PARAMETER_WITH_RESERVED_CHARS");
    UtlSList alarmParams;
    UtlString alarmParam("<sample>; \"x=y\"");
    alarmParams.append(&alarmParam);
    cAlarmServer::getInstance()->handleAlarm(localhost, alarmId, alarmParams);
    OsTask::delay(DELAY);
    UtlString actualString;
    UtlString expectedString = "Parameters may contain xml reserved characters e.g. '<sample>; \\\"x=y\\\"'";
    tail(mAlarmFile, actualString);
    char msg[1000];
    sprintf(msg, "incorrect message was logged: actualString '%s'  expected '%s'", actualString.data(), expectedString.data());
    CPPUNIT_ASSERT_MESSAGE(msg, actualString.contains(expectedString));
 }
예제 #12
0
파일: rpc.cpp 프로젝트: chaoaero/rDSN
TEST(core, rpc_perf_test_sync)
{
    ::dsn::rpc_address localhost("localhost", 20101);

    std::chrono::steady_clock clock;
    auto tic = clock.now();

    int round = 100000;
    int concurrency = 10;
    int total_query_count = round * concurrency;

    std::vector<task_ptr> tasks;
    for (int i = 0; i < round; i++)
    {
        for (int j = 0; j < concurrency; j++)
        {
            int req = 0;
            auto task = ::dsn::rpc::call(
                localhost,
                RPC_TEST_HASH,
                req,
                nullptr,
                [](error_code err, std::string&& result) 
                {
                    // nothing to do
                }
                );

            tasks.push_back(task);
        }

        for (auto& t : tasks)
            t->wait();

        tasks.clear();
    }

    auto toc = clock.now();
    auto time_us = std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count();
    std::cout << "rpc-sync perf test: throughput = " 
        << total_query_count * 1000000llu / time_us << " #/s, avg latency = "
        << time_us / total_query_count 
        << " us"<< std::endl;
}
예제 #13
0
 void testNewlinesInStrings()
 {
    OsSysLog::add(FAC_SUPERVISOR, PRI_DEBUG, "AlarmServerTest::testNewlinesInStrings");
    UtlString localhost("localhost");
    UtlString alarmId("MESSAGE_WITH_NEWLINES");
    UtlSList alarmParams;
    UtlString alarmParam("1");
    alarmParams.append(&alarmParam);
    UtlString alarmParam2 = "\nparam on new line";
    alarmParams.append(&alarmParam2);
    cAlarmServer::getInstance()->handleAlarm(localhost, alarmId, alarmParams);
    OsTask::delay(DELAY);
    UtlString actualString;
    UtlString expectedString = "param on new line";
    tail(mAlarmFile, actualString);
    char msg[1000];
    sprintf(msg, "incorrect message was logged: actualString '%s'  expected '%s'", actualString.data(), expectedString.data());
    CPPUNIT_ASSERT_MESSAGE(msg, actualString.contains(expectedString));
 }
예제 #14
0
 void testParameterSubstitution()
 {
    OsSysLog::add(FAC_SUPERVISOR, PRI_DEBUG, "AlarmServerTest::testParameterSubstitution");
    UtlString localhost("localhost");
    UtlString alarmId("PARAMETER_SUBSTITUTION");
    UtlSList alarmParams;
    UtlString alarmParam("1");
    alarmParams.append(&alarmParam);
    UtlString alarmParam2 = "2";
    alarmParams.append(&alarmParam2);
    cAlarmServer::getInstance()->handleAlarm(localhost, alarmId, alarmParams);
    OsTask::delay(DELAY);
    UtlString actualString;
    UtlString expectedString = "Parameter 2, then parameter 1";
    tail(mAlarmFile, actualString);
    char msg[1000];
    sprintf(msg, "incorrect message was logged: actualString '%s'  expected '%s'", actualString.data(), expectedString.data());
    CPPUNIT_ASSERT_MESSAGE(msg, actualString.contains(expectedString));
 }
예제 #15
0
/*
 * Determine the local and remote user, tty, and machines
 */
int
get_names (int argc, char *argv[])
{
  char *his_name, *my_name;
  char *my_machine_name, *his_machine_name;
  char *his_tty;
  register char *cp;

  if ((my_name = getlogin ()) == NULL)
    {
      struct passwd *pw;

      if ((pw = getpwuid (getuid ())) == NULL)
	{
	  printf ("You don't exist. Go away.\n");
	  exit (-1);
	}
      my_name = pw->pw_name;
    }

  my_machine_name = localhost ();
  if (!my_machine_name)
    {
      perror ("Cannot get local hostname");
      exit (-1);
    }

  /* check for, and strip out, the machine name of the target */
  for (cp = argv[0]; *cp && !strchr ("@:!.", *cp); cp++)
    ;
  if (*cp == '\0')
    {
      /* this is a local to local talk */
      his_name = argv[0];
      his_machine_name = my_machine_name;
    }
  else
    {
      if (*cp++ == '@')
	{
	  /* user@host */
	  his_name = argv[0];
	  his_machine_name = cp;
	}
      else
	{
	  /* host.user or host!user or host:user */
	  his_name = cp;
	  his_machine_name = argv[0];
	}
      *--cp = '\0';
    }
  if (argc > 1)
    his_tty = argv[1];		/* tty name is arg 2 */
  else
    his_tty = "";
  get_addrs (my_machine_name, his_machine_name);
  /*
   * Initialize the message template.
   */
  msg.vers = TALK_VERSION;
  msg.addr.sa_family = htons (AF_INET);
  msg.ctl_addr.sa_family = htons (AF_INET);
  msg.id_num = htonl (0);
  strncpy (msg.l_name, my_name, NAME_SIZE);
  msg.l_name[NAME_SIZE - 1] = '\0';
  strncpy (msg.r_name, his_name, NAME_SIZE);
  msg.r_name[NAME_SIZE - 1] = '\0';
  strncpy (msg.r_tty, his_tty, TTY_SIZE);
  msg.r_tty[TTY_SIZE - 1] = '\0';

  free (my_machine_name);

  return 0;
}
예제 #16
0
int main(int argc, char* argv[])
{
//  try
//  {

    std::string localhost("127.0.0.1");
    std::string localport("9998");
    std::string remotehost("127.0.0.1");
    std::string remoteport("9998");

    std::cout << "argc: " << argc << "\n";
    /// @todo add default localhost/localport
    if (argc != 5 && argc != 1 && argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " <localip> <localport> <remoteip> <remoteport>\n";
        return 1;
    }

    bool shouldReceive = true;

    if(argc == 3) {
        remotehost = std::string(argv[1]);
        remoteport = std::string(argv[2]);
        shouldReceive = false;
    }

    if(argc == 5) {
        localhost = std::string(argv[1]);
        localport = std::string(argv[2]);
        remotehost = std::string(argv[3]);
        remoteport = std::string(argv[4]);
        shouldReceive = true;
    }

    std::cout << "using: "  << argv[0] << " ";
    if(shouldReceive) std::cout <<  localhost << " " << localport << " ";
    std::cout <<  remotehost << " " << remoteport << "\n";
    boost::asio::io_service io_service;


    // Register signal handlers so that the daemon may be shut down when a signal is received.
    boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);
    signals.async_wait( std::bind(&boost::asio::io_service::stop, &io_service));
#if 0
    std::shared_ptr<AzmqFlatbuffer> sendP;
    {
        boost::system::error_code ec;
        azmq::socket socket(io_service, ZMQ_DEALER);
        socket.connect("tcp://"+ remotehost + ":" + remoteport);
        sendP = std::make_shared<AzmqFlatbuffer>(std::move(socket));
    }
    std::shared_ptr<AzmqFlatbuffer> receiveP;
    {
        boost::system::error_code ec;
        azmq::socket socket(io_service, ZMQ_DEALER);
        socket.bind("tcp://" + localhost + ":" + localport);
        receiveP = std::make_shared<AzmqFlatbuffer>(std::move(socket));
    }

    // Will run until signal is received, using separate objects for send and receive
    std::thread t(bounce,sendP,receiveP);
#else

    std::shared_ptr<AzmqFlatbuffer> receiveP;
    {
        boost::system::error_code ec;
        azmq::socket socket(io_service, ZMQ_DEALER);
        socket.bind("tcp://" + localhost + ":" + localport);
        socket.connect("tcp://"+ remotehost + ":" + remoteport);
        receiveP = std::make_shared<AzmqFlatbuffer>(std::move(socket));
    }

    // Will run until signal is received, using one object for both send and receive
    std::thread t(bounce,receiveP,receiveP,shouldReceive);
#endif

    io_service.run();

    t.join();

//  }
//  catch (std::exception& e)
//  {
//    std::cerr << "Exception: " << e.what() << "\n";
//  }

    return 0;
}
예제 #17
0
파일: supscan.c 프로젝트: ryo/netbsd-src
int
init(int argc, char **argv)
{
    char buf[STRINGLENGTH], fbuf[STRINGLENGTH], *p, *q;
    FILE *f;
    SCAN_COLLECTION **c;
    int fflag, sflag;
    char *filename = NULL;
    int errs = 0;

    quiet = FALSE;
    trace = FALSE;
    fflag = FALSE;
    sflag = FALSE;
    while (argc > 1 && argv[1][0] == '-') {
        switch (argv[1][1]) {
        case 'f':
            fflag = TRUE;
            if (argc == 2)
                usage();
            --argc;
            argv++;
            filename = argv[1];
            break;
        case 'q':
            quiet = TRUE;
            break;
        case 'v':
            trace = TRUE;
            break;
        case 's':
            sflag = TRUE;
            break;
        default:
            fprintf(stderr, "supscan: Invalid flag %s ignored\n",
                    argv[1]);
            (void) fflush(stderr);
        }
        --argc;
        argv++;
    }
    if (!fflag) {
        (void) sprintf(fbuf, FILEDIRS, DEFDIR);
        filename = fbuf;
    }
    if (sflag) {
        if (argc != 1)
            usage();
        firstC = NULL;
        c = &firstC;
        (void) sprintf(buf, FILEHOSTS, DEFDIR);
        if ((f = fopen(buf, "r")) == NULL)
            quit(1, "supscan: Unable to open %s\n", buf);
        while ((p = fgets(buf, STRINGLENGTH, f)) != NULL) {
            q = strchr(p, '\n');
            if (q)
                *q = 0;
            if (strchr("#;:", *p))
                continue;
            collname = nxtarg(&p, " \t=");
            p = skipover(p, " \t=");
            if (!localhost(p))
                continue;
            *c = getscancoll(filename, estrdup(collname), NULL);
            if (*c)
                c = &((*c)->Cnext);
            else
                errs++;
        }
        (void) fclose(f);
        return errs;
    }
    if (argc < 2 && fflag) {
        firstC = NULL;
        c = &firstC;
        if ((f = fopen(filename, "r")) == NULL)
            quit(1, "supscan: Unable to open %s\n", filename);
        while ((p = fgets(buf, STRINGLENGTH, f)) != NULL) {
            q = strchr(p, '\n');
            if (q)
                *q = 0;
            if (strchr("#;:", *p))
                continue;
            q = nxtarg(&p, " \t=");
            p = skipover(p, " \t=");
            *c = getscancoll(filename, estrdup(q), estrdup(p));
            if (*c)
                c = &((*c)->Cnext);
            else
                errs++;
        }
        (void) fclose(f);
        return errs;
    }
    if (argc < 2 || argc > 3)
        usage();
    firstC = getscancoll(filename, estrdup(argv[1]),
                         argc > 2 ? estrdup(argv[2]) : NULL);
    if (firstC == NULL)
        errs++;
    return errs;
}
예제 #18
0
   void testHandleAlarm()
   {
      OsSysLog::add(FAC_ALARM, PRI_DEBUG, "AlarmServerTest::testHandleAlarm");

      UtlString localhost("localhost");
      UtlString alarmId("NO_LOG");
      UtlString alarmParam("testing");
      UtlSList alarmParams;
      alarmParams.append(&alarmParam);
      UtlString oldLastString;
      tail(mAlarmFile, oldLastString);
      OsSysLog::add(FAC_ALARM, PRI_DEBUG, "oldLastString %s", oldLastString.data());
      bool rc=cAlarmServer::getInstance()->handleAlarm(localhost, alarmId, alarmParams);
      OsTask::delay(500);
      CPPUNIT_ASSERT_MESSAGE("handleAlarm('NO_LOG') failed", rc==true);
      UtlString newLastString;
      tail(mAlarmFile, newLastString);
      OsSysLog::add(FAC_ALARM, PRI_DEBUG, "newLastString %s", newLastString.data());
      CPPUNIT_ASSERT_MESSAGE("alarm with 'NO_LOG' was logged", !oldLastString.compareTo(newLastString));

      alarmId = "TEST_LOG";
      alarmParam = "single parameter";
      alarmParams.removeAll();
      alarmParams.append(&alarmParam);
      OsSysLog::add(FAC_ALARM, PRI_DEBUG, "Test TEST_LOG");
      cAlarmServer::getInstance()->handleAlarm(localhost, alarmId, alarmParams);
      OsTask::delay(DELAY);
      UtlString actualString;
      UtlString expectedString = "This is a test of the log function. Single parameter should be here: single parameter, and that's all that is required";
      tail(mAlarmFile, actualString);
      char msg[1000];
      sprintf(msg, "incorrect message was logged: actualString '%s'  expected '%s'", actualString.data(), expectedString.data());
      CPPUNIT_ASSERT_MESSAGE(msg, actualString.contains(expectedString));

      // test that non-existant alarm returns false
      alarmId = "NONEXISTANT_ID";
      rc=cAlarmServer::getInstance()->handleAlarm(localhost, alarmId, alarmParams);
      CPPUNIT_ASSERT_MESSAGE("handleAlarm('NONEXISTANT_ID') did not fail, and should have", rc!=true);

      // test that alarm with min_threshold is only logged after n attempts
      alarmId = "MIN_THRESHOLD";
      alarmParam = "one";
      alarmParams.removeAll();
      alarmParams.append(&alarmParam);
      tail(mAlarmFile, oldLastString);
      OsSysLog::add(FAC_ALARM, PRI_DEBUG, "oldLastString %s", oldLastString.data());
      cAlarmServer::getInstance()->handleAlarm(localhost, alarmId, alarmParams);
      OsTask::delay(DELAY);
      tail(mAlarmFile, newLastString);
      OsSysLog::add(FAC_ALARM, PRI_DEBUG, "newLastString %s", newLastString.data());
      CPPUNIT_ASSERT_MESSAGE("first instance of alarm with 'min_threshold' was logged", !oldLastString.compareTo(newLastString));
      alarmParam = "two";
      alarmParams.append(&alarmParam);
      cAlarmServer::getInstance()->handleAlarm(localhost, alarmId, alarmParams);
      OsTask::delay(DELAY);
      tail(mAlarmFile, actualString);
      expectedString = "This should only be logged the second time";
      sprintf(msg, "incorrect message was logged: actualString '%s'  expected '%s'", actualString.data(), expectedString.data());
      CPPUNIT_ASSERT_MESSAGE(msg, actualString.contains(expectedString));

   }
예제 #19
0
int
main (int argc, char *argv[], char **envp)
{
  int index;

  set_program_name (argv[0]);

#ifdef HAVE_TZSET
  tzset ();			/* In case no timezone database in ~ftp.  */
#endif

#ifdef HAVE_INITSETPROCTITLE
  /* Save start and extent of argv for setproctitle.  */
  initsetproctitle (argc, argv, envp);
#endif /* HAVE_INITSETPROCTITLE */

  /* Parse the command line */
  iu_argp_init ("ftpd", default_program_authors);
  argp_parse (&argp, argc, argv, 0, &index, NULL);
  
  /* Bail out, wrong usage */
  argc -= index;
  if (argc != 0)
    error (1, 0, "surplus arguments; try `%s --help' for more info",
	   program_name);

  /* LOG_NDELAY sets up the logging connection immediately,
     necessary for anonymous ftp's that chroot and can't do it later.  */
  openlog ("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
  freopen (PATH_DEVNULL, "w", stderr);

  /* If not running via inetd, we detach and dup(fd, 0), dup(fd, 1) the
     fd = accept(). tcpd is check if compile with the support  */
  if (daemon_mode)
    {
      if (server_mode (pid_file, &his_addr) < 0)
	exit (1);
    }
  else
    {
      socklen_t addrlen = sizeof (his_addr);
      if (getpeername (STDIN_FILENO, (struct sockaddr *) &his_addr,
		       &addrlen) < 0)
	{
	  syslog (LOG_ERR, "getpeername (%s): %m", program_name);
	  exit (1);
	}
    }

  signal (SIGHUP, sigquit);
  signal (SIGINT, sigquit);
  signal (SIGQUIT, sigquit);
  signal (SIGTERM, sigquit);
  signal (SIGPIPE, lostconn);
  signal (SIGCHLD, SIG_IGN);
  if (signal (SIGURG, myoob) == SIG_ERR)
    syslog (LOG_ERR, "signal: %m");

  /* Get info on the ctrl connection.  */
  {
    socklen_t addrlen = sizeof (ctrl_addr);
    if (getsockname (STDIN_FILENO, (struct sockaddr *) &ctrl_addr,
		     &addrlen) < 0)
      {
	syslog (LOG_ERR, "getsockname (%s): %m", program_name);
	exit (1);
      }
  }

#if defined (IP_TOS) && defined (IPTOS_LOWDELAY) && defined (IPPROTO_IP)
  /* To  minimize delays for interactive traffic.  */
  {
    int tos = IPTOS_LOWDELAY;
    if (setsockopt (STDIN_FILENO, IPPROTO_IP, IP_TOS,
		    (char *) &tos, sizeof (int)) < 0)
      syslog (LOG_WARNING, "setsockopt (IP_TOS): %m");
  }
#endif

#ifdef SO_OOBINLINE
  /* Try to handle urgent data inline.  */
  {
    int on = 1;
    if (setsockopt (STDIN_FILENO, SOL_SOCKET, SO_OOBINLINE,
		    (char *) &on, sizeof (on)) < 0)
      syslog (LOG_ERR, "setsockopt: %m");
  }
#endif

#ifdef SO_KEEPALIVE
  /* Set keepalives on the socket to detect dropped connections.  */
  {
    int keepalive = 1;
    if (setsockopt (STDIN_FILENO, SOL_SOCKET, SO_KEEPALIVE,
		    (char *) &keepalive, sizeof (keepalive)) < 0)
      syslog (LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
  }
#endif

#ifdef	F_SETOWN
  if (fcntl (STDIN_FILENO, F_SETOWN, getpid ()) == -1)
    syslog (LOG_ERR, "fcntl F_SETOWN: %m");
#endif

  dolog (&his_addr, &cred);

  /* Deal with login disable.  */
  if (display_file (PATH_NOLOGIN, 530) == 0)
    {
      reply (530, "System not available.");
      exit (0);
    }

  /* Display a Welcome message if exists,
     N.B. reply(220,) must follow.  */
  display_file (PATH_FTPWELCOME, 220);

  hostname = localhost ();
  if (!hostname)
    perror_reply (550, "Local resource failure: malloc");

  /* Tell them we're ready to roll.  */
  if (!no_version)
    reply (220, "%s FTP server (%s %s) ready.",
	   hostname, PACKAGE_NAME, PACKAGE_VERSION);
  else
    reply (220, "%s FTP server ready.", hostname);

  /* Set the jump, if we have an error parsing,
     come here and start fresh.  */
  setjmp (errcatch);

  /* Roll.  */
  for (;;)
    yyparse ();
}
예제 #20
0
void
Association
::associate(Network & network)
{
    if(!network.is_initialized())
    {
        throw Exception("Network is not initialized");
    }

    if(this->is_associated())
    {
        throw Exception("Already associated");
    }

    OFCondition condition;

    T_ASC_Parameters * params;
    condition = ASC_createAssociationParameters(&params, ASC_MAXIMUMPDUSIZE);
    if(condition.bad())
    {
        throw Exception(condition);
    }

    condition = ASC_setAPTitles(params,
        this->_own_ae_title.c_str(), this->_peer_ae_title.c_str(), NULL);
    if(condition.bad())
    {
        ASC_destroyAssociationParameters(&params);
        throw Exception(condition);
    }

    std::string localhost(128, '\0');
    gethostname(&localhost[0], localhost.size()-1);

    std::ostringstream peer;
    peer << this->_peer_host_name << ":" << this->_peer_port;

    condition = ASC_setPresentationAddresses(params,
        "localhost", peer.str().c_str());
    if(condition.bad())
    {
        ASC_destroyAssociationParameters(&params);
        throw Exception(condition);
    }

    unsigned int context_id = 1;
    for(auto const & context: this->_presentation_contexts)
    {
        char const ** transfer_syntaxes = new char const *[context.transfer_syntaxes.size()];
        for(std::size_t i = 0; i < context.transfer_syntaxes.size(); ++i)
        {
            transfer_syntaxes[i] = context.transfer_syntaxes[i].c_str();
        }

        condition = ASC_addPresentationContext(params,
            context_id, context.abstract_syntax.c_str(),
            transfer_syntaxes, context.transfer_syntaxes.size(), context.role);
        if(condition.bad())
        {
            ASC_destroyAssociationParameters(&params);
            throw Exception(condition);
        }

        context_id += 2;
    }

    if(this->_user_identity_type == UserIdentityType::None)
    {
        // Nothing to do.
    }
    else if(this->_user_identity_type == UserIdentityType::Username)
    {
        condition = ASC_setIdentRQUserOnly(params,
            this->_user_identity_primary_field.c_str());
    }
    else if(this->_user_identity_type == UserIdentityType::UsernameAndPassword)
    {
        condition = ASC_setIdentRQUserOnly(params,
            this->_user_identity_primary_field.c_str(),
            this->_user_identity_secondary_field.c_str());
    }
    else if(this->_user_identity_type == UserIdentityType::Kerberos)
    {
        condition = ASC_setIdentRQKerberos(params,
            this->_user_identity_primary_field.c_str(),
            this->_user_identity_primary_field.size());
    }
    else if(this->_user_identity_type == UserIdentityType::SAML)
    {
        condition = ASC_setIdentRQSaml(params,
            this->_user_identity_primary_field.c_str(),
            this->_user_identity_primary_field.size());
    }
    else
    {
        ASC_destroyAssociationParameters(&params);
        throw Exception("Unknown identity type");
    }

    if(condition.bad())
    {
        ASC_destroyAssociationParameters(&params);
        throw Exception(condition);
    }

    condition = ASC_requestAssociation(
        network.get_network(), params, &this->_association);
    if(condition.bad())
    {
        OFString empty;

        if(condition == DUL_ASSOCIATIONREJECTED)
        {
            T_ASC_RejectParameters rej;
            ASC_getRejectParameters(params, &rej);

            ASC_destroyAssociationParameters(&params);
            throw Exception(ASC_printRejectParameters(empty, &rej).c_str());
        }
        else
        {
            ASC_destroyAssociationParameters(&params);
            throw Exception(DimseCondition::dump(empty, condition).c_str());
        }
    }
}
예제 #21
0
int main(int argc, char** argv) {
	if (argc != 2 || strlen(argv[1]) != 7) {
		printf("USAGE %s 7-char-LOCATION\n", argv[0]);
		return -1;
	}
	location = argv[1];

	int blockonly_fd, txes_fd, new_fd;
	struct sockaddr_in6 addr;

	fd_set twofds;
	FD_ZERO(&twofds);

	if ((blockonly_fd = socket(AF_INET6, SOCK_STREAM, 0)) < 0 ||
		     (txes_fd = socket(AF_INET6, SOCK_STREAM, 0)) < 0) {
		printf("Failed to create socket\n");
		return -1;
	}

	memset(&addr, 0, sizeof(addr));
	addr.sin6_family = AF_INET6;
	addr.sin6_addr = in6addr_any;
	addr.sin6_port = htons(8334);

	int reuse = 1;

	if (setsockopt(blockonly_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) ||
			bind(blockonly_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0 ||
			listen(blockonly_fd, 3) < 0) {
		printf("Failed to bind 8334: %s\n", strerror(errno));
		return -1;
	}

	addr.sin6_port = htons(8335);
	if (setsockopt(txes_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) ||
			bind(txes_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0 ||
			listen(txes_fd, 3) < 0) {
		printf("Failed to bind 8335: %s\n", strerror(errno));
		return -1;
	}

	std::mutex list_mutex;
	std::set<P2PConnection*> blockSet;
	std::set<P2PConnection*> txesSet;
	std::set<P2PConnection*> localSet;

	std::function<void (P2PConnection*, std::shared_ptr<std::vector<unsigned char> >&, struct timeval)> relayBlock =
		[&](P2PConnection* from, std::shared_ptr<std::vector<unsigned char>> & bytes, struct timeval start_recv) {
			struct timeval start_send, finish_send;
			gettimeofday(&start_send, NULL);

			if (bytes->size() < 80)
				return;
			std::vector<unsigned char> fullhash(32);
			getblockhash(fullhash, *bytes, sizeof(struct bitcoin_msg_header));

			{
				std::lock_guard<std::mutex> lock(list_mutex);
				std::set<P2PConnection*> *set;
				if (localSet.count(from))
					set = &blockSet;
				else
					set = &localSet;
				for (auto it = set->begin(); it != set->end(); it++) {
					if (!(*it)->getDisconnectFlags())
						(*it)->receive_block(fullhash, bytes);
				}
			}

			gettimeofday(&finish_send, NULL);
			for (unsigned int i = 0; i < fullhash.size(); i++)
				printf("%02x", fullhash[fullhash.size() - i - 1]);
			printf(" BLOCK %lu %s %s %u / %u TIMES: %ld %ld\n", uint64_t(start_send.tv_sec) * 1000 + uint64_t(start_send.tv_usec) / 1000, from->host.c_str(),
					localSet.count(from) ? "LOCALRELAY" : "REMOTEP2P", (unsigned)bytes->size(), (unsigned)bytes->size(),
					int64_t(start_send.tv_sec - start_recv.tv_sec)*1000 + (int64_t(start_send.tv_usec) - start_recv.tv_usec)/1000,
					int64_t(finish_send.tv_sec - start_send.tv_sec)*1000 + (int64_t(finish_send.tv_usec) - start_send.tv_usec)/1000);
		};
	std::function<void (P2PConnection*, std::shared_ptr<std::vector<unsigned char> >&)> relayTx =
		[&](P2PConnection* from, std::shared_ptr<std::vector<unsigned char> >& bytes) {
			std::vector<unsigned char> fullhash(32);
			double_sha256(&(*bytes)[sizeof(struct bitcoin_msg_header)], &fullhash[0], bytes->size() - sizeof(struct bitcoin_msg_header));

			std::lock_guard<std::mutex> lock(list_mutex);
			std::set<P2PConnection*> *set;
			if (localSet.count(from))
				set = &txesSet;
			else
				set = &localSet;
			for (auto it = set->begin(); it != set->end(); it++) {
				if (!(*it)->getDisconnectFlags())
					(*it)->receive_transaction(fullhash, bytes);
			}
		};

	printf("Awaiting connections\n");

	while (true) {
		FD_SET(blockonly_fd, &twofds);
		FD_SET(txes_fd, &twofds);
		struct timeval timeout;
		timeout.tv_sec = 30;
		timeout.tv_usec = 0;

		if (select(FD_SETSIZE, &twofds, NULL, NULL, &timeout) < 0) {
			printf("Failed to select (%s)\n", strerror(errno));
			return -1;
		}

		socklen_t addr_size = sizeof(addr);
		std::string localhost("::ffff:127.0.0.1/");
		std::string droppostfix(".uptimerobot.com");
		if (FD_ISSET(blockonly_fd, &twofds)) {
			if ((new_fd = accept(blockonly_fd, (struct sockaddr *) &addr, &addr_size)) < 0) {
				printf("Failed to accept\n");
				return -1;
			}

			std::string host = gethostname(&addr);
			if (host.length() > droppostfix.length() && !host.compare(host.length() - droppostfix.length(), droppostfix.length(), droppostfix))
				close(new_fd);
			else {
				std::lock_guard<std::mutex> lock(list_mutex);
				P2PConnection *relay = new P2PConnection(new_fd, host, relayBlock, relayTx);
				if (!host.compare(0, localhost.size(), localhost))
					localSet.insert(relay);
				else
					blockSet.insert(relay);
			}
		}
		if (FD_ISSET(txes_fd, &twofds)) {
			if ((new_fd = accept(txes_fd, (struct sockaddr *) &addr, &addr_size)) < 0) {
				printf("Failed to accept\n");
				return -1;
			}

			std::string host = gethostname(&addr);
			if (host.length() > droppostfix.length() && !host.compare(host.length() - droppostfix.length(), droppostfix.length(), droppostfix))
				close(new_fd);
			else {
				std::lock_guard<std::mutex> lock(list_mutex);
				P2PConnection *relay = new P2PConnection(new_fd, host, relayBlock, relayTx);
				if (!host.compare(0, localhost.size(), localhost))
					localSet.insert(relay);
				else {
					blockSet.insert(relay);
					txesSet.insert(relay);
				}
			}
		}

		std::lock_guard<std::mutex> lock(list_mutex);
		for (auto it = blockSet.begin(); it != blockSet.end();) {
			if ((*it)->getDisconnectFlags() & DISCONNECT_COMPLETE) {
				auto rm = it++; auto item = *rm;
				txesSet.erase(item);
				blockSet.erase(rm);
				delete item;
			} else
				it++;
		}
		for (auto it = localSet.begin(); it != localSet.end();) {
			if ((*it)->getDisconnectFlags() & DISCONNECT_COMPLETE) {
				auto rm = it++; auto item = *rm;
				localSet.erase(rm);
				delete item;
			} else
				it++;
		}
		fprintf(stderr, "Have %lu local connection(s), %lu block connection(s) and %lu txes conenction(s)\n", localSet.size(), blockSet.size() - txesSet.size(), txesSet.size());
	}
}
예제 #22
0
int
remote_userpass (char *host, char **aname, char **apass, char **aacct)
{
    char *hdir, buf[BUFSIZ], *tmp;
    char *myname, *mydomain;
    int t, c, usedefault = 0;
    size_t i;
    struct stat stb;

    hdir = getenv ("HOME");
    if (hdir == NULL)
        hdir = ".";
    snprintf (buf, sizeof buf, "%s/.netrc", hdir);

    /* The switch `-N/--netrc' would have set this.  */
    if (!netrc)
        netrc = getenv ("NETRC");

    if (netrc && netrc[0])
        snprintf (buf, sizeof buf, "%s", netrc);

    cfile = fopen (buf, "r");
    if (cfile == NULL)
    {
        if (errno != ENOENT)
            error (0, errno, "%s", buf);
        return (0);
    }

    /* The .netrc is now opened and is thus fixed.
     * Check that it is a regular file, and not a
     * soft link in particular.
     */
    if (lstat (buf, &stb) < 0)
    {
        error (0, errno, "%s", buf);
        fclose (cfile);
        return (-1);
    }

    if (!S_ISREG (stb.st_mode))
    {
        if (S_ISLNK (stb.st_mode))
            error (0, 0, "the .netrc file is symbolic link: %s", buf);
        else
            error (0, 0, "the .netrc file is no regular file: %s", buf);

        fclose (cfile);
        return (-1);
    }

    myname = localhost ();
    if (!myname)
        myname = xstrdup ("");

    mydomain = strchr (myname, '.');
    if (mydomain == NULL)
        mydomain = "";

next:
    while ((t = token ()))
        switch (t)
        {
        case DEFAULT:
            usedefault = 1;
        /* FALL THROUGH */

        case MACHINE:
            if (!usedefault)
            {
                if (token () != ID)
                    continue;
                /*
                 * Allow match either for user's input host name
                 * or official hostname.  Also allow match of
                 * incompletely-specified host in local domain.  */
                if (strcasecmp (host, tokval) == 0)
                    goto match;
                if (strcasecmp (hostname, tokval) == 0)
                    goto match;
                tmp = strchr (hostname, '.');
                if (tmp != NULL
                        && strcasecmp (tmp, mydomain) == 0
                        && strncasecmp (hostname, tokval, tmp - hostname) == 0
                        && tokval[tmp - hostname] == '\0')
                    goto match;
                tmp = strchr (host, '.');
                if (tmp != NULL
                        && strcasecmp (tmp, mydomain) == 0
                        && strncasecmp (host, tokval, tmp - host) == 0
                        && tokval[tmp - host] == '\0')
                    goto match;
                continue;
            }
match:
            while ((t = token ()) && t != MACHINE && t != DEFAULT)
                switch (t)
                {
                case LOGIN:
                    if (token ())
                    {
                        if (*aname == 0)
                        {
                            *aname = xmalloc ((unsigned) strlen (tokval) + 1);
                            strcpy (*aname, tokval);
                        }
                        else
                        {
                            if (strcmp (*aname, tokval))
                                goto next;
                        }
                    }
                    break;
                case PASSWD:
                    if ((*aname == NULL || strcmp (*aname, "anonymous"))
                            && fstat (fileno (cfile), &stb) >= 0
                            && (stb.st_mode & 077) != 0)
                    {
                        error (0, 0, "Error: .netrc file is readable by others.");
                        error (0, 0,
                               "Remove password or make file unreadable by others.");
                        goto bad;
                    }
                    if (token () && *apass == 0)
                    {
                        *apass = xmalloc ((unsigned) strlen (tokval) + 1);
                        strcpy (*apass, tokval);
                    }
                    break;
                case ACCOUNT:
                    if (fstat (fileno (cfile), &stb) >= 0
                            && (stb.st_mode & 077) != 0)
                    {
                        error (0, 0, "Error: .netrc file is readable by others.");
                        error (0, 0,
                               "Remove account or make file unreadable by others.");
                        goto bad;
                    }
                    if (token () && *aacct == 0)
                    {
                        *aacct = xmalloc ((unsigned) strlen (tokval) + 1);
                        strcpy (*aacct, tokval);
                    }
                    break;
                case MACDEF:
                    if (proxy)
                        goto done;

                    while (((c = getc (cfile)) != EOF && c == ' ') || c == '\t')
                        ;
                    if (c == EOF || c == '\n')
                    {
                        printf ("Missing macdef name argument.\n");
                        goto bad;
                    }
                    if (macnum == 16)
                    {
                        printf ("Limit of 16 macros have already been defined\n");
                        goto bad;
                    }
                    tmp = macros[macnum].mac_name;
                    *tmp++ = c;
                    for (i = 0; i < (sizeof (macros[macnum].mac_name) - 1)
                            && (c = getc (cfile)) != EOF && !isspace (c);
                            ++i)
                    {
                        *tmp++ = c;
                    }
                    if (c == EOF)
                    {
                        printf ("Macro definition missing null line terminator.\n");
                        goto bad;
                    }
                    *tmp = '\0';
                    if (c != '\n')
                    {
                        while ((c = getc (cfile)) != EOF && c != '\n');
                    }
                    if (c == EOF)
                    {
                        printf ("Macro definition missing null line terminator.\n");
                        goto bad;
                    }
                    if (macnum == 0)
                    {
                        macros[macnum].mac_start = macbuf;
                    }
                    else
                    {
                        macros[macnum].mac_start = macros[macnum - 1].mac_end + 1;
                    }
                    tmp = macros[macnum].mac_start;
                    while (tmp < macbuf + sizeof (macbuf))
                    {
                        if ((c = getc (cfile)) == EOF)
                        {
                            printf
                            ("Macro definition missing null line terminator.\n");
                            goto bad;
                        }
                        *tmp = c;
                        if (*tmp == '\n')
                        {
                            if (*(tmp - 1) == '\0')
                            {
                                macros[macnum++].mac_end = tmp - 1;
                                break;
                            }
                            *tmp = '\0';
                        }
                        tmp++;
                    }
                    if (tmp == macbuf + sizeof (macbuf))
                    {
                        printf ("4K macro buffer exceeded\n");
                        goto bad;
                    }
                    break;
                default:
                    error (0, 0, "Unknown .netrc keyword %s", tokval);
                    break;
                }
            goto done;
        }
done:
    fclose (cfile);
    free (myname);
    return (0);
bad:
    fclose (cfile);
    free (myname);
    return (-1);
}