~callum/gmsfn

ref: ef6eb96daa662e69f429ac98feeb497127dfbbd9 gmsfn/src/gmsfn.c -rw-r--r-- 11.4 KiB
ef6eb96dCallum Brown Prepend temp file to output file 1 year, 7 months ago
                                                                                
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
#include <stdio.h>
#include <openssl/err.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include "gmni.h"
#include "tofu.h"
#include "url.h"

/* From gmni.c */
struct tofu_config {
	struct gemini_tofu tofu;
	enum tofu_action action;
};

/* From gmni.c */
static enum tofu_action
tofu_callback(enum tofu_error error, const char *fingerprint,
	struct known_host *host, void *data)
{
	struct tofu_config *cfg = (struct tofu_config *)data;
	enum tofu_action action = cfg->action;
	switch (error) {
	case TOFU_VALID:
		assert(0); // Invariant
	case TOFU_INVALID_CERT:
		fprintf(stderr,
			"The server presented an invalid certificate with fingerprint %s.\n",
			fingerprint);
		if (action == TOFU_TRUST_ALWAYS) {
			action = TOFU_TRUST_ONCE;
		}
		break;
	case TOFU_UNTRUSTED_CERT:
		fprintf(stderr,
			"The certificate offered by this server is of unknown trust. "
			"Its fingerprint is: \n"
			"%s\n\n"
			"Use -j once to trust temporarily, or -j always to add to the trust store.\n", fingerprint);
		break;
	case TOFU_FINGERPRINT_MISMATCH:
		fprintf(stderr,
			"The certificate offered by this server DOES NOT MATCH the one we have on file.\n"
			"/!\\ Someone may be eavesdropping on or manipulating this connection. /!\\\n"
			"The unknown certificate's fingerprint is:\n"
			"%s\n\n"
			"The expected fingerprint is:\n"
			"%s\n\n"
			"If you're certain that this is correct, edit %s:%d\n",
			fingerprint, host->fingerprint,
			cfg->tofu.known_hosts_path, host->lineno);
		return TOFU_FAIL;
	}

	if (action == TOFU_ASK) {
		return TOFU_FAIL;
	}

	return action;
}


/* From gmnlm.c */
static char *
trim_ws(char *in)
{
	while (*in && isspace(*in)) ++in;
	return in;
}


/* Determine whether the response can be used. */
const bool
bad_response(enum gemini_result r, struct gemini_response *resp)
{
	/* Check response */
	if (r != GEMINI_OK) {
		fprintf(stderr, "Error: %s\n", gemini_strerr(r, resp));
		return true;
	}

	/* Check request was successful */
	if (gemini_response_class(resp->status) != GEMINI_STATUS_CLASS_SUCCESS) {
		fprintf(stderr, "Error: Unsuccessful request. Status: %d %s\n",
			resp->status, resp->meta);
		return true;
	}

	/* Check response is Gemtext */
	if (strncmp(resp->meta, "text/gemini", 11) != 0) {
		fprintf(stderr, "Error: Response is not text/gemini. Meta: %s\n",
			resp->meta);
		return true;
	}

	return false;
}


/* Return string up to and including the last '/' */
char *
strip_filename(const char *path)
{
	size_t last_slash = 0;
	for (size_t i = 0; i < strlen(path); ++i) {
		if (path[i] == '/')
			last_slash = ++i;
	}
	return strndup(path, last_slash);
}


/* Add scheme and domain to url if needed */
char *
get_absolute_url(char *url, char *base_url)
{
	bool absolute = true, colon = false, slash = false;
	size_t i = 0;
	while ((i < strlen(url)) && absolute) {
		switch (url[i]) {
		case ':':
			if (i == 0 || colon) {
				/* If colon is first char, or if there has already been a
					colon, then no scheme */
				absolute = false;
				break;
			} else {
				/* This is the first colon */
				colon = true;
				break;
			}
		case '/':
			if (colon && slash) {
				/* Last 2 chars were ":/" so url has scheme. Assuming there is
					a valid domain after, url is absolute. */
				return url;
			} else if (colon) {
				/* This slash directly follows a colon */
				slash = true;
				break;
			} else {
				/* This slash is before any colon, so no scheme */
				absolute = false;
				break;
			}
		default:
			/* If there has been a colon but this character is not a slash,
				then the url is not absolute. Break the loop. */
			if (colon)
				absolute = false;
		}
		++i;
	}
	/* Remove leading slashes */
	while (*url && (*url == '/')) ++url;
	/* Prepend base_url to url */
	char *abs_url = malloc(strlen(base_url) + strlen(url) + 1);
	strcpy(abs_url, base_url);
	return strcat(abs_url, url);
}


