libssh2

Форк
0
/
sftp_RW_nonblock.c 
385 строк · 10.6 Кб
1
/* Copyright (C) The libssh2 project and its contributors.
2
 *
3
 * Sample showing how to do SFTP transfers in a non-blocking manner.
4
 *
5
 * It will first download a given source file, store it locally and then
6
 * upload the file again to a given destination file.
7
 *
8
 * Using the SFTP server running on 127.0.0.1
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 _WIN32
18
#define write(f, b, c)  write((f), (b), (unsigned int)(c))
19
#endif
20

21
#ifdef HAVE_SYS_SOCKET_H
22
#include <sys/socket.h>
23
#endif
24
#ifdef HAVE_UNISTD_H
25
#include <unistd.h>
26
#endif
27
#ifdef HAVE_NETINET_IN_H
28
#include <netinet/in.h>
29
#endif
30
#ifdef HAVE_SYS_TIME_H
31
#include <sys/time.h>
32
#endif
33

34
#include <stdio.h>
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 *sftppath = "/tmp/TEST"; /* source path */
41
static const char *dest = "/tmp/TEST2";    /* destination path */
42
static const char *storage = "/tmp/sftp-storage"; /* local file name to store
43
                                                     the downloaded file in */
44

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

54
    timeout.tv_sec = 10;
55
    timeout.tv_usec = 0;
56

57
    FD_ZERO(&fd);
58

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

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

71
    if(dir & LIBSSH2_SESSION_BLOCK_INBOUND)
72
        readfd = &fd;
73

74
    if(dir & LIBSSH2_SESSION_BLOCK_OUTBOUND)
75
        writefd = &fd;
76

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

79
    return rc;
80
}
81

82
int main(int argc, char *argv[])
83
{
84
    libssh2_socket_t sock;
85
    int i, auth_pw = 1;
86
    struct sockaddr_in sin;
87
    const char *fingerprint;
88
    int rc;
89
    LIBSSH2_SESSION *session = NULL;
90
    LIBSSH2_SFTP *sftp_session;
91
    LIBSSH2_SFTP_HANDLE *sftp_handle;
92
    FILE *tempstorage = NULL;
93
    char mem[1000];
94
    struct timeval timeout;
95
    fd_set fd;
96
    fd_set fd2;
97

98
#ifdef _WIN32
99
    WSADATA wsadata;
100

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

108
    if(argc > 1) {
109
        username = argv[1];
110
    }
111
    if(argc > 2) {
112
        password = argv[2];
113
    }
114
    if(argc > 3) {
115
        sftppath = argv[3];
116
    }
117
    if(argc > 4) {
118
        dest = argv[4];
119
    }
120

121
    rc = libssh2_init(0);
122
    if(rc) {
123
        fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
124
        return 1;
125
    }
126

127
    /* Ultra basic "connect to port 22 on localhost".  Your code is
128
     * responsible for creating the socket establishing the connection
129
     */
130
    sock = socket(AF_INET, SOCK_STREAM, 0);
131
    if(sock == LIBSSH2_INVALID_SOCKET) {
132
        fprintf(stderr, "failed to create socket.\n");
133
        goto shutdown;
134
    }
135

136
    sin.sin_family = AF_INET;
137
    sin.sin_port = htons(22);
138
    sin.sin_addr.s_addr = htonl(0x7F000001);
139
    if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
140
        fprintf(stderr, "failed to connect.\n");
141
        goto shutdown;
142
    }
143

144
    /* Create a session instance */
145
    session = libssh2_session_init();
146
    if(!session) {
147
        fprintf(stderr, "Could not initialize SSH session.\n");
148
        goto shutdown;
149
    }
150

151
    /* ... start it up. This will trade welcome banners, exchange keys,
152
     * and setup crypto, compression, and MAC layers
153
     */
154
    rc = libssh2_session_handshake(session, sock);
155
    if(rc) {
156
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
157
        goto shutdown;
158
    }
