Files
sync-ssh-keys/src/server.c
2025-01-02 01:42:53 +01:00

119 lines
2.7 KiB
C

#include <netdb.h>
#include <stdio.h>
#include <libssh2.h>
#include <libssh2_sftp.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "server.h"
int server_write_file(char *host, int port, char *username, char *pubkey, char *privkey, char *password, char *remote_path, char *content) {
int rc;
libssh2_socket_t sock;
struct sockaddr_in sin;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_SFTP *sftp_session;
LIBSSH2_SFTP_HANDLE *sftp_handle;
struct addrinfo *res = NULL;
struct addrinfo *i;
if (getaddrinfo(host, NULL, 0, &res) != 0) {
fprintf(stderr, "Cloudn't resolve host \"%s\"\n", host);
return 1;
}
for (i = res; i != NULL; i = i->ai_next) {
if (i->ai_addr->sa_family == AF_INET) {
sin = *(struct sockaddr_in*)i->ai_addr;
break;
}
}
rc = libssh2_init(0);
if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket.\n");
goto shutdown;
}
//sin.sin_family = AF_INET;
sin.sin_port = htons(port);
//sin.sin_addr.s_addr = inet_addr(host);
if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect.\n");
goto shutdown;
}
session = libssh2_session_init();
if (!session) {
fprintf(stderr, "Could not initialize SSH session.\n");
goto shutdown;
}
libssh2_session_set_blocking(session, 1);
rc = libssh2_session_handshake(session, sock);
if (rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
goto shutdown;
}
if (libssh2_userauth_publickey_fromfile(session, username, pubkey, privkey, password)) {
fprintf(stderr, "Authentication by public key failed.\n");
goto shutdown;
}
sftp_session = libssh2_sftp_init(session);
if (!sftp_session) {
fprintf(stderr, "Unable to init SFTP session\n");
goto shutdown;
}
sftp_handle = libssh2_sftp_open(sftp_session, remote_path, LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT | LIBSSH2_FXF_TRUNC, LIBSSH2_SFTP_S_IRUSR | LIBSSH2_SFTP_S_IWUSR | LIBSSH2_SFTP_S_IRGRP | LIBSSH2_SFTP_S_IROTH);
if (!sftp_handle) {
fprintf(stderr, "Unable to open file with SFTP: %ld\n", libssh2_sftp_last_error(sftp_session));
goto shutdown;
}
libssh2_sftp_write(sftp_handle, content, strlen(content));
libssh2_sftp_close(sftp_handle);
libssh2_sftp_shutdown(sftp_session);
shutdown:
if(session) {
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
shutdown(sock, 2);
close(sock);
}
fprintf(stderr, "all done\n");
libssh2_exit();
return 0;
}