Exemple #1
0
/**
 *  @todo Add command-line parameters for IPv4 network address and mask so we 
 *        can remove broadcast and multicast hosts from the result
 */
void IPForensics::load_hosts(std::string filename) {
  // open the filename
  char error[PCAP_ERRBUF_SIZE] {};
  pcap_t* pcap = pcap_open_offline(filename.c_str(), error);
  if (pcap == NULL) {
    throw std::runtime_error(error);
  }
  // exit if the data link is not Ethernet
  if (pcap_datalink(pcap) != DLT_EN10MB) {
    pcap_close(pcap);
    throw std::runtime_error("Link-layer type not IEEE 802.3 Ethernet");
  }
  // read the packets from the file
  const unsigned char * packet = NULL;
  struct pcap_pkthdr header;
  // if packet_count_ is set, read specified number of packets only
  if (packet_count_ > 0) {
    for (int i = 0; i < packet_count_; ++i) {
      packet = pcap_next(pcap, &header);
      if (packet != NULL) {
        packets_.push_back(Packet(packet));
      }
    }
  } else {
    // if packet_count_ is not set, read all packets
    packet = pcap_next(pcap, &header);
    while (packet != NULL) {
      packets_.push_back(Packet(packet));
      packet = pcap_next(pcap, &header);
    }
  }
  // close the packet capture
  pcap_close(pcap);
  // extract hosts from packets
  for (Packet p : packets_) {
    // add the source host
    std::set<Host>::iterator it = hosts_.find(static_cast<Host>(p.mac_src()));
    if (it == hosts_.end()) {
      add_host(p.mac_src(), p.ipv4_src(), p.ipv6_src());
    } else {
      update_host(it, p.ipv4_src(), p.ipv6_src());
    }
    // add the destination host
    it = hosts_.find(static_cast<Host>(p.mac_dst()));
    if (it == hosts_.end()) {
      add_host(p.mac_dst(), p.ipv4_dst(), p.ipv6_dst());
    } else {
      update_host(it, p.ipv4_dst(), p.ipv6_dst());
    }
  }
  // remove meaningless hosts
  clean_hosts(nullptr, nullptr);
}
Exemple #2
0
/*
  setup_table -- initialize the table of hosts allowed to contact the server,
                 by reading from the file specified by the GNU_SECURE
		 environment variable
                 Put in the local machine, and, if a security file is specifed,
                 add each host that is named in the file.
		 Return the number of hosts added.
*/
static int
setup_table (void)
{
  FILE *host_file;
  char *file_name;
  char hostname[HOSTNAMSZ];
  unsigned int host_addr;
  int i, hosts=0;

  /* Make sure every entry is null */
  for (i=0; i<TABLE_SIZE; i++)
    permitted_hosts[i] = NULL;

  gethostname(hostname,HOSTNAMSZ);

  if ((host_addr = internet_addr (hostname)) == (unsigned int) -1)
    {
      fprintf(stderr,"%s: unable to find %s in /etc/hosts or from YP",
	      progname,hostname);
      exit(1);
    } /* if */

#ifdef AUTH_MAGIC_COOKIE

  server_xauth = XauGetAuthByAddr (FamilyInternet,
				   sizeof(host_addr), (char *)&host_addr,
				   strlen(MCOOKIE_SCREEN), MCOOKIE_SCREEN,
				   strlen(MCOOKIE_X_NAME), MCOOKIE_X_NAME);
  hosts++;

#endif /* AUTH_MAGIC_COOKIE */


#if 0 /* Don't even want to allow access from the local host by default */
  add_host(host_addr);					/* add local host */
#endif

  if (((file_name = getenv("GNU_SECURE")) != NULL &&    /* security file  */
       (host_file = fopen(file_name,"r")) != NULL))	/* opened ok */
    {
      while ((fscanf(host_file,"%s",hostname) != EOF))	/* find a host */
	if ((host_addr = internet_addr(hostname)) != (unsigned int) -1)
	  /* get its addr */
	  {
	    add_host(host_addr);			/* add the addr */
	    hosts++;
	  }
      fclose(host_file);
    } /* if */

  return hosts;
} /* setup_table */
Exemple #3
0
void
add_hosts(Vector<SimpleCpcClient*> & hosts, BaseString list){
  Vector<BaseString> split;
  list.split(split);
  for(size_t i = 0; i<split.size(); i++){
    add_host(hosts, split[i]);
  }
}
Exemple #4
0
void Session::on_event(const SessionEvent& event) {
  switch (event.type) {
    case SessionEvent::CONNECT: {
      int port = config_.port();

      const Config::ContactPointList& contact_points = config_.contact_points();
      for (Config::ContactPointList::const_iterator it = contact_points.begin(),
                                                    end = contact_points.end();
           it != end; ++it) {
        const std::string& seed = *it;
        Address address;
        if (Address::from_string(seed, port, &address)) {
          add_host(address);
        } else {
          pending_resolve_count_++;
          Resolver::resolve(loop(), seed, port, this, on_resolve);
        }
      }

      if (pending_resolve_count_ == 0) {
        internal_connect();
      }

      break;
    }

    case SessionEvent::NOTIFY_READY:
      if (pending_pool_count_ > 0) {
        if (--pending_pool_count_ == 0) {
          LOG_DEBUG("Session is connected");
          notify_connected();
        }
        LOG_DEBUG("Session pending pool count %d", pending_pool_count_);
      }
      break;

    case SessionEvent::NOTIFY_WORKER_CLOSED:
      if (--pending_workers_count_ == 0) {
        LOG_DEBUG("Session is disconnected");
        control_connection_.close();
        close_handles();
      }
      break;

    case SessionEvent::NOTIFY_UP:
      control_connection_.on_up(event.address);
      break;

    case SessionEvent::NOTIFY_DOWN:
      control_connection_.on_down(event.address);
      break;

    default:
      assert(false);
      break;
  }
}
Exemple #5
0
int ldap_add_machine_account(const char *ldap_host, 
			     const char *hostname, const char *realm)
{
	LDAP *ld;
	int ldap_port = LDAP_PORT;
	char *bind_path;
	int rc;
	LDAPMessage *res;
	void *sasl_defaults;
	int version = LDAP_VERSION3;

	bind_path = build_dn(realm);

	printf("Creating host account for %s@%s\n", hostname, realm);

	ld = ldap_open(ldap_host, ldap_port);
	ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version);

	rc = ldap_sasl_interactive_bind_s(ld, NULL, NULL, NULL, NULL, 0,
					  sasl_interact, NULL);

	if (rc != LDAP_SUCCESS) {
		ldap_perror(ld, "ldap_bind");
		goto failed;
	}

	rc = find_host(ld, &res, bind_path, hostname);
	if (rc == LDAP_SUCCESS && ldap_count_entries(ld, res) == 1) {
		printf("Host account for %s already exists\n", hostname);
		goto finished;
	}

	rc = add_host(ld, bind_path, hostname, realm);
	if (rc != LDAP_SUCCESS) {
		ldap_perror(ld, "add_host");
		goto failed;
	}

	rc = find_host(ld, &res, bind_path, hostname);
	if (rc != LDAP_SUCCESS || ldap_count_entries(ld, res) != 1) {
		ldap_perror(ld, "find_host test");
		goto failed;
	}

	printf("Successfully added machine account for %s\n", hostname);

finished:	
	free(bind_path);
	return 0;

failed:
	printf("ldap_add_machine_account failed\n");
	free(bind_path);
	ldap_unbind(ld);
	return 1;
}
void DCAwarePolicy::PerDCHostMap::add_host_to_dc(const std::string& dc, const SharedRefPtr<Host>& host) {
  ScopedWriteLock wl(&rwlock_);
  Map::iterator i = map_.find(dc);
  if (i == map_.end()) {
    CopyOnWriteHostVec hosts(new HostVec());
    hosts->push_back(host);
    map_.insert(Map::value_type(dc, hosts));
  } else {
    add_host(i->second, host);
  }
}
Exemple #7
0
/**
 *  @details Iterates through all the packets in the supplied Device and loads
 *           the source host and destination host from each packet.  If a host
 *           detected from the packets already exists in the collection, the
 *           host is updated with any new information from the packet (the IPv4
 *           or IPv6 address if not previously found).
 */
