libssh2

Форк
0
/
scp_nonblock.c 
307 строк · 7.9 Кб
1
/* Copyright (C) The libssh2 project and its contributors.
2
 *
3
 * Sample showing how to do SCP transfers in a non-blocking manner.
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
 * $ ./scp_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

16
#ifdef _WIN32
17
#define write(f, b, c)  write((f), (b), (unsigned int)(c))
18
#endif
19

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

36
#include <stdio.h>
37

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

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

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

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

65
    FD_ZERO(&fd);
66

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

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

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

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

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

87
    return rc;
88
}
89

90
int main(int argc, char *argv[])
91
{
92
    uint32_t hostaddr;
93
    libssh2_socket_t sock;
94
    int i, auth_pw = 1;
95
    struct sockaddr_in sin;
96
    const char *fingerprint;
97
    int rc;
98
    LIBSSH2_SESSION *session = NULL;
99
    LIBSSH2_CHANNEL *channel;
100
    libssh2_struct_stat fileinfo;
101
#ifdef HAVE_GETTIMEOFDAY
102
    struct timeval start;
103
    struct timeval end;
104
    long time_ms;
105
#endif
106
    int spin = 0;
107
    libssh2_struct_stat_size got = 0;
108
    libssh2_struct_stat_size total = 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
        scppath = 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
    /* Ultra basic "connect to port 22 on localhost".  Your code is
143
     * responsible for creating the socket 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
#ifdef HAVE_GETTIMEOFDAY
170
    gettimeofday(&start, NULL);
171
#endif
172

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

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

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

216
#if 0
217
    libssh2_trace(session, LIBSSH2_TRACE_CONN);
218
#endif
219

220
    /* Request a file via SCP */
221
    fprintf(stderr, "libssh2_scp_recv2().\n");
222
    do {
223
        channel = libssh2_scp_recv2(session, scppath, &fileinfo);
224

225
        if(!channel) {
226
            if(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
227
                char *err_msg;
228

229
                libssh2_session_last_error(session, &err_msg, NULL, 0);
230
                fprintf(stderr, "%s\n", err_msg);
231
                goto shutdown;
232
            }
233
            else {
234
                fprintf(stderr, "libssh2_scp_recv2() spin\n");
235
                waitsocket(sock, session);
236
            }
237
        }
238
    } while(!channel);
239
    fprintf(stderr, "libssh2_scp_recv2() is done, now receive data.\n");
240

241
    while(got < fileinfo.st_size) {
242
        char mem[1024 * 24];
243
        ssize_t nread;
244

245
        do {
246
            int amount = sizeof(mem);
247

248
            if((fileinfo.st_size - got) < amount) {
249
                amount = (int)(fileinfo.st_size - got);
250
            }
251

252
            /* loop until we block */
253
            nread = libssh2_channel_read(channel, mem, (size_t)amount);
254
            if(nread > 0) {
255
                write(1, mem, (size_t)nread);
256
                got += nread;
257
                total += nread;
258
            }
259
        } while(nread > 0);
260

261
        if(nread == LIBSSH2_ERROR_EAGAIN && got < fileinfo.st_size) {
262
            /* this is due to blocking that would occur otherwise
263
            so we loop on this condition */
264

265
            spin++;
266
            waitsocket(sock, session); /* now we wait */
267
            continue;
268
        }
269
        break;
270
    }
271

272
#ifdef HAVE_GETTIMEOFDAY
273
    gettimeofday(&end, NULL);
274

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

283
    libssh2_channel_free(channel);
284
    channel = NULL;
285

286
shutdown:
287

288
    if(session) {
289
        libssh2_session_disconnect(session, "Normal Shutdown");
290
        libssh2_session_free(session);
291
    }
292

293
    if(sock != LIBSSH2_INVALID_SOCKET) {
294
        shutdown(sock, 2);
295
        LIBSSH2_SOCKET_CLOSE(sock);
296
    }
297

298
    fprintf(stderr, "all done\n");
299

300
    libssh2_exit();
301

302
#ifdef _WIN32
303
    WSACleanup();
304
#endif
305

306
    return 0;
307
}
308

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

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

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

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