This commit is contained in:
2026-03-01 20:26:41 +01:00
parent aba48e463f
commit bff0427f2f
2 changed files with 6 additions and 48 deletions

View File

@@ -14,7 +14,6 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>
@@ -128,24 +127,6 @@ static int sign_callback(LIBSSH2_SESSION *session,
return 0;
}
/* -------------------------------------------------------------------------
* Helpers for non-blocking libssh2
* ---------------------------------------------------------------------- */
static int waitsocket(int sock_fd, LIBSSH2_SESSION *session)
{
struct timeval tv = { .tv_sec = 10, .tv_usec = 0 };
fd_set fd;
FD_ZERO(&fd);
FD_SET(sock_fd, &fd);
fd_set *rfd = NULL, *wfd = NULL;
int dir = libssh2_session_block_directions(session);
if (dir & LIBSSH2_SESSION_BLOCK_INBOUND) rfd = &fd;
if (dir & LIBSSH2_SESSION_BLOCK_OUTBOUND) wfd = &fd;
return select(sock_fd + 1, rfd, wfd, NULL, &tv);
}
/* -------------------------------------------------------------------------
* Public API
* ---------------------------------------------------------------------- */
@@ -258,23 +239,14 @@ bool ssh_execute_command(const char *cmd)
ESP_LOGI(TAG, "SSH authenticated as '%s'", CONFIG_SSH_USERNAME);
/* --- Open channel and execute command --------------------------------- */
LIBSSH2_CHANNEL *channel;
do {
channel = libssh2_channel_open_session(session);
if (!channel && libssh2_session_last_errno(session) == LIBSSH2_ERROR_EAGAIN) {
waitsocket(sock, session);
}
} while (!channel);
LIBSSH2_CHANNEL *channel = libssh2_channel_open_session(session);
if (!channel) {
ESP_LOGE(TAG, "Failed to open SSH channel");
goto cleanup_session;
}
ESP_LOGI(TAG, "Executing: %s", cmd);
while ((rc = libssh2_channel_exec(channel, cmd)) == LIBSSH2_ERROR_EAGAIN) {
waitsocket(sock, session);
}
rc = libssh2_channel_exec(channel, cmd);
if (rc != 0) {
ESP_LOGE(TAG, "channel_exec failed: %d", rc);
libssh2_channel_free(channel);
@@ -285,28 +257,14 @@ bool ssh_execute_command(const char *cmd)
char buf[256];
int bytes;
ESP_LOGI(TAG, "--- command output ---");
for (;;) {
do {
bytes = libssh2_channel_read(channel, buf, sizeof(buf) - 1);
} while (bytes == LIBSSH2_ERROR_EAGAIN && (waitsocket(sock, session), 1));
if (bytes <= 0) break;
while ((bytes = libssh2_channel_read(channel, buf, sizeof(buf) - 1)) > 0) {
buf[bytes] = '\0';
printf("%s", buf);
}
ESP_LOGI(TAG, "--- end output ---");
/* --- Shutdown --------------------------------------------------------- */
while ((rc = libssh2_channel_send_eof(channel)) == LIBSSH2_ERROR_EAGAIN) {
waitsocket(sock, session);
}
while (libssh2_channel_wait_eof(channel) == LIBSSH2_ERROR_EAGAIN) {
waitsocket(sock, session);
}
while (libssh2_channel_wait_closed(channel) == LIBSSH2_ERROR_EAGAIN) {
waitsocket(sock, session);
}
libssh2_channel_close(channel);
int exit_status = libssh2_channel_get_exit_status(channel);
ESP_LOGI(TAG, "Command exited with status: %d", exit_status);