void IPForensics::load_hosts(Device device) {
  for (Packet packet : device.packets()) {
    // add the source host
    auto it = hosts_.find(static_cast<Host>(packet.mac_src()));
    if (it == hosts_.end()) {
      add_host(packet.mac_src(), packet.ipv4_src(), packet.ipv6_src());
    } else {
      update_host(it, packet.ipv4_src(), packet.ipv6_src());
    }
    // add the destination host
    it = hosts_.find(static_cast<Host>(packet.mac_dst()));
    if (it == hosts_.end()) {
      add_host(packet.mac_dst(), packet.ipv4_dst(), packet.ipv6_dst());
    } else {
      update_host(it, packet.ipv4_dst(), packet.ipv6_dst());
    }
  }
  // remove multicast and broadcast hosts
  IPv4Address net = device.net(), mask = device.mask();
  clean_hosts(&net, &mask);
}
Exemple #8
0
/** Display dialog to get connection info from user. */
void Add::operator()(const com_ptr<IDataObject>&, const com_ptr<IBindCtx>&)
const
{
    host_info info = add_host(m_hwnd);

    if (ConnectionExists(info.name))
        BOOST_THROW_EXCEPTION(com_error(E_FAIL));

    AddConnectionToRegistry(
        info.name, info.host, info.port, info.user, info.path);

    notify_shell(m_folder_pidl);
}
Exemple #9
0
void recv_add_host(void)
{
    char name[MAXNAME];

    int n = recv_value();
    int x = recv_value();
    int y = recv_value();
    int w = recv_value();
    int h = recv_value();

    recv_array(name, n, 1);

    add_host(name, x, y, w, h);
}
Exemple #10
0
unsigned int send_add_host(const char *name, int x, int y, int w, int h)
{
    int n = strlen(name) + 1;

    send_event(EVENT_ADD_HOST);
    send_value(n);
    send_value(x);
    send_value(y);
    send_value(w);
    send_value(h);
    send_array(name, n, 1);

    return add_host(name, x, y, w, h);
}
Exemple #11
0
Dispatcher::Dispatcher(char *port, char *settings_file) {
    this->port = port;
    cluster_nodes = new std::vector<struct Host*>;

    std::ifstream settingsFile(settings_file);
    if (!settingsFile.is_open()) {
        log_err("Could not find settings file.");
        throw "Could not find settings file.";
    }
    
    Json::Reader r = Json::Reader();
    Json::Value v;
    debug("Parse settings");
    if (!r.parse(settingsFile, v, false)) {
        log_err("Could not parse settings file! No valid JSON.");
        throw "Could not parse settings file! No valid JSON.";
    }

    Json::Value jsonHosts = v.get("hosts", "");

    for (auto host: jsonHosts) {
        std::string url = host.get("url", "").asString();
        int port = host.get("port", "0").asInt();
        if (url != "" and port != 0) {
            const char *url_c = url.c_str();
            add_host(url_c, port);
        }
    }

    if (cluster_nodes->size() == 0) {
        debug("Settings file does not contain any valid hosts.");
    }

    thread_pool_size = v.get("threads", 1).asInt();

    std::string dispatch_algorithm = v.get("algorithm", "RoundRobin").asString();

    if (dispatch_algorithm == "Stream") {
        distributor = new StreamDistributor(cluster_nodes);
        debug("Used dispatching algorithm: Stream");
    } else {
        //SimpleRoundRobinDipatcher is the standard algorithm
        distributor = new RoundRobinDistributor(cluster_nodes);
        debug("Used dispatching algorithm: RoundRobin");
    }
}
Exemple #12
0
static void read_hosts(char *fname)
{
	FILE *fp;
	char buf[512], ip[512], host[512];
	int skip, n;

	fp = fopen(fname, "r");
	if (!fp) return;
	while (fgets(buf, sizeof(buf), fp)) {
		if (strchr(buf, '#')) continue;
		skip = read_thing(buf, ip);
		if (!strlen(ip)) continue;
		while ((n = read_thing(buf+skip, host))) {
			skip += n;
			if (strlen(host)) add_host(host, ip);
		}
	}
	fclose(fp);
}
void
redirect( uint64_t datapath_id, uint16_t in_port, const buffer *data ) {
  debug( "A message received (dpid = %#" PRIx64 ", in_port = %u, length = %zu).",
         datapath_id, in_port, data->length );

  packet_info packet_info = get_packet_info( data );
  if ( !packet_type_ipv4( data ) ) {
    debug( "Cannot redirect the packet which is not IPv4." );
    return;
  }

  uint8_t *mac = packet_info.eth_macsa;
  uint32_t ip = packet_info.ipv4_saddr;
  add_host( mac, ip, datapath_id, in_port );

  debug( "Redirecting an IP packet to tun interface." );
  assert( packet_info.l3_header != NULL );
  // redirect an IP packet to a tun interface
  send_packet_to_tun( packet_info.l3_header,
                      packet_info.ipv4_tot_len );
}
Exemple #14
0
JNIEXPORT void JNICALL
Java_com_sun_netstorage_samqfs_mgmt_fs_Host_addToConfig(JNIEnv *env,
    jclass cls /*ARGSUSED*/, jobject ctx, jstring fsName, jobject hostInfo) {

	jboolean isCopy; /* used by string macros */
	char *fstr = GET_STR(fsName, isCopy);
	host_info_t *host;

	PTRACE(1, "jni:Host_addToConfig entry");
	PTRACE(1, "jni:Adding to fs[%s]", Str(fstr));

	host = (host_info_t *)Host2host(env, hostInfo);

	if (-1 == add_host(CTX, fstr, host)) {
		REL_STR(fsName, fstr, isCopy);
		ThrowEx(env);
		return;
	}

	REL_STR(fsName, fstr, isCopy);
	free_host_info(host);

	PTRACE(1, "jni:Host_addToConfig() done");
}
Exemple #15
0
int main(int argc, char *argv[])
{
	dnsa_comm_line_s *cm;
	dnsa_config_s *dc;
	char *domain = NULL;
	int retval;

	cm = cmdb_malloc(sizeof(dnsa_comm_line_s), "cm in main");
	dnsa_init_comm_line_struct(cm);
	if ((retval = parse_dnsa_command_line(argc, argv, cm)) != 0) {
		cmdb_free(cm, sizeof(dnsa_comm_line_s));
		display_command_line_error(retval, argv[0]);
	}
	dc = cmdb_malloc(sizeof(dnsa_config_s), "dc in main");
	dnsa_init_config_values(dc);
	if ((retval = parse_dnsa_config_file(dc, cm->config)) != 0) {
		parse_dnsa_config_error(retval);
		goto cleanup;
	}
	domain = cmdb_malloc(CONF_S, "domain in main");
	if (!(strncpy(domain, cm->domain, CONF_S - 1)))
		goto cleanup;
	if (cm->type == FORWARD_ZONE) {
		if (cm->action == LIST_ZONES) {
			list_zones(dc);
			retval = 0;
		} else if (cm->action == DISPLAY_ZONE) {
			display_zone(domain, dc);
			retval = 0;
		} else if (cm->action == COMMIT_ZONES) {
			retval = commit_fwd_zones(dc, domain);
		} else if (cm->action == ADD_HOST) {
			retval = add_host(dc, cm);
		} else if (cm->action == ADD_ZONE) {
			retval = add_fwd_zone(dc, cm);
		} else if (cm->action == DELETE_RECORD) {
			retval = delete_record(dc, cm);
		} else if (cm->action == DELETE_ZONE) {
			retval = delete_fwd_zone(dc, cm);
		} else if (cm->action == ADD_CNAME_ON_ROOT) {
			retval = add_cname_to_root_domain(dc, cm);
		} else {
			printf("Action code %d not implemented\n", cm->action);
		}
	} else if (cm->type == REVERSE_ZONE) {
		if (cm->action == LIST_ZONES) {
			list_rev_zones(dc);
			retval = 0;
		} else if (cm->action == DISPLAY_ZONE) {
			display_rev_zone(domain, dc);
			retval = 0;
		} else if (cm->action == COMMIT_ZONES) {
			retval = commit_rev_zones(dc, domain);
		} else if (cm->action == ADD_ZONE) {
			retval = add_rev_zone(dc, cm);
		} else if (cm->action == MULTIPLE_A) {
			retval = display_multi_a_records(dc, cm);
		} else if (cm->action == ADD_PREFER_A) {
			retval = mark_preferred_a_record(dc, cm);
		} else if (cm->action == BUILD_REV) {
			retval = build_reverse_zone(dc, cm);
		} else if (cm->action == DELETE_PREFERRED) {
			retval = delete_preferred_a(dc, cm);
		} else if (cm->action == DELETE_ZONE) {
			retval = delete_reverse_zone(dc, cm);
		} else {
			printf("Action code %d not implemented\n", cm->action);
		}
	} else if (cm->type == GLUE_ZONE) {
		if (cm->action == ADD_ZONE)
			retval = add_glue_zone(dc, cm);
		else if (cm->action == LIST_ZONES)
			list_glue_zones(dc);
		else if (cm->action == DELETE_ZONE)
			delete_glue_zone(dc, cm);
		else
			printf("Action code %d not implemented\n", cm->action);
	}

	cleanup:
		if (domain)
			cmdb_free(domain, CONF_S);
		cmdb_free(cm, sizeof(dnsa_comm_line_s));
		cmdb_free(dc, sizeof(dnsa_config_s));
		exit(retval);
}
Exemple #16
0
void MainWindow::slotReconnect()
{
  char buf[MAX_PRINTF_LENGTH],host[MAX_PRINTF_LENGTH],sshstring[MAX_PRINTF_LENGTH],*cptr;
  QString qbuf;
  int iport,i,ssh,max,maxtab;

  if(opt.arg_debug)
  {
    printf("slotReconnect url=%s current=%s isReconnect=%d\n",
           (const char *) url.toUtf8(),
           (const char *) pvbtab[currentTab].url.toUtf8(),
           isReconnect);
  }         
  if(isReconnect == 1) url = pvbtab[currentTab].url;
  else                 pvbtab[currentTab].url = url;
  pvbtab[currentTab].manual_url = "index.html";
  ssh = 0;
  sshstring[0] = '\0';
  url.truncate(sizeof(buf) - 80);
  strcpy(buf,url.toUtf8());
  // eleminate spaces
  for(i=0; buf[i] != '\0'; i++)
  {
    if(buf[i] == ' ' || buf[i] == '\t')
    {
      buf[i] = '\0';
      break;
    }
  }

  if(strncmp(buf,"http://",7) == 0 || strncmp(buf,"https://",8) == 0 || strncmp(buf,"file://",7) == 0) 
  {
    if(pvbtab[currentTab].s != -1) 
    {
      tcp_close(&pvbtab[currentTab].s);
      pvbtab[currentTab].s = -1;
    }  
    pvbtab[currentTab].interpreter.showMyBrowser(buf);
    add_host(buf);
    return;
  }

  do // eliminate windows slosh'es
  {
    cptr = strchr(buf,'\\');
    if(cptr != NULL) *cptr = '/';
  }
  while(cptr != NULL);
  if(buf[strlen(buf)-1] == '/') buf[strlen(buf)-1] = '\0';

  if     (strncmp(buf,"ssh://",6) == 0 || strncmp(buf,"pvssh://",8) == 0)
  {
    char ssh_user_host[MAX_PRINTF_LENGTH];
    char ssh_host[MAX_PRINTF_LENGTH];
    int  ssh_port;
    ssh = 1;
    strcpy(sshstring,buf);
    sprintf(host,"localhost:%d",opt.sshport); // we connect locally
    strcpy(ssh_host,"localhost");
    ssh_port = opt.port;
    cptr = &buf[6]; 
    if(buf[0] == 'p') cptr = &buf[8];
    i = 0;
    while(*cptr != ':' && *cptr != '\0') ssh_user_host[i++] = *cptr++;
    ssh_user_host[i] = '\0';
    if(*cptr == ':')
    {
      cptr++;
      if(isalpha(*cptr) || strchr(cptr,'.') != NULL)
      {
        i = 0;
        while(*cptr != ':' && *cptr != '\0') ssh_host[i++] = *cptr++;
        ssh_host[i] = '\0';
        cptr++;
      }
      if(*cptr != '\0') sscanf(cptr,"%d",&ssh_port);  
    }
    if(isReconnect == 0)
    {
      isReconnect = 1;
      QString qbuf;
#ifdef PVUNIX    
      qbuf.sprintf("xterm -e %s -L %d:%s:%d %s &",opt.ssh,opt.sshport,ssh_host,ssh_port,ssh_user_host);
#endif
#ifdef PVWIN32
      qbuf.sprintf("%s -ssh -L %d:%s:%d %s",opt.ssh,opt.sshport,ssh_host,ssh_port,ssh_user_host);
#endif
      if(opt.arg_debug) printf("mysystem(%s)\n",(const char *) qbuf.toUtf8());
      mysystem(qbuf.toUtf8());
    }
  }
  else if(strncmp(buf,"pv://"  ,5) == 0) 
  {
    strcpy(host,&buf[5]);
  }  
  else
  {
    strcpy(host,buf);
  }  

  if(host[0] == '\0') return;

  if(pvbtab[currentTab].s != -1) 
  {
    tcp_close(&pvbtab[currentTab].s);
    pvbtab[currentTab].s = -1;
  }  
  strcpy(buf,host);
  iport = opt.port;
  if(buf[0] == '[')
  { // plain IPV6 address as number
    strcpy(buf,&host[1]);
    cptr = strchr(buf,']');
    if(cptr != NULL)
    {
      *cptr = '\0';
      cptr++;
      if(*cptr == ':') // port is given
      {
        cptr++;
        sscanf(cptr,"%d",&iport);
      }
    }
  }
  else
  {
    cptr = strchr(buf,':'); // if special port is given
    if(cptr != NULL)
    {
      *cptr++ = '\0';
      sscanf(cptr,"%d",&iport);
    }
  }
  cptr = strstr(buf,"/");
  if(cptr != NULL) *cptr = '\0';
  QApplication::setOverrideCursor( Qt::WaitCursor );
  pvbtab[currentTab].s = tcp_con(buf,iport);
  if(pvbtab[currentTab].s > 0)
  {
    pvbtab[currentTab].in_use = 1;
  }  
  max = maxtab= 0;
  for(i=0; i<MAX_TABS; i++)
  {
    if(pvbtab[i].s > max) max = pvbtab[i].s;
    if(pvbtab[i].in_use)  maxtab = i;
  }
  maxfd = max;
  numTabs = maxtab+1;
  if(opt.arg_debug) printf("slotReconnect tcp_con s=%d host=%s:%d maxfd=%d\n",pvbtab[currentTab].s,buf,iport,maxfd);
  QApplication::restoreOverrideCursor();

  cptr = strstr(host,"/"); // send initial mask
  if(cptr == NULL)
  {
    sprintf(buf,"initial(0,\"\") version=%s",VERSION);
#ifdef PVWIN32  
    strcat(buf, " Windows");
#endif
#ifdef PVUNIX
    strcat(buf, " Unix");
#ifdef PVMAC
    strcat(buf, " OS-X");
#elif defined(USE_ANDROID)
    strcat(buf, " Android");
#elif defined(USE_MAEMO)
    strcat(buf, " Maemo");
#elif defined(USE_SYMBIAN)
    strcat(buf, " Symbian");
#endif
#endif
    QRect maxrect = QApplication::desktop()->availableGeometry();
    char tempbuf[1024];
    sprintf(tempbuf," (%dx%d)", maxrect.width(), maxrect.height());
    strcat(buf, tempbuf);
    strcat(buf, "\n");
    tcp_send(&pvbtab[currentTab].s,buf,strlen(buf));
  }
  else
  {
    cptr++;
    sprintf(buf,"initial(0,\"%s\") version=%s\n",cptr,VERSION);
    tcp_send(&pvbtab[currentTab].s,buf,strlen(buf));
  }

  // send initial url
  sprintf(buf,"@url=%s\n", (const char *) url.toUtf8());
  tcp_send(&pvbtab[currentTab].s,buf,strlen(buf));

  if(pvbtab[currentTab].s != -1)
  {
    if(ssh == 0)
    {
      qbuf  = l_status_connected;
      qbuf += " ";
      qbuf += host;
    }
    else if(ssh == 1)
    {
      qbuf  = l_status_connected;
      qbuf += " ";
      qbuf += sshstring;
    }
    QPalette palette;
    statusBar()->setPalette(palette);
    statusBar()->showMessage(qbuf);
    if     (ssh == 0) add_host(host);
    else if(ssh == 1) add_host(sshstring);
  }
  else
  {
    if(ssh == 0)
    {
      qbuf  = l_status_could_not_connect;
      qbuf += " ";
      qbuf += host;
    }
    else if(ssh == 1)
    {
      qbuf  = l_status_could_not_connect;
      qbuf += " ";
      qbuf += sshstring;
    }
    QPalette palette(QColor(255,0,0));
    statusBar()->setPalette(palette);
    //rlehrig statusBar()->setPaletteBackgroundColor(QColor(255,0,0));
    statusBar()->showMessage(qbuf);
    qApp->beep();
  }
  isReconnect = 1;
}
Exemple #17
0
MainWindow::MainWindow()
{
  const char *cptr;
  int i;

#ifdef BROWSERPLUGIN
  pvbinit();
#endif

  isReconnect = 0;
#ifndef NO_WEBKIT  
  textbrowser = NULL;
#endif  
  tabToolBar  = NULL;
  maxfd = currentTab = numTabs = 0;
  for(i=0; i<MAX_TABS; i++)
  {
    pvbtab[i].s          = -1;        // socket
    pvbtab[i].in_use     = 0;         // tab is currently not used
    pvbtab[i].w          = 1280;      // default width
    pvbtab[i].h          = 1024;      // default height
    pvbtab[i].pvsVersion = 0x0040600; // last version of pvserver that does not send version
    pvbtab[i].rootWidget = NULL;
    pvbtab[i].hasLayout  = 0;
    for(int ii=0; ii<MAX_DOCK_WIDGETS; ii++) 
    {
      pvbtab[i].dock[ii] = NULL;
    }  
  }

  cptr = readIniFile();
  if(cptr != NULL)
  {
    QMessageBox::warning(NULL,"MainWindow","readIniFile ERROR: terminating ...");
    printf("readIniFile ERROR=%s\n",cptr);
    exit(-1);
  }
  if(opt.appfontsize > 0) // intoduced june 2012 for android application font setting
  {
    //QFont f = qApp->font();
    //f.setPointSize(opt.appfontsize);
    //qApp->setFont(f);
    QFont f = QApplication::font();
    f.setPointSize(opt.appfontsize);
    QApplication::setFont(f);
  }

  createActions();
  createToolBars();
  createMenus();
  createStatusBar();
  if(opt.menubar   == 0) menuBar()->hide();
  if(opt.toolbar   == 0) fileToolBar->hide();
  if(opt.statusbar == 0) statusBar()->hide();
  tcp_init();

  setCurrentFile("");
  readHosts();

  semaphore.release();
  mythread.pv = this;
  // slow_start_on_windows mythread.start();
  // there is a problem within the firefox plugin on windows
  // we do not get enough CPU time there
  // no problem on linux
  // we get more CPU time if we continiously move the mouse over the widget
  // problem not solved jet
#ifdef BROWSERPLUGIN
  mythread.start(QThread::HighestPriority); // this does not help also
#endif

  // setup watchdog
  timer = new QTimer();
  QObject::connect(timer, SIGNAL(timeout()), this, SLOT(slotTimeOut()));
  // moved timer start to end of this method  because show may need longer on mobile devices  timer->start(1000*10);

  if(opt.arg_host[0] != '\0') url = opt.arg_host;
  else                        url = opt.initialhost;
  add_host(url.toUtf8());

  if(opt.arg_x != -1 && opt.arg_y != -1 && opt.arg_w != -1 && opt.arg_h != -1)
  {
    setGeometry(opt.arg_x,opt.arg_y, opt.arg_w,opt.arg_h);
  }
  else if(opt.fullscreen)
  {
    showFullScreen();
  }
  else if(opt.maximized)
  {
    showMaximized();
  }
  else
  {
    resize(800,600);
  }

  if(opt.cursor_shape >= 0)
  {
    QApplication::restoreOverrideCursor();
    QApplication::setOverrideCursor(QCursor((Qt::CursorShape) opt.cursor_shape));
  }  

// delay textbrowser for speedup starting on windows  
// loading the help file is damn slow on windows
// thus we delay this operation until help is really needed
//QMessageBox::information(this,"pvbrowser","step begin",1);
//  textbrowser = new dlgTextBrowser;
//QMessageBox::information(this,"pvbrowser","step end",1);
  setFocus(Qt::MouseFocusReason);
#ifdef BROWSERPLUGIN
  QApplication::setActiveWindow(this); // now we will get keyboard events
#endif
  busyWidget = new QPushButton(this);
  busyWidget->setIcon(QIcon(":images/app.png"));
  busyWidgetTimer = new QTimer(this);
  busyWidgetTimer->setSingleShot(true);
  connect(busyWidgetTimer,SIGNAL(timeout()),this,SLOT(slotBusyWidgetTimeout()));
  timer->start(1000*10);
}
Exemple #18
0
void Session::on_event(const SessionEvent& event) {
  switch (event.type) {
    case SessionEvent::CONNECT: {
      int port = config_.port();

      const ContactPointList& contact_points = config_.contact_points();
      for (ContactPointList::const_iterator it = contact_points.begin(),
                                                    end = contact_points.end();
           it != end; ++it) {
        const std::string& seed = *it;
        Address address;
        if (Address::from_string(seed, port, &address)) {
          add_host(address);
        } else {
          pending_resolve_count_++;
          Resolver::resolve(loop(), seed, port, this, on_resolve);
        }
      }

      if (pending_resolve_count_ == 0) {
        internal_connect();
      }

      break;
    }

    case SessionEvent::NOTIFY_READY:
      if (pending_pool_count_ > 0) {
        if (--pending_pool_count_ == 0) {
          LOG_DEBUG("Session is connected");
          notify_connected();
        }
        LOG_DEBUG("Session pending pool count %d", pending_pool_count_);
      }
      break;

    case SessionEvent::NOTIFY_KEYSPACE_ERROR: {
      // Currently, this is only called when the keyspace does not exist
      // and not for any other keyspace related errors.
      const CopyOnWritePtr<std::string> keyspace(keyspace_);
      notify_connect_error(CASS_ERROR_LIB_UNABLE_TO_SET_KEYSPACE,
                           "Keyspace '" + *keyspace + "' does not exist");
      break;
    }

    case SessionEvent::NOTIFY_WORKER_CLOSED:
      if (--pending_workers_count_ == 0) {
        LOG_DEBUG("Session is disconnected");
        control_connection_.close();
        close_handles();
      }
      break;

    case SessionEvent::NOTIFY_UP:
      control_connection_.on_up(event.address);
      break;

    case SessionEvent::NOTIFY_DOWN:
      control_connection_.on_down(event.address);
      break;

    default:
      assert(false);
      break;
  }
}
Exemple #19
0
/* Map the host name NAME to the actual to be used host name.  This
   allows us to manage round robin DNS names.  We use our own strategy
   to choose one of the hosts.  For example we skip those hosts which
   failed for some time and we stick to one host for a time
   independent of DNS retry times.  If FORCE_RESELECT is true a new
   host is always selected.  The selected host is stored as a malloced
   string at R_HOST; on error NULL is stored.  If we know the port
   used by the selected host, a string representation is written to
   R_PORTSTR, otherwise it is left untouched.  If R_HTTPFLAGS is not
   NULL it will receive flags which are to be passed to http_open.  If
   R_POOLNAME is not NULL a malloced name of the pool is stored or
   NULL if it is not a pool. */
