-
Notifications
You must be signed in to change notification settings - Fork 21
/
SSH2.xs
2739 lines (2390 loc) · 75.5 KB
/
SSH2.xs
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
/*
* SSH2.xs - C functions for Net::SSH2
*
* Authors: D. Robins, Rafael Kitover, Salvador Fandiño
*/
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#define NEED_sv_2pv_flags
#define NEED_newRV_noinc
#define NEED_sv_2pv_nolen
#include "ppport.h"
#if PERL_REVISION == 5 && (PERL_VERSION < 8 || (PERL_VERSION == 8 && PERL_SUBVERSION < 4 ))
# ifdef SvPVbyte_force
# undef SvPVbyte_force
# endif
# define SvPVbyte_force(sv,lp) SvPV_force(sv,lp)
# ifdef SvPVbyte_nolen
# undef SvPVbyte_nolen
# endif
# define SvPVbyte_nolen SvPV_nolen
#endif
#include <libssh2.h>
#include <libssh2_sftp.h>
#include <libssh2_publickey.h>
#define LIBSSH2_HOSTKEY_POLICY_STRICT 1
#define LIBSSH2_HOSTKEY_POLICY_ASK 2
#define LIBSSH2_HOSTKEY_POLICY_TOFU 3
#define LIBSSH2_HOSTKEY_POLICY_ADVISORY 4
#define LIBSSH2_EXTENDED_DATA_STDERR SSH_EXTENDED_DATA_STDERR
#define LIBSSH2_CHANNEL_FLUSH_STDERR SSH_EXTENDED_DATA_STDERR
#include "const-c.inc"
#if defined(USE_ITHREADS) && (defined(I_PTHREAD) || defined(WIN32))
#ifdef USE_GCRYPT
#define HAVE_GCRYPT
#include <gcrypt.h>
#else /* OpenSSL */
#define HAVE_OPENSSL
#include <openssl/crypto.h>
#endif
#else
/* is #warning portable across C compilers? */
/* NO, an error with -pedantic */
/* #warning "Building a non-threadsafe Net::SSH2" */
#endif
#ifndef MULTIPLICITY
/* for debugging output */
#define my_perl ((void *)0)
#endif
/* constants */
#ifndef LIBSSH2_ERROR_NONE
#define LIBSSH2_ERROR_NONE 0
#endif /* LIBSSH2_ERROR_NONE */
/* LIBSSH2_ERROR_* values; from 0 continuing negative */
static const char *const xs_libssh2_error[] = {
"NONE",
"SOCKET_NONE",
"BANNER_NONE",
"BANNER_SEND",
"INVALID_MAC",
"KEX_FAILURE",
"ALLOC",
"SOCKET_SEND",
"KEY_EXCHANGE_FAILURE",
"TIMEOUT",
"HOSTKEY_INIT",
"HOSTKEY_SIGN",
"DECRYPT",
"SOCKET_DISCONNECT",
"PROTO",
"PASSWORD_EXPIRED",
"FILE",
"METHOD_NONE",
"AUTHENTICATION_FAILED",
"PUBLICKEY_UNVERIFIED",
"CHANNEL_OUTOFORDER",
"CHANNEL_FAILURE",
"CHANNEL_REQUEST_DENIED",
"CHANNEL_UNKNOWN",
"CHANNEL_WINDOW_EXCEEDED",
"CHANNEL_PACKET_EXCEEDED",
"CHANNEL_CLOSED",
"CHANNEL_EOF_SENT",
"SCP_PROTOCOL",
"ZLIB",
"SOCKET_TIMEOUT",
"SFTP_PROTOCOL",
"REQUEST_DENIED",
"METHOD_NOT_SUPPORTED",
"INVAL",
"INVALID_POLL_TYPE",
"PUBLICKEY_PROTOCOL",
"EAGAIN",
"ERROR_BUFFER_TOO_SMALL",
"BAD_USE",
"ERROR_COMPRESS",
"OUT_OF_BOUNDARY",
"AGENT_PROTOCOL",
"SOCKET_RECV",
"ENCRYPT",
"BAD_SOCKET",
"KNOWN_HOSTS",
"CHANNEL_WINDOW_FULL",
"KEYFILE_AUTH_FAILED",
};
/* SSH_FX_* values; from 0 continuing positive */
static const char *const sftp_error[] = {
"OK",
"EOF",
"NO_SUCH_FILE",
"PERMISSION_DENIED",
"FAILURE",
"BAD_MESSAGE",
"NO_CONNECTION",
"CONNECTION_LOST",
"OP_UNSUPPORTED",
"INVALID_HANDLE",
"NO_SUCH_PATH",
"FILE_ALREADY_EXISTS",
"WRITE_PROTECT",
"NO_MEDIA",
"NO_SPACE_ON_FILESYSTEM",
"QUOTA_EXCEEDED",
"UNKNOWN_PRINCIPLE",
"LOCK_CONFLICT",
"DIR_NOT_EMPTY",
"NOT_A_DIRECTORY",
"INVALID_FILENAME",
"LINK_LOOP"
};
/* private internal functions */
#define countof(x) (sizeof(x)/sizeof(*x))
#define XLATATTR(name, field, flag) \
else if (strEQ(key, name)) { \
attrs.field = SvUV(ST(i + 1)); \
attrs.flags |= LIBSSH2_SFTP_ATTR_##flag; \
}
typedef int SSH2_RC; /* for converting true/false to 1/undef */
typedef int SSH2_BYTES; /* for functions returning a byte count or a negative number to signal an error */
typedef libssh2_int64_t SSH2_BYTES64; /* the same for unsigned 64bit numbers */
typedef libssh2_uint64_t SSH2_BYTESU64; /* the same for unsigned 64bit numbers */
typedef int SSH2_ERROR; /* for returning SSH2 error numbers */
typedef int SSH2_NERROR; /* for converting SSH2 error code to boolean just indicating success or failure */
typedef int SSH2_BOOL; /* for yes/no responses */
typedef IV SSH2_METHOD; /* LIBSSH2_METHOD_ constants */
typedef IV SSH2_FLAG; /* LIBSSH2_FLAG_ constants */
typedef IV SSH2_CALLBACK; /* LIBSSH2_CALLBACK_ constants */
typedef IV SSH2_HOSTKEY_HASH; /* LIBSSH2_HOSTKEY_HASH_ constants */
typedef IV SSH2_CHANNEL_EXTENDED_DATA; /* SSH2_CHANNEL_EXTENDED_DATA_ constants */
typedef IV SSH2_STREAM_ID; /* stream_id or LIBSSH2_CHANNEL_FLUSH macros */
typedef char * SSH2_CHARP; /* string that can not be NULL */
typedef char * SSH2_CHARP_OR_NULL; /* string that can be NULL */
/* Net::SSH2 object */
typedef struct SSH2 {
LIBSSH2_SESSION* session;
SV* sv_ss; /* NB: not set until callback() called */
SV* socket;
SV* hostname;
int port;
SV* sv_tmp;
SV* rgsv_cb[LIBSSH2_CALLBACK_X11 + 1];
} SSH2;
/* Net::SSH2::Channel object */
typedef struct SSH2_CHANNEL {
SSH2* ss;
SV* sv_ss;
LIBSSH2_CHANNEL* channel;
} SSH2_CHANNEL;
/* Net::SSH2::SFTP object */
typedef struct SSH2_SFTP {
SSH2* ss;
SV* sv_ss;
LIBSSH2_SFTP* sftp;
} SSH2_SFTP;
/* Net::SSH2::Listener object */
typedef struct SSH2_LISTENER {
SSH2* ss;
SV* sv_ss;
LIBSSH2_LISTENER* listener;
} SSH2_LISTENER;
/* Net::SSH2::File object */
typedef struct SSH2_FILE {
SSH2_SFTP* sf;
SV* sv_sf;
LIBSSH2_SFTP_HANDLE* handle;
} SSH2_FILE;
/* Net::SSH2::Dir object */
typedef struct SSH2_DIR {
SSH2_SFTP* sf;
SV* sv_sf;
LIBSSH2_SFTP_HANDLE* handle;
} SSH2_DIR;
/* Net::SSH2::PublicKey object */
typedef struct SSH2_PUBLICKEY {
SSH2* ss;
SV* sv_ss;
LIBSSH2_PUBLICKEY* pkey;
} SSH2_PUBLICKEY;
#if LIBSSH2_VERSION_NUM >= 0x010200
/* Net::SSH2::KnownHosts object */
typedef struct SSH2_KNOWNHOSTS {
SSH2 *ss;
SV *sv_ss;
LIBSSH2_KNOWNHOSTS* knownhosts;
} SSH2_KNOWNHOSTS;
#endif
static int net_ss_debug_out = 0;
static unsigned long gensym_count = 0;
/* debug output */
static void debug(const char* format, ...) {
if (net_ss_debug_out) {
va_list va;
va_start(va, format);
vwarn(format, &va);
va_end(va);
}
}
/* libssh2 allocator thunks */
LIBSSH2_ALLOC_FUNC(local_alloc) {
void *buf;
New(0, buf, count, char);
return buf;
}
LIBSSH2_REALLOC_FUNC(local_realloc) {
return Renew(ptr, count, char);
}
LIBSSH2_FREE_FUNC(local_free) {
Safefree(ptr);
}
#define SV2TYPE(sv, type) ((type)((sizeof(IV) < sizeof(type)) ? SvNV(sv) : SvIV(sv)))
#define SV2UTYPE(sv, type) ((type)((sizeof(IV) < sizeof(type)) ? SvNV(sv) : SvUV(sv)))
static void
wrap_tied_into(SV *to, const char *pkg, void *object) {
GV* gv = (GV*)newSVrv(to, pkg);
IO* io = (IO*)newSV(0);
SV* name_sv = sv_2mortal(newSVpvf("_GEN_%ld", (long)gensym_count++));
STRLEN name_len;
const char *name = SvPVbyte(name_sv, name_len);
SvUPGRADE((SV*)gv, SVt_PVGV);
gv_init(gv, gv_stashpv(pkg, GV_ADD), name, name_len, 0);
SvUPGRADE((SV*)io, SVt_PVIO);
GvSV(gv) = newSViv(PTR2IV(object));
GvIOp(gv) = io;
#if PERL_VERSION > 6
sv_magic((SV*)io, newRV((SV*)gv), PERL_MAGIC_tiedscalar, Nullch, 0);
#else
sv_magic((SV*)gv, newRV((SV*)gv), PERL_MAGIC_tiedscalar, Nullch, 0);
#endif
}
static IV
unwrap(SV *sv, const char *pkg, const char *method) {
if (SvROK(sv) && sv_isa(sv, pkg)) {
SV *inner = SvRV(sv);
if (SvIOK(inner))
return SvIVX(inner);
}
croak("%s::%s: invalid object %s", pkg, method, SvPV_nolen(sv));
}
static IV
unwrap_tied(SV *sv, const char *pkg, const char *method) {
if (SvROK(sv) && sv_isa(sv, pkg)) {
SV *gv = SvRV(sv);
if (SvTYPE(gv) == SVt_PVGV) {
SV *inner = GvSV((GV*)gv);
if (inner && SvIOK(inner))
return SvIVX(inner);
}
}
croak("%s::%s: invalid object %s", pkg, method, SvPV_nolen(sv));
}
/* push a hash of values onto the return stack, for '%hash = func()' */
static int push_hv(SV** sp, HV* hv) {
I32 keys = hv_iterinit(hv);
const char* pv_key;
I32 len_key;
SV* value;
EXTEND(SP, keys * 2);
while ((value = hv_iternextsv(hv, (char**)&pv_key, &len_key))) {
PUSHs(sv_2mortal(newSVpvn(pv_key, len_key)));
PUSHs(sv_2mortal(SvREFCNT_inc(value)));
}
SvREFCNT_dec(hv);
return keys * 2;
}
static SV *
sv_upper(SV *sv) {
STRLEN len, i;
char *pv = SvPVbyte(sv, len);
for (i = 0; i < len; i++) {
if (isLOWER(pv[i])) {
sv = sv_2mortal(newSVpvn(pv, len));
pv = SvPVX(sv);
for (; i < len; i++)
pv[i] = toUPPER(pv[i]);
break;
}
}
return sv;
}
static IV
sv2iv_constant_or_croak(const char *name, SV *sv) {
if (!SvOK(sv) || SvIOK(sv) || looks_like_number(sv))
return SvIV(sv);
else {
STRLEN len;
char *pv;
int type, i;
IV value;
sv = sv_upper(sv);
pv = SvPVbyte(sv, len);
type = constant(aTHX_ pv, len, &value);
if (type == PERL_constant_NOTFOUND) {
sv = sv_2mortal(newSVpvf("LIBSSH2_%s_%s", name, pv));
pv = SvPVbyte(sv, len);
type = constant(aTHX_ SvPV_nolen(sv), len, &value);
}
if (type == PERL_constant_ISIV)
return value;
croak("Invalid constant of type LIBSSH2_%s (%s)", name, pv);
}
}
/* create a hash from an SFTP attributes structure */
static HV*
hv_from_attrs(LIBSSH2_SFTP_ATTRIBUTES* attrs) {
HV* hv = newHV();
debug("hv_from_attrs: attrs->flags = %d\n", attrs->flags);
if (attrs->flags & LIBSSH2_SFTP_ATTR_SIZE)
hv_store(hv, "size", 4, newSVuv(attrs->filesize), 0/*hash*/);
if (attrs->flags & LIBSSH2_SFTP_ATTR_UIDGID) {
hv_store(hv, "uid", 3, newSVuv(attrs->uid), 0/*hash*/);
hv_store(hv, "gid", 3, newSVuv(attrs->gid), 0/*hash*/);
}
if (attrs->flags & LIBSSH2_SFTP_ATTR_PERMISSIONS)
hv_store(hv, "mode", 4, newSVuv(attrs->permissions), 0/*hash*/);
if (attrs->flags & LIBSSH2_SFTP_ATTR_ACMODTIME) {
hv_store(hv, "atime", 5, newSVuv(attrs->atime), 0/*hash*/);
hv_store(hv, "mtime", 5, newSVuv(attrs->mtime), 0/*hash*/);
}
return hv;
}
/* return attributes from function, as flat hash or hashref */
#define XSRETURN_STAT_ATTRS(name) XSRETURN(return_stat_attrs(sp, &attrs, name))
static int return_stat_attrs(SV** sp, LIBSSH2_SFTP_ATTRIBUTES* attrs,
SV* name) {
HV* hv_attrs = hv_from_attrs(attrs);
if (name)
hv_store(hv_attrs, "name", 4, name, 0/*hash*/);
switch (GIMME_V) {
case G_SCALAR:
PUSHs(sv_2mortal(newRV_noinc((SV*)hv_attrs)));
return 1;
case G_ARRAY:
return push_hv(sp, hv_attrs);
default:
SvREFCNT_dec(hv_attrs);
}
return 0;
}
/* general wrapper */
#define NEW_ITEM(type, field, create, parent) do { \
Newz(0/*id*/, RETVAL, 1, type); \
if (RETVAL) { \
RETVAL->parent = parent; \
RETVAL->sv_##parent = SvREFCNT_inc(SvRV(ST(0))); \
RETVAL->field = create; \
debug(#create " -> 0x%p\n", RETVAL->field); \
} \
if (!RETVAL || !RETVAL->field) { \
if (RETVAL) \
SvREFCNT_dec(RETVAL->sv_##parent); \
Safefree(RETVAL); \
XSRETURN_EMPTY; \
} \
} while(0)
/* wrap a libSSH2 channel */
#define NEW_CHANNEL(create) NEW_ITEM(SSH2_CHANNEL, channel, create, ss)
/* wrap a libSSH2 listener */
#define NEW_LISTENER(create) NEW_ITEM(SSH2_LISTENER, listener, create, ss)
/* wrap a libSSH2 SFTP connection */
#define NEW_SFTP(create) NEW_ITEM(SSH2_SFTP, sftp, create, ss)
/* wrap a libSSH2 SFTP file */
#define NEW_FILE(create) NEW_ITEM(SSH2_FILE, handle, create, sf)
/* wrap a libSSH2 SFTP directory */
#define NEW_DIR(create) NEW_ITEM(SSH2_DIR, handle, create, sf)
/* wrap a libSSH2 public key object */
#define NEW_PUBLICKEY(create) NEW_ITEM(SSH2_PUBLICKEY, pkey, create, ss)
/* wrap a libSSH2 knownhosts object */
#define NEW_KNOWNHOSTS(create) NEW_ITEM(SSH2_KNOWNHOSTS, knownhosts, create, ss)
static void
set_cb_args(pTHX_ AV* data) {
GV *gv = gv_fetchpv("Net::SSH2::_cb_args", 1, SVt_PV);
SV *sv = save_scalar(gv);
sv_setsv(sv, sv_2mortal(newRV_inc((SV*)data)));
}
static SV*
get_cb_arg(pTHX_ I32 ix) {
SV *sv = get_sv("Net::SSH2::_cb_args", 1);
if (SvROK(sv)) {
AV *data = (AV*)SvRV(sv);
if (SvTYPE(data) == SVt_PVAV) {
SV **svp = av_fetch(data, ix, 0);
if (svp && *svp)
return *svp;
Perl_croak(aTHX_ "internal error: unable to fetch callback data slot %d", ix);
}
}
Perl_croak(aTHX_ "internal error: unexpected structure found for callback data");
}
/* callback for returning a password via "keyboard-interactive" auth */
static LIBSSH2_USERAUTH_KBDINT_RESPONSE_FUNC(cb_kbdint_response_password) {
if (num_prompts != 1 || prompts[0].echo) {
int i;
for (i = 0; i < num_prompts; ++i) {
responses[i].text = NULL;
responses[i].length = 0;
}
}
else {
/* single prompt, no echo: assume it's a password request */
dTHX;
SV *password = get_cb_arg(aTHX_ 0);
STRLEN len_password;
const char* pv_password = SvPVbyte(password, len_password);
responses[0].text = savepvn(pv_password, len_password);
responses[0].length = len_password;
}
}
/* thunk to call perl input-reading function for "keyboard-interactive" auth */
static LIBSSH2_USERAUTH_KBDINT_RESPONSE_FUNC(cb_kbdint_response_callback) {
dTHX; dSP;
int count, i;
SV *cb = get_cb_arg(aTHX_ 0);
SV *self = get_cb_arg(aTHX_ 1);
SV *username = get_cb_arg(aTHX_ 2);
ENTER;
SAVETMPS;
PUSHMARK(SP);
EXTEND(SP, 4 + num_prompts);
PUSHs(self);
PUSHs(username);
PUSHs(sv_2mortal(newSVpvn(name, name_len)));
PUSHs(sv_2mortal(newSVpvn(instruction, instruction_len)));
for (i = 0; i < num_prompts; ++i) {
HV* hv = newHV();
/* Perl_warn(aTHX_ "prompt %d: text: %p, length: %d, echo: %d\n", */
/* i, prompts[i].text, prompts[i].length, prompts[i].echo); */
PUSHs(sv_2mortal(newRV_noinc((SV*)hv)));
hv_store(hv, "text", 4, newSVpvn((const char *)prompts[i].text, prompts[i].length), 0);
hv_store(hv, "echo", 4, newSVuv(prompts[i].echo), 0);
responses[i].text = NULL;
responses[i].length = 0;
}
PUTBACK;
count = call_sv(cb, G_ARRAY);
SPAGAIN;
if (count > num_prompts) {
Perl_warn(aTHX_ "Too many responses from callback, %d expected but %d found!",
num_prompts, count);
while (count-- > num_prompts)
POPs;
}
while (count-- > 0) {
STRLEN len_response;
SV *sv = POPs;
char *pv_response = SvPVbyte(sv, len_response);
responses[count].text = savepvn(pv_response, len_response);
responses[count].length = len_response;
}
PUTBACK;
FREETMPS;
LEAVE;
}
/* thunk to call perl password change function for "password" auth */
static LIBSSH2_PASSWD_CHANGEREQ_FUNC(cb_password_change_callback) {
dTHX; dSP;
int count;
SV *cb = get_cb_arg(aTHX_ 0);
SV *self = get_cb_arg(aTHX_ 1);
SV *username = get_cb_arg(aTHX_ 2);
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs(self);
XPUSHs(username);
PUTBACK;
count = call_sv(cb, G_SCALAR);
SPAGAIN;
if (count > 0) {
STRLEN len_password;
const char* pv_password = SvPVbyte(POPs, len_password);
*newpw = savepvn(pv_password, len_password);
*newpw_len = len_password;
}
else {
*newpw = NULL;
*newpw_len = 0;
}
PUTBACK;
FREETMPS;
LEAVE;
}
/* thunk to call perl SSH_MSG_IGNORE packet function */
static LIBSSH2_IGNORE_FUNC(cb_ignore_callback) {
SSH2* ss = (SSH2*)*abstract;
dSP; I32 ax; int count;
ENTER; SAVETMPS; PUSHMARK(SP);
XPUSHs(sv_2mortal(newRV_inc(ss->sv_ss)));
mXPUSHp(message, message_len);
PUTBACK;
count = call_sv(ss->rgsv_cb[LIBSSH2_CALLBACK_IGNORE], G_VOID);
SPAGAIN; SP -= count; ax = (SP - PL_stack_base) + 1;
PUTBACK; FREETMPS; LEAVE;
}
/* thunk to call perl SSH_MSG_DEBUG packet function */
static LIBSSH2_DEBUG_FUNC(cb_debug_callback) {
SSH2* ss = (SSH2*)*abstract;
dSP; I32 ax; int count;
ENTER; SAVETMPS; PUSHMARK(SP);
XPUSHs(sv_2mortal(newRV_inc(ss->sv_ss)));
mXPUSHi(always_display);
mXPUSHp(message, message_len);
mXPUSHp(language, language_len);
PUTBACK;
count = call_sv(ss->rgsv_cb[LIBSSH2_CALLBACK_DEBUG], G_VOID);
SPAGAIN; SP -= count; ax = (SP - PL_stack_base) + 1;
PUTBACK; FREETMPS; LEAVE;
}
/* thunk to call perl SSH_MSG_DISCONNECT packet function */
static LIBSSH2_DISCONNECT_FUNC(cb_disconnect_callback) {
SSH2* ss = (SSH2*)*abstract;
dSP; I32 ax; int count;
ENTER; SAVETMPS; PUSHMARK(SP);
XPUSHs(sv_2mortal(newRV_inc(ss->sv_ss)));
mXPUSHi(reason);
mXPUSHp(message, message_len);
mXPUSHp(language, language_len);
PUTBACK;
count = call_sv(ss->rgsv_cb[LIBSSH2_CALLBACK_DISCONNECT], G_VOID);
SPAGAIN; SP -= count; ax = (SP - PL_stack_base) + 1;
PUTBACK; FREETMPS; LEAVE;
}
/* thunk to call perl SSH_MSG_MACERROR packet function */
static LIBSSH2_MACERROR_FUNC(cb_macerror_callback) {
SSH2* ss = (SSH2*)*abstract;
int ret = 0;
dSP; I32 ax; int count;
ENTER; SAVETMPS; PUSHMARK(SP);
XPUSHs(sv_2mortal(newRV_inc(ss->sv_ss)));
mXPUSHp(packet, packet_len);
PUTBACK;
count = call_sv(ss->rgsv_cb[LIBSSH2_CALLBACK_MACERROR], G_SCALAR);
SPAGAIN; SP -= count ; ax = (SP - PL_stack_base) + 1;
if (count > 0)
ret = SvIV(ST(0));
PUTBACK; FREETMPS; LEAVE;
return ret;
}
/* thunk to call perl X11 forwarder packet function */
static LIBSSH2_X11_OPEN_FUNC(cb_x11_open_callback) {
SSH2* ss = (SSH2*)*abstract;
dSP; I32 ax; int count;
ENTER; SAVETMPS; PUSHMARK(SP);
XPUSHs(sv_2mortal(newRV_inc(ss->sv_ss)));
/*TODO: we actually need to push a channel here, but we don't know the
* SV of the channel (use a local hash?) */
XPUSHs(&PL_sv_undef);
mXPUSHp(shost, strlen(shost));
mXPUSHi(sport);
PUTBACK;
count = call_sv(ss->rgsv_cb[LIBSSH2_CALLBACK_X11], G_VOID);
SPAGAIN; SP -= count ; ax = (SP - PL_stack_base) + 1 ;
PUTBACK; FREETMPS; LEAVE;
}
void * cb_as_void_ptr(void (*cb)()) {
void * addr;
memcpy(&addr, &cb, sizeof addr);
return addr;
}
static void (*msg_cb[])() = {
(void (*)())cb_ignore_callback,
(void (*)())cb_debug_callback,
(void (*)())cb_disconnect_callback,
(void (*)())cb_macerror_callback,
(void (*)())cb_x11_open_callback
};
#define MY_CXT_KEY "Net::SSH2::_guts" XS_VERSION
#ifdef HAVE_GCRYPT
#ifndef WIN32
GCRY_THREAD_OPTION_PTHREAD_IMPL;
#else
GCRY_THREAD_OPTION_PTH_IMPL;
#endif
#endif
typedef struct {
HV* global_cb_data;
UV tid;
} my_cxt_t;
START_MY_CXT
static UV get_my_thread_id(void) /* returns threads->tid() value */
{
dSP;
UV tid = 0;
int count = 0;
#ifdef USE_ITHREADS
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs(sv_2mortal(newSVpv("threads", 0)));
PUTBACK;
count = call_method("tid", G_SCALAR|G_EVAL);
SPAGAIN;
if (SvTRUE(ERRSV) || count != 1)
/* if threads not loaded or an error occurs return 0 */
tid = 0;
else
tid = (UV)POPi;
PUTBACK;
FREETMPS;
LEAVE;
#endif
return tid;
}
#if defined(USE_ITHREADS) && !defined(HAVE_GCRYPT)
/* IMPORTANT NOTE:
* openssl locking was implemented according to http://www.openssl.org/docs/crypto/threads.html
* we implement both static and dynamic locking as described on URL above
* locking is supported when OPENSSL_THREADS macro is defined which means openssl-0.9.7 or newer
* we intentionally do not implement cleanup of openssl's threading as it causes troubles
* with apache-mpm-worker+mod_perl+mod_ssl+net-ssleay
*/
static perl_mutex *GLOBAL_openssl_mutex = NULL;
static void openssl_locking_function(int mode, int type, const char *file, int line)
{
if (!GLOBAL_openssl_mutex) return;
if (mode & CRYPTO_LOCK)
MUTEX_LOCK(&GLOBAL_openssl_mutex[type]);
else
MUTEX_UNLOCK(&GLOBAL_openssl_mutex[type]);
}
#if OPENSSL_VERSION_NUMBER < 0x10000000L
static unsigned long openssl_threadid_func(void)
{
dMY_CXT;
return (unsigned long)(MY_CXT.tid);
}
#else
static void openssl_threadid_func(CRYPTO_THREADID *id)
{
dMY_CXT;
CRYPTO_THREADID_set_numeric(id, (unsigned long)(MY_CXT.tid));
}
#endif
struct CRYPTO_dynlock_value
{
perl_mutex mutex;
};
static struct CRYPTO_dynlock_value *openssl_dynlocking_create_function(const char *file, int line)
{
struct CRYPTO_dynlock_value *retval;
New(0, retval, 1, struct CRYPTO_dynlock_value);
if (!retval) return NULL;
MUTEX_INIT(&retval->mutex);
return retval;
}
static void openssl_dynlocking_lock_function(int mode, struct CRYPTO_dynlock_value *l, const char *file, int line)
{
if (!l) return;
if (mode & CRYPTO_LOCK)
MUTEX_LOCK(&l->mutex);
else
MUTEX_UNLOCK(&l->mutex);
}
static void openssl_dynlocking_destroy_function(struct CRYPTO_dynlock_value *l, const char *file, int line)
{
if (!l) return;
MUTEX_DESTROY(&l->mutex);
Safefree(l);
}
static void openssl_threads_init(void)
{
int i;
/* initialize static locking */
if ( !CRYPTO_get_locking_callback() ) {
#if OPENSSL_VERSION_NUMBER < 0x10000000L
if ( !CRYPTO_get_id_callback() ) {
#else
if ( !CRYPTO_THREADID_get_callback() ) {
#endif
New(0, GLOBAL_openssl_mutex, CRYPTO_num_locks(), perl_mutex);
if (!GLOBAL_openssl_mutex) return;
for (i=0; i<CRYPTO_num_locks(); i++) MUTEX_INIT(&GLOBAL_openssl_mutex[i]);
CRYPTO_set_locking_callback(openssl_locking_function);
#ifndef WIN32
/* no need for threadid_func() on Win32 */
#if OPENSSL_VERSION_NUMBER < 0x10000000L
CRYPTO_set_id_callback(openssl_threadid_func);
#else
CRYPTO_THREADID_set_callback(openssl_threadid_func);
#endif
#endif
}
}
/* initialize dynamic locking */
if ( !CRYPTO_get_dynlock_create_callback() &&
!CRYPTO_get_dynlock_lock_callback() &&
!CRYPTO_get_dynlock_destroy_callback() ) {
CRYPTO_set_dynlock_create_callback(openssl_dynlocking_create_function);
CRYPTO_set_dynlock_lock_callback(openssl_dynlocking_lock_function);
CRYPTO_set_dynlock_destroy_callback(openssl_dynlocking_destroy_function);
}
}
#else
/* no threads */
static void openssl_threads_init(void)
{
}
#endif
static void
croak_last_error(SSH2 *ss, const char *class, const char *method) {
char *errmsg = NULL;
int err = libssh2_session_last_error(ss->session, &errmsg, NULL, 0);
croak("%s::%s: %s (%d)", class, method, errmsg, err);
}
#define CROAK_LAST_ERROR(session, method) (croak_last_error((session), class, (method)))
#if LIBSSH2_VERSION_NUM < 0x010601
#define libssh2_session_set_last_error(ss, errcode, errmsg) 0
#endif
static void
save_eagain(LIBSSH2_SESSION *session, int error) {
if (error == LIBSSH2_ERROR_EAGAIN)
libssh2_session_set_last_error(session, LIBSSH2_ERROR_EAGAIN, "Operation would block");
}
/* perl module exports */
MODULE = Net::SSH2 PACKAGE = Net::SSH2 PREFIX = net_ss_
PROTOTYPES: DISABLE
INCLUDE: const-xs.inc
BOOT:
{
MY_CXT_INIT;
#ifdef HAVE_GCRYPT
gcry_error_t ret;
#ifndef WIN32
ret = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
#else
ret = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
#endif
if (gcry_err_code(ret) != GPG_ERR_NO_ERROR)
croak("could not initialize libgcrypt for threads (%d: %s/%s)",
gcry_err_code(ret),
gcry_strsource(ret),
gcry_strerror(ret));
if (!gcry_check_version(GCRYPT_VERSION))
croak("libgcrypt version mismatch (needed: %s)", GCRYPT_VERSION);
#else /* OpenSSL */
openssl_threads_init();
MY_CXT.global_cb_data = newHV();
MY_CXT.tid = get_my_thread_id();
debug("Net::SSH2::BOOT: tid=%d my_perl=0x%p\n", MY_CXT.tid, my_perl);
#endif
}
#define class "Net::SSH2"
void
CLONE(...)
CODE:
MY_CXT_CLONE;
MY_CXT.global_cb_data = newHV();
MY_CXT.tid = get_my_thread_id();
debug("%s::CLONE: tid=%d my_perl=0x%p\n", class, MY_CXT.tid, my_perl);
IV
_parse_constant(char *prefix, SV *value)
CODE:
RETVAL = sv2iv_constant_or_croak(prefix, value);
OUTPUT:
RETVAL
SSH2*
net_ss__new(SV* proto)
CODE:
Newz(0/*id*/, RETVAL, 1, SSH2);
if (RETVAL) {
RETVAL->session = libssh2_session_init_ex(
local_alloc, local_free, local_realloc, RETVAL);
}
if (!RETVAL || !RETVAL->session) {
Safefree(RETVAL);
XSRETURN_EMPTY;
}
debug("Net::SSH2: created new object 0x%x\n", RETVAL);
OUTPUT:
RETVAL
void
net_ss_trace(SSH2* ss, IV bitmask)
CODE:
libssh2_trace(ss->session, bitmask);
#if LIBSSH2_VERSION_MAJOR >= 1
IV
net_ss_block_directions(SSH2* ss)
CODE:
RETVAL = libssh2_session_block_directions(ss->session);
OUTPUT:
RETVAL
#else
void
net_ss_block_directions(SSH2* ss)
CODE:
croak("libssh2 version 1.0 or higher required for block_directions support");
#endif
#if LIBSSH2_VERSION_NUM >= 0x010209
SV *
net_ss_timeout(SSH2* ss, SV *timeout = &PL_sv_undef)
PREINIT:
long r;
CODE:
if (items > 1)
libssh2_session_set_timeout(ss->session,
(SvOK(timeout) ? SvUV(timeout) : 0));
r = libssh2_session_get_timeout(ss->session);
RETVAL = (r > 0 ? newSVuv(r) : &PL_sv_undef);
OUTPUT:
RETVAL
#else
void
net_ss_timeout(SSH2* ss, long timeout)
CODE:
croak("libssh2 version 1.2.9 or higher required for set_timeout support");
#endif
SSH2_BOOL
net_ss_blocking(SSH2* ss, SSH2_BOOL blocking = 0)
CODE:
if (items > 1)
libssh2_session_set_blocking(ss->session, blocking);
RETVAL = libssh2_session_get_blocking(ss->session);
OUTPUT:
RETVAL
void
net_ss_DESTROY(SSH2* ss)
CODE:
debug("%s::DESTROY object 0x%x\n", class, ss);
libssh2_session_free(ss->session);
if (ss->socket)
SvREFCNT_dec(ss->socket);
if (ss->hostname)
SvREFCNT_dec(ss->hostname);
Safefree(ss);
void
net_ss_debug(SV*, IV debug)
CODE:
net_ss_debug_out = debug & 1; /* allow for future flags */
void
net_ss_version(...)
PPCODE:
EXTEND(SP, 3);
ST(0) = sv_2mortal(newSVpv(LIBSSH2_VERSION, 0));
if (GIMME_V != G_ARRAY)
XSRETURN(1);
#ifdef LIBSSH2_VERSION_NUM
ST(1) = sv_2mortal(newSVuv(LIBSSH2_VERSION_NUM));
#else
ST(1) = &PL_sv_undef;
#endif