Example #1
0
int pfring_loop(pfring *ring, pfringProcesssPacket looper,
		const u_char *user_bytes, u_int8_t wait_for_packet) {
  int rc = 0;
  struct pfring_pkthdr hdr;

  memset(&hdr, 0, sizeof(hdr));
  ring->break_recv_loop = 0;

  if((! ring)
     || ring->is_shutting_down
     || (! ring->recv)
     || ring->mode == send_only_mode)
    return -1;

  if(!ring->chunk_mode_enabled) {
    /* Packet (non chunk) mode */
    u_char *buffer = NULL;

    while(!ring->break_recv_loop) {
      rc = ring->recv(ring, &buffer, 0, &hdr, wait_for_packet);
      
      if(rc < 0)
	break;
      else if(rc > 0) {
	hdr.caplen = min_val(hdr.caplen, ring->caplen);
	
	looper(&hdr, buffer, user_bytes);
      } else {
	/* if(!wait_for_packet) usleep(1); */
      }
    }
  } else {
    /* Chunk mode */
    void *chunk;
    
    if(!ring->recv_chunk) return(-2);

    /* All set to zero as the header is meaningless */
    memset(&hdr, 0, sizeof(hdr));

    while(!ring->break_recv_loop) {
      rc = ring->recv_chunk(ring, &chunk, &hdr.len, wait_for_packet);
      
      if(rc < 0)
	break;
      else if(rc > 0) {
	hdr.caplen = min_val(hdr.len, ring->caplen);
	
	looper(&hdr, chunk, user_bytes);
      } else {
	/* if(!wait_for_packet) usleep(1); */
      }
    }
  }

  return(rc);
}
Example #2
0
int KinematicAltBands::first_band_alt_generic(Detection3D* conflict_det, Detection3D* recovery_det,
    double B, double T, double B2, double T2,
    const TrafficState& ownship, const std::vector<TrafficState>& traffic, bool dir, bool green) {
  int upper = (int)(dir ? std::floor((max_val(ownship)-min_val(ownship))/get_step())+1 :
      std::floor((ownship.altitude()-min_val(ownship))/get_step()));
  int lower = dir ? (int)(std::ceil(ownship.altitude()-min_val(ownship))/get_step()) : 0;
  if (ownship.altitude() < min_val(ownship) || ownship.altitude() > max_val(ownship)) {
    return -1;
  } else {
    return first_nat(lower,upper,dir,conflict_det,recovery_det,B,T,B2,T2,ownship,traffic,green);
  }
}
Example #3
0
int pfring_loop(pfring *ring, pfringProcesssPacket looper,
		const u_char *user_bytes, u_int8_t wait_for_packet) {
  u_char *buffer = NULL;
  struct pfring_pkthdr hdr;
  int rc = 0;

  memset(&hdr, 0, sizeof(hdr));
  ring->break_recv_loop = 0;

  if((! ring)
     || ring->is_shutting_down
     || (! ring->recv)
     || ring->mode == send_only_mode)
    return -1;

  while(!ring->break_recv_loop) {
    rc = ring->recv(ring, &buffer, 0, &hdr, wait_for_packet);

    if(rc < 0)
      break;
    else if(rc > 0) {
      hdr.caplen = min_val(hdr.caplen, ring->caplen);

      looper(&hdr, buffer, user_bytes);
    } else {
      /* if(!wait_for_packet) usleep(1); */
    }
  }

  return(rc);
}
Example #4
0
int pfring_recv(pfring *ring, u_char** buffer, u_int buffer_len,
		struct pfring_pkthdr *hdr,
		u_int8_t wait_for_incoming_packet) {
  if(likely((ring
	     && ring->enabled
	     && ring->recv
	     && (ring->mode != send_only_mode)))) {
    int rc;

    /* Reentrancy is not compatible with zero copy */
    if(unlikely((buffer_len == 0) && ring->reentrant))
      return(PF_RING_ERROR_INVALID_ARGUMENT);

    ring->break_recv_loop = 0;
    rc = ring->recv(ring, buffer, buffer_len, hdr, wait_for_incoming_packet);
    hdr->caplen = min_val(hdr->caplen, ring->caplen);

    if(unlikely(ring->reflector_socket != NULL)) {
      if (rc > 0)
        pfring_send(ring->reflector_socket, (char *) *buffer, hdr->caplen, 0 /* flush */);
    }

    return rc;
  }

  if(!ring->enabled)
    return(PF_RING_ERROR_RING_NOT_ENABLED);

  return(PF_RING_ERROR_NOT_SUPPORTED);
}
int main(int argc, char * argv[]) {
	double h, *val, max, min;
	int n, nval, i, *vet, size;
	long unsigned int duracao;
	struct timeval start, end;

	scanf("%d",&size);

	/* entrada do numero de dados */
	scanf("%d",&nval);
	/* numero de barras do histograma a serem calculadas */
	scanf("%d",&n);

	/* vetor com os dados */
	val = (double *)malloc(nval*sizeof(double));
	vet = (int *)malloc(n*sizeof(int));

	/* entrada dos dados */
	for(i=0;i<nval;i++) {
		scanf("%lf",&val[i]);
	}

	/* calcula o minimo e o maximo valores inteiros */
	min = floor(min_val(val,nval));
	max = ceil(max_val(val,nval));

	/* calcula o tamanho de cada barra */
	h = (max - min)/n;

	gettimeofday(&start, NULL);

	/* chama a funcao */
	vet = count(min, max, vet, n, h, val, nval);

	gettimeofday(&end, NULL);

	duracao = ((end.tv_sec * 1000000 + end.tv_usec) - \
	(start.tv_sec * 1000000 + start.tv_usec));

	printf("%.2lf",min);
	for(i=1;i<=n;i++) {
		printf(" %.2lf",min + h*i);
	}
	printf("\n");

	/* imprime o histograma calculado */
	printf("%d",vet[0]);
	for(i=1;i<n;i++) {
		printf(" %d",vet[i]);
	}
	printf("\n");

	/* imprime o tempo de duracao do calculo */
	printf("%lu\n",duracao);

	free(vet);
	free(val);

	return 0;
}
Example #6
0
void Profiles::loadProfiles() {
  char **vals;
  Redis *redis = ntop->getRedis();
  int rc;

  rc = (redis ? redis->hashKeys(CONST_PROFILES_PREFS, &vals) : -1);
  if(rc > 0) {
    rc = min_val(rc, MAX_NUM_PROFILES);

    for(int i = 0; i < rc; i++) {
      if(vals[i] != NULL) {
	char contents[2048];

	if(redis->hashGet((char*)CONST_PROFILES_PREFS, vals[i], contents, sizeof(contents)) != -1) {
	  Profile *c = addProfile(vals[i], contents);
	  if(c) profiles[numProfiles++] = c;
	}

	free(vals[i]);
      }
    }

    free(vals);
  }
}
Example #7
0
// dir=false is down, dir=true is up. Return NaN if there is not a resolution
double KinematicAltBands::resolution(Detection3D* conflict_det, Detection3D* recovery_det, const TrafficState& repac,
    int epsh, int epsv, double B, double T, const TrafficState& ownship, const std::vector<TrafficState>& traffic,
    bool dir) {
  int ires = first_band_alt_generic(conflict_det,recovery_det,B,T,0,B,ownship,traffic,dir,true);
  if (ires < 0) {
    return (dir ? 1 : -1)*PINFINITY;
  } else {
    return min_val(ownship)+ires*get_step();
  }
}
Example #8
0
Btree btree_delete(String key, Btree t)
{
  if (btree_isempty(t))
    return t;
  else if (strcmp(key, t->key) < 0){
    if (btree_isempty(t->left))
      return t;
    else{
      t->left = btree_delete(key, t->left);
      return t;
    }}
    else if (strcmp(key, t->key) > 0){
      if (btree_isempty(t->right))
	return t;
      else{
	t->right = btree_delete(key, t->right);
	return t;
      }}
    else if ((btree_isempty(t->right)) && (btree_isempty(t->left))){
      free(t->key);
      free(t->value);
      free(t);
	return btree_empty();
    }
    else if (btree_isempty(t->left)){
      Btree p = t->right;
      free(t->key);
      free(t->value);
      free(t);
	return p;
    }
    else if (btree_isempty(t->right)){
      Btree p = t->left;
      free(t->key);
      free(t->value);
      free(t);
	return p;
    }
      else{
	Btree p;
        p->key = min_key(t->right);
	p->value = min_val(t->right);
	p->right = deletemin(t->right);
	free(t->key);
	free(t->value);
	free(t);
	return p;
      }
}
Example #9
0
std::pair<Vect3, Velocity> KinematicAltBands::trajectory(const TrafficState& ownship, double time, bool dir) const {
  double target_alt = min_val(ownship)+j_step_*get_step();
  std::pair<Position,Velocity> posvel;
  if (instantaneous_bands()) {
    posvel = std::pair<Position,Velocity>(ownship.getPosition().mkZ(target_alt),ownship.getVelocity().mkVs(0));
  } else {
    double tsqj = ProjectedKinematics::vsLevelOutTime(ownship.getPosition(),ownship.getVelocity(),vertical_rate_,
        target_alt,vertical_accel_)+time_step(ownship);
    if (time <= tsqj) {
      posvel = ProjectedKinematics::vsLevelOut(ownship.getPosition(), ownship.getVelocity(), time, vertical_rate_, target_alt, vertical_accel_);
    } else {
      Position npo = ownship.getPosition().linear(ownship.getVelocity(),time);
      posvel = std::pair<Position,Velocity>(npo.mkZ(target_alt),ownship.getVelocity().mkVs(0));
    }
  }
  return std::pair<Vect3,Velocity>(ownship.pos_to_s(posvel.first),ownship.vel_to_v(posvel.first,posvel.second));
}
Example #10
0
int min_clicks() {
    int i;
    mclicks+=get_digits(clist[0]);     /*for the first channel, you will always key in the digits*/
    curr_ch=clist[0];
    for(i=1;i<=cnum;i++){               /*run loop from second channel to cnum*/
      init(clicks,8);                   /*initialize clicks to 0 at the beginning of every iteration*/

      clicks[0]=get_digits(clist[i]);
      /*end of part 1 - directly key in the digits*/

      curr_ch=clist[i-1];
      channel_up(i,1);
      /*end of part 2 - keep pressing up*/

      curr_ch=clist[i-1];
      channel_down(i,2);
      /*end of part 3 - keep pressing down*/

      curr_ch=low;
      clicks[3]+=get_digits(low);
      channel_down(i,3);
      /*end of part 4 - key in min value and go back*/

      curr_ch=high;
      clicks[4]+=get_digits(high);
      channel_up(i,4);
      /*end of part 5 - key in max value and go forward*/

     if(i>1){
      curr_ch=clist[i-2];
      clicks[5]++;
      channel_up(i,5);
     } else clicks[5]=10000;
      /*end of part 6 - press back and then keep pressing down*/

     if(i>1) {
      curr_ch=clist[i-2];
      clicks[6]++;
      channel_down(i,6);
     } else clicks[6]=10000;
      /*end of part 7 - press back and then keep pressing up*/

      mclicks+=min_val(clicks,7); /*increment minclicks by the min value among the procedures followed for current channel*/
    }
  return mclicks;
}
Example #11
0
/*!
 * @brief Use this to declare a new alarm
 * @param d
 * @param id
 * @param callback
 * @param value
 * @param period
 *
 * @return
 */