159

160
    libssh2_session_set_blocking(session, 0);
161

162
    /* At this point we have not yet authenticated.  The first thing to do
163
     * is check the hostkey's fingerprint against our known hosts Your app
164
     * may have it hard coded, may go to a file, may present it to the
165
     * user, that's your call
166
     */
167
    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
168
    fprintf(stderr, "Fingerprint: ");
169
    for(i = 0; i < 20; i++) {
170
        fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]);
171
    }
172
    fprintf(stderr, "\n");
173

174
    tempstorage = fopen(storage, "wb");
175
    if(!tempstorage) {
176
        fprintf(stderr, "Cannot open temp storage file %s\n", storage);
177
        goto shutdown;
178
    }
179

180
    if(auth_pw) {
181
        /* We could authenticate via password */
182
        while((rc = libssh2_userauth_password(session, username, password)) ==
183
              LIBSSH2_ERROR_EAGAIN);
184
        if(rc) {
185
            fprintf(stderr, "Authentication by password failed.\n");
186
            goto shutdown;
187
        }
188
    }
189
    else {
190
        /* Or by public key */
191
        while((rc =
192
              libssh2_userauth_publickey_fromfile(session, username,
193
                                                  pubkey, privkey,
194
                                                  password)) ==
195
              LIBSSH2_ERROR_EAGAIN);
196
        if(rc) {
197
            fprintf(stderr, "Authentication by public key failed.\n");
198
            goto shutdown;
199
        }
200
    }
201

202
    do {
203
        sftp_session = libssh2_sftp_init(session);
204

205
        if(!sftp_session) {
206
            if(libssh2_session_last_errno(session) == LIBSSH2_ERROR_EAGAIN) {
207
                fprintf(stderr, "non-blocking init\n");
208
                waitsocket(sock, session); /* now we wait */
209
            }
210
            else {
211
                fprintf(stderr, "Unable to init SFTP session\n");
212
                goto shutdown;
213
            }
214
        }
215
    } while(!sftp_session);
216

217
    /* Request a file via SFTP */
218
    do {
219
        sftp_handle = libssh2_sftp_open(sftp_session, sftppath,
220
                                        LIBSSH2_FXF_READ, 0);
221
        if(!sftp_handle) {
222
            if(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
223
                fprintf(stderr, "Unable to open file with SFTP: %ld\n",
224
                        libssh2_sftp_last_error(sftp_session));
225
                goto shutdown;
226
            }
227
            else {
228
                fprintf(stderr, "non-blocking open\n");
229
                waitsocket(sock, session); /* now we wait */
230
            }
231
        }
232
    } while(!sftp_handle);
233

234
    fprintf(stderr, "libssh2_sftp_open() is done, now receive data.\n");
235
    do {
236
        ssize_t nread;
237
        do {
238
            /* read in a loop until we block */
239
            nread = libssh2_sftp_read(sftp_handle, mem, sizeof(mem));
240
            fprintf(stderr, "libssh2_sftp_read returned %ld\n",
241
                    (long)nread);
242

243
            if(nread > 0) {
244
                /* write to stderr */
245
                write(2, mem, (size_t)nread);
246
                /* write to temporary storage area */
247
                fwrite(mem, (size_t)nread, 1, tempstorage);
248
            }
249
        } while(nread > 0);
250

251
        if(nread != LIBSSH2_ERROR_EAGAIN) {
252
            /* error or end of file */
253
            break;
254
        }
255

256
        timeout.tv_sec = 10;
257
        timeout.tv_usec = 0;
258

259
        FD_ZERO(&fd);
260
        FD_ZERO(&fd2);
261
#if defined(__GNUC__)
262
#pragma GCC diagnostic push
263
#pragma GCC diagnostic ignored "-Wsign-conversion"
264
#endif
265
        FD_SET(sock, &fd);
266
        FD_SET(sock, &fd2);
267
#if defined(__GNUC__)
268
#pragma GCC diagnostic pop
269
#endif
270

271
        /* wait for readable or writeable */
272
        rc = select((int)(sock + 1), &fd, &fd2, NULL, &timeout);
273
        if(rc <= 0) {
274
            /* negative is error
275
               0 is timeout */
276
            fprintf(stderr, "SFTP download timed out: %d\n", rc);
277
            break;
278
        }
279

280
    } while(1);
