libssh2

Форк
0
/
sftp_nonblock.c 
310 строк · 8.1 Кб
1
/* Copyright (C) The libssh2 project and its contributors.
2
 *
3
 * Sample showing how to do SFTP non-blocking 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_nonblock 192.168.0.1 user password /tmp/secrets
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_ARPA_INET_H
31
#include <arpa/inet.h>
32
#endif
33
#ifdef HAVE_SYS_TIME_H
34
#include <sys/time.h>
35
#endif
36

37
#include <stdio.h>
38

39
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
40
static const char *privkey = "/home/username/.ssh/id_rsa";
41
static const char *username = "username";
42
static const char *password = "password";
43
static const char *sftppath = "/tmp/TEST";
44

45
#ifdef HAVE_GETTIMEOFDAY
46
/* diff in ms */
47
static long tvdiff(struct timeval newer, struct timeval older)
48
{
49
    return (newer.tv_sec - older.tv_sec) * 1000 +
50
        (newer.tv_usec - older.tv_usec) / 1000;
51
}
52
#endif
53

54
static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
55
{
56
    struct timeval timeout;
57
    int rc;
58
    fd_set fd;
59
    fd_set *writefd = NULL;
60
    fd_set *readfd = NULL;
61
    int dir;
62

63
    timeout.tv_sec = 10;
64
    timeout.tv_usec = 0;
65

66
    FD_ZERO(&fd);
67

68
#if defined(__GNUC__)
69
#pragma GCC diagnostic push
70
#pragma GCC diagnostic ignored "-Wsign-conversion"
71
#endif
72
    FD_SET(socket_fd, &fd);
73
#if defined(__GNUC__)
74
#pragma GCC diagnostic pop
75
#endif
76

77
    /* now make sure we wait in the correct direction */
78
    dir = libssh2_session_block_directions(session);
79

80
    if(dir & LIBSSH2_SESSION_BLOCK_INBOUND)
81
        readfd = &fd;
82

83
    if(dir & LIBSSH2_SESSION_BLOCK_OUTBOUND)
84
        writefd = &fd;
85

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

88
    return rc;
89
}
90

