libssh2

Форк
0
/
sftp_write_nonblock.c 
298 строк · 8.1 Кб
1
/* Copyright (C) The libssh2 project and its contributors.
2
 *
3
 * Sample showing how to do SFTP non-blocking write transfers.
4
 *
5
 * The sample code has default values for host name, user name, password
6
 * and path to copy, but you can specify them on the command line like:
7
 *
8
 * $ ./sftp_write_nonblock 192.168.0.1 user password thisfile /tmp/storehere
9
 *
10
 * SPDX-License-Identifier: BSD-3-Clause
11
 */
12

13
#include "libssh2_setup.h"
14
#include <libssh2.h>
15
#include <libssh2_sftp.h>
16

17
#ifdef HAVE_SYS_SOCKET_H
18
#include <sys/socket.h>
19
#endif
20
#ifdef HAVE_UNISTD_H
21
#include <unistd.h>
22
#endif
23
#ifdef HAVE_NETINET_IN_H
24
#include <netinet/in.h>
25
#endif
26
#ifdef HAVE_ARPA_INET_H
27
#include <arpa/inet.h>
28
#endif
29
#ifdef HAVE_SYS_TIME_H
30
#include <sys/time.h>
31
#endif
32

33
#include <stdio.h>
34
#include <time.h>  /* for time() */
35

36
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
37
static const char *privkey = "/home/username/.ssh/id_rsa";
38
static const char *username = "username";
39
static const char *password = "password";
40
static const char *loclfile = "sftp_write_nonblock.c";
41
static const char *sftppath = "/tmp/sftp_write_nonblock.c";
42

43
static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
44
{
45
    struct timeval timeout;
46
    int rc;
47
    fd_set fd;
48
    fd_set *writefd = NULL;
49
    fd_set *readfd = NULL;
50
    int dir;
51

52
    timeout.tv_sec = 10;
53
    timeout.tv_usec = 0;
54

55
    FD_ZERO(&fd);
56

57
#if defined(__GNUC__)
58
#pragma GCC diagnostic push
59
#pragma GCC diagnostic ignored "-Wsign-conversion"
60
#endif
61
    FD_SET(socket_fd, &fd);
62
#if defined(__GNUC__)
63
#pragma GCC diagnostic pop
64
#endif
65

66
    /* now make sure we wait in the correct direction */
67
    dir = libssh2_session_block_directions(session);
68

69
    if(dir & LIBSSH2_SESSION_BLOCK_INBOUND)
70
        readfd = &fd;
71

72
    if(dir & LIBSSH2_SESSION_BLOCK_OUTBOUND)
73
        writefd = &fd;
74

75
    rc = select((int)(socket_fd + 1), readfd, writefd, NULL, &timeout);
76

77
    return rc;
78
}
79

80
int main(int argc, char *argv[])
81
{
82
    uint32_t hostaddr;
83
    libssh2_socket_t sock;
84
    int i, auth_pw = 1;
85
    struct sockaddr_in sin;
86
    const char *fingerprint;
87
    int rc;
88
    LIBSSH2_SESSION *session = NULL;
89
    LIBSSH2_SFTP *sftp_session;
90
    LIBSSH2_SFTP_HANDLE *sftp_handle;
91
    FILE *local;
92
    char mem[1024 * 100];
93
    size_t nread;
94
    ssize_t nwritten;
95
    char *ptr;
96
    time_t start;
97
    libssh2_struct_stat_size total = 0;
98
    int duration;
99

100
#ifdef _WIN32
101
    WSADATA wsadata;
102

103
    rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
104
    if(rc) {
105
        fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
106
        return 1;
107
    }
108
#endif
109

110
    if(argc > 1) {
111
        hostaddr = inet_addr(argv[1]);
112
    }
113
    else {
114
        hostaddr = htonl(0x7F000001);
115
    }
116
    if(argc > 2) {
117
        username = argv[2];
118
    }
119
    if(argc > 3) {
120
        password = argv[3];
121
    }
122
    if(argc > 4) {
123
        loclfile = argv[4];
124
    }
125
    if(argc > 5) {
126
        sftppath = argv[5];
127
    }
128

129
    rc = libssh2_init(0);
130
    if(rc) {
131
        fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
132
        return 1;
133
    }
134

135
    local = fopen(loclfile, "rb");
136
    if(!local) {
137
        fprintf(stderr, "Cannot open local file %s\n", loclfile);
138
        return 1;
139
    }
140

141
    /*
142
     * The application code is responsible for creating the socket
143
     * and establishing the connection
144
     */
145
    sock = socket(AF_INET, SOCK_STREAM, 0);
146
    if(sock == LIBSSH2_INVALID_SOCKET) {
147
        fprintf(stderr, "failed to create socket.\n");
148
        goto shutdown;
149
    }
150

151
    sin.sin_family = AF_INET;
152
    sin.sin_port = htons(22);
153
    sin.sin_addr.s_addr = hostaddr;
154
    if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
155
        fprintf(stderr, "failed to connect.\n");
156
        goto shutdown;
157
    }
