コード例 #1
0
ファイル: process.c プロジェクト: michaelstorm/Tangent
int process_stab_reply(Header *header, ChordPacketArgs *args,
					   StabilizeReply *msg, Node *from)
{
	ChordServer *srv = args->srv;
	Finger *succ;
	int fnew;
	chordID id;

	if (IN6_IS_ADDR_UNSPECIFIED(&srv->node.addr))
		return CHORD_ADDR_UNDISCOVERED;

	in6_addr addr;
	memcpy(addr.s6_addr, msg->addr.data, 16);

	get_address_id(&id, &addr, msg->port);

	LOG_PROCESS(&id, NULL, -1);

	// If we are our successor's predecessor, everything is fine, so do nothing.
	if (v6_addr_equals(&srv->node.addr, &addr) && srv->node.port == msg->port)
		return CHORD_NO_ERROR;

	// Otherwise, there is a better successor in between us and our current
	// successor. So we notify the in-between node that we should be its
	// predecessor.
	insert_finger(srv, &id, &addr, msg->port, &fnew);
	succ = succ_finger(srv);
	send_notify(srv, &succ->node.addr, succ->node.port);
	if (fnew)
		send_ping(srv, &addr, msg->port, get_current_time());
	return CHORD_NO_ERROR;
}
コード例 #2
0
ファイル: network.c プロジェクト: tapted/bomberclone-nacl
int
net_check_timeout (int pl_nr)
{
    int timeout = UDP_TIMEOUT;

    if ((players[pl_nr].state & (PSF_net + PSF_used + PSF_ai)) == (PSF_used + PSF_net)
        && ((players[pl_nr].net.flags & NETF_local2) == 0)
        && timestamp - players[pl_nr].net.timestamp > timeout
        && players[pl_nr].net.pingreq != players[pl_nr].net.pingack) {
        d_printf ("net_check_timeout pl_nr=%d, ack=%d, req=%d, timediff=%d\n", pl_nr,
                  players[pl_nr].net.pingack, players[pl_nr].net.pingreq,
                  timestamp - players[pl_nr].net.timestamp);
        players[pl_nr].net.timestamp = timestamp;
        players[pl_nr].net.pingack = players[pl_nr].net.pingreq;
        send_ping (&players[pl_nr].net.addr, players[pl_nr].net.pingack + 100, PKG_pingreq);
    }
    if ((players[pl_nr].state & (PSF_net + PSF_used + PSF_ai)) == (PSF_used + PSF_net)
        && ((players[pl_nr].net.flags & NETF_local2) == 0)
        && timestamp - players[pl_nr].net.timestamp > timeout
        && players[pl_nr].net.pingreq == players[pl_nr].net.pingack) {
        d_printf ("net_check_timeout pl_nr=%d, ack=%d, req=%d, timediff=%d\n", pl_nr,
                  players[pl_nr].net.pingack, players[pl_nr].net.pingreq,
                  timestamp - players[pl_nr].net.timestamp);
        return 1;
    }
    return 0;
};
コード例 #3
0
ファイル: process.c プロジェクト: michaelstorm/Tangent
int process_fs_reply(Header *header, ChordPacketArgs *args,
					 FindSuccessorReply *msg, Node *from)
{
	ChordServer *srv = args->srv;
	int fnew;
	chordID id;

	if (IN6_IS_ADDR_UNSPECIFIED(&srv->node.addr))
		return CHORD_ADDR_UNDISCOVERED;

	in6_addr addr;
	memcpy(addr.s6_addr, msg->addr.data, 16);

	get_address_id(&id, &addr, msg->port);

	if (!verify_ticket(srv->ticket_salt, srv->ticket_salt_len,
					   srv->ticket_hash_len, msg->ticket.data, msg->ticket.len,
					   "c", CHORD_FS))
		return CHORD_INVALID_TICKET;

	if (v6_addr_equals(&srv->node.addr, &addr) && srv->node.port == msg->port)
		return CHORD_NO_ERROR;
	
	LOG_PROCESS(&id, &from->addr, from->port);

	insert_finger(srv, &id, &addr, msg->port, &fnew);
	if (fnew)
		send_ping(srv, &addr, msg->port, get_current_time());

	return CHORD_NO_ERROR;
}
コード例 #4
0
ファイル: process.c プロジェクト: michaelstorm/Tangent
int process_ping(Header *header, ChordPacketArgs *args, Ping *msg, Node *from)
{
	ChordServer *srv = args->srv;
	int fnew;
	Finger *pred;

	if (IN6_IS_ADDR_UNSPECIFIED(&srv->node.addr))
		return CHORD_ADDR_UNDISCOVERED;

	LOG_PROCESS(&from->id, &from->addr, from->port);

	insert_finger(srv, &from->id, &from->addr, from->port, &fnew);
	if (fnew)
		Debug("Inserted a new possible finger");
	
	pred = pred_finger(srv);
	if (fnew && (pred == NULL || (pred != NULL && id_is_between(&from->id, &pred->node.id, &srv->node.id)))) {
		if (pred == NULL)
			Debug("We have no predecessor, and this is a possible new finger, so we ping it");
		else
			Debug("This possible new finger falls between our current predecessor and ourselves, so we ping it");
		
		send_ping(srv, &from->addr, from->port, get_current_time());
	}

	Debug("Replying to the ping with a pong");
	send_pong(srv, msg->ticket.data, msg->ticket.len, &from->addr, from->port, msg->time);

	return CHORD_NO_ERROR;
}
コード例 #5
0
ファイル: p2p.c プロジェクト: tempbottle/torrentkino
void p2p_bootstrap_this(const char *bootstrap_node, int bootstrap_port)
{
	struct addrinfo hints;
	struct addrinfo *addrinfo = NULL;
	struct addrinfo *p = NULL;
	int rc = 0;
	int i = 0;
	ITEM *ti = NULL;
	char port[6];

	snprintf(port, 6, "%i", bootstrap_port);

	/* Compute address of bootstrap node */
	memset(&hints, '\0', sizeof(struct addrinfo));
	hints.ai_socktype = SOCK_STREAM;

#ifdef IPV6
	hints.ai_family = AF_INET6;
#elif IPV4
	hints.ai_family = AF_INET;
#endif
	rc = getaddrinfo(bootstrap_node, port, &hints, &addrinfo);
	if (rc != 0) {
		/* info( _log, NULL, "getaddrinfo: %s", gai_strerror( rc ) ); */
		return;
	}

	p = addrinfo;
	while (p != NULL && i < P2P_MAX_BOOTSTRAP_NODES) {

		/* Send PING to a bootstrap node */
		if (strcmp(_main->conf->bootstrap_node, BOOTSTRAP_MCAST) == 0) {
			ti = tdb_put(P2P_PING_MULTICAST);
			send_ping((IP *) p->ai_addr, tdb_tid(ti));
		} else {
			ti = tdb_put(P2P_PING);
			send_ping((IP *) p->ai_addr, tdb_tid(ti));
		}

		p = p->ai_next;
		i++;
	}

	freeaddrinfo(addrinfo);
}
コード例 #6
0
ファイル: flux-ping.c プロジェクト: SteVwonder/flux-core
/* Send a request each time the timer fires.
 * After 'ctx->count' requests have been sent, stop the watcher.
 */
