void recvPing(){
	int    		 	size;
	char   		 	recvbuf[BUFSIZE];
	char    		controlbuf[BUFSIZE];
	struct msghdr 	msg;
	struct iovec 	iov;
	ssize_t 		n;
	struct timeval 	tval;

	size = 60 * 1024;          
	setsockopt (pg, SOL_SOCKET, SO_RCVBUF, &size, sizeof (size));

	iov.iov_base = recvbuf;
	iov.iov_len = sizeof (recvbuf);
	msg.msg_name = pr->sarecv;
	msg.msg_iov = &iov;
	msg.msg_iovlen = 1;
	msg.msg_control = controlbuf;

	msg.msg_namelen = pr->salen;
	msg.msg_controllen = sizeof (controlbuf);

	n = recvmsg (pg, &msg, 0);

	if (n < 0) {
		if (errno == EINTR){
		}else{
			err_sys("[ERROR]: recvmsg error");
		}
	}
	Gettimeofday (&tval, NULL);
	proc(recvbuf, n, &msg, &tval);
	count++;
}
示例#2
0
/*
 *	print_times -- Print absolute and delta time for debugging
 *
 *	Inputs:
 *
 *	None.
 *
 *	Returns:
 *
 *	None.
 *
 *	This function is only used for debugging.  It should not be called
 *	from production code.
 */
