Merge remote-tracking branch 'origin/master'
This commit is contained in:
commit
8e7b38d25d
16 files changed
+1250
-929
No files matched your search
+342
-143
@@ -91,15 +91,20 @@ static void accept_callback(socket_t fd, void* arg);
|
||||
static void client_read_callback(socket_t fd, void* arg);
|
||||
static void client_write_callback(socket_t fd, void* arg);
|
||||
static void client_except_callback(socket_t fd, void* arg);
|
||||
static void handle_client_data(struct control_server* server, struct control_client* client);
|
||||
static int handle_client_data(struct control_server* server, struct control_client* client);
|
||||
static void close_client(struct control_server* server, struct control_client* client);
|
||||
static void control_client_idle_cb(void* arg);
|
||||
static void control_output_ready(struct ll_queue* queue, void* arg);
|
||||
static int control_wait_output(struct control_client* client);
|
||||
static int control_client_arm_timer(struct control_client* client, int tx);
|
||||
|
||||
static void send_conn_list(struct control_server* server, struct control_client* client, uint8_t seq_id);
|
||||
static void send_socket_list(struct control_server* server, struct control_client* client, uint8_t seq_id);
|
||||
static void send_metrics(struct control_server* server, struct control_client* client, uint8_t seq_id);
|
||||
static void send_debug_config(struct control_server* server, struct control_client* client, uint8_t seq_id);
|
||||
static void send_error(struct control_client* client, uint8_t error_code, const char* msg, uint8_t seq_id);
|
||||
static int handle_action(struct control_server* server, struct control_client* client,
|
||||
const uint8_t* payload, uint16_t size, uint8_t seq_id);
|
||||
|
||||
static void control_server_send_node_list(struct control_server* server, struct control_client* client, uint8_t seq_id);
|
||||
static void send_single_node_info(struct control_server* server, struct control_client* client, struct TOPO_GROUP_NODE* nq);
|
||||
@@ -428,6 +433,9 @@ static void accept_callback(socket_t fd, void* arg) {
|
||||
}
|
||||
client->subscribed_nodes = 0;
|
||||
client->write_registered = 0;
|
||||
queue_set_size_limit(client->output_queue, 1);
|
||||
queue_set_threshold(client->output_queue, 0, 0);
|
||||
queue_set_waiter_defer(client->output_queue, 1);
|
||||
|
||||
/* Register with uasync */
|
||||
client->socket_id = uasync_add_socket_t(server->ua, client_fd,
|
||||
@@ -488,6 +496,7 @@ static void accept_callback(socket_t fd, void* arg) {
|
||||
static void client_read_callback(socket_t fd, void* arg) {
|
||||
struct control_client* client = (struct control_client*)arg;
|
||||
struct control_server* server = client->server;
|
||||
if (client->read_paused) return;
|
||||
|
||||
if (client->recv_len >= ETCPMON_MAX_MSG_SIZE) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Control recv buffer overflow (pre-check)");
|
||||
@@ -584,57 +593,87 @@ static void client_read_callback(socket_t fd, void* arg) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Один таймер: ожидание команд в покое, отсутствие положительного send во время TX. */
|
||||
static int control_client_arm_timer(struct control_client* client, int tx) {
|
||||
if (client->idle_timer) uasync_cancel_timeout(client->server->ua, client->idle_timer);
|
||||
client->timer_is_tx = tx != 0;
|
||||
client->idle_timer = uasync_set_timeout(client->server->ua, 300000, client, control_client_idle_cb, tx ? "ctrl_tx" : "ctrl_idle");
|
||||
if (!client->idle_timer) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Control timer failed fd=%d mode=%s", (int)client->fd, tx ? "TX" : "idle");
|
||||
client->failed = 1;
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Останавливает входных producers до пустой очереди. Waiter всегда отложен, повторных регистраций нет. */
|
||||
static int control_wait_output(struct control_client* client) {
|
||||
if (!client->read_paused) {
|
||||
if (uasync_set_socket_read(client->server->ua, client->socket_id, 0) < 0) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to pause control reads fd=%d", (int)client->fd);
|
||||
client->failed = 1;
|
||||
return -1;
|
||||
}
|
||||
client->read_paused = 1;
|
||||
DEBUG_DEBUG(DEBUG_CATEGORY_CONTROL, "Control reads paused fd=%d queued=%zu snapshot=%zu/%zu dirty=%zu",
|
||||
(int)client->fd, queue_total_bytes(client->output_queue), client->snapshot_index,
|
||||
client->snapshot_count, client->dirty_count);
|
||||
}
|
||||
if (!client->timer_is_tx && control_client_arm_timer(client, 1) < 0) return -1;
|
||||
if (!client->output_waiter.internal && !client->output_waiter.call_soon_id &&
|
||||
queue_waiter_wait(client->output_queue, &client->output_waiter, control_output_ready, client) < 0) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to wait for control output fd=%d", (int)client->fd);
|
||||
client->failed = 1;
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void client_write_callback(socket_t fd, void* arg) {
|
||||
struct control_client* client = (struct control_client*)arg;
|
||||
struct control_client* client = arg;
|
||||
struct control_server* server = client->server;
|
||||
struct ll_queue* q = client->output_queue;
|
||||
|
||||
while (q->head) {
|
||||
struct ll_entry* entry = q->head;
|
||||
|
||||
struct ll_queue* queue = client->output_queue;
|
||||
struct ll_entry* entry = queue->head;
|
||||
if (client->failed) { close_client(server, client); return; }
|
||||
if (entry) {
|
||||
#ifdef _WIN32
|
||||
int sent = send(fd, (const char*)entry->dgram + client->output_offset, entry->len - client->output_offset, 0);
|
||||
if (sent == SOCKET_ERROR) {
|
||||
int err = WSAGetLastError();
|
||||
if (err != WSAEWOULDBLOCK) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Client send error: %d, closing", err);
|
||||
close_client(server, client);
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
int error = WSAGetLastError();
|
||||
if (error == WSAEWOULDBLOCK) return;
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Control send failed fd=%d error=%d", (int)fd, error);
|
||||
#else
|
||||
ssize_t sent = send(fd, entry->dgram + client->output_offset, entry->len - client->output_offset, 0);
|
||||
if (sent < 0) {
|
||||
if (errno != EAGAIN && errno != EWOULDBLOCK) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Client send error: %s, closing", strerror(errno));
|
||||
close_client(server, client);
|
||||
return;
|
||||
}
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK) return;
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Control send failed fd=%d: %s", (int)fd, strerror(errno));
|
||||
#endif
|
||||
close_client(server, client);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (sent == 0) {
|
||||
DEBUG_WARN(DEBUG_CATEGORY_CONTROL, "Control client send made no progress fd=%d, closing", (int)fd);
|
||||
if (!sent) {
|
||||
DEBUG_WARN(DEBUG_CATEGORY_CONTROL, "Control send made no progress fd=%d", (int)fd);
|
||||
close_client(server, client);
|
||||
return;
|
||||
}
|
||||
client->output_offset += (uint16_t)sent;
|
||||
if (client->output_offset < entry->len) {
|
||||
DEBUG_DEBUG(DEBUG_CATEGORY_CONTROL, "Control partial send fd=%d offset=%u size=%u queued_bytes=%zu",
|
||||
(int)fd, client->output_offset, entry->len, queue_total_bytes(q));
|
||||
DEBUG_DEBUG(DEBUG_CATEGORY_CONTROL, "Control partial send fd=%d offset=%u/%u",
|
||||
(int)fd, client->output_offset, entry->len);
|
||||
if (control_client_arm_timer(client, 1) < 0) close_client(server, client);
|
||||
return;
|
||||
}
|
||||
|
||||
struct ll_entry* e = queue_data_get(q);
|
||||
queue_dgram_free(e); queue_entry_free(e);
|
||||
entry = queue_data_get(queue);
|
||||
queue_dgram_free(entry); queue_entry_free(entry);
|
||||
client->output_offset = 0;
|
||||
}
|
||||
|
||||
uasync_set_socket_write(server->ua, client->socket_id, 0);
|
||||
if (uasync_set_socket_write(server->ua, client->socket_id, 0) < 0) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to disable control writes fd=%d", (int)fd);
|
||||
close_client(server, client);
|
||||
return;
|
||||
}
|
||||
client->write_registered = 0;
|
||||
if (q->count > 128) DEBUG_WARN(DEBUG_CATEGORY_CONTROL, "ctrl_out: large output queue count=%d fd=%d", q->count, (int)client->fd);
|
||||
(void)fd;
|
||||
if (control_client_arm_timer(client, client->snapshot_active || client->dirty_count) < 0) close_client(server, client);
|
||||
}
|
||||
|
||||
static void client_except_callback(socket_t fd, void* arg) {
|
||||
@@ -650,33 +689,48 @@ static void client_except_callback(socket_t fd, void* arg) {
|
||||
|
||||
/* Принимает владение буфером, включая ветки ошибки постановки в очередь. */
|
||||
static int control_client_send(struct control_server* server, struct control_client* client, uint8_t* dgram, uint16_t len) {
|
||||
(void)server;
|
||||
if (!client || !client->output_queue || !dgram || len == 0 || len > ETCPMON_MAX_MSG_SIZE) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Invalid control output message client=%p size=%u", (void*)client, len);
|
||||
if (!client || !client->output_queue || !dgram || !len || len > ETCPMON_MAX_MSG_SIZE) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Invalid control output client=%p size=%u", (void*)client, len);
|
||||
if (client) client->failed = 1;
|
||||
u_free(dgram);
|
||||
return -1;
|
||||
}
|
||||
if (client->output_queue->head || client->failed) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Control producer violated TX backpressure fd=%d queued=%zu incoming=%u",
|
||||
(int)client->fd, queue_total_bytes(client->output_queue), len);
|
||||
client->failed = 1; u_free(dgram);
|
||||
return -1;
|
||||
}
|
||||
struct ll_entry* entry = queue_entry_new(0);
|
||||
if (!entry) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to allocate output queue entry size=%u", len);
|
||||
u_free(dgram);
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to allocate control output entry fd=%d size=%u", (int)client->fd, len);
|
||||
client->failed = 1; u_free(dgram);
|
||||
return -1;
|
||||
}
|
||||
entry->dgram = dgram; entry->len = len;
|
||||
if (queue_data_put(client->output_queue, entry) < 0) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to enqueue control output fd=%d size=%u", (int)client->fd, len);
|
||||
client->failed = 1;
|
||||
return -1;
|
||||
}
|
||||
entry->dgram = dgram;
|
||||
entry->len = len;
|
||||
queue_data_put(client->output_queue, entry);
|
||||
if (!client->write_registered) {
|
||||
uasync_set_socket_write(client->server->ua, client->socket_id, 1);
|
||||
if (uasync_set_socket_write(server->ua, client->socket_id, 1) < 0) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to enable control writes fd=%d", (int)client->fd);
|
||||
client->failed = 1;
|
||||
return -1;
|
||||
}
|
||||
client->write_registered = 1;
|
||||
}
|
||||
return 0;
|
||||
return control_wait_output(client);
|
||||
}
|
||||
|
||||
static void control_client_idle_cb(void* arg) {
|
||||
struct control_client* client = (struct control_client*)arg;
|
||||
struct control_client* client = arg;
|
||||
if (!client || !client->server) return;
|
||||
client->idle_timer = NULL;
|
||||
DEBUG_WARN(DEBUG_CATEGORY_CONTROL, "Control client idle timeout fd=%d, closing", client->fd);
|
||||
DEBUG_WARN(DEBUG_CATEGORY_CONTROL, "Control %s timeout fd=%d queued_bytes=%zu snapshot=%zu/%zu dirty=%zu",
|
||||
client->timer_is_tx ? "TX progress" : "idle", (int)client->fd, queue_total_bytes(client->output_queue),
|
||||
client->snapshot_index, client->snapshot_count, client->dirty_count);
|
||||
close_client(client->server, client);
|
||||
}
|
||||
|
||||
@@ -688,6 +742,8 @@ static void close_client(struct control_server* server, struct control_client* c
|
||||
client->output_offset, client->idle_timer != NULL);
|
||||
|
||||
if (client->idle_timer) { uasync_cancel_timeout(server->ua, client->idle_timer); client->idle_timer = NULL; }
|
||||
if (client->output_queue) queue_waiter_cancel(client->output_queue, &client->output_waiter);
|
||||
u_free(client->snapshot_ids); client->snapshot_ids = NULL;
|
||||
|
||||
/* Log disconnection */
|
||||
if (server->log_file) {
|
||||
@@ -740,19 +796,24 @@ static void close_client(struct control_server* server, struct control_client* c
|
||||
* Message Handling
|
||||
* ============================================================================ */
|
||||
|
||||
static void handle_client_data(struct control_server* server, struct control_client* client) {
|
||||
static int handle_client_data(struct control_server* server, struct control_client* client) {
|
||||
if (client->failed) { close_client(server, client); return -1; }
|
||||
if (client->output_queue->head || client->snapshot_active || client->dirty_count) {
|
||||
if (control_wait_output(client) < 0) { close_client(server, client); return -1; }
|
||||
return 0;
|
||||
}
|
||||
while (client->recv_len >= sizeof(struct etcpmon_msg_header)) {
|
||||
struct etcpmon_msg_header* hdr = (struct etcpmon_msg_header*)client->recv_buffer;
|
||||
|
||||
if (hdr->size == 0 || hdr->size > ETCPMON_MAX_MSG_SIZE) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Invalid message size from client: %u", hdr->size);
|
||||
close_client(server, client);
|
||||
return;
|
||||
return -1;
|
||||
}
|
||||
if (hdr->type < ETCPMON_CMD_LIST_CONN || hdr->type > ETCPMON_CMD_SUBSCRIBE_NODES) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Invalid command type from client: 0x%02X", hdr->type);
|
||||
close_client(server, client);
|
||||
return;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Validate header */
|
||||
@@ -764,7 +825,7 @@ static void handle_client_data(struct control_server* server, struct control_cli
|
||||
}
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Invalid message header from client");
|
||||
close_client(server, client);
|
||||
return;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Check if full message received */
|
||||
@@ -777,6 +838,14 @@ static void handle_client_data(struct control_server* server, struct control_cli
|
||||
uint16_t payload_size = hdr->size - sizeof(struct etcpmon_msg_header);
|
||||
|
||||
uint8_t req_seq = hdr->seq_id;
|
||||
if ((hdr->type == ETCPMON_CMD_SELECT_CONN && payload_size != sizeof(struct etcpmon_cmd_select)) ||
|
||||
(hdr->type != ETCPMON_CMD_SELECT_CONN && hdr->type != ETCPMON_CMD_ACTION &&
|
||||
hdr->type != ETCPMON_CMD_SET_DEBUG_CONFIG && payload_size)) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Invalid command payload fd=%d type=0x%02X size=%u",
|
||||
(int)client->fd, hdr->type, payload_size);
|
||||
close_client(server, client);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (server->log_file) {
|
||||
fprintf(server->log_file, "%llu: [LOG] Received command type=0x%02X seq=%d size=%d\n",
|
||||
@@ -803,7 +872,7 @@ static void handle_client_data(struct control_server* server, struct control_cli
|
||||
} else {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Bad SELECT_CONN payload size %u", payload_size);
|
||||
close_client(server, client);
|
||||
return;
|
||||
return -1;
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -821,37 +890,9 @@ static void handle_client_data(struct control_server* server, struct control_cli
|
||||
break;
|
||||
|
||||
case ETCPMON_CMD_ACTION:
|
||||
if (payload_size >= sizeof(struct etcpmon_cmd_action)) {
|
||||
struct etcpmon_cmd_action* cmd = (struct etcpmon_cmd_action*)payload;
|
||||
if (strncmp(cmd->action, "nat", 3) == 0) {
|
||||
DEBUG_INFO(DEBUG_CATEGORY_CONTROL, "Action 'nat' received, requesting NAT check for all links");
|
||||
if (server->instance->nat_det)
|
||||
nat_detection_request_check_all(server->instance->nat_det);
|
||||
stun_nat_recheck(server->instance);
|
||||
} else if (strncmp(cmd->action, "nodes", 5) == 0) {
|
||||
DEBUG_INFO(DEBUG_CATEGORY_CONTROL, "Action 'nodes' received, dumping all BGP nodes");
|
||||
uint16_t text_max = (ETCPMON_MAX_MSG_SIZE > 1024) ? ETCPMON_MAX_MSG_SIZE - 512 : 1024;
|
||||
char* text = (char*)u_malloc(text_max);
|
||||
if (text) {
|
||||
int text_len = topo_node_format_all(topo_groups_get_default(server->instance->topo_groups), text, text_max);
|
||||
if (text_len < 0) text_len = 0;
|
||||
text[text_len] = '\0';
|
||||
uint16_t rsp_size = ETCPMON_ACTION_RESULT_SIZE(text_len);
|
||||
uint8_t* buffer = (uint8_t*)u_malloc(rsp_size);
|
||||
if (buffer) {
|
||||
struct etcpmon_msg_header* rsp_hdr = (struct etcpmon_msg_header*)buffer;
|
||||
etcpmon_build_header(rsp_hdr, sizeof(struct etcpmon_rsp_action_result) + text_len + 1,
|
||||
ETCPMON_RSP_ACTION_RESULT, req_seq);
|
||||
struct etcpmon_rsp_action_result* rsp = (struct etcpmon_rsp_action_result*)(buffer + sizeof(*rsp_hdr));
|
||||
rsp->code = 0;
|
||||
memcpy(buffer + sizeof(*rsp_hdr) + sizeof(*rsp), text, text_len + 1);
|
||||
control_client_send(server, client, buffer, rsp_size);
|
||||
}
|
||||
u_free(text);
|
||||
}
|
||||
} else {
|
||||
DEBUG_WARN(DEBUG_CATEGORY_CONTROL, "Unknown action received: '%.32s'", cmd->action);
|
||||
}
|
||||
if (handle_action(server, client, payload, payload_size, req_seq) < 0) {
|
||||
close_client(server, client);
|
||||
return -1;
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -864,7 +905,7 @@ static void handle_client_data(struct control_server* server, struct control_cli
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Bad SET_DEBUG_CONFIG payload size=%u categories=%d",
|
||||
payload_size, payload_size >= 2 ? payload[1] : -1);
|
||||
close_client(server, client);
|
||||
return;
|
||||
return -1;
|
||||
}
|
||||
uint8_t global_lvl = payload[0];
|
||||
uint8_t cat_count = payload[1];
|
||||
@@ -884,13 +925,6 @@ static void handle_client_data(struct control_server* server, struct control_cli
|
||||
}
|
||||
|
||||
case ETCPMON_CMD_SUBSCRIBE_NODES:
|
||||
client->subscribed_nodes = 1;
|
||||
if (server->log_file) {
|
||||
fprintf(server->log_file, "%llu: [LOG] Client subscribed to node updates\n",
|
||||
(unsigned long long)get_timestamp_ms());
|
||||
fflush(server->log_file);
|
||||
}
|
||||
DEBUG_INFO(DEBUG_CATEGORY_CONTROL, "Client subscribed to node updates");
|
||||
control_server_send_node_list(server, client, req_seq);
|
||||
break;
|
||||
|
||||
@@ -901,22 +935,15 @@ static void handle_client_data(struct control_server* server, struct control_cli
|
||||
fflush(server->log_file);
|
||||
}
|
||||
close_client(server, client);
|
||||
return;
|
||||
return -1;
|
||||
|
||||
default:
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Unknown command from client: 0x%02X", hdr->type);
|
||||
close_client(server, client);
|
||||
return;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Reset idle timer on each valid command */
|
||||
if (client->idle_timer) { uasync_cancel_timeout(server->ua, client->idle_timer); }
|
||||
client->idle_timer = uasync_set_timeout(server->ua, 300000, client, control_client_idle_cb, "ctrl_idle");
|
||||
if (!client->idle_timer) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to reset control client idle timer fd=%d", (int)client->fd);
|
||||
close_client(server, client);
|
||||
return;
|
||||
}
|
||||
if (client->failed) { close_client(server, client); return -1; }
|
||||
|
||||
/* Remove processed message from buffer */
|
||||
uint16_t msg_size = hdr->size;
|
||||
@@ -925,13 +952,70 @@ static void handle_client_data(struct control_server* server, struct control_cli
|
||||
client->recv_len - msg_size);
|
||||
}
|
||||
client->recv_len -= msg_size;
|
||||
if (client->output_queue->head || client->snapshot_active || client->dirty_count) {
|
||||
if (control_wait_output(client) < 0) { close_client(server, client); return -1; }
|
||||
return 0;
|
||||
}
|
||||
if (control_client_arm_timer(client, 0) < 0) { close_client(server, client); return -1; }
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ============================================================================
|
||||
* Response Builders
|
||||
* ============================================================================ */
|
||||
|
||||
/* Любая корректная Action завершается ответом с исходным seq; nat подтверждает запуск, а не результат проверки. */
|
||||
static int handle_action(struct control_server* server, struct control_client* client,
|
||||
const uint8_t* payload, uint16_t size, uint8_t seq_id) {
|
||||
if (size != sizeof(struct etcpmon_cmd_action) || !memchr(payload, 0, size)) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Invalid Action payload fd=%d seq=%u size=%u", (int)client->fd, seq_id, size);
|
||||
return -1;
|
||||
}
|
||||
const char* action = (const char*)payload;
|
||||
int nat = !strcmp(action, "nat");
|
||||
if (!nat && strcmp(action, "nodes")) {
|
||||
DEBUG_WARN(DEBUG_CATEGORY_CONTROL, "Unknown Action fd=%d seq=%u action='%s'", (int)client->fd, seq_id, action);
|
||||
send_error(client, ETCPMON_ERR_INVALID_CMD, "Unknown action", seq_id);
|
||||
return 0;
|
||||
}
|
||||
struct TOPO_GROUP* group = topo_groups_get_default(server->instance->topo_groups);
|
||||
if ((nat && !server->instance->nat_det && !server->instance->stun_nat) || (!nat && !group)) {
|
||||
DEBUG_WARN(DEBUG_CATEGORY_CONTROL, "Action unavailable fd=%d seq=%u action=%s", (int)client->fd, seq_id, action);
|
||||
send_error(client, ETCPMON_ERR_SERVER_BUSY, nat ? "NAT/STUN service unavailable" : "BGP not available", seq_id);
|
||||
return 0;
|
||||
}
|
||||
size_t capacity = nat ? ETCPMON_ACTION_RESULT_SIZE(strlen("NAT check requested")) : ETCPMON_MAX_MSG_SIZE;
|
||||
uint8_t* buffer = u_malloc(capacity);
|
||||
if (!buffer) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Action response allocation failed fd=%d seq=%u size=%zu", (int)client->fd, seq_id, capacity);
|
||||
return -1;
|
||||
}
|
||||
struct etcpmon_msg_header* header = (void*)buffer;
|
||||
struct etcpmon_rsp_action_result* result = (void*)(buffer + sizeof(*header));
|
||||
char* text = (char*)(result + 1);
|
||||
int text_len;
|
||||
if (nat) {
|
||||
if (server->instance->nat_det) nat_detection_request_check_all(server->instance->nat_det);
|
||||
stun_nat_recheck(server->instance);
|
||||
strcpy(text, "NAT check requested");
|
||||
text_len = (int)strlen(text);
|
||||
} else {
|
||||
text_len = topo_node_format_all(group, text, capacity - sizeof(*header) - sizeof(*result));
|
||||
if (text_len < 0) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Action nodes formatting failed fd=%d seq=%u", (int)client->fd, seq_id);
|
||||
u_free(buffer);
|
||||
send_error(client, ETCPMON_ERR_SERVER_BUSY, "Node dump failed", seq_id);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
result->code = 0;
|
||||
etcpmon_build_header(header, sizeof(*result) + text_len + 1, ETCPMON_RSP_ACTION_RESULT, seq_id);
|
||||
DEBUG_INFO(DEBUG_CATEGORY_CONTROL, "Action completed fd=%d seq=%u action=%s response_bytes=%u",
|
||||
(int)client->fd, seq_id, action, header->size);
|
||||
return control_client_send(server, client, buffer, header->size);
|
||||
}
|
||||
|
||||
static void send_conn_list(struct control_server* server, struct control_client* client, uint8_t seq_id) {
|
||||
struct UTUN_INSTANCE* instance = server->instance;
|
||||
|
||||
@@ -948,6 +1032,7 @@ static void send_conn_list(struct control_server* server, struct control_client*
|
||||
uint8_t* buffer = (uint8_t*)u_malloc(rsp_size);
|
||||
if (!buffer) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to allocate connection list buffer");
|
||||
client->failed = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -987,7 +1072,11 @@ static void send_socket_list(struct control_server* server, struct control_clien
|
||||
if (!instance || !instance->etcp_sockets) {
|
||||
uint16_t rsp_size = ETCPMON_SOCKET_LIST_SIZE(0);
|
||||
uint8_t* buffer = (uint8_t*)u_malloc(rsp_size);
|
||||
if (!buffer) return;
|
||||
if (!buffer) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to allocate empty socket list fd=%d", (int)client->fd);
|
||||
client->failed = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
struct etcpmon_msg_header* hdr = (struct etcpmon_msg_header*)buffer;
|
||||
etcpmon_build_header(hdr, sizeof(struct etcpmon_rsp_socket_list),
|
||||
@@ -1019,6 +1108,7 @@ static void send_socket_list(struct control_server* server, struct control_clien
|
||||
uint8_t* buffer = (uint8_t*)u_malloc(rsp_size);
|
||||
if (!buffer) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to allocate socket list buffer");
|
||||
client->failed = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1110,6 +1200,7 @@ static void send_metrics(struct control_server* server, struct control_client* c
|
||||
uint8_t* buffer = (uint8_t*)u_malloc(rsp_size);
|
||||
if (!buffer) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to allocate metrics buffer");
|
||||
client->failed = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1362,7 +1453,11 @@ static void send_error(struct control_client* client, uint8_t error_code, const
|
||||
uint16_t rsp_size = ETCPMON_ERROR_SIZE(msg_len);
|
||||
|
||||
uint8_t* buffer = (uint8_t*)u_malloc(rsp_size);
|
||||
if (!buffer) return;
|
||||
if (!buffer) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to allocate control error fd=%d seq=%u", (int)client->fd, seq_id);
|
||||
client->failed = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
struct etcpmon_msg_header* hdr = (struct etcpmon_msg_header*)buffer;
|
||||
etcpmon_build_header(hdr, sizeof(struct etcpmon_rsp_error) + msg_len + 1,
|
||||
@@ -1403,7 +1498,11 @@ static void send_debug_config(struct control_server* server, struct control_clie
|
||||
uint16_t payload_size = 2 + names_len + cat_count;
|
||||
uint16_t rsp_size = sizeof(struct etcpmon_msg_header) + payload_size;
|
||||
uint8_t* buffer = (uint8_t*)u_malloc(rsp_size);
|
||||
if (!buffer) { DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to allocate debug config buffer"); return; }
|
||||
if (!buffer) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to allocate debug config buffer");
|
||||
client->failed = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
struct etcpmon_msg_header* hdr = (struct etcpmon_msg_header*)buffer;
|
||||
etcpmon_build_header(hdr, payload_size, ETCPMON_RSP_DEBUG_CONFIG, seq_id);
|
||||
@@ -1443,16 +1542,29 @@ static struct ETCP_CONN* find_connection_by_peer_id(struct UTUN_INSTANCE* instan
|
||||
static void send_single_node_info(struct control_server* server, struct control_client* client, struct TOPO_GROUP_NODE* nq) {
|
||||
if (!server || !nq) return;
|
||||
struct TOPO_NODE* ni = topo_node_registry_find(server->instance->topo_groups, nq->node_id);
|
||||
if (!ni) return;
|
||||
uint8_t buf[8192];
|
||||
if (!ni) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Node snapshot has no registry entry fd=%d node=%016llx", (int)client->fd,
|
||||
(unsigned long long)nq->node_id);
|
||||
client->failed = 1;
|
||||
return;
|
||||
}
|
||||
uint8_t buf[TOPO_NODE_WIRE_MAX_SIZE + 2];
|
||||
int ser_len = topo_node_serialize(ni, nq, TOPO_GROUP_UTUN, TOPO_FLAG_SEND_SUBNETS, buf + 2, sizeof(buf) - 2, 0);
|
||||
if (ser_len < 0) { DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to serialize node info"); return; }
|
||||
if (ser_len < 0) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to serialize node info node=%016llx", (unsigned long long)nq->node_id);
|
||||
client->failed = 1;
|
||||
return;
|
||||
}
|
||||
buf[0] = CTRL_BGP_CMD; buf[1] = CTRL_BGP_SUBCMD;
|
||||
size_t data_size = 2 + (size_t)ser_len;
|
||||
|
||||
size_t np_size = sizeof(struct etcpmon_msg_header) + data_size;
|
||||
uint8_t* buffer = (uint8_t*)u_malloc(np_size);
|
||||
if (!buffer) { DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to allocate node info buffer"); return; }
|
||||
if (!buffer) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to allocate node info buffer");
|
||||
client->failed = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
struct etcpmon_msg_header* hdr = (struct etcpmon_msg_header*)buffer;
|
||||
etcpmon_build_header(hdr, (uint16_t)data_size, ETCPMON_RSP_NODE_INFO, 0);
|
||||
@@ -1463,61 +1575,148 @@ static void send_single_node_info(struct control_server* server, struct control_
|
||||
|
||||
static void control_server_send_node_list(struct control_server* server, struct control_client* client, uint8_t seq_id) {
|
||||
struct TOPO_GROUP* group = topo_groups_get_default(server->instance->topo_groups);
|
||||
if (!group) { send_error(client, ETCPMON_ERR_SERVER_BUSY, "BGP not available", seq_id); return; }
|
||||
|
||||
/* Send local node first */
|
||||
if (group->local_node) send_single_node_info(server, client, group->local_node);
|
||||
|
||||
/* Send all known remote nodes */
|
||||
struct ll_entry* e = group->nodes ? group->nodes->head : NULL;
|
||||
while (e) {
|
||||
struct TOPO_GROUP_NODE* nq = (struct TOPO_GROUP_NODE*)e;
|
||||
send_single_node_info(server, client, nq);
|
||||
e = e->next;
|
||||
if (!group) {
|
||||
DEBUG_WARN(DEBUG_CATEGORY_CONTROL, "Node subscription unavailable fd=%d seq=%u", (int)client->fd, seq_id);
|
||||
send_error(client, ETCPMON_ERR_SERVER_BUSY, "BGP not available", seq_id);
|
||||
return;
|
||||
}
|
||||
size_t count = (group->nodes ? queue_entry_count(group->nodes) : 0) + (group->local_node != NULL);
|
||||
if (count > UINT32_MAX / sizeof(uint64_t)) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Node snapshot too large fd=%d nodes=%zu", (int)client->fd, count);
|
||||
client->failed = 1;
|
||||
return;
|
||||
}
|
||||
uint64_t* ids = count ? u_malloc(count * sizeof(*ids)) : NULL;
|
||||
if (count && !ids) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Node snapshot allocation failed fd=%d nodes=%zu", (int)client->fd, count);
|
||||
client->failed = 1;
|
||||
return;
|
||||
}
|
||||
size_t used = 0;
|
||||
if (group->local_node) ids[used++] = group->local_node->node_id;
|
||||
for (struct ll_entry* e = group->nodes ? group->nodes->head : NULL; e; e = e->next) {
|
||||
if (used >= count) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Node snapshot count mismatch fd=%d count=%zu", (int)client->fd, count);
|
||||
u_free(ids); client->failed = 1;
|
||||
return;
|
||||
}
|
||||
ids[used++] = ((struct TOPO_GROUP_NODE*)e)->node_id;
|
||||
}
|
||||
u_free(client->snapshot_ids);
|
||||
client->snapshot_ids = ids; client->snapshot_count = used; client->snapshot_index = 0;
|
||||
client->snapshot_active = 1; client->snapshot_seq = seq_id; client->subscribed_nodes = 1;
|
||||
DEBUG_INFO(DEBUG_CATEGORY_CONTROL, "Node snapshot started fd=%d seq=%u nodes=%zu id_bytes=%zu",
|
||||
(int)client->fd, seq_id, used, used * sizeof(*ids));
|
||||
}
|
||||
|
||||
/* Send end-of-list marker */
|
||||
uint8_t* buffer = (uint8_t*)u_malloc(sizeof(struct etcpmon_msg_header));
|
||||
if (!buffer) return;
|
||||
struct etcpmon_msg_header* hdr = (struct etcpmon_msg_header*)buffer;
|
||||
etcpmon_build_header(hdr, 0, ETCPMON_RSP_NODE_INFO_END, seq_id);
|
||||
control_client_send(server, client, buffer, sizeof(struct etcpmon_msg_header));
|
||||
/* Продолжение producer после опустошения TX; за один вызов создаётся максимум один кадр. */
|
||||
static void control_output_ready(struct ll_queue* queue, void* arg) {
|
||||
struct control_client* client = arg;
|
||||
struct control_server* server = client->server;
|
||||
if (client->failed) { close_client(server, client); return; }
|
||||
if (queue->head) {
|
||||
if (control_wait_output(client) < 0) close_client(server, client);
|
||||
return;
|
||||
}
|
||||
struct TOPO_GROUP* group = topo_groups_get_default(server->instance->topo_groups);
|
||||
if ((client->snapshot_active || client->dirty_count) && !group) {
|
||||
DEBUG_WARN(DEBUG_CATEGORY_CONTROL, "Subscribed UTUN group disappeared fd=%d", (int)client->fd);
|
||||
close_client(server, client);
|
||||
return;
|
||||
}
|
||||
while (client->snapshot_active && client->snapshot_index < client->snapshot_count && !queue->head && !client->failed) {
|
||||
uint64_t id = client->snapshot_ids[client->snapshot_index++];
|
||||
struct TOPO_GROUP_NODE* node = group->local_node && group->local_node->node_id == id ?
|
||||
group->local_node : topo_node_find_by_id(group, id);
|
||||
if (node) send_single_node_info(server, client, node);
|
||||
else DEBUG_DEBUG(DEBUG_CATEGORY_CONTROL, "Snapshot skips removed node fd=%d node=%016llx", (int)client->fd,
|
||||
(unsigned long long)id);
|
||||
}
|
||||
if (client->snapshot_active && client->snapshot_index == client->snapshot_count && !queue->head && !client->failed) {
|
||||
uint8_t* buffer = u_malloc(sizeof(struct etcpmon_msg_header));
|
||||
if (!buffer) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to allocate node list end fd=%d", (int)client->fd);
|
||||
client->failed = 1;
|
||||
} else {
|
||||
etcpmon_build_header((void*)buffer, 0, ETCPMON_RSP_NODE_INFO_END, client->snapshot_seq);
|
||||
DEBUG_INFO(DEBUG_CATEGORY_CONTROL, "Node snapshot queued fd=%d seq=%u nodes=%zu",
|
||||
(int)client->fd, client->snapshot_seq, client->snapshot_count);
|
||||
client->snapshot_active = 0;
|
||||
u_free(client->snapshot_ids); client->snapshot_ids = NULL;
|
||||
client->snapshot_count = 0; client->snapshot_index = 0;
|
||||
control_client_send(server, client, buffer, sizeof(struct etcpmon_msg_header));
|
||||
}
|
||||
}
|
||||
while (!client->snapshot_active && client->dirty_count && !queue->head && !client->failed) {
|
||||
uint64_t id = client->dirty_ids[0];
|
||||
int removed = client->dirty_removed[0];
|
||||
client->dirty_count--;
|
||||
memmove(client->dirty_ids, client->dirty_ids + 1, client->dirty_count * sizeof(*client->dirty_ids));
|
||||
memmove(client->dirty_removed, client->dirty_removed + 1, client->dirty_count * sizeof(*client->dirty_removed));
|
||||
struct TOPO_GROUP_NODE* node = group->local_node && group->local_node->node_id == id ?
|
||||
group->local_node : topo_node_find_by_id(group, id);
|
||||
if (!removed && node) send_single_node_info(server, client, node);
|
||||
else {
|
||||
size_t size = sizeof(struct etcpmon_msg_header) + sizeof(id);
|
||||
uint8_t* buffer = u_malloc(size);
|
||||
if (!buffer) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to allocate node removal fd=%d", (int)client->fd);
|
||||
client->failed = 1;
|
||||
break;
|
||||
}
|
||||
etcpmon_build_header((void*)buffer, sizeof(id), ETCPMON_RSP_NODE_REMOVED, 0);
|
||||
memcpy(buffer + sizeof(struct etcpmon_msg_header), &id, sizeof(id));
|
||||
control_client_send(server, client, buffer, (uint16_t)size);
|
||||
}
|
||||
}
|
||||
if (client->failed) { close_client(server, client); return; }
|
||||
if (queue->head) return;
|
||||
if (handle_client_data(server, client) < 0) return;
|
||||
if (queue->head || client->snapshot_active || client->dirty_count) return;
|
||||
if (client->read_paused) {
|
||||
if (uasync_set_socket_read(server->ua, client->socket_id, 1) < 0) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_CONTROL, "Failed to resume control reads fd=%d", (int)client->fd);
|
||||
close_client(server, client);
|
||||
return;
|
||||
}
|
||||
client->read_paused = 0;
|
||||
DEBUG_DEBUG(DEBUG_CATEGORY_CONTROL, "Control reads resumed fd=%d buffered=%u", (int)client->fd, client->recv_len);
|
||||
}
|
||||
if (client->timer_is_tx && control_client_arm_timer(client, 0) < 0) close_client(server, client);
|
||||
}
|
||||
|
||||
DEBUG_INFO(DEBUG_CATEGORY_CONTROL, "Sent node list to client (seq=%d)", seq_id);
|
||||
/* Сохраняет только последнее событие узла. Ограниченный набор не растёт от повторов одного ID. */
|
||||
static int control_mark_node(struct control_client* client, uint64_t id, int removed) {
|
||||
size_t index = 0;
|
||||
while (index < client->dirty_count && client->dirty_ids[index] != id) index++;
|
||||
if (index == CONTROL_NODE_DIRTY_MAX) {
|
||||
DEBUG_WARN(DEBUG_CATEGORY_CONTROL, "Control subscriber overwhelmed fd=%d dirty_nodes=%zu queued_bytes=%zu",
|
||||
(int)client->fd, client->dirty_count, queue_total_bytes(client->output_queue));
|
||||
return -1;
|
||||
}
|
||||
if (index == client->dirty_count) client->dirty_count++;
|
||||
client->dirty_ids[index] = id; client->dirty_removed[index] = removed != 0;
|
||||
return control_wait_output(client);
|
||||
}
|
||||
|
||||
void control_server_notify_node_change(struct control_server* server, struct TOPO_GROUP_NODE* node) {
|
||||
if (!server || !node) return;
|
||||
struct control_client* client = server->clients;
|
||||
while (client) {
|
||||
if (client->subscribed_nodes) send_single_node_info(server, client, node);
|
||||
client = client->next;
|
||||
struct control_client* next = client->next;
|
||||
if (client->subscribed_nodes && control_mark_node(client, node->node_id, 0) < 0) close_client(server, client);
|
||||
client = next;
|
||||
}
|
||||
}
|
||||
|
||||
void control_server_notify_node_removed(struct control_server* server, uint64_t node_id) {
|
||||
if (!server) return;
|
||||
|
||||
uint8_t* buffer = (uint8_t*)u_malloc(sizeof(struct etcpmon_msg_header) + sizeof(uint64_t));
|
||||
if (!buffer) return;
|
||||
|
||||
struct etcpmon_msg_header* hdr = (struct etcpmon_msg_header*)buffer;
|
||||
etcpmon_build_header(hdr, sizeof(uint64_t), ETCPMON_RSP_NODE_REMOVED, 0);
|
||||
*(uint64_t*)(buffer + sizeof(*hdr)) = node_id;
|
||||
|
||||
struct control_client* client = server->clients;
|
||||
while (client) {
|
||||
if (client->subscribed_nodes) {
|
||||
/* Every client needs its own copy since ownership transfers to the queue */
|
||||
uint8_t* copy = (uint8_t*)u_malloc(sizeof(struct etcpmon_msg_header) + sizeof(uint64_t));
|
||||
if (copy) {
|
||||
memcpy(copy, buffer, sizeof(struct etcpmon_msg_header) + sizeof(uint64_t));
|
||||
control_client_send(server, client, copy, sizeof(struct etcpmon_msg_header) + sizeof(uint64_t));
|
||||
}
|
||||
}
|
||||
client = client->next;
|
||||
struct control_client* next = client->next;
|
||||
if (client->subscribed_nodes && control_mark_node(client, node_id, 1) < 0) close_client(server, client);
|
||||
client = next;
|
||||
}
|
||||
u_free(buffer);
|
||||
}
|
||||
|
||||
/* ============================================================================
|
||||
|
||||
+32
-6
@@ -2,7 +2,11 @@
|
||||
* control_server.h - Control Socket Server for ETCP Monitoring
|
||||
*
|
||||
* TCP-мониторинг ETCP: init → обработка команд в uasync-потоке → shutdown.
|
||||
* Метрики отправляются по запросу; доступ — по IPv4 control_allow, idle timeout — 30 секунд.
|
||||
* Метрики отправляются по запросу; доступ — по IPv4 [control] allow.
|
||||
* Один таймер 30 секунд: отсутствие команд в покое либо отсутствие прогресса send при активном TX.
|
||||
* Шифрования/аутентификации протокола нет. Общий wire-контракт — etcpmon_protocol.h.
|
||||
* Client владеет сокетом, таймером и одним TX-кадром до 32 КиБ. Остальные команды ждут в RX.
|
||||
* Начальный список узлов хранится как ID, сериализуется порционно; live-изменения объединяются по ID.
|
||||
*/
|
||||
|
||||
#ifndef CONTROL_SERVER_H
|
||||
@@ -10,6 +14,7 @@
|
||||
|
||||
#include "../tools/etcpmon/etcpmon_protocol.h"
|
||||
#include "../lib/socket_compat.h"
|
||||
#include "../lib/ll_queue.h"
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
|
||||
@@ -26,6 +31,8 @@ struct ll_queue;
|
||||
/* Forward declaration */
|
||||
struct control_server;
|
||||
|
||||
#define CONTROL_NODE_DIRTY_MAX 256
|
||||
|
||||
/* Client connection state */
|
||||
struct control_client {
|
||||
struct control_client* next; /* Linked list */
|
||||
@@ -40,11 +47,23 @@ struct control_client {
|
||||
/* Selected connection */
|
||||
uint64_t selected_peer_id; /* 0 = none selected */
|
||||
|
||||
struct ll_queue* output_queue; /* Output queue for async sends */
|
||||
struct ll_queue* output_queue; /* Владеет единственным TX-кадром; следующий producer ждёт пустой очереди */
|
||||
uint16_t output_offset; /* Отправленные байты головы очереди; dgram/len не меняются */
|
||||
void* idle_timer; /* Client idle timeout */
|
||||
void* idle_timer; /* Отсутствие команд либо прогресса TX, см. timer_is_tx */
|
||||
uint8_t subscribed_nodes; /* 1 = subscribed to node updates */
|
||||
uint8_t write_registered; /* 1 = write events registered in uasync */
|
||||
uint8_t read_paused; /* Чтение/разбор ждут пустой TX-очереди */
|
||||
uint8_t failed; /* Ошибка producer; владелец callback закроет client после возврата */
|
||||
uint8_t timer_is_tx; /* Таймер контролирует прогресс TX, иначе отсутствие команд */
|
||||
struct queue_waiter_handle output_waiter; /* Отложенное продолжение; отменить до освобождения client */
|
||||
uint64_t* snapshot_ids; /* ID начального списка; никаких заимствованных TOPO_GROUP_NODE* */
|
||||
size_t snapshot_count;
|
||||
size_t snapshot_index; /* Следующий ID для сериализации */
|
||||
uint8_t snapshot_active; /* 1 до постановки NODE_INFO_END */
|
||||
uint8_t snapshot_seq; /* seq запроса для NODE_INFO_END */
|
||||
uint64_t dirty_ids[CONTROL_NODE_DIRTY_MAX]; /* Последние изменения объединяются по ID */
|
||||
uint8_t dirty_removed[CONTROL_NODE_DIRTY_MAX]; /* Последнее событие: 1 = удаление, 0 = обновление */
|
||||
size_t dirty_count; /* При переполнении подписчик отключается, события не теряются молча */
|
||||
};
|
||||
|
||||
/* Control server state */
|
||||
@@ -79,10 +98,11 @@ struct control_server {
|
||||
* ua - uasync context for event handling
|
||||
* instance - Parent utun instance
|
||||
* bind_addr - Address to bind (from config control_sock)
|
||||
* max_clients - Maximum concurrent client connections
|
||||
* max_clients - Maximum concurrent client connections; 0 selects 8
|
||||
*
|
||||
* Returns:
|
||||
* 0 on success, -1 on error
|
||||
* 0 on success, -1 on error. Server copies bind_addr; caller retains ua/instance/server.
|
||||
* With valid arguments, shutdown also cleans resources left by a failed initialization.
|
||||
*/
|
||||
int control_server_init(struct control_server* server,
|
||||
struct UASYNC* ua,
|
||||
@@ -100,7 +120,8 @@ int control_server_init(struct control_server* server,
|
||||
void control_server_shutdown(struct control_server* server);
|
||||
|
||||
/* Разобрать накопленные команды всех клиентов в uasync-потоке.
|
||||
* Чтение сокета также запускает разбор; метрики отправляются только по CMD_GET_METRICS.
|
||||
* Чтение сокета само запускает разбор; отдельный периодический вызов не требуется.
|
||||
* Функция лишь повторно разбирает уже принятые данные, не читает сокеты и не рассылает метрики по таймеру.
|
||||
*
|
||||
* Parameters:
|
||||
* server - Server state
|
||||
@@ -117,7 +138,12 @@ void control_server_process_updates(struct control_server* server);
|
||||
*/
|
||||
uint32_t control_server_get_client_count(const struct control_server* server);
|
||||
|
||||
/* В uasync-потоке отметить последнее изменение node у подписчиков; node заимствован на время вызова.
|
||||
* NODE_INFO содержит 01 04 + topo_node_serialize для UTUN с подсетями; seq=0.
|
||||
* Сериализация отложена до освобождения TX, запись заново ищется по ID. Вызывать только для UTUN-группы.
|
||||
* Более 256 различных ожидающих ID отключают подписчика с WARN; события не теряются молча. */
|
||||
void control_server_notify_node_change(struct control_server* server, struct TOPO_GROUP_NODE* node);
|
||||
/* В uasync-потоке отметить удаление UTUN node_id; NODE_REMOVED с seq=0 отправляется после освобождения TX. */
|
||||
void control_server_notify_node_removed(struct control_server* server, uint64_t node_id);
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
@@ -5,16 +5,28 @@ TCP-сервер для мониторинга ETCP-соединений. При
|
||||
|
||||
## 2. Как пользоваться
|
||||
1. Вызвать `control_server_init()` — создаёт слушающий TCP-сокет на адресе из конфига `control_sock`, регистрирует accept-колбэк в uasync.
|
||||
2. Периодически вызывать `control_server_process_updates()` для обработки накопившихся данных клиентов.
|
||||
3. При изменении/удалении узла BGP-топологии вызывать `control_server_notify_node_change()` / `control_server_notify_node_removed()` — сервер сам разошлёт уведомления подписанным клиентам.
|
||||
2. Выполнять цикл uasync: read-колбэк сам принимает и разбирает команды. Периодический вызов
|
||||
`control_server_process_updates()` не требуется; эта функция лишь повторно разбирает уже накопленные данные.
|
||||
3. При изменении/удалении узла UTUN-группы вызывать `control_server_notify_node_change()` /
|
||||
`control_server_notify_node_removed()` — сервер отметит ID и отправит актуальное состояние при освобождении TX.
|
||||
4. При остановке вызвать `control_server_shutdown()`.
|
||||
|
||||
**Нюансы:**
|
||||
- Доступ разрешён только IPv4-клиентам по `control_allow` в конфиге; без правил доступ запрещён. IPv6-клиенты отклоняются.
|
||||
- Клиенты отключаются по idle-таймауту (30 секунд без команд). Каждая обработанная команда перезапускает таймер.
|
||||
- В покое клиент отключается после 30 секунд без команд. При активной отправке тот же таймер
|
||||
отсчитывает 30 секунд без положительного `send()`; поступление команд его не продлевает.
|
||||
- Лог пишется в `control_server.log`: дампы содержат первые 256 байт каждого чтения RX и некоторых ответов TX.
|
||||
- `control_server_process_updates()` разбирает команды; метрики отправляются только по `CMD_GET_METRICS`.
|
||||
- Очередь отправки владеет исходными буферами до полной отправки или отключения; частичная отправка хранит отдельное смещение.
|
||||
- В TX помещается один кадр до 32 КиБ. Следующий producer ждёт пустой очереди через deferred
|
||||
`queue_waiter_wait()`. Чтение сокета и разбор уже принятого RX-буфера приостановлены до освобождения TX.
|
||||
- Подписка сохраняет ID текущих узлов (`8 × N` байт), сериализует их по одному при освобождении TX.
|
||||
Узлы повторно ищутся по ID; удалённые до своей очереди пропускаются. После начального списка
|
||||
отправляется `NODE_INFO_END` с seq запроса, затем накопленные live-изменения.
|
||||
- Live-изменения объединяются по ID (последнее обновление/удаление); предел — 256 различных ID.
|
||||
При переполнении подписчик отключается с WARN. CHAT-узлы в эту подписку не входят.
|
||||
- При stop/ошибке отменяются timer и waiter, включая уже запланированный callback, затем освобождаются
|
||||
список ID и TX-буфер. `control_client_send()` сам клиента не освобождает: ошибку обрабатывает владелец callback.
|
||||
- Если список сокетов превышает предел сообщения (32 768 байт; сейчас помещается 230 записей),
|
||||
возвращается `RSP_ERROR` с кодом `SERVER_BUSY`. Список не усекается; сокеты `probe_only` не учитываются.
|
||||
- `SET_DEBUG_CONFIG` требует ровно `2 + category_count` байт, не более 64 категорий.
|
||||
@@ -35,7 +47,7 @@ TCP-сервер для мониторинга ETCP-соединений. При
|
||||
|---------|-----------|
|
||||
| `control_server_init(server, ua, instance, bind_addr, max_clients)` | Создать слушающий сокет, зарегистрировать в uasync. Возвращает 0 / -1. |
|
||||
| `control_server_shutdown(server)` | Закрыть всех клиентов, освободить слушающий сокет, закрыть лог-файл. |
|
||||
| `control_server_process_updates(server)` | Обработать накопившиеся данные всех клиентов (вызывать периодически). |
|
||||
| `control_server_process_updates(server)` | Повторно разобрать накопленные данные всех клиентов; вызов необязателен. |
|
||||
| `control_server_get_client_count(server)` | Вернуть количество подключённых клиентов. |
|
||||
| `control_server_notify_node_change(server, node)` | Разослать подписанным клиентам сериализованную информацию об узле. |
|
||||
| `control_server_notify_node_removed(server, node_id)` | Разослать подписанным клиентам уведомление об удалении узла. |
|
||||
@@ -48,8 +60,16 @@ TCP-сервер для мониторинга ETCP-соединений. При
|
||||
| `CMD_SELECT_CONN` | — | Выбрать соединение по `peer_node_id` для метрик. |
|
||||
| `CMD_GET_METRICS` | `RSP_METRICS` | Полные метрики: ETCP, TUN, router, все каналы с BBR. |
|
||||
| `CMD_LIST_SOCKETS` | `RSP_SOCKET_LIST` | Список локальных сокетов с NAT-типом и NAT-адресом. |
|
||||
| `CMD_ACTION` | Для `"nodes"` — `RSP_ACTION_RESULT`; для `"nat"` — без ответа | `"nat"` — запрос NAT-проверки; `"nodes"` — дамп BGP-узлов текстом. |
|
||||
| `CMD_ACTION` | `RSP_ACTION_RESULT` или `RSP_ERROR`, с seq запроса | Полные имена `"nodes"`/`"nat"`; `nat` подтверждает запуск проверки, неизвестное имя даёт ошибку. |
|
||||
| `CMD_GET_DEBUG_CONFIG` | `RSP_DEBUG_CONFIG` | Текущие уровни отладки (глобальный + по категориям). |
|
||||
| `CMD_SET_DEBUG_CONFIG` | — | Установить уровни отладки. |
|
||||
| `CMD_SUBSCRIBE_NODES` | `RSP_NODE_INFO` (список) + `RSP_NODE_INFO_END` | Подписка на изменения узлов + текущий список. |
|
||||
| `CMD_DISCONNECT` | — | Отключение клиента. |
|
||||
|
||||
Общий формат задаёт `tools/etcpmon/etcpmon_protocol.h`: 4-байтовый заголовок с `seq_id`, packed-структуры,
|
||||
целые в порядке байтов хоста, без согласования версии/шифрования. Обычный ответ копирует `seq_id`
|
||||
запроса; снимки `NODE_INFO` имеют `seq=0`, маркер `NODE_INFO_END` — seq запроса подписки.
|
||||
`NODE_INFO` содержит префикс `01 04` и результат `topo_node_serialize()` для UTUN с подсетями.
|
||||
|
||||
Action требует ровно 32 байта payload с NUL внутри поля. Повреждённая команда закрывает соединение;
|
||||
неизвестное корректное имя или недоступная служба возвращают `RSP_ERROR` без разрыва TCP.
|
||||
@@ -1200,9 +1200,11 @@ static int topo_group_routes_changed(struct TOPO_GROUP* group, struct TOPO_GROUP
|
||||
topo_fire_nodeinfo_cbk(group->instance, group, node);
|
||||
if (!node->paths) {
|
||||
event = TOPO_NODE_EVENT_REMOVE;
|
||||
if (group->instance->control_srv) control_server_notify_node_removed(group->instance->control_srv, id);
|
||||
if (group->group_id == TOPO_GROUP_UTUN && group->instance->control_srv)
|
||||
control_server_notify_node_removed(group->instance->control_srv, id);
|
||||
topo_nodeq_remove_node(group, node);
|
||||
} else if (group->instance->control_srv) control_server_notify_node_change(group->instance->control_srv, node);
|
||||
} else if (group->group_id == TOPO_GROUP_UTUN && group->instance->control_srv)
|
||||
control_server_notify_node_change(group->instance->control_srv, node);
|
||||
for (struct topo_node_cbk_entry* c = group->node_cbks; c; c = c->next) c->fn(group, id, event, c->arg);
|
||||
topo_group_publish_route(group, id);
|
||||
topo_recovery_changed(group);
|
||||
|
||||
+187
-7
@@ -1,12 +1,20 @@
|
||||
/* Регрессии control_server: настоящие очереди/таймеры, управляемые короткие send
|
||||
* и ошибки регистрации. Включение реализации даёт доступ к socket callbacks. */
|
||||
#define nat_detection_request_check_all test_nat_check_all
|
||||
#define stun_nat_recheck test_stun_recheck
|
||||
#include "../src/control_server.c"
|
||||
#undef nat_detection_request_check_all
|
||||
#undef stun_nat_recheck
|
||||
#include <assert.h>
|
||||
|
||||
static socket_t pending_accept = -1, capture_fd = -1;
|
||||
static int fail_registration, fail_timer, fail_entry, send_mode;
|
||||
static size_t send_chunk, wire_size;
|
||||
static uint8_t wire[ETCPMON_MAX_MSG_SIZE];
|
||||
static uint8_t wire[ETCPMON_MAX_MSG_SIZE * 8];
|
||||
static int nat_checks, stun_checks;
|
||||
|
||||
void test_nat_check_all(struct NAT_DETECTION* detector) { assert(detector); nat_checks++; }
|
||||
void test_stun_recheck(struct UTUN_INSTANCE* instance) { assert(instance); stun_checks++; }
|
||||
|
||||
socket_t __real_accept(socket_t, struct sockaddr*, socklen_t*);
|
||||
socket_t __wrap_accept(socket_t fd, struct sockaddr* addr, socklen_t* len) {
|
||||
@@ -82,6 +90,9 @@ static void fixture_destroy(struct fixture* f) {
|
||||
capture_fd = -1; send_mode = 0;
|
||||
control_server_shutdown(&f->server);
|
||||
if (f->peer >= 0) close(f->peer);
|
||||
DEBUG_DEBUG(DEBUG_CATEGORY_CONTROL, "Fixture drain after shutdown: timers_alloc=%zu timers_free=%zu immediate=%p",
|
||||
f->inst.ua->timer_alloc_count, f->inst.ua->timer_free_count, (void*)f->inst.ua->immediate_queue_head);
|
||||
uasync_drain_immediate(f->inst.ua);
|
||||
TimeoutEntry pending;
|
||||
assert(timeout_heap_peek(f->inst.ua->timeout_heap, &pending) != 0);
|
||||
assert(timeout_heap_get_size(f->inst.ua->timeout_heap) == 0);
|
||||
@@ -101,29 +112,39 @@ static void test_partial_send(void) {
|
||||
struct fixture f; fixture_init(&f);
|
||||
struct control_client* client = fixture_accept(&f); assert(client);
|
||||
capture_fd = client->fd; send_chunk = 3; wire_size = 0;
|
||||
enqueue(&f, client, "0123456789"); enqueue(&f, client, "abcdefgh");
|
||||
enqueue(&f, client, "0123456789");
|
||||
uint8_t* base = client->output_queue->head->dgram;
|
||||
client_write_callback(client->fd, client);
|
||||
assert(client->output_offset == 3 && client->output_queue->head->dgram == base);
|
||||
assert(queue_total_bytes(client->output_queue) == 18);
|
||||
assert(queue_total_bytes(client->output_queue) == 10);
|
||||
send_mode = 1; client_write_callback(client->fd, client);
|
||||
assert(client->output_offset == 3 && wire_size == 3);
|
||||
send_mode = 0;
|
||||
while (client->output_queue->head) client_write_callback(client->fd, client);
|
||||
enqueue(&f, client, "abcdefgh");
|
||||
while (client->output_queue->head) client_write_callback(client->fd, client);
|
||||
assert(wire_size == 18 && !memcmp(wire, "0123456789abcdefgh", 18));
|
||||
assert(!client->output_offset && !client->write_registered && !queue_total_bytes(client->output_queue));
|
||||
uasync_drain_immediate(f.inst.ua);
|
||||
assert(!client->read_paused && !client->output_waiter.internal && !client->output_waiter.call_soon_id);
|
||||
fixture_destroy(&f);
|
||||
puts("PASS partial send: exact wire bytes, EAGAIN, stable buffer and queue accounting");
|
||||
}
|
||||
|
||||
static void test_cleanup(void) {
|
||||
for (int mode = 0; mode <= 3; mode++) {
|
||||
for (int mode = 0; mode <= 4; mode++) {
|
||||
struct fixture f; fixture_init(&f);
|
||||
struct control_client* client = fixture_accept(&f); assert(client);
|
||||
enqueue(&f, client, "first message"); enqueue(&f, client, "second message");
|
||||
enqueue(&f, client, "first message");
|
||||
capture_fd = client->fd; send_chunk = 2; wire_size = 0;
|
||||
client_write_callback(client->fd, client); assert(client->output_offset == 2);
|
||||
if (mode >= 2) { send_mode = mode; client_write_callback(client->fd, client); }
|
||||
if (mode == 4) {
|
||||
send_chunk = 100;
|
||||
client_write_callback(client->fd, client);
|
||||
assert(client->output_waiter.call_soon_id);
|
||||
close_client(&f.server, client);
|
||||
uasync_drain_immediate(f.inst.ua);
|
||||
} else if (mode >= 2) { send_mode = mode; client_write_callback(client->fd, client); }
|
||||
else if (mode == 1) {
|
||||
uasync_cancel_timeout(f.inst.ua, client->idle_timer);
|
||||
control_client_idle_cb(client);
|
||||
@@ -249,9 +270,168 @@ static void test_socket_limit(void) {
|
||||
puts("PASS socket list: zero, maximum fitting, first excessive and 250 sockets; probe-only sockets excluded");
|
||||
}
|
||||
|
||||
/* Action подтверждает запуск NAT, возвращает ошибки без разрыва и не принимает префиксы/повреждённые строки. */
|
||||
static void test_actions(void) {
|
||||
for (int variant = 0; variant < 7; variant++) {
|
||||
struct fixture f; fixture_init(&f);
|
||||
struct control_client* client = fixture_accept(&f); assert(client);
|
||||
struct etcpmon_msg_header* header = (void*)client->recv_buffer;
|
||||
struct etcpmon_cmd_action action = {0};
|
||||
strcpy(action.action, variant == 2 ? "nat123" : variant == 3 ? "unknown" : variant == 6 ? "nodes" : "nat");
|
||||
if (variant == 0) f.inst.nat_det = (void*)&f;
|
||||
if (variant == 5) memset(&action, 'x', sizeof(action));
|
||||
etcpmon_build_header(header, sizeof(action) - (variant == 4), ETCPMON_CMD_ACTION, 41 + variant);
|
||||
memcpy(client->recv_buffer + sizeof(*header), &action, sizeof(action));
|
||||
client->recv_len = header->size;
|
||||
handle_client_data(&f.server, client);
|
||||
if (variant == 4 || variant == 5) assert(!f.server.clients);
|
||||
else {
|
||||
assert(f.server.clients == client);
|
||||
struct ll_entry* entry = queue_data_get(client->output_queue); assert(entry);
|
||||
struct etcpmon_msg_header* response = (void*)entry->dgram;
|
||||
assert(response->seq_id == 41 + variant && response->size == entry->len);
|
||||
assert(response->type == (variant == 0 ? ETCPMON_RSP_ACTION_RESULT : ETCPMON_RSP_ERROR));
|
||||
if (variant == 0) assert(strstr((char*)entry->dgram + sizeof(*response) + 1, "requested"));
|
||||
queue_dgram_free(entry); queue_entry_free(entry);
|
||||
}
|
||||
fixture_destroy(&f);
|
||||
}
|
||||
assert(nat_checks == 1 && stun_checks == 1);
|
||||
puts("PASS Action: NAT acknowledgement, unavailable services, unknown/exact names and malformed payloads");
|
||||
}
|
||||
|
||||
/* Пакет запросов остаётся в bounded RX до отправки предыдущего ответа; команды не продлевают TX deadline. */
|
||||
static void test_backpressure(void) {
|
||||
struct fixture f; fixture_init(&f);
|
||||
struct control_client* client = fixture_accept(&f); assert(client);
|
||||
for (int i = 0; i < 8; i++)
|
||||
etcpmon_build_header((void*)(client->recv_buffer + i * sizeof(struct etcpmon_msg_header)), 0,
|
||||
ETCPMON_CMD_GET_DEBUG_CONFIG, i + 1);
|
||||
client->recv_len = 8 * sizeof(struct etcpmon_msg_header);
|
||||
assert(handle_client_data(&f.server, client) == 0);
|
||||
assert(client->output_queue->count == 1 && client->read_paused && client->timer_is_tx);
|
||||
assert(client->recv_len == 7 * sizeof(struct etcpmon_msg_header));
|
||||
void* deadline = client->idle_timer;
|
||||
capture_fd = client->fd; send_mode = 1; wire_size = 0;
|
||||
for (int i = 0; i < 10; i++) {
|
||||
assert(handle_client_data(&f.server, client) == 0);
|
||||
client_write_callback(client->fd, client);
|
||||
assert(client->output_queue->count == 1 && client->idle_timer == deadline);
|
||||
}
|
||||
send_mode = 0; send_chunk = 3;
|
||||
for (int step = 0; step < 5000 && (client->read_paused || client->output_queue->head); step++) {
|
||||
if (client->output_queue->head) client_write_callback(client->fd, client);
|
||||
uasync_drain_immediate(f.inst.ua);
|
||||
assert(client->output_queue->count <= 1 && queue_total_bytes(client->output_queue) <= ETCPMON_MAX_MSG_SIZE);
|
||||
}
|
||||
assert(!client->read_paused && !client->recv_len && !client->timer_is_tx);
|
||||
size_t offset = 0;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
struct etcpmon_msg_header* header = (void*)(wire + offset);
|
||||
assert(header->type == ETCPMON_RSP_DEBUG_CONFIG && header->seq_id == i + 1);
|
||||
offset += header->size;
|
||||
}
|
||||
assert(offset == wire_size);
|
||||
fixture_destroy(&f);
|
||||
puts("PASS backpressure: one TX frame, paused buffered requests, exact ordered replies and independent TX deadline");
|
||||
}
|
||||
|
||||
/* Минимальная настоящая топология для сериализации большого списка без сетевых служб/БД. */
|
||||
struct node_fixture {
|
||||
struct TOPO_GROUPS groups;
|
||||
struct TOPO_GROUP* group;
|
||||
struct TOPO_NODE* records;
|
||||
};
|
||||
|
||||
static void node_fixture_init(struct fixture* f, struct node_fixture* nodes, int count) {
|
||||
memset(nodes, 0, sizeof(*nodes));
|
||||
nodes->groups.instance = &f->inst; f->inst.topo_groups = &nodes->groups;
|
||||
nodes->groups.group_list = queue_new(f->inst.ua, 16, 0, 8, "test groups");
|
||||
nodes->groups.node_registry = queue_new(f->inst.ua, 16, 0, 8, "test registry");
|
||||
struct ll_entry* entry = queue_entry_new(sizeof(struct TOPO_GROUP)); assert(entry);
|
||||
memset(entry->data, 0, entry->size);
|
||||
nodes->group = (void*)entry; nodes->group->group_id = TOPO_GROUP_UTUN; nodes->group->instance = &f->inst;
|
||||
nodes->group->nodes = queue_new(f->inst.ua, 16, offsetof(struct TOPO_GROUP_NODE, node_id) - sizeof(struct ll_entry), 8, "test nodes");
|
||||
assert(nodes->groups.group_list && nodes->groups.node_registry && nodes->group->nodes);
|
||||
assert(queue_data_put_with_index(nodes->groups.group_list, entry) == 0);
|
||||
nodes->records = u_calloc(count, sizeof(*nodes->records)); assert(nodes->records);
|
||||
for (int i = 0; i < count; i++) {
|
||||
struct TOPO_NODE* record = &nodes->records[i];
|
||||
record->node_id = 100 + i; record->timestamp = 1; record->node_name = "monitor-test";
|
||||
entry = queue_entry_new(8 + sizeof(record)); assert(entry);
|
||||
memcpy(entry->data, &record->node_id, 8); memcpy(entry->data + 8, &record, sizeof(record));
|
||||
assert(queue_data_put_with_index(nodes->groups.node_registry, entry) == 0);
|
||||
entry = queue_entry_new(sizeof(struct TOPO_GROUP_NODE)); assert(entry);
|
||||
memset(entry->data, 0, entry->size);
|
||||
((struct TOPO_GROUP_NODE*)entry)->node_id = record->node_id;
|
||||
assert(queue_data_put_with_index(nodes->group->nodes, entry) == 0);
|
||||
}
|
||||
}
|
||||
|
||||
static void node_fixture_destroy(struct fixture* f, struct node_fixture* nodes) {
|
||||
if (f->server.clients) close_client(&f->server, f->server.clients);
|
||||
struct ll_entry* entry;
|
||||
while ((entry = queue_data_get(nodes->group->nodes))) queue_entry_free(entry);
|
||||
queue_free(nodes->group->nodes);
|
||||
queue_entry_free(queue_data_get(nodes->groups.group_list)); queue_free(nodes->groups.group_list);
|
||||
while ((entry = queue_data_get(nodes->groups.node_registry))) queue_entry_free(entry);
|
||||
queue_free(nodes->groups.node_registry); u_free(nodes->records); f->inst.topo_groups = NULL;
|
||||
}
|
||||
|
||||
/* Снимок больше wire-лимита, удаление ещё не отправленного узла и объединение live-изменений. */
|
||||
static void test_node_snapshot(void) {
|
||||
struct fixture f; fixture_init(&f);
|
||||
struct node_fixture nodes; node_fixture_init(&f, &nodes, 400);
|
||||
struct control_client* client = fixture_accept(&f); assert(client);
|
||||
control_server_send_node_list(&f.server, client, 77);
|
||||
assert(client->snapshot_count == 400 && !client->output_queue->head);
|
||||
assert(control_wait_output(client) == 0);
|
||||
uasync_drain_immediate(f.inst.ua);
|
||||
assert(client->output_queue->count == 1);
|
||||
struct TOPO_GROUP_NODE* removed = topo_node_find_by_id(nodes.group, 101); assert(removed);
|
||||
control_server_notify_node_removed(&f.server, 101);
|
||||
assert(queue_remove_data(nodes.group->nodes, &removed->ll) == 0); queue_entry_free(&removed->ll);
|
||||
nodes.records[2].timestamp = 2;
|
||||
for (int i = 0; i < 100; i++) control_server_notify_node_change(&f.server, topo_node_find_by_id(nodes.group, 102));
|
||||
assert(client->dirty_count == 2);
|
||||
capture_fd = client->fd; send_chunk = ETCPMON_MAX_MSG_SIZE; wire_size = 0;
|
||||
for (int step = 0; step < 2000 && client->read_paused; step++) {
|
||||
if (client->output_queue->head) client_write_callback(client->fd, client);
|
||||
uasync_drain_immediate(f.inst.ua);
|
||||
assert(client->output_queue->count <= 1 && queue_total_bytes(client->output_queue) <= ETCPMON_MAX_MSG_SIZE);
|
||||
}
|
||||
assert(!client->read_paused && !client->snapshot_ids && !client->dirty_count && wire_size > ETCPMON_MAX_MSG_SIZE);
|
||||
size_t offset = 0; int infos = 0, ends = 0, removals = 0, updated = 0;
|
||||
while (offset < wire_size) {
|
||||
struct etcpmon_msg_header* header = (void*)(wire + offset);
|
||||
assert(etcpmon_validate_header(header) == 0 && offset + header->size <= wire_size);
|
||||
if (header->type == ETCPMON_RSP_NODE_INFO) {
|
||||
struct TOPOMSG_NODE* node = (void*)(wire + offset + sizeof(*header) + 2);
|
||||
assert(node->node_id != 101);
|
||||
if (node->node_id == 102) { assert(node->timestamp == 2); updated++; }
|
||||
infos++;
|
||||
} else if (header->type == ETCPMON_RSP_NODE_INFO_END) {
|
||||
assert(header->seq_id == 77 && infos == 399); ends++;
|
||||
} else {
|
||||
uint64_t id; memcpy(&id, wire + offset + sizeof(*header), sizeof(id));
|
||||
assert(header->type == ETCPMON_RSP_NODE_REMOVED && id == 101 && ends == 1); removals++;
|
||||
}
|
||||
offset += header->size;
|
||||
}
|
||||
assert(infos == 400 && ends == 1 && removals == 1 && updated == 2);
|
||||
for (int i = 0; i < CONTROL_NODE_DIRTY_MAX; i++) control_server_notify_node_removed(&f.server, 1000 + i);
|
||||
assert(client->dirty_count == CONTROL_NODE_DIRTY_MAX);
|
||||
control_server_notify_node_removed(&f.server, 1000 + CONTROL_NODE_DIRTY_MAX);
|
||||
assert(!f.server.clients);
|
||||
uasync_drain_immediate(f.inst.ua);
|
||||
node_fixture_destroy(&f, &nodes); fixture_destroy(&f);
|
||||
puts("PASS node snapshot: 400 nodes with one frame, removed/updated IDs, ordered end, coalescing and bounded overload cleanup");
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
debug_config_init(); debug_set_level(DEBUG_LEVEL_WARN);
|
||||
debug_set_category_level(DEBUG_CATEGORY_CONTROL, DEBUG_LEVEL_DEBUG);
|
||||
test_partial_send(); test_cleanup(); test_debug_payload(); test_metrics(); test_socket_limit();
|
||||
test_partial_send(); test_cleanup(); test_debug_payload(); test_metrics(); test_socket_limit(); test_actions();
|
||||
test_backpressure(); test_node_snapshot();
|
||||
return 0;
|
||||
}
|
||||
+22
-166
@@ -1,171 +1,27 @@
|
||||
# ETCP Monitor - Implementation Summary
|
||||
# Устройство etcpmon
|
||||
|
||||
## Overview
|
||||
ETCP Monitor is a Windows GUI utility for real-time monitoring of ETCP connections in uTun.
|
||||
Действующие контракты и использование описаны в [etcpmon_doc.md](etcpmon_doc.md),
|
||||
API — в `etcpmon_client.h`, `etcpmon_gui.h`, `etcpmon_graph.h` и `etcpmon_protocol.h`.
|
||||
Серверная реализация: `src/control_server.c/h` и
|
||||
[control_server_doc.md](../../src/control_server_doc.md).
|
||||
|
||||
## Architecture
|
||||
`WinMain` создаёт `etcpmon_app`, инициализирует Winsock/классы окон, создаёт окно и запускает
|
||||
message loop. Таймер GUI вызывает неблокирующий `etcpmon_client_process()`; фонового сетевого
|
||||
потока нет. Client завершает connect, разбирает TCP-кадры, обновляет кеши и вызывает GUI callbacks.
|
||||
Сэмпл истории добавляет только парсер ответа метрик; GUI отображает уже сохранённую историю.
|
||||
|
||||
### Protocol (Binary)
|
||||
- **Format**: `[2 bytes: size] [1 byte: type] [payload...]`
|
||||
- **Period**: 100ms updates
|
||||
- **Transport**: TCP socket
|
||||
Все команды клиента проходят через один TX FIFO с лимитом 64 КиБ/256 кадров и смещением досылки.
|
||||
Pending с ненулевым seq регистрируется вместе с кадром, но срок ответа начинается после полной отправки.
|
||||
Тип и payload ответа проверяются до снятия pending и вызова callback.
|
||||
|
||||
### Message Types
|
||||
**Client → Server:**
|
||||
- `0x01` - Request connection list
|
||||
- `0x02` - Select connection by peer_node_id
|
||||
- `0x03` - Request metrics
|
||||
- `0x04` - Disconnect
|
||||
Сервер использует `ll_queue` с одним кадром до 32 КиБ и отдельным смещением частичной отправки.
|
||||
Чтение/разбор команд ждут пустой очереди через отменяемый deferred waiter. Начальная подписка
|
||||
хранит ID узлов и сериализует актуальную запись при освобождении TX; live-изменения объединяются
|
||||
в ограниченном наборе из 256 ID. Переполнение отключает подписчика с диагностикой.
|
||||
Перед освобождением клиента отменяются таймер и waiter, затем освобождаются снимок и очередь.
|
||||
Метрики выдаются по запросу, а сообщения об узлах UTUN — только после явной подписки другого клиента;
|
||||
сам GUI etcpmon подписку не использует.
|
||||
|
||||
**Server → Client:**
|
||||
- `0x81` - Connection list response
|
||||
- `0x82` - Metrics response (ETCP + TUN + Links)
|
||||
- `0xFF` - Error response
|
||||
|
||||
## Files Created
|
||||
|
||||
### Protocol (Shared)
|
||||
- `tools/etcpmon/etcpmon_protocol.h` - Protocol definitions and structures
|
||||
|
||||
### Server (uTun)
|
||||
- `src/control_server.h` - Control server interface
|
||||
- `src/control_server.c` - TCP server implementation
|
||||
- Modified `src/utun_instance.c` - Integration with uTun lifecycle
|
||||
- Modified `src/Makefile.am` - Added control_server.c to build
|
||||
- Modified `lib/debug_config.h` - Added DEBUG_CATEGORY_CONTROL
|
||||
|
||||
### Client (Windows GUI)
|
||||
- `tools/etcpmon/etcpmon_client.h/c` - Network layer (Winsock)
|
||||
- `tools/etcpmon/etcpmon_gui.h/c` - WinAPI GUI implementation
|
||||
- `tools/etcpmon/etcpmon_main.c` - Entry point
|
||||
- `tools/etcpmon/Makefile.mingw` - MinGW build
|
||||
- `tools/etcpmon/build.bat` - Windows build script
|
||||
- `tools/etcpmon/build.sh` - Unix build script
|
||||
- `tools/etcpmon/clean.bat` - Clean script
|
||||
- `tools/etcpmon/README.md` - Documentation
|
||||
|
||||
### Test
|
||||
- `tests/test_control_server.c` - Integration test for control server protocol
|
||||
|
||||
### Library Fix
|
||||
- `lib/u_async.c` - Modified to use select() on Windows instead of WSAPoll
|
||||
|
||||
## Build Instructions
|
||||
|
||||
### Windows (Recommended)
|
||||
```cmd
|
||||
cd tools\etcpmon
|
||||
build.bat
|
||||
```
|
||||
|
||||
### Unix/MinGW
|
||||
```bash
|
||||
cd tools/etcpmon
|
||||
bash build.sh
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### 1. Configure uTun
|
||||
Add to `utun.conf`:
|
||||
```ini
|
||||
control_ip=127.0.0.1
|
||||
control_port=9090
|
||||
```
|
||||
|
||||
### 2. Start uTun
|
||||
```bash
|
||||
./utun
|
||||
```
|
||||
|
||||
### 3. Start ETCP Monitor
|
||||
```cmd
|
||||
etcpmon.exe
|
||||
```
|
||||
|
||||
### 4. Connect
|
||||
- Enter server IP:port (default: 127.0.0.1:9090)
|
||||
- Click "Connect"
|
||||
- Select connection from list
|
||||
- View real-time metrics
|
||||
|
||||
## Metrics Displayed
|
||||
|
||||
### ETCP Connection
|
||||
- RTT (last, avg 10, avg 100)
|
||||
- Jitter
|
||||
- Bytes sent total
|
||||
- Retransmission count
|
||||
- ACK count
|
||||
- Unacked bytes
|
||||
- Links count
|
||||
|
||||
### TUN Interface
|
||||
- Bytes read/written
|
||||
- Packets read/written
|
||||
- Read/write errors
|
||||
|
||||
### Links (per link)
|
||||
- Status (UP/DOWN)
|
||||
- Encrypt/decrypt errors
|
||||
- Send/receive errors
|
||||
- Total encrypted/decrypted bytes
|
||||
- Bandwidth (Kbps)
|
||||
- NAT changes count
|
||||
|
||||
## Technical Details
|
||||
|
||||
### Windows select() Implementation
|
||||
On Windows, the uasync library now uses `select()` instead of `WSAPoll()` for socket monitoring. This resolves issues with accepted TCP sockets that caused WSAPoll to fail with error 10022 (WSAEINVAL).
|
||||
|
||||
**Changes in `lib/u_async.c`:**
|
||||
- Added Windows-specific code path using `select()`
|
||||
- Maintains compatibility with Linux (uses `poll()`)
|
||||
- Properly handles both regular FDs and socket_t types
|
||||
|
||||
### Binary Protocol
|
||||
The protocol uses fixed-size binary structures for efficient communication:
|
||||
- Header: 3 bytes (2 size + 1 type)
|
||||
- Connection list item: 40 bytes (8 peer_id + 32 name)
|
||||
- ETCP metrics: 40 bytes
|
||||
- Link metrics: 32 bytes per link
|
||||
- TUN metrics: 24 bytes
|
||||
|
||||
## Testing
|
||||
|
||||
### Unit Test
|
||||
```bash
|
||||
cd tests
|
||||
./test_control_server
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```
|
||||
================================
|
||||
Control Server Protocol Test
|
||||
================================
|
||||
|
||||
[TEST] Setting up mock data...
|
||||
[TEST] Mock data ready (1 conn, 2 links)
|
||||
[TEST] Starting control server on port 19090...
|
||||
[TEST] Control server started ✓
|
||||
[TEST] Starting client thread...
|
||||
[TEST] Running event loop...
|
||||
|
||||
[CLIENT] Connecting to 127.0.0.1:19090...
|
||||
[CLIENT] Connected
|
||||
[CLIENT] Sending CMD_LIST_CONN...
|
||||
[CLIENT] Waiting for response...
|
||||
[CLIENT] Received connection list: 1 connection(s)
|
||||
[CLIENT] Connection verified: peer_id=0x1234567890ABCDEF ✓
|
||||
[CLIENT] All tests passed ✓
|
||||
|
||||
[TEST] Cleaning up...
|
||||
|
||||
================================
|
||||
[PASS] All tests passed!
|
||||
================================
|
||||
```
|
||||
|
||||
## License
|
||||
See main project LICENSE file.
|
||||
Проверки клиента: `make -C tools/etcpmon CC=x86_64-w64-mingw32-gcc TEST_RUNNER=wine check`.
|
||||
Проверки серверных очередей/cleanup/метрик: цель `test_control_server` из `tests/Makefile.am`.
|
||||
Они проверяют разные стороны протокола и не заменяют интеграционный запуск клиента с сервером.
|
||||
+37
-109
@@ -1,137 +1,65 @@
|
||||
# ETCP Monitor
|
||||
|
||||
Windows GUI утилита для мониторинга ETCP подключений uTun в реальном времени.
|
||||
WinAPI-монитор соединений uTun. Работает под Windows и Wine, подключается по IPv4 TCP
|
||||
к `control_server`. Метрики выбранного соединения запрашиваются раз в 100 мс,
|
||||
списки соединений и сокетов — раз в секунду. Сеть обрабатывается в GUI-потоке.
|
||||
|
||||
## Описание
|
||||
Полное описание протокола, интерфейса, владения ресурсами и текущих ограничений:
|
||||
[etcpmon_doc.md](etcpmon_doc.md). Серверная часть: [control_server_doc.md](../../src/control_server_doc.md).
|
||||
|
||||
ETCP Monitor - это Windows GUI приложение, которое подключается к работающему экземпляру uTun и отображает статистику ETCP подключений в реальном времени с периодом обновления 100мс.
|
||||
## Сборка и запуск
|
||||
|
||||
## Архитектура
|
||||
|
||||
### Протокол управления (бинарный)
|
||||
|
||||
Формат сообщения: `[2 байта: размер] [1 байт: тип] [payload...]`
|
||||
|
||||
**Команды клиента:**
|
||||
- `0x01` - запрос списка подключений
|
||||
- `0x02` - выбор подключения по `peer_node_id`
|
||||
- `0x03` - запрос метрик выбранного подключения
|
||||
- `0x04` - отключение
|
||||
|
||||
**Ответы сервера:**
|
||||
- `0x81` - список подключений
|
||||
- `0x82` - метрики ETCP + линки + TUN
|
||||
- `0xFF` - ошибка
|
||||
|
||||
### Файлы
|
||||
|
||||
**Общие (протокол):**
|
||||
- `etcpmon_protocol.h` - определения структур и констант протокола
|
||||
|
||||
**Сервер (utun):**
|
||||
- `src/control_server.h` - интерфейс control server
|
||||
- `src/control_server.c` - реализация TCP сервера
|
||||
|
||||
**Клиент (Windows GUI):**
|
||||
- `etcpmon_client.h/c` - сетевая часть (Winsock)
|
||||
- `etcpmon_gui.h/c` - GUI (WinAPI)
|
||||
- `etcpmon_main.c` - точка входа
|
||||
|
||||
## Сборка
|
||||
|
||||
### Клиент (Windows) - Рекомендуемый способ
|
||||
|
||||
**Используя MSYS2 UCRT64 (рекомендуется):**
|
||||
Windows/MSYS2 UCRT64:
|
||||
|
||||
```cmd
|
||||
cd tools\etcpmon
|
||||
build.bat
|
||||
etcpmon.exe
|
||||
```
|
||||
|
||||
Это автоматически запустит MSYS2 UCRT64 shell и выполнит сборку.
|
||||
`build.bat` использует `C:\msys64`, либо `MSYS2_ROOT`/`MSYS2`. Внутри MSYS2 можно выполнить `bash build.sh`.
|
||||
|
||||
Требования:
|
||||
- Установленный MSYS2 (обычно в `C:\msys64`)
|
||||
- Или переменная окружения `MSYS2_ROOT` с путем к MSYS2
|
||||
|
||||
**Альтернативные способы:**
|
||||
Linux с установленными MinGW и Wine, из корня проекта:
|
||||
|
||||
```bash
|
||||
# Через MSYS2 напрямую
|
||||
cd tools/etcpmon
|
||||
bash build.sh
|
||||
|
||||
# Через Makefile (если установлен make для Windows)
|
||||
make -f Makefile.mingw
|
||||
make -C tools/etcpmon CC=x86_64-w64-mingw32-gcc
|
||||
wine tools/etcpmon/etcpmon.exe
|
||||
make -C tools/etcpmon CC=x86_64-w64-mingw32-gcc TEST_RUNNER=wine check
|
||||
```
|
||||
|
||||
**Очистка:**
|
||||
```cmd
|
||||
clean.bat
|
||||
```
|
||||
Для запуска GUI и WinAPI-тестов нужен дисплей; без рабочего стола можно использовать `xvfb-run -a`.
|
||||
|
||||
### Сервер (utun)
|
||||
## Подключение
|
||||
|
||||
Control server интегрирован в utun. Сборка стандартная:
|
||||
|
||||
```bash
|
||||
./configure
|
||||
make
|
||||
```
|
||||
|
||||
## Настройка
|
||||
|
||||
### Конфигурация uTun
|
||||
|
||||
Добавьте в `utun.conf`:
|
||||
В конфиге uTun:
|
||||
|
||||
```ini
|
||||
control_ip=127.0.0.1
|
||||
control_port=9090
|
||||
[control]
|
||||
ip=127.0.0.1
|
||||
port=9090
|
||||
allow=127.0.0.1/32
|
||||
```
|
||||
|
||||
### Использование
|
||||
Без `allow` все подключения отклоняются. Транспорт управления не шифруется и не аутентифицирует
|
||||
ключи ETCP: используйте loopback или доверенный защищённый канал.
|
||||
|
||||
1. Запустите uTun с настроенным control socket
|
||||
2. Запустите etcpmon.exe
|
||||
3. Введите IP и порт control сервера
|
||||
4. Нажмите "Connect"
|
||||
5. Выберите подключение из списка для просмотра метрик
|
||||
При открытии окна etcpmon автоматически начинает connect к `192.168.40.1:9091`.
|
||||
Нажмите Disconnect, задайте числовой IPv4/порт своего сервера и нажмите Connect.
|
||||
Первое соединение выбирается автоматически. Enter в адресе/порту подключает, Escape отключает.
|
||||
|
||||
## Отображаемые метрики
|
||||
## Состав
|
||||
|
||||
### ETCP Connection:
|
||||
- RTT Last/Avg10/Avg100 (микросекунды)
|
||||
- Jitter (микросекунды)
|
||||
- Bytes Sent (всего)
|
||||
- Retransmissions (число)
|
||||
- ACK received (число)
|
||||
- Unacked bytes (текущие)
|
||||
- Links count (число линков)
|
||||
- `etcpmon_client.c/h`: неблокирующий Winsock-клиент, разбор кадров, pending ответов, кеши и история.
|
||||
- `etcpmon_gui.c/h`: окно, контролы, опрос списков, обработка событий и Action Result.
|
||||
- `etcpmon_graph.c/h`: график восьми метрик первого линка и выбор сэмпла курсором.
|
||||
- `etcpmon_protocol.h`: общий с сервером wire-layout: `[size:2][type:1][seq_id:1][payload]`.
|
||||
- `test_etcpmon.c`: регрессии клиента/GUI с локальным TCP-сервером; запускаются через `make check`.
|
||||
|
||||
### TUN Interface:
|
||||
- Bytes Read/Written
|
||||
- Packets Read/Written
|
||||
- Read/Write Errors
|
||||
Команда Action `nodes` возвращает текст узлов, `nat` подтверждает запуск NAT/STUN-проверки.
|
||||
Неизвестная команда или недоступная служба возвращает ошибку с сохранением TCP-соединения.
|
||||
|
||||
### Links:
|
||||
- Status (UP/DOWN)
|
||||
- Encrypt/Decrypt Errors
|
||||
- Send/Receive Errors
|
||||
- Total Encrypted/Decrypted Bytes
|
||||
- Bandwidth (Kbps)
|
||||
- NAT Changes Count
|
||||
Клиент досылает частичные кадры через ограниченный TX (64 КиБ/256 кадров). Сервер формирует
|
||||
один кадр до 32 КиБ, приостанавливая чтение до его отправки; список узлов передаётся порциями.
|
||||
Таймауты и ограничения подписки описаны в [etcpmon_doc.md](etcpmon_doc.md).
|
||||
|
||||
## Период обновления
|
||||
|
||||
100 мс (10 обновлений в секунду)
|
||||
|
||||
## Безопасность
|
||||
|
||||
- Поддержка нескольких одновременных клиентов
|
||||
- Отдельный TCP сокет (не путать с ETCP UDP)
|
||||
- Рекомендуется использовать localhost (127.0.0.1) для локального мониторинга
|
||||
|
||||
## Лицензия
|
||||
|
||||
См. основной LICENSE файл проекта uTun.
|
||||
Клиент пишет `etcpmon.log`, сервер — `control_server.log` в текущем рабочем каталоге каждого процесса.
|
||||
+276
-377
@@ -18,6 +18,117 @@
|
||||
|
||||
static struct etcpmon_pending_request* find_pending_request(struct etcpmon_client* client, uint8_t seq_id);
|
||||
|
||||
/* Кадр живёт до полной отправки; offset не меняет исходные байты и порядок FIFO. */
|
||||
struct etcpmon_tx_frame {
|
||||
struct etcpmon_tx_frame* next;
|
||||
uint16_t size;
|
||||
uint16_t offset;
|
||||
uint8_t seq_id;
|
||||
uint8_t bytes[];
|
||||
};
|
||||
|
||||
/* Единственная ветка аварийного отключения: лог, освобождение транспорта и уведомления владельца. */
|
||||
static int client_fail(struct etcpmon_client* client, const char* reason, int error) {
|
||||
FILE* log = client->log_file ? client->log_file : stderr;
|
||||
fprintf(log, "%llu: [ERROR] %s: error=%d queued_frames=%u queued_bytes=%u\n",
|
||||
(unsigned long long)get_timestamp_ms(), reason, error, client->tx_count, (unsigned)client->tx_bytes);
|
||||
fflush(log);
|
||||
etcpmon_client_disconnect(client);
|
||||
if (client->on_disconnected) client->on_disconnected(client->user_data);
|
||||
if (client->on_error) client->on_error(reason, client->user_data);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Неблокирующая досылка: за вызов не более одного максимального кадра по объёму. */
|
||||
static int flush_outgoing(struct etcpmon_client* client) {
|
||||
size_t budget = ETCPMON_MAX_MSG_SIZE;
|
||||
while (client->fully_connected && client->tx_head && budget) {
|
||||
struct etcpmon_tx_frame* frame = client->tx_head;
|
||||
int size = frame->size - frame->offset;
|
||||
if ((size_t)size > budget) size = (int)budget;
|
||||
int sent = send(client->sock, (const char*)frame->bytes + frame->offset, size, 0);
|
||||
if (sent == SOCKET_ERROR) {
|
||||
int error = WSAGetLastError();
|
||||
if (error != WSAEWOULDBLOCK) return client_fail(client, "TCP send failed", error);
|
||||
if (!client->tx_blocked && client->log_file) {
|
||||
fprintf(client->log_file, "[DEBUG] TX waiting: frames=%u bytes=%u offset=%u/%u\n",
|
||||
client->tx_count, (unsigned)client->tx_bytes, frame->offset, frame->size);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
client->tx_blocked = 1;
|
||||
return 0;
|
||||
}
|
||||
if (!sent) return client_fail(client, "TCP send made no progress", 0);
|
||||
if (client->tx_blocked && client->log_file) {
|
||||
fprintf(client->log_file, "[DEBUG] TX resumed: sent=%d frames=%u bytes=%u\n", sent, client->tx_count, (unsigned)client->tx_bytes);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
client->tx_blocked = 0;
|
||||
client->tx_progress_at = GetTickCount();
|
||||
frame->offset += sent;
|
||||
budget -= sent;
|
||||
if (frame->offset != frame->size) continue;
|
||||
struct etcpmon_pending_request* req = find_pending_request(client, frame->seq_id);
|
||||
if (req) { req->sent = 1; req->sent_at = client->tx_progress_at; }
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "[DEBUG] TX complete: type=0x%02X seq=%u size=%u\n",
|
||||
frame->bytes[2], frame->seq_id, frame->size);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
client->tx_head = frame->next;
|
||||
if (!client->tx_head) client->tx_tail = NULL;
|
||||
client->tx_bytes -= frame->size;
|
||||
client->tx_count--;
|
||||
free(frame);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Принимает req во владение, если передан; публикация кадра и pending выполняется до первого send. */
|
||||
static int send_message(struct etcpmon_client* client, uint8_t type, const void* payload,
|
||||
uint16_t payload_size, struct etcpmon_pending_request* req) {
|
||||
size_t size = sizeof(struct etcpmon_msg_header) + (size_t)payload_size;
|
||||
if (!client || !client->connected || client->sock == INVALID_SOCKET || size > ETCPMON_MAX_MSG_SIZE ||
|
||||
(payload_size && !payload)) {
|
||||
FILE* log = client && client->log_file ? client->log_file : stderr;
|
||||
fprintf(log, "[ERROR] Invalid outgoing command: type=0x%02X size=%u connected=%d\n",
|
||||
type, (unsigned)size, client ? client->connected : 0);
|
||||
fflush(log); free(req);
|
||||
return -1;
|
||||
}
|
||||
if (client->tx_count >= ETCPMON_TX_MAX_FRAMES || size > ETCPMON_TX_MAX_BYTES - client->tx_bytes) {
|
||||
FILE* log = client->log_file ? client->log_file : stderr;
|
||||
fprintf(log, "[ERROR] TX queue full: type=0x%02X size=%u frames=%u bytes=%u\n",
|
||||
type, (unsigned)size, client->tx_count, (unsigned)client->tx_bytes);
|
||||
fflush(log); free(req);
|
||||
return -1;
|
||||
}
|
||||
struct etcpmon_tx_frame* frame = malloc(sizeof(*frame) + size);
|
||||
if (!frame) {
|
||||
FILE* log = client->log_file ? client->log_file : stderr;
|
||||
fprintf(log, "[ERROR] TX allocation failed: type=0x%02X size=%u\n", type, (unsigned)size);
|
||||
fflush(log); free(req);
|
||||
return -1;
|
||||
}
|
||||
frame->next = NULL; frame->size = (uint16_t)size; frame->offset = 0; frame->seq_id = req ? req->seq_id : 0;
|
||||
etcpmon_build_header((void*)frame->bytes, payload_size, type, frame->seq_id);
|
||||
if (payload_size) memcpy(frame->bytes + sizeof(struct etcpmon_msg_header), payload, payload_size);
|
||||
if (req) {
|
||||
if (client->pending_tail) client->pending_tail->next = req;
|
||||
else client->pending_head = req;
|
||||
client->pending_tail = req;
|
||||
}
|
||||
if (client->tx_tail) client->tx_tail->next = frame;
|
||||
else { client->tx_head = frame; client->tx_progress_at = GetTickCount(); }
|
||||
client->tx_tail = frame; client->tx_bytes += size; client->tx_count++;
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "[DEBUG] TX queued: type=0x%02X seq=%u size=%u frames=%u bytes=%u\n",
|
||||
type, frame->seq_id, (unsigned)size, client->tx_count, (unsigned)client->tx_bytes);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
return flush_outgoing(client);
|
||||
}
|
||||
|
||||
/* Get current timestamp in milliseconds (Unix epoch) */
|
||||
uint64_t get_timestamp_ms(void) {
|
||||
FILETIME ft;
|
||||
@@ -140,7 +251,8 @@ int etcpmon_client_connect(struct etcpmon_client* client, const char* addr, uint
|
||||
|
||||
/* Set non-blocking mode */
|
||||
u_long nonblock = 1;
|
||||
ioctlsocket(client->sock, FIONBIO, &nonblock);
|
||||
if (ioctlsocket(client->sock, FIONBIO, &nonblock) == SOCKET_ERROR)
|
||||
return client_fail(client, "Failed to enable nonblocking TCP", WSAGetLastError());
|
||||
|
||||
/* Setup address */
|
||||
struct sockaddr_in server_addr;
|
||||
@@ -188,6 +300,7 @@ int etcpmon_client_connect(struct etcpmon_client* client, const char* addr, uint
|
||||
client->server_port = port;
|
||||
client->connected = 1;
|
||||
client->fully_connected = 0;
|
||||
client->connect_started_at = GetTickCount();
|
||||
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [LOG] Socket created, connection in progress\n",
|
||||
@@ -202,20 +315,6 @@ void etcpmon_client_disconnect(struct etcpmon_client* client) {
|
||||
if (!client) return;
|
||||
|
||||
if (client->sock != INVALID_SOCKET) {
|
||||
/* Send disconnect command */
|
||||
if (client->connected) {
|
||||
struct etcpmon_msg_header hdr;
|
||||
etcpmon_build_header(&hdr, 0, ETCPMON_CMD_DISCONNECT, 0);
|
||||
|
||||
if (client->log_file) {
|
||||
log_hex_data(client->log_file, "TX", (const uint8_t*)&hdr, sizeof(hdr));
|
||||
fprintf(client->log_file, "%llu: [LOG] Sending CMD_DISCONNECT\n",
|
||||
(unsigned long long)get_timestamp_ms());
|
||||
}
|
||||
|
||||
send(client->sock, (const char*)&hdr, sizeof(hdr), 0);
|
||||
}
|
||||
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [LOG] Connection closed\n",
|
||||
(unsigned long long)get_timestamp_ms());
|
||||
@@ -228,6 +327,13 @@ void etcpmon_client_disconnect(struct etcpmon_client* client) {
|
||||
|
||||
client->connected = 0;
|
||||
client->fully_connected = 0;
|
||||
while (client->tx_head) {
|
||||
struct etcpmon_tx_frame* frame = client->tx_head;
|
||||
client->tx_head = frame->next;
|
||||
free(frame);
|
||||
}
|
||||
client->tx_tail = NULL; client->tx_count = 0; client->tx_bytes = 0;
|
||||
client->tx_blocked = 0; client->tx_progress_at = 0; client->connect_started_at = 0;
|
||||
client->recv_len = 0;
|
||||
client->selected_peer_id = 0;
|
||||
client->last_metrics_request_ms = 0;
|
||||
@@ -262,60 +368,12 @@ int etcpmon_client_is_connected(const struct etcpmon_client* client) {
|
||||
}
|
||||
|
||||
int etcpmon_client_request_list(struct etcpmon_client* client) {
|
||||
if (!client || client->sock == INVALID_SOCKET) return -1;
|
||||
|
||||
struct etcpmon_msg_header hdr;
|
||||
etcpmon_build_header(&hdr, 0, ETCPMON_CMD_LIST_CONN, 0); /* seq=0 = legacy режим */
|
||||
|
||||
if (client->log_file) {
|
||||
log_hex_data(client->log_file, "TX", (const uint8_t*)&hdr, sizeof(hdr));
|
||||
fprintf(client->log_file, "%llu: [LOG] CMD_LIST_CONN (seq=0)\n",
|
||||
(unsigned long long)get_timestamp_ms());
|
||||
fflush(client->log_file);
|
||||
}
|
||||
|
||||
int sent = send(client->sock, (const char*)&hdr, sizeof(hdr), 0);
|
||||
if (sent != sizeof(hdr)) {
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [ERROR] Failed to send CMD_LIST_CONN: %d\n",
|
||||
(unsigned long long)get_timestamp_ms(), WSAGetLastError());
|
||||
fflush(client->log_file);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
return send_message(client, ETCPMON_CMD_LIST_CONN, NULL, 0, NULL);
|
||||
}
|
||||
|
||||
int etcpmon_client_select_connection(struct etcpmon_client* client, uint64_t peer_node_id) {
|
||||
if (!client || client->sock == INVALID_SOCKET) return -1;
|
||||
|
||||
/* SELECT is special - it's not a request/response, it just sets state
|
||||
* So we send with seq_id=0 (broadcast) */
|
||||
uint8_t buffer[sizeof(struct etcpmon_msg_header) + sizeof(struct etcpmon_cmd_select)];
|
||||
struct etcpmon_msg_header* hdr = (struct etcpmon_msg_header*)buffer;
|
||||
struct etcpmon_cmd_select* cmd = (struct etcpmon_cmd_select*)(buffer + sizeof(*hdr));
|
||||
|
||||
etcpmon_build_header(hdr, sizeof(*cmd), ETCPMON_CMD_SELECT_CONN, 0); /* seq_id=0 for SELECT */
|
||||
cmd->peer_node_id = peer_node_id;
|
||||
|
||||
if (client->log_file) {
|
||||
log_hex_data(client->log_file, "TX", buffer, sizeof(buffer));
|
||||
fprintf(client->log_file, "%llu: [LOG] CMD_SELECT_CONN peer_id=%016llX\n",
|
||||
(unsigned long long)get_timestamp_ms(), (unsigned long long)peer_node_id);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
|
||||
int sent = send(client->sock, (const char*)buffer, sizeof(buffer), 0);
|
||||
if (sent != sizeof(buffer)) {
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [ERROR] Failed to send CMD_SELECT_CONN: %d\n",
|
||||
(unsigned long long)get_timestamp_ms(), WSAGetLastError());
|
||||
fflush(client->log_file);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct etcpmon_cmd_select command = {peer_node_id};
|
||||
if (send_message(client, ETCPMON_CMD_SELECT_CONN, &command, sizeof(command), NULL) < 0) return -1;
|
||||
client->selected_peer_id = peer_node_id;
|
||||
client->last_metrics_request_ms = 0;
|
||||
memset(&client->history, 0, sizeof(client->history));
|
||||
@@ -323,55 +381,11 @@ int etcpmon_client_select_connection(struct etcpmon_client* client, uint64_t pee
|
||||
}
|
||||
|
||||
int etcpmon_client_request_socket_list(struct etcpmon_client* client) {
|
||||
if (!client || client->sock == INVALID_SOCKET) return -1;
|
||||
|
||||
struct etcpmon_msg_header hdr;
|
||||
etcpmon_build_header(&hdr, 0, ETCPMON_CMD_LIST_SOCKETS, 0);
|
||||
|
||||
if (client->log_file) {
|
||||
log_hex_data(client->log_file, "TX", (const uint8_t*)&hdr, sizeof(hdr));
|
||||
fprintf(client->log_file, "%llu: [LOG] CMD_LIST_SOCKETS (seq=0)\n",
|
||||
(unsigned long long)get_timestamp_ms());
|
||||
fflush(client->log_file);
|
||||
}
|
||||
|
||||
int sent = send(client->sock, (const char*)&hdr, sizeof(hdr), 0);
|
||||
if (sent != sizeof(hdr)) {
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [ERROR] Failed to send CMD_LIST_SOCKETS: %d\n",
|
||||
(unsigned long long)get_timestamp_ms(), WSAGetLastError());
|
||||
fflush(client->log_file);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
return send_message(client, ETCPMON_CMD_LIST_SOCKETS, NULL, 0, NULL);
|
||||
}
|
||||
|
||||
int etcpmon_client_request_metrics(struct etcpmon_client* client) {
|
||||
if (!client || client->sock == INVALID_SOCKET) return -1;
|
||||
|
||||
struct etcpmon_msg_header hdr;
|
||||
etcpmon_build_header(&hdr, 0, ETCPMON_CMD_GET_METRICS, 0);
|
||||
|
||||
if (client->log_file) {
|
||||
log_hex_data(client->log_file, "TX", (const uint8_t*)&hdr, sizeof(hdr));
|
||||
fprintf(client->log_file, "%llu: [LOG] CMD_GET_METRICS\n",
|
||||
(unsigned long long)get_timestamp_ms());
|
||||
fflush(client->log_file);
|
||||
}
|
||||
|
||||
int sent = send(client->sock, (const char*)&hdr, sizeof(hdr), 0);
|
||||
if (sent != sizeof(hdr)) {
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [ERROR] Failed to send CMD_GET_METRICS: %d\n",
|
||||
(unsigned long long)get_timestamp_ms(), WSAGetLastError());
|
||||
fflush(client->log_file);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
return send_message(client, ETCPMON_CMD_GET_METRICS, NULL, 0, NULL);
|
||||
}
|
||||
|
||||
static void action_auto_callback(void* arg, uint8_t msg_type, const uint8_t* payload, uint16_t payload_size) {
|
||||
@@ -393,93 +407,33 @@ int etcpmon_client_send_action(struct etcpmon_client* client, const char* action
|
||||
|
||||
/* Send request with callback - queued version */
|
||||
int etcpmon_client_send_request(struct etcpmon_client* client,
|
||||
uint8_t type,
|
||||
const void* payload, uint16_t payload_size,
|
||||
void (*callback)(void* arg, uint8_t msg_type, const uint8_t* payload, uint16_t payload_size),
|
||||
void* arg) {
|
||||
if (!client || client->sock == INVALID_SOCKET || !callback) return -1;
|
||||
if (payload_size > ETCPMON_MAX_MSG_SIZE - sizeof(struct etcpmon_msg_header) || (payload_size && !payload)) {
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [ERROR] Invalid request payload: type=0x%02X size=%u\n",
|
||||
(unsigned long long)get_timestamp_ms(), type, payload_size);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
uint8_t type, const void* payload, uint16_t payload_size,
|
||||
void (*callback)(void*, uint8_t, const uint8_t*, uint16_t), void* arg) {
|
||||
if (!client || !callback) {
|
||||
fprintf(stderr, "[ERROR] Invalid request owner/callback: type=0x%02X\n", type);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Не переиспользуем seq_id ещё ожидающего ответа запроса. */
|
||||
int attempts = 0;
|
||||
while (find_pending_request(client, client->next_seq_id) && attempts++ < 255) {
|
||||
if (++client->next_seq_id == 0) client->next_seq_id = 1;
|
||||
}
|
||||
if (attempts >= 255) {
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [ERROR] All request sequence IDs are in use\n",
|
||||
(unsigned long long)get_timestamp_ms());
|
||||
fflush(client->log_file);
|
||||
}
|
||||
FILE* log = client->log_file ? client->log_file : stderr;
|
||||
fprintf(log, "[ERROR] All request sequence IDs are in use\n");
|
||||
fflush(log);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Allocate pending request */
|
||||
struct etcpmon_pending_request* req = (struct etcpmon_pending_request*)malloc(sizeof(*req));
|
||||
struct etcpmon_pending_request* req = calloc(1, sizeof(*req));
|
||||
if (!req) {
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [ERROR] Failed to allocate pending request\n",
|
||||
(unsigned long long)get_timestamp_ms());
|
||||
fflush(client->log_file);
|
||||
}
|
||||
FILE* log = client->log_file ? client->log_file : stderr;
|
||||
fprintf(log, "[ERROR] Pending request allocation failed: type=0x%02X\n", type);
|
||||
fflush(log);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Assign sequence ID */
|
||||
req->seq_id = client->next_seq_id++;
|
||||
if (client->next_seq_id == 0) client->next_seq_id = 1; /* Skip 0 (broadcast) */
|
||||
req->callback = callback;
|
||||
req->arg = arg;
|
||||
req->type = type;
|
||||
req->sent_at = GetTickCount();
|
||||
req->next = NULL;
|
||||
|
||||
/* Build message with seq_id */
|
||||
uint8_t buffer[ETCPMON_MAX_MSG_SIZE];
|
||||
|
||||
struct etcpmon_msg_header* hdr = (struct etcpmon_msg_header*)buffer;
|
||||
etcpmon_build_header(hdr, payload_size, type, req->seq_id);
|
||||
|
||||
if (payload && payload_size > 0) {
|
||||
memcpy(buffer + sizeof(*hdr), payload, payload_size);
|
||||
}
|
||||
|
||||
uint16_t total_size = sizeof(*hdr) + payload_size;
|
||||
|
||||
if (client->log_file) {
|
||||
log_hex_data(client->log_file, "TX", buffer, total_size);
|
||||
fprintf(client->log_file, "%llu: [LOG] CMD 0x%02X seq=%d queued\n",
|
||||
(unsigned long long)get_timestamp_ms(), type, req->seq_id);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
|
||||
int sent = send(client->sock, (const char*)buffer, total_size, 0);
|
||||
if (sent != total_size) {
|
||||
free(req);
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [ERROR] Failed to send request: type=0x%02X sent=%d/%u error=%d\n",
|
||||
(unsigned long long)get_timestamp_ms(), type, sent, total_size, sent == SOCKET_ERROR ? WSAGetLastError() : 0);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
/* После частичной отправки следующий пакет уже нельзя писать в этот поток. */
|
||||
etcpmon_client_disconnect(client);
|
||||
if (client->on_disconnected) client->on_disconnected(client->user_data);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* В очередь попадает только полностью отправленный запрос. */
|
||||
if (client->pending_tail) client->pending_tail->next = req;
|
||||
else client->pending_head = req;
|
||||
client->pending_tail = req;
|
||||
|
||||
return 0;
|
||||
if (!client->next_seq_id) client->next_seq_id = 1;
|
||||
req->callback = callback; req->arg = arg; req->type = type;
|
||||
return send_message(client, type, payload, payload_size, req);
|
||||
}
|
||||
|
||||
static void handle_response(struct etcpmon_client* client, uint8_t msg_type,
|
||||
@@ -733,19 +687,78 @@ static void remove_pending_request(struct etcpmon_client* client, struct etcpmon
|
||||
}
|
||||
|
||||
/* Handle response - find matching request and call callback */
|
||||
/* Полный payload проверяется до снятия pending и любых пользовательских callbacks. */
|
||||
static int valid_response(uint8_t type, const uint8_t* payload, uint16_t size) {
|
||||
switch (type) {
|
||||
case ETCPMON_RSP_CONN_LIST:
|
||||
return size >= 1 && payload[0] <= ETCPMON_MAX_CONNECTIONS &&
|
||||
size == 1 + payload[0] * sizeof(struct etcpmon_conn_info);
|
||||
case ETCPMON_RSP_SOCKET_LIST:
|
||||
return size >= 1 && payload[0] <= ETCPMON_MAX_CONNECTIONS &&
|
||||
size == 1 + payload[0] * sizeof(struct etcpmon_socket_info);
|
||||
case ETCPMON_RSP_METRICS: {
|
||||
if (size < sizeof(struct etcpmon_rsp_metrics)) return 0;
|
||||
const struct etcpmon_rsp_metrics* metrics = (const void*)payload;
|
||||
return metrics->etcp.links_count <= ETCPMON_MAX_LINKS &&
|
||||
size == sizeof(*metrics) + metrics->etcp.links_count * sizeof(struct etcpmon_link_metrics);
|
||||
}
|
||||
case ETCPMON_RSP_ERROR:
|
||||
case ETCPMON_RSP_ACTION_RESULT:
|
||||
return size >= 2 && memchr(payload + 1, 0, size - 1) != NULL;
|
||||
case ETCPMON_RSP_DEBUG_CONFIG: {
|
||||
const uint8_t* end = size > 2 ? memchr(payload + 2, 0, size - 2) : NULL;
|
||||
if (!end || payload[0] > 5 || payload[1] > ETCPMON_MAX_DEBUG_CATEGORIES ||
|
||||
(size_t)(end - payload) + 1 + payload[1] != size) return 0;
|
||||
unsigned names = end == payload + 2 ? 0 : 1;
|
||||
for (const uint8_t* p = payload + 2; p < end; p++) if (*p == ',') names++;
|
||||
return names == payload[1];
|
||||
}
|
||||
case ETCPMON_RSP_NODE_INFO: return size >= 2 && payload[0] == 1 && payload[1] == 4;
|
||||
case ETCPMON_RSP_NODE_INFO_END: return size == 0;
|
||||
case ETCPMON_RSP_NODE_REMOVED: return size == sizeof(uint64_t);
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Тип успешного ответа; RSP_ERROR завершает любой запрос. */
|
||||
static uint8_t expected_response(uint8_t type) {
|
||||
switch (type) {
|
||||
case ETCPMON_CMD_LIST_CONN: return ETCPMON_RSP_CONN_LIST;
|
||||
case ETCPMON_CMD_GET_METRICS: return ETCPMON_RSP_METRICS;
|
||||
case ETCPMON_CMD_LIST_SOCKETS: return ETCPMON_RSP_SOCKET_LIST;
|
||||
case ETCPMON_CMD_ACTION: return ETCPMON_RSP_ACTION_RESULT;
|
||||
case ETCPMON_CMD_GET_DEBUG_CONFIG: return ETCPMON_RSP_DEBUG_CONFIG;
|
||||
case ETCPMON_CMD_SUBSCRIBE_NODES: return ETCPMON_RSP_NODE_INFO_END;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static void handle_response_with_callback(struct etcpmon_client* client, uint8_t msg_type,
|
||||
const uint8_t* payload, uint16_t payload_size) {
|
||||
uint8_t seq_id = client->last_response_seq_id;
|
||||
if (!valid_response(msg_type, payload, payload_size)) {
|
||||
if (client->log_file) fprintf(client->log_file, "[ERROR] Invalid response: type=0x%02X seq=%u size=%u\n",
|
||||
msg_type, seq_id, payload_size);
|
||||
client_fail(client, "Invalid response payload", 0);
|
||||
return;
|
||||
}
|
||||
|
||||
/* Find pending request */
|
||||
struct etcpmon_pending_request* req = find_pending_request(client, seq_id);
|
||||
|
||||
if (req) {
|
||||
if (!req->sent || (msg_type != ETCPMON_RSP_ERROR && msg_type != expected_response(req->type))) {
|
||||
if (client->log_file) fprintf(client->log_file, "[ERROR] Response mismatch: command=0x%02X response=0x%02X seq=%u sent=%u\n",
|
||||
req->type, msg_type, seq_id, req->sent);
|
||||
client_fail(client, "Response does not match request", 0);
|
||||
return;
|
||||
}
|
||||
/* Callback может отправить новый запрос или отключить клиент. */
|
||||
void (*callback)(void*, uint8_t, const uint8_t*, uint16_t) = req->callback;
|
||||
void* arg = req->arg;
|
||||
remove_pending_request(client, req);
|
||||
if (callback) callback(arg, msg_type, payload, payload_size);
|
||||
if (!client->connected) return;
|
||||
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [LOG] Response handled, seq=%d removed from queue\n",
|
||||
@@ -753,6 +766,13 @@ static void handle_response_with_callback(struct etcpmon_client* client, uint8_t
|
||||
fflush(client->log_file);
|
||||
}
|
||||
} else {
|
||||
if (seq_id) {
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "[WARN] Ignoring response without pending: type=0x%02X seq=%u\n", msg_type, seq_id);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
return;
|
||||
}
|
||||
/* No pending request - maybe broadcast/unsolicited or stale */
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [LOG] Response seq=%d - no pending request (broadcast?)\n",
|
||||
@@ -781,178 +801,79 @@ static void metrics_auto_callback(void* arg, uint8_t msg_type, const uint8_t* pa
|
||||
|
||||
int etcpmon_client_process(struct etcpmon_client* client) {
|
||||
if (!client || client->sock == INVALID_SOCKET) return -1;
|
||||
|
||||
/* Проверка завершения non-blocking connect */
|
||||
if (client->connected && !client->fully_connected) {
|
||||
if (!client->fully_connected) {
|
||||
if (GetTickCount() - client->connect_started_at >= REQUEST_TIMEOUT_MS)
|
||||
return client_fail(client, "Connect timeout", WSAETIMEDOUT);
|
||||
fd_set writable, failed;
|
||||
FD_ZERO(&writable);
|
||||
FD_ZERO(&failed);
|
||||
FD_SET(client->sock, &writable);
|
||||
FD_SET(client->sock, &failed);
|
||||
FD_ZERO(&writable); FD_ZERO(&failed);
|
||||
FD_SET(client->sock, &writable); FD_SET(client->sock, &failed);
|
||||
struct timeval timeout = {0, 0};
|
||||
int ready = select(0, NULL, &writable, &failed, &timeout);
|
||||
if (ready == 0) return 0;
|
||||
int error = 0;
|
||||
int len = sizeof(error);
|
||||
if (ready > 0 && getsockopt(client->sock, SOL_SOCKET, SO_ERROR, (char*)&error, &len) == 0) {
|
||||
if (error == 0) {
|
||||
client->fully_connected = 1;
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [LOG] Connection established\n",
|
||||
(unsigned long long)get_timestamp_ms());
|
||||
fflush(client->log_file);
|
||||
}
|
||||
if (client->on_connected) {
|
||||
client->on_connected(client->user_data);
|
||||
}
|
||||
return 0;
|
||||
} else if (error == WSAEINPROGRESS || error == WSAEALREADY) {
|
||||
return 0;
|
||||
} else {
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [ERROR] Connect failed: %d\n",
|
||||
(unsigned long long)get_timestamp_ms(), error);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
etcpmon_client_disconnect(client);
|
||||
if (client->on_disconnected) client->on_disconnected(client->user_data);
|
||||
if (client->on_error) {
|
||||
char msg[256];
|
||||
snprintf(msg, sizeof(msg), "Connect failed: %d", error);
|
||||
client->on_error(msg, client->user_data);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
if (!ready) return 0;
|
||||
if (ready == SOCKET_ERROR) return client_fail(client, "Connect select failed", WSAGetLastError());
|
||||
int error = 0, len = sizeof(error);
|
||||
if (getsockopt(client->sock, SOL_SOCKET, SO_ERROR, (char*)&error, &len) == SOCKET_ERROR)
|
||||
return client_fail(client, "Connect SO_ERROR failed", WSAGetLastError());
|
||||
if (error == WSAEINPROGRESS || error == WSAEALREADY) return 0;
|
||||
if (error) return client_fail(client, "Connect failed", error);
|
||||
client->fully_connected = 1;
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [ERROR] Failed to check connect completion: %d\n",
|
||||
(unsigned long long)get_timestamp_ms(), WSAGetLastError());
|
||||
fprintf(client->log_file, "%llu: [INFO] Connection established to %s:%u\n",
|
||||
(unsigned long long)get_timestamp_ms(), client->server_addr, client->server_port);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
etcpmon_client_disconnect(client);
|
||||
if (client->on_disconnected) client->on_disconnected(client->user_data);
|
||||
return -1;
|
||||
if (client->on_connected) client->on_connected(client->user_data);
|
||||
return client->connected ? 0 : -1;
|
||||
}
|
||||
if (flush_outgoing(client) < 0) return -1;
|
||||
int space = ETCPMON_MAX_MSG_SIZE - client->recv_len;
|
||||
if (space <= 0) return client_fail(client, "Receive buffer full without a complete frame", 0);
|
||||
uint8_t* input = client->recv_buffer + client->recv_len;
|
||||
int received = recv(client->sock, (char*)input, space, 0);
|
||||
if (received == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
|
||||
return client_fail(client, "TCP recv failed", WSAGetLastError());
|
||||
if (!received) return client_fail(client, "Connection closed by server", 0);
|
||||
if (received > 0) {
|
||||
if (client->log_file) log_hex_data(client->log_file, "RX", input, received);
|
||||
client->recv_len += received;
|
||||
}
|
||||
int processed = 0;
|
||||
while (client->recv_len >= sizeof(struct etcpmon_msg_header)) {
|
||||
struct etcpmon_msg_header* header = (void*)client->recv_buffer;
|
||||
if (etcpmon_validate_header(header) < 0) return client_fail(client, "Invalid TCP frame header", 0);
|
||||
uint16_t size = header->size;
|
||||
if (client->recv_len < size) break;
|
||||
client->last_response_seq_id = header->seq_id;
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "[DEBUG] RX frame: type=0x%02X seq=%u size=%u\n", header->type, header->seq_id, size);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
handle_response_with_callback(client, header->type, client->recv_buffer + sizeof(*header), size - sizeof(*header));
|
||||
if (!client->connected) return -1;
|
||||
client->recv_len -= size;
|
||||
memmove(client->recv_buffer, client->recv_buffer + size, client->recv_len);
|
||||
processed++;
|
||||
}
|
||||
|
||||
/* Один запрос метрик в полёте; зависший сервер не раздувает очередь. */
|
||||
int metrics_pending = 0;
|
||||
DWORD tick = GetTickCount();
|
||||
if (client->tx_head && tick - client->tx_progress_at >= REQUEST_TIMEOUT_MS)
|
||||
return client_fail(client, "TCP TX progress timeout", WSAETIMEDOUT);
|
||||
int metrics_pending = 0;
|
||||
for (struct etcpmon_pending_request* req = client->pending_head; req; req = req->next) {
|
||||
if (tick - req->sent_at >= REQUEST_TIMEOUT_MS) {
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [ERROR] Response timeout: type=0x%02X seq=%u elapsed=%lu ms\n",
|
||||
(unsigned long long)get_timestamp_ms(), req->type, req->seq_id, (unsigned long)(tick - req->sent_at));
|
||||
fflush(client->log_file);
|
||||
}
|
||||
etcpmon_client_disconnect(client);
|
||||
if (client->on_disconnected) client->on_disconnected(client->user_data);
|
||||
return -1;
|
||||
if (req->sent && tick - req->sent_at >= REQUEST_TIMEOUT_MS) {
|
||||
if (client->log_file) fprintf(client->log_file, "[ERROR] Response timeout: type=0x%02X seq=%u elapsed=%lu ms\n",
|
||||
req->type, req->seq_id, (unsigned long)(tick - req->sent_at));
|
||||
return client_fail(client, "Response timeout", WSAETIMEDOUT);
|
||||
}
|
||||
if (req->type == ETCPMON_CMD_GET_METRICS) metrics_pending = 1;
|
||||
}
|
||||
|
||||
/* Авто-запрос метрик каждые 100 мс (асинхронно) */
|
||||
if (client->fully_connected && client->selected_peer_id != 0 && !metrics_pending) {
|
||||
if (client->selected_peer_id && !metrics_pending) {
|
||||
uint64_t now = GetTickCount64();
|
||||
if (now - client->last_metrics_request_ms >= ETCPMON_UPDATE_INTERVAL_MS) {
|
||||
if (etcpmon_client_send_request(client, ETCPMON_CMD_GET_METRICS, NULL, 0, metrics_auto_callback, NULL) != 0) {
|
||||
etcpmon_client_disconnect(client);
|
||||
if (client->on_disconnected) client->on_disconnected(client->user_data);
|
||||
return -1;
|
||||
}
|
||||
if (etcpmon_client_send_request(client, ETCPMON_CMD_GET_METRICS, NULL, 0, metrics_auto_callback, NULL) < 0)
|
||||
return client->connected ? client_fail(client, "Failed to queue metrics request", 0) : -1;
|
||||
client->last_metrics_request_ms = now;
|
||||
}
|
||||
}
|
||||
|
||||
/* Приём данных */
|
||||
uint8_t* buf = client->recv_buffer + client->recv_len;
|
||||
int buf_space = ETCPMON_MAX_MSG_SIZE - client->recv_len;
|
||||
if (buf_space <= 0) {
|
||||
client->recv_len = 0; /* защита от переполнения */
|
||||
buf = client->recv_buffer;
|
||||
buf_space = ETCPMON_MAX_MSG_SIZE;
|
||||
}
|
||||
|
||||
int received = recv(client->sock, (char*)buf, buf_space, 0);
|
||||
|
||||
if (received == SOCKET_ERROR) {
|
||||
int err = WSAGetLastError();
|
||||
if (err == WSAEWOULDBLOCK) return 0;
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [ERROR] recv failed: %d\n",
|
||||
(unsigned long long)get_timestamp_ms(), err);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
etcpmon_client_disconnect(client);
|
||||
if (client->on_disconnected) client->on_disconnected(client->user_data);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (received == 0) {
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [LOG] Connection closed by server\n",
|
||||
(unsigned long long)get_timestamp_ms());
|
||||
fflush(client->log_file);
|
||||
}
|
||||
etcpmon_client_disconnect(client);
|
||||
if (client->on_disconnected) client->on_disconnected(client->user_data);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [LOG] Received %d bytes (offset=%d)\n",
|
||||
(unsigned long long)get_timestamp_ms(), received, client->recv_len);
|
||||
log_hex_data(client->log_file, "RX", buf, received);
|
||||
}
|
||||
|
||||
client->recv_len += received;
|
||||
|
||||
/* === ОСНОВНОЙ ПАРСЕР (ИСПРАВЛЕННЫЙ) === */
|
||||
int processed = 0;
|
||||
while (client->recv_len >= sizeof(struct etcpmon_msg_header)) {
|
||||
struct etcpmon_msg_header* hdr = (struct etcpmon_msg_header*)client->recv_buffer;
|
||||
|
||||
/* Валидация */
|
||||
if (etcpmon_validate_header(hdr) != 0) {
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [ERROR] Invalid header, skipping byte %02X\n",
|
||||
(unsigned long long)get_timestamp_ms(), client->recv_buffer[0]);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
memmove(client->recv_buffer, client->recv_buffer + 1, client->recv_len - 1);
|
||||
client->recv_len--;
|
||||
continue;
|
||||
}
|
||||
|
||||
/* hdr->size — это ПОЛНЫЙ размер сообщения (header + payload) */
|
||||
uint16_t total_size = hdr->size;
|
||||
if (client->recv_len < total_size) {
|
||||
break; /* ждём остаток */
|
||||
}
|
||||
|
||||
uint16_t payload_size = total_size - sizeof(*hdr);
|
||||
uint8_t* payload = client->recv_buffer + sizeof(*hdr);
|
||||
|
||||
client->last_response_seq_id = hdr->seq_id;
|
||||
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [LOG] Parsed message type=0x%02X total=%d payload=%d seq=%d\n",
|
||||
(unsigned long long)get_timestamp_ms(), hdr->type, total_size, payload_size, hdr->seq_id);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
|
||||
handle_response_with_callback(client, hdr->type, payload, payload_size);
|
||||
if (!client->connected) return -1;
|
||||
processed++;
|
||||
|
||||
/* Удаляем обработанное сообщение */
|
||||
if (client->recv_len > total_size) {
|
||||
memmove(client->recv_buffer, client->recv_buffer + total_size,
|
||||
client->recv_len - total_size);
|
||||
}
|
||||
client->recv_len -= total_size;
|
||||
}
|
||||
|
||||
return processed;
|
||||
}
|
||||
|
||||
@@ -1007,39 +928,16 @@ int etcpmon_client_request_debug_config(struct etcpmon_client* client) {
|
||||
|
||||
int etcpmon_client_send_debug_config(struct etcpmon_client* client,
|
||||
uint8_t global_level, uint8_t count, const uint8_t* levels) {
|
||||
if (!client || client->sock == INVALID_SOCKET || !levels || count == 0 || count > ETCPMON_MAX_DEBUG_CATEGORIES) return -1;
|
||||
|
||||
uint8_t payload[2 + ETCPMON_MAX_DEBUG_CATEGORIES];
|
||||
payload[0] = global_level;
|
||||
payload[1] = count;
|
||||
memcpy(payload + 2, levels, count);
|
||||
uint16_t payload_size = 2 + count;
|
||||
|
||||
uint8_t buffer[sizeof(struct etcpmon_msg_header) + sizeof(payload)];
|
||||
struct etcpmon_msg_header* hdr = (struct etcpmon_msg_header*)buffer;
|
||||
etcpmon_build_header(hdr, payload_size, ETCPMON_CMD_SET_DEBUG_CONFIG, 0);
|
||||
memcpy(buffer + sizeof(*hdr), payload, payload_size);
|
||||
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "%llu: [LOG] CMD_SET_DEBUG_CONFIG global=%d count=%d\n",
|
||||
(unsigned long long)get_timestamp_ms(), global_level, count);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
|
||||
int total_size = sizeof(*hdr) + payload_size;
|
||||
int sent = send(client->sock, (const char*)buffer, total_size, 0);
|
||||
if (sent != total_size) {
|
||||
if (client->log_file) {
|
||||
fprintf(client->log_file, "[ERROR] Failed to send debug config: sent=%d/%d error=%d\n",
|
||||
sent, total_size, sent == SOCKET_ERROR ? WSAGetLastError() : 0);
|
||||
fflush(client->log_file);
|
||||
}
|
||||
etcpmon_client_disconnect(client);
|
||||
if (client->on_disconnected) client->on_disconnected(client->user_data);
|
||||
if (!client || !levels || !count || count > ETCPMON_MAX_DEBUG_CATEGORIES || global_level > 5) {
|
||||
fprintf(stderr, "[ERROR] Invalid debug config: global=%u count=%u\n", global_level, count);
|
||||
return -1;
|
||||
}
|
||||
uint8_t payload[2 + ETCPMON_MAX_DEBUG_CATEGORIES];
|
||||
payload[0] = global_level; payload[1] = count;
|
||||
memcpy(payload + 2, levels, count);
|
||||
if (send_message(client, ETCPMON_CMD_SET_DEBUG_CONFIG, payload, 2 + count, NULL) < 0) return -1;
|
||||
client->debug_global_level = global_level;
|
||||
for (uint8_t i = 0; i < count; i++) client->debug_category_levels[i] = levels[i];
|
||||
memcpy(client->debug_category_levels, levels, count);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1048,17 +946,18 @@ void etcpmon_client_add_to_history(struct etcpmon_client* client, struct etcpmon
|
||||
|
||||
struct metrics_history* h = &client->history;
|
||||
int idx = h->head;
|
||||
for (int metric = 0; metric < GRAPH_METRIC_COUNT; metric++) h->values[metric][idx] = 0;
|
||||
|
||||
/* BBR per-link metrics (use first link as representative) */
|
||||
if (client->last_links_count > 0 && client->last_links) {
|
||||
struct etcpmon_link_metrics* l = &client->last_links[0];
|
||||
h->values[GRAPH_METRIC_INFLIGHT_BYTES][idx] = l->inflight_bytes / 1024.f;
|
||||
h->values[GRAPH_METRIC_INFLIGHT_LIM][idx] = l->inflight_lim_bytes / 1024.f;
|
||||
h->values[GRAPH_METRIC_INFLIGHT_BYTES][idx] = (float)l->inflight_bytes;
|
||||
h->values[GRAPH_METRIC_INFLIGHT_LIM][idx] = (float)l->inflight_lim_bytes;
|
||||
h->values[GRAPH_METRIC_MIN_RTT][idx] = l->bbr_min_rtt_us / 1000.f;
|
||||
h->values[GRAPH_METRIC_BW_HI][idx] = l->bbr_bw_hi / 125.f;
|
||||
h->values[GRAPH_METRIC_PACING_RATE][idx] = l->bbr_pacing_rate / 125.f;
|
||||
h->values[GRAPH_METRIC_BW_LO][idx] = l->bbr_bw_lo / 125.f;
|
||||
h->values[GRAPH_METRIC_INFLIGHT_HI][idx] = l->bbr_inflight_hi / 1024.f;
|
||||
h->values[GRAPH_METRIC_BW_HI][idx] = (float)l->bbr_bw_hi;
|
||||
h->values[GRAPH_METRIC_PACING_RATE][idx] = (float)l->bbr_pacing_rate;
|
||||
h->values[GRAPH_METRIC_BW_LO][idx] = (float)l->bbr_bw_lo;
|
||||
h->values[GRAPH_METRIC_INFLIGHT_HI][idx] = (float)l->bbr_inflight_hi;
|
||||
h->values[GRAPH_METRIC_BBR_MODE][idx] = (float)l->bbr_mode;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
/*
|
||||
* etcpmon_client.h - ETCP Monitor Client Network Layer
|
||||
*
|
||||
* Handles TCP connection to utun control server
|
||||
* TCP-клиент control_server: init → connect → регулярный process → cleanup.
|
||||
* Все вызовы и callbacks выполняются в одном потоке; Winsock запускает/останавливает вызывающий код.
|
||||
* connect принимает числовой IPv4. connected включает CONNECTING, fully_connected означает готовый TCP.
|
||||
* process завершает connect, принимает кадры и сам запрашивает метрики выбранного пира раз в 100 мс.
|
||||
* Списки и debug config запрашивает вызывающая сторона. TX ограничен 64 КиБ/256 кадрами;
|
||||
* short send/WSAEWOULDBLOCK продолжаются в process с сохранением порядка и смещения.
|
||||
* Pending хранит до 255 запросов. Срок connect, отсутствия прогресса TX и ответа — по 5 секунд;
|
||||
* срок ответа начинается после полной отправки соответствующего кадра.
|
||||
*/
|
||||
|
||||
#ifndef ETCPMON_CLIENT_H
|
||||
@@ -18,6 +23,10 @@ extern "C" {
|
||||
|
||||
/* Graph history size (samples) */
|
||||
#define GRAPH_HISTORY_SIZE 860
|
||||
#define ETCPMON_TX_MAX_BYTES (2u * ETCPMON_MAX_MSG_SIZE)
|
||||
#define ETCPMON_TX_MAX_FRAMES 256
|
||||
|
||||
struct etcpmon_tx_frame;
|
||||
|
||||
/* Graph metrics types */
|
||||
typedef enum {
|
||||
@@ -32,35 +41,42 @@ typedef enum {
|
||||
GRAPH_METRIC_COUNT
|
||||
} graph_metric_type_t;
|
||||
|
||||
/* Metrics history buffer */
|
||||
/* Кольцевая история первого линка: объёмы в байтах, скорости в байтах/с, minRTT в мс, mode безразмерный. */
|
||||
struct metrics_history {
|
||||
float values[GRAPH_METRIC_COUNT][GRAPH_HISTORY_SIZE];
|
||||
float min_val[GRAPH_METRIC_COUNT];
|
||||
float max_val[GRAPH_METRIC_COUNT];
|
||||
DWORD last_minmax_update;
|
||||
int head;
|
||||
int count;
|
||||
int head; /* Индекс следующей записи, 0..GRAPH_HISTORY_SIZE-1 */
|
||||
int count; /* Число заполненных сэмплов, не более GRAPH_HISTORY_SIZE */
|
||||
uint32_t last_retrans;
|
||||
uint32_t last_acks;
|
||||
uint64_t last_bytes_sent;
|
||||
};
|
||||
|
||||
/* Client state */
|
||||
/* Клиент владеет сокетом, логом, кешами и pending. Не копировать активную структуру. */
|
||||
struct etcpmon_client {
|
||||
SOCKET sock;
|
||||
int connected;
|
||||
int fully_connected;
|
||||
SOCKET sock; /* INVALID_SOCKET после init/disconnect */
|
||||
int connected; /* 1 с начала неблокирующего connect */
|
||||
int fully_connected; /* 1 после успешной проверки select/SO_ERROR в process */
|
||||
DWORD connect_started_at; /* Монотонные мс начала connect; срок 5 секунд */
|
||||
struct etcpmon_tx_frame* tx_head; /* FIFO исходящих кадров; client владеет памятью */
|
||||
struct etcpmon_tx_frame* tx_tail;
|
||||
size_t tx_bytes; /* Сумма полных размеров кадров, включая частично отправленную голову */
|
||||
unsigned tx_count; /* Не более ETCPMON_TX_MAX_FRAMES */
|
||||
DWORD tx_progress_at; /* Начало ожидания или последний положительный send */
|
||||
int tx_blocked; /* 1 после WSAEWOULDBLOCK, для логирования переходов */
|
||||
|
||||
/* Receive buffer */
|
||||
uint8_t recv_buffer[ETCPMON_MAX_MSG_SIZE];
|
||||
uint16_t recv_len;
|
||||
uint16_t recv_len; /* Неразобранный хвост TCP-потока; границы recv не являются границами кадров */
|
||||
|
||||
/* Server address */
|
||||
char server_addr[64];
|
||||
uint16_t server_port;
|
||||
|
||||
/* Selected connection */
|
||||
uint64_t selected_peer_id;
|
||||
uint64_t selected_peer_id; /* 0 запрещает автоматический запрос метрик */
|
||||
|
||||
/* Connection info cache */
|
||||
struct etcpmon_conn_info* conn_list;
|
||||
@@ -81,7 +97,7 @@ struct etcpmon_client {
|
||||
/* Metrics history for graph */
|
||||
struct metrics_history history;
|
||||
|
||||
/* Pending requests queue with callbacks */
|
||||
/* Принятые в TX запросы с ненулевым seq_id; disconnect отменяет их без вызова callbacks. */
|
||||
struct etcpmon_pending_request* pending_head;
|
||||
struct etcpmon_pending_request* pending_tail;
|
||||
uint8_t next_seq_id;
|
||||
@@ -96,7 +112,7 @@ struct etcpmon_client {
|
||||
char debug_category_names[512];
|
||||
uint8_t debug_config_dirty;
|
||||
|
||||
/* Callbacks */
|
||||
/* Callbacks вызываются синхронно в потоке вызывающего API; аргументы заимствованы, владение не передаётся. */
|
||||
void (*on_connected)(void* user_data);
|
||||
void (*on_disconnected)(void* user_data);
|
||||
void (*on_conn_list)(struct etcpmon_conn_info* list, uint8_t count, void* user_data);
|
||||
@@ -108,74 +124,76 @@ struct etcpmon_client {
|
||||
void (*on_action_result)(const char* text, void* user_data);
|
||||
|
||||
void* user_data;
|
||||
uint64_t last_metrics_request_ms;
|
||||
uint64_t last_metrics_request_ms; /* GetTickCount64, монотонные мс; 0 после выбора/отключения */
|
||||
};
|
||||
|
||||
/* Pending request with callback */
|
||||
struct etcpmon_pending_request {
|
||||
uint8_t seq_id; /* Sequence ID */
|
||||
uint8_t type; /* Тип команды для ограничения опроса */
|
||||
DWORD sent_at; /* Монотонное время отправки */
|
||||
DWORD sent_at; /* Монотонное время полной отправки; значимо только при sent=1 */
|
||||
uint8_t sent; /* 1 после полной отправки; только тогда идёт таймаут ответа */
|
||||
void (*callback)(void* arg, uint8_t msg_type, const uint8_t* payload, uint16_t payload_size);
|
||||
void* arg; /* User argument for callback */
|
||||
struct etcpmon_pending_request* next;
|
||||
};
|
||||
|
||||
/* Initialize client structure */
|
||||
/* Обнулить неактивную caller-owned структуру client; сокет/лог не открывает. */
|
||||
void etcpmon_client_init(struct etcpmon_client* client);
|
||||
|
||||
/* Cleanup client resources */
|
||||
/* Отключить client и освободить его кеши, pending и лог; сам client и Winsock не освобождает. */
|
||||
void etcpmon_client_cleanup(struct etcpmon_client* client);
|
||||
|
||||
/* Connect to server
|
||||
* Returns 0 on success, -1 on error
|
||||
*/
|
||||
/* Начать connect к числовому IPv4 addr:port. 0 = попытка начата, -1 = немедленная ошибка.
|
||||
* Завершение/таймаут 5 секунд проверяет process; on_connected означает успех.
|
||||
* Уже открытое соединение закрывается. Лог etcpmon.log создаётся при первой попытке в текущем каталоге. */
|
||||
int etcpmon_client_connect(struct etcpmon_client* client, const char* addr, uint16_t port);
|
||||
|
||||
/* Disconnect from server */
|
||||
/* Закрыть сокет client, сбросить выбор/историю/кеши и отменить pending без callbacks.
|
||||
* Лог и кеш debug config сохраняются. Сам disconnect не вызывает on_disconnected. */
|
||||
void etcpmon_client_disconnect(struct etcpmon_client* client);
|
||||
|
||||
/* Check if connected */
|
||||
/* Вернуть connected (также 1 во время CONNECTING), для NULL — 0. */
|
||||
int etcpmon_client_is_connected(const struct etcpmon_client* client);
|
||||
|
||||
/* Request connection list
|
||||
* Returns 0 on success, -1 on error
|
||||
*/
|
||||
/* Поставить LIST_CONN с seq=0 в TX без ожидания ответа. 0 = принят в TX, -1 = ошибка.
|
||||
* Отказ выделения/лимита TX не меняет соединение; фатальная ошибка send отключает его с callbacks. */
|
||||
int etcpmon_client_request_list(struct etcpmon_client* client);
|
||||
|
||||
/* Request local socket list
|
||||
* Returns 0 on success, -1 on error
|
||||
*/
|
||||
/* Поставить LIST_SOCKETS с seq=0 в TX без ожидания ответа; возврат как у request_list. */
|
||||
int etcpmon_client_request_socket_list(struct etcpmon_client* client);
|
||||
|
||||
/* Select connection to monitor
|
||||
* Returns 0 on success, -1 on error
|
||||
*/
|
||||
/* Отправить SELECT_CONN с seq=0, без подтверждения; peer_node_id=0 снимает выбор.
|
||||
* После принятия в TX меняет локальный selected_peer_id и очищает историю.
|
||||
* 0 = принят в TX, -1 = ошибка; существование пира проверит сервер при запросе метрик. */
|
||||
int etcpmon_client_select_connection(struct etcpmon_client* client, uint64_t peer_node_id);
|
||||
|
||||
/* Request metrics for selected connection
|
||||
* Returns 0 on success, -1 on error
|
||||
*/
|
||||
/* Разовый GET_METRICS с seq=0, без ожидания ответа. Обычно достаточно автоопроса в process.
|
||||
* 0 = принят в TX, -1 = ошибка; этот вызов не участвует в ограничении автоопроса. */
|
||||
int etcpmon_client_request_metrics(struct etcpmon_client* client);
|
||||
|
||||
/* Send request with callback
|
||||
* callback will be called when response is received
|
||||
* arg will be passed to callback
|
||||
* Returns 0 on success (queued), -1 on error
|
||||
*/
|
||||
/* Поставить type/payload с уникальным seq=1..255 в ограниченный TX; payload копируется до возврата.
|
||||
* 0 = кадр и pending приняты, -1 = ошибка. Фатальная ошибка send закрывает соединение с callbacks.
|
||||
* Обязательный callback(arg, type, payload, size) вызывается по совпадению seq до общих callbacks;
|
||||
* тип ответа и полный payload проверяются до снятия pending/callback. RSP_ERROR завершает любой запрос.
|
||||
* Payload действителен только во время callback. Неизвестный ненулевой seq игнорируется с WARN.
|
||||
* callback может отправлять запросы или отключить клиент; рекурсивно вызывать process нельзя.
|
||||
* Таймаут 5 с проверяется в process; при отмене/таймауте callback не вызывается. */
|
||||
int etcpmon_client_send_request(struct etcpmon_client* client,
|
||||
uint8_t type,
|
||||
const void* payload, uint16_t payload_size,
|
||||
void (*callback)(void* arg, uint8_t msg_type, const uint8_t* payload, uint16_t payload_size),
|
||||
void* arg);
|
||||
|
||||
/* Process incoming data (non-blocking)
|
||||
* Should be called periodically (e.g., from window message loop)
|
||||
* Returns 1 if data was processed, 0 if no data, -1 on error
|
||||
*/
|
||||
/* Неблокирующий шаг в потоке владельца: connect, досылка TX, одно recv, разбор, таймауты и автоопрос.
|
||||
* Возвращает число разобранных кадров (может быть >1), 0 = полных кадров нет, -1 = ошибка/отключение.
|
||||
* На автоопрос метрик одновременно допускается один pending. Вызывать регулярно, чаще 100 мс.
|
||||
* Фатальная ошибка TCP/протокола или таймаут закрывают соединение и вызывают on_disconnected/on_error. */
|
||||
int etcpmon_client_process(struct etcpmon_client* client);
|
||||
|
||||
/* Set callbacks */
|
||||
/* Установить необязательные общие callbacks и caller-owned user_data.
|
||||
* Списки/метрики принадлежат client до следующей замены кеша/отключения;
|
||||
* строки ошибок/Action действительны только во время callback. */
|
||||
void etcpmon_client_set_callbacks(struct etcpmon_client* client,
|
||||
void (*on_connected)(void*),
|
||||
void (*on_disconnected)(void*),
|
||||
@@ -188,22 +206,30 @@ void etcpmon_client_set_callbacks(struct etcpmon_client* client,
|
||||
void (*on_action_result)(const char*, void*),
|
||||
void* user_data);
|
||||
|
||||
/* Get connection name by peer_id */
|
||||
/* Заимствованное имя peer_id в кеше client до его замены/отключения; NULL, если не найдено. */
|
||||
const char* etcpmon_client_get_conn_name(struct etcpmon_client* client, uint64_t peer_id);
|
||||
|
||||
/* Get metrics history */
|
||||
/* Заимствованная встроенная история client; NULL для NULL client, отдельно не освобождать. */
|
||||
struct metrics_history* etcpmon_client_get_history(struct etcpmon_client* client);
|
||||
|
||||
/* Add metrics to history */
|
||||
/* Добавить сэмпл из client->last_links[0]; metrics должен быть ненулевым.
|
||||
* Вызывается парсером метрик ровно один раз на принятый снимок; GUI повторно не добавляет. */
|
||||
void etcpmon_client_add_to_history(struct etcpmon_client* client, struct etcpmon_rsp_metrics* metrics);
|
||||
|
||||
/* Send action command to server */
|
||||
/* Отправить action (до 31 байта + NUL) как запрос с pending; возврат как у send_request.
|
||||
* Успех передаётся on_action_result, ошибка команды — on_error без отключения TCP.
|
||||
* "nat" подтверждает запуск проверки, "nodes" возвращает текстовый дамп. */
|
||||
int etcpmon_client_send_action(struct etcpmon_client* client, const char* action);
|
||||
|
||||
/* Запрос debug config с pending; 0 = принят в TX, -1 = ошибка. Кеш обновляет process. */
|
||||
int etcpmon_client_request_debug_config(struct etcpmon_client* client);
|
||||
/* Отправить SET_DEBUG_CONFIG с seq=0 без подтверждения: count=1..64, levels[count].
|
||||
* 0 = принят в TX и локальные уровни обновлены; -1 = ошибка.
|
||||
* Категории следуют порядку имён из ответа GET_DEBUG_CONFIG; GUI поддерживает уровни 0..5. */
|
||||
int etcpmon_client_send_debug_config(struct etcpmon_client* client, uint8_t global_level, uint8_t count, const uint8_t* levels);
|
||||
|
||||
uint64_t get_timestamp_ms(void); // Add this declaration
|
||||
/* Wall-clock мс Unix epoch для лога; для таймаутов не используется. */
|
||||
uint64_t get_timestamp_ms(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
## 1. Назначение
|
||||
|
||||
Windows GUI монитор для ETCP соединений uTun в реальном времени (100ms refresh). Подключается по TCP к control_server внутри uTun и отображает метрики соединений, линков, TUN-интерфейса, роутера и дебаг-уровней. Позволяет менять debug levels на лету через GUI.
|
||||
Windows GUI монитор для ETCP соединений uTun. Подключается по обычному IPv4 TCP к control_server внутри uTun
|
||||
и отображает метрики соединений, линков, TUN, роутера и уровней отладки. Все сетевые вызовы и callbacks
|
||||
выполняются в GUI-потоке: WM_TIMER установлен на 10 мс, автоматический запрос метрик — раз в 100 мс
|
||||
при отсутствии предыдущего запроса в pending. Частота полученных сэмплов зависит от ответов сервера.
|
||||
|
||||
Connections и локальные сокеты опрашиваются раз в секунду, даже при пустом списке соединений.
|
||||
Выбор сохраняется по ID узла при изменении порядка и имён. При удалении выбранного соединения
|
||||
@@ -14,16 +17,28 @@ Connections и локальные сокеты опрашиваются раз
|
||||
|
||||
### Типовой сценарий
|
||||
|
||||
1. В конфиге uTun (`utun.conf`): `control_ip=127.0.0.1`, `control_port=9090`
|
||||
1. В конфиге uTun настроить `[control]` (без `allow` сервер отклоняет все подключения):
|
||||
|
||||
```ini
|
||||
[control]
|
||||
ip=127.0.0.1
|
||||
port=9090
|
||||
allow=127.0.0.1/32
|
||||
```
|
||||
2. Запустить uTun → он поднимает TCP control server на указанном порту
|
||||
3. Запустить `etcpmon.exe` (Windows, MinGW/MSYS2 сборка)
|
||||
4. Ввести IP:порт сервера (по умолчанию `192.168.40.1:9091`), нажать Connect
|
||||
5. Выбрать соединение из списка Connections — начнут поступать метрики
|
||||
4. Ввести числовой IPv4 и порт сервера, нажать Connect. При создании окна уже начинается попытка
|
||||
подключения к `192.168.40.1:9091`; для смены адреса сначала нажать Disconnect.
|
||||
5. Первое доступное соединение выбирается автоматически; другое можно выбрать в Connections.
|
||||
|
||||
Канал управления не шифруется и не проверяет ключи ETCP; `allow` фильтрует только IPv4 источника.
|
||||
Для удалённого управления требуется доверенный защищённый канал. DNS-имена и IPv6 клиент не принимает.
|
||||
|
||||
### Что отображает
|
||||
|
||||
**ETCP Connection:**
|
||||
- RTT (last / avg10 / avg100, в 0.1ms), jitter, bytes sent, retransmissions, ACKs, unacked bytes, optimal inflight, links count
|
||||
- RTT last / avg10 и jitter (wire: 0.1 мс, GUI: мс), bytes sent, retransmissions, ACKs, unacked bytes, optimal inflight, links count
|
||||
- Поле RTT Avg100 в окне есть, но соответствующего значения в протоколе нет: оно не заполняется
|
||||
- RX/TX дубликаты, таймеры (retrans/ack_resp), WaitAck состояние (suspended/cb/timer)
|
||||
- ID Sequence: next_tx_id, last_rx_id, last_delivered_id, rx_ack_till
|
||||
- Счётчики ошибок: reinit, reset, pkt_format_errors
|
||||
@@ -36,7 +51,7 @@ Connections и локальные сокеты опрашиваются раз
|
||||
**Links:**
|
||||
- Статус (UP/DOWN), encrypt/decrypt/send/recv ошибки
|
||||
- Total encrypted/decrypted bytes, bandwidth (Kbps), NAT changes
|
||||
- RTT (last/avg10), transmit time, keepalive counters (sent/recv)
|
||||
- RTT last, поле с подписью avg10 (фактически BBR minRTT, 0 без BBR), transmit time, keepalive counters (sent/recv)
|
||||
- Inflight bytes/packets/limit, таймеры (init/keepalive/shaper)
|
||||
|
||||
**BBR per link:**
|
||||
@@ -44,13 +59,13 @@ Connections и локальные сокеты опрашиваются раз
|
||||
- pacing_rate (bytes/sec), min_rtt (us), bw_hi/bw_lo (bytes/sec), inflight_hi/lo, pacing_gain
|
||||
|
||||
**Router Congestion (агрегированные):**
|
||||
- total_conns, total_inflight, total_send_q, total_recv_q
|
||||
- total_conns, total_inflight, total_send_q, total_recv_q (счётчики записей очередей, не байтов)
|
||||
- pkts sent/recv, send err, ACK sent/recv, dup_dropped, oob_dropped, stale_ack, sign_fail
|
||||
- RTT max/avg, jitter max, minRTT min
|
||||
|
||||
**Графики BBR (scrolling canvas, 860 сэмплов, 1px=1sample):**
|
||||
- Inflight Bytes, Cwnd (inflight_lim), minRTT, bwHi, Pacing Rate, bwLo, inflight Hi, BBR Mode
|
||||
- 8 каналов с индивидуальными галочками включения
|
||||
- История первого линка, до 860 сэмплов; если галочек нет, отображаются первые четыре канала
|
||||
- Вертикальная линия курсора с показом значений в блоках под графиком
|
||||
|
||||
**Очереди (Queues & Errors):**
|
||||
@@ -65,8 +80,11 @@ Connections и локальные сокеты опрашиваются раз
|
||||
- Radio-кнопки отправляют CMD_SET_DEBUG_CONFIG на сервер при клике
|
||||
|
||||
**Action:**
|
||||
- Текстовое поле + кнопка Send — отправка произвольной команды (CMD_ACTION)
|
||||
- Результат открывается в отдельном окне с моноширинным шрифтом Consolas
|
||||
- Текстовое поле + кнопка Send отправляют CMD_ACTION (до 31 байта текста + NUL)
|
||||
- Сервер распознаёт префиксы `nodes` (текстовый дамп узлов) и `nat` (перезапуск NAT/STUN-проверок)
|
||||
- `nodes` возвращает текст в отдельное окно Consolas, `nat` — подтверждение запуска проверки
|
||||
- Имена сравниваются целиком. Неизвестная команда или недоступная служба возвращают `RSP_ERROR`
|
||||
с исходным seq; GUI показывает ошибку и сохраняет TCP-соединение
|
||||
|
||||
### Сборка
|
||||
|
||||
@@ -80,12 +98,20 @@ make # MinGW Makefile
|
||||
make check # WinAPI/Winsock регрессии списка, выбора и переподключения
|
||||
```
|
||||
|
||||
На Linux с MinGW и Wine из каталога `tools/etcpmon`:
|
||||
|
||||
```bash
|
||||
CC=x86_64-w64-mingw32-gcc bash build.sh
|
||||
make CC=x86_64-w64-mingw32-gcc TEST_RUNNER=wine check
|
||||
wine etcpmon.exe
|
||||
```
|
||||
|
||||
Серверная часть (control_server) встроена в utun, собирается стандартным `./configure && make`.
|
||||
|
||||
### Горячие клавиши
|
||||
|
||||
- Tab в поле Server/Port — переключение между полями
|
||||
- Enter в поле Server/Port — Connect/Disconnect
|
||||
- Enter в поле Server/Port — Connect, если отключён; Escape — Disconnect
|
||||
- Enter в поле Action — отправка команды
|
||||
|
||||
## 3. API / Структура
|
||||
@@ -96,7 +122,7 @@ make check # WinAPI/Winsock регрессии списка, выбор
|
||||
|------|-----------|
|
||||
| `etcpmon_main.c` | WinMain: инициализация GUI, создание окна, message loop |
|
||||
| `etcpmon_client.h/c` | TCP клиент (Winsock2): connect, send/recv, парсинг протокола, history, pending requests с коллбэками |
|
||||
| `etcpmon_gui.h/c` | WinAPI GUI: окно 1000×1400, все контролы (~200 edit-полей, списки, кнопки, radio, graph), тултипы |
|
||||
| `etcpmon_gui.h/c` | WinAPI GUI: заданный размер окна 1250×1400, контролы, таймер, callbacks, тултипы |
|
||||
| `etcpmon_graph.h/c` | Real-time график: 8 каналов, off-screen буфер, пересчёт min/max, курсор, обновление channel values |
|
||||
| `etcpmon_protocol.h` | Бинарный протокол, общие структуры, shared между клиентом и сервером |
|
||||
|
||||
@@ -104,6 +130,13 @@ make check # WinAPI/Winsock регрессии списка, выбор
|
||||
|
||||
Формат: `[size:2][type:1][seq_id:1][payload...]`
|
||||
|
||||
`size` включает 4-байтовый заголовок, диапазон 4..32768. Все структуры packed(1), целые передаются
|
||||
в порядке байтов хоста. Константа VERSION=3 не передаётся по сети: клиенту и серверу нужны одинаковые
|
||||
форматы структур и порядок байтов. TCP-чтение может содержать часть кадра или несколько кадров.
|
||||
`seq=0` не создаёт ожидания в клиенте; `seq=1..255` сопоставляет ответ с pending по одному номеру.
|
||||
SELECT_CONN, SET_DEBUG_CONFIG и DISCONNECT не подтверждаются. GUI отправляет списки с seq=0,
|
||||
а GET_DEBUG_CONFIG, автоопрос метрик и Action — с ненулевым seq и таймаутом.
|
||||
|
||||
**Клиент → Сервер:**
|
||||
- `0x01` CMD_LIST_CONN — запрос списка соединений (без payload)
|
||||
- `0x02` CMD_SELECT_CONN — выбор соединения: `peer_node_id` (uint64_t)
|
||||
@@ -120,8 +153,25 @@ make check # WinAPI/Winsock регрессии списка, выбор
|
||||
- `0x82` RSP_METRICS: `etcp_metrics + tun_metrics + router_metrics + N × link_metrics`
|
||||
- `0x83` RSP_SOCKET_LIST: `count(1) + N × socket_info`
|
||||
- `0x84` RSP_DEBUG_CONFIG: `global_level(1) + cat_count(1) + names_csv(NUL-term) + levels[N]`
|
||||
- `0x85` RSP_NODE_INFO — один узел (raw BGP_NODEINFO_PACKET)
|
||||
- `0x86` RSP_NODE_INFO_END — конец списка узлов
|
||||
- `0x85` RSP_NODE_INFO — префикс `01 04` + `topo_node_serialize()` для UTUN с подсетями, seq=0
|
||||
- `0x86` RSP_NODE_INFO_END — конец списка узлов с seq запроса подписки
|
||||
- `0x88` RSP_NODE_REMOVED — узел удалён: `node_id(8)`
|
||||
- `0x89` RSP_ACTION_RESULT — результат команды: `code(1) + text(NUL-term)`
|
||||
- `0xFF` RSP_ERROR: `error_code(1) + message(NUL-term)`
|
||||
|
||||
Подписку на узлы поддерживает сервер, но GUI etcpmon её не запрашивает и эти уведомления не отображает.
|
||||
|
||||
### Очереди, таймауты и единицы
|
||||
|
||||
- Все команды клиента копируются в общий TX FIFO (до 64 КиБ/256 кадров). Short send и WSAEWOULDBLOCK
|
||||
сохраняют смещение для следующего прохода. Переполнение не принимает новую команду и возвращает ошибку.
|
||||
- Pending регистрируется вместе с кадром, срок ответа 5 секунд начинается после его полной отправки.
|
||||
Тип и payload ответа проверяются до снятия pending/callback; `RSP_ERROR` завершает любой запрос.
|
||||
- Connect и отсутствие прогресса TX также ограничены 5 секундами. Ответы на списки с seq=0 отдельно
|
||||
не отслеживаются; EOF/фатальная ошибка/таймаут закрывают соединение с диагностикой.
|
||||
- Сервер держит один готовый кадр до 32 КиБ. Чтение и разбор запросов ждут его отправки через
|
||||
отменяемый deferred waiter. Для начального списка узлов хранятся ID, сериализация выполняется порционно.
|
||||
- Live-изменения UTUN объединяются по ID (до 256); переполнение отключает подписчика с WARN.
|
||||
Серверный таймаут 30 секунд во время TX продлевается только положительным send, иначе — командами.
|
||||
- История хранит байты, байты/с и minRTT в мс. При выводе используются B/KiB/MiB и B/s/KiB/s/MiB/s,
|
||||
включая строки BBR. Сравнение идёт с текстом самого контрола, поэтому очистка/reconnect не скрывают прежние значения.
|
||||
@@ -153,24 +153,24 @@ void UpdateChannelValues(struct etcpmon_app* app, int history_idx)
|
||||
{
|
||||
if (!app || !app->client) return;
|
||||
struct metrics_history* h = etcpmon_client_get_history(app->client);
|
||||
if (!h || history_idx < 0 || history_idx >= GRAPH_HISTORY_SIZE) {
|
||||
if (!h || !h->count || history_idx < 0 || history_idx >= GRAPH_HISTORY_SIZE) {
|
||||
for (int i = 0; i < GRAPH_METRICS_COUNT; i++) {
|
||||
if (app->hChannelValue[i])
|
||||
SetWindowTextA(app->hChannelValue[i], "-");
|
||||
}
|
||||
return;
|
||||
}
|
||||
static char last_text[GRAPH_METRICS_COUNT][32] = {0};
|
||||
for (int i = 0; i < GRAPH_METRICS_COUNT; i++) {
|
||||
if (!app->hChannelValue[i]) continue;
|
||||
float val = h->values[i][history_idx];
|
||||
char buf[32] = {0};
|
||||
if (i == GRAPH_METRIC_BW_HI || i == GRAPH_METRIC_BW_LO || i == GRAPH_METRIC_PACING_RATE) {
|
||||
if (val >= 1024) snprintf(buf, sizeof(buf), "%.1f MB/s", val/1024.);
|
||||
else snprintf(buf, sizeof(buf), "%.1f KB/s", val);
|
||||
if (val >= 1024*1024) snprintf(buf, sizeof(buf), "%.1f MiB/s", val/(1024.*1024.));
|
||||
else if (val >= 1024) snprintf(buf, sizeof(buf), "%.1f KiB/s", val/1024.);
|
||||
else snprintf(buf, sizeof(buf), "%.0f B/s", val);
|
||||
} else if (i == GRAPH_METRIC_INFLIGHT_BYTES || i == GRAPH_METRIC_INFLIGHT_LIM || i == GRAPH_METRIC_INFLIGHT_HI) {
|
||||
if (val >= 1024*1024) snprintf(buf, sizeof(buf), "%.1f MB", val/(1024.*1024.));
|
||||
else if (val >= 1024) snprintf(buf, sizeof(buf), "%.1f KB", val/1024.);
|
||||
if (val >= 1024*1024) snprintf(buf, sizeof(buf), "%.1f MiB", val/(1024.*1024.));
|
||||
else if (val >= 1024) snprintf(buf, sizeof(buf), "%.1f KiB", val/1024.);
|
||||
else snprintf(buf, sizeof(buf), "%.0f B", val);
|
||||
} else if (i == GRAPH_METRIC_MIN_RTT) {
|
||||
snprintf(buf, sizeof(buf), "%.1f ms", val);
|
||||
@@ -181,9 +181,9 @@ void UpdateChannelValues(struct etcpmon_app* app, int history_idx)
|
||||
} else {
|
||||
snprintf(buf, sizeof(buf), "%.1f", val);
|
||||
}
|
||||
if (strcmp(buf, last_text[i]) == 0)
|
||||
continue;
|
||||
strcpy(last_text[i], buf);
|
||||
char current[32];
|
||||
GetWindowTextA(app->hChannelValue[i], current, sizeof(current));
|
||||
if (strcmp(buf, current) == 0) continue;
|
||||
SendMessageA(app->hChannelValue[i], WM_SETREDRAW, FALSE, 0);
|
||||
SetWindowTextA(app->hChannelValue[i], buf);
|
||||
SendMessageA(app->hChannelValue[i], WM_SETREDRAW, TRUE, 0);
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
/*
|
||||
* etcpmon_graph.h - ETCP Monitor Graph Definitions
|
||||
* Отрисовка восьми BBR-каналов из кольцевой истории etcpmon_client в GUI-потоке.
|
||||
* GraphWndProc получает etcpmon_app через lpCreateParams при CreateWindowEx;
|
||||
* история и GDI-перья принадлежат app/client, модуль их не освобождает.
|
||||
* Один пиксель X соответствует сэмплу; временная шкала неравномерна при задержке ответов.
|
||||
*/
|
||||
|
||||
#ifndef ETCPMON_GRAPH_H
|
||||
@@ -27,14 +30,21 @@ extern "C" {
|
||||
struct etcpmon_app;
|
||||
struct metrics_history;
|
||||
|
||||
/* Graph colors for each metric */
|
||||
/* Цвета/короткие имена в порядке GRAPH_METRIC_* из etcpmon_client.h. */
|
||||
extern const COLORREF graph_colors[GRAPH_METRICS_COUNT];
|
||||
extern const char* graph_metric_names[GRAPH_METRICS_COUNT];
|
||||
|
||||
/* Graph functions */
|
||||
/* WinAPI wndproc: WM_PAINT рисует историю, движение мыши выбирает сэмпл, уход выключает курсор. */
|
||||
LRESULT CALLBACK GraphWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
|
||||
/* Нарисовать app в HDC hdc внутри client rect rc через временный off-screen bitmap.
|
||||
* Менее двух сэмплов — Waiting for data; масштабы видимой части обновляются не чаще 200 мс. */
|
||||
void DrawGraph(HDC hdc, RECT* rc, struct etcpmon_app* app);
|
||||
/* Записать индексы отмеченных каналов в selected[GRAPH_METRICS_COUNT], их число — в *count.
|
||||
* Если галочек нет, выбирает первые четыре канала; для NULL app число равно нулю. */
|
||||
void GetSelectedChannels(struct etcpmon_app* app, int* selected, int* count);
|
||||
/* Обновить поля значений app по физическому индексу cursor_sample в кольце; неверный индекс даёт "-".
|
||||
* Типы/единицы описаны в metrics_history; байты форматируются в B/KiB/MiB, скорости — B/s/KiB/s/MiB/s.
|
||||
* Сравнивает с текущим текстом контрола, не хранит отдельного кеша и не добавляет сэмплы. */
|
||||
void UpdateChannelValues(struct etcpmon_app* app, int cursor_sample);
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
@@ -1168,8 +1168,8 @@ static void OnAction(struct etcpmon_app* app) {
|
||||
action[sizeof(action) - 1] = '\0';
|
||||
|
||||
if (strlen(action) > 0) {
|
||||
etcpmon_client_send_action(app->client, action);
|
||||
SetWindowTextA(app->hEditAction, "");
|
||||
if (etcpmon_client_send_action(app->client, action) == 0) SetWindowTextA(app->hEditAction, "");
|
||||
else etcpmon_gui_set_status(app, "Failed to queue Action");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1792,18 +1792,18 @@ void etcpmon_gui_update_metrics(struct etcpmon_app* app,
|
||||
const char* mode_names[] = {"STARTUP","DRAIN","PROBE_BW","PROBE_RTT"};
|
||||
const char* cycle_names[] = {"UP","DOWN","CRUISE","REFILL"};
|
||||
snprintf(line3, sizeof(line3),
|
||||
" BBR: mode=%s cycle=%s full_bw=%s loss=%s pace=%.1f KB/s rtt=%u us gain=%.2f",
|
||||
" BBR: mode=%s cycle=%s full_bw=%s loss=%s pace=%.1f KiB/s rtt=%u us gain=%.2f",
|
||||
mode_names[links[i].bbr_mode > 3 ? 0 : links[i].bbr_mode],
|
||||
cycle_names[links[i].bbr_cycle_idx > 3 ? 0 : links[i].bbr_cycle_idx],
|
||||
links[i].bbr_full_bw_reached ? "yes" : "no",
|
||||
links[i].bbr_loss_in_round ? "yes" : "no",
|
||||
(float)links[i].bbr_pacing_rate / 125.0f,
|
||||
(float)links[i].bbr_pacing_rate / 1024.0f,
|
||||
links[i].bbr_min_rtt_us,
|
||||
(float)links[i].bbr_pacing_gain / 256.0f);
|
||||
snprintf(line4, sizeof(line4),
|
||||
" bwHi=%.1f KB/s bwLo=%.1f KB/s infHi=%u infLo=%u",
|
||||
(float)links[i].bbr_bw_hi / 125.0f,
|
||||
(float)links[i].bbr_bw_lo / 125.0f,
|
||||
" bwHi=%.1f KiB/s bwLo=%.1f KiB/s infHi=%u infLo=%u",
|
||||
(float)links[i].bbr_bw_hi / 1024.0f,
|
||||
(float)links[i].bbr_bw_lo / 1024.0f,
|
||||
links[i].bbr_inflight_hi,
|
||||
links[i].bbr_inflight_lo);
|
||||
|
||||
|
||||
+29
-16
@@ -1,5 +1,9 @@
|
||||
/*
|
||||
* etcpmon_gui.h - ETCP Monitor GUI Header
|
||||
* WinAPI GUI etcpmon: init(app, instance) → create_window → run → cleanup.
|
||||
* Caller владеет app; все вызовы, Winsock-клиент и callbacks работают в одном GUI-потоке.
|
||||
* init регистрирует классы окон и запускает Winsock; create_window выделяет client, создаёт
|
||||
* контролы/таймер 10 мс и сразу начинает connect к 192.168.40.1:9091. run показывает окно.
|
||||
* GUI опрашивает списки раз в секунду; метрики автоматически запрашивает client раз в 100 мс.
|
||||
*/
|
||||
|
||||
#ifndef ETCPMON_GUI_H
|
||||
@@ -213,7 +217,8 @@ extern "C" {
|
||||
#define IDC_CH_VALUE_7 527
|
||||
#define IDC_CH_CHECK_7 537
|
||||
|
||||
/* Main application structure */
|
||||
/* Состояние одного приложения; HWND контролов принадлежат окнам, перья и client — app.
|
||||
* Порядок hChannel* совпадает с GRAPH_METRIC_*; интерфейс не предназначен для нескольких app одновременно. */
|
||||
struct etcpmon_app {
|
||||
HINSTANCE hInstance;
|
||||
HWND hWndMain;
|
||||
@@ -375,53 +380,61 @@ struct etcpmon_app {
|
||||
HWND hDebugCatRadio[IDC_DEBUG_MAX_CAT][6]; /* [row][level] радио-кнопки */
|
||||
int debug_cat_count;
|
||||
|
||||
/* Client state */
|
||||
/* Выделенный create_window клиент; cleanup освобождает его и завершает Winsock. */
|
||||
struct etcpmon_client* client;
|
||||
|
||||
int need_initial_request; /* 1 = нужно запросить список при первом таймере */
|
||||
int need_initial_request; /* 1 = после готовности TCP запросить списки и debug config */
|
||||
uint64_t last_selected_peer_id; /* чтобы не спамить SELECT_CONN каждый тик */
|
||||
|
||||
/* Timer */
|
||||
UINT_PTR updateTimer;
|
||||
DWORD last_poll_time;
|
||||
int isConnected;
|
||||
DWORD last_poll_time; /* GetTickCount последнего опроса списков; период 1000 мс */
|
||||
int isConnected; /* Включает CONNECTING; блокирует редактирование адреса */
|
||||
};
|
||||
|
||||
/* Initialize application */
|
||||
/* Обнулить caller-owned app, зарегистрировать классы с hInstance, запустить Winsock.
|
||||
* 0 = успех, -1 = ошибка; основное окно и TCP-клиент ещё не созданы. */
|
||||
int etcpmon_gui_init(struct etcpmon_app* app, HINSTANCE hInstance);
|
||||
|
||||
/* Create main window */
|
||||
/* Создать главное окно, контролы, client и таймер; начать connect к адресу по умолчанию.
|
||||
* Возвращает HWND (также app->hWndMain) или NULL при ошибке создания окна. Показывает окно run. */
|
||||
HWND etcpmon_gui_create_window(struct etcpmon_app* app);
|
||||
|
||||
/* Run message loop */
|
||||
/* Показать app->hWndMain и обрабатывать сообщения/сеть до WM_QUIT.
|
||||
* Возвращает wParam сообщения выхода, -1 для отсутствующего app/окна. */
|
||||
int etcpmon_gui_run(struct etcpmon_app* app);
|
||||
|
||||
/* Cleanup */
|
||||
/* После завершения run освободить tooltip, перья, client и Winsock; сам app не освобождает. */
|
||||
void etcpmon_gui_cleanup(struct etcpmon_app* app);
|
||||
|
||||
/* Update connection status display */
|
||||
/* Скопировать text в status bar app; состояние соединения не меняет. */
|
||||
void etcpmon_gui_set_status(struct etcpmon_app* app, const char* text);
|
||||
|
||||
/* Update connection list */
|
||||
/* Показать list[count], сохранить выбор по last_selected_peer_id или выбрать первую запись.
|
||||
* list заимствован на время вызова, count=0 очищает список; SELECT здесь не отправляется. */
|
||||
void etcpmon_gui_update_conn_list(struct etcpmon_app* app,
|
||||
struct etcpmon_conn_info* list,
|
||||
uint8_t count);
|
||||
|
||||
/* Update socket list */
|
||||
/* Показать list[count] локальных сокетов; пустые name/ip пропускаются. Данные заимствованы на время вызова. */
|
||||
void etcpmon_gui_update_socket_list(struct etcpmon_app* app,
|
||||
struct etcpmon_socket_info* list,
|
||||
uint8_t count);
|
||||
|
||||
/* Update metrics display */
|
||||
/* Показать metrics и links[links_count], перерисовать график из уже обновлённой истории client.
|
||||
* Входные снимки заимствованы на время вызова; новый сэмпл в историю не добавляет. */
|
||||
void etcpmon_gui_update_metrics(struct etcpmon_app* app,
|
||||
struct etcpmon_rsp_metrics* metrics,
|
||||
struct etcpmon_link_metrics* links,
|
||||
uint8_t links_count);
|
||||
|
||||
/* Clear metrics display */
|
||||
/* Очистить поля/линки/график и освободить кеши метрик client, обнулить его историю.
|
||||
* Транспорт, selected_peer_id и pending не меняет; не вызывать с используемыми далее указателями на кеш.
|
||||
* Повторный вывод прежних величин после очистки обновляет сами контролы, отдельного кеша текста нет. */
|
||||
void etcpmon_gui_clear_metrics(struct etcpmon_app* app);
|
||||
|
||||
/* Update graph with new metrics */
|
||||
/* Запросить перерисовку графика app и обновить значения последнего сэмпла при неактивном курсоре.
|
||||
* metrics служит проверкой ненулевого аргумента; данные берутся из истории client, сэмпл не добавляется. */
|
||||
void etcpmon_gui_update_graph(struct etcpmon_app* app,
|
||||
struct etcpmon_rsp_metrics* metrics);
|
||||
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
/*
|
||||
* etcpmon_protocol.h - ETCP Monitor Protocol Definitions
|
||||
*
|
||||
* Binary protocol for monitoring ETCP connections
|
||||
* Format: [2 bytes: msg_size] [1 byte: msg_type] [payload...]
|
||||
*
|
||||
* Period: 100ms (10 updates per second)
|
||||
* Общий формат TCP control_server для etcpmon и других локальных клиентов управления.
|
||||
* Кадр: [size:uint16][type:uint8][seq_id:uint8][payload]; size включает 4-байтовый заголовок,
|
||||
* допустимо 4..32768 байт. Структуры packed(1), числа копируются в порядке байтов хоста
|
||||
* без htons/ntohs; взаимодействующие сборки должны иметь одинаковый layout и endianness.
|
||||
* VERSION — константа исходников, по сети не передаётся; согласования версии нет.
|
||||
* TCP не сохраняет границы кадров. Метрики выдаются по запросу; 100 мс — интервал клиента.
|
||||
* seq=0 не связывается с pending; ответ на запрос копирует его seq (кроме отдельных NODE_INFO).
|
||||
* SELECT_CONN/SET_DEBUG_CONFIG/DISCONNECT не подтверждаются; ACTION даёт ACTION_RESULT либо ERROR.
|
||||
* Подписка на узлы: NODE_INFO с seq=0, затем NODE_INFO_END с seq запроса; обновления также с seq=0.
|
||||
* Встроенного шифрования/аутентификации нет; сервер допускает IPv4 по [control] allow.
|
||||
*/
|
||||
|
||||
#ifndef ETCPMON_PROTOCOL_H
|
||||
@@ -92,12 +96,12 @@ struct etcpmon_msg_header {
|
||||
|
||||
/* CMD_SELECT_CONN: Select connection to monitor */
|
||||
struct etcpmon_cmd_select {
|
||||
uint64_t peer_node_id; /* peer_node_id of connection to monitor */
|
||||
uint64_t peer_node_id; /* ID выбранного соединения; 0 снимает выбор, SELECT не подтверждается */
|
||||
};
|
||||
|
||||
/* CMD_ACTION: Execute action command */
|
||||
struct etcpmon_cmd_action {
|
||||
char action[32]; /* Null-terminated action string */
|
||||
char action[32]; /* Ровно 32 байта с NUL; полное имя "nat"/"nodes", неизвестное имя даёт ERROR */
|
||||
};
|
||||
|
||||
/* CMD_GET_METRICS: No payload required (uses previously selected connection) */
|
||||
@@ -231,7 +235,7 @@ struct etcpmon_link_metrics {
|
||||
uint32_t bandwidth; /* Configured bandwidth (Kbps) */
|
||||
uint32_t nat_changes_count; /* NAT address changes */
|
||||
uint32_t rtt_last; /* Last RTT (0.1ms units) */
|
||||
uint32_t rtt_avg10; /* avg RTT (0.1ms units) */
|
||||
uint32_t rtt_avg10; /* Сейчас BBR min_rtt_us / 100 (0.1 мс), 0 без BBR; не среднее 10 RTT */
|
||||
uint32_t tt_last; /* Last transmit time (0.1ms units) */
|
||||
|
||||
/* Timer flags (1 = active, 0 = NULL) */
|
||||
@@ -293,9 +297,9 @@ struct etcpmon_tun_metrics {
|
||||
/* Router congestion metrics — aggregated over all router_conns */
|
||||
struct etcpmon_router_metrics {
|
||||
uint32_t total_conns;
|
||||
uint32_t total_inflight;
|
||||
uint32_t total_send_q;
|
||||
uint32_t total_recv_q;
|
||||
uint32_t total_inflight; /* Сумма числа записей inflight_q, не байтов */
|
||||
uint32_t total_send_q; /* Сумма числа записей send_q */
|
||||
uint32_t total_recv_q; /* Сумма числа записей recv_q */
|
||||
uint32_t pkts_sent;
|
||||
uint32_t pkts_send_err;
|
||||
uint32_t pkts_rcvd;
|
||||
@@ -322,7 +326,7 @@ struct etcpmon_rsp_metrics {
|
||||
struct etcpmon_rsp_debug_config {
|
||||
uint8_t global_level; /* Global debug level (0=NONE..5=TRACE) */
|
||||
uint8_t category_count; /* Number of categories */
|
||||
/* Followed by: char names_csv[]; null-terminated CSV: "UASYNC,LL_QUEUE,...\0" */
|
||||
/* Followed by: char names_csv[]; NUL-terminated CSV категорий 1..N из debug_config */
|
||||
/* Followed by: uint8_t levels[category_count]; per-category levels */
|
||||
};
|
||||
|
||||
@@ -378,7 +382,8 @@ struct etcpmon_rsp_error {
|
||||
* Utility Functions (optional, for both client and server)
|
||||
* ============================================================================ */
|
||||
|
||||
/* Build message header */
|
||||
/* Заполнить hdr из размера payload, типа и seq. Границы не проверяет:
|
||||
* вызывающий код обязан обеспечить payload_size <= ETCPMON_MAX_MSG_SIZE - sizeof(*hdr). */
|
||||
static inline void etcpmon_build_header(struct etcpmon_msg_header* hdr,
|
||||
uint16_t payload_size,
|
||||
uint8_t msg_type,
|
||||
@@ -388,7 +393,8 @@ static inline void etcpmon_build_header(struct etcpmon_msg_header* hdr,
|
||||
hdr->seq_id = seq_id;
|
||||
}
|
||||
|
||||
/* Validate message header */
|
||||
/* Проверить только диапазон hdr->size; 0 = допустим, -1 = ошибка.
|
||||
* hdr должен указывать на полный заголовок; наличие payload/тип/seq эта функция не проверяет. */
|
||||
static inline int etcpmon_validate_header(const struct etcpmon_msg_header* hdr) {
|
||||
if (hdr->size < sizeof(struct etcpmon_msg_header) ||
|
||||
hdr->size > ETCPMON_MAX_MSG_SIZE) {
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
/* Регрессии опроса и выбора connections на настоящих Winsock/WinAPI. */
|
||||
#include <assert.h>
|
||||
#include <winsock2.h>
|
||||
|
||||
static int WSAAPI test_send(SOCKET fd, const char* bytes, int size, int flags);
|
||||
|
||||
/* Проверяем также внутренние callbacks без расширения публичного API. */
|
||||
#define send test_send
|
||||
#include "etcpmon_client.c"
|
||||
#undef send
|
||||
#include "etcpmon_gui.c"
|
||||
|
||||
static SOCKET listener;
|
||||
@@ -10,6 +15,18 @@ static SOCKET server_sock;
|
||||
static struct etcpmon_client client;
|
||||
static struct etcpmon_app app;
|
||||
static int callbacks;
|
||||
static SOCKET limited_socket = INVALID_SOCKET;
|
||||
static int send_allowance, send_chunk;
|
||||
|
||||
/* Настоящий TCP с управляемой границей short send и WSAEWOULDBLOCK. */
|
||||
static int WSAAPI test_send(SOCKET fd, const char* bytes, int size, int flags) {
|
||||
if (fd == limited_socket) {
|
||||
if (!send_allowance) { WSASetLastError(WSAEWOULDBLOCK); return SOCKET_ERROR; }
|
||||
if (send_allowance > 0) send_allowance--;
|
||||
if (size > send_chunk) size = send_chunk;
|
||||
}
|
||||
return send(fd, bytes, size, flags);
|
||||
}
|
||||
|
||||
static void request_callback(void* arg, uint8_t type, const uint8_t* payload, uint16_t size) {
|
||||
(void)arg; (void)type; (void)payload; (void)size;
|
||||
@@ -86,6 +103,88 @@ static void deliver_list(struct etcpmon_conn_info* list, uint8_t count) {
|
||||
assert(SendMessage(app.hListConnections, LB_GETCOUNT, 0, 0) == count);
|
||||
}
|
||||
|
||||
/* Повторный вывод тех же величин после очистки и отсутствие старого сэмпла при исчезновении линка. */
|
||||
static void test_graph_values(void) {
|
||||
struct etcpmon_client graph_client;
|
||||
etcpmon_client_init(&graph_client);
|
||||
struct etcpmon_client* previous = app.client;
|
||||
app.client = &graph_client;
|
||||
struct etcpmon_link_metrics link = {.inflight_lim_bytes = 64000, .bbr_bw_hi = 900000, .bbr_min_rtt_us = 12300};
|
||||
struct etcpmon_rsp_metrics metrics = {0};
|
||||
graph_client.last_links = &link; graph_client.last_links_count = 1;
|
||||
etcpmon_client_add_to_history(&graph_client, &metrics);
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
for (int i = 0; i < GRAPH_METRIC_COUNT; i++) SetWindowTextA(app.hChannelValue[i], "");
|
||||
UpdateChannelValues(&app, 0);
|
||||
char text[64];
|
||||
GetWindowTextA(app.hChannelValue[GRAPH_METRIC_INFLIGHT_LIM], text, sizeof(text));
|
||||
assert(!strcmp(text, "62.5 KiB"));
|
||||
GetWindowTextA(app.hChannelValue[GRAPH_METRIC_BW_HI], text, sizeof(text));
|
||||
assert(!strcmp(text, "878.9 KiB/s"));
|
||||
GetWindowTextA(app.hChannelValue[GRAPH_METRIC_MIN_RTT], text, sizeof(text));
|
||||
assert(!strcmp(text, "12.3 ms"));
|
||||
}
|
||||
graph_client.history.head = 0; graph_client.last_links_count = 0;
|
||||
etcpmon_client_add_to_history(&graph_client, &metrics);
|
||||
for (int i = 0; i < GRAPH_METRIC_COUNT; i++) assert(graph_client.history.values[i][0] == 0);
|
||||
app.client = previous;
|
||||
puts("PASS graph: bytes/rates, same values after clear and no stale values without links");
|
||||
}
|
||||
|
||||
/* Очередь сохраняет wire-порядок и не запускает response timeout до полной отправки. */
|
||||
static void test_client_transport(void) {
|
||||
closesocket(server_sock); connect_client();
|
||||
limited_socket = client.sock; send_chunk = 2; send_allowance = 1;
|
||||
struct etcpmon_cmd_action action = {"nat"};
|
||||
assert(etcpmon_client_send_request(&client, ETCPMON_CMD_ACTION, &action, sizeof(action), request_callback, NULL) == 0);
|
||||
assert(client.tx_count == 1 && client.tx_head->offset == 2 && !client.pending_head->sent);
|
||||
uint8_t seq = client.pending_head->seq_id;
|
||||
client.pending_head->sent_at = GetTickCount() - REQUEST_TIMEOUT_MS;
|
||||
assert(etcpmon_client_process(&client) == 0 && client.connected);
|
||||
assert(etcpmon_client_request_list(&client) == 0 && client.tx_count == 2);
|
||||
limited_socket = INVALID_SOCKET;
|
||||
assert(etcpmon_client_process(&client) >= 0 && !client.tx_head && client.pending_head->sent);
|
||||
uint8_t expected[sizeof(struct etcpmon_msg_header) * 2 + sizeof(action)], actual[sizeof(expected)];
|
||||
etcpmon_build_header((void*)expected, sizeof(action), ETCPMON_CMD_ACTION, seq);
|
||||
memcpy(expected + sizeof(struct etcpmon_msg_header), &action, sizeof(action));
|
||||
etcpmon_build_header((void*)(expected + sizeof(struct etcpmon_msg_header) + sizeof(action)), 0, ETCPMON_CMD_LIST_CONN, 0);
|
||||
size_t used = 0;
|
||||
for (int i = 0; i < 1000 && used < sizeof(actual); i++) {
|
||||
int got = recv(server_sock, (char*)actual + used, sizeof(actual) - used, 0);
|
||||
if (got == SOCKET_ERROR) assert(WSAGetLastError() == WSAEWOULDBLOCK);
|
||||
else { assert(got > 0); used += got; }
|
||||
Sleep(1);
|
||||
}
|
||||
assert(used == sizeof(actual) && !memcmp(expected, actual, used));
|
||||
uint8_t error[] = {ETCPMON_ERR_INVALID_CMD, 'n','o',0};
|
||||
client.last_response_seq_id = seq;
|
||||
int before = callbacks;
|
||||
handle_response_with_callback(&client, ETCPMON_RSP_ERROR, error, sizeof(error));
|
||||
assert(client.connected && !client.pending_head && callbacks == before + 1);
|
||||
|
||||
limited_socket = client.sock; send_allowance = 0;
|
||||
uint8_t payload[ETCPMON_MAX_MSG_SIZE - sizeof(struct etcpmon_msg_header)] = {0};
|
||||
for (int i = 0; i < 2; i++)
|
||||
assert(etcpmon_client_send_request(&client, ETCPMON_CMD_ACTION, payload, sizeof(payload), request_callback, NULL) == 0);
|
||||
assert(client.tx_bytes == ETCPMON_TX_MAX_BYTES && client.tx_count == 2);
|
||||
assert(etcpmon_client_send_request(&client, ETCPMON_CMD_ACTION, NULL, 0, request_callback, NULL) == -1);
|
||||
assert(client.connected && client.tx_count == 2);
|
||||
client.tx_progress_at = GetTickCount() - REQUEST_TIMEOUT_MS;
|
||||
assert(etcpmon_client_process(&client) == -1 && !client.connected && !client.tx_head && !client.pending_head);
|
||||
limited_socket = INVALID_SOCKET;
|
||||
for (int malformed = 0; malformed < 2; malformed++) {
|
||||
closesocket(server_sock); connect_client();
|
||||
assert(etcpmon_client_send_request(&client, ETCPMON_CMD_ACTION, &action, sizeof(action), request_callback, NULL) == 0);
|
||||
client.last_response_seq_id = client.pending_head->seq_id;
|
||||
before = callbacks;
|
||||
const uint8_t bad[] = {0, 'x'};
|
||||
handle_response_with_callback(&client, malformed ? ETCPMON_RSP_ACTION_RESULT : ETCPMON_RSP_CONN_LIST,
|
||||
bad, malformed ? sizeof(bad) : 1);
|
||||
assert(!client.connected && !client.pending_head && callbacks == before);
|
||||
}
|
||||
puts("PASS client TX: short send/EWOULDBLOCK, exact FIFO, queue bound, progress deadline and response validation");
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
WSADATA data;
|
||||
assert(WSAStartup(MAKEWORD(2, 2), &data) == 0);
|
||||
@@ -108,6 +207,11 @@ int main(void) {
|
||||
app.hListSockets = CreateWindowExA(0, "LISTBOX", "", WS_CHILD,
|
||||
0, 100, 400, 100, app.hWndMain, (HMENU)IDC_LIST_SOCKETS, GetModuleHandle(NULL), NULL);
|
||||
assert(app.hListConnections && app.hListSockets);
|
||||
for (int i = 0; i < GRAPH_METRIC_COUNT; i++) {
|
||||
app.hChannelValue[i] = CreateWindowExA(0, "EDIT", "", WS_CHILD, 0, 0, 100, 20,
|
||||
app.hWndMain, (HMENU)(UINT_PTR)(IDC_CH_VALUE_0 + i), GetModuleHandle(NULL), NULL);
|
||||
assert(app.hChannelValue[i]);
|
||||
}
|
||||
etcpmon_client_set_callbacks(&client, on_connected, on_disconnected, on_conn_list,
|
||||
on_socket_list, on_metrics, on_error, NULL, &app);
|
||||
connect_client();
|
||||
@@ -231,6 +335,8 @@ int main(void) {
|
||||
assert(etcpmon_client_send_request(&client, ETCPMON_CMD_ACTION, NULL, 0, request_callback, NULL) == -1);
|
||||
assert(!client.connected && client.pending_head == NULL && client.pending_tail == NULL && app.need_initial_request);
|
||||
|
||||
test_graph_values();
|
||||
test_client_transport();
|
||||
etcpmon_client_cleanup(&client);
|
||||
closesocket(server_sock);
|
||||
closesocket(listener);
|
||||
|
||||
Reference in new issue
Block a user