void timer_cb (flux_reactor_t *r, flux_watcher_t *w, int revents, void *arg)
{
    struct ping_ctx *ctx = arg;

    send_ping (ctx);
    if (ctx->send_count == ctx->count)
        flux_watcher_stop (w);
    else if (ctx->period == 0.) { /* needs rearm if repeat is 0. */
        flux_timer_watcher_reset (w, ctx->period, ctx->period);
        flux_watcher_start (w);
    }
}
// the main function
int main(){ 
	int msl, msr;			// Wheel speeds
	double *rbuffer;
   	double buffer[255];
   	int j;

   	for(;;) {
	 	reset();			// Resetting the robot
	  
	  	while (wb_receiver_get_queue_length(receiver0) == 0)
        	wb_robot_step(64);
    	      
    	rbuffer = (double *)wb_receiver_get_data(receiver0);

    	COEF_KP = rbuffer[0];
    	COEF_B = rbuffer[1];
    	COEF_R = rbuffer[2];
    	COEF_S = rbuffer[3];
    	COEF_T = rbuffer[4];

		msl = 0; msr = 0; 
		
		// Forever
		for(j = 0; j < NB_STEPS; ++j) {       
				/* Send and get information */
				send_ping();  // sending a ping to other robot, so they can measure their distance to this robot
				
				process_received_ping_messages();
							
				// Compute self position
				prev_my_position[0] = my_position[0];
				prev_my_position[1] = my_position[1];
				
				update_self_motion(msl,msr);
				
				speed[robot_id][0] = (1/DELTA_T)*(my_position[0]-prev_my_position[0]);
				speed[robot_id][1] = (1/DELTA_T)*(my_position[1]-prev_my_position[1]);
		    
				// Flocking behavior of the paper with the wheels speed
				flocking_behavior(&msl, &msr);
		    
				// Set speed
				wb_differential_wheels_set_speed(msl,msr);
		    
				// Continue one step
				wb_robot_step(TIME_STEP);
		}
		
		wb_emitter_send(emitter0,(void *)buffer,sizeof(double));   
     	wb_receiver_next_packet(receiver0);
	}
}  
コード例 #8
0
// send a ping to all players
void multi_ping_send_all()
{
	int idx;
	for(idx = 0;idx < MAX_PLAYERS;idx++){
		if(MULTI_CONNECTED(Net_players[idx]) && (Net_player != NULL) && (Net_player->player_id != Net_players[idx].player_id)){
			// start the ping
			multi_ping_start(&Net_players[idx].s_info.ping);			

			// send the ping packet
			send_ping(&Net_players[idx].p_info.addr);
		}
	}
}
コード例 #9
0
ファイル: friend_connection.c プロジェクト: TokTok/toxcore
/* main friend_connections loop. */
void do_friend_connections(Friend_Connections *fr_c, void *userdata)
{
    const uint64_t temp_time = mono_time_get(fr_c->mono_time);

    for (uint32_t i = 0; i < fr_c->num_cons; ++i) {
        Friend_Conn *const friend_con = get_conn(fr_c, i);

        if (friend_con) {
            if (friend_con->status == FRIENDCONN_STATUS_CONNECTING) {
                if (friend_con->dht_pk_lastrecv + FRIEND_DHT_TIMEOUT < temp_time) {
                    if (friend_con->dht_lock) {
                        dht_delfriend(fr_c->dht, friend_con->dht_temp_pk, friend_con->dht_lock);
                        friend_con->dht_lock = 0;
                        memset(friend_con->dht_temp_pk, 0, CRYPTO_PUBLIC_KEY_SIZE);
                    }
                }

                if (friend_con->dht_ip_port_lastrecv + FRIEND_DHT_TIMEOUT < temp_time) {
                    friend_con->dht_ip_port.ip.family = net_family_unspec;
                }

                if (friend_con->dht_lock) {
                    if (friend_new_connection(fr_c, i) == 0) {
                        set_direct_ip_port(fr_c->net_crypto, friend_con->crypt_connection_id, friend_con->dht_ip_port, 0);
                        connect_to_saved_tcp_relays(fr_c, i, (MAX_FRIEND_TCP_CONNECTIONS / 2)); /* Only fill it half up. */
                    }
                }
            } else if (friend_con->status == FRIENDCONN_STATUS_CONNECTED) {
                if (friend_con->ping_lastsent + FRIEND_PING_INTERVAL < temp_time) {
                    send_ping(fr_c, i);
                }

                if (friend_con->share_relays_lastsent + SHARE_RELAYS_INTERVAL < temp_time) {
                    send_relays(fr_c, i);
                }

                if (friend_con->ping_lastrecv + FRIEND_CONNECTION_TIMEOUT < temp_time) {
                    /* If we stopped receiving ping packets, kill it. */
                    crypto_kill(fr_c->net_crypto, friend_con->crypt_connection_id);
                    friend_con->crypt_connection_id = -1;
                    handle_status(fr_c, i, 0, userdata); /* Going offline. */
                }
            }
        }
    }

    if (fr_c->local_discovery_enabled) {
        lan_discovery(fr_c);
    }
}
コード例 #10
0
/* main friend_connections loop. */
void do_friend_connections(Friend_Connections *fr_c)
{
    uint32_t i;
    uint64_t temp_time = unix_time();

    for (i = 0; i < fr_c->num_cons; ++i) {
        Friend_Conn *friend_con = get_conn(fr_c, i);

        if (friend_con) {
            if (friend_con->status == FRIENDCONN_STATUS_CONNECTING) {
                if (friend_con->dht_pk_lastrecv + FRIEND_DHT_TIMEOUT < temp_time) {
                    if (friend_con->dht_lock) {
                        DHT_delfriend(fr_c->dht, friend_con->dht_temp_pk, friend_con->dht_lock);
                        friend_con->dht_lock = 0;
                    }
                }

                if (friend_con->dht_ip_port_lastrecv + FRIEND_DHT_TIMEOUT < temp_time) {
                    friend_con->dht_ip_port.ip.family = 0;
                }

                if (friend_con->dht_lock) {
                    if (friend_new_connection(fr_c, i) == 0) {
                        set_direct_ip_port(fr_c->net_crypto, friend_con->crypt_connection_id, friend_con->dht_ip_port, 0);
                        connect_to_saved_tcp_relays(fr_c, i, (MAX_FRIEND_TCP_CONNECTIONS / 2)); /* Only fill it half up. */
                    }
                }

            } else if (friend_con->status == FRIENDCONN_STATUS_CONNECTED) {
                if (friend_con->ping_lastsent + FRIEND_PING_INTERVAL < temp_time) {
                    send_ping(fr_c, i);
                }

                if (friend_con->share_relays_lastsent + SHARE_RELAYS_INTERVAL < temp_time) {
                    send_relays(fr_c, i);
                }

                if (friend_con->ping_lastrecv + FRIEND_CONNECTION_TIMEOUT < temp_time) {
                    /* If we stopped receiving ping packets, kill it. */
                    crypto_kill(fr_c->net_crypto, friend_con->crypt_connection_id);
                    friend_con->crypt_connection_id = -1;
                    handle_status(fr_c, i, 0); /* Going offline. */
                }
            }
        }
    }

    LANdiscovery(fr_c);
}
コード例 #11
0
ファイル: net.c プロジェクト: 95ulisse/tinc
/*
  Check if the other end is active.
  If we have sent packets, but didn't receive any,
  then possibly the other end is dead. We send a
  PING request over the meta connection. If the other
  end does not reply in time, we consider them dead
  and close the connection.
*/
static void check_dead_connections(void) {
	avl_node_t *node, *next;
	connection_t *c;

	for(node = connection_tree->head; node; node = next) {
		next = node->next;
		c = node->data;

		if(c->last_ping_time + pingtimeout <= now) {
			if(c->status.active) {
				if(c->status.pinged) {
					ifdebug(CONNECTIONS) logger(LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds",
							   c->name, c->hostname, (long)now - c->last_ping_time);
					c->status.timeout = true;
					terminate_connection(c, true);
				} else if(c->last_ping_time + pinginterval <= now) {
					send_ping(c);
				}
			} else {
				if(c->status.remove) {
					logger(LOG_WARNING, "Old connection_t for %s (%s) status %04x still lingering, deleting...",
						   c->name, c->hostname, bitfield_to_int(&c->status, sizeof c->status));
					connection_del(c);
					continue;
				}
				ifdebug(CONNECTIONS) logger(LOG_WARNING, "Timeout from %s (%s) during authentication",
						   c->name, c->hostname);
				if(c->status.connecting) {
					c->status.connecting = false;
					closesocket(c->socket);
					do_outgoing_connection(c);
				} else {
					terminate_connection(c, false);
				}
			}
		}

		if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout <= now) {
			if(c->status.active) {
				ifdebug(CONNECTIONS) logger(LOG_INFO,
						"%s (%s) could not flush for %ld seconds (%d bytes remaining)",
						c->name, c->hostname, (long)now - c->last_flushed_time, c->outbuflen);
				c->status.timeout = true;
				terminate_connection(c, true);
			}
		}
	}
}
コード例 #12
0
ファイル: vivaldi.cpp プロジェクト: jayp/Rappel
int Vivaldi::timer_periodic_ping(Event& event) {

  PeriodicVivaldiPingEventData* evt_data
    = dynamic_cast<PeriodicVivaldiPingEventData*>(event.data);
  assert(evt_data != NULL);
  
  // schedule the next periodic ping
  schedule_periodic_ping(false);

  // send a ping for this period
  send_ping();
 
  // free memory
  delete(evt_data);
  return 0;
}
コード例 #13
0
ファイル: process.c プロジェクト: michaelstorm/Tangent
int process_notify(Header *header, ChordPacketArgs *args, Notify *msg,
				   Node *from)
{
	ChordServer *srv = args->srv;
	int fnew;

	if (IN6_IS_ADDR_UNSPECIFIED(&srv->node.addr))
		return CHORD_ADDR_UNDISCOVERED;

	LOG_PROCESS(&from->id, &from->addr, from->port);

	// another node thinks that it should be our predecessor
	insert_finger(srv, &from->id, &from->addr, from->port, &fnew);
	if (fnew)
		send_ping(srv, &from->addr, from->port, get_current_time());
	return CHORD_NO_ERROR;
}
コード例 #14
0
ファイル: bot.c プロジェクト: ct187/irc-bot
static void process_message(struct irc_message *msg)
{
	if (!joined && !strcmp("MODE", msg->command)) {
		send_join();
		return;
	} else if (!sent_nick && !strcmp("NOTICE", msg->command)) {
		send_nick();
		return;
	} else if (!strcmp("PING", msg->command)) {
		send_ping(msg->params);
		return;
	} else if (strcmp("PRIVMSG", msg->command)) {
		return;
	}

	process_priv_message(msg);
}
コード例 #15
0
ファイル: vivaldi.cpp プロジェクト: jayp/Rappel
int Vivaldi::timer_wait_after_ping_req(Event& evt) {

  WaitAfterVivaldiPingReqEventData* evt_data
    = dynamic_cast<WaitAfterVivaldiPingReqEventData *>(evt.data);

  _wait_for_ping_reply = NO_SUCH_EVENT_ID; // no scheduled ping
  _ping_in_progress = false; // the previous ping failed

  // send another ping request
  if (_num_ping_replies < globops.bootstrap_vivaldi_pongs_min) {
    send_ping(); 
  }

  // free memory
  delete(evt_data);
  return 0;
}
コード例 #16
0
ファイル: pico_icmp4.c プロジェクト: jinhu/picotcp
static void next_ping(uint32_t now, void *arg)
{
  struct pico_icmp4_ping_cookie *newcookie, *cookie = (struct pico_icmp4_ping_cookie *)arg;
  IGNORE_PARAMETER(now);

	if(pico_tree_findKey(&Pings,cookie)){
    if (cookie->seq < cookie->count) {
      newcookie = pico_zalloc(sizeof(struct pico_icmp4_ping_cookie));
      if (!newcookie)
        return;
      memcpy(newcookie, cookie, sizeof(struct pico_icmp4_ping_cookie));
      newcookie->seq++;

	    pico_tree_insert(&Pings,newcookie);
      send_ping(newcookie);
    }
  }
}
コード例 #17
0
ファイル: friend_connection.c プロジェクト: rmoorman/toxcore
/* main friend_connections loop. */
void do_friend_connections(Friend_Connections *fr_c)
{
    uint32_t i;
    uint64_t temp_time = unix_time();

    for (i = 0; i < fr_c->num_cons; ++i) {
        Friend_Conn *friend_con = get_conn(fr_c, i);

        if (friend_con) {
            if (friend_con->status == FRIENDCONN_STATUS_CONNECTING) {
                if (friend_con->dht_ping_lastrecv + FRIEND_DHT_TIMEOUT < temp_time) {
                    if (friend_con->dht_lock) {
                        DHT_delfriend(fr_c->dht, friend_con->dht_temp_pk, friend_con->dht_lock);
                        friend_con->dht_lock = 0;
                    }
                }

                if (friend_con->dht_ip_port_lastrecv + FRIEND_DHT_TIMEOUT < temp_time) {
                    friend_con->dht_ip_port.ip.family = 0;
                }

                if (friend_con->dht_lock) {
                    if (friend_new_connection(fr_c, i) == 0) {
                        set_connection_dht_public_key(fr_c->net_crypto, friend_con->crypt_connection_id, friend_con->dht_temp_pk);
                        set_direct_ip_port(fr_c->net_crypto, friend_con->crypt_connection_id, friend_con->dht_ip_port);
                    }
                }

            } else if (friend_con->status == FRIENDCONN_STATUS_CONNECTED) {
                if (friend_con->ping_lastsent + FRIEND_PING_INTERVAL < temp_time) {
                    send_ping(fr_c, i);
                }

                if (friend_con->ping_lastrecv + FRIEND_CONNECTION_TIMEOUT < temp_time) {
                    /* If we stopped receiving ping packets, kill it. */
                    crypto_kill(fr_c->net_crypto, friend_con->crypt_connection_id);
                    friend_con->crypt_connection_id = -1;
                    handle_status(fr_c, i, 0); /* Going offline. */
                }
            }
        }
    }
}
コード例 #18
0
ファイル: vivaldi.cpp プロジェクト: jayp/Rappel
/**
 * Nodes running the Vivaldi server (i.e., landmark nodes) send one periodic ping
 * to a randomly selected landmark node every period.
 */