91
int main(int argc, char *argv[])
92
{
93
    uint32_t hostaddr;
94
    libssh2_socket_t sock;
95
    int i, auth_pw = 1;
96
    struct sockaddr_in sin;
97
    const char *fingerprint;
98
    int rc;
99
    LIBSSH2_SESSION *session = NULL;
100
    LIBSSH2_SFTP *sftp_session;
101
    LIBSSH2_SFTP_HANDLE *sftp_handle;
102
#ifdef HAVE_GETTIMEOFDAY
103
    struct timeval start;
104
    struct timeval end;
105
    long time_ms;
106
#endif
107
    libssh2_struct_stat_size total = 0;
108
    int spin = 0;
109

110
#ifdef _WIN32
111
    WSADATA wsadata;
112

113
    rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
114
    if(rc) {
115
        fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
116
        return 1;
117
    }
118
#endif
119

120
    if(argc > 1) {
121
        hostaddr = inet_addr(argv[1]);
122
    }
123
    else {
124
        hostaddr = htonl(0x7F000001);
125
    }
126
    if(argc > 2) {
127
        username = argv[2];
128
    }
129
    if(argc > 3) {
130
        password = argv[3];
131
    }
132
    if(argc > 4) {
133
        sftppath = argv[4];
134
    }
135

136
    rc = libssh2_init(0);
137
    if(rc) {
138
        fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
139
        return 1;
140
    }
141

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

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

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

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

170
#ifdef HAVE_GETTIMEOFDAY
171
    gettimeofday(&start, NULL);
172
#endif
173

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

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

196
    if(auth_pw) {
197
        /* We could authenticate via password */
198
        while((rc = libssh2_userauth_password(session, username, password)) ==
199
              LIBSSH2_ERROR_EAGAIN);
200
        if(rc) {
201
            fprintf(stderr, "Authentication by password failed.\n");
202
            goto shutdown;
203
        }
204
    }
205
    else {
206
        /* Or by public key */
207
        while((rc =
208
              libssh2_userauth_publickey_fromfile(session, username,
209
                                                  pubkey, privkey,
210
                                                  password)) ==
211
              LIBSSH2_ERROR_EAGAIN);
212
        if(rc) {
213
            fprintf(stderr, "Authentication by public key failed.\n");
214
            goto shutdown;
215
        }
216
    }
217
#if 0
218
    libssh2_trace(session, LIBSSH2_TRACE_CONN);
219
#endif
220
    fprintf(stderr, "libssh2_sftp_init().\n");
221
    do {
222
        sftp_session = libssh2_sftp_init(session);
223

224
        if(!sftp_session) {
225
            if(libssh2_session_last_errno(session) == LIBSSH2_ERROR_EAGAIN) {
226
                fprintf(stderr, "non-blocking init\n");
227
                waitsocket(sock, session); /* now we wait */
228
            }
229
            else {
230
                fprintf(stderr, "Unable to init SFTP session\n");
231
                goto shutdown;
232
            }
233
        }
234
    } while(!sftp_session);
235

236
    fprintf(stderr, "libssh2_sftp_open().\n");
237
    /* Request a file via SFTP */
238
    do {
239
        sftp_handle = libssh2_sftp_open(sftp_session, sftppath,
240
                                        LIBSSH2_FXF_READ, 0);
241
        if(!sftp_handle) {
242
            if(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
243
                fprintf(stderr, "Unable to open file with SFTP: %ld\n",
244
                        libssh2_sftp_last_error(sftp_session));
245
                goto shutdown;
246
            }
247
            else {
248
                fprintf(stderr, "non-blocking open\n");
249
                waitsocket(sock, session); /* now we wait */
250
            }
251
        }
252
    } while(!sftp_handle);
253

254
    fprintf(stderr, "libssh2_sftp_open() is done, now receive data.\n");
255
    do {
256
        char mem[1024 * 24];
257
        ssize_t nread;
258

259
        /* loop until we fail */
260
        while((nread = libssh2_sftp_read(sftp_handle, mem, sizeof(mem))) ==
261
              LIBSSH2_ERROR_EAGAIN) {
262
            spin++;
263
            waitsocket(sock, session); /* now we wait */
264
        }
265
        if(nread > 0) {
266
            total += nread;
267
            write(1, mem, (size_t)nread);
268
        }
269
        else {
270
            break;
271
        }
272
    } while(1);
273

274
#ifdef HAVE_GETTIMEOFDAY
275
    gettimeofday(&end, NULL);
276
    time_ms = tvdiff(end, start);
277
    fprintf(stderr, "Got %ld bytes in %ld ms = %.1f bytes/sec spin: %d\n",
278
            (long)total, time_ms,
279
            (double)total / ((double)time_ms / 1000.0), spin);
280
#else
281
    fprintf(stderr, "Got %ld bytes spin: %d\n", (long)total, spin);
282
#endif
283

284
    libssh2_sftp_close(sftp_handle);
285
    libssh2_sftp_shutdown(sftp_session);
286

287
shutdown:
288

289
    if(session) {
290
        fprintf(stderr, "libssh2_session_disconnect\n");
291
        while(libssh2_session_disconnect(session, "Normal Shutdown") ==
292
              LIBSSH2_ERROR_EAGAIN);
293
        libssh2_session_free(session);
294
    }
295

296
    if(sock != LIBSSH2_INVALID_SOCKET) {
297
        shutdown(sock, 2);
298
        LIBSSH2_SOCKET_CLOSE(sock);
299
    }
300

301
    fprintf(stderr, "all done\n");
302

303
    libssh2_exit();
304

305
#ifdef _WIN32
306
    WSACleanup();
307
#endif
308

309
    return 0;
310
}
311

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

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

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

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