static gpg_error_t
map_host (ctrl_t ctrl, const char *name, int force_reselect,
          char **r_host, char *r_portstr,
          unsigned int *r_httpflags, char **r_poolname)
{
  gpg_error_t err = 0;
  hostinfo_t hi;
  int idx;

  *r_host = NULL;
  if (r_httpflags)
    *r_httpflags = 0;
  if (r_poolname)
    *r_poolname = NULL;

  /* No hostname means localhost.  */
  if (!name || !*name)
    {
      *r_host = xtrystrdup ("localhost");
      return *r_host? 0 : gpg_error_from_syserror ();
    }

  /* See whether the host is in our table.  */
  idx = find_hostinfo (name);
  if (idx == -1 && is_onion_address (name))
    {
      idx = create_new_hostinfo (name);
      if (idx == -1)
        return gpg_error_from_syserror ();
      hi = hosttable[idx];
      hi->onion = 1;
    }
  else if (idx == -1)
    {
      /* We never saw this host.  Allocate a new entry.  */
      dns_addrinfo_t aibuf, ai;
      int *reftbl;
      size_t reftblsize;
      int refidx;
      int is_pool = 0;
      char *cname;
#ifdef	USE_DNS_SRV
      char *srvrecord;
      struct srventry *srvs;
      int srvscount;
#endif	/* USE_DNS_SRV */

      reftblsize = 100;
      reftbl = xtrymalloc (reftblsize * sizeof *reftbl);
      if (!reftbl)
        return gpg_error_from_syserror ();
      refidx = 0;

      idx = create_new_hostinfo (name);
      if (idx == -1)
        {
          err = gpg_error_from_syserror ();
          xfree (reftbl);
          return err;
        }
      hi = hosttable[idx];

#ifdef	USE_DNS_SRV
      /* Check for SRV records.  */
      srvrecord = xtryasprintf ("_hkp._tcp.%s", name);
      if (srvrecord == NULL)
        {
          err = gpg_error_from_syserror ();
          xfree (reftbl);
          return err;
        }

      srvscount = getsrv (srvrecord, &srvs);
      xfree (srvrecord);
      if (srvscount < 0)
        {
          err = gpg_error_from_syserror ();
          xfree (reftbl);
          return err;
        }

      if (srvscount > 0)
        {
          int i;
          is_pool = srvscount > 1;

          for (i = 0; i < srvscount; i++)
            {
              err = resolve_dns_name (srvs[i].target, 0,
                                      AF_UNSPEC, SOCK_STREAM,
                                      &ai, &cname);
              if (err)
                continue;
              dirmngr_tick (ctrl);
              add_host (name, is_pool, ai, srvs[i].port,
                        reftbl, reftblsize, &refidx);
            }

          xfree (srvs);
        }
#endif	/* USE_DNS_SRV */

      /* Find all A records for this entry and put them into the pool
         list - if any.  */
      err = resolve_dns_name (name, 0, 0, SOCK_STREAM, &aibuf, &cname);
      if (err)
        {
          log_error ("resolving '%s' failed: %s\n", name, gpg_strerror (err));
          err = 0;
        }
      else
        {
          /* First figure out whether this is a pool.  For a pool we
             use a different strategy than for a plain server: We use
             the canonical name of the pool as the virtual host along
             with the IP addresses.  If it is not a pool, we use the
             specified name. */
          if (! is_pool)
            is_pool = arecords_is_pool (aibuf);
          if (is_pool && cname)
            {
              hi->cname = cname;
              cname = NULL;
            }

          for (ai = aibuf; ai; ai = ai->next)
            {
              if (ai->family != AF_INET && ai->family != AF_INET6)
                continue;
              dirmngr_tick (ctrl);

              add_host (name, is_pool, ai, 0, reftbl, reftblsize, &refidx);
            }
        }
      reftbl[refidx] = -1;
      xfree (cname);
      free_dns_addrinfo (aibuf);

      if (refidx && is_pool)
        {
          assert (!hi->pool);
          hi->pool = xtryrealloc (reftbl, (refidx+1) * sizeof *reftbl);
          if (!hi->pool)
            {
              err = gpg_error_from_syserror ();
              log_error ("shrinking index table in map_host failed: %s\n",
                         gpg_strerror (err));
              xfree (reftbl);
              return err;
            }
          qsort (hi->pool, refidx, sizeof *reftbl, sort_hostpool);
        }
      else
        xfree (reftbl);
    }

  hi = hosttable[idx];
  if (hi->pool)
    {
      /* Deal with the pool name before selecting a host. */
      if (r_poolname)
        {
          *r_poolname = xtrystrdup (hi->cname? hi->cname : hi->name);
          if (!*r_poolname)
            return gpg_error_from_syserror ();
        }

      /* If the currently selected host is now marked dead, force a
         re-selection .  */
      if (force_reselect)
        hi->poolidx = -1;
      else if (hi->poolidx >= 0 && hi->poolidx < hosttable_size
               && hosttable[hi->poolidx] && hosttable[hi->poolidx]->dead)
        hi->poolidx = -1;

      /* Select a host if needed.  */
      if (hi->poolidx == -1)
        {
          hi->poolidx = select_random_host (hi->pool);
          if (hi->poolidx == -1)
            {
              log_error ("no alive host found in pool '%s'\n", name);
              if (r_poolname)
                {
                  xfree (*r_poolname);
                  *r_poolname = NULL;
                }
              return gpg_error (GPG_ERR_NO_KEYSERVER);
            }
        }

      assert (hi->poolidx >= 0 && hi->poolidx < hosttable_size);
      hi = hosttable[hi->poolidx];
      assert (hi);
    }

  if (hi->dead)
    {
      log_error ("host '%s' marked as dead\n", hi->name);
      if (r_poolname)
        {
          xfree (*r_poolname);
          *r_poolname = NULL;
        }
      return gpg_error (GPG_ERR_NO_KEYSERVER);
    }

  if (r_httpflags)
    {
      /* If the hosttable does not indicate that a certain host
         supports IPv<N>, we explicit set the corresponding http
         flags.  The reason for this is that a host might be listed in
         a pool as not v6 only but actually support v6 when later
         the name is resolved by our http layer.  */
      if (!hi->v4)
        *r_httpflags |= HTTP_FLAG_IGNORE_IPv4;
      if (!hi->v6)
        *r_httpflags |= HTTP_FLAG_IGNORE_IPv6;

      /* Note that we do not set the HTTP_FLAG_FORCE_TOR for onion
         addresses because the http module detects this itself.  This
         also allows us to use an onion address without Tor mode being
         enabled.  */
    }

  *r_host = xtrystrdup (hi->name);
  if (!*r_host)
    {
      err = gpg_error_from_syserror ();
      if (r_poolname)
        {
          xfree (*r_poolname);
          *r_poolname = NULL;
        }
      return err;
    }
  if (hi->port)
    snprintf (r_portstr, 6 /* five digits and the sentinel */,
              "%hu", hi->port);
  return 0;
}
Exemple #20
0
void LatencyAwarePolicy::on_add(const Host::Ptr& host) {
  host->enable_latency_tracking(settings_.scale_ns, settings_.min_measured);
  add_host(hosts_, host);
  ChainedLoadBalancingPolicy::on_add(host);
}
Exemple #21
0
void LatencyAwarePolicy::on_up(const Host::Ptr& host) {
  add_host(hosts_, host);
  ChainedLoadBalancingPolicy::on_up(host);
}
Exemple #22
0
void sync_display(void)
{
#ifdef CONF_MPI
    MPI_Status stat;
    int        size = 0;
#endif
    int        rank = 0;

    char name[MAXNAME];
    int  i = 0;

    gethostname(name, MAXNAME);

#ifdef CONF_MPI

    assert_mpi(MPI_Comm_rank(MPI_COMM_WORLD, &rank));
    assert_mpi(MPI_Comm_size(MPI_COMM_WORLD, &size));

    if (rank)
    {
        /* Send the name to the root, recieve the host index. */

        MPI_Send(name, MAXNAME, MPI_BYTE, 0,0, MPI_COMM_WORLD);
        MPI_Recv(&i,   4,       MPI_BYTE, 0,0, MPI_COMM_WORLD, &stat);
    }
    else
    {
        int j, k;

        /* Find a host definition for the root. */

        i = find_display(name);

        /* Recieve a name from each client, send a host definition index. */

        for (j = 1; j < size; ++j)
        {
            MPI_Recv(name, MAXNAME, MPI_BYTE, j,0, MPI_COMM_WORLD, &stat);
            k = find_display(name);
            MPI_Send(&k,   4,       MPI_BYTE, j,0, MPI_COMM_WORLD);
        }
    }
#else

    i = find_display(name);

#endif

    /* If no host definition was found, create a default. */

    if (i == 0)
    {
        i = add_host(DEFAULT_NAME, DEFAULT_X, DEFAULT_Y, DEFAULT_W, DEFAULT_H);
            add_tile(i,            DEFAULT_X, DEFAULT_Y, DEFAULT_W, DEFAULT_H);

        host[i].flags = HOST_FRAMED;
    }

    /* Note the indexed host definition as current. */

    current_host = host[i];

    /* Position the server window, if necessary. */

    if (rank || (current_host.flags & HOST_FRAMED) == 0)
        set_window_pos(current_host.win_x, current_host.win_y);
}
Exemple #23
0
int main(int argc, char **argv)
{
    int c;

    myname = argv[0];

    memset(host_array, 0, sizeof(host_array));

	while ((c = getopt(argc, argv, "hf:t:p:")) != -1) {
		switch (c) {
			case 'f':
				filename = optarg;
				break;
			case 'p':
				dest_port = atoi(optarg);
				break;
			case 'h':
                usage();
				break;
			case 't':
				timeout = atoi(optarg);
				break;
			default:
				usage();
		}
	}


    argc -= optind;
	argv += optind;

    if ( (*argv && filename) || (!*argv && !filename) )
    {
        usage();
    }
    if( *argv )
    {
        while( *argv )
        {
            add_host( *argv );
            ++argv;
        }
    }else if( filename )
    {
        FILE *ping_file;
        char line[132];
        char host[132];

        ping_file = fopen( filename, "r" );

        if( !ping_file )
        {
            perror("-f");
            exit(1);
        }

        while( fgets( line, sizeof(line), ping_file ) )
        {
            if( sscanf( line, "%s", host ) != 1 )
                continue;

            if( ( !*host ) || ( host[0] == '#' ) )  /* magic to avoid comments */
                continue;

            add_host(host);
        }/* WHILE */

        fclose( ping_file );
    }
    else
    {
        usage();
    }


    if ( !host_num )
    {
        exit(1);
    }

    tcpconn();

    return 0;    
}
Exemple #24
0
/* Map the host name NAME to the actual to be used host name.  This
 * allows us to manage round robin DNS names.  We use our own strategy
 * to choose one of the hosts.  For example we skip those hosts which
 * failed for some time and we stick to one host for a time
 * independent of DNS retry times.  If FORCE_RESELECT is true a new
 * host is always selected.  If SRVTAG is NULL no service record
 * lookup will be done, if it is set that service name is used.  The
 * selected host is stored as a malloced string at R_HOST; on error
 * NULL is stored.  If we know the port used by the selected host from
 * a service record, a string representation is written to R_PORTSTR,
 * otherwise it is left untouched.  If R_HTTPFLAGS is not NULL it will
 * receive flags which are to be passed to http_open.  If R_HTTPHOST
 * is not NULL a malloced name of the host is stored there; this might
 * be different from R_HOST in case it has been selected from a
 * pool.  */