void
print_times(void) {
   static struct timeval time_first;    /* When print_times() was first called */
   static struct timeval time_last;     /* When print_times() was last called */
   static int first_call=1;
   struct timeval time_now;
   struct timeval time_delta1;
   struct timeval time_delta2;

   Gettimeofday(&time_now);

   if (first_call) {
      first_call=0;
      time_first.tv_sec  = time_now.tv_sec;
      time_first.tv_usec = time_now.tv_usec;
      printf("%lu.%.6lu (0.000000) [0.000000]\n",
             (unsigned long)time_now.tv_sec, (unsigned long)time_now.tv_usec);
   } else {
      timeval_diff(&time_now, &time_last, &time_delta1);
      timeval_diff(&time_now, &time_first, &time_delta2);
      printf("%lu.%.6lu (%lu.%.6lu) [%lu.%.6lu]\n",
             (unsigned long)time_now.tv_sec,
             (unsigned long)time_now.tv_usec,
             (unsigned long)time_delta1.tv_sec,
             (unsigned long)time_delta1.tv_usec,
             (unsigned long)time_delta2.tv_sec,
             (unsigned long)time_delta2.tv_usec);
   }
   time_last.tv_sec  = time_now.tv_sec;
   time_last.tv_usec = time_now.tv_usec;
}
示例#3
0
void
readloop(void)
{
	int				size;
	char			recvbuf[BUFSIZE];
	socklen_t		len;
	ssize_t			n;
	struct timeval	tval;

	sockfd = Socket(pr->sasend->sa_family, SOCK_RAW, pr->icmpproto);
	setuid(getuid());		/* don't need special permissions any more */

	size = 60 * 1024;		/* OK if setsockopt fails */
	setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));

	sig_alrm(SIGALRM);		/* send first packet */

	for ( ; ; ) {
		len = pr->salen;
		n = recvfrom(sockfd, recvbuf, sizeof(recvbuf), 0, pr->sarecv, &len);
		if (n < 0) {
			if (errno == EINTR)
				continue;
			else
				err_sys("recvfrom error");
		}

		Gettimeofday(&tval, NULL);
		(*pr->fproc)(recvbuf, n, &tval);
	}
}
示例#4
0
// FIXME we need better EV_ERROR handling
static inline void
handle_kqueue_results(poller *p,const struct kevent *kevents,unsigned events){
	unsigned n = 0;

	// nag("Handling %u events\n",events);
	for(n = 0 ; n < events ; ++n){
		const struct kevent *kv = &kevents[n];

		if(kv->filter == EVFILT_SIGNAL){
			nag("SignalRX (%s)\n",strsignal(kv->ident));
			if(kv->ident == SIGCHLD){
				p->sigchldrx += kv->data;
				handle_sigchld(p);
			}
		}else{
			pollfd_state *state;
			int fd = kv->ident;

			if(fd < 0 || fd >= p->pfds_available){
				bitch("Invalid fd %d (max %d)\n",fd,p->pfds_available);
				inc_stateexceptions();
				continue;
			}
			state = &p->fdstates[fd];
			if(fd != state->pfd.fd){
				// We might close a descriptor despite
				// outstanding events later in the vector. Note
				// them, but don't take action otherwise.
				handle_invalidated_kevent(kv,fd,state);
			}else{
				struct timeval tvstart,tvend;
				int r;

				Gettimeofday(&tvstart,NULL);
				state->lastuse_time = tvstart.tv_sec;
				if(kv->flags & EV_ERROR){
					handle_kqueue_error(state);
					r = -1;
				}else if(kv->filter == EVFILT_READ){
					r = handle_kqueue_read(p,state);
				}else if(kv->filter == EVFILT_WRITE){
					r = handle_kqueue_write(p,state);
				}else if(kv->filter == EVFILT_TIMER){
					// nag("Timer callback %d\n",fd);
					r = handle_kqueue_timeout(p,state);
				}else{
					bitch("Unknown kevent filter %d\n",kv->filter);
					inc_stateexceptions();
					r = 0;
				}
				if(!r){
					time_avgmax(&state->pfd_avgmax_time,&tvend,&tvstart);
				}else{
					purge_fd_resulthandler(p,state,fd);
				}
			}
		}
	}
}
示例#5
0
int 
wrap_select(WRAPPERS_ARGS, int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
{
  int rv;
  struct timeval timeout_orig;
  struct timeval start, end, delta;
  
  assert(file && function);

  /* readfds, writefds, exceptfds, and timeout could each be null, but
   * not all can be null at the same time
   */
  if (!readfds && !writefds && !exceptfds && !timeout)
    WRAPPERS_ERR_INVALID_PARAMETERS("select");

  if (timeout) 
    {
      timeout_orig = *timeout;
      Gettimeofday(&start, NULL);
    }
  else
    {
      /* unused - necessary to remove compiler warning */
      timeout_orig.tv_sec = 0;
      timeout_orig.tv_usec = 0;
    }

  do 
    {
      rv = select(n, readfds, writefds, exceptfds, timeout);
      if (rv < 0 && errno != EINTR)
        WRAPPERS_ERR_ERRNO("select");
      if (rv < 0 && timeout) 
	{
	  Gettimeofday(&end, NULL);
	  /* delta = end-start */
	  timersub(&end, &start, &delta);     
	  /* timeout = timeout_orig-delta */
	  timersub(&timeout_orig, &delta, timeout);     
	}
    } 
  while (rv < 0);

  return rv;
}
示例#6
0
uint32_t rtt_ts(struct rtt_info *ptr) /* 返回当前时间戳 */
{
    uint32_t ts;
    struct timeval tv;

    Gettimeofday(&tv, NULL);
    ts = ((tv.tv_sec - ptr->rtt_base) * 1000) + (tv.tv_usec / 1000); /*ms*/
    return (ts);
}
void send_dgram (int ttl)
{
  int n;

  rec->seq = seq++;
  sock_set_port (sasend, salen, htons(dport+seq));

  Gettimeofday (sendtv, NULL);
  n = sendto(sendfd, sendbuf, datalen, 0, sasend, salen);

  if (n==-1 && errno == ECONNREFUSED) {
    Gettimeofday (sendtv, NULL);
    n = sendto(sendfd, sendbuf, datalen, 0, sasend, salen);
  }

  if (n != datalen) {
    err_sys("sendto error");
  }
}
示例#8
0
void on_server_exit(void) {
  struct timeval tv;
  time_t currtime;
  char str_time[40];

  unlink(SRV_DGPATH);
  Gettimeofday(&tv, NULL);
  time(&currtime);
  strftime(str_time, 40, "%T", localtime(&currtime));
  INFO("Server exited at %s.%03u\n", str_time, (unsigned int)tv.tv_usec/1000);
}
示例#9
0
int 
wrap_poll(WRAPPERS_ARGS, struct pollfd *ufds, unsigned int nfds, int timeout)
{
  int rv;
  struct timeval timeout_orig, timeout_current;
  struct timeval start, end, delta;
                                                                         
  if (!ufds)  
    WRAPPERS_ERR_INVALID_PARAMETERS("poll");

  /* Poll uses timeout in milliseconds */
  if (timeout >= 0) 
    {
      timeout_orig.tv_sec = (long)timeout/1000;
      timeout_orig.tv_usec = (timeout % 1000) * 1000;
      Gettimeofday(&start, NULL);
    }
  else
    {
      /* unused - necessary to remove compiler warning */
      timeout_orig.tv_sec = 0;
      timeout_orig.tv_usec = 0;
    }

  do {
    rv = poll(ufds, nfds, timeout);
    if (rv < 0 && errno != EINTR)
      WRAPPERS_ERR_ERRNO("poll");
    if (rv < 0 && timeout >= 0) {
      Gettimeofday(&end, NULL);
      /* delta = end-start */
      timersub(&end, &start, &delta);     
      /* timeout_current = timeout_orig-delta */
      timersub(&timeout_orig, &delta, &timeout_current);
      timeout = (timeout_current.tv_sec * 1000) + (timeout_current.tv_usec/1000);
    }
  } while (rv < 0);
                                                                         
  return rv;
}
示例#10
0
// RFC 3507, 4.1. All ICAP messages begin with a start-line, ala RFC 2822.
// Requests begin with a request line, responses begin with a status line. We
// are only expecting requests and thus request lines.
//
// 4.2. All ICAP requests specify the ICAP resource being requested from the
// server using an ICAP URI. This URI is dictated by RFC 2396. A request
// consists of a method (RESPMOD, REQMOD, OPTIONS), a URI, and an ICAP version.
int icap_want_startline(struct pollfd_state *pfd,char *line){
	icap_state *is = get_pfd_icap(pfd);
	icap_status icapcode;

	if(strcmp(line,CRLF) == 0){ // Skip blank lines per RFC 3507
		return 0;
	}
	Gettimeofday(&is->transstart,NULL);
	if(parse_icap_startline(line,pfd,&icapcode)){
		return send_icapexception(pfd,icapcode);
	}
	return use_crlf_mode(is->pibuf,icap_want_headers);
}
示例#11
0
文件: rtt.c 项目: kingfree/haut
void rtt_init(struct rtt_info* ptr)
{
    struct timeval tv;

    Gettimeofday(&tv, NULL);
    ptr->rtt_base = tv.tv_sec; /* # sec since 1/1/1970 at start */

    ptr->rtt_rtt = 0;
    ptr->rtt_srtt = 0;
    ptr->rtt_rttvar = 0.75;
    ptr->rtt_rto = rtt_minmax(RTT_RTOCALC(ptr));
    /* first RTO at (srtt + (4 * rttvar)) = 3 seconds */
}
示例#12
0
文件: client.c 项目: reddragon/cse533
void on_client_exit(void) {
  struct timeval tv;
  VERBOSE("Failed Calls to recv(2) or recvfrom(2): %d/%d = %.2f\n",
          recv_failed, recv_total, (double)recv_failed/(double)recv_total);
  VERBOSE("Failed Calls to send(2)               : %d/%d = %.2f\n",
          send_failed, send_total, (double)send_failed/(double)send_total);

  Gettimeofday(&tv, NULL);
  time_t currtime;
  char str_time[40];
  time(&currtime);
  strftime(str_time, 40, "%T", localtime(&currtime));
  INFO("Client exited at %s.%03u\n", str_time, (unsigned int)tv.tv_usec/1000);
}
示例#13
0
文件: tour.c 项目: myroman/beta
void processPgResponse(void *ptr, ssize_t len, SockAddrIn senderAddr, int addrlen) {
	int icmplen;
	struct ip *ip = (struct ip *) ptr;		/* start of IP header */	
	
	if (ip->ip_p != IPPROTO_ICMP)
		return;				/* not ICMP */
	int ipheaderlen = ip->ip_hl << 2;		/* length of IP header */	
	struct icmp	*icmp = (struct icmp *) (ptr + ipheaderlen);	/* start of ICMP header */
	if ( (icmplen = len - ipheaderlen) < 8)
		return;				/* malformed packet */

	if (icmp->icmp_type != 0) {
		return;
	}
	if (ntohs(icmp->icmp_id) != PING_ICMPID) {
		return;
	}
	
	if (endOfTour == 1) {
		lastPings++;
		if (lastPings == 5) {
			char finalMsg[MAXLINE];
			int i = 0;
			for (i = 0; i < numPinging;++i) {
				pthread_cancel(ping_thread_ids[i]);	
			}

			sprintf(finalMsg, "<<<<< This is node %s . Tour has ended. Group members please identify yourselves. >>>>>", myNodeName);
			printf("Node %s. Sending: %s\n", myNodeName, finalMsg);
			sendto(mcastSendSd, finalMsg, MAXLINE, 0, sasend, salen);
		}
	}

	struct timeval	*tvsend;
	struct timeval tvrecv;
	Gettimeofday(&tvrecv, NULL);
	
	tvsend = (struct timeval *) icmp->icmp_data;
	tv_sub(&tvrecv, tvsend);
	double rtt = tvrecv.tv_sec * 1000.0 + tvrecv.tv_usec / 1000.0;

	printf("%d bytes from %s: seq=%u, ttl=%d, rtt=%.3f ms\n",
			icmplen, Sock_ntop_host((SA *)&senderAddr, addrlen),
			icmp->icmp_seq, ip->ip_ttl, rtt);
}
示例#14
0
文件: send_v4.c 项目: rkks/refer
void
send_v4(void)
{
	int			len;
	struct icmp	*icmp;

	icmp = (struct icmp *) sendbuf;
	icmp->icmp_type = ICMP_ECHO;
	icmp->icmp_code = 0;
	icmp->icmp_id = pid;
	icmp->icmp_seq = nsent++;
	Gettimeofday((struct timeval *) icmp->icmp_data, NULL);

	len = 8 + datalen;		/* checksum ICMP header and data */
	icmp->icmp_cksum = 0;
	icmp->icmp_cksum = in_cksum((u_short *) icmp, len);

	Sendto(sockfd, sendbuf, len, 0, pr->sasend, pr->salen);
}
示例#15
0
/*
 * _setup_event_node_timeout_data
 *
 * Setup event timeout calculation data structures. 
 *
 * Return 0 on success, -1 on error
 */
static int
_setup_event_node_timeout_data(void)
{
  struct timeval tv;
  int num;

  assert(conf.event_server);
  assert(listener_data);

  event_node_timeout_data = List_create(NULL);
  event_node_timeout_data_index = Hash_create(EVENT_NODE_TIMEOUT_SIZE_DEFAULT, 
                                              (hash_key_f)hash_key_string,
                                              (hash_cmp_f)strcmp, 
                                              (hash_del_f)NULL);
  event_node_timeout_data_index_size = EVENT_NODE_TIMEOUT_SIZE_DEFAULT;
  
  Gettimeofday(&tv, NULL);

  num = Hash_for_each(listener_data,
                      _event_node_timeout_data_callback,
                      &(tv.tv_sec));
  if (num != listener_data_numnodes)
    {
      fprintf(stderr, "* invalid create count: num=%d numnodes=%d\n",
              num, listener_data_numnodes);
      goto cleanup;
    }

  return 0;

 cleanup:
  if (event_node_timeout_data)
    {
      List_destroy(event_node_timeout_data);
      event_node_timeout_data = NULL;
    }
  if (event_node_timeout_data_index)
    {
      Hash_destroy(event_node_timeout_data_index);
      event_node_timeout_data_index =  NULL;
    }
  return -1;
}
void sendPing(){
	int     	len;
	struct icmp *icmp;

	icmp = (struct icmp *) sendbuf;
	icmp->icmp_type = ICMP_ECHO;
	icmp->icmp_code = 0;
	icmp->icmp_id = pid;
	icmp->icmp_seq = nsent++;
	memset (icmp->icmp_data, 0xa5, datalen); // fill with pattern 
	Gettimeofday ((struct timeval *) icmp->icmp_data, NULL);

	len = 8 + datalen;           // checksum ICMP header and data 
	icmp->icmp_cksum = 0;
	icmp->icmp_cksum = in_cksum ((u_short *) icmp, len);

	Sendto (pg, sendbuf, len, 0, pr->sasend, pr->salen);

}
示例#17
0
int fill_ping_packet_header(struct ping_packet *p_packet,uint32_t src_ip,uint32_t dst_ip) {

        int   len;
        struct icmp     *icmp_hdr;
        static int nsent = 1;
        memcpy(p_packet->dest_mac,dst_mac,MACLEN);
        memcpy(p_packet->src_mac, src_mac,MACLEN);
        p_packet->proto_id = htons(ETH_P_IP);

        icmp_hdr = &(p_packet->ping_hdr.icmp_hdr);

        icmp_hdr->icmp_type = ICMP_ECHO;
        icmp_hdr->icmp_code = 0;
        icmp_hdr->icmp_id = htons(PING_ID);
        icmp_hdr->icmp_seq = htons(++nsent);
        //memset(icmp_hdr->icmp_data, 0xa5, 56);
        Gettimeofday((struct timeval *) icmp_hdr->icmp_data, NULL);
        //len = 8 + datalen;             
        len = sizeof(struct icmp);
        icmp_hdr->icmp_cksum = 0;
        icmp_hdr->icmp_cksum = in_cksum((uint16_t *) icmp_hdr, len);


        struct ip *ip_hdr ;
        ip_hdr = (struct ip*)&(p_packet->ping_hdr.ip_hdr);

        ip_hdr->ip_hl  = sizeof(struct ip) >> 2;
        ip_hdr->ip_v = IPVERSION;
        ip_hdr->ip_tos = 0;
        ip_hdr->ip_len = htons(sizeof(struct ping_header));
        ip_hdr->ip_id  = htons(PING_ID);
        ip_hdr->ip_off = 0;
        ip_hdr->ip_ttl = 64;
        ip_hdr->ip_p   = IPPROTO_ICMP;
        ip_hdr->ip_src.s_addr = src_ip;
        ip_hdr->ip_dst.s_addr = dst_ip;
        int size = sizeof(struct ip);
        ip_hdr->ip_sum = in_cksum((uint16_t *)ip_hdr,size);

        return 1;

}
示例#18
0
文件: send_v6.c 项目: kingfree/haut
void send_v6()
{
#ifdef IPV6
    int len;
    struct icmp6_hdr* icmp6;

    icmp6 = (struct icmp6_hdr*)sendbuf;
    icmp6->icmp6_type = ICMP6_ECHO_REQUEST;
    icmp6->icmp6_code = 0;
    icmp6->icmp6_id = pid;
    icmp6->icmp6_seq = nsent++;
    memset((icmp6 + 1), 0xa5, datalen); /* fill with pattern */
    Gettimeofday((struct timeval*)(icmp6 + 1), NULL);

    len = 8 + datalen; /* 8-byte ICMPv6 header */

    Sendto(sockfd, sendbuf, len, 0, pr->sasend, pr->salen);
/* 4kernel calculates and stores checksum for us */
#endif /* IPV6 */
}
示例#19
0
文件: main.c 项目: AnSwErYWJ/UNP
int
main(int argc, char **argv)
{
	int					sockfd;
	char				buf[MAXLINE];
	ssize_t				n;
	socklen_t			salen, len;
	struct ifi_info		*ifi;
	struct sockaddr		*mcastsa, *wild, *from;
	struct timeval		now;

	if (argc != 2)
		err_quit("usage: ssntp <IPaddress>");

	sockfd = Udp_client(argv[1], "ntp", (void **) &mcastsa, &salen);

	wild = Malloc(salen);
	memcpy(wild, mcastsa, salen);	/* copy family and port */
	sock_set_wild(wild, salen);
	Bind(sockfd, wild, salen);	/* bind wildcard */

#ifdef	MCAST
		/* 4obtain interface list and process each one */
	for (ifi = Get_ifi_info(mcastsa->sa_family, 1); ifi != NULL;
		 ifi = ifi->ifi_next) {
		if (ifi->ifi_flags & IFF_MULTICAST) {
			Mcast_join(sockfd, mcastsa, salen, ifi->ifi_name, 0);
			printf("joined %s on %s\n",
				   Sock_ntop(mcastsa, salen), ifi->ifi_name);
		}
	}
#endif

	from = Malloc(salen);
	for ( ; ; ) {
		len = salen;
		n = Recvfrom(sockfd, buf, sizeof(buf), 0, from, &len);
		Gettimeofday(&now, NULL);
		sntp_proc(buf, n, &now);
	}
}
int recv_dgram ()
{
  int err;
  socklen_t len;
  ssize_t n;
  struct ip *ip;
  int maxfdp1 = max (recvfd, pipefd[0]) + 1;
  fd_set rset[1];  
  FD_ZERO (rset);

  alarm(3);       /* set the timeout alarm to handle dropped packets */

  while (1) {
    FD_SET (recvfd, rset);
    FD_SET (pipefd[0], rset);

    n = select (maxfdp1, rset, NULL, NULL, NULL);
    if (n < 0 && errno != EINTR) {
      err_sys ("select error");
    }

    if (FD_ISSET (recvfd, rset)) {
      len = salen;
      n = recvfrom (recvfd, recvbuf, sizeof(recvbuf), 0, sarecv, &len);
      err = errno;
      Gettimeofday (recvtv, NULL);   /* get time of packet arrival */
      if (n < 0 && err != EAGAIN) {
	err_sys ("recvfrom error");
      }
    }

    if (FD_ISSET (pipefd[0], rset)) {
      Read (pipefd[0], &n, 1);
      return -3;                 /* timeout */
    }

    ip = (struct ip *) recvbuf;
    return process_ip (ip, n);
  }
}
示例#21
0
void
proc_v4(int fd)
{
        struct ping_header packet;
        int                     hlen1, icmplen;
        double                  rtt;
        struct ip               *ip;
        struct icmp             *icmp;
        struct timeval  *tvsend,*tvrecv;
        char buf[INET_ADDRSTRLEN];
        tvrecv = (struct timeval *)malloc(sizeof(struct timeval));
        Gettimeofday(tvrecv,NULL);
	static nsent = 1;
        int rv = recvfrom(fd,&packet,sizeof(packet),0,NULL,NULL);
        if (rv < 0)
                perror("Error in Recvfrom");

	icmplen = rv;
        ip = &(packet.ip_hdr);
        icmp = &(packet.icmp_hdr);

        hlen1 = ip->ip_hl << 2;
        if (ip->ip_p != IPPROTO_ICMP)
                return;

        if (icmp->icmp_type == ICMP_ECHOREPLY) {
                //if (icmp->icmp_id != PING_ID)
                 //       return;
              //  if (icmplen < 16)
              //          return;

                tvsend = (struct timeval *) icmp->icmp_data;
                tv_sub(tvrecv, tvsend);
                rtt = tvrecv->tv_sec * 1000.0 + tvrecv->tv_usec / 1000.0;

                printf("\n PING REPLY %d bytes from %s: seq=%u, ttl=%d, rtt=%.3f ms\n",
                               icmplen,inet_ntop(AF_INET,&(ip->ip_src),buf,INET_ADDRSTRLEN),
                                ntohs(icmp->icmp_seq), ip->ip_ttl, rtt);
	}
}
示例#22
0
static int
test_icap_stats(void){
	struct timeval tv;
	int ret = -1;

	Gettimeofday(&tv,NULL);
	if(common_start()){
		goto done;
	}
	if(init_ctlserver(CUNIT_CTLSERVER)){
		goto done;
	}
	printf(" Testing ICAP statistics (twice)...\n");
	if(ctlclient_quiet("icap_stats_dump") < 0){
		goto done;
	}
	if(ctlclient_quiet("pfd_table_dump") < 0){
		goto done;
	}
	if(ctlclient_quiet("snare_dump") < 0){
		goto done;
	}
	time_oqueue_session(&tv);
	Gettimeofday(&tv,NULL);
	time_oqueue_session(&tv);
	Gettimeofday(&tv,NULL);
	time_oqueue_session(&tv);
	Gettimeofday(&tv,NULL);
	time_oqueue_session(&tv);
	Gettimeofday(&tv,NULL);
	time_oqueue_session(&tv);
	Gettimeofday(&tv,NULL);
	ret = (ctlclient_quiet("icap_stats_dump") < 0);
	ret |= (ctlclient_quiet("pfd_table_dump") < 0);
	ret |= (ctlclient_quiet("snare_dump") < 0);

done:
	ret |= close_icap_servers();
	ret |= reap_poller_thread(snarepoller);
	ret |= destroy_poller(snarepoller);
	ret |= stop_config();
	ret |= stop_fileconf();
	ret |= stop_ctlserver();
	return ret;
}
示例#23
0
文件: recv_v6.c 项目: kingfree/haut
int recv_v6(int seq, struct timeval* tv)
{
#ifdef IPV6
    int hlen2, icmp6len, ret;
    ssize_t n;
    socklen_t len;
    struct ip6_hdr* hip6;
    struct icmp6_hdr* icmp6;
    struct udphdr* udp;

    gotalarm = 0;
    alarm(3);
    for (;;) {
        if (gotalarm) return (-3); /* alarm expired */
        len = pr->salen;
        n = recvfrom(recvfd, recvbuf, sizeof(recvbuf), 0, pr->sarecv, &len);
        if (n < 0) {
            if (errno == EINTR)
                continue;
            else
                err_sys("recvfrom error");
        }

        icmp6 = (struct icmp6_hdr*)recvbuf; /* ICMP header */
        if ((icmp6len = n) < 8)
            continue; /* not enough to look at ICMP header */

        if (icmp6->icmp6_type == ICMP6_TIME_EXCEEDED &&
            icmp6->icmp6_code == ICMP6_TIME_EXCEED_TRANSIT) {
            if (icmp6len < 8 + sizeof(struct ip6_hdr) + 4)
                continue; /* not enough data to look at inner header */

            hip6 = (struct ip6_hdr*)(recvbuf + 8);
            hlen2 = sizeof(struct ip6_hdr);
            udp = (struct udphdr*)(recvbuf + 8 + hlen2);
            if (hip6->ip6_nxt == IPPROTO_UDP && udp->uh_sport == htons(sport) &&
                udp->uh_dport == htons(dport + seq))
                ret = -2; /* we hit an intermediate router */
            break;
        } else if (icmp6->icmp6_type == ICMP6_DST_UNREACH) {
            if (icmp6len < 8 + sizeof(struct ip6_hdr) + 4)
                continue; /* not enough data to look at inner header */

            hip6 = (struct ip6_hdr*)(recvbuf + 8);
            hlen2 = sizeof(struct ip6_hdr);
            udp = (struct udphdr*)(recvbuf + 8 + hlen2);
            if (hip6->ip6_nxt == IPPROTO_UDP && udp->uh_sport == htons(sport) &&
                udp->uh_dport == htons(dport + seq)) {
                if (icmp6->icmp6_code == ICMP6_DST_UNREACH_NOPORT)
                    ret = -1; /* have reached destination */
                else
                    ret = icmp6->icmp6_code; /* 0, 1, 2, ... */
                break;
            }
        } else if (verbose) {
            printf(" (from %s: type = %d, code = %d)\n",
                   Sock_ntop_host(pr->sarecv, pr->salen), icmp6->icmp6_type,
                   icmp6->icmp6_code);
        }
        /* Some other ICMP error, recvfrom() again */
    }
    alarm(0);               /* don't leave alarm running */
    Gettimeofday(tv, NULL); /* get time of packet arrival */
    return (ret);
#endif
}
示例#24
0
int main(void)
{
/*
 *	MD5 test vectors from RFC 1321 "The MD5 Message-Digest Algorithm"
 */
	static const char *md5_tests[] = {
		"",
		"a",
		"abc",
		"message digest",
		"abcdefghijklmnopqrstuvwxyz",
		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
		"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
		NULL
	};
	static const char *md5_results[] = {
		"d41d8cd98f00b204e9800998ecf8427e",
		"0cc175b9c0f1b6a831c399e269772661",
		"900150983cd24fb0d6963f7d28e17f72",
		"f96b697d7cb7938d525a2f31aaf161d0",
		"c3fcd3d76192e4007dfb496cca67e13b",
		"d174ab98d277d9f5a5611c2c9f419d9f",
		"57edf4a22be3c955ac49da2e2107b67a"
	};
/*
 *	SHA1 test vectors from RFC 3174 "US Secure Hash Algorithm 1 (SHA1)"
 */
	static const char *sha1_tests[] = {
		"abc",
		"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
		NULL
	};
	static const char *sha1_results[] = {
		"a9993e364706816aba3e25717850c26c9cd0d89d",
		"84983e441c3bd26ebaae4aa1f95129e5e54670f1",
	};
/*
 *	HMAC-MD5 test vectors from RFC 2104
 *	"HMAC: Keyed-Hashing for Message Authentication"
 */
	static const struct hmac_md5_test_struct {
		unsigned char key[16];
		int key_len;
		unsigned char data[64];
		int data_len;
		char *digest;
	} hmac_md5_tests[NUM_HMAC_TESTS] = {
		{ "Jefe",
		  4,
		  "what do ya want for nothing?",
		  28,
		  "750c783e6ab0b503eaa86e310a5db738" }
	};

/*
 *	HMAC-SHA1 test vectors from RFC 2202
 *	"Test Cases for HMAC-MD5 and HMAC-SHA-1"
 */
	static const struct hmac_sha1_test_struct {
		unsigned char key[20];
		int key_len;
		unsigned char data[64];
		int data_len;
		char *digest;
	} hmac_sha1_tests[NUM_HMAC_TESTS] = {
		{ "Jefe",
		  4,
		  "what do ya want for nothing?",
		  28,
		  "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79" }
	};

	const char **testp;
	const char **resultp;
	int i;

	int error = 0;

#ifdef HAVE_OPENSSL
	printf("\nUsing OpenSSL hash and HMAC functions.\n");
#else
	printf("\nUsing built-in hash and HMAC functions.\n");
#endif

	printf("\nChecking MD5 hash function...\n");
	testp = md5_tests;
	resultp = md5_results;
	while (*testp != NULL) {
		const char *expected;
		char *actual;
		printf("\"%s\"\t", *testp);
		expected = *resultp;
		actual =
			hexstring(MD5((const unsigned char *) *testp,
				      strlen(*testp),
				      NULL), 16);
		if (strcmp(actual, expected)) {
			error++;
			printf("FAIL (expected %s, got %s)\n", expected,
			       actual);
		} else {
			printf("ok\n");
		}
		testp++;
		resultp++;
	}

	printf("\nChecking SHA1 hash function...\n");
	testp = sha1_tests;
	resultp = sha1_results;
	while (*testp != NULL) {
		const char *expected;
		char *actual;
		printf("\"%s\"\t", *testp);
		expected = *resultp;
		actual =
			hexstring(SHA1((const unsigned char *) *testp,
				       strlen(*testp),
				       NULL), 20);
		if (strcmp(actual, expected)) {
			error++;
			printf("FAIL (expected %s, got %s)\n", expected,
			       actual);
		} else {
			printf("ok\n");
		}
		testp++;
		resultp++;
	}

	printf("\nChecking HMAC-MD5 keyed hash function...\n");
	for (i = 0; i < NUM_HMAC_TESTS; i++) {
		const char *expected;
		char *actual;
		printf("\"%s\" \"%s\"\t", hmac_md5_tests[i].key,
		       hmac_md5_tests[i].data);
		expected = hmac_md5_tests[i].digest;
		actual = hexstring(hmac_md5(hmac_md5_tests[i].data,
					    hmac_md5_tests[i].data_len,
					    hmac_md5_tests[i].key,
					    hmac_md5_tests[i].key_len,
					    NULL), 16);
		if (strcmp(actual, expected)) {
			error++;
			printf("FAIL (expected %s, got %s)\n", expected,
			       actual);
		} else {
			printf("ok\n");
		}
	}

	printf("\nChecking HMAC-SHA1 keyed hash function...\n");
	for (i = 0; i < NUM_HMAC_TESTS; i++) {
		const char *expected;
		char *actual;
		printf("\"%s\" \"%s\"\t", hmac_sha1_tests[i].key,
		       hmac_sha1_tests[i].data);
		expected = hmac_sha1_tests[i].digest;
		actual = hexstring(hmac_sha1(hmac_sha1_tests[i].data,
					     hmac_sha1_tests[i].data_len,
					     hmac_sha1_tests[i].key,
					     hmac_sha1_tests[i].key_len,
					     NULL), 20);
		if (strcmp(actual, expected)) {
			error++;
			printf("FAIL (expected %s, got %s)\n", expected,
			       actual);
		} else {
			printf("ok\n");
		}
	}

	printf("\nChecking HMAC-MD5 PSK cracking speed...\n");
	do {
/*
 *	The values below are observed values from a Firewall-1 system
 *	using IKE Aggressive mode with PSK authentication and MD5 hash.
 *	The ID used was "test", and the valid pre-shared key is "abc123".
 *      The expected hash_r is "f995ec2968f695aeb1d4e4b437f49d26".
 */
		char *g_xr_hex =
			"9c1e0e07828af45086a4eb559ad8dafb7d655bab38656609426653565ef7e332bed7212cf24a05048032240256a169a68ee304ca500abe073d150bc50239350446ab568132aebcf34acd25ce23b30d0de9f8e7a89c22ce0dec2dabf0409bc25f0988d5d956916dce220c630d2a1fda846667fdecb20b2dc2d5c5b8273a07095c";
		char *g_xi_hex =
			"6f8c74c15bb4dd09b7af8d1c23e7b381a38dddcd4c5afb3b1335ff766f0267df8fdca0ea907ef4482d8164506817d10ba4aed8f108d32c1b082b91772df956bcd5f7a765759bada21c11f28429c48fcd7267be7b3aea96421528b9432110fff607a65b7c41091e5d1a10e143d4701147d7cfc211ba5853cf800d12a11d129724";
		char *cky_r_hex = "6d08132c8abb6931";
		char *cky_i_hex = "eac82ea45cbe59e6";
		char *sai_b_hex =
			"00000001000000010000002c01010001000000240101000080010001800200018003000180040002800b0001000c000400007080";
		char *idir_b_hex = "01000000ac100202";
		char *ni_b_hex = "64745a975dbcd95c2abf7d2eeeb93ac4633a03f1";
		char *nr_b_hex = "502c0b3872518fa1e7ff8f5a28a3d797f65e2cb1";

		unsigned char *g_xr;
		unsigned char *g_xi;
		unsigned char *cky_r;
		unsigned char *cky_i;
		unsigned char *sai_b;
		unsigned char *idir_b;
		unsigned char *ni_b;
		unsigned char *nr_b;

		size_t g_xr_len;
		size_t g_xi_len;
		size_t cky_r_len;
		size_t cky_i_len;
		size_t sai_b_len;
		size_t idir_b_len;
		size_t ni_b_len;
		size_t nr_b_len;

		unsigned char *skeyid;
		unsigned char *hash_r;

		unsigned char *skeyid_data;
		unsigned char *hash_r_data;

		size_t skeyid_data_len;
		size_t hash_r_data_len;

		unsigned char *cp;

		unsigned char *psk = (unsigned char *) "abc123"; /* correct key */
		size_t psk_len = 6;

		struct timeval start_time;
		struct timeval end_time;
		struct timeval elapsed_time;
		double elapsed_seconds;

		g_xr = hex2data(g_xr_hex, &g_xr_len);
		g_xi = hex2data(g_xi_hex, &g_xi_len);
		cky_r = hex2data(cky_r_hex, &cky_r_len);
		cky_i = hex2data(cky_i_hex, &cky_i_len);
		sai_b = hex2data(sai_b_hex, &sai_b_len);
		idir_b = hex2data(idir_b_hex, &idir_b_len);
		ni_b = hex2data(ni_b_hex, &ni_b_len);
		nr_b = hex2data(nr_b_hex, &nr_b_len);

		skeyid_data_len = ni_b_len + nr_b_len;
		skeyid_data = Malloc(skeyid_data_len);
		cp = skeyid_data;
		memcpy(cp, ni_b, ni_b_len);
		cp += ni_b_len;
		memcpy(cp, nr_b, nr_b_len);
		skeyid = Malloc(16);
		hash_r_data_len = g_xr_len + g_xi_len + cky_r_len + cky_i_len +
				  sai_b_len + idir_b_len;
		hash_r_data = Malloc(hash_r_data_len);
		cp = hash_r_data;
		memcpy(cp, g_xr, g_xr_len);
		cp += g_xr_len;
		memcpy(cp, g_xi, g_xi_len);
		cp += g_xi_len;
		memcpy(cp, cky_r, cky_r_len);
		cp += cky_r_len;
		memcpy(cp, cky_i, cky_i_len);
		cp += cky_i_len;
		memcpy(cp, sai_b, sai_b_len);
		cp += sai_b_len;
		memcpy(cp, idir_b, idir_b_len);
		hash_r = Malloc(16);

		Gettimeofday(&start_time);
		for (i = 0; i < HMAC_SPEED_ITERATIONS; i++) {
			hmac_md5(skeyid_data, skeyid_data_len, psk, psk_len,
				 skeyid);
			hmac_md5(hash_r_data, hash_r_data_len, skeyid, 16,
				 hash_r);
		}
		Gettimeofday(&end_time);
		timeval_diff(&end_time, &start_time, &elapsed_time);
		elapsed_seconds = elapsed_time.tv_sec +
				  (elapsed_time.tv_usec / 1000000.0);
		printf(
			"%u MD5 HASH_R calculations in %.6f seconds (%.2f per sec)\n",
			HMAC_SPEED_ITERATIONS, elapsed_seconds,
			HMAC_SPEED_ITERATIONS / elapsed_seconds);
	} while (0);

	printf("\nChecking HMAC-SHA1 PSK cracking speed...\n");
	do {
/*
 *	The values below are observed values from a Firewall-1 NG AI system
 *	using IKE Aggressive mode with PSK authentication and SHA1 hash.
 *	The ID used was "test", and the valid pre-shared key is "abc123".
 *      The expected hash_r is "543ea42889c07b17390cc6f0440246c0148422df".
 */
		char *g_xr_hex =
			"6c5559243259d5293df34a766561b8ffa78a9f8ee03d8a05916aadeeba9997864e0cd712f2a08104366c5e48f391ee7ce7b0ac08c59b8001c888c9f0343fd7d7d2d1da8e672c4ff05a7dd3c4eb6adc09bec712128ed951f7fcde2c31431643eb04d5ffc0be68e17aa80168e9635cb6f4c80af8ea1432c2b095b25f3d79ac4e55";
		char *g_xi_hex =
			"857209de96faf07bad57ff1aba648a2c61a6802e4db3ab54c5593fa8abd9b1304bbb0fe2b5ff5d63565c7d10c1073d22adbd51fb70fc4f35568ede01678f32b24a41940040f263964ee0a70fe8e43295a18390117fdf46d56d24d7d4b40987fe4a1bfe8a0d61205c42c76b2aab9dbf4c20505da02fa4759dc84c717c55f87b9f";
		char *cky_r_hex = "963c61ef1778b6c5";
		char *cky_i_hex = "efa6639971a91c08";
		char *sai_b_hex =
			"00000001000000010000002c01010001000000240101000080010001800200028003000180040002800b0001000c000400007080";
		char *idir_b_hex = "01000000ac100202";
		char *ni_b_hex = "6d62656f72fd1c53cda7337d0612aeebe3529a09";
		char *nr_b_hex = "8e83c48eb087b8276b4bb2976ea23bf426abde8f";

		unsigned char *g_xr;
		unsigned char *g_xi;
		unsigned char *cky_r;
		unsigned char *cky_i;
		unsigned char *sai_b;
		unsigned char *idir_b;
		unsigned char *ni_b;
		unsigned char *nr_b;

		size_t g_xr_len;
		size_t g_xi_len;
		size_t cky_r_len;
		size_t cky_i_len;
		size_t sai_b_len;
		size_t idir_b_len;
		size_t ni_b_len;
		size_t nr_b_len;

		unsigned char *skeyid;
		unsigned char *hash_r;

		unsigned char *skeyid_data;
		unsigned char *hash_r_data;

		size_t skeyid_data_len;
		size_t hash_r_data_len;

		unsigned char *cp;

		unsigned char *psk = (unsigned char *) "abc123"; /* correct key */
		size_t psk_len = 6;

		struct timeval start_time;
		struct timeval end_time;
		struct timeval elapsed_time;
		double elapsed_seconds;

		g_xr = hex2data(g_xr_hex, &g_xr_len);
		g_xi = hex2data(g_xi_hex, &g_xi_len);
		cky_r = hex2data(cky_r_hex, &cky_r_len);
		cky_i = hex2data(cky_i_hex, &cky_i_len);
		sai_b = hex2data(sai_b_hex, &sai_b_len);
		idir_b = hex2data(idir_b_hex, &idir_b_len);
		ni_b = hex2data(ni_b_hex, &ni_b_len);
		nr_b = hex2data(nr_b_hex, &nr_b_len);

		skeyid_data_len = ni_b_len + nr_b_len;
		skeyid_data = Malloc(skeyid_data_len);
		cp = skeyid_data;
		memcpy(cp, ni_b, ni_b_len);
		cp += ni_b_len;
		memcpy(cp, nr_b, nr_b_len);
		skeyid = Malloc(20);
		hash_r_data_len = g_xr_len + g_xi_len + cky_r_len + cky_i_len +
				  sai_b_len + idir_b_len;
		hash_r_data = Malloc(hash_r_data_len);
		cp = hash_r_data;
		memcpy(cp, g_xr, g_xr_len);
		cp += g_xr_len;
		memcpy(cp, g_xi, g_xi_len);
		cp += g_xi_len;
		memcpy(cp, cky_r, cky_r_len);
		cp += cky_r_len;
		memcpy(cp, cky_i, cky_i_len);
		cp += cky_i_len;
		memcpy(cp, sai_b, sai_b_len);
		cp += sai_b_len;
		memcpy(cp, idir_b, idir_b_len);
		hash_r = Malloc(20);

		Gettimeofday(&start_time);
		for (i = 0; i < HMAC_SPEED_ITERATIONS; i++) {
			hmac_sha1(skeyid_data, skeyid_data_len, psk, psk_len,
				  skeyid);
			hmac_sha1(hash_r_data, hash_r_data_len, skeyid, 20,
				  hash_r);
		}
		Gettimeofday(&end_time);
		timeval_diff(&end_time, &start_time, &elapsed_time);
		elapsed_seconds = elapsed_time.tv_sec +
				  (elapsed_time.tv_usec / 1000000.0);
		printf(
			"%u SHA1 HASH_R calculations in %.6f seconds (%.2f per sec)\n",
			HMAC_SPEED_ITERATIONS, elapsed_seconds,
			HMAC_SPEED_ITERATIONS / elapsed_seconds);
	} while (0);

	printf("\nChecking MD5 hash speed...\n");
	do {
		size_t hash_data_len;
		unsigned char *hash_result;
		struct timeval start_time;
		struct timeval end_time;
		struct timeval elapsed_time;
		double elapsed_seconds;
		unsigned char hash_speed_data[] = "12345678";
		size_t memcpy_len;

		hash_data_len = strlen((char *) hash_speed_data);
		memcpy_len = hash_data_len > 16 ? 16 : hash_data_len;
		Gettimeofday(&start_time);
		for (i = 0; i < HASH_SPEED_ITERATIONS; i++) {
			hash_result =
				MD5(hash_speed_data, hash_data_len, NULL);
			memcpy(hash_speed_data, hash_result, memcpy_len);
		}
		Gettimeofday(&end_time);
		timeval_diff(&end_time, &start_time, &elapsed_time);
		elapsed_seconds = elapsed_time.tv_sec +
				  (elapsed_time.tv_usec / 1000000.0);
		printf("%u MD5 calculations in %.6f seconds (%.2f per sec)\n",
		       HASH_SPEED_ITERATIONS, elapsed_seconds,
		       HASH_SPEED_ITERATIONS / elapsed_seconds);
	} while (0);

	printf("\nChecking SHA1 hash speed...\n");
	do {
		size_t hash_data_len;
		unsigned char *hash_result;
		struct timeval start_time;
		struct timeval end_time;
		struct timeval elapsed_time;
		double elapsed_seconds;
		unsigned char hash_speed_data[] = "12345678";
		size_t memcpy_len;

		hash_data_len = strlen((char *) hash_speed_data);
		memcpy_len = hash_data_len > 20 ? 20 : hash_data_len;
		Gettimeofday(&start_time);
		for (i = 0; i < HASH_SPEED_ITERATIONS; i++) {
			hash_result =
				SHA1(hash_speed_data, hash_data_len, NULL);
			memcpy(hash_speed_data, hash_result, memcpy_len);
		}
		Gettimeofday(&end_time);
		timeval_diff(&end_time, &start_time, &elapsed_time);
		elapsed_seconds = elapsed_time.tv_sec +
				  (elapsed_time.tv_usec / 1000000.0);
		printf("%u SHA1 calculations in %.6f seconds (%.2f per sec)\n",
		       HASH_SPEED_ITERATIONS, elapsed_seconds,
		       HASH_SPEED_ITERATIONS / elapsed_seconds);
	} while (0);

	if (error)
		return EXIT_FAILURE;
	else
		return EXIT_SUCCESS;
}
void
cerebrod_speaker_data_get_heartbeat_metric_data(struct cerebrod_message *msg,
        unsigned int *message_len,
        int *more_data_to_send)
{
    struct cerebrod_speaker_metric_info *metric_info;
    ListIterator itr = NULL;
    struct timeval tv;

    assert(msg && message_len && more_data_to_send);

    if (!speaker_data_init)
        CEREBRO_EXIT(("initialization not complete"));

    *more_data_to_send = 0;

#if !WITH_CEREBROD_NO_THREADS
    Pthread_mutex_lock(&metric_list_lock);
#endif /* !WITH_CEREBROD_NO_THREADS */

    /* There may not be any metrics to distribute */
    if (!metric_list_size)
    {
        msg->metrics_len = 0;
        msg->metrics = NULL;
        goto lock_out;
    }

    msg->metrics_len = 0;
    msg->metrics = Malloc(sizeof(struct cerebrod_message_metric *)*(metric_list_size + 1));
    memset(msg->metrics, '\0', sizeof(struct cerebrod_message_metric *)*(metric_list_size + 1));

    Gettimeofday(&tv, NULL);

    itr = List_iterator_create(metric_list);
    while ((metric_info = list_next(itr)))
    {
        struct cerebrod_message_metric *mm = NULL;

        if (tv.tv_sec <= metric_info->next_call_time)
            break;

        if (metric_info->metric_origin & CEREBROD_METRIC_SPEAKER_ORIGIN_MODULE
                && !(metric_info->metric_flags & CEREBRO_METRIC_MODULE_FLAGS_SEND_ON_PERIOD))
            mm = _get_module_metric_value(metric_info->index);

        if (metric_info->metric_origin & CEREBROD_METRIC_SPEAKER_ORIGIN_USERSPACE)
            mm = _get_userspace_metric_value(metric_info);

        if (mm)
        {
            unsigned int new_len;

            new_len = *message_len + CEREBROD_MESSAGE_METRIC_HEADER_LEN + mm->metric_value_len;
            if (new_len >= CEREBRO_MAX_PACKET_LEN)
            {
                *more_data_to_send = 1;
                goto sort_out;
            }
            else
            {
                *message_len += CEREBROD_MESSAGE_METRIC_HEADER_LEN;
                *message_len += mm->metric_value_len;
                msg->metrics[msg->metrics_len] = mm;
                msg->metrics_len++;
            }
        }

        if (metric_info->metric_origin & CEREBROD_METRIC_SPEAKER_ORIGIN_MODULE)
        {
            if (metric_info->metric_period < 0)
                metric_info->next_call_time = UINT_MAX;

            /*
             * Metric period stays at 0 for metrics that need to be
             * propogated every time
             */
            if (metric_info->metric_period > 0)
                metric_info->next_call_time = tv.tv_sec + metric_info->metric_period;
        }

        if (metric_info->metric_origin & CEREBROD_METRIC_SPEAKER_ORIGIN_USERSPACE)
            metric_info->next_call_time = UINT_MAX;
    }
sort_out:
    List_iterator_destroy(itr);
    cerebrod_speaker_data_metric_list_sort();
lock_out:
#if !WITH_CEREBROD_NO_THREADS
    Pthread_mutex_unlock(&metric_list_lock);
#endif /* !WITH_CEREBROD_NO_THREADS */
    return;
}
示例#26
0
int
main(int argc, char **argv)
{
	
	int n, i, size, prflag;
	int pos = 3;
	int maxfd;
	int rt_sockfd,recv_ping_sockfd;
	int send_mulcst_fd, recv_mulcst_fd;
	const int on = 1;
	
	char buff_recv[BUFFSIZE];
	char tour_array[TOURNUM][IPLEN];
	char *ptr;

	fd_set  rset;
	struct timeval tval, tval1, tval2, tval3, tval4;
	struct sockaddr_ll saddrll;

	Signal(SIGALRM, sig_alrm);
	//Signal(SIGCHLD, sig_chld);
	uname(&myname);
	
	if (argc == 1){
		fputs("This is NOT source node\n", stdout);
		//_is_src_node = 0;
		source_flag = 0;
	}else{
		fputs("I'm source node, start to send tour infomation \n", stdout);
		//_is_src_node = 1;
		source_flag = 1;
	}

	
	//if (uname(&myname) < 0)
		//err_sys("uname error");

	for ( hwa = Get_hw_addrs(); hwa != NULL; hwa = hwa->hwa_next) {

		if(strcmp(hwa->if_name,"eth0")==0){
		
			/* in eth0 we create pfsocket and bind it to hw addr, this pf socket is for sned ping info */
			//pf_sockfd = socket(PF_PACKET, SOCK_RAW,htons(ETH_P_IP));
			send_ping_pf_sockfd = socket(PF_PACKET, SOCK_RAW,htons(ETH_P_IP));
			//send_ping_pf_sockfd use to send ping to source node
			saddrll.sll_family      = PF_PACKET;
			saddrll.sll_ifindex     = hwa->if_index;
			saddrll.sll_protocol    = htons(ETH_P_IP); 
			bind(send_ping_pf_sockfd, (struct sockaddr *) &saddrll, sizeof(saddrll));
			
			
			printf("%s :%s", hwa->if_name, ((hwa->ip_alias) == IP_ALIAS) ? " (alias)\n" : "\n");
		
			if ( (sa = hwa->ip_addr) != NULL)
				printf("IP addr = %s\n", Sock_ntop_host(sa, sizeof(*sa)));
				
			prflag = 0;
			i = 0;
			do {
				if (hwa->if_haddr[i] != '\0') {
					prflag = 1;
					break;
				}
			} while (++i < IF_HADDR);

			if (prflag) {
				printf("         HW addr = ");
				ptr = hwa->if_haddr;
				i = IF_HADDR;
				do {
					printf("%.2x%s", *ptr++ & 0xff, (i == 1) ? " " : ":");
				} while (--i > 0);
			}
			printf("\n         Interface Index = %d\n\n", hwa->if_index);	
			break;
		}
		
	}
	
	
	/* creat two raw sockets for route travesal and receive ping*/

	rt_sockfd = Socket(AF_INET, SOCK_RAW, 254);
	setsockopt(rt_sockfd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on));
	
	recv_ping_sockfd = Socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
	setuid(getuid());           /* don't need special permissions any more */
	size = 60 * 1024;           /* OK if setsockopt fails */
	setsockopt (recv_ping_sockfd, SOL_SOCKET, SO_RCVBUF, &size, sizeof (size));
		
	if (source_flag == 1)
	{//this node is source 

		struct icmp *icmp;
		struct ip* ip;
		int node_num;
		
		node_num = argc + 3;
		strcpy(tour_array[0], Sock_ntop_host(sa, sizeof(*sa)));//first one is source code

		sprintf(tour_array[1],"%d",argc - 1);
		sprintf(tour_array[2],"%d",node_num);
		sprintf(tour_array[3],"%d",4);
		for (i = 4; i < node_num; i++)
			strcpy(tour_array[i], getipbyvm(argv[i-3]));

//////////////////////////before send we let the source node join the multicast

		send_mulcst_fd = Udp_client(MC_ADDR_LIN, MC_PORT_LIN, (void **) &sasend, &salen);
		recv_mulcst_fd = Socket(AF_INET, SOCK_DGRAM, 0);
		Setsockopt(recv_mulcst_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
		sarecv = Malloc(salen);
		memcpy(sarecv, sasend, salen);
	
		Bind(recv_mulcst_fd, sarecv, salen);
		Mcast_join(recv_mulcst_fd, sasend, salen, NULL, 0);
		Mcast_set_loop(send_mulcst_fd, 0);
///////////////////////////////////////////////	this is the send tour part
	
		rt_send(rt_sockfd, tour_array);
	
		for(;;){
			if(first_mulcst_flag == 1){
				
				printf("wait for first multicast info\n");
				recv_all(recv_mulcst_fd, salen);
				first_mulcst_flag = 0;
				char buf[MAXLINE];
				//sleep(1);
				snprintf(buf, sizeof(buf), "<<<<< Node: %s I am a member of the group.>>>>>\n", myname.nodename);
				send_all(send_mulcst_fd, sasend, salen, buf);
				
			}else{
				for(;;){
					recv_all(recv_mulcst_fd, salen);
					printf("Waiting for 5 seconds and exit\n");
					
				}
			}
		}
			
	
			
		
		
		
	}else{//not source node
		pthread_t tid, tid2;
		char source_name[IPLEN];
		
		for( ;; )
		{
			FD_ZERO(&rset);
			
			FD_SET(rt_sockfd, &rset);
			
			
			maxfd = rt_sockfd;
			if(rt_recved_flag == 1){
				FD_SET(recv_ping_sockfd, &rset);
				maxfd = max(recv_ping_sockfd, maxfd);
			}
			
			if (ns_first_flag == 0)
			{
				FD_SET(recv_mulcst_fd,&rset);
				//maxfd = (maxfd > recv_mulcst_fd) ? maxfd : recv_mulcst_fd;
				maxfd = max(maxfd, recv_mulcst_fd);
			}
			
			//printf("before select\n");
			
			select(maxfd + 1, &rset, NULL, NULL, NULL);
			
			if (FD_ISSET(rt_sockfd, &rset)) 
			{    
				printf("receive route travelsal paket\n");
				n = rt_recv(rt_sockfd, tour_array);
				memcpy(dest_ip_addr, tour_array[0], IPLEN);
				if (n < 0) {
					if (errno == EINTR)
						continue;
				else
					err_sys("receive tour packet error");
				}
				
			    get_vmname(tour_array[0], source_name);
				
				
				 if (ns_first_flag == 1)
				{
					ns_first_flag = 0;
					rt_recved_flag = 1;
					
					// join the multicast first
					send_mulcst_fd = Udp_client(MC_ADDR_LIN, MC_PORT_LIN, (void **) &sasend, &salen);
					recv_mulcst_fd = Socket(AF_INET, SOCK_DGRAM, 0);
					Setsockopt(recv_mulcst_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
					sarecv = Malloc(salen);
					memcpy(sarecv, sasend, salen);
					Bind(recv_mulcst_fd, sarecv, salen);
					Mcast_join(recv_mulcst_fd, sasend, salen, NULL, 0);
					Mcast_set_loop(send_mulcst_fd, 0);
					
					//create a thread for ping
					Pthread_create(&tid, NULL, &ping, NULL);
						
				
				} 
				if(last_node_flag == 0){
					rt_send(rt_sockfd, tour_array);
				}else{
					//create a thread to handle last operations
					Pthread_create(&tid2, NULL, &ls_send_mul, &send_mulcst_fd);
				}
			}
			
			if (FD_ISSET(recv_mulcst_fd, &rset)) 
			{//recv multicast info
				if (first_mulcst_flag == 1 )
				{
					first_mulcst_flag = 0;
					ping_over_flag = 1;//
					//printf("ping_over_flag is %d\n", ping_over_flag);
					recv_all(recv_mulcst_fd, salen);
					char buf[MAXLINE];
					snprintf(buf, sizeof(buf), "<<<<< Node: %s I am a member of the group.>>>>>\n", myname.nodename);
					send_all(send_mulcst_fd, sasend, salen, buf); 
					//printf("gonna go to alarm with pof changed\n");
					alarm(0);
				
				}else{
						
						for(;;){
							recv_all(recv_mulcst_fd, salen);
						}
						printf("Waiting for 5 seconds and exit\n");
					}
				
			}
			
			 if (FD_ISSET(recv_ping_sockfd, &rset)) 
			{//recv ping reply
				//printf("received ping reply\n");
				recvfrom(recv_ping_sockfd, buff_recv, MAXLINE, 0, NULL, NULL);
				Gettimeofday (&tval, NULL);
				proc_v4 (buff_recv, n, &tval);
				if (ping_over_flag == 1)
					alarm(0);
			} 	
				
		}
	}
	

}
示例#27
0
void send_icmp_request(unsigned char *dst_mac)
{
	static int nset= 0;
	unsigned char buffer[MAXLINE]={};
	int icmplen = 8+icmpdata;
	int length = sizeof(my_ip_header)+sizeof(my_eth_header)+icmplen;
	int ip_len = sizeof(my_ip_header)+icmplen;
	my_eth_header		eh;
	my_ip_header 		iph;
	struct icmp		    *icmp;
	unsigned char       sendbuf[MAXLINE];


	icmp= (struct icmp*)sendbuf;
	struct sockaddr_ll  dest_addr;

	bzero(buffer, sizeof(buffer));

	memcpy(eh.h_dest, dst_mac, ETH_ALEN);	
	memcpy(eh.h_source, eth0_mac, ETH_ALEN);	
	eh.h_proto = htons(ETH_P_IP);

	//iph.ihl      =  5;
	//iph.version  =  4;
	iph.v_hl = (4<<4)+5;
	iph.tos 	 =  0;
	iph.tot_len  =  htons(ip_len);
	iph.id  	 =  htons(MY_IP_ID);
	iph.fragment =  0;
	iph.ttl      =  MAX_VISITS;
	iph.protocol =  IPPROTO_ICMP;
	iph.check    = 0;
	iph.check    = cksum(&iph, 20);//htons((in_cksum((unsigned short *)&iph,20)));
	fill_buff_with_ip_of_hostname(our_hostname);
	inet_aton(ip_static_buff, (struct in_addr *)&iph.saddr);
	memcpy(&iph.daddr, &dest_of_echo_req, sizeof(iph.daddr));

	//icmph.icmph_type     =  MY_ICMP_ECHO;
	//icmph.icmph_code     =  0;
	//icmph.icmph_checksum =  0;
	//icmph.icmph_id       =  MY_ICMP_ID;
	//icmph.icmph_sequence =  nset++;
	//icmph.icmph_checksum = in_cksum((unsigned short*)&icmph, 8+icmpdata);

	icmp->icmp_type = ICMP_ECHO;
	icmp->icmp_code = 0;
	icmp->icmp_id  = htons(MY_ICMP_ID);
	icmp->icmp_seq = htons(nset++);

	memset(icmp->icmp_data, 0xa5, icmpdata);

	Gettimeofday((struct timeval*)(icmp->icmp_data), NULL);
	
	icmp->icmp_cksum = 0;
	icmp->icmp_cksum  = (in_cksum((unsigned short*)icmp, icmplen));
	

	//printf("echo request length %d\n", length);
	memcpy(buffer, &eh, sizeof(eh));
	memcpy(buffer+sizeof(eh), &iph, sizeof(iph));
	memcpy(buffer+sizeof(eh)+sizeof(iph), icmp, icmplen);

	bzero(&dest_addr, sizeof(dest_addr));
	dest_addr.sll_family   =  PF_PACKET;
	dest_addr.sll_protocol =  htons(ETH_P_IP);	
	dest_addr.sll_ifindex  =  eth0_if;
	// dest_addr.sll_hatype   =  ARPHRD_ETHER;
	// dest_addr.sll_pkttype  =  PACKET_OTHERHOST;
	dest_addr.sll_halen    =  ETH_ALEN;
	memcpy(dest_addr.sll_addr, dst_mac, ETH_ALEN);
	//int j =0;
	//for(;j< length; j++)
	//{
	//	printf("%.2x ", buffer[j]);
	//	if((j-9) % 10 == 0) printf("\n");
	//	fflush(stdout);
	//}
	Sendto(request_sock, buffer, length, 0, (struct sockaddr *)&dest_addr, sizeof(dest_addr));
}
示例#28
0
int main(int argc, char **argv){
	const int  on = 1;
	unsigned char ttl = 1;
	time_t 	   rawtime;
	time_t 	   lasttime;
	int 	   maxfd;
	fd_set 	   rset;
	ssize_t	   how_much_read;
	char	   msg[MAXLINE];

	rt 			   = Socket(AF_INET, SOCK_RAW, MY_IP_PROTO);
	Setsockopt(rt, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on));

	pg			   = Socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
	request_sock   = Socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP));
	multicast_sock = Socket(AF_INET, SOCK_DGRAM, 0);
	multicast_recv = Socket(AF_INET, SOCK_DGRAM, 0);
	Mcast_set_loop(multicast_sock,0);
	Setsockopt(multicast_sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
	Setsockopt(multicast_recv, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));

	gethostname(our_hostname, sizeof(our_hostname));
	//printf("My our_hostname: %s\n", our_hostname);
	get_eth0_stuff();
	if(argc > 1)
	{
		//DEBUG("%s is the start of the tour!\n",our_hostname);

		int   i = 1;		
		tour  tour_pkt;
		
		// separate func
		bzero(&tour_pkt, sizeof(tour_pkt));

		fill_buff_with_ip_of_hostname(our_hostname);
		//printf("fill buff ok\n");
		inet_aton(ip_static_buff, &(tour_pkt.payload[0]));
		join_mcast(MULTICAST_ADDRESS, MULTICAST_PORT);
		#if 0
		// tokenize by ' ' and send each char* to gethostbyname
		char 		*token, *prev_token;
		const char  s[2] = " ";

		/* get the first token */
		token = strtok(argv[1], s);

		/* walk through other tokens */
		while(token != NULL)
		{
			DEBUG("token = %s\n", token );

			fill_buff_with_ip_of_hostname(token);
			inet_aton(ip_static_buff, &tour_pkt.payload[i]);

			prev_token  = token;
			token 		= strtok(NULL, s);
			if(!strcmp(prev_token, token)){
				perror("The same node should not appear consequentively in the tour list – i.e., the next node on the tour cannot be the current node itself");
				exit(0);
			}

			i++;
		}
		// separate func
		#endif
		while(i< argc)
		{
			//printf("argv[%d] is %s\n",i, argv[i]);
			fill_buff_with_ip_of_hostname(argv[i]);
			//printf("fill buff ok\n");
			inet_aton(ip_static_buff, &(tour_pkt.payload[i]));
			i++;
		}
		tour_pkt.index = 0; // We're the origin
		tour_pkt.total = i-1;
		//printf("tour_pkt total %d\n", tour_pkt.total);
		send_raw_tour_packet(&tour_pkt);

	}else{
		//DEBUG("We're NOT the start of the tour!");
		#if 0
		while(1)
		{
			int len = 0;
			len = Recv(rt, msg, sizeof(msg), 0);
			printf("received len %d\n",len);
			int j = 0;
			for(;j<len; j++)
			{
				printf("%.2x ", msg[j]);
				if((i-9) % 10 == 0) printf("\n");
				fflush(stdout);
			}
		}
		#endif
	}
	#if 0
	fill_buff_with_ip_of_hostname("vm2");
	inet_aton(ip_static_buff, (struct in_addr *)&dest_of_echo_req);
	printf("destofechoreq %x\n", dest_of_echo_req.s_addr);
	struct sockaddr_in IPaddr;
	struct hwaddr 	   HWaddr;
	bzero(&IPaddr, sizeof(IPaddr));
	bzero(&HWaddr, sizeof(HWaddr));
	IPaddr.sin_addr = dest_of_echo_req;
	//Areq((struct sockaddr *)&IPaddr, sizeof(struct sockaddr_in), &HWaddr);
	//printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",HWaddr.sll_addr[0],HWaddr.sll_addr[1],HWaddr.sll_addr[2],
	//			HWaddr.sll_addr[3],HWaddr.sll_addr[4],HWaddr.sll_addr[5]);
	void sig_alrm(int signo);
	if(argc > 1){
	Signal(SIGALRM, sig_alrm);
	sig_alrm(SIGALRM);
	}
	//send_icmp_request(HWaddr.sll_addr);
	int n  = 0;
	struct timeval tval;
	
	while(1)
	{
		n = recv(pg, msg, sizeof(msg), 0);
		if(n<0)
		{
			if (errno == EINTR)
				continue;
		}
		printf("receive ping packet\n");
		//int j = 0;
		//for (; j < n; j++)
		//{
		//	printf("%.2x ", msg[j]);
		//	if((j-9) % 10 == 0) printf("\n");
		//	fflush(stdout);
		//}
		Gettimeofday(&tval, NULL);
		proc_v4(msg,n,NULL, &tval);
	}
	#endif
	#if 1
    //act_open.sa_flags = 0;
    //sigemptyset(&act_open.sa_mask);
    //sigaddset(&act_open.sa_mask, SIGALRM);
    //act_open.sa_handler = terminate;
	Signal(SIGALRM, sig_alrm);
	FD_ZERO(&rset);
	maxfd = max(pg, multicast_recv);
	maxfd = max(rt, maxfd);

	while(1){
		FD_SET(multicast_recv, &rset);
		FD_SET(rt, &rset);
		FD_SET(pg, &rset);

		if(select(maxfd+1, &rset, NULL, NULL, NULL)<0)
		{
			if(errno == EINTR)
			{
				continue;
			}
		}

		if(FD_ISSET(rt, &rset)){
			//DEBUG("possibly totally wrong here\n");
			//DEBUG("possibly totally wrong here\n");
			//DEBUG("possibly totally wrong here\n");
			alarm(0);
			bzero(msg, sizeof(msg));
			how_much_read = Recv(rt, msg, sizeof(msg), 0);
		

			//assert(how_much_read == sizeof(sizeof(my_ip_header)+sizeof(tour)));
			//printf("rt receive pkt len %d\n", how_much_read);
			my_ip_header  *head     =  (my_ip_header *)msg;
			tour 		  *tour_pkt =  (tour *)(msg+sizeof(my_ip_header));
			
			if(ntohs(head->id) != MY_IP_ID){
				//DEBUG("head->id != MY_IP_ID\n");
				continue;
			}
			char *name = find_vm_name(inet_ntoa(*(struct in_addr *)&head->saddr));
			time(&rawtime);
			printf("<%s> recieved source routing packet from <%s>\n", ctime (&rawtime), name);
			
			if(!already_here){
				already_here = 1;
				// IP_MULTICAST_TTL - If not otherwise specified, has a default value of 1.
				join_mcast(inet_ntoa(tour_pkt->multicast_addr), ntohs(tour_pkt->multicast_port));
				stop_pinging = 0;
			}
				// start icmp echo reqs
			for(i = 0; i < prev_sender_list.index; i++)
			{
				if(!memcmp(&prev_sender_list.previous_senders[i], &tour_pkt->payload[(tour_pkt->index)], sizeof(struct in_addr)))
					we_dont_need_to_send_echo_req = 1;
				else{
					we_dont_need_to_send_echo_req = 0;
					break;
				}
			}

			if(!we_dont_need_to_send_echo_req){
				//DEBUG("We Need To Send Echo Request\n");

				prev_sender_list.previous_senders[prev_sender_list.index] = tour_pkt->payload[(tour_pkt->index)];
				prev_sender_list.index++;

				dest_of_echo_req = tour_pkt->payload[(tour_pkt->index)];

				char *name = find_vm_name(inet_ntoa(*(struct in_addr *)&tour_pkt->payload[(tour_pkt->index)]));
				printf("PING %s (%s): %d data bytes\n",name,inet_ntoa(dest_of_echo_req), icmpdata);
				sig_alrm(SIGALRM);
			}
			else
			{
				char *name = find_vm_name(inet_ntoa(*(struct in_addr *)&tour_pkt->payload[(tour_pkt->index)]));
				printf("We have ping %s before\n",name);
			}
			

			// INCREMENTING THE INDEX
			tour_pkt->index = (tour_pkt->index)+1;
			if((tour_pkt->index) == MAX_VISITS){
				perror("MAX_VISITS has been reached.");
				exit(0);
			}

			// Now blank
			//bzero(&for_comparisons, sizeof(for_comparisons));
			// ghiTODO this may not work ghiTODO
			//if(!memcmp(&tour_pkt->payload[ntohl(tour_pkt->index)], &for_comparisons, sizeof(for_comparisons))){
			//printf("rt current pkt index %d, total index %d\n",tour_pkt->index, tour_pkt->total);
			if(tour_pkt->index == tour_pkt->total)
			{
				//printf("We're the final destination.\n");
				// ping the saddr
				final_destination = 1;
				char buffer[100];
				snprintf(buffer, 100, "<<<<< This is node %s.  Tour has ended.  Group members please identify yourselves. >>>>>",our_hostname);
				printf("Node %s.  Sending: <%s>.  ",our_hostname, buffer);
				send_multicast_message(buffer,strlen(buffer)+1);
				//printf("send mulitcast msg ok\n");

			}else{
				//printf("We're NOT the final destination, keep touring.\n");
				// pass it along
				send_raw_tour_packet(tour_pkt);
			}


		}else if(FD_ISSET(multicast_recv, &rset)){
			//DEBUG("Receiving multicast message.\n");
			printf("");
			bzero(msg, sizeof(msg));
			how_much_read = Recv(multicast_recv, msg, sizeof(msg), 0);
			//printf("multicast msg len %d\n", how_much_read);
			msg[how_much_read]='\0';
			if(!first_term){
				printf("Node %s.  Received <%s>.  ",our_hostname,msg);
				// then should immediately stop ping 
				//DEBUG("how_much_read is %lu\n", how_much_read);
				stop_pinging = 1;
				alarm(0);
				bzero(msg, sizeof(msg));
				snprintf(msg, sizeof(msg), "<<<<< Node %s I am a member of the group. >>>>>", our_hostname);
				printf("Node %s. Sending <%s>.  ", our_hostname, msg);
				fflush(stdout);
				first_term = 1;
				send_multicast_message(msg,strlen(msg)+1);
			}
			else
			{
				Signal(SIGALRM, terminate);
				alarm(5);
				printf("");
				printf("Node %s.  Received <%s>.  ",our_hostname,msg);
				fflush(stdout);
			}

			//send_multicast_message(msg);
		}else if(FD_ISSET(pg, &rset)){
			//DEBUG("Receiving echo reply message.\n");
			struct timeval tval;
			bzero(msg, sizeof(msg));
			how_much_read = Recv(pg, msg, sizeof(msg), 0);
			Gettimeofday(&tval, NULL);
			proc_v4(msg,how_much_read,NULL, &tval);
			//assert(how_much_read == sizeof(sizeof(my_eth_header)+sizeof(my_ip_header)+sizeof(my_icmp_header)));
			//DEBUG("how_much_read is %lu\n", how_much_read);
			//DEBUG("Node %s recieved %s\n", our_hostname, msg);
			// my_eth_header   *eh    =  (my_eth_header  *)msg;
			// my_ip_header    *iph   =  (my_ip_header   *)msg+sizeof(my_eth_header);
			// my_icmp_header  *icmph =  (my_icmp_header *)msg+sizeof(my_eth_header)+sizeof(my_ip_header);
			//my_ip_header *iph = (my_ip_header *)(msg+sizeof(my_eth_header));
			//if(!memcmp(&iph->saddr, &dest_of_echo_req, sizeof(dest_of_echo_req))){
			//	DEBUG("ghiTODO\n");
			//	count_of_replies++;
			//	DEBUG("ghiTODO\n");
				//DEBUG("ghiTODO\n");
				//DEBUG("ghiTODO\n");
			//	if(final_destination && count_of_replies >= 5){
			//		stop_pinging = 1;
			//		bzero(msg, sizeof(msg));
			///		snprintf(msg, sizeof(msg), "<<<<< This is node %s Tour has ended. Group members please identify yourselves.>>>>>", our_hostname);
			//		printf("Node %s sending %s", our_hostname, msg);
			//		send_multicast_message(msg, strlen(msg)+1);
			//		alarm(5);
			//	}
			//}else{
				//DEBUG("The following is FALSE !memcmp(&iph->saddr, &dest_of_echo_req, sizeof(dest_of_echo_req))");
			//}
		}
		#if 0
		time(&rawtime);
		if(lasttime+1 <= rawtime){
			if(!stop_pinging){	
				struct sockaddr_in IPaddr;
				struct hwaddr 	   HWaddr;
				bzero(&IPaddr, sizeof(IPaddr));
				bzero(&HWaddr, sizeof(HWaddr));
				IPaddr.sin_addr = dest_of_echo_req;
				Areq((struct sockaddr *)&IPaddr, sizeof(struct sockaddr_in), &HWaddr);
				send_raw_echo_request_message(HWaddr.sll_addr);
			}

		}else{
			lasttime = rawtime;
		}
		#endif

	}
	#endif
}
示例#29
0
文件: Progress.c 项目: aosm/ncftp
/* This routine should be called after a transfer finishes, even if no
 * progress reports were done.  Besides cleaning up the progress stuff,
 * we also do our logging here.
 */