TIMER_HANDLE SetAlarm(CO_Data* d, UNS32 id, TimerCallback_t callback, TIMEVAL value, TIMEVAL period)
{
	TIMER_HANDLE row_number;
	s_timer_entry *row;

	/* in order to decide new timer setting we have to run over all timer rows */
	for (row_number = 0, row = timers; row_number <= last_timer_raw + 1 && row_number < MAX_NB_TIMER; row_number++, row++)
	{
		/* if something to store and empty row */
		if (callback && row->state == TIMER_FREE)
		{	/* just store */
			TIMEVAL real_timer_value;
			TIMEVAL elapsed_time;

			if (row_number == last_timer_raw + 1)
			{
				last_timer_raw++;
			}

			elapsed_time = getElapsedTime();

			/* set next wakeup alarm if new entry is sooner than others, or if it is alone */
			real_timer_value = value;
			real_timer_value = min_val(real_timer_value, TIMEVAL_MAX);

			if (total_sleep_time > elapsed_time && total_sleep_time - elapsed_time > real_timer_value)
			{
				total_sleep_time = elapsed_time + real_timer_value;
				setTimer(real_timer_value);
			}

			row->callback = callback;
			row->d = d;
			row->id = id;
			row->val = value + elapsed_time;
			row->interval = period;
			row->state = TIMER_ARMED;

			return row_number;
		}
	}

	return TIMER_NONE;
}
int pfring_mod_get_hash_filtering_rule_stats(pfring *ring,
					     hash_filtering_rule* rule,
					     char* stats, u_int *stats_len) {
  char buffer[2048];
  int rc;
  u_int len;

  memcpy(buffer, rule, sizeof(hash_filtering_rule));
  len = sizeof(buffer);
  rc = getsockopt(ring->fd, 0,
		  SO_GET_HASH_FILTERING_RULE_STATS,
		  buffer, &len);
  if(rc < 0)
    return(rc);

  *stats_len = min_val(*stats_len, rc);
  memcpy(stats, buffer, *stats_len);
  return(0);
}
Example #13
0
void vec2Di::print(const wchar_t* file) const
{
        const vec2Di& v = *this;
        wchar_t format[32] = L"%4d";

        int mx = max_val();
        int mn = min_val();
        if (abs(mn) > mx)
                mx = abs(mn);

        if (mx >= 10000)
                wcscpy(format, L"%7d");
        else if (mx >= 10000)
                wcscpy(format, L"%6d");
        else if (mx >= 1000)
                wcscpy(format, L"%5d");
        else if (mx >= 100)
                wcscpy(format, L"%4d");
        else if(mx >= 10)
                wcscpy(format, L"%3d");
        else if(mx < 10)
                wcscpy(format, L"%2d");
        
        if (file) {
                FILE *fp = _wfopen(file, L"wt");
                if (fp != 0) {
                        fwprintf(fp, L"\n vec: %p\n", this);
                        for (unsigned int i = 0; i < height(); i++) {
                                for (unsigned int j = 0; j < width(); j++)
                                        fwprintf(fp, format, v(i, j));
                                fwprintf(fp, L"\n");
                        }
                        fclose(fp);
                }
        } else {
                wprintf(L"\n vec: %p\n", this);
                for (unsigned int i = 0; i < height(); i++) {
                        for (unsigned int j = 0; j < width(); j++)
                                wprintf(format, v(i, j));
                        wprintf(L"\n");
                }
        }
}
Example #14
0
int pfring_recv(pfring *ring, u_char** buffer, u_int buffer_len,
		struct pfring_pkthdr *hdr,
		u_int8_t wait_for_incoming_packet) {
  if (likely(ring
	     && ring->enabled
	     && ring->recv
	     && ring->mode != send_only_mode)) {
    int rc;

    /* Reentrancy is not compatible with zero copy */
    if (unlikely(buffer_len == 0 && ring->reentrant))
      return PF_RING_ERROR_INVALID_ARGUMENT;

    ring->break_recv_loop = 0;

#ifdef ENABLE_BPF
recv_next:
#endif

    rc = ring->recv(ring, buffer, buffer_len, hdr, wait_for_incoming_packet);
    hdr->caplen = min_val(hdr->caplen, ring->caplen), hdr->extended_hdr.if_index = ring->device_id;

    if(unlikely(ring->ixia_timestamp_enabled))
      pfring_handle_ixia_hw_timestamp(*buffer, hdr);

#ifdef ENABLE_BPF
    if (unlikely(rc > 0 && ring->userspace_bpf && bpf_filter(ring->userspace_bpf_filter.bf_insns, *buffer, hdr->caplen, hdr->len) == 0))
      goto recv_next; /* rejected */
#endif

    if (unlikely(rc > 0 && ring->reflector_socket != NULL))
        pfring_send(ring->reflector_socket, (char *) *buffer, hdr->caplen, 0 /* flush */);

    return rc;
  }

  if (!ring->enabled)
    return PF_RING_ERROR_RING_NOT_ENABLED;

  return PF_RING_ERROR_NOT_SUPPORTED;
}
Example #15
0
void LH_MonitoringDial::updateBounds()
{
    bool ok;
    SensorGroup *group = this->selectedSensorGroup(&ok);

    qreal _max = setup_max_->value();
    qreal _min = setup_min_->value();

    bool minExists = false;
    bool maxExists = false;

    if(ok)
    {
        minExists = group->limits.minimum.exists;
        if(group->limits.minimum.exists)
        {
            _min = group->limits.minimum.value;
            setup_min_->setValue(_min);
        }

        maxExists = group->limits.maximum.exists;
        if(group->limits.maximum.exists)
        {
            _max = group->limits.maximum.value;
            setup_max_->setValue(_max);
        }
    }

    setMax(_max);
    setMin(_min);

    //qDebug() << "Min: " << ok << "; minExists: " << minExists << "; min=" << _min << "; min_val():" << min_val() << "; setup_min_:" << setup_min_->value() << "; actual=set:" << (setup_min_->value() == min_val());
    //qDebug() << "Max: " << ok << "; maxExists: " << maxExists << "; max=" << _max << "; max_val():" << max_val() << "; setup_max_:" << setup_max_->value() << "; actual=set:" << (setup_max_->value() == max_val());

    bool _visible = (!minExists || setup_min_->value() == min_val()) && (!maxExists || setup_max_->value() == max_val());
    setup_min_->setVisible(_visible);
    setup_max_->setVisible(_visible);
    setup_minmax_hr_->setVisible(_visible);

    requestRender();
}
Example #16
0
int pfring_dna_recv(pfring *ring, u_char** buffer, u_int buffer_len,
                    struct pfring_pkthdr *hdr,
                    u_int8_t wait_for_incoming_packet) {
    u_char *pkt = NULL;
    int8_t status = 0;

    if(unlikely(ring->reentrant)) pthread_rwlock_wrlock(&ring->rx_lock);

redo_pfring_recv:
    if(ring->is_shutting_down || ring->break_recv_loop) {
        if(unlikely(ring->reentrant)) pthread_rwlock_unlock(&ring->rx_lock);
        return(-1);
    }

    pkt = ring->dna_next_packet(ring, buffer, buffer_len, hdr);

    if(pkt && (hdr->len > 0)) {
        if(unlikely(ring->sampling_rate > 1)) {
            if (likely(ring->dna.sampling_counter > 0)) {
                ring->dna.sampling_counter--;
                goto redo_pfring_recv;
            } else {
                ring->dna.sampling_counter = ring->sampling_rate-1;
            }
        }

        hdr->caplen = min_val(hdr->caplen, ring->caplen);
        if(unlikely(ring->reentrant)) pthread_rwlock_unlock(&ring->rx_lock);
        return(1);
    }

    if(wait_for_incoming_packet) {
        status = ring->dna_check_packet_to_read(ring, wait_for_incoming_packet);

        if(status > 0)
            goto redo_pfring_recv;
    }

    if(unlikely(ring->reentrant)) pthread_rwlock_unlock(&ring->rx_lock);
    return(0);
}
Example #17
0
void KinematicAltBands::alt_bands_generic(std::vector<Integerval>& l,
    Detection3D* conflict_det, Detection3D* recovery_det,
    double B, double T, double B2, double T2,
    const TrafficState& ownship, const std::vector<TrafficState>& traffic) {
  int max_step = (int)std::floor((max_val(ownship)-min_val(ownship))/get_step())+1;
  int d = -1; // Set to the first index with no conflict
  for (int k = 0; k <= max_step; ++k) {
    j_step_ = k;
    if (d >=0 && conflict_free_traj_step(conflict_det,recovery_det,B,T,B2,T2,ownship,traffic))  {
      continue;
    } else if (d >=0) {
      l.push_back(Integerval(d,k-1));
      d = -1;
    } else if (conflict_free_traj_step(conflict_det,recovery_det,B,T,B2,T2,ownship,traffic)) {
      d = k;
    }
  }
  if (d >= 0) {
    l.push_back(Integerval(d,max_step));
  }
}
Example #18
0
bool KinematicAltBands::conflict_free_traj_step(Detection3D* conflict_det, Detection3D* recovery_det,
    double B, double T, double B2, double T2,
    const TrafficState& ownship, const std::vector<TrafficState>& traffic) const {
  bool trajdir = true;
  if (instantaneous_bands()) {
    return no_conflict(conflict_det,recovery_det,B,T,B2,T2,trajdir,0,ownship,traffic);
  } else {
    double tstep = time_step(ownship);
    double target_alt = min_val(ownship)+j_step_*get_step();
    Tuple5<double,double,double,double,double> tsqj = Kinematics::vsLevelOutTimes(ownship.altitude(),ownship.verticalSpeed(),
        vertical_rate_,target_alt,vertical_accel_,-vertical_accel_,true);
    double tsqj1 = tsqj.first+0;
    double tsqj2 = tsqj.second+0;
    double tsqj3 = tsqj.third+tstep;
    for (int i=0; i<=std::floor(tsqj1/tstep);++i) {
      double tsi = i*tstep;
      if ((B<=tsi && tsi<=T && any_los_aircraft(conflict_det,trajdir,tsi,ownship,traffic)) ||
          (recovery_det != NULL && B2 <= tsi && tsi <= T2 &&
              any_los_aircraft(recovery_det,trajdir,tsi,ownship,traffic))) {
        return false;
      }
    }
    if ((tsqj2>=B &&
        any_conflict_aircraft(conflict_det,B,std::min(T,tsqj2),trajdir,std::max(tsqj1,0.0),ownship,traffic)) ||
        (recovery_det != NULL && tsqj2>=B2 &&
            any_conflict_aircraft(recovery_det,B2,std::min(T2,tsqj2),trajdir,std::max(tsqj1,0.0),ownship,traffic))) {
      return false;
    }
    for (int i=(int)std::ceil(tsqj2/tstep); i<=std::floor(tsqj3/tstep);++i) {
      double tsi = i*tstep;
      if ((B<=tsi && tsi<=T && any_los_aircraft(conflict_det,trajdir,tsi,ownship,traffic)) ||
          (recovery_det != NULL && B2 <= tsi && tsi <= T2 &&
              any_los_aircraft(recovery_det,trajdir,tsi,ownship,traffic))) {
        return false;
      }
    }
    return no_conflict(conflict_det,recovery_det,B,T,B2,T2,trajdir,std::max(tsqj3,0.0),ownship,traffic);
  }
}
Example #19
0
vm::tuple*
agg_configuration::generate_min_int(const field_num field) const
{
   assert(!vals.empty());
   
   const_iterator end(vals.end());
   const_iterator it(vals.begin());
   vm::tuple *min_tpl((*it)->get_tuple());
   int_val min_val(min_tpl->get_int(field));

   ++it;
   for(; it != end; ++it) {
      simple_tuple *sother(*it);
      vm::tuple *other(sother->get_tuple());

      if(min_val > other->get_int(field)) {
         min_val = other->get_int(field);
         min_tpl = other;
      }
   }

   return min_tpl->copy();
}
Example #20
0
static void* packetPollLoop(void* ptr) {
  PcapInterface *iface = (PcapInterface*)ptr;
  pcap_t  *pd;
  FILE *pcap_list = iface->get_pcap_list();

  /* Wait until the initialization completes */
  while(!iface->isRunning()) sleep(1);

  do {
    if(pcap_list != NULL) {
      char path[256], *fname;
      pcap_t *pcap_handle;

      while((fname = fgets(path, sizeof(path), pcap_list)) != NULL) {
	char pcap_error_buffer[PCAP_ERRBUF_SIZE];
	int l = (int)strlen(path)-1;
	
	if((l <= 1) || (path[0] == '#')) continue;
	path[l--] = '\0';

	/* Remove trailer white spaces */
	while((l > 0) && (path[l] == ' ')) path[l--] = '\0';	

	if((pcap_handle = pcap_open_offline(path, pcap_error_buffer)) == NULL) {
	  ntop->getTrace()->traceEvent(TRACE_ERROR, "Unable to open file '%s': %s", 
				       path, pcap_error_buffer);
	} else {
	  ntop->getTrace()->traceEvent(TRACE_NORMAL, "Reading packes from pcap file %s", path);
	  iface->set_pcap_handle(pcap_handle);
	  break;
	}
      }

      if(fname == NULL) {
	ntop->getTrace()->traceEvent(TRACE_NORMAL, "No more pcap files to read");
	fclose(pcap_list);
	return(NULL);
      } else
	iface->set_datalink(pcap_datalink(pcap_handle));
    }

    pd = iface->get_pcap_handle();
    
    while((pd != NULL) 
	  && iface->isRunning() 
	  && (!ntop->getGlobals()->isShutdown())) {
      const u_char *pkt;
      struct pcap_pkthdr *hdr;
      int rc;

      while(iface->idle()) { iface->purgeIdle(time(NULL)); sleep(1); }

      if((rc = pcap_next_ex(pd, &hdr, &pkt)) > 0) {
	if((rc > 0) && (pkt != NULL) && (hdr->caplen > 0)) {
	  int a, b;
	  
#ifdef WIN32
	  /*
	    For some unknown reason, on Windows winpcap
	    gets crazy with specific packets and so ntopng
	    crashes. Copying the packet memory onto a local buffer
	    prevents that, as specified in
	    https://github.com/ntop/ntopng/issues/194
	  */
	  u_char pkt_copy[1600];
	  struct pcap_pkthdr hdr_copy;

	  memcpy(&hdr_copy, hdr, sizeof(hdr_copy));
	  hdr_copy.len = min(hdr->len, sizeof(pkt_copy) - 1);
	  hdr_copy.caplen = min(hdr_copy.len, hdr_copy.caplen);
	  memcpy(pkt_copy, pkt, hdr_copy.len);
	  iface->packet_dissector(&hdr_copy, (const u_char*)pkt_copy, &a, &b);
#else
	  hdr->caplen = min_val(hdr->caplen, iface->getMTU());
	  iface->packet_dissector(hdr, pkt, &a, &b);
#endif
	}
      } else if(rc < 0) {
	if(iface->read_from_pcap_dump())
	  break;
      } else {
	/* No packet received before the timeout */
	iface->purgeIdle(time(NULL));
      }
    } /* while */
  } while(pcap_list != NULL);

  ntop->getTrace()->traceEvent(TRACE_NORMAL, "Terminated packet polling for %s", iface->get_name());

  if(ntop->getPrefs()->shutdownWhenDone())
    ntop->getGlobals()->shutdown();

  return(NULL);
}
Example #21
0
int pfring_loop(pfring *ring, pfringProcesssPacket looper,
		const u_char *user_bytes, u_int8_t wait_for_packet) {
  int rc = 0;
  struct pfring_pkthdr hdr;

  memset(&hdr, 0, sizeof(hdr));
  ring->break_recv_loop = 0;

  if((! ring)
     || ring->is_shutting_down
     || (! ring->recv)
     || ring->mode == send_only_mode)
    return -1;

  if(!ring->chunk_mode_enabled) {
    /* Packet (non chunk) mode */
    u_char *buffer = NULL;

    while(!ring->break_recv_loop) {
      rc = ring->recv(ring, &buffer, 0, &hdr, wait_for_packet);

      if(rc < 0)
	break;
      else if(rc > 0) {
	hdr.caplen = min_val(hdr.caplen, ring->caplen);

#ifdef ENABLE_BPF
        if (unlikely(ring->userspace_bpf && bpf_filter(ring->userspace_bpf_filter.bf_insns, buffer, hdr.caplen, hdr.len) == 0))
          continue; /* rejected */
#endif
        if(unlikely(ring->ixia_timestamp_enabled))
          pfring_handle_ixia_hw_timestamp(buffer, &hdr);

	looper(&hdr, buffer, user_bytes);
      } else {
	/* if(!wait_for_packet) usleep(1); */
      }
    }
  } else {
    /* Chunk mode */
    void *chunk;

    if(!ring->recv_chunk) return(-2);

    /* All set to zero as the header is meaningless */
    memset(&hdr, 0, sizeof(hdr));

    while(!ring->break_recv_loop) {
      rc = ring->recv_chunk(ring, &chunk, &hdr.len, wait_for_packet);

      if(rc < 0)
	break;
      else if(rc > 0) {
	hdr.caplen = min_val(hdr.len, ring->caplen);

	looper(&hdr, chunk, user_bytes);
      } else {
	/* if(!wait_for_packet) usleep(1); */
      }
    }
  }

  return(rc);
}
Example #22
0
File: main.cpp Project: CCJY/coliru
	static void sync_min(T e) { if (e < min_val()) min_val() = int(e); }
