#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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\n", inet_ntoa(si_other.sin_addr)); return; } LOG_INFO("received discovery from %s:%d\n", inet_ntoa(si_other.sin_addr), discovery_answer_port); if(discovery_answer_port == 0) { LOG_ERROR("invalid port received\n"); return; } char* payload; size_t payload_size; mpack_writer_t writer; mpack_writer_init_growable(&writer, &payload, &payload_size); mpack_start_map(&writer, 2); mpack_write_uint(&writer, DISCOVERY_MAPPING_ID); mpack_write_bin(&writer, (char*)controller->id, sizeof(uuid_t)); mpack_write_uint(&writer, DISCOVERY_MAPPING_COMMAND_PORT); mpack_write_u16(&writer, controller->command_port); mpack_write_uint(&writer, DISCOVERY_MAPPING_RELAY_COUNT); mpack_write_u8(&writer, controller->relay_count); mpack_write_uint(&writer, COMMAND_MAPPING_PERIODS_COUNT); mpack_write_cstr(&writer, controller->name); mpack_finish_map(&writer); // finish writing if(mpack_writer_destroy(&writer) != mpack_ok) { LOG_ERROR("error writing discovery answer payload\n"); return; } 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\n"); free(payload); return; } if((bytes_transferred = send(fd_answer, &payload_size, sizeof(payload_size), 0)) <= 0) { LOG_ERROR("error during sending\n"); free(payload); close(fd_answer); return; } if((bytes_transferred = send(fd_answer, payload, payload_size, 0)) <= 0) { LOG_ERROR("error during sending\n"); free(payload); close(fd_answer); return; } free(payload); close(fd_answer); }