Пример #1
0
bool write_remap_read_5() {

	int i = 65;
	void *j;

	bool ok;
	dht_init();
	ok = dht_init_table(0, 20, false);
	
	if (!ok) {
		printf("> malloc fail causes fail not logic fail.\n");
		return false;
	}

	/* expect null */
	j = &i;
	dht_write(0, j);

	ok = dht_init_table(0, 4, false);
	
	if (!ok) {
		printf("> malloc fail causes fail not logic fail.\n");
		return false;
	}

	j = dht_read(0);

	return (j == NULL);

}
Пример #2
0
bool write_remap_read_3() {

	int i = 1, b;
	void *j;

	bool ok;
	dht_init();
	ok = dht_init_table(101, 1600, false);
	
	if (!ok) {
		printf("> malloc fail causes fail not logic fail.\n");
		return false;
	}

	/* expect null */
	j = &i;
	dht_write(171, j);

	ok = dht_init_table(100, 172, true);
	
	if (!ok) {
		printf("> malloc fail causes fail not logic fail.\n");
		return false;
	}

	j = dht_read(171);

	b = *((int*)j);
	return (b == i);

}
Пример #3
0
bool write_remap_read_4() {

	int i = 65, b;
	void *j;

	bool ok;
	dht_init();
	ok = dht_init_table(0, 20, false);
	
	if (!ok) {
		printf("> malloc fail causes fail not logic fail.\n");
		return false;
	}

	/* expect null */
	j = &i;
	dht_write(0, j);

	ok = dht_init_table(0, 4, true);
	
	if (!ok) {
		printf("> malloc fail causes fail not logic fail.\n");
		return false;
	}

	j = dht_read(0);

	b = *((int*)j);
	return (b == i);

}
Пример #4
0
void kad_setup( void ) {
	UCHAR node_id[SHA1_BIN_LENGTH];
	int s4, s6;

	s4 = -1;
	s6 = -1;

	/* Let the DHT output debug text */
	if( gconf->verbosity == VERBOSITY_DEBUG ) {
		dht_debug = stdout;
	}

	bytes_from_hex( node_id, gconf->node_id_str, strlen( gconf->node_id_str ) );

	dht_lock_init();

	if( gconf->af == AF_INET ) {
		s4 = net_bind( "KAD", DHT_ADDR4, gconf->dht_port, gconf->dht_ifname, IPPROTO_UDP, AF_INET );
		net_add_handler( s4, &dht_handler );
	} else {
		s6 = net_bind( "KAD", DHT_ADDR6, gconf->dht_port, gconf->dht_ifname, IPPROTO_UDP, AF_INET6 );
		net_add_handler( s6, &dht_handler );
	}

	/* Init the DHT.  Also set the sockets into non-blocking mode. */
	if( dht_init( s4, s6, node_id, (UCHAR*) "KN\0\0") < 0 ) {
		log_err( "KAD: Failed to initialize the DHT." );
	}
}
Пример #5
0
bool read_write_11() {
	

	int i = 72, b;
	void *j;
	

	bool ok;
	dht_init();
	ok = dht_init_table(0, 20, false);
	
	if (!ok) {
		printf("> malloc fail causes fail not logic fail.\n");
		return false;
	}

	/* expect null */
	j = &i;
	dht_write(19, j);
	j = dht_read(19);

	b = *((int*)j);
	return (b == i);

}
Пример #6
0
Файл: main.c Проект: JMR-b/RIOT
int main(void)
{
    dht_t dev;

    puts("DHT temperature and humidity sensor test application\n");

    printf("Initializing DHT sensor at GPIO_%ld... ", (long)DHT_GPIO);
    if (dht_init(&dev, DHT_TYPE, DHT_GPIO) == 0) {
        puts("[OK]\n");
    }
    else {
        puts("[Failed]");
        return 1;
    }

    dht_data_t data;
    float temp, hum;
    while (1) {

        if (dht_read_raw(&dev, &data) == -1) {
            puts("error reading data");
        }
        dht_parse(&dev, &data, &hum, &temp);
        printf("raw relative humidity: %i\nraw temperature: %i C\n", data.humidity, data.temperature);
        printf("relative humidity: %i\ntemperature: %i C\n", (int) hum, (int) temp);
        xtimer_usleep(2000 * MS_IN_USEC);
    }

    return 0;
}
Пример #7
0
void kad_setup( void ) {
	int s4, s6;

	s4 = -1;
	s6 = -1;

	/* Let the DHT output debug text */
	if( gconf->verbosity == VERBOSITY_DEBUG ) {
		dht_debug = stdout;
	}

	dht_lock_init();

	if( gconf->af == AF_INET ) {
		s4 = net_bind( "DHT", DHT_ADDR4, gconf->dht_port, gconf->dht_ifce, IPPROTO_UDP, AF_INET );
		net_add_handler( s4, &dht_handler );
	} else {
		s6 = net_bind( "DHT", DHT_ADDR6, gconf->dht_port, gconf->dht_ifce, IPPROTO_UDP, AF_INET6 );
		net_add_handler( s6, &dht_handler );
	}

	/* Init the DHT.  Also set the sockets into non-blocking mode. */
	if( dht_init( s4, s6, gconf->node_id, (UCHAR*) "KN\0\0") < 0 ) {
		log_err( "DHT: Failed to initialize the DHT." );
	}
}
Пример #8
0
int
dht_group_test_init(void)
{
    int i;

    /* Some simple debugging */
    debug = 0;

    event_init();

    dht_init();

    addr_pton("127.0.0.1", &addr);

    /* Set up the nodes */
    for (i = 0; i < GROUP_SIZE; ++i) {
        struct dht_node *dht = kad_make_dht(PORT_BASE + i);
        assert(dht != NULL);
        node[i] = dht_group_new(dht);
        dht_group_register_cb(node[i], receive_msg, NULL);
        assert(node[i] != NULL);
    }

    return 0;
}
Пример #9
0
void read_dht22 (float &dhthum, float &dthtemp, int1 &minus)
{
   byte i, dht22_checksum;
   int16 temperature, humidity;
   float temp, hum;
   dht_init();
   CheckRe();
   if(check == 1)
   {
      for (i=0; i<5; i++)
      {
         dht22_dat[i] = read_data_dht();
      }
   }
   dht22_checksum = dht22_dat[0]+dht22_dat[1]+dht22_dat[2]+dht22_dat[3];
   if(dht22_dat[4] != dht22_checksum)
   {
      printf("DHT checksum error");
   }
   humidity = make16(dht22_dat[0], dht22_dat[1]);
   temperature = make16(dht22_dat[2], dht22_dat[3]);
   if(temperature > 0x8000)
   {
      temperature = temperature & 0x7FFF;
      minus = 1;
   }
   hum = humidity;
   temp = temperature;
   dhthum = (hum)/10;
   dthtemp = (temp)/10;
}
Пример #10
0
int
main(int argc, char **argv)
{
    struct dht     *dht;
    struct dht_server *serv;
    struct dht_server *node_a,
                   *node_b,
                   *node_c;

    dht = dht_init(250);

    node_a = dht_add_server(dht, "192.168.0.1", 5555, NULL);
    node_b = dht_add_server(dht, "192.168.0.2", 5555, NULL);
    node_c = dht_add_server(dht, "192.168.0.3", 5555, NULL);

    dht_set_server_status(dht, node_a, DHT_SERV_STATUS_UP);
    dht_set_server_status(dht, node_b, DHT_SERV_STATUS_UP);
    dht_set_server_status(dht, node_c, DHT_SERV_STATUS_UP);

    serv = dht_fetch_server(dht, argv[1]);

    printf("%s:%d\n", serv->host, serv->port);
    dht_del_server(dht, node_a);
    dht_del_server(dht, node_b);
    dht_del_server(dht, node_c);

    serv = dht_fetch_server(dht, argv[1]);
    printf("%p\n", serv);

    free(dht->dht_tree);
    free(dht);
    return 0;
}
Пример #11
0
bool uninitialise_test() {

	bool b;

	dht_init();

	/* this should return false. no table initialised yet */
	b = dht_is_initialised();

	return (!b);
}
Пример #12
0
bool DHTManager::startDHT()
{
	OS_ASSERT(m_socket == -1);

	m_socket = socket(PF_INET, SOCK_DGRAM, 0);
	if(m_socket < 0)
		return false;

	m_port = Options::instance()->getOption<uint32>(OS_DHT_OPTION_PORT);

	memset(&m_sockaddr, 0, sizeof(m_sockaddr));
	m_sockaddr.sin_family = AF_INET;
	m_sockaddr.sin_port = htons(m_port);

    if(bind(m_socket, reinterpret_cast<sockaddr *>(&m_sockaddr), sizeof(m_sockaddr)) < 0)
	{
#if OS_PLATFORM == OS_PLATFORM_WIN
		closesocket(m_socket);
#else
        close(m_socket);
#endif
		m_socket = -1;

		return false;
	}

#ifdef OS_DEBUG
	dht_debug = stdout;
#endif

	dht_random_bytes(m_id, OS_DHT_HASH_SIZE);

	if(dht_init(static_cast<int>(m_socket), -1, m_id, reinterpret_cast<const unsigned char *>("OS\0\0")) < 0)
	{
#if OS_PLATFORM == OS_PLATFORM_WIN
		closesocket(m_socket);
#else
        close(m_socket);
#endif
		m_socket = -1;

		OS_ASSERTFALSE();
		return false;
    }

	m_dhtThread.reset(OS_NEW DHTThread(m_rootPath, m_socket));
	m_dhtThread->start();

	return true;
}
Пример #13
0
bool check_bound_test_2() {

	bool ok;
	dht_init();
	ok = dht_init_table(62, 1109, false);
	
	if (!ok) {
		printf("> malloc fail causes fail not logic fail.\n");
		return false;
	}

	return (dht_get_lower_bound() == 62);

}
Пример #14
0
bool check_bound_test_5() {

	bool ok;
	dht_init();
	ok = dht_init_table(0, 2, false);
	
	if (!ok) {
		printf("> malloc fail causes fail not logic fail.\n");
		return false;
	}

	return (dht_get_upper_bound() == 2);

}
Пример #15
0
bool initialised_test() {

	bool b;

	dht_init();

	dht_init_table(0, 10, false);
	
	/* this should return true. no table initialised yet */
	b = dht_is_initialised();

	return b;

}
Пример #16
0
bool get_size_test_5() {

	int size;
	bool ok;

	dht_init();
	ok = dht_init_table(1065, 1109, false);

	if (!ok) {
		printf("> malloc fail causes fail not logic fail.\n");
		return false;
	}

	size = dht_get_size();

	return (size == 44);
}
Пример #17
0
void user_init(void) {
	stdout_init();
	io_init();
	dht_init(SENSORTYPE, POOLTIME);

	// 0x40200000 is the base address for spi flash memory mapping, ESPFS_POS is the position
	// where image is written in flash that is defined in Makefile.
#ifdef ESPFS_POS
	espFsInit((void*)(0x40200000 + ESPFS_POS));
#else
	espFsInit((void*)(webpages_espfs_start));
#endif
	httpdInit(builtInUrls, 80);

        wifi_init();
	config_init();	
        action_init();
	os_printf("\nESP Ready\n");
}
Пример #18
0
bool read_write_5() {
	
	void *j;

	bool ok;
	dht_init();
	ok = dht_init_table(1, 20, false);
	
	if (!ok) {
		printf("> malloc fail causes fail not logic fail.\n");
		return false;
	}

	/* expect null */
	j = dht_read(3);

	return (j == NULL);

}
Пример #19
0
void auto_init_dht(void)
{
    for (unsigned int i = 0; i < DHT_NUM; i++) {
        LOG_DEBUG("[auto_init_saul] initializing dht #%u\n", i);

        if (dht_init(&dht_devs[i], &dht_params[i]) != DHT_OK) {
            LOG_ERROR("[auto_init_saul] error initializing dht #%u\n", i);
        }
        else {
            saul_entries[(i * 2)].dev = &(dht_devs[i]);
            saul_entries[(i * 2)].name = dht_saul_info[i][0].name;
            saul_entries[(i * 2)].driver = &dht_temp_saul_driver;
            saul_entries[(i * 2) + 1].dev = &(dht_devs[i]);
            saul_entries[(i * 2) + 1].name = dht_saul_info[i][1].name;
            saul_entries[(i * 2) + 1].driver = &dht_hum_saul_driver;
            saul_reg_add(&(saul_entries[(i * 2)]));
            saul_reg_add(&(saul_entries[(i * 2) + 1]));
        }
    }
}
Пример #20
0
int
main(int argc, char *argv[]){
    int sfd, fd;
    int rc, i;
    int opt, quiet = 0, port;
    struct sockaddr_in sin;
    unsigned char myid[20];
    
    if(argc < 2){
        usage();
    }

    while(1){
        int opt_result = 1;
        opt = getopt(argc, argv, "qb:");
        if(opt < 0){
            break;
        }

        switch(opt){
        case 'q': quiet = 1; break;
        case 'b':{
            char buf[16];
            int rc;
            rc = inet_pton(AF_INET, optarg, buf);
            if(rc == 1){
                memcpy(&sin.sin_addr, buf, 4);
                break;
            }
            opt_result = 0;
        }
        default:
            opt_result = 0;
        }
        if(opt_result == 0){
            usage();
        }
    }

    i = optind;
    if(argc < i + 1){
        usage();
    }

    port = atoi(argv[i++]);
    if(port <= 0 || port >= 0x10000){
        usage();
    }

    while(i < argc){
        struct addrinfo hints, *info, *infop;
        memset(&hints, 0, sizeof(hints));
        hints.ai_socktype = SOCK_DGRAM;
        hints.ai_family = AF_INET;
        rc = getaddrinfo(argv[i], argv[i + 1], &hints, &info);
        if(rc != 0){
			fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc));
			exit(1);
        }

		i++;
		if(i >= argc){
			usage();
		}

		infop = info;
		while(infop){
			memcpy(&bootstrap_nodes[num_bootstrap_nodes],
					infop->ai_addr, infop->ai_addrlen);
			infop = infop->ai_next;
			num_bootstrap_nodes++;
		}
		freeaddrinfo(info);
		i++;
    }

	if(!quiet){
		dht_debug = stdout;
	}

    fd = open("/dev/urandom", O_RDONLY);
    if(fd < 0){
        perror("open(random)");
        exit(1);
    }
    rc = read(fd, myid, 20);
    if(rc < 0){
        perror("read(random)");
        exit(EXIT_FAILURE);
    }
    close(fd);
    print_hex(stdout, myid, sizeof(char) * 20);

    sfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sfd < -1){
        perror("socket(IPv4)");
    }

    sin.sin_port = htons(port);
    rc = bind(sfd, (struct sockaddr*)&sin, sizeof(sin));
    if(rc < 0){
		perror("bind(IPv6)");
		exit(1);
	}

	rc = dht_init(sfd, 0, myid, NULL);
	if(rc < 0){
		perror("dht_init");
		exit(1);
	}

	for(i = 0; i < num_bootstrap_nodes; i++){
		dht_ping_node((struct sockaddr*)&bootstrap_nodes[i],
					  sizeof(bootstrap_nodes[i]));
		usleep(random() % 100000);
	}
    close(sfd);

    return EXIT_SUCCESS;
}
Пример #21
0
int
tr_dhtInit(tr_session *ss, const tr_address * tr_addr)
{
    struct sockaddr_in sin;
    tr_benc benc;
    int rc;
    tr_bool have_id = FALSE;
    char * dat_file;
    uint8_t * nodes = NULL, * nodes6 = NULL;
    const uint8_t * raw;
    size_t len, len6;
    struct bootstrap_closure * cl;

    if( session ) /* already initialized */
        return -1;

    dht_port = tr_sessionGetPeerPort(ss);
    if(dht_port <= 0)
        return -1;

    tr_ndbg( "DHT", "Initializing DHT" );

    dht_socket = socket(PF_INET, SOCK_DGRAM, 0);
    if(dht_socket < 0)
        goto fail;

    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    memcpy(&sin.sin_addr, &tr_addr->addr.addr4, sizeof (struct in_addr));
    sin.sin_port = htons(dht_port);
    rc = bind(dht_socket, (struct sockaddr*)&sin, sizeof(sin));
    if(rc < 0)
        goto fail;

    if(tr_globalIPv6())
        rebind_ipv6(TRUE);

    if( getenv( "TR_DHT_VERBOSE" ) != NULL )
        dht_debug = stderr;

    dat_file = tr_buildPath( ss->configDir, "dht.dat", NULL );
    rc = tr_bencLoadFile( &benc, TR_FMT_BENC, dat_file );
    tr_free( dat_file );
    if(rc == 0) {
        have_id = tr_bencDictFindRaw(&benc, "id", &raw, &len);
        if( have_id && len==20 )
            memcpy( myid, raw, len );
        if( dht_socket >= 0 &&
            tr_bencDictFindRaw( &benc, "nodes", &raw, &len ) && !(len%6) ) {
                nodes = tr_memdup( raw, len );
        }
        if( dht6_socket > 0 &&
            tr_bencDictFindRaw( &benc, "nodes6", &raw, &len6 ) && !(len6%18) ) {
            nodes6 = tr_memdup( raw, len6 );
        }
        tr_bencFree( &benc );
    }

    if(nodes == NULL)
        len = 0;
    if(nodes6 == NULL)
        len6 = 0;

    if( have_id )
        tr_ninf( "DHT", "Reusing old id" );
    else {
        /* Note that DHT ids need to be distributed uniformly,
         * so it should be something truly random. */
        tr_ninf( "DHT", "Generating new id" );
        tr_cryptoRandBuf( myid, 20 );
    }

    rc = dht_init( dht_socket, dht6_socket, myid, NULL );
    if( rc < 0 )
        goto fail;

    session = ss;

    cl = tr_new( struct bootstrap_closure, 1 );
    cl->session = session;
    cl->nodes = nodes;
    cl->nodes6 = nodes6;
    cl->len = len;
    cl->len6 = len6;
    tr_threadNew( dht_bootstrap, cl );

    dht_event = event_new( session->event_base, dht_socket, EV_READ, event_callback, NULL );
    tr_timerAdd( dht_event, 0, tr_cryptoWeakRandInt( 1000000 ) );

    if( dht6_socket >= 0 )
    {
        dht6_event = event_new( session->event_base, dht6_socket, EV_READ, event_callback, NULL );
        tr_timerAdd( dht6_event, 0, tr_cryptoWeakRandInt( 1000000 ) );
    }

    tr_ndbg( "DHT", "DHT initialized" );

    return 1;

    fail:
    {
        const int save = errno;
        close(dht_socket);
        if( dht6_socket >= 0 )
            close(dht6_socket);
        dht_socket = dht6_socket = -1;
        session = NULL;
        tr_ndbg( "DHT", "DHT initialization failed (errno = %d)", save );
        errno = save;
    }

    return -1;
}
Пример #22
0
int
main(int argc, char **argv)
{
    int i, rc, fd;
    int s = -1, s6 = -1, port;
    int have_id = 0;
    unsigned char myid[20];
    time_t tosleep = 0;
    char *id_file = "dht-example.id";
    int opt;
    int quiet = 0, ipv4 = 1, ipv6 = 1;
    struct sockaddr_in sin;
    struct sockaddr_in6 sin6;

    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;

    memset(&sin6, 0, sizeof(sin6));
    sin6.sin6_family = AF_INET6;

    while(1) {
        opt = getopt(argc, argv, "q46b:i:");
        if(opt < 0)
            break;

        switch(opt) {
        case 'q': quiet = 1; break;
        case '4': ipv6 = 0; break;
        case '6': ipv4 = 0; break;
        case 'b': {
            char buf[16];
            int rc;
            rc = inet_pton(AF_INET, optarg, buf);
            if(rc == 1) {
                memcpy(&sin.sin_addr, buf, 4);
                break;
            }
            rc = inet_pton(AF_INET6, optarg, buf);
            if(rc == 1) {
                memcpy(&sin6.sin6_addr, buf, 16);
                break;
            }
            goto usage;
        }
            break;
        case 'i':
            id_file = optarg;
            break;
        default:
            goto usage;
        }
    }

    /* Ids need to be distributed evenly, so you cannot just use your
       bittorrent id.  Either generate it randomly, or take the SHA-1 of
       something. */
    fd = open(id_file, O_RDONLY);
    if(fd >= 0) {
        rc = read(fd, myid, 20);
        if(rc == 20)
            have_id = 1;
        close(fd);
    }
    
    fd = open("/dev/urandom", O_RDONLY);
    if(fd < 0) {
        perror("open(random)");
        exit(1);
    }

    if(!have_id) {
        int ofd;

        rc = read(fd, myid, 20);
        if(rc < 0) {
            perror("read(random)");
            exit(1);
        }
        have_id = 1;
        close(fd);

        ofd = open(id_file, O_WRONLY | O_CREAT | O_TRUNC, 0666);
        if(ofd >= 0) {
            rc = write(ofd, myid, 20);
            if(rc < 20)
                unlink(id_file);
            close(ofd);
        }
    }

    {
        unsigned seed;
        read(fd, &seed, sizeof(seed));
        srandom(seed);
    }

    close(fd);

    if(argc < 2)
        goto usage;

    i = optind;

    if(argc < i + 1)
        goto usage;

    port = atoi(argv[i++]);
    if(port <= 0 || port >= 0x10000)
        goto usage;

    while(i < argc) {
        struct addrinfo hints, *info, *infop;
        memset(&hints, 0, sizeof(hints));
        hints.ai_socktype = SOCK_DGRAM;
        if(!ipv6)
            hints.ai_family = AF_INET;
        else if(!ipv4)
            hints.ai_family = AF_INET6;
        else
            hints.ai_family = 0;
        rc = getaddrinfo(argv[i], argv[i + 1], &hints, &info);
        if(rc != 0) {
            fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc));
            exit(1);
        }

        i++;
        if(i >= argc)
            goto usage;

        infop = info;
        while(infop) {
            memcpy(&bootstrap_nodes[num_bootstrap_nodes],
                   infop->ai_addr, infop->ai_addrlen);
            infop = infop->ai_next;
            num_bootstrap_nodes++;
        }
        freeaddrinfo(info);

        i++;
    }

    /* If you set dht_debug to a stream, every action taken by the DHT will
       be logged. */
    if(!quiet)
        dht_debug = stdout;

    /* We need an IPv4 and an IPv6 socket, bound to a stable port.  Rumour
       has it that uTorrent works better when it is the same as your
       Bittorrent port. */
    if(ipv4) {
        s = socket(PF_INET, SOCK_DGRAM, 0);
        if(s < 0) {
            perror("socket(IPv4)");
        }
    }

    if(ipv6) {
        s6 = socket(PF_INET6, SOCK_DGRAM, 0);
        if(s6 < 0) {
            perror("socket(IPv6)");
        }
    }

    if(s < 0 && s6 < 0) {
        fprintf(stderr, "Eek!");
        exit(1);
    }


    if(s >= 0) {
        sin.sin_port = htons(port);
        rc = bind(s, (struct sockaddr*)&sin, sizeof(sin));
        if(rc < 0) {
            perror("bind(IPv4)");
            exit(1);
        }
    }

    if(s6 >= 0) {
        int rc;
        int val = 1;

        rc = setsockopt(s6, IPPROTO_IPV6, IPV6_V6ONLY,
                        (char *)&val, sizeof(val));
        if(rc < 0) {
            perror("setsockopt(IPV6_V6ONLY)");
            exit(1);
        }

        /* BEP-32 mandates that we should bind this socket to one of our
           global IPv6 addresses.  In this simple example, this only
           happens if the user used the -b flag. */

        sin6.sin6_port = htons(port);
        rc = bind(s6, (struct sockaddr*)&sin6, sizeof(sin6));
        if(rc < 0) {
            perror("bind(IPv6)");
            exit(1);
        }
    }

    /* Init the dht.  This sets the socket into non-blocking mode. */
    rc = dht_init(s, s6, myid, (unsigned char*)"JC\0\0");
    if(rc < 0) {
        perror("dht_init");
        exit(1);
    }

    init_signals();

    /* For bootstrapping, we need an initial list of nodes.  This could be
       hard-wired, but can also be obtained from the nodes key of a torrent
       file, or from the PORT bittorrent message.

       Dht_ping_node is the brutal way of bootstrapping -- it actually
       sends a message to the peer.  If you're going to bootstrap from
       a massive number of nodes (for example because you're restoring from
       a dump) and you already know their ids, it's better to use
       dht_insert_node.  If the ids are incorrect, the DHT will recover. */
    for(i = 0; i < num_bootstrap_nodes; i++) {
        dht_ping_node((struct sockaddr*)&bootstrap_nodes[i],
                      sizeof(bootstrap_nodes[i]));
        usleep(random() % 100000);
    }

    while(1) {
        struct timeval tv;
        fd_set readfds;
        tv.tv_sec = tosleep;
        tv.tv_usec = random() % 1000000;

        FD_ZERO(&readfds);
        if(s >= 0)
            FD_SET(s, &readfds);
        if(s6 >= 0)
            FD_SET(s6, &readfds);
        rc = select(s > s6 ? s + 1 : s6 + 1, &readfds, NULL, NULL, &tv);
        if(rc < 0) {
            if(errno != EINTR) {
                perror("select");
                sleep(1);
            }
        }
        
        if(exiting)
            break;

        rc = dht_periodic(rc > 0, &tosleep, callback, NULL);
        if(rc < 0) {
            if(errno == EINTR) {
                continue;
            } else {
                perror("dht_periodic");
                if(rc == EINVAL || rc == EFAULT)
                    abort();
                tosleep = 1;
            }
        }

        /* This is how you trigger a search for a torrent hash.  If port
           (the second argument) is non-zero, it also performs an announce.
           Since peers expire announced data after 30 minutes, it's a good
           idea to reannounce every 28 minutes or so. */
        if(searching) {
            if(s >= 0)
                dht_search(hash, 0, AF_INET, callback, NULL);
            if(s6 >= 0)
                dht_search(hash, 0, AF_INET6, callback, NULL);
            searching = 0;
        }

        /* For debugging, or idle curiosity. */
        if(dumping) {
            dht_dump_tables(stdout);
            dumping = 0;
        }
    }

    {
        struct sockaddr_in sin[500];
        struct sockaddr_in6 sin6[500];
        int num = 500, num6 = 500;
        int i;
        i = dht_get_nodes(sin, &num, sin6, &num6);
        printf("Found %d (%d + %d) good nodes.\n", i, num, num6);
    }

    dht_uninit(1);
    return 0;
    
 usage:
    printf("Usage: dht-example [-q] [-4] [-6] [-i filename] [-b address]...\n"
           "                   port [address port]...\n");
    exit(1);
}
Пример #23
0
int
tr_dhtInit(tr_session *ss)
{
    tr_benc benc;
    int rc;
    bool have_id = false;
    char * dat_file;
    uint8_t * nodes = NULL, * nodes6 = NULL;
    const uint8_t * raw;
    size_t len, len6;
    struct bootstrap_closure * cl;

    if( session ) /* already initialized */
        return -1;

    tr_ndbg( "DHT", "Initializing DHT" );

    if( getenv( "TR_DHT_VERBOSE" ) != NULL )
        dht_debug = stderr;

    dat_file = tr_buildPath( ss->configDir, "dht.dat", NULL );
    rc = tr_bencLoadFile( &benc, TR_FMT_BENC, dat_file );
    tr_free( dat_file );
    if(rc == 0) {
        have_id = tr_bencDictFindRaw(&benc, "id", &raw, &len);
        if( have_id && len==20 )
            memcpy( myid, raw, len );
        if( ss->udp_socket >= 0 &&
            tr_bencDictFindRaw( &benc, "nodes", &raw, &len ) && !(len%6) ) {
                nodes = tr_memdup( raw, len );
        }
        if( ss->udp6_socket > 0 &&
            tr_bencDictFindRaw( &benc, "nodes6", &raw, &len6 ) && !(len6%18) ) {
            nodes6 = tr_memdup( raw, len6 );
        }
        tr_bencFree( &benc );
    }

    if(nodes == NULL)
        len = 0;
    if(nodes6 == NULL)
        len6 = 0;

    if( have_id )
        tr_ninf( "DHT", "Reusing old id" );
    else {
        /* Note that DHT ids need to be distributed uniformly,
         * so it should be something truly random. */
        tr_ninf( "DHT", "Generating new id" );
        tr_cryptoRandBuf( myid, 20 );
    }

    rc = dht_init( ss->udp_socket, ss->udp6_socket, myid, NULL );
    if( rc < 0 )
        goto fail;

    session = ss;

    cl = tr_new( struct bootstrap_closure, 1 );
    cl->session = session;
    cl->nodes = nodes;
    cl->nodes6 = nodes6;
    cl->len = len;
    cl->len6 = len6;
    tr_threadNew( dht_bootstrap, cl );

    dht_timer = evtimer_new( session->event_base, timer_callback, session );
    tr_timerAdd( dht_timer, 0, tr_cryptoWeakRandInt( 1000000 ) );

    tr_ndbg( "DHT", "DHT initialized" );

    return 1;

 fail:
    tr_ndbg( "DHT", "DHT initialization failed (errno = %d)", errno );
    session = NULL;
    return -1;
}
Пример #24
0
int
tr_dhtInit (tr_session *ss)
{
    tr_variant benc;
    int rc;
    bool have_id = false;
    char * dat_file;
    uint8_t * nodes = NULL, * nodes6 = NULL;
    const uint8_t * raw;
    size_t len, len6;
    struct bootstrap_closure * cl;

    if (session) /* already initialized */
        return -1;

    tr_logAddNamedDbg ("DHT", "Initializing DHT");

    if (tr_env_key_exists ("TR_DHT_VERBOSE"))
        dht_debug = stderr;

    dat_file = tr_buildPath (ss->configDir, "dht.dat", NULL);
    rc = tr_variantFromFile (&benc, TR_VARIANT_FMT_BENC, dat_file, NULL) ? 0 : -1;
    tr_free (dat_file);
    if (rc == 0) {
        have_id = tr_variantDictFindRaw (&benc, TR_KEY_id, &raw, &len);
        if (have_id && len==20)
            memcpy (myid, raw, len);
        if (ss->udp_socket != TR_BAD_SOCKET &&
            tr_variantDictFindRaw (&benc, TR_KEY_nodes, &raw, &len) && ! (len%6)) {
                nodes = tr_memdup (raw, len);
        }
        if (ss->udp6_socket != TR_BAD_SOCKET &&
            tr_variantDictFindRaw (&benc, TR_KEY_nodes6, &raw, &len6) && ! (len6%18)) {
            nodes6 = tr_memdup (raw, len6);
        }
        tr_variantFree (&benc);
    }

    if (nodes == NULL)
        len = 0;
    if (nodes6 == NULL)
        len6 = 0;

    if (have_id)
        tr_logAddNamedInfo ("DHT", "Reusing old id");
    else {
        /* Note that DHT ids need to be distributed uniformly,
         * so it should be something truly random. */
        tr_logAddNamedInfo ("DHT", "Generating new id");
        tr_rand_buffer (myid, 20);
    }

    rc = dht_init (ss->udp_socket, ss->udp6_socket, myid, NULL);
    if (rc < 0)
        goto fail;

    session = ss;

    cl = tr_new (struct bootstrap_closure, 1);
    cl->session = session;
    cl->nodes = nodes;
    cl->nodes6 = nodes6;
    cl->len = len;
    cl->len6 = len6;
    tr_threadNew (dht_bootstrap, cl);

    dht_timer = evtimer_new (session->event_base, timer_callback, session);
    tr_timerAdd (dht_timer, 0, tr_rand_int_weak (1000000));

    tr_logAddNamedDbg ("DHT", "DHT initialized");

    return 1;

 fail:
    tr_logAddNamedDbg ("DHT", "DHT initialization failed (errno = %d)", errno);
    session = NULL;
    return -1;
}
Пример #25
0
void main()
{
//Configuraciones del PIC-------------------------------------------------------
   //Configuración de puertos...   
   set_tris_A(0x0B);
   set_tris_B(0xFF);
   set_tris_C(0x80);
   set_tris_D(0x00);
   
   lcd_init();
   dht_init();
//Parámetros del ADC...
   setup_adc(ADC_CLOCK_INTERNAL);      //Reloj interno para conversiones
   setup_adc_ports(AN0_AN1_AN3);       //Puertos usados como entradas
   
//Parámetros para el PWM...
   setup_ccp1(CCP_PWM);                //Módulo PWM activado
   setup_timer_2(T2_DIV_BY_4,249,1);   //Onda de 4KHz
   
//Parámetros de Timer0...
   setup_timer_0(RTCC_INTERNAL|RTCC_DIV_16); //4ms para desbordamiento
      //Interrupciones...
   enable_interrupts(INT_RB);          //Interrupción puerto B
   enable_interrupts(INT_RTCC);        //Interrupción Timer0
   enable_interrupts(INT_RDA);         //Interrupción RS-232
   enable_interrupts(GLOBAL);
//Análisis de la bandera...
   set_pwm1_duty(0);
   lcd_init();
   if(read_eeprom(0x00) == 0)
   {
//LM35--------------------------------------------------------------------------
      bitRes1=read_eeprom(0x01);
      cadEnv1=read_eeprom(0x02);
      offSens1=(float)read_eeprom(0x03)/10.0;
      if(read_eeprom(0x04)==0)
         offSens1*=-1.0;
//------------------------------------------------------------------------------
//RHT03-------------------------------------------------------------------------         
      cadEnv2=read_eeprom(0x06);
      offSens2=(float)read_eeprom(0x07)/10.0;
      if(read_eeprom(0x08)==0)
         offSens2*=-1.0;
//------------------------------------------------------------------------------
//LDR---------------------------------------------------------------------------         
      bitRes3=read_eeprom(0x0A);
      cadEnv3=read_eeprom(0x0B);
      offSens3=(float)read_eeprom(0x0C)/10.0;
      if(read_eeprom(0x0D)==0)
         offSens3*=-1.0;
//------------------------------------------------------------------------------
//PWM---------------------------------------------------------------------------
      pwmSens=read_eeprom(0x0F);
      threshold[0]=read_eeprom(0x10);
      threshold[1]=read_eeprom(0x11);
      threshold[2]=read_eeprom(0x12);
      threshold[3]=read_eeprom(0x13);
//------------------------------------------------------------------------------
   }
//------------------------------------------------------------------------------
while(true){
//Al presionar aceptar o cancelar se limpia el display.-------------------------
      if(cls){
         cls=false;
         lcd_init();
      }
//Lectura de los sensores-------------------------------------------------------
   if(readSens){
      readSens=false;
      ReadSensData();
   }
    
//Muestra las lecturas o configuraciones en el display--------------------------
      if(!enterConfig && !displayConfigs)
         ShowDisplay();
      else if(displayConfigs && !enterConfig)
         ShowConfigs();
      if(enterConfig){
         if(selector==1)
            ConfigLM35();
         else if(selector==2)
            ConfigRHT03();
         else if(selector==3)
            ConfigLDR();
         else if(selector==4)
            ConfigPWM();
      }
      if(save==true){
         save=false;
         SaveC();
      }

//Control del ventilador--------------------------------------------------------
   FanRPM();
         
//Lectura del búfer-------------------------------------------------------------
      if(read){
         ReadBuffer();
         ExecCmd();
         SaveC();
      }
      
//Envío a la PC-----------------------------------------------------------------
      if(sendData){
         sendData=false;
         if(segs1==cadEnv1){
            MakeNSendFrame(1);
            segs1=0;
         }
         if(segs2==cadEnv2){
            MakeNSendFrame(2);
            segs2=0;
         }
         if(segs3==cadEnv3){
            MakeNSendFrame(3);
            segs3=0;
         }
      }//End if sendData
   }//End while
}