/* Append path2 to path1, delete path2, rename path1 to path2. */
int
cat_and_rename(char *path1, char *path2)
{
	FILE *fp1 = fopen(path1, "a");
	if (!fp1) {
		fprintf(stderr, "Could not open %s for appending.\n", path1);
		return 1;
	}
	FILE *fp2 = fopen(path2, "r");
	if (!fp2) {
		fprintf(stderr, "Could not open %s for reading.\n", path2);
		return 1;
	}
	char buf[BUFSIZ];
	while (fgets(buf, BUFSIZ, fp2) != NULL) {
		fputs(buf, fp1);
	}
	fclose(fp1);
	fclose(fp2);
	if (remove(path2) != 0) {
		fprintf(stderr, "Could not delete %s\n", path2);
	}
	if (rename(path1, path2) != 0) {
		fprintf(stderr, "Could not rename %s to %s\n", path1, path2);
		return 1;
	}
	return 0;
}


int
make_response_from_file(struct gemini_response *resp, FILE *fp) {
	BIO *file = BIO_new_fp(fp, BIO_CLOSE);
	resp->bio = BIO_new(BIO_f_buffer());
	BIO_push(resp->bio, file);
	resp->meta = strdup("text/gemini");
	resp->status = GEMINI_STATUS_SUCCESS;
	resp->fd = -1;
	resp->ssl = NULL;
	resp->ssl_ctx = NULL;
	return 0;
}


const bool
token_is_heading(struct gemini_token tok, int heading_level)
{
	if (tok.token == GEMINI_HEADING) {
		return tok.heading.level == heading_level;
	} else {
		return false;
	}
}


const bool
token_is_good_link(struct gemini_token tok)
{
	if (tok.token == GEMINI_LINK) {
		return (strlen(tok.link.url) != 0) && (tok.link.url != NULL);
	} else {
		return false;
	}
}


