~panda-roux/MoonGem

ref: 89faa1b6603d57249eedc6f5989fa1ae2d008d2a MoonGem/src/gemini.c -rw-r--r-- 10.8 KiB
89faa1b6 — panda-roux clang-tidy 8 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
#include "gemini.h"

#define GNU_SOURCE

#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/bufferevent_ssl.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <magic.h>
#include <openssl/ssl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#include "cert.h"
#include "log.h"
#include "net.h"
#include "parse.h"
#include "status.h"
#include "uri.h"
#include "util.h"

#define CRLF "\r\n"
#define TAG_DELIMITER ";"
#define MAX_URL_LENGTH 1024
#define MIMETYPE_GEMTEXT "text/gemini; encoding=utf-8"
#define DEFAULT_MIMETYPE "application/octet-stream"

#define SIGNAL_HANDLERS_COUNT 4
#define LISTENER_EVFLAGS \
  (LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE | LEV_OPT_CLOSE_ON_EXEC)

typedef struct gemini_listener_t {
  struct evconnlistener* listener;
  cli_options_t* options;
  net_t* net;
  struct magic_set* magic;
} gemini_listener_t;

typedef struct context_t {
  gemini_context_t gemini;
  file_info_t file;
  struct evbuffer* out;
  SSL* ssl;
  cli_options_t* options;
  struct magic_set* magic;
} context_t;

static client_cert_t* create_client_cert() {
  client_cert_t* cert = malloc(sizeof(client_cert_t));
  if (cert == NULL) {
    LOG_ERROR("Failed to allocate memory for client cert object");
    return NULL;
  }

  cert->fingerprint = NULL;
  cert->not_after = 0;
  cert->initialized = false;

  return cert;
}

static void event_cb(struct bufferevent* bev, short evt, void* data) {
  if (evt & BEV_EVENT_EOF || evt & BEV_EVENT_ERROR) {
    LOG_DEBUG("Freeing connection buffer and context data");

    context_t* ctx = (context_t*)data;
    if (ctx != NULL) {
      request_t* req = &ctx->gemini.request;

      if (req->cert != NULL) {
        destroy_client_cert(req->cert);
      }

      if (req->uri != NULL) {
        destroy_uri(req->uri);
      }

      evbuffer_free(ctx->out);

      if (ctx->file.ptr != NULL) {
        fclose(ctx->file.ptr);
      }

      free(ctx);
    }

    bufferevent_free(bev);
  }
}

static void end_response_cb(struct bufferevent* bev, void* data) {
  bufferevent_flush(bev, EV_WRITE, BEV_FINISHED);
  bufferevent_trigger_event(bev, BEV_EVENT_EOF | BEV_EVENT_WRITING, 0);
}

static void write_header(context_t* ctx) {
  gemini_context_t* gemini = &ctx->gemini;
  response_t* res = &gemini->response;
  struct evbuffer* out = ctx->out;

  evbuffer_add_printf(out, "%d", res->status);

  // write meta
  bool has_tags = false;
  if (response_has_meta(res)) {
    evbuffer_add_printf(out, " %s", &res->meta[0]);
    has_tags = true;
  }

  // write mimetype
  if (response_has_mime(res)) {
    if (has_tags) {
      evbuffer_add(out, TAG_DELIMITER, sizeof(TAG_DELIMITER) - 1);
    }

    evbuffer_add_printf(out, " %s", &res->mimetype[0]);
    has_tags = true;
  }

  // write language
  if (response_has_lang(res)) {
    if (has_tags) {
      evbuffer_add(out, TAG_DELIMITER, sizeof(TAG_DELIMITER) - 1);
    }

    evbuffer_add_printf(out, " lang=%s", &res->language[0]);
  }

  // terminate header
  evbuffer_add(out, CRLF, sizeof(CRLF) - 1);
}