158

159
    /* Create a session instance */
160
    session = libssh2_session_init();
161
    if(!session) {
162
        fprintf(stderr, "Could not initialize SSH session.\n");
163
        goto shutdown;
164
    }
165

166
    /* Since we have set non-blocking, tell libssh2 we are non-blocking */
167
    libssh2_session_set_blocking(session, 0);
168

169
    /* ... start it up. This will trade welcome banners, exchange keys,
170
     * and setup crypto, compression, and MAC layers
171
     */
172
    while((rc = libssh2_session_handshake(session, sock)) ==
173
          LIBSSH2_ERROR_EAGAIN);
174
    if(rc) {
175
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
176
        goto shutdown;
177
    }
178

179
    /* At this point we have not yet authenticated.  The first thing to do
180
     * is check the hostkey's fingerprint against our known hosts Your app
181
     * may have it hard coded, may go to a file, may present it to the
182
     * user, that's your call
183
     */
184
    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
185
    fprintf(stderr, "Fingerprint: ");
186
    for(i = 0; i < 20; i++) {
187
        fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]);
188
    }
189
    fprintf(stderr, "\n");
190

191
    if(auth_pw) {
192
        /* We could authenticate via password */
193
        while((rc = libssh2_userauth_password(session, username, password)) ==
194
              LIBSSH2_ERROR_EAGAIN);
195
        if(rc) {
196
            fprintf(stderr, "Authentication by password failed.\n");
197
            goto shutdown;
198
        }
199
    }
200
    else {
201
        /* Or by public key */
202
        while((rc = libssh2_userauth_publickey_fromfile(session, username,
203
                                                        pubkey, privkey,
204
                                                        password)) ==
205
              LIBSSH2_ERROR_EAGAIN);
206
        if(rc) {
207
            fprintf(stderr, "Authentication by public key failed.\n");
208
            goto shutdown;
209
        }
210
    }
211

212
    fprintf(stderr, "libssh2_sftp_init().\n");
213
    do {
214
        sftp_session = libssh2_sftp_init(session);
215

216
        if(!sftp_session &&
217
           libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
218
            fprintf(stderr, "Unable to init SFTP session\n");
219
            goto shutdown;
220
        }
221
    } while(!sftp_session);
222

223
    fprintf(stderr, "libssh2_sftp_open().\n");
224
    /* Request a file via SFTP */
225
    do {
226
        sftp_handle = libssh2_sftp_open(sftp_session, sftppath,
227
                                        LIBSSH2_FXF_WRITE |
228
                                        LIBSSH2_FXF_CREAT |
229
                                        LIBSSH2_FXF_TRUNC,
230
                                        LIBSSH2_SFTP_S_IRUSR |
231
                                        LIBSSH2_SFTP_S_IWUSR |
232
                                        LIBSSH2_SFTP_S_IRGRP |
233
                                        LIBSSH2_SFTP_S_IROTH);
234
        if(!sftp_handle &&
235
           libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
236
            fprintf(stderr, "Unable to open file with SFTP: %ld\n",
237
                    libssh2_sftp_last_error(sftp_session));
238
            goto shutdown;
239
        }
240
    } while(!sftp_handle);
241

242
    fprintf(stderr, "libssh2_sftp_open() is done, now send data.\n");
243
    start = time(NULL);
244
    do {
245
        nread = fread(mem, 1, sizeof(mem), local);
246
        if(nread <= 0) {
247
            /* end of file */
248
            break;
249
        }
250
        ptr = mem;
251

252
        total += (libssh2_struct_stat_size)nread;
253

254
        do {
255
            /* write data in a loop until we block */
256
            while((nwritten = libssh2_sftp_write(sftp_handle, ptr, nread)) ==
257
                  LIBSSH2_ERROR_EAGAIN) {
258
                waitsocket(sock, session);
259
            }
260
            if(nwritten < 0)
261
                break;
262
            ptr += nwritten;
263
            nread -= (size_t)nwritten;
264
        } while(nread);
265
    } while(nwritten > 0);
266

267
    duration = (int)(time(NULL) - start);
268

269
    fprintf(stderr, "%ld bytes in %d seconds makes %.1f bytes/sec\n",
270
            (long)total, duration, (double)total / duration);
271

272
    fclose(local);
273
    libssh2_sftp_close(sftp_handle);
274
    libssh2_sftp_shutdown(sftp_session);
275

276
shutdown:
277

278
    if(session) {
279
        while(libssh2_session_disconnect(session, "Normal Shutdown") ==
280
              LIBSSH2_ERROR_EAGAIN);
281
        libssh2_session_free(session);
282
    }
283

284
    if(sock != LIBSSH2_INVALID_SOCKET) {
285
        shutdown(sock, 2);
286
        LIBSSH2_SOCKET_CLOSE(sock);
287
    }
288

289
    fprintf(stderr, "all done\n");
290

291
    libssh2_exit();
292

293
#ifdef _WIN32
294
    WSACleanup();
295
#endif
296

297
    return 0;
298
}
299

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.