2017-02-15 17:04:10 +00:00
|
|
|
#include <stdlib.h>
|
|
|
|
#include <netdb.h>
|
|
|
|
#include <arpa/inet.h>
|
|
|
|
|
|
|
|
#include "multiaddr/multiaddr.h"
|
|
|
|
#include "libp2p/net/p2pnet.h"
|
|
|
|
#include "libp2p/conn/connection.h"
|
|
|
|
#include "libp2p/conn/transport_dialer.h"
|
2017-03-02 21:14:52 +00:00
|
|
|
#include "libp2p/utils/multiaddress.h"
|
2017-02-15 17:04:10 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* An implementation of a tcp transport dialer
|
|
|
|
*/
|
|
|
|
|
2017-03-02 21:14:52 +00:00
|
|
|
int libp2p_conn_tcp_can_handle(const struct MultiAddress* addr) {
|
2017-02-15 17:04:10 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2017-02-16 23:49:17 +00:00
|
|
|
int libp2p_conn_tcp_read(const struct Connection* connection, char** out, size_t* num_bytes) {
|
|
|
|
int buffer_size = 65535;
|
|
|
|
*out = (char*)malloc(buffer_size);
|
|
|
|
ssize_t bytes = socket_read(connection->socket_handle, *out, buffer_size, 0);
|
|
|
|
*num_bytes = bytes;
|
|
|
|
return bytes > 0;
|
|
|
|
}
|
2017-02-15 17:04:10 +00:00
|
|
|
|
2017-02-16 23:49:17 +00:00
|
|
|
int libp2p_conn_tcp_write(const struct Connection* connection, const char* in, size_t num_bytes) {
|
|
|
|
ssize_t bytes = socket_write(connection->socket_handle, in, num_bytes, 0);
|
|
|
|
return bytes == num_bytes;
|
|
|
|
}
|
2017-02-15 17:04:10 +00:00
|
|
|
|
2017-03-02 21:14:52 +00:00
|
|
|
struct Connection* libp2p_conn_tcp_dial(const struct TransportDialer* transport_dialer, const struct MultiAddress* addr) {
|
2017-02-15 17:04:10 +00:00
|
|
|
struct Connection* conn = (struct Connection*) malloc(sizeof(struct Connection*));
|
|
|
|
conn->socket_handle = socket_open4();
|
2017-03-02 21:14:52 +00:00
|
|
|
char* ip;
|
|
|
|
int port;
|
|
|
|
libp2p_utils_multiaddress_parse_ip4_tcp(addr, &ip, &port);
|
|
|
|
struct hostent* host = gethostbyname(ip);
|
2017-02-15 17:04:10 +00:00
|
|
|
struct in_addr** addr_list = (struct in_addr**)host->h_addr_list;
|
2017-03-02 21:14:52 +00:00
|
|
|
socket_connect4(conn->socket_handle, (*addr_list[0]).s_addr, port);
|
2017-02-16 23:49:17 +00:00
|
|
|
conn->read = libp2p_conn_tcp_read;
|
|
|
|
conn->write = libp2p_conn_tcp_write;
|
2017-02-15 17:04:10 +00:00
|
|
|
return conn;
|
|
|
|
}
|
|
|
|
|
|
|
|
struct TransportDialer* libp2p_conn_tcp_transport_dialer_new(char* peer_id, struct PrivateKey* private_key) {
|
|
|
|
struct TransportDialer* out = libp2p_conn_transport_dialer_new(peer_id, private_key);
|
|
|
|
out->can_handle = libp2p_conn_tcp_can_handle;
|
|
|
|
out->dial = libp2p_conn_tcp_dial;
|
|
|
|
return out;
|
|
|
|
}
|