void Vivaldi::bring_online() {

  _num_ping_replies = 0;
  _ping_in_progress = false;

  // NOTE: July12,07: Why does a vivaldi node always remain in bootstrap mode?
  // i.e., always changes coordinates? Because once node goes out of bootstrap
  // mode it does not send out periodic pings.

  if (!_node->is_a_vivaldi_node()) {
/*
    // first, create the timer
    BootstrapPeriodExpiredEventData* evt_data = new BootstrapPeriodExpiredEventData;

    Event event;
    event.node_id = _node->get_node_id();
    event.layer = LYR_APPLICATION;
    event.flag = EVT_VIVALDI_NC_BOOTSTRAP_PERIOD_EXPIRED;
    event.data = evt_data;
    event.whence = globops.bootstrap_vivaldi_timeout;

    // schedule the check
    _bootstrap_check_event_id = _timer->schedule_event(event);
*/

#if COMPILE_FOR == NETWORK
    // sync the time
    schedule_periodic_sync(true);
#endif // COMPILE_FOR == NETWORK
  }

  // the vivadi component sends a periodic ping to a landmark
#if COMPILE_FOR == NETWORK
  if (globops.self_name != "sync_server") {
#endif // COMPILE_FOR == NETWORK
    schedule_periodic_ping(true);
    // send the first ping now
    send_ping();
#if COMPILE_FOR == NETWORK
  }
#endif // COMPILE_FOR == NETWORK
}
コード例 #19
0
ファイル: ircd.c プロジェクト: DanielOaks/irc2-mirror
/*
 * calculate preference value based on accumulated stats.
 */
