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