C - libssh 和 sftp - client/server - 创建 sftp 会话挂起

C - libssh and sftp - client/server - creating sftp session hangs

我通过 SSH 与 libssh 实现了 client/server 通信。我现在也想实现从客户端到服务器的文件上传,一直在关注doc

然而,它在通话中挂起 sftp = sftp_new(session);。我是否也必须在服务器端为其显式打开另一个 ssh_channel ?到目前为止,我只在客户端添加了 sftp 代码。

对于所有同样苦苦挣扎的人,我终于找到了解决方案。

我在 this question 的帖子上发现 libssh/sftp.h 确实在最后为服务器提供了单独的功能。要启用它们,您必须使用 #define WITH_SERVER.

尽管文档中提到您不必自己处理通道,但您必须在服务器端为 SFTP 通信打开一个新通道。实现这个对我有用:

while ((msg = ssh_message_get(session)))
{

    if (ssh_message_type(msg) == SSH_REQUEST_CHANNEL_OPEN && ssh_message_subtype(msg) == SSH_CHANNEL_SESSION)
    {
        printf("[+] Got channel open request, opening new channel for sftp\n");
        sftpChannel = ssh_message_channel_request_open_reply_accept(msg);
        ssh_message_free(msg);
    }

    if (ssh_message_type(msg) == SSH_REQUEST_CHANNEL && ssh_message_subtype(msg) == SSH_CHANNEL_REQUEST_SUBSYSTEM)
    {
        if (!strcmp(ssh_message_channel_request_subsystem(msg), "sftp"))
        {
            ssh_message_channel_request_reply_success(msg);
            ssh_message_free(msg);

            // setup SFTP session
            sftp_session sftp = sftp_server_new(session, sftpChannel);
            if (sftp == NULL)
            {
                fprintf(stderr, "Error allocating SFTP session: %s\n", ssh_get_error(session));
            }                           
            int rc = sftp_server_init(sftp);
            if (rc != SSH_OK)
            {
               fprintf(stderr, "Error initializing SFTP session: %i.\n", sftp_get_error(sftp));
               sftp_free(sftp);
            }

            // handle communication...
         }
    }
}