Example #23
0
template <typename PointInT, typename PointOutT> void 
pcl::SIFTKeypoint<PointInT, PointOutT>::findScaleSpaceExtrema (
    const PointCloudIn &input, KdTree &tree, const Eigen::MatrixXf &diff_of_gauss, 
    std::vector<int> &extrema_indices, std::vector<int> &extrema_scales)
{
  const int k = 25;
  std::vector<int> nn_indices (k);
  std::vector<float> nn_dist (k);

  const int nr_scales = static_cast<int> (diff_of_gauss.cols ());
  std::vector<float> min_val (nr_scales), max_val (nr_scales);

  for (int i_point = 0; i_point < static_cast<int> (input.size ()); ++i_point)
  {
    // Define the local neighborhood around the current point
    const size_t nr_nn = tree.nearestKSearch (i_point, k, nn_indices, nn_dist); //*
    // * note: the neighborhood for finding local extrema is best defined as a small fixed-k neighborhood, regardless of
    //   the configurable search method specified by the user, so we directly employ tree.nearestKSearch here instead 
    //   of using searchForNeighbors

    // At each scale, find the extreme values of the DoG within the current neighborhood
    for (int i_scale = 0; i_scale < nr_scales; ++i_scale)
    {
      min_val[i_scale] = std::numeric_limits<float>::max ();
      max_val[i_scale] = -std::numeric_limits<float>::max ();

      for (size_t i_neighbor = 0; i_neighbor < nr_nn; ++i_neighbor)
      {
        const float &d = diff_of_gauss (nn_indices[i_neighbor], i_scale);

        min_val[i_scale] = (std::min) (min_val[i_scale], d);
        max_val[i_scale] = (std::max) (max_val[i_scale], d);
      }
    }

    // If the current point is an extreme value with high enough contrast, add it as a keypoint 
    for (int i_scale = 1; i_scale < nr_scales - 1; ++i_scale)
    {
      const float &val = diff_of_gauss (i_point, i_scale);

      // Does the point have sufficient contrast?
      if (fabs (val) >= min_contrast_)
      {
        // Is it a local minimum?
        if ((val == min_val[i_scale]) && 
            (val <  min_val[i_scale - 1]) && 
            (val <  min_val[i_scale + 1]))
        {
          extrema_indices.push_back (i_point);
          extrema_scales.push_back (i_scale);
        }
        // Is it a local maximum?
        else if ((val == max_val[i_scale]) && 
                 (val >  max_val[i_scale - 1]) && 
                 (val >  max_val[i_scale + 1]))
        {
          extrema_indices.push_back (i_point);
          extrema_scales.push_back (i_scale);
        }
      }
    }
  }
}
Example #24
0
void KinematicAltBands::none_bands(IntervalSet& noneset, Detection3D* conflict_det, Detection3D* recovery_det, const TrafficState& repac,
    int epsh, int epsv, double B, double T, const TrafficState& ownship, const std::vector<TrafficState>& traffic) {
  std::vector<Integerval> altint = std::vector<Integerval>();
  alt_bands_generic(altint,conflict_det,recovery_det,B,T,0,B,ownship,traffic);
  toIntervalSet(noneset,altint,get_step(),min_val(ownship),min_val(ownship),max_val(ownship));
}
Example #25
0
File: main.cpp Project: CCJY/coliru
	static int min() { return min_val(); }