static void serve_static_file_cb(struct bufferevent* bev, void* data) {
  context_t* ctx = (context_t*)data;
  file_info_t* file = &ctx->file;

  size_t remaining = ctx->file.size - ctx->file.offset;

  // while there remains data to be buffered, load another block
  if (remaining > 0) {
    size_t chunk_size = ctx->options->chunk_size;
    size_t length = remaining > chunk_size ? chunk_size : remaining;
    struct evbuffer_file_segment* segment =
        evbuffer_file_segment_new(file->fd, file->offset, length, 0);
    evbuffer_add_file_segment(ctx->out, segment, 0, -1);
    evbuffer_file_segment_free(segment);

    LOG_DEBUG("Buffering %zu bytes (%zu/%ld)", length,
              ctx->file.offset + length, ctx->file.size);

    file->offset += length;

    bufferevent_write_buffer(bev, ctx->out);
  } else {
    // the entire file has been sent
    bufferevent_setcb(bev, NULL, end_response_cb, event_cb, ctx);
    bufferevent_trigger(bev, EV_WRITE, 0);
  }
}

static void send_status_response(context_t* ctx, struct bufferevent* bev) {
  // write the response header
  write_header(ctx);

  // write the response to the socket and terminate
  bufferevent_write_buffer(bev, ctx->out);
  bufferevent_setcb(bev, NULL, end_response_cb, event_cb, ctx);
}

static void send_script_response(context_t* ctx, struct bufferevent* bev) {
  response_t* res = &ctx->gemini.response;

  LOG_DEBUG("Sending gemtext response");

  // parse the gemtext file and run any scripts found within
  parser_t* parser = create_doc_parser(&ctx->gemini, &ctx->file);
  struct evbuffer* rendered = evbuffer_new();
  parse_gemtext_doc(parser, rendered);
  destroy_doc_parser(parser);

  if (res->interrupted || res->status != STATUS_DEFAULT) {
    // a status code was set by the script, so the rendered body should not be
    // sent to the client
    evbuffer_free(rendered);
    send_status_response(ctx, bev);
    return;
  }

  set_response_mime(res, MIMETYPE_GEMTEXT);

  // write the response header to a buffer, followed by the rendered gemtext
  write_header(ctx);
  evbuffer_add_buffer(ctx->out, rendered);
  evbuffer_free(rendered);

  // write the response to the socket and terminate
  bufferevent_write_buffer(bev, ctx->out);
  bufferevent_setcb(bev, NULL, end_response_cb, event_cb, ctx);
}

static void send_file_response(context_t* ctx, struct bufferevent* bev) {
  request_t* req = &ctx->gemini.request;
  response_t* res = &ctx->gemini.response;

  LOG_DEBUG("Sending non-gemtext file");

  const char* mimetype = magic_descriptor(ctx->magic, ctx->file.fd);

  if (mimetype == NULL) {
    LOG("Could not determine mimetype of %s; using the default (%s)",
        req->uri->path, DEFAULT_MIMETYPE);
    mimetype = DEFAULT_MIMETYPE;
  }

  set_response_mime(res, mimetype);

  // write response header
  write_header(ctx);
  bufferevent_write_buffer(bev, ctx->out);

  // serve the file
  bufferevent_setcb(bev, NULL, serve_static_file_cb, event_cb, ctx);
}

static void write_response_cb(struct bufferevent* bev, void* data) {
  context_t* ctx = (context_t*)data;

  if (ctx->gemini.response.status == STATUS_DEFAULT) {
    if (ctx->gemini.request.uri->type == URI_TYPE_GEMTEXT) {
      send_script_response(ctx, bev);
    } else {
      send_file_response(ctx, bev);
    }
  } else {
    send_status_response(ctx, bev);
  }
}

static void read_cb(struct bufferevent* bev, void* data) {
  context_t* ctx = (context_t*)data;
  request_t* req = &ctx->gemini.request;
  response_t* res = &ctx->gemini.response;
  file_info_t* file = &ctx->file;

  // read the entire request into a buffer
  char request_buffer[MAX_URL_LENGTH + 2] = {0};
  bufferevent_read(bev, &request_buffer[0],
                   sizeof(request_buffer) / sizeof(char));

  // extract the uri
  req->uri = create_uri(&request_buffer[0]);

  if (req->uri == NULL) {
    set_response_status(res, STATUS_BAD_REQUEST, META_BAD_REQUEST);
  } else {
    // set the client certificate if one exists
    client_cert_t* cert =
        (client_cert_t*)SSL_get_ex_data(ctx->ssl, CLIENT_CERT_INDEX);
    if (cert != NULL) {
      req->cert = cert;
    }

    // check whether the requested file exists
    struct stat st;
    if (stat(req->uri->path, &st) != 0 || !S_ISREG(st.st_mode)) {
      LOG_DEBUG("File %s does not exist", req->uri->path);
      set_response_status(res, STATUS_NOT_FOUND, META_NOT_FOUND);
    } else {
      LOG_DEBUG("File %s exists", req->uri->path);
      file->ptr = fopen(req->uri->path, "rb");
      if (file->ptr == NULL) {
        LOG_ERROR("Failed to open file at \"%s\"", req->uri->path);

        // if we can't open the file, it may be due to being denied permissions,
        // which is may have been intentional if the host doesn't want the files
        // to be served; tell the client they don't exist
        set_response_status(res, STATUS_NOT_FOUND, META_NOT_FOUND);
      } else {
        // file exists and was opened successfully
        file->fd = fileno(file->ptr);
        file->size = st.st_size;
      }
    }
  }

  bufferevent_setcb(bev, NULL, write_response_cb, event_cb, ctx);
  bufferevent_trigger(bev, EV_WRITE, 0);
}

