示例#1
0
文件: ntk-perf.C 项目: 0mk/non
   void draw ( void )
        {          
            if ( use_cairo )
                fl_push_use_cairo(true);

            fl_rectf( x(), y(), w(), h(), FL_BLACK );

            unsigned long long then = get_ts();

            fl_push_clip( x(), y(), w(), h() );

            int count = 400;

            /* draw stuff */
            int i = 0;
            for ( ; i < count; ++i )
                fl_draw_box( boxtype, x(), y(), w(), h(), fl_lighter( FL_BLACK ) );

            fl_pop_clip();

            unsigned long long now = get_ts();

            double elapsedms = (now - then) / 1000.0;

            static char text[256];
            sprintf( text, "Drew %i boxes in in %fms", i, elapsedms );

            fl_color( FL_RED );
            fl_draw( text, x(), y(), w(), h(), FL_ALIGN_CENTER | FL_ALIGN_INSIDE );

            draw_label();

            if ( use_cairo )
                fl_pop_use_cairo();
        }
示例#2
0
Context *getContext(void)
{
#if APITRACE_TLS
    return get_ts()->current_context.get();
#else
    return get_ts()->current_context;
#endif
}
示例#3
0
/*
void response_client_open_ex(response_client_t *uclient, char *conn_str, char *(*id_f)(), char *(*pph_f)()) {
    uclient->id_f = id_f;
    uclient->passphrase_f = pph_f;
    response_client_open_int(uclient, conn_str);
}
*/
int response_client_send(response_client_t *uclient, response_request_t *request) {
    int ret;
    long nbytes;
    char buff[UCLIENT_BUFSIZE];
#if defined(USERVER_ENCRYPTED)
    char cipher[UCLIENT_BUFSIZE];
    char message[UCLIENT_BUFSIZE];
    uint32_t timestamp;
    char sts[32];
    char *passphrase = uclient->passphrase_f();
    char otp[100];
    char *id = uclient->id_f();
    char challenge[32];
    int len = 32;
    int len1 = 32;
    
    lvc_t lvc;
    
    timestamp = get_ts();
    len1 = ts2str(timestamp, sts);
    
    generate_otp(otp, passphrase, sts);

    do_encrypt(challenge, &len, sts, len1, otp);

    lvc_init(&lvc, message, UCLIENT_BUFSIZE);

    fprintf(stdout, "lvc_pack id:%s\n", id);
    lvc_pack( &lvc, strlen(id), id );
    fprintf(stdout, "lvc_pack ts:%u\n", timestamp);
    lvc_pack( &lvc, sizeof(uint32_t), (char *)&timestamp );
    fprintf(stdout, "lvc_pack challenge:%d\n", len);
    lvc_pack( &lvc, len, challenge );
#endif
    response_build_request(buff, sizeof(buff), request);
    nbytes = strlen(buff);

#if defined(USERVER_ENCRYPTED)
    fprintf(stdout, "Message to send:%.*s\n", nbytes, buff);
    
    len = sizeof(cipher);
    do_encrypt(cipher, &len, buff, nbytes, otp);

    lvc_pack( &lvc, len, cipher );
    lvc_pack_finish(&lvc);
    
    nbytes = lvc.len;

    ret = pj_sock_sendto(uclient->fd, lvc.data, &nbytes, 0, (const pj_sockaddr_t *)uclient->connect_data, sizeof(pj_sockaddr_in));
#else
    ret = pj_sock_sendto(uclient->fd, buff, &nbytes, 0, (const pj_sockaddr_t *)uclient->connect_data, sizeof(pj_sockaddr_in));
#endif

    if(ret != 0) {
        PERROR_IF_TRUE(1, "Error in sending data\n");
        return -1;
    }

    return nbytes;
}
示例#4
0
void
SimpleSwitch::enqueue(int egress_port, std::unique_ptr<Packet> &&packet) {
    packet->set_egress_port(egress_port);

    PHV *phv = packet->get_phv();

    if (with_queueing_metadata) {
      phv->get_field("queueing_metadata.enq_timestamp").set(get_ts().count());
      phv->get_field("queueing_metadata.enq_qdepth")
          .set(egress_buffers.size(egress_port));
    }

#ifdef SSWITCH_PRIORITY_QUEUEING_ON
    size_t priority =
        phv->get_field(SSWITCH_PRIORITY_QUEUEING_SRC).get<size_t>();
    if (priority >= SSWITCH_PRIORITY_QUEUEING_NB_QUEUES) {
      bm::Logger::get()->error("Priority out of range, dropping packet");
      return;
    }
    egress_buffers.push_front(
        egress_port, SSWITCH_PRIORITY_QUEUEING_NB_QUEUES - 1 - priority,
        std::move(packet));
#else
    egress_buffers.push_front(egress_port, std::move(packet));
#endif
}
示例#5
0
std::string generate_logging_table(statistics_global *ps, std::string username)
{
	std::vector<history_logins> log = ps -> get_login_history();

	std::string content = "<table class=\"table2 tablemargins fullwidth\">\n";
	content += "<tr class=\"lighttable\"><td class=\"timestamp\">event ts</td><td>event type</td><td>user</td><td>host</td><td>type</td></tr>\n";
	content += "<tr class=\"lighttable\"><td>connected since</td><td>duration</td><td colspan=\"3\">notes</td></tr>\n";

	double now_ts = get_ts();
	for(int index=log.size()-1; index >= 0; index--)
	{
		if (username.size() > 0 && log.at(index).user != username)
			continue;

		content += "<tr>";
		content += "<td>" + time_to_str((time_t)log.at(index).event_ts) + "</td>";
		content += "<td>";

		switch(log.at(index).hl)
		{
			case HL_LOGIN_OK:
				content += "login ok";
				break;
			case HL_LOGOUT_OK:
				content += "logout ok";
				break;
			case HL_LOGIN_USER_FAIL:
				content += "unknown user";
				break;
			case HL_LOGIN_PW_FAIL:
				content += "password fail";
				break;
			case HL_LOGIN_OTHER:
				content += "other error";
				break;
			default:
				content += "INTERNAL ERROR";
		}

		content += "</td><td>" + log.at(index).user + "</td>";
		content += "<td>" + log.at(index).host + "</td>";
		content += "<td>" + log.at(index).type + "</td>";
		content += "</tr>";
		content += "<tr class=\"lighttable2\">";
		content += "<td>" + time_to_str((time_t)log.at(index).time_logged_in) + "</td>";
		if (log.at(index).hl == HL_LOGOUT_OK)
			content += format("<td>%f</td>", log.at(index).duration);
		else if (log.at(index).hl == HL_LOGIN_OK)
			content += format("<td>[%f]</td>", now_ts - log.at(index).time_logged_in);
		else
			content += "<td></td>";
		content += "<td colspan=\"3\">" + log.at(index).details + "</td>";
		content += "</tr>\n";
	}
	content += "</table>\n";

	return content;
}
示例#6
0
static void
add_new_tcp(struct tcphdr * this_tcphdr, struct ip * this_iphdr)
{
  struct tcp_stream *tolink;
  struct tcp_stream *a_tcp;
  int hash_index;
  struct tuple4 addr;
  
  addr.source = ntohs(this_tcphdr->th_sport);
  addr.dest = ntohs(this_tcphdr->th_dport);
  addr.saddr = this_iphdr->ip_src.s_addr;
  addr.daddr = this_iphdr->ip_dst.s_addr;
  hash_index = mk_hash_index(addr);
  
  if (tcp_num > max_stream) {
    struct lurker_node *i;
    
    tcp_oldest->nids_state = NIDS_TIMED_OUT;
    for (i = tcp_oldest->listeners; i; i = i->next)
      (i->item) (tcp_oldest, &i->data);
    free_tcp(tcp_oldest);
    nids_params.syslog(NIDS_WARN_TCP, NIDS_WARN_TCP_TOOMUCH, ugly_iphdr, this_tcphdr);
  }
  a_tcp = free_streams;
  if (!a_tcp) {
    fprintf(stderr, "gdb me ...\n");
#ifdef WIN32 /* Exit here, I do not know of a function similar to pause() in WIN32 -- Mike */
	exit(-1);
#else
    pause();
#endif
  }
  free_streams = a_tcp->next_free;
  
  tcp_num++;
  tolink = tcp_stream_table[hash_index];
  memset(a_tcp, 0, sizeof(struct tcp_stream));
  a_tcp->hash_index = hash_index;
  a_tcp->addr = addr;
  a_tcp->client.state = TCP_SYN_SENT;
  a_tcp->client.seq = ntohl(this_tcphdr->th_seq) + 1;
  a_tcp->client.first_data_seq = a_tcp->client.seq;
  a_tcp->client.window = ntohs(this_tcphdr->th_win);
  a_tcp->client.ts_on = get_ts(this_tcphdr, &a_tcp->client.curr_ts);
  a_tcp->server.state = TCP_CLOSE;
  a_tcp->next_node = tolink;
  a_tcp->prev_node = 0;
  if (tolink)
    tolink->prev_node = a_tcp;
  tcp_stream_table[hash_index] = a_tcp;
  a_tcp->next_time = tcp_latest;
  a_tcp->prev_time = 0;
  if (!tcp_oldest)
    tcp_oldest = a_tcp;
  if (tcp_latest)
    tcp_latest->prev_time = a_tcp;
  tcp_latest = a_tcp;
}
示例#7
0
debug_console::debug_console()
{
	nc = false;
	win_term = win_regs = win_logs = NULL;
	max_x = max_y = -1;
	n_ticks = 0;
	start_ts = get_ts();
	had_logging = false;

	refresh_limit = refresh_counter = 0;
	refresh_limit_valid = false;
}
示例#8
0
文件: mssl.c 项目: CCbird/httping
int connect_ssl(int fd, SSL_CTX *client_ctx, SSL **ssl_h, BIO **s_bio, double timeout, double *ssl_handshake)
{
	int dummy = -1;
	double dstart = get_ts();

	struct timeval tv;
	tv.tv_sec  = (long)(timeout / 1000.0);
	tv.tv_usec = (long)(timeout * 1000.0) % 1000000;

	*ssl_handshake = -1.0;

	if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv) == -1)
	{
		set_error(gettext("problem setting receive timeout (%s)"), strerror(errno));
		return -1;
	}

	if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv) == -1)
	{
		set_error(gettext("problem setting transmit timeout (%s)"), strerror(errno));
		return -1;
	}

	*ssl_h = SSL_new(client_ctx);

	*s_bio = BIO_new_socket(fd, BIO_NOCLOSE);
	SSL_set_bio(*ssl_h, *s_bio, *s_bio);

	dummy = SSL_connect(*ssl_h);
	if (dummy <= 0)
	{
		set_error(gettext("problem starting SSL connection: %d"), SSL_get_error(*ssl_h, dummy));
		return -1;
	}

	*ssl_handshake = get_ts() - dstart;

	return 0;
}
示例#9
0
void setContext(uintptr_t context_id)
{
    ThreadState *ts = get_ts();
    context_ptr_t ctx;

    context_map_mutex.lock();

    assert(context_map.find(context_id) != context_map.end());
    ctx = context_map[context_id];

    context_map_mutex.unlock();

    ts->current_context = ctx;

    if (!ctx->bound) {
        ctx->profile = glfeatures::getCurrentContextProfile();
        ctx->extensions.getCurrentContextExtensions(ctx->profile);
        ctx->features.load(ctx->profile, ctx->extensions);
        ctx->bound = true;
    }

    if (!ctx->boundDrawable) {
        /*
         * The default viewport and scissor state is set when a context is
         * first made current, with values matching the bound drawable.  Many
         * applications never thouch the default state ever again.
         *
         * Since we currently don't trace window sizes, and rely on viewport
         * calls to deduct, emit fake calls here so that viewport/scissor state
         * can be deducated.
         *
         * FIXME: don't call the real functions here -- just emit the fake
         * calls.
         */
        GLint viewport[4] = {0, 0, 0, 0};
        GLint scissor[4] = {0, 0, 0, 0};
        _glGetIntegerv(GL_VIEWPORT, viewport);
        _glGetIntegerv(GL_SCISSOR_BOX, scissor);

        /*
         * On MacOSX the current context and surface are set independently, and
         * we might be called before both are set, so ignore empty boxes.
         */
        if (viewport[2] && viewport[3] && scissor[2] && scissor[3]) {
            glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);
            glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
            ctx->boundDrawable = true;
        }
    }
}
示例#10
0
void Packet::print()
{
   uint32_t tsval, tsecr;
   char sip_str[INET_ADDRSTRLEN];
   char dip_str[INET_ADDRSTRLEN];

   inet_ntop(AF_INET, &ip_hdr->ip_src.s_addr, sip_str, INET_ADDRSTRLEN);
   inet_ntop(AF_INET, &ip_hdr->ip_dst.s_addr, dip_str, INET_ADDRSTRLEN);

   get_tcp_ts(&tsval,&tsecr);
   switch(get_ip_protocol()) 
   {
      case IPPROTO_TCP:
	 std::cout << "TCP packet: "
	      << "[" << get_ts().tv_sec << "." << std::setw(9) << std::setfill('0') << get_ts().tv_nsec << "] ["
	      << sip_str << ":" << get_tcp_sport() << "->"
	      << dip_str << ":" << get_tcp_dport() << "] "
	      << "[S:" << get_tcp_seq() << "] "
	      << "[A:" << get_tcp_ack() << "] "
	      << "[L:" << get_tcp_payload_len() << "] "
	      << "[M:" << get_tcp_mss() << "] "
	      << "[TV:" << tsval << "] "
	      << "[TE:" << tsecr << "]"
	      << std::endl << std::flush;
	 break;
      case IPPROTO_ICMP:
	 std::cout << "ICMP packet: ["
	      << sip_str << "->"
	      << dip_str << "] " 
	      << "[TTL:" << get_ip_ttl() << "]"
	      << std::endl << std::flush;
	 break;
      default:
	 std::cout << "Unknown packet!" << std::endl << std::flush;
	 break;
   }
}
示例#11
0
static void *
timedcond_routine (void *arg)
{
  int ret;
  struct timespec ts;

  gl_lock_lock (lockcond);
  while (!cond_value)
    {
      get_ts (&ts);
      ret = glthread_cond_timedwait (&condtest, &lockcond, &ts);
      if (ret == ETIMEDOUT)
        cond_timeout = 1;
    }
  gl_lock_unlock (lockcond);

  return NULL;
}
示例#12
0
int
SimpleSwitch::receive(int port_num, const char *buffer, int len) {
  static int pkt_id = 0;

  // this is a good place to call this, because blocking this thread will not
  // block the processing of existing packet instances, which is a requirement
  if (do_swap() == 0) {
    check_queueing_metadata();
  }

  // we limit the packet buffer to original size + 512 bytes, which means we
  // cannot add more than 512 bytes of header data to the packet, which should
  // be more than enough
  auto packet = new_packet_ptr(port_num, pkt_id++, len,
                               bm::PacketBuffer(len + 512, buffer, len));

  BMELOG(packet_in, *packet);

  PHV *phv = packet->get_phv();
  // many current P4 programs assume this
  // it is also part of the original P4 spec
  phv->reset_metadata();

  // setting standard metadata

  phv->get_field("standard_metadata.ingress_port").set(port_num);
  // using packet register 0 to store length, this register will be updated for
  // each add_header / remove_header primitive call
  packet->set_register(PACKET_LENGTH_REG_IDX, len);
  phv->get_field("standard_metadata.packet_length").set(len);
  Field &f_instance_type = phv->get_field("standard_metadata.instance_type");
  f_instance_type.set(PKT_INSTANCE_TYPE_NORMAL);

  if (phv->has_field("intrinsic_metadata.ingress_global_timestamp")) {
    phv->get_field("intrinsic_metadata.ingress_global_timestamp")
        .set(get_ts().count());
  }

  input_buffer.push_front(std::move(packet));
  return 0;
}
示例#13
0
void
SimpleSwitch::egress_thread(size_t worker_id) {
  PHV *phv;

  while (1) {
    std::unique_ptr<Packet> packet;
    size_t port;
    egress_buffers.pop_back(worker_id, &port, &packet);

    Deparser *deparser = this->get_deparser("deparser");
    Pipeline *egress_mau = this->get_pipeline("egress");

    phv = packet->get_phv();

    if (with_queueing_metadata) {
      auto enq_timestamp =
          phv->get_field("queueing_metadata.enq_timestamp").get<ts_res::rep>();
      phv->get_field("queueing_metadata.deq_timedelta").set(
          get_ts().count() - enq_timestamp);
      phv->get_field("queueing_metadata.deq_qdepth").set(
          egress_buffers.size(port));
    }

    phv->get_field("standard_metadata.egress_port").set(port);

    Field &f_egress_spec = phv->get_field("standard_metadata.egress_spec");
    f_egress_spec.set(0);

    phv->get_field("standard_metadata.packet_length").set(
        packet->get_register(PACKET_LENGTH_REG_IDX));

    egress_mau->apply(packet.get());

    Field &f_clone_spec = phv->get_field("standard_metadata.clone_spec");
    unsigned int clone_spec = f_clone_spec.get_uint();

    // EGRESS CLONING
    if (clone_spec) {
      BMLOG_DEBUG_PKT(*packet, "Cloning packet at egress");
      int egress_port = get_mirroring_mapping(clone_spec & 0xFFFF);
      if (egress_port >= 0) {
        f_clone_spec.set(0);
        p4object_id_t field_list_id = clone_spec >> 16;
        std::unique_ptr<Packet> packet_copy =
            packet->clone_with_phv_reset_metadata_ptr();
        PHV *phv_copy = packet_copy->get_phv();
        FieldList *field_list = this->get_field_list(field_list_id);
        for (const auto &p : *field_list) {
          phv_copy->get_field(p.header, p.offset)
            .set(phv->get_field(p.header, p.offset));
        }
        phv_copy->get_field("standard_metadata.instance_type")
            .set(PKT_INSTANCE_TYPE_EGRESS_CLONE);
        enqueue(egress_port, std::move(packet_copy));
      }
    }

    // TODO(antonin): should not be done like this in egress pipeline
    int egress_spec = f_egress_spec.get_int();
    if (egress_spec == 511) {  // drop packet
      BMLOG_DEBUG_PKT(*packet, "Dropping packet at the end of egress");
      continue;
    }

    deparser->deparse(packet.get());

    // RECIRCULATE
    if (phv->has_field("intrinsic_metadata.recirculate_flag")) {
      Field &f_recirc = phv->get_field("intrinsic_metadata.recirculate_flag");
      if (f_recirc.get_int()) {
        BMLOG_DEBUG_PKT(*packet, "Recirculating packet");
        p4object_id_t field_list_id = f_recirc.get_int();
        f_recirc.set(0);
        FieldList *field_list = this->get_field_list(field_list_id);
        // TODO(antonin): just like for resubmit, there is no need for a copy
        // here, but it is more convenient for this first prototype
        std::unique_ptr<Packet> packet_copy = packet->clone_no_phv_ptr();
        PHV *phv_copy = packet_copy->get_phv();
        phv_copy->reset_metadata();
        for (const auto &p : *field_list) {
          phv_copy->get_field(p.header, p.offset)
              .set(phv->get_field(p.header, p.offset));
        }
        phv_copy->get_field("standard_metadata.instance_type")
            .set(PKT_INSTANCE_TYPE_RECIRC);
        size_t packet_size = packet_copy->get_data_size();
        packet_copy->set_register(PACKET_LENGTH_REG_IDX, packet_size);
        phv_copy->get_field("standard_metadata.packet_length").set(packet_size);
        input_buffer.push_front(std::move(packet_copy));
        continue;
      }
    }

    output_buffer.push_front(std::move(packet));
  }
示例#14
0
文件: tcp.c 项目: carriercomm/GNP3C
static void
tcp_queue(struct tcp_stream * a_tcp, struct tcphdr * this_tcphdr,
	  struct half_stream * snd, struct half_stream * rcv,
	  char *data, int datalen, int skblen
	  )
{
  a_tcp->lasttime = time((time_t *)0);
  u_int this_seq = ntohl(this_tcphdr->th_seq);
  struct skbuff *pakiet;
  
  /*
   * Did we get anything new to ack?
   */
  if (!after(this_seq, EXP_SEQ)) {
    if (after(this_seq + datalen + (this_tcphdr->th_flags & TH_FIN), EXP_SEQ)) {

      // the packet straddles our window end 
      get_ts(this_tcphdr, &snd->curr_ts);
      add_from_skb(a_tcp, rcv, snd, data, datalen, this_seq,
		   (this_tcphdr->th_flags & TH_FIN),
		   (this_tcphdr->th_flags & TH_URG),
		   ntohs(this_tcphdr->th_urp) + this_seq - 1);
      
       // Do we have any old packets to ack that the above
       // made visible? (Go forward from skb)
       
      pakiet = rcv->list;
      while (pakiet) {
	if (after(pakiet->seq, EXP_SEQ))
	  break;
	if (after(pakiet->seq + pakiet->len + pakiet->fin, EXP_SEQ)) {
	  struct skbuff *tmp;
	  
	  add_from_skb(a_tcp, rcv, snd, pakiet->data,
		       pakiet->len, pakiet->seq, pakiet->fin, pakiet->urg,
		       pakiet->urg_ptr + pakiet->seq - 1);
	  rcv->rmem_alloc -= pakiet->truesize;
	  if (pakiet->prev)
	    pakiet->prev->next = pakiet->next;
	  else
	    rcv->list = pakiet->next;
	  if (pakiet->next)
	    pakiet->next->prev = pakiet->prev;
	  else
	    rcv->listtail = pakiet->prev;
	  tmp = pakiet->next;
	  free(pakiet->data);
	  free(pakiet);
	  pakiet = tmp;
	}
	else
	  pakiet = pakiet->next;
      }
   
  }

 }

 else if(this_tcphdr->th_flags & TH_FIN  ||  this_tcphdr->th_flags & TH_RST )
      {       
           pakiet = rcv->list;
           while (pakiet) {
	      struct skbuff *tmp;
	      add_from_skb(a_tcp, rcv, snd, pakiet->data,
		       pakiet->len, pakiet->seq, pakiet->fin, pakiet->urg,
		       pakiet->urg_ptr + pakiet->seq - 1);
	      rcv->rmem_alloc -= pakiet->truesize;
	      if (pakiet->prev)
	         pakiet->prev->next = pakiet->next;
	      else
	         rcv->list = pakiet->next;
	      if (pakiet->next)
	         pakiet->next->prev = pakiet->prev;
	      else
	          rcv->listtail = pakiet->prev;
	      tmp = pakiet->next;
	      free(pakiet->data);
	      free(pakiet);
	      pakiet = tmp;   
         }
         //free_tcp(a_tcp);   
   
      }
  else
 {
    struct skbuff *p = rcv->listtail;

    pakiet = mknew(struct skbuff);
    pakiet->truesize = skblen;
    rcv->rmem_alloc += pakiet->truesize;
    pakiet->len = datalen;
    pakiet->data = malloc(datalen);
    if (!pakiet->data)
      nids_params.no_mem("tcp_queue");
    memcpy(pakiet->data, data, datalen);
    pakiet->fin = (this_tcphdr->th_flags & TH_FIN);
    pakiet->seq = this_seq;
    pakiet->urg = (this_tcphdr->th_flags & TH_URG);
    pakiet->urg_ptr = ntohs(this_tcphdr->th_urp);
    for (;;) {
    /*
       if (!p || !after(p->seq, this_seq))
	break;
    */
      if( !p )
         break;
    
      if ( !after(p->seq, this_seq))   
      { 
        
        if(  p->seq != this_seq){
           
	    break;
	}
	else {
	 if(p->len > datalen)
	        break;
	}//if_else

      }//if
      
      p = p->prev;
    }//for
    if (!p) {
      pakiet->prev = 0;
      pakiet->next = rcv->list;
      if (rcv->list)
         rcv->list->prev = pakiet;
      rcv->list = pakiet;
      if (!rcv->listtail)
	rcv->listtail = pakiet;
    }
    else {
      pakiet->next = p->next;
      p->next = pakiet;
      pakiet->prev = p;
      if (pakiet->next)
	pakiet->next->prev = pakiet;
      else
	rcv->listtail = pakiet;
    }
  }
}
示例#15
0
文件: tcp.c 项目: carriercomm/GNP3C
void process_tcp(u_char * data, int skblen)
{
//   printf("into process_tcp\n");
  struct ip *this_iphdr = (struct ip *)data;
  struct tcphdr *this_tcphdr = (struct tcphdr *)(data + 4 * this_iphdr->ip_hl);
  int datalen, iplen;
  int from_client = 1;
  unsigned int tmp_ts;
  struct tcp_stream *a_tcp;
  struct half_stream *snd, *rcv;

  ugly_iphdr = this_iphdr;
  iplen = ntohs(this_iphdr->ip_len);
  if ((unsigned)iplen < 4 * this_iphdr->ip_hl + sizeof(struct tcphdr)) {
    nids_params.syslog(NIDS_WARN_TCP, NIDS_WARN_TCP_HDR, this_iphdr,
		       this_tcphdr);
    return;
  } // ktos sie bawi
  
  datalen = iplen - 4 * this_iphdr->ip_hl - 4 * this_tcphdr->th_off;
  
  if (datalen < 0) {
    nids_params.syslog(NIDS_WARN_TCP, NIDS_WARN_TCP_HDR, this_iphdr,
		       this_tcphdr);
    return;
  } // ktos sie bawi

  if ((this_iphdr->ip_src.s_addr | this_iphdr->ip_dst.s_addr) == 0) {
    nids_params.syslog(NIDS_WARN_TCP, NIDS_WARN_TCP_HDR, this_iphdr,
		       this_tcphdr);
    return;
  }
  /*
  if (!(this_tcphdr->th_flags & TH_ACK))
    detect_scan(this_iphdr);
  */  
if (!nids_params.n_tcp_streams) return;
  if (my_tcp_check(this_tcphdr, iplen - 4 * this_iphdr->ip_hl,
		   this_iphdr->ip_src.s_addr, this_iphdr->ip_dst.s_addr)) {
    nids_params.syslog(NIDS_WARN_TCP, NIDS_WARN_TCP_HDR, this_iphdr,
		       this_tcphdr);
    //return;
  }
#if 0
  check_flags(this_iphdr, this_tcphdr);
//ECN
#endif
  if (!(a_tcp = find_stream(this_tcphdr, this_iphdr, &from_client))) {
    if ((this_tcphdr->th_flags & TH_SYN) &&
	!(this_tcphdr->th_flags & TH_ACK) &&
	!(this_tcphdr->th_flags & TH_RST))
      add_new_tcp(this_tcphdr, this_iphdr);
//     printf("add new\n");
    return;
  }
//   printf("tcp exist\n");

  if (from_client) {
    snd = &a_tcp->client;
    rcv = &a_tcp->server;
  }
  else {
    rcv = &a_tcp->client;
    snd = &a_tcp->server;
  }
  if ((this_tcphdr->th_flags & TH_SYN)) {
    if (from_client || a_tcp->client.state != TCP_SYN_SENT ||
      a_tcp->server.state != TCP_CLOSE || !(this_tcphdr->th_flags & TH_ACK))
      return;
    if (a_tcp->client.seq != ntohl(this_tcphdr->th_ack))
      return;
    a_tcp->server.state = TCP_SYN_RECV;
    a_tcp->server.seq = ntohl(this_tcphdr->th_seq) + 1;
    a_tcp->server.first_data_seq = a_tcp->server.seq;
    a_tcp->server.ack_seq = ntohl(this_tcphdr->th_ack);
    a_tcp->server.window = ntohs(this_tcphdr->th_win);
    if (a_tcp->client.ts_on) {
    	a_tcp->server.ts_on = get_ts(this_tcphdr, &a_tcp->server.curr_ts);
	if (!a_tcp->server.ts_on)
		a_tcp->client.ts_on = 0;
    } else a_tcp->server.ts_on = 0;	
    if (a_tcp->client.wscale_on) {
    	a_tcp->server.wscale_on = get_wscale(this_tcphdr, &a_tcp->server.wscale);
	if (!a_tcp->server.wscale_on) {
		a_tcp->client.wscale_on = 0;
		a_tcp->client.wscale  = 1;
		a_tcp->server.wscale = 1;
	}	
    } else {
    	a_tcp->server.wscale_on = 0;	
    	a_tcp->server.wscale = 1;
    }	
    return;
  }
  if (
  	! (  !datalen && ntohl(this_tcphdr->th_seq) == rcv->ack_seq  )
  	&&
  	( !before(ntohl(this_tcphdr->th_seq), rcv->ack_seq + rcv->window*rcv->wscale) ||
          before(ntohl(this_tcphdr->th_seq) + datalen, rcv->ack_seq)  
        )
     )     
     return;

  if ((this_tcphdr->th_flags & TH_RST)) {
    if (a_tcp->nids_state == NIDS_DATA) {
      struct lurker_node *i;
      
      a_tcp->nids_state = NIDS_RESET;
      for (i = a_tcp->listeners; i; i = i->next)
	(i->item) (a_tcp, &i->data);
    }
    free_tcp(a_tcp);
    return;
  }

  /* PAWS check */
  if (rcv->ts_on && get_ts(this_tcphdr, &tmp_ts) && 
  	before(tmp_ts, snd->curr_ts))
  return; 	
  
  if ((this_tcphdr->th_flags & TH_ACK)) {
    if (from_client && a_tcp->client.state == TCP_SYN_SENT &&
	a_tcp->server.state == TCP_SYN_RECV) {
      if (ntohl(this_tcphdr->th_ack) == a_tcp->server.seq) {
	a_tcp->client.state = TCP_ESTABLISHED;
	a_tcp->client.ack_seq = ntohl(this_tcphdr->th_ack);
	{
	  struct proc_node *i;
	  struct lurker_node *j;
	  void *data;
	  
	  a_tcp->server.state = TCP_ESTABLISHED;
	  a_tcp->nids_state = NIDS_JUST_EST;
	  for (i = tcp_procs; i; i = i->next) {
	    char whatto = 0;
	    char cc = a_tcp->client.collect;
	    char sc = a_tcp->server.collect;
	    char ccu = a_tcp->client.collect_urg;
	    char scu = a_tcp->server.collect_urg;
	    
	    (i->item) (a_tcp, &data);
	    if (cc < a_tcp->client.collect)
	      whatto |= COLLECT_cc;
	    if (ccu < a_tcp->client.collect_urg)
	      whatto |= COLLECT_ccu;
	    if (sc < a_tcp->server.collect)
	      whatto |= COLLECT_sc;
	    if (scu < a_tcp->server.collect_urg)
	      whatto |= COLLECT_scu;
	    if (nids_params.one_loop_less) {
	    		if (a_tcp->client.collect >=2) {
	    			a_tcp->client.collect=cc;
	    			whatto&=~COLLECT_cc;
	    		}
	    		if (a_tcp->server.collect >=2 ) {
	    			a_tcp->server.collect=sc;
	    			whatto&=~COLLECT_sc;
	    		}
	    }  
	    if (whatto) {
	      j = mknew(struct lurker_node);
	      j->item = i->item;
	      j->data = data;
	      j->whatto = whatto;
	      j->next = a_tcp->listeners;
	      a_tcp->listeners = j;
	    }
	  }
	  if (!a_tcp->listeners) {
	    free_tcp(a_tcp);
	    return;
	  }
	  a_tcp->nids_state = NIDS_DATA;
	}
      }
      // return;
    }
  }
示例#16
0
文件: misc.c 项目: BADSEC/multitail
void statistics_menu(void)
{
	NEWWIN *mywin = create_popup(23, 65);
	int offset = 0, cur_line = 0;

	for(;;)
	{
		int c;
		int vmsize = get_vmsize(getpid());
		time_t now = time(NULL);
		struct tm *tmnow = localtime(&now);
		proginfo **plist = NULL;
		char     *issub = NULL;
		int      *winnr = NULL;
		int loop, nwin = 0;

		/* create list of (sub-)windows */
		for(loop=0; loop<nfd; loop++)
		{
			proginfo *cur = &pi[loop];

			while(cur)
			{
				plist = (proginfo **)myrealloc(plist, (nwin + 1) * sizeof(proginfo *));
				issub = (char *)     myrealloc(issub, (nwin + 1) * sizeof(char)      );
				winnr = (int *)      myrealloc(winnr, (nwin + 1) * sizeof(int)       );

				plist[nwin] = cur;
				issub[nwin] = (cur != &pi[loop]);
				winnr[nwin] = loop;
				nwin++;

				cur = cur -> next;
			}
		}

		werase(mywin -> win);
		win_header(mywin, "Statistics");

		for(loop=0; loop<18; loop++)
		{
			int cur_index = loop + offset;
			int is_sub_indent;

			if (cur_index >= nwin) break;

			is_sub_indent = issub[cur_index];

			if (loop == cur_line) ui_inverse_on(mywin);
			if (is_sub_indent)
				mvwprintw(mywin -> win, 2 + loop, 7, "%s", shorten_filename(plist[cur_index] -> filename, 54));
			else
				mvwprintw(mywin -> win, 2 + loop, 2, "[%02d] %s", winnr[cur_index], shorten_filename(plist[cur_index] -> filename, 56));
			if (loop == cur_line) ui_inverse_off(mywin);
		}

		mvwprintw(mywin -> win, 20, 2, "Run-time: %.2f hours  %02d:%02d", (get_ts() - mt_started) / 3600.0, tmnow -> tm_hour, tmnow -> tm_min);
		if (vmsize != -1)
		{
			char *vmsize_str = amount_to_str(vmsize);
			mvwprintw(mywin -> win, 20, 35, "Memory usage: %s", vmsize_str);
			myfree(vmsize_str);
		}
		escape_print(mywin, 21, 2, "Press ^r^ to reset counters, ^q^ to exit");

		draw_border(mywin);
		mydoupdate();

		c = toupper(wait_for_keypress(HELP_STATISTICS, popup_refresh_interval, mywin, 1));

		if (c == 'R')
		{
			for(loop=0; loop<nfd; loop++)
			{
				proginfo *cur = &pi[loop];

				while(cur)
				{
					reset_counters(&cur -> statistics);

					cur = cur -> next;
				}
			}
		}
		else if (c == KEY_UP)
		{
			if (cur_line)
				cur_line--;
			else if (offset)
				offset--;
			else
				wrong_key();
		}
		else if (c == KEY_DOWN)
		{
			if ((cur_line + offset) < (nwin - 1))
			{
				if (cur_line < (18 - 1))
					cur_line++;
				else
					offset++;
			}
			else
				wrong_key();

		}
		else if (c == 13 || c == ' ')
		{
			statistics_popup(winnr[cur_line + offset], plist[cur_line + offset]);
		}
		else if (c == 'Q' || c == abort_key)
		{
			myfree(plist);
			myfree(issub);
			myfree(winnr);
			break;
		}
		else if (c != -1)
		{
			wrong_key();
		}

		myfree(plist);
		myfree(issub);
		myfree(winnr);
	}

	delete_popup(mywin);
}
示例#17
0
void debug_console::tick(processor *p)
{
	n_ticks++;

	if (!refresh_limit_valid)
	{
		double now_ts = get_ts();
		double t_diff = now_ts - start_ts;

		// first second: ignore as the cpu might need to come out of
		// reduced clock frequency (linux: "ondemand" scaling governor)
		if (t_diff >= 1.0)
			refresh_limit++;

		if (t_diff >= 1.0 + 1.0 / double(SCREEN_REFRESHES_PER_SECOND))
		{
			dc_log("Refresh screen every %d instructions", refresh_limit);
			refresh_limit_valid = true;
		}
	}

	uint64_t PC = p -> is_delay_slot() ? p -> get_delay_slot_PC() : p -> get_PC();

	uint32_t instruction = -1;
	bool r_ok = true;
	try
	{
		p -> get_mem_32b(PC, &instruction);
	}
	catch(processor_exception & pe)
	{
		dc_log("EXCEPTION %d at/for %016llx, PC: %016llx (3), sr: %08x", pe.get_cause(), pe.get_BadVAddr(), pe.get_EPC(), pe.get_status());

		r_ok = false;
	}

	std::string logline = p -> da_logline(instruction);
	dolog(logline.c_str());

	std::string decoded = p -> decode_to_text(instruction);

#ifdef _DEBUG
	unsigned int space = decoded.find(' ');
	if (space == std::string::npos)
		space = decoded.length();

	std::string instruction_name = decoded.substr(0, space);

	std::map<std::string, long int>::iterator found = instruction_counts.find(instruction_name);

	if (found != instruction_counts.end())
		found -> second++;
	else
		instruction_counts.insert(std::pair<std::string, long int>(instruction_name, 1));
#endif

	if ((++refresh_counter >= refresh_limit && refresh_limit_valid == true) || single_step)
	{
		double now_ts = get_ts();

		if (term_change)
			recreate_terminal();

		int x = -1, y = -1;
		for(int registers=0; registers<32; registers++)
		{
			if (registers < 16)
			{
				x = 0;
				y = registers;
			}
			else
			{
				x = 22;
				y = registers - 16;
			}

			mvwprintw(win_regs, y, x, "%s %016llx", registers == 0 ? "0  " : processor::reg_to_name(registers), p -> get_register_64b_unsigned(registers));
		}

		mvwprintw(win_regs, 0, 44, "PC: %016llx %c", PC, p -> is_delay_slot() ? 'D' : '.');
		mvwprintw(win_regs, 1, 44, "LO: %016llx", p -> get_LO());
		mvwprintw(win_regs, 2, 44, "HI: %016llx", p -> get_HI());
		mvwprintw(win_regs, 3, 44, "SR: %016llx", p -> get_SR());

		mvwprintw(win_regs, 4, 44, "mem: %d/%08x", r_ok, instruction);

		int opcode = (instruction >> 26) & MASK_6B;
		int function = instruction & MASK_6B;
		int sa = processor::get_SA(instruction);
		int rd = processor::get_RD(instruction);
		int rt = processor::get_RT(instruction);
		int rs = processor::get_RS(instruction);
		int immediate = processor::get_immediate(instruction);
		int b18_signed_offset = processor::get_SB18(instruction);
		mvwprintw(win_regs,  5, 44, "op: %02x  rs: %02x", opcode, rs);
		mvwprintw(win_regs,  6, 44, "rt: %02x  rd: %02x", rt, rd);
		mvwprintw(win_regs,  7, 44, "sa: %02x  fu: %02d", sa, function);
		mvwprintw(win_regs,  8, 44, "im: %04x  of: %d", immediate, b18_signed_offset);

		mvwprintw(win_regs,  9, 44, ">                       ");
		mvwprintw(win_regs,  9, 44, "> %s", decoded.c_str());

		double t_diff = now_ts - start_ts;
		if (t_diff)
		{
			double i_per_s = double(n_ticks) / t_diff;

			if (i_per_s >= 1000000000.0)
				mvwprintw(win_regs, 10, 44, "I/S: %6.2fG", i_per_s / 1000000000.0);
			else if (i_per_s >= 1000000.0)
				mvwprintw(win_regs, 10, 44, "I/S: %6.2fM", i_per_s / 1000000.0);
			else if (i_per_s >= 1000.0)
				mvwprintw(win_regs, 10, 44, "I/S: %6.2fk", i_per_s / 1000.0);
			else
				mvwprintw(win_regs, 10, 44, "I/S: %6.2f", i_per_s);
		}

		if (n_ticks >= 1000000000)
			mvwprintw(win_regs, 11, 44, "cnt: %7.2fG", double(n_ticks) / 1000000000.0);
		else if (n_ticks >= 1000000)
			mvwprintw(win_regs, 11, 44, "cnt: %7.2fM", double(n_ticks) / 1000000.0);
		else if (n_ticks >= 1000)
			mvwprintw(win_regs, 11, 44, "cnt: %7.2fk", double(n_ticks) / 1000.0);
		else
			mvwprintw(win_regs, 11, 44, "cnt: %lld", n_ticks);

			mvwprintw(win_regs, 11, 44, "cnt: %lld", n_ticks);

		const memory_bus *pmb = p -> get_memory_bus();
		mvwprintw(win_regs, 12, 44, "I_S: %016x", pmb -> get_cur_segment_i());
		mvwprintw(win_regs, 13, 44, "D_S: %016x", pmb -> get_cur_segment());

		if (had_logging)
		{
			wnoutrefresh(win_logs);
			had_logging = false;
		}

		wnoutrefresh(win_regs);
		doupdate();

		if (refresh_limit_valid)
			refresh_counter = 0;
	}
示例#18
0
文件: example.cpp 项目: gbiggs/hdf5r
void round_one()
{
    std::cout << "Creating new file test.hdf5r\n";
    // Open the HDF5 file
    hdf5r::HDF5R f("test.hdf5r", hdf5r::TRUNCATE);

    // Show the number of channels - it will be zero for a new file
    std::cout << "Number of channels in the file: " << f.channels().size() <<
        '\n';

    // Add a couple of channels of varying type
    std::cout << "Adding channel 'integers' to log\n";
    hdf5r::ChannelID int_chan = f.add_channel("integers", "int", "thin_air",
            H5T_NATIVE_INT, H5T_STD_I64LE);
    std::cout << "Adding channel 'floats' to log\n";
    hdf5r::ChannelID float_chan = f.add_channel("floats", "float",
            "thinner_air", H5T_NATIVE_FLOAT, H5T_IEEE_F32LE);

    std::cout << "Number of channels in the file: " << f.channels().size() <<
        '\n';

    // Put some data into the channels
    std::cout << "Writing some data\n";
    int int_data[] = {1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
    float float_data[] = {2.7182818284590451, 7.3890560989306495,
        20.085536923187664, 54.598150033144229, 148.41315910257657,
        403.428793492735, 1096.6331584284583, 2980.9579870417269,
        8103.0839275753797, 22026.465794806703};
    f.add_entry(int_chan, get_ts(), &int_data[0]);
    f.add_entry(int_chan, get_ts(), &int_data[1]);
    f.add_entry(float_chan, get_ts(), &float_data[0]);
    f.add_entry(int_chan, get_ts(), &int_data[2]);
    f.add_entry(float_chan, get_ts(), &float_data[1]);
    f.add_entry(float_chan, get_ts(), &float_data[2]);
    f.add_entry(float_chan, get_ts(), &float_data[3]);
    f.add_entry(float_chan, get_ts(), &float_data[4]);
    f.add_entry(int_chan, get_ts(), &int_data[3]);
    f.add_entry(float_chan, get_ts(), &float_data[5]);
    f.add_entry(int_chan, get_ts(), &int_data[4]);
    f.add_entry(float_chan, get_ts(), &float_data[6]);
    f.add_entry(int_chan, get_ts(), &int_data[5]);
    f.add_entry(int_chan, get_ts(), &int_data[6]);
    f.add_entry(int_chan, get_ts(), &int_data[7]);
    f.add_entry(float_chan, get_ts(), &float_data[7]);
    f.add_entry(int_chan, get_ts(), &int_data[8]);
    f.add_entry(float_chan, get_ts(), &float_data[8]);
    f.add_entry(int_chan, get_ts(), &int_data[9]);
    f.add_entry(float_chan, get_ts(), &float_data[9]);

    // Add a couple of tags
    std::cout << "Setting tags\n";
    f.set_text_tag("TITLE", "Sample HDF5R log");
    f.set_text_tag("LIB_NAME", "hdf5r 1.0");

    std::cout << "Closing file\n\n";
}
示例#19
0
文件: misc.c 项目: BADSEC/multitail
void info(void)
{
	NEWWIN *mywin = create_popup(19, 60);
	int line = 7;
	struct utsname uinfo;
	int proc_u_line;
	char *term = getenv("TERM");

	mvwprintw(mywin -> win, 1, 2, "-=* MultiTail " VERSION " *=-");
	mvwprintw(mywin -> win, 3, 2, "Written by [email protected]");
	mvwprintw(mywin -> win, 4, 2, "Website: http://www.vanheusden.com/multitail/");
	if (!use_colors)
		mvwprintw(mywin -> win, line++, 2, "Your terminal doesn't support colors");

	if (uname(&uinfo) == -1)
		error_popup("Retrieving system information", -1, "uname() failed\n");
	else
	{
		line++;
		mvwprintw(mywin -> win, line++, 2, "Running on:");
#ifdef _GNU_SOURCE
		mvwprintw(mywin -> win, line++, 2, "%s/%s %s %s", uinfo.nodename, uinfo.sysname, uinfo.machine, uinfo.domainname);
#else
		mvwprintw(mywin -> win, line++, 2, "%s/%s %s", uinfo.nodename, uinfo.sysname, uinfo.machine);
#endif
		mvwprintw(mywin -> win, line++, 2, "%s %s", uinfo.release, uinfo.version);
		line++;
	}

	if (has_colors())
		mvwprintw(mywin -> win, line++, 2, "colors: %d, colorpairs: %d (%d), change colors: %s", COLORS, COLOR_PAIRS, cp.n_def, can_change_color()?"yes":"no");
	else
		mvwprintw(mywin -> win, line++, 2, "Terminal does not support colors.");
	if (term)
		mvwprintw(mywin -> win, line++, 2, "Terminal size: %dx%d, terminal: %s", max_x, max_y, term);
	else
		mvwprintw(mywin -> win, line++, 2, "Terminal size: %dx%d", max_x, max_y);

	if (beep_interval > 0)
		mvwprintw(mywin -> win, line++, 2, "Did %d beeps.", did_n_beeps);

	proc_u_line = line++;

	escape_print(mywin, 16, 2, "_Press any key to exit this screen_");

#if defined(__FreeBSD__) || defined(linux) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(sun) || defined(__sun) || defined(__GNU__) || defined(__CYGWIN__)
	for(;;)
	{
		dtime_t run_time = get_ts() - mt_started;
#ifndef __CYGWIN__
		double v1, v2, v3;

		get_load_values(&v1, &v2, &v3);
		mvwprintw(mywin -> win, 6, 2, "Current load of system: %f %f %f", v1, v2, v3);
#endif

		if (run_time)
		{
			struct rusage usage;

			if (getrusage(RUSAGE_SELF, &usage) == -1)
				error_exit(TRUE, FALSE, "getrusage() failed\n");

			mvwprintw(mywin -> win, proc_u_line, 2, "Runtime: %02d:%02d:%02d, avg.proc.usage: %.2f%% ints/s: %.1f",
					(int)(run_time / 3600), ((int)run_time / 60) % 60, (int)run_time % 60,
					((double)usage.ru_utime.tv_sec + (double)usage.ru_utime.tv_usec / 1000000.0 + 
					 (double)usage.ru_stime.tv_sec + (double)usage.ru_stime.tv_usec / 1000000.0) * 100.0 / run_time,
					 (double)total_wakeups / run_time);
		}

		mydoupdate();

		if (wait_for_keypress(-1, popup_refresh_interval, mywin, 0) != -1)
			break;
	}
#else
	mydoupdate();
	wait_for_keypress(-1, 0, mywin, 0);
#endif

	delete_popup(mywin);
}
示例#20
0
//  Main
int
main (int argc, char **argv)
{
        //  Do some initial sanity checking
        assert (TIME_BITLEN + MACHINE_BITLEN + SEQ_BITLEN == 64);

        //  Parse command-line arguments
        int opt;
        int has_port_opt = 0;
        int has_machine_opt = 0;
        int has_config_file_opt = 0;
        int has_daemonize_opt = 0;
        int machine_specified = 0;

        const char *config_file_path;
        int port = DEFAULT_PORT;
        uint64_t machine;
        
        while ((opt = getopt (argc, argv, "hp:m:f:d")) != -1) {
                switch (opt) {
                case 'h':
                        print_help ();
                        exit (EXIT_SUCCESS);
                case 'p':
                        has_port_opt = 1;
                        port = atoi (optarg);
                        break;
                case 'm':
                        has_machine_opt = 1;
                        machine = atoll (optarg);
                        machine_specified = 1;
                        break;
                case 'f':
                        has_config_file_opt = 1;
                        config_file_path = optarg;
                        break;
                case 'd':
                        has_daemonize_opt = 1;
                        break;
                }
        }

        //  Read the config file
        if (has_config_file_opt) {
                config_t cfg;

                config_init (&cfg);

                if (!config_read_file (&cfg, config_file_path)) {
                        config_destroy (&cfg);
                        fprintf (stderr, "Invalid config file\n");
                        exit (EXIT_FAILURE);
                }

                long unsigned int machine_from_file;
                if (config_lookup_int (&cfg, "machine", &machine_from_file) && !has_machine_opt) {
                        machine_specified = 1;
                        machine = (uint64_t) machine_from_file;
                }

                long unsigned int port_from_file;
                if (config_lookup_int (&cfg, "port", &port_from_file) && !has_port_opt)
                        port = (int) port_from_file;

                
        }

        //  Sanity check the machine number
        if (!machine_specified) {
                fprintf (stderr, "No machine number specified.\n");
                exit (EXIT_FAILURE);
        }
        else if (machine > MACHINE_MAX) {
                fprintf (stderr, "Machine number too large. Cannot be greater than %llu\n", MACHINE_MAX);
                exit (EXIT_FAILURE);
        }

        //  Daemonize
        static char *pid_file_path = "/var/run/znowflaked.pid";
        int pid_file;
        
        if (has_daemonize_opt) {
                pid_t pid, sid;

                pid = fork ();
                if (pid < 0) {
                        exit (EXIT_FAILURE);
                }
                if (pid > 0) {
                        exit (EXIT_SUCCESS);
                }

                umask (0);
                
                sid = setsid ();
                if (sid < 0) {
                        exit (EXIT_FAILURE);
                }
        
                if ((chdir ("/")) < 0) {
                        exit (EXIT_FAILURE);
                }

                //  Create and lock the pid file
                pid_file = open (pid_file_path, O_CREAT | O_RDWR, 0666);
                if (pid_file > 0) {
                        int rc = lockf (pid_file, F_TLOCK, 0);
                        if (rc) {
                                switch (errno) {
                                case EACCES:
                                case EAGAIN:
                                        fprintf (stderr, "PID file already locked\n");
                                        break;
                                case EBADF:
                                        fprintf (stderr, "Bad pid file\n");
                                        break;
                                default:
                                        fprintf (stderr, "Could not lock pid file\n");
                                }
                                exit (EXIT_FAILURE);
                        }

                        char *pid_string = NULL;
                        int pid_string_len = asprintf (&pid_string, "%ld", (long) getpid ());
                        write (pid_file, pid_string, pid_string_len);
                }
        
                close (STDIN_FILENO);
                close (STDOUT_FILENO);
                close (STDERR_FILENO);
        }

        //  Sleep for 1ms to prevent collisions
        struct timespec ms;
        ms.tv_sec = 0;
        ms.tv_nsec = 1000000;
        nanosleep (&ms, NULL);

        //  Initialize ZeroMQ
        zctx_t *context = zctx_new ();
        assert (context);
        void *socket = zsocket_new (context, ZMQ_REP);
        assert (socket);
        assert (streq (zsocket_type_str (socket), "REP"));
        int rc = zsocket_bind (socket, "tcp://*:%d", port);
        if (rc != port) {
                printf ("E: bind failed: %s\n", strerror (errno));
                exit (EXIT_FAILURE);
        }

        //  Start remembering the last timer tick
        uint64_t ts = 0;
        uint64_t last_ts = 0;
        uint64_t seq = 0;

        //  Main loop
        s_catch_signals ();        
        while (1) {
                //  Wait for the next request
                zmsg_t *request_msg = zmsg_new ();
                assert (request_msg);
                request_msg = zmsg_recv (socket);
                assert (request_msg);
                zmsg_destroy (&request_msg);

                //  Grab a time click
                last_ts = ts;
                ts = get_ts ();

                //  Make sure the system clock wasn't reversed on us
                if (ts < last_ts) {
                        //  Wait until it catches up
                        while (ts <= last_ts) {
                                nanosleep (&ms, NULL);
                                ts = get_ts ();
                        }
                }

                //  Increment the sequence number
                if (ts != last_ts) {
                        //  We're in a new time click, so reset the sequence
                        seq = 0;
                }
                else if (seq == SEQ_MAX) {
                        //  Wrapped sequence, so wait for the next time tick
                        seq = 0;
                        nanosleep (&ms, NULL);
                }
                else {
                        //  Still in the same time click
                        seq++;
                }

                //  Build the ID and put it in network byte order
                uint64_t id = build_id (ts, machine, seq);
                uint64_t id_be64 = htobe64 (id);

                //  Reply
                zmsg_t *reply_msg = zmsg_new ();
                assert (reply_msg);
                zframe_t *frame = zframe_new (&id_be64, 8);
                assert (frame);
                zmsg_push (reply_msg, frame);
                assert (zmsg_size (reply_msg) == 1);
                assert (zmsg_content_size (reply_msg) == 8);
                zmsg_send (&reply_msg, socket);
                assert (reply_msg == NULL);

                //  Exit program
                if (s_interrupted) {
                        printf ("interrupt received, killing server…\n");
                        break;
                }
        }
        zctx_destroy (&context);
        if (has_daemonize_opt) {
                if (pid_file > 0) {
                        unlink (pid_file_path);
                        close (pid_file);
                }
        }
        exit (EXIT_SUCCESS);
}
int main(int argc, char *argv[])
{

    if(argc < 2)
        printf("usage: %s matroska_filename\n", argv[0]);

    char* filename = argv[1];
    
    uint8_t* in_frame = calloc(800*600,1);
    
    FILE *fp;
    if ((fp = fopen(filename,"rb"))!=NULL) {  // (rb) read in binary mode
        printf("opening %s\n", filename);
    } else {
        printf("couldn't open %s for read\n",filename);
        free(in_frame);
        return (-1);
    }
    int i = 0;
    uint64_t timecode_scale = 0;
    uint64_t cluster_file_pos = 0;
    uint64_t end_cluster_file_pos = 0;
    uint64_t cluster_ts = 0;
    uint64_t block_ts = 0;
    uint32_t ID = 0x00000000;
    int next_byte = 0;
    uint64_t uisize = 0;
    uint64_t frame_n = 0;
    uint64_t seg_inf_size = 0;
    uint64_t seg_inf_pos = 0;
    uint64_t tracks_size = 0;
    uint64_t tracks_pos = 0;
    uint64_t tmp_size = 0;
    uint64_t tmp_pos = 0;
    
    int video_track = 1;
    //EBML HEADER ID
    do
    {
        next_byte = fgetc(fp);
        if(next_byte != EOF)
        {
            next_byte &= 0x000000ff;
            ID <<= 8;
            ID &= 0xffffff00;
            ID += next_byte;
        }
        else
        {
            if(ferror(fp))
                printf("An error ocurred when reading the file\n");
                
            fclose(fp);
            free(in_frame);
            return(-2);
        }
    }
    while(ID != EBML_ID_HEADER);
    tmp_size = get_size(fp);
    printf("ebml header size:%llu - skipping\n", tmp_size);
    //skip ebml header
    fseeko(fp, tmp_size, SEEK_CUR);
    
    //search for timecode scale in segment info
    //SEGMENT ID
    do
    {
        next_byte = fgetc(fp);
        if(next_byte != EOF)
        {
            next_byte &= 0x000000ff;
            ID <<= 8;
            ID &= 0xffffff00;
            ID += next_byte;
        }
        else
        {
            if(ferror(fp))
                printf("An error ocurred when reading the file\n");
                
            fclose(fp);
            free(in_frame);
            return(-2);
        }
    }
    while(ID != MATROSKA_ID_SEGMENT);
    //SEGMENT INFO ID
    do
    {
        next_byte = fgetc(fp);
        if(next_byte != EOF)
        {
            next_byte &= 0x000000ff;
            ID <<= 8;
            ID &= 0xffffff00;
            ID += next_byte;
        }
        else
        {
            if(ferror(fp))
                printf("An error ocurred when reading the file\n");
                
            fclose(fp);
            free(in_frame);
            return(-2);
        }
    }
    while(ID != MATROSKA_ID_INFO);
    seg_inf_size = get_size(fp);
    seg_inf_pos = ftello(fp);
    //TIMECODE SCALE ID
    do
    {
        next_byte = fgetc(fp);
        if(next_byte != EOF)
        {
            next_byte &= 0x000000ff;
            ID <<= 8;
            ID &= 0x00ffff00;
            ID += next_byte;
        }
        else
        {
            if(ferror(fp))
                printf("An error ocurred when reading the file\n");
                
            fclose(fp);
            free(in_frame);
            return(-2);
        }
    }
    while((ID != MATROSKA_ID_TIMECODESCALE) && (ftello(fp) < (seg_inf_pos + seg_inf_size)));
    
    //get timecode scale
    int ts_size = get_size(fp);
    for(i=0; i< ts_size; i++)
    {
        next_byte = fgetc(fp);
        if(next_byte != EOF)
        {
            next_byte &= 0x000000ff;
            timecode_scale <<= 8;
            timecode_scale &= 0xffffffffffffff00;
            timecode_scale += next_byte;
        }
        else
        {
            if(ferror(fp))
                printf("An error ocurred when reading the file\n");
                
            fclose(fp);
            free(in_frame);
            return(-2);
        }
    }
    
    printf("timecode scale is %llu\n", timecode_scale);
    
    //SEGMENT TRACKS
    do
    {
        next_byte = fgetc(fp);
        if(next_byte != EOF)
        {
            next_byte &= 0x000000ff;
            ID <<= 8;
            ID &= 0xffffff00;
            ID += next_byte;
        }
        else
        {
            if(ferror(fp))
                printf("An error ocurred when reading the file\n");
                
            fclose(fp);
            free(in_frame);
            return(-2);
        }
    }
    while(ID != MATROSKA_ID_TRACKS);
    tracks_size = get_size(fp);
    tracks_pos = ftello(fp);
    
    //printf("tracks info size: %llu - skip to pos %llu\n", tmp_size, tmp_pos+tmp_size);
    //skip segment tracks header
    //fseeko(fp, tmp_size, SEEK_CUR);
    int track_n = 1;
    int is_video = 0;
    do
    {
        next_byte = fgetc(fp);
        if(next_byte != EOF)
        {
            next_byte &= 0x000000ff;
            
            if(next_byte == MATROSKA_ID_TRACKENTRY)
            {
                //check track number and type
                //if its a video track register number and skip rest of tracks header
                tmp_size = get_size(fp);
                tmp_pos = ftello(fp);
                track_n = 0;
                int skip = 0;
                do
                {
                    next_byte = fgetc(fp);
                    if(next_byte != EOF)
                    {
                        next_byte &= 0x000000ff;
                        if(next_byte == MATROSKA_ID_TRACKNUMBER)
                        {
                            int nsize = get_size(fp);
                            track_n = get_ts(fp, nsize);
                        }
                        else if(next_byte == MATROSKA_ID_TRACKTYPE)
                        {
                            int nsize = get_size(fp);
                            if(get_ts(fp, nsize) == 1)
                                is_video = 1;
                            else
                                skip = 1; //skip track - not a video track
                        }
                        else if (next_byte == 0x73) //0x73c5 UID
                        {
                            next_byte = fgetc(fp);
                            if(next_byte != EOF)
                            {
                                next_byte &=0x000000ff;
                                if(next_byte == 0xc5) //track uid
                                {
                                    int uid_size = get_size(fp);
                                    fseeko(fp, uid_size, SEEK_CUR); //skip uid
                                }
                            }
                            else
                            {
                                if(ferror(fp))
                                    printf("An error ocurred when reading the file\n");
                
                                fclose(fp);
                                free(in_frame);
                                return(-2);
                            }
                        }
                        
                    }
                    else
                    {
                        if(ferror(fp))
                            printf("An error ocurred when reading the file\n");
                
                        fclose(fp);
                        free(in_frame);
                        return(-2);
                    }
                    
                    if(is_video && track_n)
                    {
                        video_track = track_n;
                        printf("video track at index %d\n", video_track);
                        break;
                    }
                }
                while((ftello(fp) < (tmp_pos + tmp_size)) && !skip);
                
                fseeko(fp, tmp_pos + tmp_size, SEEK_SET);
            }
        }
        else
        {
            if(ferror(fp))
                printf("An error ocurred when reading the file\n");
                
            fclose(fp);
            free(in_frame);
            return(-2);
        }
    }
    while((ftello(fp) < (tracks_pos + tracks_size)) && !is_video);
    
    //search for clusters
    while(1)
    {
        do 
        {
            next_byte = fgetc(fp);
            if(next_byte != EOF)
            {
                next_byte &= 0x000000ff;
                //if(ftello(fp) == 5553)
                //    printf("ID is 0x%08X next is 0x%08X\n", ID, next_byte);
                ID <<= 8;
                ID &= 0xffffff00;
                ID += next_byte;
            }
            else
            {
                if(ferror(fp))
                    printf("An error ocurred when reading the file\n");
                
                fclose(fp);
                free(in_frame);
                return(-2);
            }
        }
        while(ID != MATROSKA_ID_CLUSTER);
        
        cluster_file_pos = ftello(fp);
        printf("cluster found at position 0x%016X\n", cluster_file_pos-4);
        //get size
        end_cluster_file_pos = get_size(fp);
        end_cluster_file_pos += cluster_file_pos;
        
        next_byte = fgetc(fp);
        if(next_byte != EOF)
        {
            next_byte &= 0x000000ff;
        }
        else
        {
            if(ferror(fp))
                printf("An error ocurred when reading the file\n");
                
            fclose(fp);
            free(in_frame);
            return(-2);
        }
        
        if(next_byte == MATROSKA_ID_CLUSTERTIMECODE)
        {
            //printf("cluster time code found at position 0x%016X\n", ftello(fp));
            uisize = get_size(fp);
            cluster_ts = get_ts(fp, uisize);
            //printf("cluster timestamp is %llu ms\n", cluster_ts);
        }
        else
        {
            printf("found 0x%02X instead of 0xE7 - We must have arrived to the Seek Head block - finish\n", next_byte);
            printf("extracted %llu frames\n", frame_n);
            fclose(fp);
            free(in_frame);
            return (1);
        }
        
        uint64_t bgsize = 0;
        uint64_t bsize = 0;
        uint64_t fstart = 0;
        uint64_t fend = 0;
        uint64_t f_ts = 0;
        uint64_t block_start_pos = 0;
        //get frame time stamp and frame data
        do 
        {
            
            next_byte = fgetc(fp);
            if(next_byte != EOF)
            {
                next_byte &= 0x000000ff;
                if(next_byte == MATROSKA_ID_BLOCKGROUP)
                {
                    //printf("found block group at %llu \n", ftello(fp));
                    bgsize = get_size(fp);
                    next_byte = fgetc(fp);
                    if(next_byte != EOF)
                    {
                        next_byte &= 0x000000ff;
                        if(next_byte == MATROSKA_ID_BLOCK)
                        {
                            block_start_pos = ftello(fp);
                            //printf("found block at %llu \n", block_start_pos);
                            bsize = get_size(fp); //only 1 uint8_t (1-video 2-audio)
                            //video or audio ?
                            if(get_size(fp) == video_track)
                            {
                                printf("found video frame\n");
                                //timestamp - allways 2 bytes
                                f_ts = cluster_ts;
                                f_ts += get_frame_delta(fp);
                                //empty byte before frame
                                next_byte = fgetc(fp);
                                if(next_byte == EOF)
                                {
                                    if(ferror(fp))
                                        printf("An error ocurred when reading the file\n");
                
                                    fclose(fp);
                                    free(in_frame);
                                    return(-2);
                                }
                                if(next_byte != 0)
                                    printf("frame flags set to 0x%02X\n", next_byte);
                                
                                //frame
                                if( (bsize-4) > 0)
                                {
                                    fread(in_frame, 1, bsize-4, fp);
                                    char image_file[80];
                                    sprintf( image_file, "frame_%016llu_ts-%016llu.jpg", frame_n, f_ts );
                                    frame_n++;
                                    printf("saving %s\n", image_file);
                                    saveJPG(image_file, bsize-4, in_frame);
                                }
                                else
                                    printf("frame is empty - skip it\n");
                            }
                            else
                            {
                                printf("found non video frame - skip it\n");
                                fseeko(fp, bsize-1, SEEK_CUR);
                            }
                        }
                    }
                    else
                    {
                        if(ferror(fp))
                            printf("An error ocurred when reading the file\n");
                
                        fclose(fp);
                        free(in_frame);
                        return(-2);
                    }
                    
                }
                else
                if(next_byte == MATROSKA_ID_SIMPLEBLOCK)
                {
                    block_start_pos = ftello(fp);
                    printf("found simple block at %llu\n", block_start_pos);
                    bsize = get_size(fp);
                    //video or audio
                    if(get_size(fp) == video_track)
                    {
                        printf("found video frame\n");
                        //timestamp - allways 2 bytes
                        f_ts = cluster_ts;
                        f_ts += get_frame_delta(fp);
                        //empty byte before frame
                        next_byte = fgetc(fp);
                        if(next_byte == EOF)
                        {
                            if(ferror(fp))
                                printf("An error ocurred when reading the file\n");
                
                            fclose(fp);
                            free(in_frame);
                            return(-2);
                        }
                        if(next_byte != 0)
                            printf("frame flags set to 0x%02X \n", next_byte);
                                
                        //frame
                        if( (bsize-4) > 0)
                        {
                            fread(in_frame, 1, bsize-4, fp);
                            char image_file[80];
                            sprintf( image_file, "frame_%016llu_ts-%016llu.jpg", frame_n, f_ts );
                            frame_n++;
                            printf("saving %s\n", image_file);
                            saveJPG(image_file, bsize-4, in_frame);
                        }
                         else
                            printf("frame is empty - skip it\n");
                    }
                    else
                        printf("not a video frame - skip it\n");
                }
            }
            else
            {
                if(ferror(fp))
                    printf("An error ocurred when reading the file\n");
                
                fclose(fp);
                free(in_frame);
                return(-2);
            }
        }
        while( ftello(fp) < end_cluster_file_pos);
    }
    printf("extracted %llu frames\n", frame_n);
    fclose(fp);
    free(in_frame);
    return 0;
}
示例#22
0
static void
add_new_tcp(struct tcphdr * this_tcphdr, struct ip * this_iphdr)
{
  struct tcp_stream *tolink;
  struct tcp_stream *a_tcp;
  int hash_index;
  struct tuple4 addr;
  
  addr.source = ntohs(this_tcphdr->th_sport);
  addr.dest = ntohs(this_tcphdr->th_dport);
  addr.saddr = this_iphdr->ip_src.s_addr;
  addr.daddr = this_iphdr->ip_dst.s_addr;
  hash_index = mk_hash_index(addr);
  
  if (tcp_num > max_stream) {
    struct lurker_node *i;
    int orig_client_state=tcp_oldest->client.state;
    tcp_oldest->nids_state = NIDS_TIMED_OUT;
    for (i = tcp_oldest->listeners; i; i = i->next)
      (i->item) (tcp_oldest, &i->data);
    nids_free_tcp_stream(tcp_oldest);
    if (orig_client_state!=TCP_SYN_SENT)
      nids_params.syslog(NIDS_WARN_TCP, NIDS_WARN_TCP_TOOMUCH, ugly_iphdr, this_tcphdr);
  }
  a_tcp = free_streams;
  if (!a_tcp) {
    fprintf(stderr, "gdb me ...\n");
    pause();
  }
  free_streams = a_tcp->next_free;
  
  tcp_num++;
  tolink = tcp_stream_table[hash_index];
  memset(a_tcp, 0, sizeof(struct tcp_stream));
 #ifdef OSPLIT 
  struct ipfrag *frag_tag=this_fragments;
  struct ipfrag *ip_frag_next;
  if(this_fragments)
	  ip_frag_next=this_fragments->next;
  a_tcp->fp=split_file[(TCP_file_idx++)%SPLIT_FILE_NUM];
  /*write all fragment(s) to fp trace file*/
  if(is_frag==0) {
	  write_pcap_hdr(a_tcp->fp,(char*)nids_last_pcap_header,sizeof(struct pcap_sf_pkthdr));
	  write_ip(a_tcp->fp,(char*)this_iphdr,ntohs(this_iphdr->ip_len),(char*)nids_last_pcap_header);
  }
  else {
	  /*fragments*/
	  while(frag_tag!=NULL) {
		  write_pcap_hdr(a_tcp->fp,(char*)(&(frag_tag->pcap_header)),sizeof(struct pcap_sf_pkthdr));
		  write_ip(a_tcp->fp,(char*)frag_tag->skb->data,frag_tag->wtrace_len,(char*)(&(frag_tag->pcap_header)));
		  free(frag_tag);
		  frag_tag=ip_frag_next;
		  if(ip_frag_next!=NULL)
			  ip_frag_next=ip_frag_next->next;
	  }
	  is_frag=0;
   }
	/*set statistic info*/
	store_flag=1;
 #endif
  a_tcp->hash_index = hash_index;
  a_tcp->addr = addr;
  a_tcp->client.state = TCP_SYN_SENT;
  a_tcp->client.seq = ntohl(this_tcphdr->th_seq) + 1;
  a_tcp->client.first_data_seq = a_tcp->client.seq;
  a_tcp->client.window = ntohs(this_tcphdr->th_win);
  a_tcp->client.ts_on = get_ts(this_tcphdr, &a_tcp->client.curr_ts);
  a_tcp->client.wscale_on = get_wscale(this_tcphdr, &a_tcp->client.wscale);
  a_tcp->server.state = TCP_CLOSE;
  a_tcp->next_node = tolink;
  a_tcp->prev_node = 0;
  if (tolink)
    tolink->prev_node = a_tcp;
  tcp_stream_table[hash_index] = a_tcp;
  a_tcp->next_time = tcp_latest;
  a_tcp->prev_time = 0;
  if (!tcp_oldest)
    tcp_oldest = a_tcp;
  if (tcp_latest)
    tcp_latest->prev_time = a_tcp;
  tcp_latest = a_tcp;
}
示例#23
0
void get_now_ts(char *format_str, char *dest, int dest_size)
{
	double_ts_to_str(get_ts(), format_str, dest, dest_size);
}
示例#24
0
debug_console_simple::~debug_console_simple()
{
	printf("cycles/sec: %f\n", double(n_ticks) / (get_ts() - start_ts));
}
示例#25
0
static void
tcp_queue(struct tcp_stream * a_tcp, struct tcphdr * this_tcphdr,
	  struct half_stream * snd, struct half_stream * rcv,
	  char *data, int datalen, int skblen
	  )
{
  u_int this_seq = ntohl(this_tcphdr->th_seq);
  struct skbuff *pakiet, *tmp;
  
  /*
   * Did we get anything new to ack?
   */
  
  if (!after(this_seq, EXP_SEQ)) {
    if (after(this_seq + datalen + (this_tcphdr->th_flags & TH_FIN), EXP_SEQ)) {
      /* the packet straddles our window end */
      get_ts(this_tcphdr, &snd->curr_ts);
      add_from_skb(a_tcp, rcv, snd, (u_char *)data, datalen, this_seq,
		   (this_tcphdr->th_flags & TH_FIN),
		   (this_tcphdr->th_flags & TH_URG),
		   ntohs(this_tcphdr->th_urp) + this_seq - 1);
      /*
       * Do we have any old packets to ack that the above
       * made visible? (Go forward from skb)
       */
      pakiet = rcv->list;
      while (pakiet) {
	if (after(pakiet->seq, EXP_SEQ))
	  break;
	if (after(pakiet->seq + pakiet->len + pakiet->fin, EXP_SEQ)) {
	  add_from_skb(a_tcp, rcv, snd, pakiet->data,
		       pakiet->len, pakiet->seq, pakiet->fin, pakiet->urg,
		       pakiet->urg_ptr + pakiet->seq - 1);
        }
	rcv->rmem_alloc -= pakiet->truesize;
	if (pakiet->prev)
	  pakiet->prev->next = pakiet->next;
	else
	  rcv->list = pakiet->next;
	if (pakiet->next)
	  pakiet->next->prev = pakiet->prev;
	else
	  rcv->listtail = pakiet->prev;
	tmp = pakiet->next;
	free(pakiet->data);
	free(pakiet);
	pakiet = tmp;
      }
    }
    else
      return;
  }
  else {
    struct skbuff *p = rcv->listtail;

    pakiet = mknew(struct skbuff);
    pakiet->truesize = skblen;
    rcv->rmem_alloc += pakiet->truesize;
    pakiet->len = datalen;
    pakiet->data = malloc(datalen);
    if (!pakiet->data)
      nids_params.no_mem("tcp_queue");
    memcpy(pakiet->data, data, datalen);
    pakiet->fin = (this_tcphdr->th_flags & TH_FIN);
    /* Some Cisco - at least - hardware accept to close a TCP connection
     * even though packets were lost before the first TCP FIN packet and
     * never retransmitted; this violates RFC 793, but since it really
     * happens, it has to be dealt with... The idea is to introduce a 10s
     * timeout after TCP FIN packets were sent by both sides so that
     * corresponding libnids resources can be released instead of waiting
     * for retransmissions which will never happen.  -- Sebastien Raveau
     */
    if (pakiet->fin) {
      snd->state = TCP_CLOSING;
      if (rcv->state == FIN_SENT || rcv->state == FIN_CONFIRMED)
	add_tcp_closing_timeout(a_tcp);
    }
    pakiet->seq = this_seq;
    pakiet->urg = (this_tcphdr->th_flags & TH_URG);
    pakiet->urg_ptr = ntohs(this_tcphdr->th_urp);
    for (;;) {
      if (!p || !after(p->seq, this_seq))
	break;
      p = p->prev;
    }
    if (!p) {
      pakiet->prev = 0;
      pakiet->next = rcv->list;
      if (rcv->list)
         rcv->list->prev = pakiet;
      rcv->list = pakiet;
      if (!rcv->listtail)
	rcv->listtail = pakiet;
    }
    else {
      pakiet->next = p->next;
      p->next = pakiet;
      pakiet->prev = p;
      if (pakiet->next)
	pakiet->next->prev = pakiet;
      else
	rcv->listtail = pakiet;
    }
  }
}
示例#26
0
static void httplive_mediaproc(void *pArg) {
  HTTPLIVE_CLIENT_T *pClient = (HTTPLIVE_CLIENT_T *) pArg;
  int rc = 0;
  const char *p;
  const char *puri = NULL;
  char path[VSX_MAX_PATH_LEN];

  pClient->running = 0;

  LOG(X_DEBUG("Starting HTTPLive client media thread"));

  path[sizeof(path) - 1] = '\0';

  while(rc >= 0 && pClient->pCfg->running == 0 && pClient->insession) {

    path[0] = '\0';

    pthread_mutex_lock(&pClient->mtx);

    if(pClient->nextidx > pClient->curidx) {
      LOG(X_WARNING("HTTPLive skipping playlist media chunk index %d - %d"),
                     pClient->curidx, pClient->nextidx - 1);
      pClient->curidx = pClient->nextidx;
      //pClient->nextidx++;
    }

    if((p = find_path(&pClient->pl, pClient->curidx))) {
      strncpy(path, p, sizeof(path) - 1);
    } else {

    }
    pthread_mutex_unlock(&pClient->mtx);

    if(!(puri = get_uri_from_path(pClient, path))) {
      rc = -1;
      break;
    }

    if(puri && puri[0] != '\0') {

      // TODO: create httplive retrieval flag forcing new socket... lame
      if(NETIOSOCK_FD(pClient->netsock) != INVALID_SOCKET && net_issockremotelyclosed(NETIOSOCK_FD(pClient->netsock), 1)) {
        LOG(X_DEBUG("HTTPLive media socket has been closed")); 
        netio_closesocket(&pClient->netsock);
      }

      if(NETIOSOCK_FD(pClient->netsock) == INVALID_SOCKET) {

      //fprintf(stderr, "----MEDIA GET for '%s' '%s'\n", path, puri);

        if((rc = httpcli_connect(&pClient->netsock, &pClient->sa, "HTTPLive media thread")) < 0) {
          break;
        }

      }

      //fprintf(stderr, "may call get_ts puri:'%s', idx:%d, next:%d\n", puri, pClient->curidx, pClient->nextidx);

      if((rc = get_ts(pClient, puri)) >= 0) {

        //fprintf(stderr, "HTTPLive ts retrieval '%s' returned %d\n", puri, rc);

        pthread_mutex_lock(&pClient->mtx);
        pClient->nextidx++;
        pClient->curidx = pClient->nextidx;
        pthread_mutex_unlock(&pClient->mtx);
      }

    } // end of if(puri && puri[0] != '\0' ...

    sleep(1);

  }

  netio_closesocket(&pClient->netsock);

  pClient->insession = 0;
  pClient->running = -1;

  LOG(X_DEBUG("HTTPLive media download thread exiting with code %d"), rc);
}
示例#27
0
void clearContext(void)
{
    ThreadState *ts = get_ts();

    ts->current_context = ts->dummy_context;
}
示例#28
0
文件: misc.c 项目: BADSEC/multitail
void statistics_popup(int f_index, proginfo *cur)
{
	NEWWIN *popup = create_popup(16, 68);
	const char *title = "Statistics for ";
	char *abbr_fname = shorten_filename(cur -> filename, 54 - strlen(title));
	char buffer[54 + 1];

	snprintf(buffer, sizeof(buffer), "%s%s", title, abbr_fname);

	for(;;)
	{
		dtime_t time_running = get_ts() - cur -> statistics.start_ts;
		time_t start_ts = (time_t)cur -> statistics.start_ts;
		char *start_ts_str = mystrdup(ctime(&start_ts));
		time_t lastevent = (time_t)cur -> statistics.lastevent;
		char *last_ts_str  = mystrdup(ctime(&lastevent));
		char *dummy;
		char *vmsize_str = NULL;
		char *fsize_str = NULL;
		char *total_data_processed_str = amount_to_str(cur -> statistics.bytes_processed);
		char *buffer_kb;
		off64_t fsize = -1;
		int c;
		int total_re = 0;
		int loop;

		if (cur -> wt == WT_COMMAND)
		{
			vmsize_str = amount_to_str(get_vmsize(cur -> pid));
		}
		else if (cur -> wt == WT_FILE)
		{
			(void)file_info(cur -> filename, &fsize, 0, NULL, NULL);
			fsize_str = amount_to_str(fsize);
		}

		dummy = strchr(start_ts_str, '\n');
		if (dummy) *dummy = 0x00;
		dummy = strchr(last_ts_str, '\n');
		if (dummy) *dummy = 0x00;

		werase(popup -> win);
		win_header(popup, buffer);

		ui_inverse_on(popup);
		mvwprintw(popup -> win, 3, 2, "# lines       :");
		mvwprintw(popup -> win, 3, 27, "#l/s :");
		mvwprintw(popup -> win, 3, 44, "Avg len:");
		mvwprintw(popup -> win, 4, 2, "Data interval :");
		if (cur -> wt == WT_COMMAND)
			mvwprintw(popup -> win, 5, 2, "VM size       :");
		else if (cur -> wt == WT_FILE)
			mvwprintw(popup -> win, 5, 2, "File size     :");
		mvwprintw(popup -> win, 9, 2, "Data processed:");
		mvwprintw(popup -> win, 9, 27, "Bps  :");
		mvwprintw(popup -> win, 6, 2, "Started at    :");
		mvwprintw(popup -> win, 7, 2, "Last event    :");
		mvwprintw(popup -> win, 8, 2, "Next expected@:");
		mvwprintw(popup -> win, 10, 2, "# matched r.e.:");
		mvwprintw(popup -> win, 11, 2, "Buffered lines:");
		mvwprintw(popup -> win, 11, 27, "Bytes:");
		mvwprintw(popup -> win, 11, 44, "Limit  :");
		mvwprintw(popup -> win, 12, 2, "# of beeps:    ");
		if (cur -> wt == WT_COMMAND)
		{
			mvwprintw(popup -> win, 13, 2, "Number of runs:");
			mvwprintw(popup -> win, 13, 27, "Last rc:");
		}
		ui_inverse_off(popup);

		mvwprintw(popup -> win, 3, 18, "%d", cur -> statistics.n_events);
		mvwprintw(popup -> win, 6, 18, "%s", start_ts_str);
		if (cur -> statistics.lastevent != (dtime_t)0.0)
			mvwprintw(popup -> win, 7, 18, "%s", last_ts_str);
		else
			mvwprintw(popup -> win, 7, 18, "---");

		if (cur -> statistics.n_events == 0)
		{
			mvwprintw(popup -> win, 4, 18, "Not yet available");
		}
		else
		{
			double avg = cur -> statistics.med / (double)cur -> statistics.n_events;
			double dev = sqrt((cur -> statistics.dev / (double)cur -> statistics.n_events) - pow(avg, 2.0));

			/* serial correlation coefficient */
			double scct1 = cur -> statistics.scct1 + cur -> statistics.scclast * cur -> statistics.sccu0;
			double med = cur -> statistics.med * cur -> statistics.med;
			double scc = (double)cur -> statistics.n_events * cur -> statistics.dev - med;
			if (scc != 0.0)
			{
				scc = ((double)cur -> statistics.n_events * scct1 - med) / scc;
				mvwprintw(popup -> win, 4, 18, "average: %.2f, std.dev.: %.2f, SCC: %1.6f", avg, dev, scc);
			}
			else
				mvwprintw(popup -> win, 4, 18, "average: %.2f, std.dev.: %.2f, not correlated", avg, dev);

			if (avg)
			{
				double dummy_d = (double)(time(NULL) - cur -> statistics.lastevent) / avg;
				time_t next_event = cur -> statistics.lastevent + (ceil(dummy_d) * avg);
				char *ne_str = mystrdup(ctime(&next_event));
				char *dummy_str = strchr(ne_str, '\n');

				if (dummy_str) *dummy_str = 0x00;
				mvwprintw(popup -> win, 8, 18, "%s", ne_str); 
				myfree(ne_str);
			}

			mvwprintw(popup -> win, 3, 53, "%.1f", (double)cur -> statistics.bytes_processed / (double)cur -> statistics.n_events);
		}
		if (cur -> wt == WT_COMMAND)
			mvwprintw(popup -> win, 5, 18, "%s", vmsize_str);
		else if (cur -> wt == WT_STDIN || cur -> wt == WT_SOCKET)
			mvwprintw(popup -> win, 5, 18, "n.a.");
		else if (cur -> wt == WT_FILE)
			mvwprintw(popup -> win, 5, 18, "%s", fsize_str);
		myfree(vmsize_str);
		myfree(fsize_str);
		mvwprintw(popup -> win, 9, 18, "%s", total_data_processed_str);
		myfree(total_data_processed_str);
		if (time_running > 0)
		{
			char *bps_str = amount_to_str((double)cur -> statistics.bytes_processed / (double)time_running);
			mvwprintw(popup -> win, 9, 34, "%s", bps_str);
			myfree(bps_str);

			mvwprintw(popup -> win, 3, 34, "%.4f", (double)cur -> statistics.n_events / (double)time_running);
		}
		buffer_kb = amount_to_str(lb[f_index].curbytes);
		mvwprintw(popup -> win, 11, 18, "%d", lb[f_index].curpos);
		mvwprintw(popup -> win, 11, 34, "%s", buffer_kb);
		myfree(buffer_kb);
		mvwprintw(popup -> win, 12, 18, "%d", cur -> beep.did_n_beeps);
		escape_print(popup, 14, 2, "Press ^r^ to reset counters, ^q^ to exit");
		myfree(start_ts_str);
		myfree(last_ts_str);
		for(loop=0; loop<cur -> n_re; loop++)
			total_re += (cur -> pre)[loop].match_count;
		if (cur -> statistics.n_events)
			mvwprintw(popup -> win, 10, 18, "%d (%.2f%%)", total_re, (total_re * 100.0) / (double)cur -> statistics.n_events);
		else
			mvwprintw(popup -> win, 10, 18, "%d", total_re);
		if (cur -> wt == WT_COMMAND)
		{
			mvwprintw(popup -> win, 13, 18, "%d", cur -> n_runs);
			mvwprintw(popup -> win, 13, 36, "%d", cur -> last_exit_rc);
		}
		if (lb[f_index].maxnlines > 0)
		{
			mvwprintw(popup -> win, 11, 53, "%d lines", lb[f_index].maxnlines);
		}
		else if (lb[f_index].maxbytes > 0)
		{
			char *str = amount_to_str(lb[f_index].maxbytes);
			mvwprintw(popup -> win, 11, 53, "%s", str);
			myfree(str);
		}
		draw_border(popup);
		mydoupdate();

		c = toupper(wait_for_keypress(HELP_STATISTICS_POPUP, popup_refresh_interval, popup, 0));

		if (c == 'Q' || c == abort_key)
		{
			break;
		}
		else if (c == 'R')
		{
			reset_counters(&cur -> statistics);
		}
		else if (c !=  -1)
		{
			wrong_key();
		}
	}

	delete_popup(popup);
}
示例#29
0
Context *getContext(void)
{
    return get_ts()->current_context.get();
}
示例#30
0
void
process_tcp(u_char * data, int skblen)
{
  struct ip *this_iphdr = (struct ip *)data;
  struct tcphdr *this_tcphdr = (struct tcphdr *)(data + 4 * this_iphdr->ip_hl);
  int datalen, iplen;
  int from_client = 1;
  unsigned int tmp_ts;
  struct tcp_stream *a_tcp;
  struct half_stream *snd, *rcv;

  ugly_iphdr = this_iphdr;
  iplen = ntohs(this_iphdr->ip_len);
  if ((unsigned)iplen < 4 * this_iphdr->ip_hl + sizeof(struct tcphdr)) {
    nids_params.syslog(NIDS_WARN_TCP, NIDS_WARN_TCP_HDR, this_iphdr,
		       this_tcphdr);
    return;
  } // ktos sie bawi
  
  datalen = iplen - 4 * this_iphdr->ip_hl - 4 * this_tcphdr->th_off;
  
  if (datalen < 0) {
    nids_params.syslog(NIDS_WARN_TCP, NIDS_WARN_TCP_HDR, this_iphdr,
		       this_tcphdr);
    return;
  } // ktos sie bawi

  if ((this_iphdr->ip_src.s_addr | this_iphdr->ip_dst.s_addr) == 0) {
    nids_params.syslog(NIDS_WARN_TCP, NIDS_WARN_TCP_HDR, this_iphdr,
		       this_tcphdr);
    return;
  }
  if (!(this_tcphdr->th_flags & TH_ACK))
    detect_scan(this_iphdr);
  if (!nids_params.n_tcp_streams) return;
  /*FIXME: remove the tcp header check function tempor..*/
#ifdef OSPLIT
#ifdef CHECK_TCPHDR_DISABLED
#if 0
  if (my_tcp_check(this_tcphdr, iplen - 4 * this_iphdr->ip_hl,
			  this_iphdr->ip_src.s_addr, this_iphdr->ip_dst.s_addr)) {
	  nids_params.syslog(NIDS_WARN_TCP, NIDS_WARN_TCP_HDR, this_iphdr,
			  this_tcphdr);
	  return;
  }
#endif
#else
  if (my_tcp_check(this_tcphdr, iplen - 4 * this_iphdr->ip_hl,
			  this_iphdr->ip_src.s_addr, this_iphdr->ip_dst.s_addr)) {
	  nids_params.syslog(NIDS_WARN_TCP, NIDS_WARN_TCP_HDR, this_iphdr,
			  this_tcphdr);
	  return;
  }
#endif
#endif
#if 0
  check_flags(this_iphdr, this_tcphdr);
//ECN
#endif
  if (!(a_tcp = find_stream(this_tcphdr, this_iphdr, &from_client))) {
    if ((this_tcphdr->th_flags & TH_SYN) &&
	!(this_tcphdr->th_flags & TH_ACK) &&
	!(this_tcphdr->th_flags & TH_RST))
      add_new_tcp(this_tcphdr, this_iphdr);
    return;
  }
 #ifdef OSPLIT
  struct ipfrag *frag_tag=this_fragments;
  struct ipfrag *ip_frag_next;
  if(this_fragments)
	  ip_frag_next=this_fragments->next;
  /*write all fragment(s) to fp trace file*/
  if(is_frag==0) {
	  write_pcap_hdr(a_tcp->fp,(char*)nids_last_pcap_header,sizeof(struct pcap_sf_pkthdr));
	  write_ip(a_tcp->fp,(char*)this_iphdr,ntohs(this_iphdr->ip_len),(char*)nids_last_pcap_header);
  }
  else {
	  /*fragments*/
	  while(frag_tag!=NULL) {
		  write_pcap_hdr(a_tcp->fp,(char*)(&(frag_tag->pcap_header)),sizeof(struct pcap_sf_pkthdr));
		  write_ip(a_tcp->fp,(char*)frag_tag->skb->data,frag_tag->wtrace_len,(char*)(&(frag_tag->pcap_header)));
		  free(frag_tag);
		  frag_tag=ip_frag_next;
		  if(ip_frag_next!=NULL)
			  ip_frag_next=ip_frag_next->next;
	  }
	  is_frag=0;
   }
	/*set statistic info*/
	store_flag=1;
 #endif
  if (from_client) {
    snd = &a_tcp->client;
    rcv = &a_tcp->server;
  }
  else {
    rcv = &a_tcp->client;
    snd = &a_tcp->server;
  }
  if ((this_tcphdr->th_flags & TH_SYN)) {
    if (from_client || a_tcp->client.state != TCP_SYN_SENT ||
      a_tcp->server.state != TCP_CLOSE || !(this_tcphdr->th_flags & TH_ACK))
      return;
    if (a_tcp->client.seq != ntohl(this_tcphdr->th_ack))
      return;
    a_tcp->server.state = TCP_SYN_RECV;
    a_tcp->server.seq = ntohl(this_tcphdr->th_seq) + 1;
    a_tcp->server.first_data_seq = a_tcp->server.seq;
    a_tcp->server.ack_seq = ntohl(this_tcphdr->th_ack);
    a_tcp->server.window = ntohs(this_tcphdr->th_win);
    if (a_tcp->client.ts_on) {
    	a_tcp->server.ts_on = get_ts(this_tcphdr, &a_tcp->server.curr_ts);
	if (!a_tcp->server.ts_on)
		a_tcp->client.ts_on = 0;
    } else a_tcp->server.ts_on = 0;	
    if (a_tcp->client.wscale_on) {
    	a_tcp->server.wscale_on = get_wscale(this_tcphdr, &a_tcp->server.wscale);
	if (!a_tcp->server.wscale_on) {
		a_tcp->client.wscale_on = 0;
		a_tcp->client.wscale  = 1;
		a_tcp->server.wscale = 1;
	}	
    } else {
    	a_tcp->server.wscale_on = 0;	
    	a_tcp->server.wscale = 1;
    }	
    return;
  }
  if (
  	! (  !datalen && ntohl(this_tcphdr->th_seq) == rcv->ack_seq  )
  	&&
  	( !before(ntohl(this_tcphdr->th_seq), rcv->ack_seq + rcv->window*rcv->wscale) ||
          before(ntohl(this_tcphdr->th_seq) + datalen, rcv->ack_seq)  
        )
     )     
     return;

  if ((this_tcphdr->th_flags & TH_RST)) {
    if (a_tcp->nids_state == NIDS_DATA) {
      struct lurker_node *i;

      a_tcp->nids_state = NIDS_RESET;
      for (i = a_tcp->listeners; i; i = i->next)
	(i->item) (a_tcp, &i->data);
    }
    nids_free_tcp_stream(a_tcp);
    return;
  }

  /* PAWS check */
  if (rcv->ts_on && get_ts(this_tcphdr, &tmp_ts) && 
  	before(tmp_ts, snd->curr_ts))
  return; 	
  
  if ((this_tcphdr->th_flags & TH_ACK)) {
    if (from_client && a_tcp->client.state == TCP_SYN_SENT &&
	a_tcp->server.state == TCP_SYN_RECV) {
      if (ntohl(this_tcphdr->th_ack) == a_tcp->server.seq) {
	a_tcp->client.state = TCP_ESTABLISHED;
	a_tcp->client.ack_seq = ntohl(this_tcphdr->th_ack);
	{
	  struct proc_node *i;
	  struct lurker_node *j;
	  void *data;
	  
	  a_tcp->server.state = TCP_ESTABLISHED;
	  a_tcp->nids_state = NIDS_JUST_EST;
	  for (i = tcp_procs; i; i = i->next) {
	    char whatto = 0;
	    char cc = a_tcp->client.collect;
	    char sc = a_tcp->server.collect;
	    char ccu = a_tcp->client.collect_urg;
	    char scu = a_tcp->server.collect_urg;
	    
	    (i->item) (a_tcp, &data);
	    if (cc < a_tcp->client.collect)
	      whatto |= COLLECT_cc;
	    if (ccu < a_tcp->client.collect_urg)
	      whatto |= COLLECT_ccu;
	    if (sc < a_tcp->server.collect)
	      whatto |= COLLECT_sc;
	    if (scu < a_tcp->server.collect_urg)
	      whatto |= COLLECT_scu;
	    if (nids_params.one_loop_less) {
	    		if (a_tcp->client.collect >=2) {
	    			a_tcp->client.collect=cc;
	    			whatto&=~COLLECT_cc;
	    		}
	    		if (a_tcp->server.collect >=2 ) {
	    			a_tcp->server.collect=sc;
	    			whatto&=~COLLECT_sc;
	    		}
	    }  
	    if (whatto) {
	      j = mknew(struct lurker_node);
	      j->item = i->item;
	      j->data = data;
	      j->whatto = whatto;
	      j->next = a_tcp->listeners;
	      a_tcp->listeners = j;
	    }
	  }
 #ifdef OSPLIT
 #if 0
	  if (!a_tcp->listeners) {
	    nids_free_tcp_stream(a_tcp);
	    return;
	  }
#endif
 #endif
	  a_tcp->nids_state = NIDS_DATA;
	}
      }
      // return;
    }
  }