forked from yongchaofan/tinyTerm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh2.c
1455 lines (1397 loc) · 40.5 KB
/
ssh2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// "$Id: ssh2.c 41206 2020-09-15 12:05:10 $"
//
// tinyTerm -- A minimal serail/telnet/ssh/sftp terminal emulator
//
// ssh2.c is the host communication implementation for
// ssh/sftp/netconf based on libssh2-1.9.0
//
// Copyright 2018-2020 by Yongchao Fan.
//
// This library is free software distributed under GNU GPL 3.0,
// see the license at:
//
// https://github.com/yongchaofan/tinyTerm/blob/master/LICENSE
//
// Please report all bugs and problems on the following page:
//
// https://github.com/yongchaofan/tinyTerm/issues/new
//
#include "tiny.h"
#include <ws2tcpip.h>
#include <time.h>
#include <fcntl.h>
#include <direct.h>
#include <shlwapi.h>
int fnmatch(char *pattern, char *file, int flag)
{
return PathMatchSpecA(file, pattern) ? 0 : 1;
}
/****************************************************************************
* local dirent implementation for compiling on vs2017
****************************************************************************/
#define DT_UNKNOWN 0
#define DT_DIR 1
#define DT_REG 2
#define DT_LNK 3
struct dirent {
unsigned char d_type;
char d_name[MAX_PATH*3];
};
typedef struct tagDIR {
struct dirent dd_dir;
HANDLE dd_handle;
int dd_stat;
} DIR;
static void finddata2dirent(struct dirent *ent, WIN32_FIND_DATA *fdata)
{
wchar_to_utf8(fdata->cFileName, -1, ent->d_name, sizeof(ent->d_name));
if (fdata->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
ent->d_type = DT_DIR;
else
ent->d_type = DT_REG;
}
DIR *opendir(const char *name)
{
WCHAR pattern[MAX_PATH + 2];
int len = utf8_to_wchar(name, -1, pattern, MAX_PATH+2);
if ( len < 0) return NULL;
if ( len && pattern[len - 1]!=L'/' ) wcscat(pattern, L"\\");
wcscat(pattern, L"*.*");
WIN32_FIND_DATA fdata;
HANDLE h = FindFirstFile(pattern, &fdata);
if ( h == INVALID_HANDLE_VALUE ) return NULL;
DIR *dir = (DIR *)malloc(sizeof(DIR));
dir->dd_handle = h;
dir->dd_stat = 0;
finddata2dirent(&dir->dd_dir, &fdata);
return dir;
}
struct dirent *readdir(DIR *dir)
{
if (!dir) return NULL;
if (dir->dd_stat) {
WIN32_FIND_DATA fdata;
if (FindNextFile(dir->dd_handle, &fdata))
finddata2dirent(&dir->dd_dir, &fdata);
else
return NULL;
}
++dir->dd_stat;
return &dir->dd_dir;
}
int closedir(DIR *dir)
{
if (dir) {
FindClose(dir->dd_handle);
free(dir);
}
return 0;
}
/******************************************************************************/
void ssh2_Construct(HOST *ph)
{
ph->session = NULL;
ph->channel =NULL;
ph->sftp = NULL;
ph->bReturn = TRUE;
ph->mtx = CreateMutex(NULL, FALSE, L"channel mutex");
ph->tunnel_list = NULL;
ph->mtx_tun = CreateMutex(NULL, FALSE, L"tunnel mutex");
*ph->homedir = 0;
const char *home = getenv("USERPROFILE");
if ( home!=NULL ) {
strcpy(ph->homedir, home);
strcat(ph->homedir, "/.ssh/");
}
}
int ssh_wait_socket(HOST *ph)
{
TIMEVAL tv = {0, 100000};
fd_set fds, *rfd=NULL, *wfd=NULL;
FD_ZERO(&fds); FD_SET(ph->sock, &fds);
int dir = libssh2_session_block_directions(ph->session);
if ( dir==0 ) return 1;
if ( dir & LIBSSH2_SESSION_BLOCK_INBOUND ) rfd = &fds;
if ( dir & LIBSSH2_SESSION_BLOCK_OUTBOUND ) wfd = &fds;
return select(ph->sock+1, rfd, wfd, NULL, &tv);
}
char *ssh2_Gets(HOST *ph, char *prompt, BOOL bEcho)
{
term_Disp(ph->term, prompt);
ph->bPassword=!bEcho;
ph->bReturn=FALSE;
ph->bGets=TRUE;
ph->keys[0]=0;
ph->cursor=0;
int old_cursor=0;
for ( int i=0; i<600&&ph->bGets&&(!ph->bReturn); i++ ) {
if ( ph->cursor>old_cursor ) {
old_cursor=ph->cursor;
i=0;
}
Sleep(100);
}
if ( ph->bReturn ) {
term_Disp(ph->term, "\r\n");
return ph->keys;
}
else
return NULL;
}
void ssh2_Send(HOST *ph, char *buf, int len)
{
if ( !ph->bReturn ) {
for ( char *p=buf; p<buf+len; p++ ) switch( *p ) {
case '\015':ph->keys[ph->cursor]=0;
ph->bReturn=TRUE;
break;
case '\010':
case '\177':if ( --ph->cursor<0 )
ph->cursor=0;
else
if ( !ph->bPassword ) term_Disp(ph->term, "\010 \010");
break;
default: ph->keys[ph->cursor++]=*p;
if ( ph->cursor>255 ) ph->cursor=255;
if ( !ph->bPassword ) term_Parse(ph->term, p, 1);
}
}
else if ( ph->channel!=NULL ) {
int total=0, cch=0;
while ( total<len ) {
if ( WaitForSingleObject(ph->mtx, INFINITE)!=WAIT_OBJECT_0 ) break;
cch=libssh2_channel_write(ph->channel, buf+total, len-total);
ReleaseMutex(ph->mtx);
if ( cch>=0 )
total += cch;
else
if ( cch!=LIBSSH2_ERROR_EAGAIN || ssh_wait_socket(ph)<0 ) break;
}
}
}
void ssh2_Size(HOST *ph, int w, int h)
{
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
if ( ph->channel!=NULL )
libssh2_channel_request_pty_size(ph->channel, w, h);
ReleaseMutex(ph->mtx);
}
}
void ssh2_Close(HOST *ph )
{
ph->bGets = FALSE;
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
if ( ph->channel!=NULL )
libssh2_channel_send_eof(ph->channel);
if ( ph->session!=NULL )
libssh2_session_disconnect(ph->session, "disconn");
ReleaseMutex(ph->mtx);
}
}
void tun_closeall(HOST *ph);
const char *keytypes[]={"unknown", "rsa", "dss", "ecdsa256",
"ecdsa384", "ecdsa521", "ed25519"};
int ssh_parameters( HOST *ph, char *p )
{
ph->username = ph->password = ph->passphrase = NULL;
ph->hostname = ph->subsystem = NULL;
while ( (p!=NULL) && (*p!=0) ) {
while ( *p==' ' ) p++;
if ( *p=='-' ) {
switch ( p[1] ) {
case 'l': p+=3; ph->username = p; break;
case 'p': if ( p[2]=='w' ) { p+=4; ph->password = p; }
if ( p[2]=='p' ) { p+=4; ph->passphrase = p; }
break;
case 'P': p+=3; ph->port = atoi(p); break;
case 's': p+=3; ph->subsystem = p; break;
}
p = strchr( p, ' ');
if ( p!=NULL ) *p++ = 0;
}
else {
if (*p ) ph->hostname = p;
break;
}
}
if ( ph->username==NULL && ph->hostname!=NULL ) {
p = strchr(ph->hostname, '@');
if ( p!=NULL ) {
ph->username = ph->hostname;
ph->hostname = p+1;
*p=0;
}
}
if ( ph->hostname==NULL ) {
term_Disp(ph->term, "hostname or ip required!\r\n");
return -1;
}
p = strchr(ph->hostname, ':');
char *q = strrchr(ph->hostname, ':');
if ( p!=NULL && p==q ) {
*p = 0;
ph->port = atoi(p+1);
}
return 0;
}
int ssh_knownhost(HOST *ph)
{
int rc = -4;
int type, check, buff_len;
size_t len;
char knownhostfile[MAX_PATH];
strcpy(knownhostfile, ph->homedir);
struct stat sb;
if ( stat(knownhostfile, &sb)!=0 ) mkdir(knownhostfile);
strcat(knownhostfile, "known_hosts");
char keybuf[256];
const char *key = libssh2_session_hostkey(ph->session, &len, &type);
if ( key==NULL ) {
term_Disp(ph->term, "hostkey ");
return rc;
}
buff_len=sprintf(keybuf, "%s key fingerprint", keytypes[type]);
if ( type>0 ) type++;
const char *fingerprint;
fingerprint = libssh2_hostkey_hash(ph->session, LIBSSH2_HOSTKEY_HASH_SHA1);
if ( fingerprint!=NULL ) for(int i = 0; i < 20; i++) {
sprintf(keybuf+buff_len+i*3, ":%02x", (unsigned char)fingerprint[i]);
}
LIBSSH2_KNOWNHOSTS *nh = libssh2_knownhost_init(ph->session);
if ( nh==NULL ) {
term_Disp(ph->term, "known_hosts init");
return rc;
}
if ( libssh2_knownhost_readfile(nh, knownhostfile,
LIBSSH2_KNOWNHOST_FILE_OPENSSH)<0 ) {
term_Disp(ph->term, "known_hosts read");
return rc;
};
struct libssh2_knownhost *knownhost;
check = libssh2_knownhost_check(nh, ph->hostname, key, len,
LIBSSH2_KNOWNHOST_TYPE_PLAIN|
LIBSSH2_KNOWNHOST_KEYENC_RAW, &knownhost);
char *p = NULL;
const char *msg = "Disconnected!";
switch ( check ) {
case LIBSSH2_KNOWNHOST_CHECK_MATCH: rc=0; msg=""; break;
case LIBSSH2_KNOWNHOST_CHECK_MISMATCH:
if ( type==((knownhost->typemask&LIBSSH2_KNOWNHOST_KEY_MASK)
>>LIBSSH2_KNOWNHOST_KEY_SHIFT) ) {
term_Print(ph->term, "%s\r\n\033[31m!!!hostkey changed!!!\r\n",
keybuf);
p=ssh2_Gets(ph, "Update hostkey and continue?(Yes/No):", TRUE);
if ( p==NULL ) {
term_Print(ph->term, "\r\n");
break;
}
if ( *p!='y' && *p!='Y' ) break;
libssh2_knownhost_del(nh, knownhost);//delete old hostkey
msg = "\033[32mhostkey updated";
}
//fall through if hostkey type different, or to update hostkey
case LIBSSH2_KNOWNHOST_CHECK_NOTFOUND:
if ( p == NULL ) {
term_Print(ph->term, "%s\r\n\033[33mhostkey unknown!", keybuf);
p = ssh2_Gets( ph, "Add to .ssh/known_hosts?(Yes/No):", TRUE);
}
if ( p==NULL ) {
term_Print(ph->term, "\r\n");
break;
}
if ( *p!='y' && *p!='Y' ) break;
rc = 0;
libssh2_knownhost_addc(nh, ph->hostname, "", key,
len,"**tinyTerm**", 12,
LIBSSH2_KNOWNHOST_TYPE_PLAIN|
LIBSSH2_KNOWNHOST_KEYENC_RAW|
(type<<LIBSSH2_KNOWNHOST_KEY_SHIFT),
&knownhost);
if ( libssh2_knownhost_writefile(nh, knownhostfile,
LIBSSH2_KNOWNHOST_FILE_OPENSSH)==0 ) {
if ( *msg=='D' ) msg = "\033[32mhostkey added";
}
else
msg = "\033[33mfailed to update hostkey file";
}
term_Print(ph->term, "%s\r\n", msg);
libssh2_knownhost_free(nh);
return rc;
}
static void kbd_callback(const char *name, int name_len,
const char *instruction, int instruction_len,
int num_prompts,
const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts,
LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses,
void **abstract)
{
for ( int i=0; i<num_prompts; i++) {
char *prompt = strdup(prompts[i].text);
prompt[prompts[i].length] = 0;
const char *p = tiny_Gets(prompt, prompts[i].echo);
free(prompt);
if ( p!=NULL ) {
responses[i].text = strdup(p);
responses[i].length = strlen(p);
}
}
}
int ssh_authentication(HOST *ph)
{
char user[256], pw[256];
if ( ph->username==NULL ) {
char *p = ssh2_Gets( ph, "\r\nusername: ", TRUE);
if ( p==NULL ) return -5;
if ( *p==0 ) return -5;
strcpy(user, p);
ph->username = user;
}
char *authlist =
libssh2_userauth_list(ph->session,ph->username,strlen(ph->username));
if ( authlist==NULL ) return 0; //null authentication
if ( strstr(authlist, "publickey")!=NULL ) { // try public key
char pubkeyfile[MAX_PATH], privkeyfile[MAX_PATH];
strcpy(pubkeyfile, ph->homedir);
strcat(pubkeyfile, "id_rsa.pub");
strcpy(privkeyfile, ph->homedir);
strcat(privkeyfile, "id_rsa");
struct stat buf;
if ( stat(pubkeyfile, &buf)==0 && stat(privkeyfile, &buf)==0 ) {
if ( !libssh2_userauth_publickey_fromfile(ph->session,
ph->username, pubkeyfile, privkeyfile, ph->passphrase) ) {
term_Print(ph->term,
"\033[32mpublic key(RSA) authentication\r\n");
return 0;
}
}
}
if ( strstr(authlist, "password")!=NULL ) {
for ( int rep=0; rep<3; rep++ ) {
if ( ph->password==NULL ) {
char *p = ssh2_Gets( ph, "password: ", FALSE);
if ( p==NULL ) continue;
strcpy(pw, p);
ph->password = pw;
}
if ( !libssh2_userauth_password(ph->session, ph->username,
ph->password) ) {
return 0;
}
ph->password=NULL;
}
return -5; //waited 3 times, no password input
}
else if ( strstr(authlist, "keyboard-interactive")!=NULL ) {
for ( int i=0; i<3; i++ )
if (!libssh2_userauth_keyboard_interactive(ph->session,
ph->username,
&kbd_callback) ) {
term_Print(ph->term,
"\033[32mkeyboard-interactive authentication\r\n");
return 0;
}
}
return -5;
}
const char *IETF_HELLO="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\
<capabilities><capability>urn:ietf:params:netconf:base:1.0</capability>\
</capabilities></hello>]]>]]>";
DWORD WINAPI ssh(void *pv)
{
int rc=0;
HOST *ph = (HOST *)pv;
char port[256];
strcpy( port, ph->cmdline+4);
ph->port = 22;
if ( strstr(port, "-s netconf")!=NULL ) ph->port = 830;
if ( ssh_parameters( ph, port )<0 ) goto TCP_Close;
ph->type = (ph->subsystem==NULL ) ? SSH : NETCONF;
ph->status=CONNECTING;
term_Title(ph->term, ph->hostname);
if ( host_tcp(ph)==-1 ) goto TCP_Close;
ph->session = libssh2_session_init();
if ( ph->session!=NULL ) {
while ( (rc=libssh2_session_handshake(ph->session, ph->sock))
==LIBSSH2_ERROR_EAGAIN );
}
if ( rc!=0 || ph->session==NULL ) {
term_Error(ph->term, "session failure");
goto Session_Close;
}
const char *banner = libssh2_session_banner_get(ph->session);
if ( banner!=NULL ) {
term_Disp(ph->term, "\r\n");
term_Disp(ph->term, banner);
}
ph->status=AUTHENTICATING;
if ( ssh_knownhost( ph )<0 ) {
term_Error(ph->term, "verification failure");
goto Session_Close;
}
if ( ssh_authentication( ph )<0 ) {
term_Error(ph->term,"authentication failure");
goto Session_Close;
}
ph->channel = libssh2_channel_open_session(ph->session);
if ( !ph->channel ) {
term_Error(ph->term, "channel failure");
goto Session_Close;
}
if ( ph->subsystem==NULL ) {
if (libssh2_channel_request_pty(ph->channel, "xterm")) {
term_Error(ph->term, "pty failure");
goto Channel_Close;
}
if (libssh2_channel_shell(ph->channel)) {
term_Error(ph->term, "shell failure");
goto Channel_Close;
}
}
else {
if (libssh2_channel_subsystem(ph->channel, ph->subsystem)) {
term_Error(ph->term, "subsystem failure");
goto Channel_Close;
}
libssh2_channel_write(ph->channel, IETF_HELLO, strlen(IETF_HELLO));
}
libssh2_session_set_blocking(ph->session, 0);
ph->status=CONNECTED;
term_Title(ph->term, ph->hostname);
while ( libssh2_channel_eof(ph->channel)==0 ) {
char buf[32768];
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
int cch=libssh2_channel_read(ph->channel, buf, 32768);
ReleaseMutex(ph->mtx);
if ( cch >= 0 ) {
if ( ph->subsystem==NULL )
term_Parse(ph->term, buf, cch);
else
term_Parse_XML(ph->term, buf, cch);
}
else {
if ( cch!=LIBSSH2_ERROR_EAGAIN || ssh_wait_socket( ph )<0 )
break;
}
}
}
tun_closeall( ph);
ph->type = NONE;
term_Error(ph->term, "Disconnected");
Channel_Close:
if ( ph->channel!=NULL ) {
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
libssh2_channel_close(ph->channel);
ReleaseMutex(ph->mtx);
}
ph->channel = NULL;
}
Session_Close:
if ( ph->session!=NULL ) {
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
libssh2_session_free(ph->session);
ReleaseMutex(ph->mtx);
}
ph->session = NULL;
}
closesocket(ph->sock);
ph->sock = 0;
TCP_Close:
ph->status=IDLE;
term_Title(ph->term, "");
return 1;
}
void print_total(TERM *pt, time_t start, long total)
{
double duration = difftime(time(NULL), start);
term_Print(pt, "\033[12D%ld bytes", total);
if ( duration>0 )
term_Print(pt, ", %dMB/s", (int)((total>>20)/duration));
}
int scp_read_one(HOST *ph, const char *rpath, const char *lpath)
{
LIBSSH2_CHANNEL *scp_channel;
libssh2_struct_stat fileinfo;
term_Print(ph->term, "\r\n\033[32mscp: %s\t\t\t", lpath);
int err_no=0;
do {
WaitForSingleObject(ph->mtx, INFINITE);
scp_channel = libssh2_scp_recv2(ph->session, rpath, &fileinfo);
if ( !scp_channel ) err_no = libssh2_session_last_errno(ph->session);
ReleaseMutex(ph->mtx);
if (!scp_channel) {
if ( err_no!=LIBSSH2_ERROR_EAGAIN || ssh_wait_socket(ph)<0 ) {
term_Print(ph->term,"\033[31mcouldn't open remote file");
return -1;
}
}
} while (!scp_channel);
FILE *fp = fopen_utf8(lpath, "wb");
if ( fp==NULL ) {
term_Print(ph->term, "\033[31mcouldn't write to local file");
goto Close;
}
int blocks = 0;
time_t start = time(NULL);
libssh2_struct_stat_size total = 0;
libssh2_struct_stat_size fsize = fileinfo.st_size;
while ( total<fsize ) {
char mem[1024*32];
int amount=sizeof(mem);
if ( (fsize-total) < amount) {
amount = (int)(fsize-total);
}
int rc = 0;
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
rc = libssh2_channel_read(scp_channel, mem, amount);
ReleaseMutex(ph->mtx);
}
if ( rc==0 ) continue;
if ( rc>0) {
int nwrite = fwrite(mem, 1, rc, fp);
if ( nwrite>0 ) {
total += nwrite;
if ( ++blocks==32 ) {
blocks = 0;
term_Print(ph->term, "\033[12D% 10lldKB", total>>10);
}
}
if ( nwrite!=rc ) {
term_Print(ph->term, ", \033[31merror writing to file");
break;
}
}
else {
if ( rc!=LIBSSH2_ERROR_EAGAIN || ssh_wait_socket(ph)<0 ) {
term_Print(ph->term, ", \033[31merror reading from host");
break;
}
}
}
fclose(fp);
if ( total==fsize ) print_total(ph->term, start, total);
Close:
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
libssh2_channel_close(scp_channel);
libssh2_channel_free(scp_channel);
ReleaseMutex(ph->mtx);
}
return 0;
}
int scp_write_one(HOST *ph, const char *lpath, const char *rpath)
{
LIBSSH2_CHANNEL *scp_channel;
struct _stat fileinfo;
term_Print(ph->term, "\r\n\033[32mscp: %s\t\t\t", rpath);
FILE *fp =fopen_utf8(lpath, "rb");
if ( !fp ) {
term_Print(ph->term, "\033[31mcouldn't read local file");
return -1;
}
stat_utf8(lpath, &fileinfo);
int err_no = 0;
do {
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
scp_channel = libssh2_scp_send(ph->session, rpath,
fileinfo.st_mode&0777, (unsigned long)fileinfo.st_size);
if ( !scp_channel ) err_no = libssh2_session_last_errno(ph->session);
ReleaseMutex(ph->mtx);
}
if ( !scp_channel ) {
if ( err_no!=LIBSSH2_ERROR_EAGAIN || ssh_wait_socket(ph)<0 ) {
term_Print(ph->term, "\033[31mcouldn't create remote file");
fclose(fp);
return -2;
}
}
} while ( !scp_channel);
char mem[1024*32];
time_t start=time(NULL);
size_t nread=0;
long total=0;
int blocks=0;
while ( (nread=fread(mem, 1, sizeof(mem), fp)) >0 ) {
char *ptr = mem;
int rc = 0;
while ( nread>0 ) {
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
rc = libssh2_channel_write(scp_channel, ptr, nread);
ReleaseMutex(ph->mtx);
}
if ( rc>0 ) {
ptr += rc;
nread -= rc;
total += rc;
}
else {
if ( rc!=LIBSSH2_ERROR_EAGAIN || ssh_wait_socket(ph)<0 ) break;
}
}
if ( rc>0 ) {
if ( ++blocks==32 ) {
blocks = 0;
term_Print(ph->term, "\033[12D% 10ldKB", total>>10);
}
}
else {
term_Print(ph->term, ", \033[31merror writing to host");
break;
}
}
if ( nread==0 ) //end of file
print_total(ph->term, start, total);
fclose(fp);
int rc;
do {
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
rc = libssh2_channel_send_eof(scp_channel);
ReleaseMutex(ph->mtx);
}
} while (rc==LIBSSH2_ERROR_EAGAIN);
do {
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
rc = libssh2_channel_wait_eof(scp_channel);
ReleaseMutex(ph->mtx);
}
} while (rc==LIBSSH2_ERROR_EAGAIN);
do {
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
rc = libssh2_channel_wait_closed(scp_channel);
ReleaseMutex(ph->mtx);
}
} while (rc==LIBSSH2_ERROR_EAGAIN);
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
libssh2_channel_close(scp_channel);
libssh2_channel_free(scp_channel);
ReleaseMutex(ph->mtx);
}
return 0;
}
void scp_read(HOST *ph, char *lpath, char *rfiles)
{
char lfile[4096];
strncpy(lfile, lpath, 1024);
lfile[1024] = 0;
struct _stat statbuf;
if ( stat_utf8(lpath, &statbuf)!=-1 ) {
if ( (statbuf.st_mode & S_IFMT) == S_IFDIR )
strcat(lfile, "/");
}
char *ldir = lfile+strlen(lfile);
char *p1, *p2, *p = rfiles;
while ( (p1=strchr(p, '\012'))!=NULL ) {
*p1++ = 0;
if ( ldir[-1]=='/' ) { //lpath is a directory
p2 = strrchr(p, '/');
if ( p2==NULL ) p2=p; else p2++;
strcpy(ldir, p2);
}
scp_read_one( ph, p, lfile);
p = p1;
*ldir = 0;
}
}
void scp_write(HOST *ph, char *lpath, char *rpath)
{
DIR *dir;
struct dirent *dp;
struct _stat statbuf;
if ( stat_utf8(lpath, &statbuf)!=-1 ) { //lpath exist
char rfile[4096];
strncpy(rfile, rpath, 1024);
rfile[1024] = 0;
if ( rpath[strlen(rpath)-1]=='/' ) {//rpath specifies a directory
char *p = strrchr(lpath, '/'); //build rfile
if ( p==NULL ) p=lpath; else p++;
strcat(rfile, p);
}
scp_write_one( ph, lpath, rfile);
}
else { //lpath specifies a pattern
char *ldir=".";
char *lpattern = strrchr(lpath, '/');
if ( lpattern!=NULL ) {
*lpattern++ = 0;
if ( *lpath ) ldir = lpath;
}
else
lpattern = lpath;
int cnt = 0;
if ( (dir=opendir(ldir) ) != NULL ) {
while ( (dp=readdir(dir)) != NULL ) {
if ( dp->d_type!=DT_REG ) continue;
if ( fnmatch(lpattern, dp->d_name, 0)==0 ) {
cnt++;
char lfile[1024], rfile[1024];
strcpy(lfile, ldir);
strcat(lfile, "/");
strcat(lfile, dp->d_name);
strcpy(rfile, rpath);
if ( rpath[strlen(rpath)-1]=='/' )
strcat(rfile, dp->d_name);
scp_write_one( ph, lfile, rfile);
}
}
closedir(dir);
}
if ( cnt==0 )
term_Print(ph->term, "\r\n\033[31mscp: %s/%s no mathcing file",
ldir, lpattern);
}
}
struct Tunnel *tun_add(HOST *ph, int tun_sock,
LIBSSH2_CHANNEL *tun_channel,
char *localip, unsigned short localport,
char *remoteip, unsigned short remoteport)
{
struct Tunnel *tun = (struct Tunnel *)malloc(sizeof(struct Tunnel));
if ( tun!=NULL ) {
tun->host = ph;
tun->socket = tun_sock;
tun->channel = tun_channel;
tun->localip = strdup(localip);
tun->localport = localport;
tun->remoteip = strdup(remoteip);
tun->remoteport = remoteport;
if ( WaitForSingleObject(ph->mtx_tun, INFINITE)==WAIT_OBJECT_0 ) {
tun->next = ph->tunnel_list;
ph->tunnel_list = tun;
ReleaseMutex(ph->mtx_tun);
}
term_Print(ph->term, "\r\n\033[32mtunnel %d %s:%d %s:%d\r\n", tun_sock,
localip, localport, remoteip, remoteport);
}
return tun;
}
void tun_del(HOST *ph, int tun_sock)
{
if ( WaitForSingleObject(ph->mtx_tun, INFINITE)==WAIT_OBJECT_0 ) {
struct Tunnel *tun_pre = NULL;
struct Tunnel *tun = ph->tunnel_list;
while ( tun!=NULL ) {
if ( tun->socket==tun_sock ) {
free(tun->localip);
free(tun->remoteip);
if ( tun_pre!=NULL )
tun_pre->next = tun->next;
else
ph->tunnel_list = tun->next;
free(tun);
term_Print(ph->term, "\r\n\033[32mtunnel %d closed\r\n", tun_sock);
break;
}
tun_pre = tun;
tun = tun->next;
}
ReleaseMutex(ph->mtx_tun);
}
}
void tun_closeall(HOST *ph)
{
if ( WaitForSingleObject(ph->mtx_tun, INFINITE)==WAIT_OBJECT_0 ) {
struct Tunnel *tun = ph->tunnel_list;
while ( tun!=NULL ) {
closesocket(tun->socket);
tun = tun->next;
}
}
ReleaseMutex(ph->mtx_tun);
}
DWORD WINAPI tun_worker(void *pv)
{
struct Tunnel *tun = (struct Tunnel *)pv;
LIBSSH2_CHANNEL *tun_channel = tun->channel;
HOST *ph = (HOST *)(tun->host);
int tun_sock = tun->socket;
char buff[16384];
while ( TRUE ) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(ph->sock, &fds);
FD_SET(tun_sock, &fds);
int rc = select(tun_sock+1, &fds, NULL, NULL, NULL);//blocking call
if ( rc==-1 ) break;
if ( rc==0 ) continue;
if ( FD_ISSET(tun_sock, &fds) ) {
int len = recv(tun_sock, buff, sizeof(buff), 0);
if ( len<=0 ) break;
for ( int wr=0, i=0; wr<len; wr+=i ) {
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
i = libssh2_channel_write(tun_channel, buff+wr, len-wr);
ReleaseMutex(ph->mtx);
}
if ( i==LIBSSH2_ERROR_EAGAIN ){ i=0; continue; }
if ( i<=0 ) goto shutdown;
}
}
int len = 0;
if ( FD_ISSET(ph->sock, &fds) ) while ( TRUE ) {
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
len = libssh2_channel_read(tun_channel, buff, sizeof(buff));
ReleaseMutex(ph->mtx);
}
if ( len==LIBSSH2_ERROR_EAGAIN ) break;
if ( len<=0 ) goto shutdown;
for ( int wr=0, i=0; wr<len; wr+=i ) {
i = send(tun_sock, buff+wr, len-wr, 0);
if ( i<=0 ) break;
}
}
}
shutdown:
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
libssh2_channel_close(tun_channel);
libssh2_channel_free(tun_channel);
ReleaseMutex(ph->mtx);
}
closesocket(tun_sock);
tun_del(ph, tun_sock);
return 0;
}
DWORD WINAPI tun_local(void *pv)
{
HOST *ph = (HOST *)pv;
char *lpath, *rpath;
char *cmd = ph->tunline;
char *p = strchr(cmd, ' ');
if ( p!=NULL ) {
lpath = cmd;
rpath = p+1;
*p = 0;
}
else
return 0;
char shost[256], dhost[256], *client_host;
unsigned short sport, dport, client_port;
strncpy(shost, lpath, 255); shost[255]=0;
strncpy(dhost, rpath, 255); dhost[255]=0;
if ( (p=strchr(shost, ':'))==NULL ) return -1;
*p = 0; sport = atoi(++p);
if ( (p=strchr(dhost, ':'))==NULL ) return -1;
*p = 0; dport = atoi(++p);
struct sockaddr_in sin;
int sinlen=sizeof(sin);
struct addrinfo *ainfo;
if ( getaddrinfo(shost, NULL, NULL, &ainfo)!=0 ) {
term_Print(ph->term, "\r\n\033[31minvalid address: %s\r\n", shost);
return -1;
}
int listensock = socket(ainfo->ai_family, SOCK_STREAM, 0);
((struct sockaddr_in *)(ainfo->ai_addr))->sin_port = htons(sport);
int rc = bind(listensock, ainfo->ai_addr, ainfo->ai_addrlen);
freeaddrinfo(ainfo);
if ( rc==-1 ) {
term_Print(ph->term, "\r\n\033[31mport %d invalid or in use\r\n", sport);
closesocket(listensock);
return -1;
}
if ( listen(listensock, 2)==-1 ) {
term_Print(ph->term, "\r\n\033[31mlisten error\r\n");
closesocket(listensock);
return -1;
}
tun_add( ph, listensock, NULL, shost, sport, dhost, dport);
int tun_sock;
LIBSSH2_CHANNEL *tun_channel=NULL;
while ((tun_sock=accept(listensock,(struct sockaddr*)&sin,&sinlen))!=-1) {
client_host = inet_ntoa(sin.sin_addr);
client_port = ntohs(sin.sin_port);
do {
int rc = 0;
if ( WaitForSingleObject(ph->mtx, INFINITE)==WAIT_OBJECT_0 ) {
tun_channel = libssh2_channel_direct_tcpip_ex(ph->session,
dhost, dport, client_host, client_port);
if (!tun_channel) rc = libssh2_session_last_errno(ph->session);
ReleaseMutex(ph->mtx);
}
if ( !tun_channel ) {
if ( rc!=LIBSSH2_ERROR_EAGAIN || ssh_wait_socket(ph)<0 ) {
term_Print(ph->term, "\033[31mCouldn't tunnel, is it supported?\r\n");
closesocket(tun_sock);
goto shutdown;
}
}
} while ( !tun_channel);
void *tun = tun_add( ph, tun_sock, tun_channel,
client_host, client_port, dhost, dport);
CreateThread( NULL, 0, tun_worker, tun, 0, NULL);
}
shutdown:
closesocket(listensock);
tun_del( ph, listensock);
return 0;
}
void ssh2_Tun(HOST *ph, char *cmd)
{
if ( *cmd==' ' ) {
char *p = strchr(++cmd, ' ');
if ( p!=NULL ) { //close a tunnel
DWORD dwTunnelId; //open new tunnel
strncpy(ph->tunline, cmd, 255);
ph->tunline[255] = 0;
term_Print(ph->term, "tunnel:%s\r\n", ph->tunline);
CreateThread( NULL, 0, tun_local, ph, 0, &dwTunnelId);
Sleep(100);
}
else {
int sock = atoi(cmd);
struct Tunnel *tun = ph->tunnel_list;
while ( tun!=NULL ) {
if ( tun->socket==sock ) closesocket(sock);
tun = tun->next;
}
}
}
else { //list existing tunnels
struct Tunnel *tun = ph->tunnel_list;
int listen_cnt = 0, active_cnt = 0;
term_Print(ph->term, "\r\nTunnels:\r\n");
while ( tun!=NULL ) {
term_Print(ph->term, tun->channel==NULL?"listen":"active");
term_Print(ph->term, " socket %d\t%s:%d\t%s:%d\r\n",
tun->socket, tun->localip, tun->localport,
tun->remoteip, tun->remoteport);
if ( tun->channel!=NULL )
active_cnt++;
else
listen_cnt++;
tun = tun->next;
}
term_Print(ph->term, "\t%d listenning, %d active\r\n",
listen_cnt, active_cnt);