int
main(int argc, char *argv[])
{
	/* Must have exactly one argument */
	if (argc != 2) {
		fprintf(stderr, "Usage: gmsfn /path/to/config/file.gmi");
		return 1;
	}

	/* Open config file */
	FILE *config_fp = fopen(argv[1], "r");
	if (!config_fp) {
		fprintf(stderr, "Failed to access config file %s.\n", argv[1]);
		return 1;
	}
	char *config_dir = strip_filename(argv[1]);

	/* Setup for using gmni */
	struct addrinfo hints = {0};
	struct gemini_options opts = {
		.hints = &hints,
	};
	struct tofu_config cfg;
	cfg.action = TOFU_ASK;
	SSL_load_error_strings();
	ERR_load_crypto_strings();
	opts.ssl_ctx = SSL_CTX_new(TLS_method());
	gemini_tofu_init(&cfg.tofu, opts.ssl_ctx, &tofu_callback, &cfg);

	/* Make a gmni response from the config file */
	struct gemini_response config_resp;
	make_response_from_file(&config_resp, config_fp);

	/* Parse config file */
	bool absolute = true, good_output_file = false;
	char *out_path, *tmp_out_path, **existing_links;
	FILE *tmp_out_fp;
	int num_existing_links = 0;
	struct gemini_parser config_parser;
	struct gemini_token config_tok;
	gemini_parser_init(&config_parser, config_resp.bio);

	while (gemini_parser_next(&config_parser, &config_tok) == 0) {
		/* Change output file */
		if (token_is_heading(config_tok, 3)) {
			/* Clear up from previous output file */
			if (good_output_file) {
				fclose(tmp_out_fp);
				free(existing_links);
				cat_and_rename(tmp_out_path, out_path);
				free(tmp_out_path);
			}
			if (!absolute) {
				free(out_path);
			}

			/* Get path to the output file. If it does not start with '/'
				assume relative to the directory the config file is in */
			char *path = trim_ws(config_tok.heading.title);
			if ((absolute = path[0] == '/')) {
				out_path = path;
			} else {
				out_path = malloc(strlen(config_dir) + strlen(path) + 1);
				strcpy(out_path, config_dir);
				strcat(out_path, path);
			}

			/* If file doesn't exist then it can't be read from so it says it
				is bad. TODO: auto-create output files if needed. */
			FILE *count_fp = fopen(out_path, "r");
			if (!count_fp) {
				printf("Bad output file: %s\n", out_path);
				/* Skip links until a new output file is given */
				good_output_file = false;
				continue;
			}

			/* TODO: Find a way to re-use file pointer and gemini structures.
				It seems a bit silly to close and re-create, but it might be
				the only way. */

			/* Count number of links in output file */
			struct gemini_response count_resp;
			struct gemini_parser count_parser;
			struct gemini_token count_tok;
			make_response_from_file(&count_resp, count_fp);
			gemini_parser_init(&count_parser, count_resp.bio);
			num_existing_links = 0;
			while (gemini_parser_next(&count_parser, &count_tok) == 0) {
				if (token_is_good_link(count_tok)) {
					++num_existing_links;
				}
			}
			gemini_token_finish(&count_tok);
			gemini_parser_finish(&count_parser);
			gemini_response_finish(&count_resp); // Closes count_fp

			/* Copy link urls in output file into existing_links */
			if (num_existing_links > 0) {
				/* We know this fopen will work from earlier */
				FILE *copy_fp = fopen(out_path, "r");
				struct gemini_response copy_resp;
				struct gemini_parser copy_parser;
				struct gemini_token copy_tok;
				int i = 0;
				/* Contains pointers to strings */
				existing_links = (char **) malloc(num_existing_links * sizeof(char *));
				make_response_from_file(&copy_resp, copy_fp);
				gemini_parser_init(&copy_parser, copy_resp.bio);
				while (gemini_parser_next(&copy_parser, &copy_tok) == 0) {
					if (token_is_good_link(copy_tok)) {
						*(existing_links + i) = copy_tok.link.url;
						++i;
					}
				}
				gemini_token_finish(&copy_tok);
				gemini_parser_finish(&copy_parser);
				gemini_response_finish(&copy_resp); // Closes copy_fp
			}

			/* Make a temporary output file which new links will be written to.
				The existing output file will be appended to it before being
				deleted, then the temporary file will be renamed. (TODO)*/
			tmp_out_path = malloc(strlen(out_path) + 5);
			strcpy(tmp_out_path, out_path);
			strcat(tmp_out_path, "-tmp");
			tmp_out_fp = fopen(tmp_out_path, "w");
			if (!tmp_out_fp) {
				fprintf(stderr, "Could not open temporary output file.");
				free(tmp_out_path);
				good_output_file = false;
			}
			good_output_file = true;

		/* Make requests and output links */
		} else if (good_output_file && token_is_good_link(config_tok)) {
			/* Get gemlog index page */
			struct gemini_response resp;
			enum gemini_result r = gemini_request(config_tok.link.url, &opts, &resp);
			if (bad_response(r, &resp)) {
				fprintf(stderr, "Could not access %s.\n", config_tok.link.url);
				gemini_response_finish(&resp);
				/* Go to next link in config file */
				continue;
			}

			/* Parse gemlog index page */
			char *abs_url, *base_url = strip_filename(config_tok.link.url);
			struct gemini_parser p;
			struct gemini_token tok;
			gemini_parser_init(&p, resp.bio);

			while (gemini_parser_next(&p, &tok) == 0) {
				if (token_is_good_link(tok)) {
					abs_url = get_absolute_url(tok.link.url, base_url);
					/* Work out if abs_url is already in the output file. */
					bool link_already_exists = false;
					for (int i = 0; i < num_existing_links; ++i) {
						if (strcmp(abs_url, *(existing_links + i)) == 0) {
							link_already_exists = true;
							break;
						}
					}
					/* If it isn't then add it to the temporary file */
					if (!link_already_exists) {
						fprintf(tmp_out_fp, "=> %s", abs_url);
						if (config_tok.link.text) {
							fprintf(tmp_out_fp, " %s", config_tok.link.text);
						}
						if (config_tok.link.text && tok.link.text) {
							fprintf(tmp_out_fp, ":");
						}
						if (tok.link.text) {
							fprintf(tmp_out_fp, " %s", tok.link.text);
						}
						fprintf(tmp_out_fp, "\n");
					}
					free(abs_url);
				}
			}

			gemini_token_finish(&tok);
			gemini_parser_finish(&p);
			gemini_response_finish(&resp);
		}
	}

	/* Clear up from previous output file */
	if (good_output_file) {
		fclose(tmp_out_fp);
		free(existing_links);
		cat_and_rename(tmp_out_path, out_path);
		free(tmp_out_path);
	}
	if (!absolute) {
		free(out_path);
	}

	gemini_token_finish(&config_tok);
	gemini_parser_finish(&config_parser);
	gemini_response_finish(&config_resp); // Closes config_fp
	gemini_tofu_finish(&cfg.tofu);
	SSL_CTX_free(opts.ssl_ctx);
	return 0;
}