libssh2

Форк
0
326 строк · 12.4 Кб
1
      * Example: print a remote ascii file using sftp
2
      *
3
     h DFTACTGRP(*NO) ACTGRP(*NEW)
4
     h OPTION(*NOSHOWCPY)
5
     h BNDDIR('LIBSSH2')
6
     h BNDDIR('QC2LE')
7
      *
8
      * Copyright (C) The libssh2 project and its contributors.
9
      *
10
      * Usage:
11
      *
12
      * CALL SFTPXMPLE ('<host>' '<port>' '<user>' '<password>' '<filepath>')
13
      *
14
      * SPDX-License-Identifier: BSD-3-Clause
15
      *
16
     fQPRINT    o    f  120        printer
17
      *
18
      /include LIBSSH2RPG,SSH2_SFTP
19
      /include LIBSSH2RPG,SSH2_CCSID
20
      *
21
     d                 pi
22
     d host                         120
23
     d port                           5
24
     d user                          20
25
     d password                     120
26
     d filepath                     120
27
      *
28
      **************************************************************************
29
      *                          External definitions
30
      **************************************************************************
31
      *
32
     d atoi            pr            10i 0 extproc('atoi')
33
     d  numstr                         *   value options(*string)
34
      *
35
     d inet_addr       pr            10u 0 extproc('inet_addr')
36
     d  char_addr                      *   value options(*string)
37
      *
38
     d socket          pr            10i 0 extproc('socket')
39
     d  domain                       10i 0 value
40
     d  type                         10i 0 value
41
     d  protocol                     10i 0 value
42
      *
43
     d AF_INET         c                   2
44
     d SOCK_STREAM     c                   1
45
     d IPPROTO_IP      c                   0
46
      *
47
     d connect         pr            10i 0 extproc('connect')
48
     d  sockfd                       10i 0 value
49
     d  addr                           *   value
50
     d  addrlen                      10u 0 value
51
      *