static void listener_cb(struct evconnlistener* listener, evutil_socket_t fd,
                        struct sockaddr* addr, int socklen, void* data) {
  gemini_listener_t* gemini = (gemini_listener_t*)data;

  SSL* ssl = SSL_new(gemini->net->ssl_ctx);
  SSL_set_ex_data(ssl, CLIENT_CERT_INDEX, create_client_cert());

  enum bufferevent_ssl_state ssl_status =
      fd != -1 ? BUFFEREVENT_SSL_ACCEPTING : BUFFEREVENT_SSL_CONNECTING;
  struct event_base* base = evconnlistener_get_base(listener);
  struct bufferevent* bev = bufferevent_openssl_socket_new(
      base, fd, ssl, ssl_status, BEV_OPT_CLOSE_ON_FREE);

  if (bev == NULL) {
    LOG_ERROR("Error constructing bufferevent!");
    event_base_loopbreak(base);
    return;
  }

  context_t* ctx = calloc(1, sizeof(context_t));
  ctx->ssl = ssl;
  ctx->out = evbuffer_new();
  ctx->gemini.response.status = STATUS_DEFAULT;
  ctx->magic = gemini->magic;
  ctx->options = gemini->options;

  bufferevent_setcb(bev, read_cb, NULL, event_cb, ctx);
  bufferevent_enable(bev, EV_READ);
}

static bool init_regex(void) {
  return init_uri_regex() == 0 && init_parser_regex() == 0;
}

static struct magic_set* init_magic(void) {
  struct magic_set* magic = magic_open(MAGIC_MIME | MAGIC_CHECK);
  if (magic != NULL) {
    magic_load(magic, NULL);
  }
  return magic;
}

gemini_listener_t* init_gemini_listener(cli_options_t* options,
                                        struct event_base* evtbase) {
  if (!init_regex()) {
    LOG_ERROR("Failed to compile gemini regex");
    return NULL;
  }

  gemini_listener_t* gemini = calloc(1, sizeof(gemini_listener_t));

  gemini->magic = init_magic();
  if (gemini->magic == NULL) {
    LOG_ERROR("Failed to load libmagic database");
    goto cleanup;
  }

  // set up socket + TLS
  gemini->net = init_net(options);
  if (gemini->net == NULL) {
    LOG_ERROR("Failed to initialize socket for Gemini listener");
    goto cleanup;
  }

  gemini->options = options;

  gemini->listener =
      evconnlistener_new_bind(evtbase, listener_cb, gemini, LISTENER_EVFLAGS,
                              -1, gemini->net->addr, gemini->net->addr_size);
  if (gemini->listener == NULL) {
    LOG_ERROR("Failed to create event listener");
    goto cleanup;
  }

  return gemini;

cleanup:
  cleanup_gemini_listener(gemini);
  return NULL;
}

void cleanup_gemini_listener(gemini_listener_t* gemini) {
  cleanup_uri_regex();
  cleanup_parser_regex();

  if (gemini == NULL) {
    return;
  }

  if (gemini->listener != NULL) {
    evconnlistener_free(gemini->listener);
  }

  if (gemini->net != NULL) {
    destroy_net(gemini->net);
  }

  if (gemini->magic != NULL) {
    magic_close(gemini->magic);
  }

  free(gemini);
}

void set_response_status(response_t* response, int code, const char* meta) {
  response->status = code;
  set_response_meta(response, meta);
}