libssh2

Форк
0
/
scp_write_nonblock.c 
297 строк · 7.8 Кб
1
/* Copyright (C) The libssh2 project and its contributors.
2
 *
3
 * Sample showing how to do an SCP non-blocking upload transfer.
4
 *
5
 * SPDX-License-Identifier: BSD-3-Clause
6
 */
7

8
#include "libssh2_setup.h"
9
#include <libssh2.h>
10

11
#ifdef HAVE_SYS_SOCKET_H
12
#include <sys/socket.h>
13
#endif
14
#ifdef HAVE_UNISTD_H
15
#include <unistd.h>
16
#endif
17
#ifdef HAVE_NETINET_IN_H
18
#include <netinet/in.h>
19
#endif
20
#ifdef HAVE_ARPA_INET_H
21
#include <arpa/inet.h>
22
#endif
23
#ifdef HAVE_SYS_TIME_H
24
#include <sys/time.h>
25
#endif
26

27
#include <stdio.h>
28
#include <time.h>  /* for time() */
29

30
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
31
static const char *privkey = "/home/username/.ssh/id_rsa";
32
static const char *username = "username";
33
static const char *password = "password";
34
static const char *loclfile = "scp_write.c";
35
static const char *scppath = "/tmp/TEST";
36

37
static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
38
{
39
    struct timeval timeout;
40
    int rc;
41
    fd_set fd;
42
    fd_set *writefd = NULL;
43
    fd_set *readfd = NULL;
44
    int dir;
45

46
    timeout.tv_sec = 10;
47
    timeout.tv_usec = 0;
48

49
    FD_ZERO(&fd);
50

51
#if defined(__GNUC__)
52
#pragma GCC diagnostic push
53
#pragma GCC diagnostic ignored "-Wsign-conversion"
54
#endif
55
    FD_SET(socket_fd, &fd);
56
#if defined(__GNUC__)
57
#pragma GCC diagnostic pop
58
#endif
59

60
    /* now make sure we wait in the correct direction */
61
    dir = libssh2_session_block_directions(session);
62

63
    if(dir & LIBSSH2_SESSION_BLOCK_INBOUND)
64
        readfd = &fd;
65

66
    if(dir & LIBSSH2_SESSION_BLOCK_OUTBOUND)
67
        writefd = &fd;
68

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

71
    return rc;
72
}
73

74
int main(int argc, char *argv[])
75
{
76
    uint32_t hostaddr;
77
    libssh2_socket_t sock;
78
    int i, auth_pw = 1;
79
    struct sockaddr_in sin;
80
    const char *fingerprint;
81
    int rc;
82
    LIBSSH2_SESSION *session = NULL;
83
    LIBSSH2_CHANNEL *channel;
84
    FILE *local;
85
    char mem[1024 * 100];
86
    size_t nread;
87
    char *ptr;
88
    struct stat fileinfo;
89
    time_t start;
90
    libssh2_struct_stat_size total = 0;
91
    int duration;
92
    size_t prev;
93

94
#ifdef _WIN32
95
    WSADATA wsadata;
96

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

104
    if(argc > 1) {
105
        hostaddr = inet_addr(argv[1]);
106
    }
107
    else {
108
        hostaddr = htonl(0x7F000001);
109
    }
110
    if(argc > 2) {
111
        username = argv[2];
112
    }
113
    if(argc > 3) {
114
        password = argv[3];
115
    }
116
    if(argc > 4) {
117
        loclfile = argv[4];
118
    }
119
    if(argc > 5) {
120
        scppath = argv[5];
121
    }
122

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

129
    local = fopen(loclfile, "rb");
130
    if(!local) {
131
        fprintf(stderr, "Cannot open local file %s\n", loclfile);
132
        return 1;
133
    }
134

135
    stat(loclfile, &fileinfo);
136

137
    /* Ultra basic "connect to port 22 on localhost".  Your code is
138
     * responsible for creating the socket establishing the connection
139
     */
140
    sock = socket(AF_INET, SOCK_STREAM, 0);
141
    if(sock == LIBSSH2_INVALID_SOCKET) {
142
        fprintf(stderr, "failed to create socket.\n");
143
        goto shutdown;
144
    }
145

146
    sin.sin_family = AF_INET;
147
    sin.sin_port = htons(22);
148
    sin.sin_addr.s_addr = hostaddr;
149
    if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
150
        fprintf(stderr, "failed to connect.\n");
151
        goto shutdown;
152
    }
153

154
    /* Create a session instance */
155
    session = libssh2_session_init();
156
    if(!session) {
157
        fprintf(stderr, "Could not initialize SSH session.\n");
158
        goto shutdown;
159
    }
160

161
    /* Since we have set non-blocking, tell libssh2 we are non-blocking */
162
    libssh2_session_set_blocking(session, 0);
163

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

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

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

207
    /* Send a file via scp. The mode parameter must only have permissions! */
208
    do {
209
        channel = libssh2_scp_send(session, scppath, fileinfo.st_mode & 0777,
210
                                   (size_t)fileinfo.st_size);
211

212
        if(!channel &&
213
           libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
214
            char *err_msg;
215

216
            libssh2_session_last_error(session, &err_msg, NULL, 0);
217
            fprintf(stderr, "%s\n", err_msg);
218
            goto shutdown;
219
        }
220
    } while(!channel);
221

222
    fprintf(stderr, "SCP session waiting to send file\n");
223
    start = time(NULL);
224
    do {
225
        nread = fread(mem, 1, sizeof(mem), local);
226
        if(nread <= 0) {
227
            /* end of file */
228
            break;
229
        }
230
        ptr = mem;
231

232
        total += (libssh2_struct_stat_size)nread;
233

234
        prev = 0;
235
        do {
236
            ssize_t nwritten;
237
            while((nwritten = libssh2_channel_write(channel, ptr, nread)) ==
238
                  LIBSSH2_ERROR_EAGAIN) {
239
                waitsocket(sock, session);
240
                prev = 0;
241
            }
242
            if(nwritten < 0) {
243
                fprintf(stderr, "ERROR %ld total %ld / %lu prev %lu\n",
244
                        (long)nwritten, (long)total,
245
                        (unsigned long)nread, (unsigned long)prev);
246
                break;
247
            }
248
            else {
249
                prev = nread;
250

251
                /* nwritten indicates how many bytes were written this time */
252
                ptr += nwritten;
253
                nread -= (size_t)nwritten;
254
            }
255
        } while(nread);
256
    } while(!nread); /* only continue if nread was drained */
257

258
    duration = (int)(time(NULL) - start);
259

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

263
    fprintf(stderr, "Sending EOF\n");
264
    while(libssh2_channel_send_eof(channel) == LIBSSH2_ERROR_EAGAIN);
265

266
    fprintf(stderr, "Waiting for EOF\n");
267
    while(libssh2_channel_wait_eof(channel) == LIBSSH2_ERROR_EAGAIN);
268

269
    fprintf(stderr, "Waiting for channel to close\n");
270
    while(libssh2_channel_wait_closed(channel) == LIBSSH2_ERROR_EAGAIN);
271

272
    libssh2_channel_free(channel);
273
    channel = NULL;
274

275
shutdown:
276

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

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

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

290
    libssh2_exit();
291

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

296
    return 0;
297
}
298

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

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

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

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