52
     d sockaddr_in     ds                  based(######typedef######)
53
     d                                     align qualified
54
     d  sin_family                    5i 0
55
     d  sin_port                      5i 0
56
     d  sin_addr                     10u 0
57
     d  sin_zero                      8
58
      *
59
     d shutdown        pr            10i 0 extproc('shutdown')
60
     d  socket                       10i 0 value
61
     d  how                          10i 0 value
62
      *
63
     d SHUT_RDWR       c                   2
64
      *
65
     d qmhsndpm        pr                  extpgm('QMHSNDPM')
66
     d  msgid                         7    const
67
     d  qmsgfn                       20    const
68
     d  data                     999999    const options(*varsize)
69
     d  datalength                   10u 0 const
70
     d  msgtype                      10    const
71
     d  csentry                  999999    const options(*varsize)
72
     d  cscounter                    10u 0 const
73
     d  msgkey                        4
74
     d  errcode                  999999    options(*varsize)
75
     d  csentrylen                   10u 0 const options(*nopass)
76
     d  csqual                       20    const options(*nopass)
77
     d  waittime                     10u 0 const options(*nopass)
78
     d  csentrytype                  10    const options(*nopass)
79
     d  ccsid                        10u 0 const options(*nopass)
80
      *
81
      **************************************************************************
82
      *                               Constants
83
      **************************************************************************
84
      *
85
     d EBCDIC_CR       c                   X'0D'
86
     d EBCDIC_LF       c                   X'25'
87
      *
88
      **************************************************************************
89
      *                            Global storage
90
      **************************************************************************
91
      *
92
     d sc              s               *   inz(*NULL)                           String cache
93
     d session         s               *   inz(*NULL)                           Session
94
     d sftp_session    s               *   inz(*NULL)                           LIBSSH2_SFTP *
95
     d sftp_handle     s               *   inz(*NULL)                           LIBSSH2_SFTP_HANDLE*
96
     d sin             ds                  likeds(sockaddr_in)                  Remote IP address
97
     d sock            s             10i 0 inz(LIBSSH2_INVALID_SOCKET)          Socket descriptor
98
     d rc              s             10i 0                                      Result code
99
     d hostlen         s             10u 0                                      Host name length
100
      *
101
      **************************************************************************
102
      *                            Main program
103
      **************************************************************************
104

105
        // Initialize ssh lbrary
106
        rc = libssh2_init(0);
107
        if rc <> 0;
108
            error('libssh2 initialization failed (' + %trim(%char(rc)) + ')');
109
        else;
110
            // Build remote address
111
            sin.sin_family = AF_INET;
112
            hostlen = trimmed_length(host: %len(host): %addr(port));
113
            if hostlen <> 0;
114
                 sin.sin_addr = inet_addr(%subst(host: 1: hostlen));
115
            else;
116
                sin.sin_addr = inet_addr('127.0.0.1');
117
            endif;
118
            sin.sin_port = atoi(port);
119
            if sin.sin_port <= 0;
120
                sin.sin_port = 22;
121
            endif;
122
            sin.sin_zero = *ALLX'00';
123

124
            main();
125
            cleanout();
126
        endif;
127

128
        *inlr = *on;
129
      /space 3
130
        begsr *pssr;
131
            cleanout();
132
        endsr;
133
      /eject
134
      **************************************************************************
135
      * Main procedure
136
      **************************************************************************
137
      *
138
     p main            b
139
      *
140
     d buf             s           1024                                         Data buffer
141
     d nread           s             10i 0                                      Read bytes count
142

143
        // Connect to remote server
144
        sock = socket(AF_INET: SOCK_STREAM: IPPROTO_IP);
145
        if sock = LIBSSH2_INVALID_SOCKET;
146
            error('failed to create socket');
147
            return;
148
        endif;
149
        if connect(sock: %addr(sin): %size(sin)) <> 0;
150
            error('failed to connect');
151
            return;
152
        endif;
153

154
        // Create a session instance
155
        session = libssh2_session_init();
156
        if session = *NULL;
157
            error('Could not initialize SSH session');
158
            return;
159
        endif;
160

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

164
        // ... start it up. This will trade welcome banners, exchange keys,
165
        // and setup crypto, compression, and MAC layers
166
        rc = libssh2_session_handshake(session: sock);
167
        if rc <> 0;
168
            error('Failure establishing SSH session: ' + %trim(%char(rc)));
169
            return;
170
        endif;
171

172
        // Authenticate
173
        if libssh2_userauth_password(session:
174
          libssh2_from_ccsid(session: sc: 0: user:
175
                             trimmed_length(user: %size(user):
176
                                            %addr(password)): *omit):
177
          libssh2_from_ccsid(session: sc: 0: password:
178
                             trimmed_length(password: %size(password):
179
                                            %addr(filepath)): *omit)) <> 0;
180
            error('Authentication by password failed');
181
            return;
182
        endif;
183

184
        // Request a file via SFTP
185
        sftp_session = libssh2_sftp_init(session);
186

187
        if sftp_session = *NULL;
188
            error('Unable to init SFTP session');
189
            return;
190
        endif;
191

192
        sftp_handle = libssh2_sftp_open(sftp_session:
193
          libssh2_from_ccsid(session: sc: 0: filepath:
194
                             trimmed_length(filepath: %size(filepath): *null):
195
                                            *omit): LIBSSH2_FXF_READ: 0);
196
        if sftp_handle = *NULL;
197
            error('Unable to open file with SFTP: ' +
198
                  %trim(%char(libssh2_sftp_last_error(sftp_session))));
199
            return;
200
        endif;
201

202
        // Download and display the remote file
203
        nread = libssh2_sftp_read(sftp_handle: %addr(buf): %size(buf));
204
        dow nread > 0;  // loop until we fail
205
            print(libssh2_to_ccsid(session: sc: 0: %addr(buf): nread: *omit):
206
                  -1);
207
            libssh2_release_string_cache(session: sc);
208
            nread = libssh2_sftp_read(sftp_handle: %addr(buf): %size(buf));
209
        enddo;
210
     p main            e
211
      /eject
212
      **************************************************************************
213
      * Release all allocated resources
214
      **************************************************************************
215
      *
216
     p cleanout        b
217
      *
218

219
        if sftp_handle <> *NULL;
220
            libssh2_sftp_close(sftp_handle);
221
        endif;
222

223
        if sftp_session <> *NULL;
224
            libssh2_sftp_shutdown(sftp_session);
225
        endif;
226

227
        if session <> *NULL;
228
            libssh2_session_disconnect(session: libssh2_from_ccsid(session: sc:
229
              0: 'Normal shutdown': -1: *omit));
230
            libssh2_release_string_cache(session: sc);
231
            libssh2_session_free(session);
232
        endif;
233

234
        if sock <> LIBSSH2_INVALID_SOCKET;
235
                shutdown(sock: SHUT_RDWR);
236
                LIBSSH2_SOCKET_CLOSE(sock);
237
        endif;
238

239
        libssh2_exit();
240
     p cleanout        e
241
      /eject
242
      **************************************************************************
243
      * Print data line by line
244
      **************************************************************************
245
      *
246
     p print           b
247
     d                 pi
248
     d  string                         *   value options(*string)
249
     d  len                          10i 0 value
250
      *
251
     d recout          ds                                                       Output line buffer
252
     d  lineout                     120    inz(*blanks)
253
      *
254
     d i               s             10u 0
255
     d j               s             10u 0 inz(0)
256

257
        if len < 0;
258
            len = %len(%str(string));
259
        endif;
260

261
        for i = 0 to len - 1;
262
            if %str(string + i: 1) <> EBCDIC_CR;
263
                if %str(string + i: 1) = EBCDIC_LF;
264
                    write QPRINT recout;
265
                    lineout = *blanks;
266
                    j = 0;
267
                else;
268
                    if j >= %size(lineout);
269
                        write QPRINT recout;
270
                        lineout = *blanks;
271
                        j = 0;
272
                    endif;
273
                    j = j + 1;
274
                    %subst(lineout: j: 1) = %str(string + i: 1);
275
                endif;
276
            endif;
277
        endfor;
278
        if j > 0;
279
            write QPRINT recout;
280
        endif;
281
     p print           e
282
      /eject
283
      **************************************************************************
284
      * Error procedure
285
      **************************************************************************
286
      *
287
     p error           b
288
     d                 pi
289
     d  message                        *   value options(*string)
290
      *
291
     d errcode         ds                  qualified
292
     d  provided                     10u 0 inz(0)
293
     d  available                    10u 0
294
      *
295
     d msgkey          s              4
296

297
        // Send error as an exception to the calling level.
298
        qmhsndpm('CPF9898': 'QCPFMSG   QSYS':
299
                 %str(message): %len(%str(message)): '*ESCAPE':
300
                 '*          ': 1: msgkey: errcode);
301
     p error           e
302
      /eject
303
      **************************************************************************
304
      * Get the length of right-trimmed string
305
      **************************************************************************
306
      *
307
     p trimmed_length  b
308
     d                 pi            10u 0
309
     d  string                   999999    options(*varsize)
310
     d  length                       10u 0 value
311
     d  nextarg                        *   value
312
      *
313
     d len             s             10u 0
314

315
        if nextarg <> *null;
316
            len = nextarg - %addr(string);
317
            if length > len;
318
                length = len;
319
            endif;
320
        endif;
321
        len = %scan(X'00': string: 1: length); // Maybe zero-terminated
322
        if len = 0;
323
            len = length + 1;
324
        endif;
325
        return %checkr(' ': string: len - 1);  // Trim right
326
     p trimmed_length  e
327

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

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

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

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