Example #26
0
int MySQLDB::exec_sql_query(lua_State *vm, char *sql, bool limitRows) {
  MYSQL_RES *result;
  MYSQL_ROW row;
  char *fields[MYSQL_MAX_NUM_FIELDS] = { NULL };
  int num_fields, rc, num = 0;

  if(!db_operational)
    return(-2);

  if(m) m->lock(__FILE__, __LINE__);

  if((rc = mysql_query(&mysql, sql)) != 0) {
    rc = mysql_errno(&mysql);

    ntop->getTrace()->traceEvent(TRACE_ERROR, "MySQL error: [%s][%d]", 
				 get_last_db_error(&mysql), rc);
    
    mysql_close(&mysql);
    if(m) m->unlock(__FILE__, __LINE__);
    connectToDB(&mysql, true);

    if(!db_operational)
      return(-2);
    
    if(m) m->lock(__FILE__, __LINE__);
    rc = mysql_query(&mysql, sql);
  }

  if((rc != 0) || ((result = mysql_store_result(&mysql)) == NULL)) {
    lua_pushstring(vm, get_last_db_error(&mysql));
    if(m) m->unlock(__FILE__, __LINE__);
    return(rc);
  }

  num_fields = min_val(mysql_num_fields(result), MYSQL_MAX_NUM_FIELDS);
  lua_newtable(vm);

  num = 0;
  while((row = mysql_fetch_row(result))) {
    lua_newtable(vm);

    if(num == 0) {
      for(int i = 0; i < num_fields; i++) {
	MYSQL_FIELD *field = mysql_fetch_field(result);

	fields[i] = field->name;
      }
    }

    for(int i = 0; i < num_fields; i++)
      lua_push_str_table_entry(vm, (const char*)fields[i], row[i] ? row[i] : (char*)"");    

    lua_pushnumber(vm, ++num);
    lua_insert(vm, -2);
    lua_settable(vm, -3);

    if(limitRows && num >= MYSQL_MAX_NUM_ROWS) break;
  }

  mysql_free_result(result);

  if(m) m->unlock(__FILE__, __LINE__);

  return(0);
}