1 #include "session_fixture.h"
2
3 #include <libssh2.h>
4
5 #include <stdio.h>
6 #include <stdlib.h>
7
8 static const char *USERNAME = "libssh2"; /* set in Dockerfile */
9 static const char *KEY_FILE_ED25519_PRIVATE = "key_ed25519";
10
11 int read_file(const char *path, char **buf, size_t *len);
12
test(LIBSSH2_SESSION * session)13 int test(LIBSSH2_SESSION *session)
14 {
15 int rc;
16 char *buffer = NULL;
17 size_t len = 0;
18 const char *userauth_list = NULL;
19
20 userauth_list = libssh2_userauth_list(session, USERNAME, strlen(USERNAME));
21 if(userauth_list == NULL) {
22 print_last_session_error("libssh2_userauth_list");
23 return 1;
24 }
25
26 if(strstr(userauth_list, "publickey") == NULL) {
27 fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
28 userauth_list);
29 return 1;
30 }
31
32 if(read_file(KEY_FILE_ED25519_PRIVATE, &buffer, &len)) {
33 fprintf(stderr, "Reading key file failed.");
34 return 1;
35 }
36
37 rc = libssh2_userauth_publickey_frommemory(session,
38 USERNAME, strlen(USERNAME),
39 NULL, 0,
40 buffer, len,
41 NULL);
42
43 free(buffer);
44
45 if(rc != 0) {
46 print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
47 return 1;
48 }
49
50 return 0;
51 }
52
read_file(const char * path,char ** out_buffer,size_t * out_len)53 int read_file(const char *path, char **out_buffer, size_t *out_len)
54 {
55 FILE *fp = NULL;
56 char *buffer = NULL;
57 size_t len = 0;
58
59 if(out_buffer == NULL || out_len == NULL || path == NULL) {
60 fprintf(stderr, "invalid params.");
61 return 1;
62 }
63
64 *out_buffer = NULL;
65 *out_len = 0;
66
67 fp = fopen(path, "r");
68
69 if(!fp) {
70 fprintf(stderr, "File could not be read.");
71 return 1;
72 }
73
74 fseek(fp, 0L, SEEK_END);
75 len = ftell(fp);
76 rewind(fp);
77
78 buffer = calloc(1, len + 1);
79 if(!buffer) {
80 fclose(fp);
81 fprintf(stderr, "Could not alloc memory.");
82 return 1;
83 }
84
85 if(1 != fread(buffer, len, 1, fp)) {
86 fclose(fp);
87 free(buffer);
88 fprintf(stderr, "Could not read file into memory.");
89 return 1;
90 }
91
92 fclose(fp);
93
94 *out_buffer = buffer;
95 *out_len = len;
96
97 return 0;
98 }
99