281

282
    libssh2_sftp_close(sftp_handle);
283
    fclose(tempstorage);
284

285
    tempstorage = fopen(storage, "rb");
286
    if(!tempstorage) {
287
        /* weird, we cannot read the file we just wrote to... */
288
        fprintf(stderr, "Cannot open %s for reading\n", storage);
289
        goto shutdown;
290
    }
291

292
    /* we're done downloading, now reverse the process and upload the
293
       temporarily stored data to the destination path */
294
    sftp_handle = libssh2_sftp_open(sftp_session, dest,
295
                                    LIBSSH2_FXF_WRITE |
296
                                    LIBSSH2_FXF_CREAT,
297
                                    LIBSSH2_SFTP_S_IRUSR |
298
                                    LIBSSH2_SFTP_S_IWUSR |
299
                                    LIBSSH2_SFTP_S_IRGRP |
300
                                    LIBSSH2_SFTP_S_IROTH);
301
    if(sftp_handle) {
302
        size_t nread;
303
        char *ptr;
304
        do {
305
            ssize_t nwritten;
306
            nread = fread(mem, 1, sizeof(mem), tempstorage);
307
            if(nread <= 0) {
308
                /* end of file */
309
                break;
310
            }
311
            ptr = mem;
312

313
            do {
314
                /* write data in a loop until we block */
315
                nwritten = libssh2_sftp_write(sftp_handle, ptr,
316
                                              nread);
317
                if(nwritten < 0)
318
                    break;
319
                ptr += nwritten;
320
                nread -= (size_t)nwritten;
321
            } while(nwritten >= 0);
322

323
            if(nwritten != LIBSSH2_ERROR_EAGAIN) {
324
                /* error or end of file */
325
                break;
326
            }
327

328
            timeout.tv_sec = 10;
329
            timeout.tv_usec = 0;
330

331
            FD_ZERO(&fd);
332
            FD_ZERO(&fd2);
333
#if defined(__GNUC__)
334
#pragma GCC diagnostic push
335
#pragma GCC diagnostic ignored "-Wsign-conversion"
336
#endif
337
            FD_SET(sock, &fd);
338
            FD_SET(sock, &fd2);
339
#if defined(__GNUC__)
340
#pragma GCC diagnostic pop
341
#endif
342

343
            /* wait for readable or writeable */
344
            rc = select((int)(sock + 1), &fd, &fd2, NULL, &timeout);
345
            if(rc <= 0) {
346
                /* negative is error
347
                   0 is timeout */
348
                fprintf(stderr, "SFTP upload timed out: %d\n", rc);
349
                break;
350
            }
351
        } while(1);
352
        fprintf(stderr, "SFTP upload done.\n");
353
    }
354
    else {
355
        fprintf(stderr, "SFTP failed to open destination path: %s\n",
356
                dest);
357
    }
358

359
    libssh2_sftp_shutdown(sftp_session);
360

361
shutdown:
362

363
    if(session) {
364
        libssh2_session_disconnect(session, "Normal Shutdown");
365
        libssh2_session_free(session);
366
    }
367

368
    if(sock != LIBSSH2_INVALID_SOCKET) {
369
        shutdown(sock, 2);
370
        LIBSSH2_SOCKET_CLOSE(sock);
371
    }
372

373
    if(tempstorage)
374
        fclose(tempstorage);
375

376
    fprintf(stderr, "all done\n");
377

378
    libssh2_exit();
379

380
#ifdef _WIN32
381
    WSACleanup();
382
#endif
383

384
    return 0;
385
}
386

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

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

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

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