time_t calculate_preference(time_t currenttime)
{
	aConfItem *aconf;
	aCPing	*cp;
	double	f, f2;

	for (aconf = conf; aconf; aconf = aconf->next)
	{
		/* not a C-line */
		if (!(aconf->status & (CONF_CONNECT_SERVER|CONF_ZCONNECT_SERVER)))
			continue;

		/* not a candidate for AC */
		if (aconf->port <= 0)
			continue;

		/* send (udp) pings for all AC-able C-lines, we'll use it to
		** calculate preferences */
		send_ping(aconf);

		if (!(cp = aconf->ping) || !cp->seq || !cp->recvd)
		{
			aconf->pref = -1;
		}
		else
		{
			f = (double)cp->recvd / (double)cp->seq;
			f2 = pow(f, (double)20.0);
			if (f2 < (double)0.001)
				f = (double)0.001;
			else
				f = f2;
			f2 = (double)cp->ping / (double)cp->recvd;
			f = f2 / f;
			if (f > 100000.0)
				f = 100000.0;
			aconf->pref = (u_int) (f * (double)100.0);
		}
	}
	return currenttime + 60;
}
コード例 #20
0
ファイル: p2p.c プロジェクト: tempbottle/torrentkino
void p2p_cron_ping(void)
{
	ITEM *item_b = NULL;
	BUCK *b = NULL;
	ITEM *item_n = NULL;
	UDP_NODE *n = NULL;
	ITEM *ti = NULL;
	unsigned long int j = 0;

	/* Cycle through all the buckets */
	item_b = list_start(_main->nbhd->bucket);
	while (item_b != NULL) {
		b = list_value(item_b);

		/* Cycle through all the nodes */
		j = 0;
		item_n = list_start(b->nodes);
		while (item_n != NULL) {
			n = list_value(item_n);

			/* It's time for pinging */
			if (_main->p2p->time_now.tv_sec > n->time_ping) {

				/* Ping the first 8 nodes. Ignore the rest. */
				if (j < 8) {
					ti = tdb_put(P2P_PING);
					send_ping(&n->c_addr, tdb_tid(ti));
					nbhd_pinged(n->id);
				} else {
					nbhd_pinged(n->id);
				}
			}

			item_n = list_next(item_n);
			j++;
		}

		item_b = list_next(item_b);
	}
}
コード例 #21
0
ファイル: pico_icmp4.c プロジェクト: jinhu/picotcp
int pico_icmp4_ping(char *dst, int count, int interval, int timeout, int size, void (*cb)(struct pico_icmp4_stats *))
{
  static uint16_t next_id = 0x91c0;
  struct pico_icmp4_ping_cookie *cookie;

  if((dst == NULL) || (interval == 0) || (timeout == 0) || (count == 0)){
    pico_err = PICO_ERR_EINVAL;
    return -1;
  }

  cookie = pico_zalloc(sizeof(struct pico_icmp4_ping_cookie));
  if (!cookie) {
    pico_err = PICO_ERR_ENOMEM;
    return -1;
  }

  if (pico_string_to_ipv4(dst, &cookie->dst.addr) < 0) {
    pico_err = PICO_ERR_EINVAL;
    pico_free(cookie);
    return -1;
  }
  cookie->seq = 1;
  cookie->id = next_id++;
  cookie->err = PICO_PING_ERR_PENDING;
  cookie->size = (uint16_t)size;
  cookie->interval = interval;
  cookie->timeout = timeout;
  cookie->cb = cb;
  cookie->count = count;

  pico_tree_insert(&Pings,cookie);
  send_ping(cookie);

  return 0;

}
コード例 #22
0
ファイル: examsgd.c プロジェクト: alban/OpenExanodes
/**
 * Thread processing local events (coming from localhost).
 *
 * This routine may set the network status to down as a side-effect
 * of calling network_send().
 *
 * \param dummy  Unused
 *
 * \return NULL
 */
static void *
local_events_routine(void *dummy)
{
  ping_info_t pi;

  exalog_trace("local events routine started");

  reset_ping(&pi);

  while (!quit)
    {
      int status;
      int err;

      /* Must be interruptible because signal TERM triggers quit condition */
      err = examsgWaitInterruptible(local_mh, &pi.delay);
      if (err == -EINTR)
	continue;

      if (err == -ETIME)
	{
	  status = network_status();
	  if (status == -ENETDOWN)
	    {
	      reset_ping(&pi);
	      continue;
	    }

	  if (unsent.pending)
	    {
	      if (send_unsent() && status != 0)
		network_set_status(0);
	    }
	  else
	    {
	      send_ping();
	      adjust_ping(&pi);
	    }

	  continue;
	}

      /* Local mailbox messages are more important than network messages
       * because they may ask for resend, so they are processed first.
       *
       * Process as many local messages as possible before considering
       * network messages so as to avoid sending a new network message
       * when there still are important messages.
       */
      while (local_mbox_event(&pi) == 1)
	;

      status = network_status();
      if (status == -ENETDOWN)
	continue;

      if (unsent.pending)
	{
	  if (send_unsent() && status != 0)
	    network_set_status(0);
	}
      else
	net_mbox_event(&pi);
    }

  return NULL;
}
コード例 #23
0
ファイル: ead-client.c プロジェクト: 4pao/openwrt
int main(int argc, char **argv)
{
	int val = 1;
	char *st = NULL;
	const char *command = NULL;
	const char *prog = argv[0];
	int ch;

	msg->magic = htonl(EAD_MAGIC);
	msg->sid = 0;

	memset(&local, 0, sizeof(local));
	memset(&remote, 0, sizeof(remote));

	remote.sin_family = AF_INET;
	remote.sin_addr.s_addr = 0xffffffff;
	remote.sin_port = htons(EAD_PORT);

	local.sin_family = AF_INET;
	local.sin_addr.s_addr = INADDR_ANY;
	local.sin_port = 0;

	while ((ch = getopt(argc, argv, "b:s:h")) != -1) {
		switch(ch) {
		case 's':
			inet_aton(optarg, &serverip);
			break;
		case 'b':
			inet_aton(optarg, &remote.sin_addr);
			break;
		case 'h':
			return usage(prog);
		}
	}
	argv += optind;
	argc -= optind;

	switch(argc) {
	case 3:
		command = argv[2];
		/* fall through */
	case 2:
		username = argv[1];
		st = strchr(username, ':');
		if (st) {
			*st = 0;
			st++;
			strncpy(password, st, sizeof(password));
			password[sizeof(password) - 1] = 0;
			/* hide command line password */
			memset(st, 0, strlen(st));
		}
		/* fall through */
	case 1:
		nid = strtoul(argv[0], &st, 16);
		if (st && st[0] != 0)
			return usage(prog);
		/* fall through */
	case 0:
		break;
	default:
		return usage(prog);
	}

	msg->nid = htons(nid);
	s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (s < 0) {
		perror("socket");
		return -1;
	}

	setsockopt(s, SOL_SOCKET, SO_BROADCAST, &val, sizeof(val));

	if (bind(s, (struct sockaddr *)&local, sizeof(local)) < 0) {
		perror("bind");
		return -1;
	}
	sockflags = fcntl(s, F_GETFL);

	if (!send_ping()) {
		fprintf(stderr, "No devices found\n");
		return 1;
	}

	if (nid == 0xffff)
		return 0;

	if (!username || !password[0])
		return 0;

	if (!send_username()) {
		fprintf(stderr, "Device did not accept user name\n");
		return 1;
	}
	timeout = EAD_TIMEOUT_LONG;
	if (!get_prime()) {
		fprintf(stderr, "Failed to get user password info\n");
		return 1;
	}
	if (!send_a()) {
		fprintf(stderr, "Failed to send local authentication data\n");
		return 1;
	}
	if (!send_auth()) {
		fprintf(stderr, "Authentication failed\n");
		return 1;
	}
	if (!command) {
		fprintf(stderr, "Authentication succesful\n");
		return 0;
	}
	if (!send_command(command)) {
		fprintf(stderr, "Command failed\n");
		return 1;
	}

	return 0;
}
コード例 #24
0
ファイル: sv.cpp プロジェクト: Techie123/book
void KServer::recv_ping(vce::VUint64 timestamp){
    send_ping(timestamp);
};
コード例 #25
0
ファイル: aho.cpp プロジェクト: kengonakajima/snippets
 void send_ping_helper(){
     send_ping();
 }
