controller-legacy/handlers/discovery.c

73 lines
2 KiB
C
Raw Normal View History

2020-04-13 22:50:55 +00:00
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <uuid/uuid.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <errno.h>
#include <logger.h>
#include <handlers.h>
#include <helpers.h>
#include <binn.h>
#include <enums.h>
void
handler_discovery(int fd, controller_t *controller)
{
ssize_t bytes_transferred;
uint16_t discovery_answer_port;
struct sockaddr_in si_other;
socklen_t slen = sizeof(si_other);
if((bytes_transferred = recvfrom(fd, &discovery_answer_port, sizeof(discovery_answer_port), 0, (struct sockaddr *) &si_other, &slen)) <= 0)
{
LOG_ERROR("received invalid discovery from %s", inet_ntoa(si_other.sin_addr));
return;
}
LOG_DEBUG("received discovery from %s for port %d", inet_ntoa(si_other.sin_addr), discovery_answer_port);
if(discovery_answer_port == 0)
{
LOG_ERROR("invalid port received");
return;
}
binn *map = binn_map();
binn_map_set_blob(map, DISCOVERY_MAPPING_ID, &controller->id, sizeof(uuid_t));
binn_map_set_str(map, DISCOVERY_MAPPING_NAME, controller->name);
binn_map_set_uint32(map, DISCOVERY_MAPPING_COMMAND_PORT, controller->command_port);
binn_map_set_uint8(map, DISCOVERY_MAPPING_RELAY_COUNT, controller->relay_count);
void *payload = binn_ptr(map);
size_t payload_size = binn_size(map);
int fd_answer = helper_connect_tcp_server(inet_ntoa(si_other.sin_addr), discovery_answer_port);
if(fd_answer == -1)
{
LOG_ERROR("error during connecting");
binn_free(map);
return;
}
if((bytes_transferred = send(fd_answer, &payload_size, sizeof(payload_size), 0)) <= 0)
{
LOG_ERROR("error during sending");
binn_free(map);
return;
}
if((bytes_transferred = send(fd_answer, payload, payload_size, 0)) <= 0)
{
LOG_ERROR("error during sending");
binn_free(map);
return;
}
close(fd_answer);
}