void EndProgress(XferSpecPtr xp)
{
	double elapsedTime, xRate, xferred;
	char *unitStr;
	char *shortName;
	string statMsg;
	longstring fullRemote;
	long kb, hsecs;
	int wantStats;
	int localFileIsStdout;

	wantStats = 0;
	if ((xp->doReports) && (xp->bytesTransferred > 0) && (gVerbosity != kQuiet)) {
		ProgressReport(xp, kPrLastUpdateMsg);
		wantStats = (InForeGround()) &&
			((*xp->prProc)(xp, kPrEndMsg) == kPrWantStatsMsg);
	}
	(void) Gettimeofday(&xp->endTime);

	/* Compute transfer stats. */
	xRate = TransferRate(
		xp->bytesTransferred,
		&xp->startTime,
		&xp->endTime,
		&unitStr,
		&elapsedTime
	);

	/* Print the stats, if requested. */
	if (wantStats) {
		shortName = strrchr(xp->localFileName, '/');
		if (shortName == NULL)
			shortName = xp->localFileName;
		else
			shortName++;
		sprintf(statMsg, "%s:  %ld bytes %s%s in %.2f seconds",
			shortName,
			xp->bytesTransferred,
			NETREADING(xp) ? "received" : "sent",
			xp->startPoint ? " and appended to existing file" : "",
			elapsedTime
		);
		if (xRate > 0.0) {
			sprintf(statMsg + strlen(statMsg), ", %.2f %s",
				xRate,
				unitStr
			);
		}
		STRNCAT(statMsg, ".");
	
		/* Make sure echoing is back on! */
		Echo(stdin, 1);

		/* Make sure the rest of the line is padded with spaces, so it will
		 * erase junk that may have been leftover from a progress meter.
		 */
		EPrintF("%-79s\n", statMsg);
		FlushListWindow();
	} else {
		if (xRate > 0.0) {
			DebugMsg("%ld bytes transferred in %.2f seconds, %.2f %s.\n",
				xp->bytesTransferred,
				elapsedTime,
				xRate,
				unitStr
			);
		} else {
			DebugMsg("%ld bytes transferred in %.2f seconds.\n",
				xp->bytesTransferred,
				elapsedTime
			);
		}
	}

	/* Only log stuff if there was a remote filename specified.
	 * We don't want to log directory listings or globbings.
	 */
	if ((xp->remoteFileName != NULL)) {
		/* Get kilobytes transferred, rounding to the nearest kB. */
		kb = ((long) xp->bytesTransferred + 512L) / 1024L;
		OverflowAdd(&gTotalXferKiloBytes, kb);
		OverflowAdd(&gRmtInfo.xferKbytes, kb);

		/* Get hundredths of seconds, rounded up to nearest. */
		hsecs = (long) (100.0 * (elapsedTime + 0.0050));
		OverflowAdd(&gTotalXferHSeconds, hsecs);
		OverflowAdd(&gRmtInfo.xferHSeconds, hsecs);
		if (gTotalXferHSeconds < 0)
			gTotalXferHSeconds = 1L;
		if (gRmtInfo.xferHSeconds <= 0)
			gRmtInfo.xferHSeconds = 1L;

		localFileIsStdout =
			(STREQ(xp->remoteFileName, kLocalFileIsStdout));
	    /* If a simple path is given, try to log the full path. */
		if ((xp->remoteFileName[0] == '/') || (localFileIsStdout)) {
			/* Use what we had in the xp. */
			STRNCPY(fullRemote, xp->remoteFileName);
		} else {
			/* Make full path by appending what we had in the xp
			 * to the current remote directory.
			 */
			STRNCPY(fullRemote, gRemoteCWD);
			STRNCAT(fullRemote, "/");
			STRNCAT(fullRemote, xp->remoteFileName);
		}
	
		/* Save transfers to the user's logfile.  We only log something to
		 * the user log if we are actually saving a file;  we don't log
		 * to the user log if we are piping the remote output into something,
		 * or dumping it to stdout.
		 */
		if ((gLogFile != NULL) && (!localFileIsStdout)) {
			xferred = FileSize((double) xp->bytesTransferred, &unitStr, NULL);
			(void) fprintf(gLogFile, "  %-3s  %6.2f %-2s  ftp://%s%s\n",
				NETREADING(xp) ? "get" : "put",
				xferred,
				unitStr,
				gRmtInfo.name,
				fullRemote
			);
			fflush(gLogFile);
		}

#ifdef SYSLOG
    	{
        longstring infoPart1;

        /* Some syslog()'s can't take an unlimited number of arguments,
         * so shorten our call to syslog to 5 arguments total.
         */
        STRNCPY(infoPart1, gUserInfo.userName);
        if (NETREADING(xp)) {
            STRNCAT(infoPart1, " received ");
            STRNCAT(infoPart1, fullRemote);	/* kLocalFileIsStdout is ok. */
            STRNCAT(infoPart1, " as ");
            STRNCAT(infoPart1, xp->localFileName);
            STRNCAT(infoPart1, " from ");
        } else {
            STRNCAT(infoPart1, " sent ");
            STRNCAT(infoPart1, xp->localFileName);
            STRNCAT(infoPart1, " as ");
            STRNCAT(infoPart1, fullRemote);
            STRNCAT(infoPart1, " to ");
        }
        STRNCAT(infoPart1, gActualHostName);
#ifndef LOG_INFO
#	define LOG_INFO 6		/* Don't know if this is standard! */
#endif
        syslog (LOG_INFO, "%s (%ld bytes).", infoPart1, xp->bytesTransferred);
    	}
#endif  /* SYSLOG */
	}
}									   /* EndProgress */
示例#30
0
void *
cerebrod_listener(void *arg)
{
  char buf[CEREBRO_MAX_PACKET_LEN];

  _cerebrod_listener_initialize();

  for (;;)
    {
      struct cerebrod_message *msg;
      char nodename_buf[CEREBRO_MAX_NODENAME_LEN+1];
      char nodename_key[CEREBRO_MAX_NODENAME_LEN+1];
      struct timeval tv;
      int in_cluster_flag, i, count;
      fd_set readfds;
      int recv_len = 0;
      int maxfd = 0;

      FD_ZERO(&readfds);
      Pthread_mutex_lock(&listener_fds_lock);
      for (i = 0; i < conf.listen_message_config_len; i++)
        {
          if (listener_fds[i] > maxfd)
            maxfd = listener_fds[i];
          FD_SET(listener_fds[i], &readfds);
        }

      count = Select(maxfd + 1, &readfds, NULL, NULL, NULL);

      for (i = 0; i < conf.listen_message_config_len; i++)
        {
          if (FD_ISSET(listener_fds[i], &readfds))
            {
              if ((recv_len = recvfrom(listener_fds[i], 
                                       buf, 
                                       CEREBRO_MAX_PACKET_LEN, 
                                       0, 
                                       NULL, 
                                       NULL)) < 0)
                listener_fds[i] = cerebrod_reinit_socket(listener_fds[i], 
                                                         i,
                                                         _listener_setup_socket, 
                                                         "listener: recvfrom");
              break;
            }
        }
      Pthread_mutex_unlock(&listener_fds_lock);

      /* No packet read */
      if (recv_len <= 0)
	continue;

      if (recv_len >= CEREBRO_MAX_PACKET_LEN)
        {
	  CEREBROD_DBG(("received truncated packet"));
          continue;
        }

      if (_cerebrod_message_check_version(buf, recv_len) < 0)
        {
	  CEREBROD_DBG(("received invalid version packet"));
          continue;
        }

      if (!(msg = _cerebrod_message_unmarshall(buf, recv_len)))
        {
	  CEREBROD_DBG(("received unmarshallable packet"));
          continue;
        }

      _cerebrod_message_dump(msg, "Received Message");
      
      /* Guarantee ending '\0' character */
      memset(nodename_buf, '\0', CEREBRO_MAX_NODENAME_LEN+1);
      memcpy(nodename_buf, msg->nodename, CEREBRO_MAX_NODENAME_LEN);

      if (!strlen(nodename_buf))
        {
          CEREBROD_DBG(("received null nodename"));
          cerebrod_message_destroy(msg);
          continue;
        }

      if (found_clusterlist_module)
        {
          if ((in_cluster_flag = clusterlist_module_node_in_cluster(clusterlist_handle,
                                                                    nodename_buf)) < 0)
            CEREBROD_EXIT(("clusterlist_module_node_in_cluster: %s", nodename_buf));

          /* Second chance, is this data being forwarded from another host */
          if (!in_cluster_flag)
            {
              if (Hostlist_find(conf.forward_host_accept, nodename_buf) >= 0)
                in_cluster_flag++;
            }
        }
      else
        /* must assume it is in the cluster */
        /* Note, there is no need to handle 'forward_host_accept' under this case, 
         * since we don't know if it is in the cluster or not anyways.
         */
        in_cluster_flag = 1;
      
      if (!in_cluster_flag)
	{
	  CEREBROD_DBG(("received non-cluster packet: %s", nodename_buf));
          cerebrod_message_destroy(msg);
	  continue;
	}
      
      memset(nodename_key, '\0', CEREBRO_MAX_NODENAME_LEN+1);

      if (found_clusterlist_module)
        {
          if (clusterlist_module_get_nodename(clusterlist_handle,
                                              nodename_buf,
                                              nodename_key, 
                                              CEREBRO_MAX_NODENAME_LEN+1) < 0)
            {
              CEREBROD_DBG(("clusterlist_module_get_nodename: %s", nodename_buf));
              cerebrod_message_destroy(msg);
              continue;
            }
        }
      else
        memcpy(nodename_key, nodename_buf, CEREBRO_MAX_NODENAME_LEN+1);

      Gettimeofday(&tv, NULL);
      cerebrod_listener_data_update(nodename_key, msg, tv.tv_sec);

      /* Forward data as necessary.  Note, there is no need to
       * marshall data, it should already be marshalled when we
       * read it earlier.
       */
      for (i = 0; i < conf.forward_message_config_len; i++)
        {
          /* if the forward destination is local to the machine, don't forward */
          if (conf.forward_message_config[i].ip_is_local)
            continue;

          if (!forwarding_info[i].hosts
              || hostlist_find(forwarding_info[i].hosts, nodename_key) >= 0)
            {
              struct sockaddr *addr;
              struct sockaddr_in msgaddr;
              unsigned int addrlen;
              int rv;
              
              memset(&msgaddr, '\0', sizeof(struct sockaddr_in));
              msgaddr.sin_family = AF_INET;
              msgaddr.sin_port = htons(conf.forward_message_config[i].destination_port);
              memcpy(&msgaddr.sin_addr,
                     &conf.forward_message_config[i].ip_in_addr,
                     sizeof(struct in_addr));
              
              addr = (struct sockaddr *)&msgaddr;
              addrlen = sizeof(struct sockaddr_in);
              
              _cerebrod_message_dump(msg, "Forwarding Message");

              Pthread_mutex_lock(&forwarding_info[i].lock);
              
              if ((rv = sendto(forwarding_info[i].fd,
                               buf,
                               recv_len,
                               0,
                               addr,
                               addrlen)) != recv_len)
                {
                  if (rv < 0)
                    forwarding_info[i].fd = cerebrod_reinit_socket(forwarding_info[i].fd,
                                                                   i,
                                                                   _forwarding_setup_socket,
                                                                   "forwarding: sendto");
                  else
                    CEREBROD_ERR(("sendto: invalid bytes sent"));
                }
              
              Pthread_mutex_unlock(&forwarding_info[i].lock);
            }
        }

      cerebrod_message_destroy(msg);
    }

  return NULL;			/* NOT REACHED */
}