コード例 #26
0
ファイル: flux-ping.c プロジェクト: SteVwonder/flux-core
int main (int argc, char *argv[])
{
    int ch;
    int pad_bytes = 0;
    char *target;
    flux_watcher_t *tw = NULL;
    struct ping_ctx ctx = {
        .period = 1.0,
        .rank = NULL,
        .nodeid = FLUX_NODEID_ANY,
        .topic = NULL,
        .pad = NULL,
        .count = -1,
        .send_count = 0,
        .batch = false,
    };

    log_init ("flux-ping");

    while ((ch = getopt_long (argc, argv, OPTIONS, longopts, NULL)) != -1) {
        switch (ch) {
            case 'h': /* --help */
                usage ();
                break;
            case 'p': /* --pad bytes */
                pad_bytes = strtoul (optarg, NULL, 10);
                break;
            case 'd': /* --delay seconds */
                ctx.period = strtod (optarg, NULL);
                if (ctx.period < 0)
                    usage ();
                break;
            case 'r': /* --rank NODESET  */
                ctx.rank = optarg;
                break;
            case 'c': /* --count N */
                ctx.count = strtoul (optarg, NULL, 10);
                break;
            case 'b': /* --batch-request */
                ctx.batch = true;
                break;
            default:
                usage ();
                break;
        }
    }
    if (optind != argc - 1)
        usage ();
    if (ctx.batch && ctx.count == -1)
        log_msg_exit ("--batch should only be used with --count");
    target = argv[optind++];

    /* Create null terminated pad string for reuse in each message.
     * By default it's the empty string.
     */
    ctx.pad = xzmalloc (pad_bytes + 1);
    memset (ctx.pad, 'p', pad_bytes);

    /* If "rank!" is prepended to the target, and there is no --rank
     * argument, snip it off and set the rank.  If it's just the bare
     * rank, assume the target is "cmb".
     */
    if (ctx.rank == NULL) {
        char *p;
        nodeset_t *ns = NULL;
        if ((p = strchr (target, '!'))) {
            *p++ = '\0';
            ctx.rank = target;
            target = p;
        } else if ((ns = nodeset_create_string (target)) != NULL) {
            ctx.rank = target;
            target = "cmb";
            nodeset_destroy (ns);
        } else if (!strcmp (target, "all")) {
            ctx.rank = target;
            target = "cmb";
        }
    }
    /* Use singleton rpc if there's only one nodeid
     */
    if (ctx.rank != NULL) {
        nodeset_t *ns = nodeset_create_string (ctx.rank);
        if (ns) {
            if (nodeset_count (ns) == 1) {
                ctx.nodeid = nodeset_min (ns);
                ctx.rank = NULL;
            }
            nodeset_destroy (ns);
        }
    }

    ctx.topic = xasprintf ("%s.ping", target);

    if (!(ctx.h = flux_open (NULL, 0)))
        log_err_exit ("flux_open");
    if (!(ctx.reactor = flux_get_reactor (ctx.h)))
        log_err_exit ("flux_get_reactor");

    /* In batch mode, requests are sent before reactor is started
     * to process responses.  o/w requests are set in a timer watcher.
     */
    if (ctx.batch) {
        while (ctx.send_count < ctx.count) {
            send_ping (&ctx);
            usleep ((useconds_t)(ctx.period * 1E6));
        }
    } else {
        tw = flux_timer_watcher_create (ctx.reactor, ctx.period, ctx.period,
                                        timer_cb, &ctx);
        if (!tw)
            log_err_exit ("error creating watchers");
        flux_watcher_start (tw);
    }
    if (flux_reactor_run (ctx.reactor, 0) < 0)
        log_err_exit ("flux_reactor_run");

    /* Clean up.
     */
    flux_watcher_destroy (tw);

    free (ctx.topic);
    free (ctx.pad);

    flux_close (ctx.h);
    log_fini ();

    return 0;
}
コード例 #27
0
// process characters at a time for commands
char
command(void)
{
	S16	ret=0;
	IPADDR	t;
	U8		*u;

	readln_from_a_file((FILE*)stdin, command_buffer, CMD_MAX_SIZE);

	yprintf("command in = %s\n",command_buffer);

			if(command_buffer[0]=='?')
			{
				// Attach to service
				printf("Supported Commands:\n");
				printf("	r - restart\n");
				printf("	e - drop next tunnel rx packet\n");
				printf("	m - check status of memory allocator\n");
				printf("	p - change port\n");
				printf("	s - status\n");
				printf("	y - startup proxy\n");
				printf("	c - connect\n");
				printf("	w - send wakup command (ping server and clients)\n");
                printf("    i - send direct message (specify uid and msg)\n");
#if defined(WEB_SSL)
				printf("    ssl on - enable ssl\n");
				printf("    ssl off - disable ssl\n");
#endif
				printf("	f - files from share target (fl - directory list...)\n");
				printf("	d - Get device List (only works if yoicsid client.)\n");

				printf("\n    q to quit bcaster\n");
				printf("\n    x to exit right now without cleanup.\n");

			}
			else
			 if(command_buffer[0]=='r')
			{
				// Attach to service
				printf("Reconnect to Weaved Service...\n");
				Yoics_reconnect();
				//printf("current state %s\n",server_state_string[state]);
			}
			else if(command_buffer[0]=='p')
			{
				printf("Swapping local port to %d\n",Yoics_Change_Port(0));
			}
			else if(command_buffer[0]=='w')
			{
				printf("Wakeup Command\n");
				send_ping(PING_STANDARD);
				Yoics_Session_Force_Ping();
#if defined(TRACE_LOG)
                traceDump();            // Tracedump just for test
#endif
			}
			else if (command_buffer[0]=='c')
			{
				// connect
				printf("sending connect request for ");
				print_uid(Remote_Address);
				printf("\n");
				//Session_create(&Remote_Address, 0);	////+++ remote address right?
#if defined(BCASTER)				
				ret=Yoics_Session_create(Remote_Address);
				if(-1== ret )
				{
					printf("Initiate session create faild\n");
				}
				else if(-2==ret)
				{
					printf("Initiate session create faild, no slots left\n");
				}
				else
					printf("OK ret= %d\n",ret);
#endif
#if defined(BUILD_SHARE)				
				new_share=Share_Connect(Remote_Address,&share_app_callback);
			
				if(0== new_share )
				{
					printf("Initiate session create faild\n");
				}
				else
					printf("OK ret= %d\n",ret);
#endif
				//yoics_connect(Remote_Address);
			}
			else if (command_buffer[0]=='m')
			{
#if ALLOC_DEBUG
				alloc_check();
#else
				alloc_stat();
#endif
				alloc_pool_check(pool);
			}
			else if (command_buffer[0]=='s')
			{

#if defined(WEB_SSL)
				if (!strcmp(command_buffer,"ssl on")) {
					printf("Turn on SSL\n");

					//
					// Set the web port to ssl port
					//
					webPort = WEB_PORT_SSL;

					//
					// Enable SSL module
					Yoics_Set_SSL(SSL_ENABLE);

				}
				else if (!strcmp (command_buffer, "ssl off")) {

					printf("Turn off SSL\n");

					//
					// Set the web port to non SSL port
					//
					webPort = WEB_PORT;

					//
					// Disable SSL module
					//
					Yoics_Set_SSL (SSL_DISABLE);
				}
				else 
#endif
				{
					t=Yoics_Get_Current_Server();
					u=Yoics_Current_UID();
					printf("server state is %d -- 0)Uconn 1)rstart 2)NATchk 3)ReqAuth 4)ID 5)Conn\n",Yoics_Server_Connection_State());
					printf("  server is %d.%d.%d.%d:%d\n",t.ipb1,t.ipb2,t.ipb3,t.ipb4,(U16)Yoics_Get_Current_Server_Port());
					printf("  key hash is %x:%x\n",secret[0],secret[1]);
					printf("  server spi is 0x%X\n",(unsigned int)Yoics_Return_Server_SPI());
					printf("Our UID is %.2x:%.2x:%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
					u[0],u[1],u[2],u[3],u[4],u[5],u[6],u[7]);
					printf("Our Serial Number is %.2x:%.2x:%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
					serial_num[0],serial_num[1],serial_num[2],serial_num[3],serial_num[4],serial_num[5],
					serial_num[6],serial_num[7]);
					t=Yoics_Get_Our_Bound_IP();
					printf("Our bound ip:port is %d.%d.%d.%d:%d\n",t.ipb1,t.ipb2,t.ipb3,t.ipb4,Yoics_Get_Our_Bound_Port());
					t=Yoics_Get_Our_Mapped_IP();
					printf("Our mapped ip:port is %d.%d.%d.%d:%d -  UPNP/NAT-PMP mapped port is %d\n",t.ipb1,t.ipb2,t.ipb3,t.ipb4,Yoics_Get_Our_Mapped_Port(),parameters.upnp_port);
					printf("Last server hearbeat %u seconds ago\n",(U32)((U32)second_count()-(U32)server_hearbeat));					
					printf("Our NAT type is %d\n",Yoics_Return_NAT_Type());
                    printf("Forward Port is %d\n\n",parameters.forward_port);
					alloc_stat();
					printf("\nActive Sessions %d\n",active_sessions);
					printf("\nSession List\n");
					Yoics_session_list();
					printf("\nProxy Status\n");
					proxy_status();
				}
			}
			else if (command_buffer[0]=='e')
			{
				//printf("Drop next tun data packet.\n");
				//tunnel_drop(tun_num);
			}
			else if (command_buffer[0]=='y')
			{
				if(sindex)
				{
					if(proxy_local_port==0)
						proxy_local_port=5959;
					printf("Starting Proxy on port %d.\n",proxy_local_port);

					if(proxy_client_start(proxy_ip,proxy_local_port, restrict_connect_ip, sindex))
					//if(proxy_start(proxy_ip,proxy_local_port))
						printf("Proxy started.\n");
					else
						printf("proxy startup failed.\n");
				}
				else
				{
					printf("must be connected to peer first\n");
				}
			}
			else if (command_buffer[0]=='d')
			{
				printf("Device List:\n");

#if !defined(BCASTER)			
				if(YOICS_SERVER_CONNECTED==Yoics_Server_Connection_State())
				{
					DEVICE devlist[10];
					char	server_name[32];
					int		tt;
					IPADDR	answer;
					// Get current server IP and make it into a string
					answer=Yoics_Get_Current_Server();

					sprintf(server_name,"%d.%d.%d.%d",answer.ipb1,answer.ipb2,answer.ipb3,answer.ipb4);					
					
					tt=Yoics_Get_Device_List(server_name, webPort, 5000, devlist, 10, 1);

					printf("found %d entries\n",tt);
				
				}
				else
					printf("Must be connected to service to issue this command\n");
#endif				

			}
			else if (command_buffer[0]=='z')
			{
                U8* crash;
				yprintf("Force SIG 11:\n");
                crash=0;
                *crash="c";                                         // This is correct, it forces a crash!  Ignore this warning in compile
				//session_list();
			}
			else if (command_buffer[0]=='q')
			{
				ret=EXIT;
			}
			else if (command_buffer[0]=='x')
			{
                DEBUG4("Free Pool x\n");
	            free_pool();
#if defined(TRACE_LOG)
                traceCleanup();
#endif
				exit(0);
				ret=EXIT;
			}
			else if (command_buffer[0]=='i')
			{
                int len;
                U8* tptr;
                char tpack[255];
                U8 tuid[32];
                YOICSPACKET	*pkt;
                pkt=(YOICSPACKET*)tpack;
                 //
                // Create a map peer
                //
                pkt->packet_type	= htons(PING_MSG);		
                pkt->source			= htons(TARGET_FORWARD);				// not done yet
                len					= sizeof(YOICSPACKET);
                pkt->salt			= 0;
                pkt->spi			= 0;
                tptr=pkt->data;	
                //
                // Add our UID
                //
	            tptr=yoics_add_data(tptr,CLIENTUID,my_uid,UID_SIZE);
	            len+=UID_SIZE+sizeof(DATATYPE);

                //
                // Add Null Type to finish the message
                //
                yoics_add_data(tptr,NULLTYPE,0,0);
                len+=sizeof(DATATYPE);
                //
				// send direct message using packet forwarder
                //
                UID_Extract(&tuid[0],"80:00:00:05:46:00:26:e7");
                send_packet_forward(tuid, (U8*)tpack ,len);

			}
			else
			{
			yprintf("unknown command = %s\n",command_buffer);
			}

	return((S8)ret);

}
コード例 #28
0
ファイル: Messenger.c プロジェクト: Yim4/ProjectTox-Core
//TODO: make this function not suck.
void doFriends(Messenger *m)
{
    /* TODO: add incoming connections and some other stuff. */
    uint32_t i;
    int len;
    uint8_t temp[MAX_DATA_SIZE];
    uint64_t temp_time = unix_time();

    for (i = 0; i < m->numfriends; ++i) {
        if (m->friendlist[i].status == FRIEND_ADDED) {
            int fr = send_friendrequest(m->friendlist[i].client_id, m->friendlist[i].friendrequest_nospam, m->friendlist[i].info,
                                        m->friendlist[i].info_size);

            if (fr >= 0) {
                set_friend_status(m, i, FRIEND_REQUESTED);
                m->friendlist[i].friendrequest_lastsent = temp_time;
            }
        }

        if (m->friendlist[i].status == FRIEND_REQUESTED
                || m->friendlist[i].status == FRIEND_CONFIRMED) { /* friend is not online */
            if (m->friendlist[i].status == FRIEND_REQUESTED) {
                /* If we didn't connect to friend after successfully sending him a friend request the request is deemed
                   unsuccessful so we set the status back to FRIEND_ADDED and try again.*/
                if (m->friendlist[i].friendrequest_lastsent + m->friendlist[i].friendrequest_timeout < temp_time) {
                    set_friend_status(m, i, FRIEND_ADDED);
                    /* Double the default timeout everytime if friendrequest is assumed to have been
                       sent unsuccessfully. */
                    m->friendlist[i].friendrequest_timeout *= 2;
                }
            }

            IP_Port friendip = DHT_getfriendip(m->friendlist[i].client_id);

            switch (is_cryptoconnected(m->friendlist[i].crypt_connection_id)) {
                case 0:
                    if (friendip.ip.i > 1)
                        m->friendlist[i].crypt_connection_id = crypto_connect(m->friendlist[i].client_id, friendip);

                    break;

                case 3: /*  Connection is established */
                    set_friend_status(m, i, FRIEND_ONLINE);
                    m->friendlist[i].name_sent = 0;
                    m->friendlist[i].userstatus_sent = 0;
                    m->friendlist[i].statusmessage_sent = 0;
                    m->friendlist[i].ping_lastrecv = temp_time;
                    break;

                case 4:
                    crypto_kill(m->friendlist[i].crypt_connection_id);
                    m->friendlist[i].crypt_connection_id = -1;
                    break;

                default:
                    break;
            }
        }

        while (m->friendlist[i].status == FRIEND_ONLINE) { /* friend is online */
            if (m->friendlist[i].name_sent == 0) {
                if (m_sendname(m, i, m->name, m->name_length))
                    m->friendlist[i].name_sent = 1;
            }

            if (m->friendlist[i].statusmessage_sent == 0) {
                if (send_statusmessage(m, i, m->statusmessage, m->statusmessage_length))
                    m->friendlist[i].statusmessage_sent = 1;
            }

            if (m->friendlist[i].userstatus_sent == 0) {
                if (send_userstatus(m, i, m->userstatus))
                    m->friendlist[i].userstatus_sent = 1;
            }

            if (m->friendlist[i].ping_lastsent + FRIEND_PING_INTERVAL < temp_time) {
                send_ping(m, i);
            }

            len = read_cryptpacket(m->friendlist[i].crypt_connection_id, temp);
            uint8_t packet_id = temp[0];
            uint8_t *data = temp + 1;
            int data_length = len - 1;

            if (len > 0) {
                switch (packet_id) {
                    case PACKET_ID_PING: {
                        m->friendlist[i].ping_lastrecv = temp_time;
                        break;
                    }

                    case PACKET_ID_NICKNAME: {
                        if (data_length >= MAX_NAME_LENGTH || data_length == 0)
                            break;

                        if (m->friend_namechange)
                            m->friend_namechange(m, i, data, data_length, m->friend_namechange_userdata);

                        memcpy(m->friendlist[i].name, data, data_length);
                        m->friendlist[i].name[data_length - 1] = 0; /* make sure the NULL terminator is present. */
                        break;
                    }

                    case PACKET_ID_STATUSMESSAGE: {
                        if (data_length == 0)
                            break;

                        uint8_t *status = calloc(MIN(data_length, MAX_STATUSMESSAGE_LENGTH), 1);
                        memcpy(status, data, MIN(data_length, MAX_STATUSMESSAGE_LENGTH));

                        if (m->friend_statusmessagechange)
                            m->friend_statusmessagechange(m, i, status, MIN(data_length, MAX_STATUSMESSAGE_LENGTH),
                                                          m->friend_statuschange_userdata);

                        set_friend_statusmessage(m, i, status, MIN(data_length, MAX_STATUSMESSAGE_LENGTH));
                        free(status);
                        break;
                    }

                    case PACKET_ID_USERSTATUS: {
                        if (data_length != 1)
                            break;

                        USERSTATUS status = data[0];

                        if (m->friend_userstatuschange)
                            m->friend_userstatuschange(m, i, status, m->friend_userstatuschange_userdata);

                        set_friend_userstatus(m, i, status);
                        break;
                    }

                    case PACKET_ID_MESSAGE: {
                        uint8_t *message_id = data;
                        uint8_t message_id_length = 4;
                        uint8_t *message = data + message_id_length;
                        uint16_t message_length = data_length - message_id_length;

                        if (m->friendlist[i].receives_read_receipts) {
                            write_cryptpacket_id(m, i, PACKET_ID_RECEIPT, message_id, message_id_length);
                        }

                        if (m->friend_message)
                            (*m->friend_message)(m, i, message, message_length, m->friend_message_userdata);

                        break;
                    }

                    case PACKET_ID_ACTION: {
                        if (m->friend_action)
                            (*m->friend_action)(m, i, data, data_length, m->friend_action_userdata);

                        break;
                    }

                    case PACKET_ID_RECEIPT: {
                        uint32_t msgid;

                        if (data_length < sizeof(msgid))
                            break;

                        memcpy(&msgid, data, sizeof(msgid));
                        msgid = ntohl(msgid);

                        if (m->read_receipt)
                            (*m->read_receipt)(m, i, msgid, m->read_receipt_userdata);

                        break;
                    }
                }
            } else {
                if (is_cryptoconnected(m->friendlist[i].crypt_connection_id) == 4) { /* if the connection timed out, kill it */
                    crypto_kill(m->friendlist[i].crypt_connection_id);
                    m->friendlist[i].crypt_connection_id = -1;
                    set_friend_status(m, i, FRIEND_CONFIRMED);
                }

                break;
            }

            if (m->friendlist[i].ping_lastrecv + FRIEND_CONNECTION_TIMEOUT < temp_time) {
                /* if we stopped recieving ping packets kill it */
                crypto_kill(m->friendlist[i].crypt_connection_id);
                m->friendlist[i].crypt_connection_id = -1;
                set_friend_status(m, i, FRIEND_CONFIRMED);
            }
        }
    }
}
コード例 #29
0
ファイル: vivaldi.cpp プロジェクト: jayp/Rappel
// receive a ping reply
int Vivaldi::receive_ping_reply(Message& recv_msg) {

  VivaldiPingReplyData* reply_data = dynamic_cast<VivaldiPingReplyData*>(recv_msg.data) ;
  assert(reply_data != NULL);

  // delete the wait for timer 
  if (_timer->cancel_event(reply_data->wait_for_timer) == false) {

#ifdef DEBUG
    Clock delay = _timer->get_time() - reply_data->request_sent_at;
    // cancel failed -- the fault handler for this event has already been executed
    if (delay > globops.vivaldi_reply_timeout) {
      std::cerr << "warn: timeout: ping_reply from: " << recv_msg.src.str()
        << "; reply took: " << _timer->get_time_str(delay) << " seconds" << std::endl;
    }
#endif // DEBUG

    delete(reply_data);
    return 0;
  }

  assert(_wait_for_ping_reply == reply_data->wait_for_timer);
  _wait_for_ping_reply = NO_SUCH_EVENT_ID;

  ++_num_ping_replies;
  _ping_in_progress = false; // finished with the ping previously in progress

  _node->add_landmark(recv_msg.src);
  _node->add_landmarks(reply_data->sample_landmarks);

  // update the coordinates
  if (_node->is_a_vivaldi_node() || !_node->is_rappel_online()) {

    //convert latency to milliseconds
    double ow_latency = (_timer->get_time() - reply_data->request_sent_at) 
      / (double) (2 * MILLI_SECONDS);

#ifdef DEBUG
    printf("current sample; ow_latency=%0.3f\n", ow_latency);
#endif // DEBUG

    // add measurement to sample set
    _node->add_landmark_measurement(recv_msg.src, ow_latency,
      reply_data->sender_coord);

    // update coords with filtered sample
    _node->update_local_nc(reply_data->sender_coord,
      _node->get_filtered_landmark_measurement(recv_msg.src, false));
  }

  // signal that the nc has been bootstrapped, if not already
  if (_num_ping_replies >= globops.bootstrap_vivaldi_pongs_min &&
#if COMPILE_FOR == NETWORK
    _sync_offsets.size() >= globops.bootstrap_sync_min &&
#endif // COMPILE_FOR == NETWORK
    !_node->is_a_vivaldi_node() && !_node->is_bootstrapped()) {

    // finish bootstrapping
    _node->signal_vivaldi_bootstrap_complete();

/*
    // cancel bootstrap timeout
    assert(_bootstrap_check_event_id != NO_SUCH_EVENT_ID);
    _timer->cancel_event(_bootstrap_check_event_id);
    _bootstrap_check_event_id = NO_SUCH_EVENT_ID;
*/
  }

  // continuously send the first X pings
  if (_num_ping_replies < globops.bootstrap_vivaldi_pongs_min) {

    // send another ping request
    send_ping();
  }

  // free memory
  delete (reply_data);
  return 0;
}
コード例 #30
0
ファイル: net.c プロジェクト: 95ulisse/tinc
/*
  this is where it all happens...
*/
int main_loop(void) {
	fd_set readset, writeset;
#ifdef HAVE_PSELECT
	struct timespec tv;
	sigset_t omask, block_mask;
	time_t next_event;
#else
	struct timeval tv;
#endif
	int r, maxfd;
	time_t last_ping_check, last_config_check, last_graph_dump;
	event_t *event;

	last_ping_check = now;
	last_config_check = now;
	last_graph_dump = now;
	
	srand(now);

#ifdef HAVE_PSELECT
	if(lookup_config(config_tree, "GraphDumpFile"))
		graph_dump = true;
	/* Block SIGHUP & SIGALRM */
	sigemptyset(&block_mask);
	sigaddset(&block_mask, SIGHUP);
	sigaddset(&block_mask, SIGALRM);
	sigprocmask(SIG_BLOCK, &block_mask, &omask);
#endif

	running = true;

	while(running) {
#ifdef HAVE_PSELECT
		next_event = last_ping_check + pingtimeout;
		if(graph_dump && next_event > last_graph_dump + 60)
			next_event = last_graph_dump + 60;

		if((event = peek_next_event()) && next_event > event->time)
			next_event = event->time;

		if(next_event <= now)
			tv.tv_sec = 0;
		else
			tv.tv_sec = next_event - now;
		tv.tv_nsec = 0;
#else
		tv.tv_sec = 1;
		tv.tv_usec = 0;
#endif

		maxfd = build_fdset(&readset, &writeset);

#ifdef HAVE_MINGW
		LeaveCriticalSection(&mutex);
#endif
#ifdef HAVE_PSELECT
		r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
#else
		r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
#endif
		now = time(NULL);
#ifdef HAVE_MINGW
		EnterCriticalSection(&mutex);
#endif

		if(r < 0) {
			if(!sockwouldblock(sockerrno)) {
				logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
				dump_connections();
				return 1;
			}
		}

		if(r > 0)
			check_network_activity(&readset, &writeset);

		if(do_purge) {
			purge();
			do_purge = false;
		}

		/* Let's check if everybody is still alive */

		if(last_ping_check + pingtimeout <= now) {
			check_dead_connections();
			last_ping_check = now;

			if(routing_mode == RMODE_SWITCH)
				age_subnets();

			age_past_requests();

			/* Should we regenerate our key? */

			if(keyexpires <= now) {
				avl_node_t *node;
				node_t *n;

				ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");

				for(node = node_tree->head; node; node = node->next) {
					n = node->data;
					if(n->inkey) {
						free(n->inkey);
						n->inkey = NULL;
					}
				}

				send_key_changed();
				keyexpires = now + keylifetime;
			}

			/* Detect ADD_EDGE/DEL_EDGE storms that are caused when
			 * two tinc daemons with the same name are on the VPN.
			 * If so, sleep a while. If this happens multiple times
			 * in a row, sleep longer. */

			if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
				logger(LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
				usleep(sleeptime * 1000000LL);
				sleeptime *= 2;
				if(sleeptime < 0)
					sleeptime = 3600;
			} else {
				sleeptime /= 2;
				if(sleeptime < 10)
					sleeptime = 10;
			}

			contradicting_add_edge = 0;
			contradicting_del_edge = 0;
		}

		if(sigalrm) {
			avl_node_t *node;
			logger(LOG_INFO, "Flushing event queue");
			expire_events();
			for(node = connection_tree->head; node; node = node->next) {
				connection_t *c = node->data;
				if(c->status.active)
					send_ping(c);
			}
			sigalrm = false;
		}

		while((event = get_expired_event())) {
			event->handler(event->data);
			free_event(event);
		}

		if(sighup) {
			connection_t *c;
			avl_node_t *node, *next;
			char *fname;
			struct stat s;
			
			sighup = false;

			reopenlogger();
			
			/* Reread our own configuration file */

			exit_configuration(&config_tree);
			init_configuration(&config_tree);

			if(!read_server_config()) {
				logger(LOG_ERR, "Unable to reread configuration file, exitting.");
				return 1;
			}

			/* Cancel non-active outgoing connections */

			for(node = connection_tree->head; node; node = next) {
				next = node->next;
				c = node->data;

				c->outgoing = NULL;

				if(c->status.connecting) {
					terminate_connection(c, false);
					connection_del(c);
				}
			}

			/* Wipe list of outgoing connections */

			for(list_node_t *node = outgoing_list->head; node; node = node->next) {
				outgoing_t *outgoing = node->data;

				if(outgoing->event)
					event_del(outgoing->event);
			}

			list_delete_list(outgoing_list);

			/* Close connections to hosts that have a changed or deleted host config file */
			
			for(node = connection_tree->head; node; node = node->next) {
				c = node->data;
				
				xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
				if(stat(fname, &s) || s.st_mtime > last_config_check)
					terminate_connection(c, c->status.active);
				free(fname);
			}

			last_config_check = now;

			/* If StrictSubnet is set, expire deleted Subnets and read new ones in */

			if(strictsubnets) {
				subnet_t *subnet;

				for(node = subnet_tree->head; node; node = node->next) {
					subnet = node->data;
					subnet->expires = 1;
				}

				load_all_subnets();

				for(node = subnet_tree->head; node; node = next) {
					next = node->next;
					subnet = node->data;
					if(subnet->expires == 1) {
						send_del_subnet(everyone, subnet);
						if(subnet->owner->status.reachable)
							subnet_update(subnet->owner, subnet, false);
						subnet_del(subnet->owner, subnet);
					} else if(subnet->expires == -1) {
						subnet->expires = 0;
					} else {
						send_add_subnet(everyone, subnet);
						if(subnet->owner->status.reachable)
							subnet_update(subnet->owner, subnet, true);
					}
				}
			}

			/* Try to make outgoing connections */
			
			try_outgoing_connections();
		}
		
		/* Dump graph if wanted every 60 seconds*/

		if(last_graph_dump + 60 <= now) {
			dump_graph();
			last_graph_dump = now;
		}
	}

#ifdef HAVE_PSELECT
	/* Restore SIGHUP & SIGALARM mask */
	sigprocmask(SIG_SETMASK, &omask, NULL);
#endif

	return 0;
}