-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
106 lines (81 loc) · 1.95 KB
/
main.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "client.h"
#include "header.h"
#include "url.h"
#define MAX_BUFFER_LEN 2048
#define MAX_REDIRECTS 5
int
main(int argc, char *argv[])
{
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
int sockfd;
int n_bytes = 0;
int n_redirects = 0;
SSL *ssl;
SSL_CTX *ctx;
struct url *url = create_url();
struct gemini_header header;
char req[MAX_BUFFER_LEN];
char res[MAX_BUFFER_LEN];
if (argc < 2) {
fprintf(stderr, "usage: %s [domain]\n", argv[0]);
exit(EXIT_FAILURE);
}
parse_url(argv[1], url);
request:
sockfd = connect_to_domain(url->authority);
secure_connection(sockfd, &ctx, &ssl, url->authority);
memset(req, '\0', sizeof(req));
memset(res, '\0', sizeof(res));
sprintf(req, "gemini://%s%s%s\r\n",
url->authority, url->path, url->query ? url->query : "");
SSL_write(ssl, req, strlen(req));
SSL_read(ssl, res, sizeof(res));
parse_gemini_header(res, &header);
switch (header.status / 10) {
case GEMINI_INPUT:
puts(header.meta);
char input[MAX_BUFFER_LEN];
fgets(input, MAX_BUFFER_LEN, stdin);
append_query(input, url);
SSL_CTX_free(ctx);
SSL_shutdown(ssl);
SSL_free(ssl);
close(sockfd);
goto request;
case GEMINI_REDIRECT:
if (++n_redirects > MAX_REDIRECTS) {
fprintf(stderr, "Number of redirects exceeded maximum.\n");
exit(EXIT_FAILURE);
}
parse_url(header.meta, url);
SSL_CTX_free(ctx);
SSL_shutdown(ssl);
SSL_free(ssl);
close(sockfd);
goto request;
case GEMINI_SUCCESS:
while ((n_bytes = SSL_read(ssl, res, MAX_BUFFER_LEN)) != 0) {
fwrite(&res, 1, n_bytes, stdout);
if (ferror(stdout)) {
fprintf(stderr, "fwrite() failed.\n");
exit(EXIT_FAILURE);
}
}
break;
case GEMINI_TEMPORARY_FAILURE:
case GEMINI_PERMANENT_FAILURE:
fprintf(stderr, "%s", header.meta);
break;
}
SSL_CTX_free(ctx);
SSL_shutdown(ssl);
SSL_free(ssl);
free_url(url);
close(sockfd);
exit(EXIT_SUCCESS);
}