static gpg_error_t
map_host (ctrl_t ctrl, const char *name, const char *srvtag, int force_reselect,
          enum ks_protocol protocol, char **r_host, char *r_portstr,
          unsigned int *r_httpflags, char **r_httphost)
{
  gpg_error_t err = 0;
  hostinfo_t hi;
  int idx;
  dns_addrinfo_t aibuf, ai;
  int is_pool;
  int new_hosts = 0;
  char *cname;

  *r_host = NULL;
  if (r_httpflags)
    *r_httpflags = 0;
  if (r_httphost)
    *r_httphost = NULL;

  /* No hostname means localhost.  */
  if (!name || !*name)
    {
      *r_host = xtrystrdup ("localhost");
      return *r_host? 0 : gpg_error_from_syserror ();
    }

  /* See whether the host is in our table.  */
  idx = find_hostinfo (name);
  if (idx == -1)
    {
      idx = create_new_hostinfo (name);
      if (idx == -1)
        return gpg_error_from_syserror ();
      hi = hosttable[idx];
      hi->onion = is_onion_address (name);
    }
  else
    hi = hosttable[idx];

  is_pool = hi->pool != NULL;

  if (srvtag && !is_ip_address (name)
      && ! hi->onion
      && ! (hi->did_srv_lookup & 1 << protocol))
    {
      struct srventry *srvs;
      unsigned int srvscount;

      /* Check for SRV records.  */
      err = get_dns_srv (name, srvtag, NULL, &srvs, &srvscount);
      if (err)
        {
          if (gpg_err_code (err) == GPG_ERR_ECONNREFUSED)
            tor_not_running_p (ctrl);
          return err;
        }

      if (srvscount > 0)
        {
          int i;
          if (! is_pool)
            is_pool = srvscount > 1;

          for (i = 0; i < srvscount; i++)
            {
              err = resolve_dns_name (srvs[i].target, 0,
                                      AF_UNSPEC, SOCK_STREAM,
                                      &ai, &cname);
              if (err)
                continue;
              dirmngr_tick (ctrl);
              add_host (name, is_pool, ai, protocol, srvs[i].port);
              new_hosts = 1;
            }

          xfree (srvs);
        }

      hi->did_srv_lookup |= 1 << protocol;
    }

  if (! hi->did_a_lookup
      && ! hi->onion)
    {
      /* Find all A records for this entry and put them into the pool
         list - if any.  */
      err = resolve_dns_name (name, 0, 0, SOCK_STREAM, &aibuf, &cname);
      if (err)
        {
          log_error ("resolving '%s' failed: %s\n", name, gpg_strerror (err));
          err = 0;
        }
      else
        {
          /* First figure out whether this is a pool.  For a pool we
             use a different strategy than for a plain server: We use
             the canonical name of the pool as the virtual host along
             with the IP addresses.  If it is not a pool, we use the
             specified name. */
          if (! is_pool)
            is_pool = arecords_is_pool (aibuf);
          if (is_pool && cname)
            {
              hi->cname = cname;
              cname = NULL;
            }

          for (ai = aibuf; ai; ai = ai->next)
            {
              if (ai->family != AF_INET && ai->family != AF_INET6)
                continue;
              if (opt.disable_ipv4 && ai->family == AF_INET)
                continue;
              if (opt.disable_ipv6 && ai->family == AF_INET6)
                continue;
              dirmngr_tick (ctrl);

              add_host (name, is_pool, ai, 0, 0);
              new_hosts = 1;
            }

          hi->did_a_lookup = 1;
        }
      xfree (cname);
      free_dns_addrinfo (aibuf);
    }
  if (new_hosts)
    hostinfo_sort_pool (hi);

  if (hi->pool)
    {
      /* Deal with the pool name before selecting a host. */
      if (r_httphost)
        {
          *r_httphost = xtrystrdup (hi->cname? hi->cname : hi->name);
          if (!*r_httphost)
            return gpg_error_from_syserror ();
        }

      /* If the currently selected host is now marked dead, force a
         re-selection .  */
      if (force_reselect)
        hi->poolidx = -1;
      else if (hi->poolidx >= 0 && hi->poolidx < hosttable_size
               && hosttable[hi->poolidx] && hosttable[hi->poolidx]->dead)
        hi->poolidx = -1;

      /* Select a host if needed.  */
      if (hi->poolidx == -1)
        {
          hi->poolidx = select_random_host (hi);
          if (hi->poolidx == -1)
            {
              log_error ("no alive host found in pool '%s'\n", name);
              if (r_httphost)
                {
                  xfree (*r_httphost);
                  *r_httphost = NULL;
                }
              return gpg_error (GPG_ERR_NO_KEYSERVER);
            }
        }

      assert (hi->poolidx >= 0 && hi->poolidx < hosttable_size);
      hi = hosttable[hi->poolidx];
      assert (hi);
    }
  else if (r_httphost && is_ip_address (hi->name))
    {
      /* This is a numerical IP address and not a pool.  We want to
       * find the canonical name so that it can be used in the HTTP
       * Host header.  Fixme: We should store that name in the
       * hosttable. */
      char *host;

      err = resolve_dns_name (hi->name, 0, 0, SOCK_STREAM, &aibuf, NULL);
      if (!err)
        {
          for (ai = aibuf; ai; ai = ai->next)
            {
              if ((!opt.disable_ipv6 && ai->family == AF_INET6)
                  || (!opt.disable_ipv4 && ai->family == AF_INET))
                {
                  err = resolve_dns_addr (ai->addr, ai->addrlen, 0, &host);
                  if (!err)
                    {
                      /* Okay, we return the first found name.  */
                      *r_httphost = host;
                      break;
                    }
                }
            }
        }
      free_dns_addrinfo (aibuf);
    }

  if (hi->dead)
    {
      log_error ("host '%s' marked as dead\n", hi->name);
      if (r_httphost)
        {
          xfree (*r_httphost);
          *r_httphost = NULL;
        }
      return gpg_error (GPG_ERR_NO_KEYSERVER);
    }

  if (r_httpflags)
    {
      /* If the hosttable does not indicate that a certain host
         supports IPv<N>, we explicit set the corresponding http
         flags.  The reason for this is that a host might be listed in
         a pool as not v6 only but actually support v6 when later
         the name is resolved by our http layer.  */
      if (!hi->v4)
        *r_httpflags |= HTTP_FLAG_IGNORE_IPv4;
      if (!hi->v6)
        *r_httpflags |= HTTP_FLAG_IGNORE_IPv6;

      /* Note that we do not set the HTTP_FLAG_FORCE_TOR for onion
         addresses because the http module detects this itself.  This
         also allows us to use an onion address without Tor mode being
         enabled.  */
    }

  *r_host = xtrystrdup (hi->name);
  if (!*r_host)
    {
      err = gpg_error_from_syserror ();
      if (r_httphost)
        {
          xfree (*r_httphost);
          *r_httphost = NULL;
        }
      return err;
    }
  if (hi->port[protocol])
    snprintf (r_portstr, 6 /* five digits and the sentinel */,
              "%hu", hi->port[protocol]);
  return 0;
}
Exemple #25
0
void Dispatcher::dispatch_requests(int id) {
    debug("Thread %i started", id);

    while (1) {
        // Get an request out of the request queue
        int socket;
        debug("Try to lock %d", id);
        {
            std::unique_lock<std::mutex> lck(request_queue_mutex);
            while (request_queue.empty()) {
                debug("Wait %d", id);
                request_queue_empty.wait(lck);
            };
            socket = request_queue.front();
            request_queue.pop();
            debug("Unlock %d", id);
        }

        debug("New request: Handled by thread %i", id);

        // Allocates memory for the request
        struct HttpRequest *request;
        int http_error = http_receive_request(socket, &request);
        if (http_error != HTTP_SUCCESS) {
            debug("Invalid Http request.");
            assert(request == NULL);
            // TODO send error msg to client
            close(socket);
            continue;
        }
        debug("Request payload: %s", request->payload);

        if (strncmp(request->resource, "/add_node/", 10) == 0) {
            struct sockaddr addr;
            socklen_t addrlen = sizeof(struct sockaddr);
            if (getpeername(socket, &addr, &addrlen) == 0) {
                if (addr.sa_family == AF_INET || addr.sa_family == AF_UNSPEC) {
                    struct sockaddr_in *sa = (struct sockaddr_in *)&addr;
                    char ip[INET_ADDRSTRLEN];
                    if (inet_ntop(AF_INET, &(sa->sin_addr), ip, INET_ADDRSTRLEN) == NULL) {
                        log_err("/add_node/ - Converting network address to string");
                    }
                    int port = (int)strtol(request->resource+10, (char **)NULL, 10);
                    if (port == 0) {
                        log_err("/add_node/ - Detecting port");
                    }
                    debug("Add host:  %s:%i", ip, port);
                    add_host(ip, port);
                } else {
                    debug("Cannot add host: Unsupported Address family %d", addr.sa_family);
                }
            } else {
                log_err("/add_node/ - getpeername()");
            }

            HttpRequest_free(request);
            close(socket);

        } else if (strncmp(request->resource, "/remove_node/", 13) == 0) {
            char *delimiter = strchr(request->resource, ':');
            if (delimiter != NULL) {
                char *ip = strndup(request->resource + 13, delimiter - (request->resource + 13));
                int port = 0;
                remove_host(ip, port);
                free(ip);
            }

            HttpRequest_free(request);
            close(socket);

        } else if (strcmp(request->resource, "/node_info") == 0) {
            sendNodeInfo(request, socket);

            HttpRequest_free(request);
            close(socket);

        } else if (strcmp(request->resource, "/query") == 0) {
            int query_t = queryType(request->payload);
            switch(query_t) {
                case READ:
                    distributor->distribute(request, socket);
                    break;
                case LOAD:
                    sendToAll(request, socket);
                    break;
                case WRITE:
                    distributor->sendToMaster(request, socket);
                    break;
                default:
                    log_err("Invalid query: %s", request->payload);
                    throw "Invalid query.";
            }
        } else if (strcmp(request->resource, "/procedure") == 0) {
            distributor->sendToMaster(request, socket);
        } else {
            log_err("Invalid HTTP resource: %s", request->resource);
            exit(1);
        }
    }
}
Exemple #26
0
Fichier : dns.c Projet : bond/dma
int
dns_get_mx_list(const char *host, int port, struct mx_hostentry **he, int no_mx)
{
	char outname[MAXDNAME];
	ns_msg msg;
	ns_rr rr;
	const char *searchhost;
	const unsigned char *cp;
	unsigned char *ans;
	struct mx_hostentry *hosts = NULL;
	size_t nhosts = 0;
	size_t anssz;
	int pref;
	int cname_recurse;
	int err;
	int i;

	res_init();
	searchhost = host;
	cname_recurse = 0;

	anssz = 65536;
	ans = malloc(anssz);
	if (ans == NULL)
		return (1);

	if (no_mx)
		goto out;

repeat:
	err = res_search(searchhost, ns_c_in, ns_t_mx, ans, anssz);
	if (err < 0) {
		switch (h_errno) {
		case NO_DATA:
			/*
			 * Host exists, but no MX (or CNAME) entry.
			 * Not an error, use host name instead.
			 */
			goto out;
		case TRY_AGAIN:
			/* transient error */
			goto transerr;
		case NO_RECOVERY:
		case HOST_NOT_FOUND:
		default:
			errno = ENOENT;
			goto err;
		}
	}

	if (!ns_initparse(ans, anssz, &msg))
		goto transerr;

	switch (ns_msg_getflag(msg, ns_f_rcode)) {
	case ns_r_noerror:
		break;
	case ns_r_nxdomain:
		goto err;
	default:
		goto transerr;
	}

	for (i = 0; i < ns_msg_count(msg, ns_s_an); i++) {
		if (ns_parserr(&msg, ns_s_an, i, &rr))
			goto transerr;

		cp = ns_rr_rdata(rr);

		switch (ns_rr_type(rr)) {
		case ns_t_mx:
			pref = ns_get16(cp);
			cp += 2;
			err = ns_name_uncompress(ns_msg_base(msg), ns_msg_end(msg),
						 cp, outname, sizeof(outname));
			if (err < 0)
				goto transerr;

			add_host(pref, outname, port, &hosts, &nhosts);
			break;

		case ns_t_cname:
			err = ns_name_uncompress(ns_msg_base(msg), ns_msg_end(msg),
						 cp, outname, sizeof(outname));
			if (err < 0)
				goto transerr;

			/* Prevent a CNAME loop */
			if (cname_recurse++ > 10)
				goto err;

			searchhost = outname;
			goto repeat;

		default:
			break;
		}
	}

out:
	err = 0;
	if (0) {
transerr:
		if (nhosts == 0)
			err = 1;
	}
	if (0) {
err:
		err = -1;
	}

	free(ans);

	if (!err) {
		/*
		 * If we didn't find any MX, use the hostname instead.
		 */
		if (nhosts == 0)
			add_host(0, searchhost, port, &hosts, &nhosts);

		qsort(hosts, nhosts, sizeof(*hosts), sort_pref);
	}

	if (nhosts > 0) {
		/* terminate list */
		*hosts[nhosts].host = 0;
	} else {
		if (hosts != NULL)
			free(hosts);
		hosts = NULL;
	}

	*he = hosts;
	return (err);

	free(ans);
	if (hosts != NULL)
		free(hosts);
	return (err);
}
Exemple #27
0
int 
main(int argc, const char** argv){
  ndb_init();
  int help = 0;
  const char *cmd=0, *name=0, *group=0, *owner=0;
  int list = 0, start = 0, stop = 0, rm = 0;
  struct getargs args[] = {
    { "cmd", 'c', arg_string, &cmd, "command", "command to run (default ls)" }
    ,{ "name", 'n', arg_string, &name, 
       "apply command for all processes with name" }
    ,{ "group", 'g', arg_string, &group, 
       "apply command for all processes in group" }
    ,{ "owner", 'g', arg_string, &owner,
       "apply command for all processes with owner" }
    ,{ "long", 'l', arg_flag, &g_settings.m_longl, "long", "long listing"}
    ,{ "usage", '?', arg_flag, &help, "Print help", "" }
    ,{ "ls",  0, arg_flag, &list, "-c list", "list process(es)" }
    ,{ "start", 0, arg_flag, &start, "-c start", "start process(es)" }
    ,{ "stop",  0, arg_flag, &stop, "-c stop", "stop process(es)" }
    ,{ "rm",    0, arg_flag, &rm, "-c rm", "undefine process(es)" }
  };
  const int num_args = 10;
  int i; 
  int optind = 0;
  char desc[] = "[host:[port]]\n";
  
  if(getarg(args, num_args, argc, argv, &optind) || help) {
    arg_printusage(args, num_args, argv[0], desc);
    return 1;
  }

  if(list + start + stop + rm > 1){
    ndbout_c("Can only specify one command");
    arg_printusage(args, num_args, argv[0], desc);
    return 1;
  }
  
  if(list) cmd = "list";
  if(start) cmd = "start";
  if(stop) cmd = "stop";
  if(rm) cmd = "rm";
  if(!cmd) cmd = "list";
  
  Expression * m_expr = 0;

  for(i = optind; i<argc; i++){
    add_host(g_hosts, argv[i]);
  }

  OrExpr * orE = new OrExpr(new Operate(cmd, g_settings), true);
  m_expr = orE;
  for(i = optind; i<argc; i++){
    BaseString tmp(argv[i]);
    Vector<BaseString> split;
    tmp.split(split, ":");
    
    if(split.size() > 2){
      Uint32 id = atoi(split[2].c_str());
      orE->push_back(new ProcEQ(g_hosts[i-optind], id));	
    }
  }

  if(g_hosts.size() == 0){
    char buf[1024];
    if(NdbEnv_GetEnv(ENV_HOSTS, buf, sizeof(buf))){
      add_hosts(g_hosts, BaseString(buf));
    }
  }
  
  if(g_hosts.size() == 0){
    g_hosts.push_back(new SimpleCpcClient("localhost", g_settings.m_port));
  }
  
  if(group != 0){
    Expression * tmp = new FieldEQ("group", group);
    m_expr = new Match(* tmp, * m_expr);
  }
  
  if(name != 0){
    Expression * tmp = new FieldEQ("name", name);
    m_expr = new Match(* tmp, * m_expr);
  }

  if(owner != 0){
    Expression * tmp = new FieldEQ("owner", owner);
    m_expr = new Match(* tmp, * m_expr);
  }

  connect(g_hosts);
  for_each(g_hosts, * m_expr);
  
  return 0;
}
Exemple #28
0
int
main(int argc, char **argv)
{
	int argc_save = argc;
	char **argv_save = argv;
	gfarm_error_t e, e_save = GFARM_ERR_NO_ERROR;
	char opt_operation = '\0'; /* default operation */
	int opt_concurrency = DEFAULT_CONCURRENCY;
	int opt_alter_aliases = 0;
	char *opt_architecture = NULL;
	char *opt_domainname = NULL;
	long opt_ncpu = 0;
	int opt_port = 0, opt_flags = -1;
	int opt_plain_order = 0; /* i.e. do not sort */
	int opt_sort_by_loadavg = 0;
	int i, c, opt_use_metadb = 1;
	char *s;

	if (argc > 0)
		program_name = basename(argv[0]);
	while ((c = getopt(argc, argv, "AD:HLMPUa:cdf:ij:lmn:p:ruv?")) != -1) {
		switch (c) {
		case 'A':
			opt_alter_aliases = 1;
			break;
		case 'L':
			opt_sort_by_loadavg = 1;
			break;
		case 'M':
		case 'H':
		case 'R':
		case 'c':
		case 'd':
		case 'l':
		case 'm':
			if (opt_operation != '\0' && opt_operation != c)
				inconsistent_option(opt_operation, c);
			opt_operation = c;
			break;
		case 'a':
			opt_architecture = optarg;
			s = validate_architecture(opt_architecture);
			if (s != NULL) {
				fprintf(stderr, "%s: "
				    "invalid character '%c' in \"-a %s\"\n",
				    program_name, *s, opt_architecture);
				exit(1);
			}
			break;
		case 'D':
			opt_domainname = optarg;
			s = validate_hostname(opt_domainname);
			if (s != NULL) {
				fprintf(stderr, "%s: "
				    "invalid character '%c' in \"-a %s\"\n",
				    program_name, *s, opt_domainname);
				exit(1);
			}
			break;
		case 'i':
			opt_resolv_addr = resolv_addr_without_address_use;
			break;
		case 'j':
			opt_concurrency = parse_opt_long(optarg,
			    c, "<concurrency>");
			if (opt_concurrency <= 0) {
				fprintf(stderr, "%s: invalid value: -%c %d\n",
				    program_name, c, opt_concurrency);
				usage();
			}
			break;
		case 'f':
			opt_flags = parse_opt_long(optarg, c, "<flags>");
			break;
		case 'n':
			opt_ncpu = parse_opt_long(optarg, c, "<ncpu>");
			break;
		case 'p':
			opt_port = parse_opt_long(optarg, c, "<port>");
			break;
		case 'r':
			output_sort_reverse = 1;
			break;
		case 'U':
			opt_udp_only = 1;
			break;
		case 'u':
			opt_plain_order = 1;
			break;
		case 'v':
			opt_verbose = 1;
			break;
		case '?':
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	switch (opt_operation) {
	case OP_CREATE_ENTRY:
		if (opt_architecture == NULL) {
			fprintf(stderr, "%s: missing -a <architecture>\n",
			    program_name);
			usage();
		}
		if (opt_ncpu == 0)
			opt_ncpu = 1;
		if (opt_flags == -1)
			opt_flags = 0;
		/* opt_alter_aliases is meaningless, but allowed */
		break;
	case OP_REGISTER_DB:
	case OP_DELETE_ENTRY:
		if (opt_architecture != NULL)
			invalid_option('a');
		if (opt_domainname != NULL)
			invalid_option('D');
		/* fall through */
	case OP_NODENAME:
	case OP_LIST_GFSD_INFO:
	case OP_LIST_LONG:
	case OP_DUMP_METADB:
		if (opt_ncpu != 0)
			invalid_option('n');
		if (opt_alter_aliases)
			invalid_option('A');
		break;
	case OP_MODIFY_ENTRY:
		if (opt_domainname != NULL)
			invalid_option('D');
		break;
	default:
		;
	}

	for (i = 0; i < argc; i++) {
		s = validate_hostname(argv[i]);
		if (s != NULL) {
			fprintf(stderr, "%s: "
			    "invalid character '%c' in hostname \"%s\"\n",
			    program_name, *s, argv[i]);
			exit(1);
		}
	}

	e = gfarm_initialize(&argc_save, &argv_save);
	if (opt_operation == OP_LIST_GFSD_INFO && argc > 0 &&
	    opt_resolv_addr == resolv_addr_without_address_use) {
		/*
		 * An implicit feature to access gfsd directly
		 * without having working gfmd.
		 * e.g. gfhost -Hi <hostname>
		 *
		 * XXX	should describe this in the manual?
		 *	or use explicit and different option?
		 */
		opt_use_metadb = 0;
		opt_resolv_addr = resolv_addr_without_metadb;
	} else if (e != GFARM_ERR_NO_ERROR) {
		fprintf(stderr, "%s: %s\n", program_name,
		    gfarm_error_string(e));
		exit(1);
	}

	switch (opt_operation) {
	case OP_CREATE_ENTRY:
		if (argc > 0) {
			if (opt_port == 0) {
				fprintf(stderr, "%s: option -p <port> is "
				    "mandatory with -c\n", program_name);
				usage();
			}
			e_save = add_host(argv[0], opt_port, &argv[1],
			    opt_architecture, opt_ncpu, opt_flags);
			if (e_save != GFARM_ERR_NO_ERROR)
				fprintf(stderr, "%s: %s: %s\n", program_name,
				    argv[0], gfarm_error_string(e_save));
		}
		break;
	case OP_MODIFY_ENTRY:
		if (argc > 0) {
			e_save = gfarm_modify_host(argv[0], opt_port, &argv[1],
			    opt_architecture, opt_ncpu, opt_flags,
			    !opt_alter_aliases);
			if (e_save != GFARM_ERR_NO_ERROR)
				fprintf(stderr, "%s: %s: %s\n", program_name,
				    argv[0], gfarm_error_string(e_save));
		}
		break;
	case OP_DELETE_ENTRY:
		for (i = 0; i < argc; i++) {
			e = gfm_client_host_info_remove(gfarm_metadb_server,
			    argv[i]);
			if (e != GFARM_ERR_NO_ERROR) {
				fprintf(stderr, "%s: %s\n", argv[i],
				    gfarm_error_string(e));
				if (e_save == GFARM_ERR_NO_ERROR)
					e_save = e;
			}
		}
		break;
	case OP_REGISTER_DB:
		if (argc > 0) {
			fprintf(stderr, "%s: too many argument: %s\n",
			    program_name, argv[0]);
			exit(1);
		}
		e_save = register_db();
		break;
	case OP_LIST_GFSD_INFO:
		e = paraccess_list(opt_concurrency, opt_udp_only,
		    opt_architecture, opt_domainname, opt_port,
		    opt_plain_order, opt_sort_by_loadavg,
		    opt_use_metadb, argc, argv,
		    request_gfsd_info, callback_gfsd_info);
		break;
	case OP_NODENAME:
		e = paraccess_list(opt_concurrency, opt_udp_only,
		    opt_architecture, opt_domainname, opt_port,
		    opt_plain_order, opt_sort_by_loadavg,
		    opt_use_metadb, argc, argv,
		    request_nodename, callback_nodename);
		break;
	case OP_LIST_LONG:
		e = paraccess_list(opt_concurrency, opt_udp_only,
		    opt_architecture, opt_domainname, opt_port,
		    opt_plain_order, opt_sort_by_loadavg,
		    opt_use_metadb, argc, argv,
		    request_long_format, callback_long_format);
		break;
	case OP_DUMP_METADB:
		if (argc == 0) {
			e_save = list_all(opt_architecture, opt_domainname,
				print_host_info, NULL);
		} else {
			e_save = list(argc, argv, print_host_info, NULL);
		}
		break;
	}
	e = gfarm_terminate();
	if (e != GFARM_ERR_NO_ERROR) {
		fprintf(stderr, "%s: %s\n", program_name,
		    gfarm_error_string(e));
		exit(1);
	}
	exit(e_save == GFARM_ERR_NO_ERROR ? 0 : 1);
}
void LatencyAwarePolicy::on_up(const SharedRefPtr<Host>& host) {
    add_host(hosts_, host);
    ChainedLoadBalancingPolicy::on_up(host);
}
Exemple #30
0
gfarm_error_t
add_line(char *line, int lineno)
{
	gfarm_error_t e;
	long port, ncpu, flags;
	int len, nhostaliases;
	char *s, *hostname, *architecture;
	char *hostaliases[MAX_HOSTALIASES + 1];

	/* parse architecture */
	line += strspn(line, space); /* skip space */
	len = strcspn(line, space);
	if (len == 0 || line[len] == '\0')
		return (invalid_input(lineno));
	line[len] = '\0';
	architecture = line;
	line += len + 1;
	s = validate_architecture(architecture);
	if (s != NULL) {
		fprintf(stderr,
		    "line %d: invalid character '%c' in architecture \"%s\"\n",
		    lineno, *s, architecture);
		return (GFARM_ERR_INVALID_ARGUMENT);
	}

	e = parse_string_long(&line, lineno, "ncpu", &ncpu);
	if (e != GFARM_ERR_NO_ERROR)
		return (e);

	/* parse hostname */
	line += strspn(line, space); /* skip space */
	len = strcspn(line, space);
	if (len == 0)
		return (invalid_input(lineno));
	hostname = line;
	if (line[len] == '\0') {
		line += len;
	} else {
		line[len] = '\0';
		line += len + 1;
	}
	s = validate_hostname(hostname);
	if (s != NULL) {
		fprintf(stderr,
		    "line %d: invalid character '%c' in hostname \"%s\"\n",
		    lineno, *s, hostname);
		return (GFARM_ERR_INVALID_ARGUMENT);
	}

	e = parse_string_long(&line, lineno, "port", &port);
	if (e != GFARM_ERR_NO_ERROR)
		return (e);

	e = parse_string_long(&line, lineno, "flags", &flags);
	if (e != GFARM_ERR_NO_ERROR)
		return (e);

	/* parse hostaliases */
	for (nhostaliases = 0;; nhostaliases++) {
		line += strspn(line, space); /* skip space */
		if (*line == '\0')
			break;
		len = strcspn(line, space);
		/* assert(len > 0); */
		if (nhostaliases >= MAX_HOSTALIASES) {
			fprintf(stderr, "line %d: "
			    "number of hostaliases exceeds %d\n",
			    lineno, nhostaliases);
			return (GFARM_ERR_INVALID_ARGUMENT);
		}
		hostaliases[nhostaliases] = line;
		if (line[len] == '\0') {
			line += len;
		} else {
			line[len] = '\0';
			line += len + 1;
		}
		s = validate_hostname(hostaliases[nhostaliases]);
		if (s != NULL) {
			fprintf(stderr, "line %d: "
			    "invalid character '%c' in hostalias \"%s\"\n",
			    lineno, *s, hostaliases[nhostaliases]);
			return (GFARM_ERR_INVALID_ARGUMENT);
		}
	}
	hostaliases[nhostaliases] = NULL;

	e = add_host(hostname, port, hostaliases, architecture, ncpu, flags);
	if (e != GFARM_ERR_NO_ERROR)
		fprintf(stderr, "line %d: %s\n",
		    lineno, gfarm_error_string(e));
	return (e);
}