Files
gotea/cgi/gotea.c
T
lotherk 802572bae9 feat(pages): build and publish bb sites on push
Add a Gotea Pages prototype: a pages branch is checked out with got, built with the vendored bb, swapped atomically into a pages root, and served only on a separate host from an allowlist. A post-receive hook installer wires the flow through Gitea delegate hooks. The CGI pages mode isolates the host and contains paths with realpath.

Assisted-by: OpenCode:DeepSeek-V4.1-Flash
2026-11-22 12:28:02 +00:00

2061 lines
47 KiB
C

/*
* gotea-cgi - HTML 4.01 frontend for gotea repositories
*
* Copyright 2026 The Gotea Authors. All rights reserved.
* SPDX-License-Identifier: MIT
*
* Read-only browser for bare Git-format repositories, using got(1) for all
* repository access. Output is HTML 4.01 Transitional and contains no
* JavaScript, so it works in text and pre-CSS browsers.
*/
#define _XOPEN_SOURCE 700
#define _POSIX_C_SOURCE 200809L
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#define PATHBUF 4096
#define MAX_SEGS 128
#define MAX_CAPTURE (4 * 1024 * 1024)
#define MAX_BLOB (512 * 1024)
#define GOT_TIMEOUT_SEC 20
struct buf {
char *p;
size_t len;
size_t cap;
};
struct palette {
char base[8];
char light[8];
char white[8];
char dark[8];
char shadow[8];
char text[8];
char link[8];
char visited[8];
char title_bg[8];
char title_fg[8];
};
struct repo {
char *name;
char *path;
};
struct path {
char *raw;
char *seg[MAX_SEGS];
size_t n;
};
static const char *g_script;
static const char *g_root;
static const char *g_got;
static int g_head_only;
static int g_pages_mode;
static const struct palette *g_pal;
static void *
xmalloc(size_t n)
{
void *p = malloc(n);
if (p == NULL) {
fputs("gotea-cgi: out of memory\n", stderr);
exit(1);
}
return p;
}
static void *
xrealloc(void *p, size_t n)
{
void *q = realloc(p, n);
if (q == NULL) {
fputs("gotea-cgi: out of memory\n", stderr);
exit(1);
}
return q;
}
static char *
xstrdup(const char *s)
{
size_t n = strlen(s) + 1;
char *p = xmalloc(n);
memcpy(p, s, n);
return p;
}
static void
b_init(struct buf *b)
{
b->p = NULL;
b->len = 0;
b->cap = 0;
}
static void
b_reserve(struct buf *b, size_t extra)
{
size_t need = b->len + extra + 1;
size_t cap;
if (need < b->len) {
fputs("gotea-cgi: buffer overflow\n", stderr);
exit(1);
}
if (need <= b->cap)
return;
cap = b->cap ? b->cap : 256;
while (cap < need) {
if (cap > SIZE_MAX / 2) {
fputs("gotea-cgi: buffer overflow\n", stderr);
exit(1);
}
cap *= 2;
}
b->p = xrealloc(b->p, cap);
b->cap = cap;
}
static void
b_putn(struct buf *b, const char *s, size_t n)
{
b_reserve(b, n);
memcpy(b->p + b->len, s, n);
b->len += n;
b->p[b->len] = '\0';
}
static void
b_puts(struct buf *b, const char *s)
{
b_putn(b, s, strlen(s));
}
static void
b_putc(struct buf *b, char c)
{
b_reserve(b, 1);
b->p[b->len++] = c;
b->p[b->len] = '\0';
}
static void
b_printf(struct buf *b, const char *fmt, ...)
{
va_list ap, ap2;
int n;
va_start(ap, fmt);
va_copy(ap2, ap);
n = vsnprintf(NULL, 0, fmt, ap);
va_end(ap);
if (n < 0) {
va_end(ap2);
return;
}
b_reserve(b, (size_t)n);
vsnprintf(b->p + b->len, (size_t)n + 1, fmt, ap2);
b->len += (size_t)n;
va_end(ap2);
}
static void
b_free(struct buf *b)
{
free(b->p);
b->p = NULL;
b->len = b->cap = 0;
}
static void
b_html(struct buf *b, const char *s)
{
for (; *s; s++) {
switch (*s) {
case '&': b_puts(b, "&amp;"); break;
case '<': b_puts(b, "&lt;"); break;
case '>': b_puts(b, "&gt;"); break;
case '"': b_puts(b, "&quot;"); break;
case '\'': b_puts(b, "&#39;"); break;
default: b_putc(b, *s); break;
}
}
}
static int
unreserved(unsigned char c)
{
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' ||
c == '~';
}
static void
b_url_path(struct buf *b, const char *s)
{
static const char hex[] = "0123456789ABCDEF";
for (; *s; s++) {
unsigned char c = (unsigned char)*s;
if (unreserved(c) || c == '/') {
b_putc(b, (char)c);
} else {
b_putc(b, '%');
b_putc(b, hex[c >> 4]);
b_putc(b, hex[c & 15]);
}
}
}
/* Link to gotea-cgi itself, with a literal suffix. */
static void
href_top(struct buf *b, const char *suffix)
{
b_puts(b, "<a href=\"");
b_url_path(b, g_script);
b_puts(b, suffix);
b_puts(b, "\">");
}
/* Link to /repo/<name>/<action>[/<path>]. */
static void
href_repo(struct buf *b, const char *action, const char *name,
const char *path)
{
b_puts(b, "<a href=\"");
b_url_path(b, g_script);
b_puts(b, "/repo/");
b_url_path(b, name);
b_puts(b, "/");
b_puts(b, action);
if (path != NULL && *path != '\0') {
b_putc(b, '/');
b_url_path(b, path);
}
b_puts(b, "\">");
}
static void
palette_defaults(struct palette *p)
{
strcpy(p->base, "#a0a0a0");
strcpy(p->light, "#d0d0d0");
strcpy(p->white, "#ffffff");
strcpy(p->dark, "#808080");
strcpy(p->shadow, "#404040");
strcpy(p->text, "#000000");
strcpy(p->link, "#000080");
strcpy(p->visited, "#551a8b");
strcpy(p->title_bg, "#000080");
strcpy(p->title_fg, "#ffffff");
}
static int
valid_color(const char *s)
{
size_t i, n;
if (s[0] != '#' || (n = strlen(s)) < 4 || n > 7)
return 0;
if (n != 4 && n != 7)
return 0;
for (i = 1; i < n; i++) {
if (!((s[i] >= '0' && s[i] <= '9') ||
(s[i] >= 'a' && s[i] <= 'f') ||
(s[i] >= 'A' && s[i] <= 'F')))
return 0;
}
return 1;
}
static void
palette_set(struct palette *p, const char *key, const char *val)
{
struct {
const char *key;
char *dst;
size_t len;
} fields[] = {
{ "base", p->base, sizeof(p->base) },
{ "light", p->light, sizeof(p->light) },
{ "white", p->white, sizeof(p->white) },
{ "dark", p->dark, sizeof(p->dark) },
{ "shadow", p->shadow, sizeof(p->shadow) },
{ "text", p->text, sizeof(p->text) },
{ "link", p->link, sizeof(p->link) },
{ "visited", p->visited, sizeof(p->visited) },
{ "title_bg", p->title_bg, sizeof(p->title_bg) },
{ "title_fg", p->title_fg, sizeof(p->title_fg) },
};
size_t i;
if (!valid_color(val))
return;
for (i = 0; i < sizeof(fields) / sizeof(fields[0]); i++) {
if (strcmp(fields[i].key, key) == 0) {
snprintf(fields[i].dst, fields[i].len, "%s", val);
return;
}
}
}
static void
palette_load(struct palette *p, const char *file)
{
FILE *f;
char line[256];
if (file == NULL || *file == '\0')
return;
f = fopen(file, "r");
if (f == NULL)
return;
while (fgets(line, sizeof(line), f) != NULL) {
char *eq, *key, *val, *end;
key = line;
while (*key == ' ' || *key == '\t')
key++;
if (*key == '#' || *key == '\n' || *key == '\0')
continue;
eq = strchr(key, '=');
if (eq == NULL)
continue;
*eq = '\0';
val = eq + 1;
end = key + strlen(key);
while (end > key && (end[-1] == ' ' || end[-1] == '\t'))
*--end = '\0';
while (*val == ' ' || *val == '\t')
val++;
end = val + strlen(val);
while (end > val && (end[-1] == '\n' || end[-1] == '\r' ||
end[-1] == ' ' || end[-1] == '\t'))
*--end = '\0';
palette_set(p, key, val);
}
fclose(f);
}
static const char *
env_or(const char *key, const char *def)
{
const char *v = getenv(key);
if (v == NULL || *v == '\0')
return def;
return v;
}
static int
hexval(int c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}
static char *
url_decode(const char *s)
{
char *out, *w;
out = xmalloc(strlen(s) + 1);
w = out;
while (*s) {
if (*s == '%') {
int a = hexval((unsigned char)s[1]);
int b = hexval((unsigned char)s[2]);
if (a < 0 || b < 0) {
free(out);
return NULL;
}
if ((a | b) == 0) {
free(out);
return NULL;
}
*w++ = (char)((a << 4) | b);
s += 3;
} else {
*w++ = *s++;
}
}
*w = '\0';
return out;
}
static int
split_path(struct path *p, const char *decoded)
{
char *s, *e;
memset(p, 0, sizeof(*p));
p->raw = xstrdup(decoded);
s = p->raw;
while (*s) {
while (*s == '/')
s++;
if (*s == '\0')
break;
e = strchr(s, '/');
if (e != NULL)
*e = '\0';
if (p->n >= MAX_SEGS)
return -1;
if (strcmp(s, ".") == 0 || strcmp(s, "..") == 0)
return -1;
p->seg[p->n++] = s;
if (e == NULL)
break;
s = e + 1;
}
return 0;
}
static char *
join_segs(struct path *p, size_t from)
{
struct buf b;
size_t i;
b_init(&b);
for (i = from; i < p->n; i++) {
if (i > from)
b_putc(&b, '/');
b_puts(&b, p->seg[i]);
}
if (b.p == NULL)
return xstrdup("");
return b.p;
}
static int
is_repo_dir(const char *path)
{
char tmp[PATHBUF];
struct stat st;
if (snprintf(tmp, sizeof(tmp), "%s/HEAD", path) >= (int)sizeof(tmp))
return 0;
if (stat(tmp, &st) != 0 || !S_ISREG(st.st_mode))
return 0;
if (snprintf(tmp, sizeof(tmp), "%s/objects", path) >= (int)sizeof(tmp))
return 0;
if (stat(tmp, &st) != 0 || !S_ISDIR(st.st_mode))
return 0;
return 1;
}
static int
valid_repo_component(const char *s, size_t n)
{
size_t i;
if (n == 0 || s[0] == '.')
return 0;
for (i = 0; i < n; i++) {
unsigned char c = (unsigned char)s[i];
if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '.' || c == '_' ||
c == '-'))
return 0;
}
return 1;
}
static int
valid_repo_name(const char *name)
{
const char *slash = strchr(name, '/');
if (slash == NULL)
return valid_repo_component(name, strlen(name));
if (strchr(slash + 1, '/') != NULL)
return 0;
return valid_repo_component(name, (size_t)(slash - name)) &&
valid_repo_component(slash + 1, strlen(slash + 1));
}
static int
find_repo(const char *name, char **path_out)
{
char cand[PATHBUF];
if (!valid_repo_name(name))
return 0;
if (snprintf(cand, sizeof(cand), "%s/%s", g_root, name) <
(int)sizeof(cand) && is_repo_dir(cand)) {
*path_out = xstrdup(cand);
return 1;
}
if (snprintf(cand, sizeof(cand), "%s/%s.git", g_root, name) <
(int)sizeof(cand) && is_repo_dir(cand)) {
*path_out = xstrdup(cand);
return 1;
}
return 0;
}
static void
strip_git_suffix(char *name)
{
size_t n = strlen(name);
if (n > 4 && strcmp(name + n - 4, ".git") == 0)
name[n - 4] = '\0';
}
static int
repo_cmp(const void *a, const void *b)
{
const struct repo *ra = a;
const struct repo *rb = b;
return strcmp(ra->name, rb->name);
}
static void
add_repo(struct repo **repos, size_t *n, size_t *cap, const char *name,
const char *path)
{
if (!valid_repo_name(name))
return;
if (*n == *cap) {
*cap = *cap ? *cap * 2 : 16;
*repos = xrealloc(*repos, *cap * sizeof(**repos));
}
(*repos)[*n].name = xstrdup(name);
(*repos)[*n].path = xstrdup(path);
(*n)++;
}
static struct repo *
scan_repos(size_t *count)
{
DIR *d, *sd;
struct dirent *de, *sub;
struct repo *repos = NULL;
size_t n = 0, cap = 0, i, out = 0;
*count = 0;
d = opendir(g_root);
if (d == NULL)
return NULL;
while ((de = readdir(d)) != NULL) {
char path[PATHBUF];
struct stat st;
if (de->d_name[0] == '.')
continue;
if (snprintf(path, sizeof(path), "%s/%s", g_root, de->d_name) >=
(int)sizeof(path))
continue;
if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode))
continue;
if (is_repo_dir(path)) {
char name[PATHBUF];
snprintf(name, sizeof(name), "%s", de->d_name);
strip_git_suffix(name);
add_repo(&repos, &n, &cap, name, path);
continue;
}
/* Gotea/Gitea lay out repositories as <owner>/<repo>.git. */
sd = opendir(path);
if (sd == NULL)
continue;
while ((sub = readdir(sd)) != NULL) {
char subpath[PATHBUF];
char name[PATHBUF];
if (sub->d_name[0] == '.')
continue;
if (snprintf(subpath, sizeof(subpath), "%s/%s", path,
sub->d_name) >= (int)sizeof(subpath))
continue;
if (stat(subpath, &st) != 0 || !S_ISDIR(st.st_mode))
continue;
if (!is_repo_dir(subpath))
continue;
snprintf(name, sizeof(name), "%s/%s", de->d_name,
sub->d_name);
strip_git_suffix(name);
add_repo(&repos, &n, &cap, name, subpath);
}
closedir(sd);
}
closedir(d);
if (n > 1)
qsort(repos, n, sizeof(*repos), repo_cmp);
/* Prefer "foo" over "foo.git" when both exist. */
for (i = 0; i < n; i++) {
if (out > 0 && strcmp(repos[i].name, repos[out - 1].name) == 0) {
free(repos[i].name);
free(repos[i].path);
continue;
}
if (out != i)
repos[out] = repos[i];
out++;
}
*count = out;
return repos;
}
static void
free_repos(struct repo *repos, size_t n)
{
size_t i;
for (i = 0; i < n; i++) {
free(repos[i].name);
free(repos[i].path);
}
free(repos);
}
/*
* Run got and capture stdout/stderr. Stderr is kept separate so pages can
* show a useful message while still returning a 404 for a missing path.
*/
static int
run_got(char *const argv[], struct buf *out, struct buf *err)
{
int op[2], ep[2];
pid_t pid;
int status = 0, timed_out = 0;
time_t deadline;
int fds_open = 2;
if (pipe(op) != 0 || pipe(ep) != 0)
return -1;
pid = fork();
if (pid < 0) {
close(op[0]); close(op[1]); close(ep[0]); close(ep[1]);
return -1;
}
if (pid == 0) {
int devnull;
setpgid(0, 0);
if (dup2(op[1], STDOUT_FILENO) < 0 ||
dup2(ep[1], STDERR_FILENO) < 0)
_exit(127);
devnull = open("/dev/null", O_RDONLY);
if (devnull >= 0) {
dup2(devnull, STDIN_FILENO);
close(devnull);
}
close(op[0]); close(op[1]);
close(ep[0]); close(ep[1]);
execvp(argv[0], argv);
_exit(127);
}
close(op[1]);
close(ep[1]);
deadline = time(NULL) + GOT_TIMEOUT_SEC;
while (fds_open > 0) {
struct pollfd pfd[2];
int timeout, r, i;
timeout = (int)(deadline - time(NULL));
if (timeout <= 0) {
timed_out = 1;
break;
}
pfd[0].fd = op[0];
pfd[0].events = POLLIN;
pfd[0].revents = 0;
pfd[1].fd = ep[0];
pfd[1].events = POLLIN;
pfd[1].revents = 0;
r = poll(pfd, 2, timeout * 1000);
if (r < 0) {
if (errno == EINTR)
continue;
break;
}
if (r == 0) {
timed_out = 1;
break;
}
for (i = 0; i < 2; i++) {
struct buf *dst = i == 0 ? out : err;
char tmp[8192];
ssize_t n;
if (pfd[i].fd < 0 || pfd[i].revents == 0)
continue;
if (!(pfd[i].revents & (POLLIN | POLLHUP | POLLERR)))
continue;
n = read(pfd[i].fd, tmp, sizeof(tmp));
if (n < 0) {
if (errno == EINTR)
continue;
close(pfd[i].fd);
pfd[i].fd = -1;
fds_open--;
continue;
}
if (n == 0) {
close(pfd[i].fd);
pfd[i].fd = -1;
if (i == 0)
op[0] = -1;
else
ep[0] = -1;
fds_open--;
continue;
}
if (dst->len + (size_t)n > MAX_CAPTURE) {
timed_out = 1;
break;
}
b_putn(dst, tmp, (size_t)n);
}
if (timed_out)
break;
}
if (timed_out)
kill(-pid, SIGKILL);
close(op[0]);
close(ep[0]);
while (waitpid(pid, &status, 0) < 0 && errno == EINTR)
continue;
if (timed_out)
return -2;
if (WIFEXITED(status))
return WEXITSTATUS(status);
return -1;
}
static void
css(struct buf *b)
{
const struct palette *p = g_pal;
b_printf(b, "body{background-color:%s;color:%s;"
"font-family:Helvetica,Arial,sans-serif;font-size:13px;margin:8px}\n",
p->base, p->text);
b_printf(b, "a{color:%s}\na:visited{color:%s}\n", p->link, p->visited);
b_printf(b, "h1,h2,h3{font-family:Helvetica,Arial,sans-serif;"
"margin:0 0 8px 0}\n");
b_printf(b, ".titlebar{background-color:%s;color:%s}\n",
p->title_bg, p->title_fg);
b_printf(b, ".bevel-out{background-color:%s;"
"border-top:2px solid %s;border-left:2px solid %s;"
"border-right:2px solid %s;border-bottom:2px solid %s}\n",
p->base, p->white, p->white, p->shadow, p->shadow);
b_printf(b, ".bevel-in{background-color:%s;"
"border-top:2px solid %s;border-left:2px solid %s;"
"border-right:2px solid %s;border-bottom:2px solid %s}\n",
p->base, p->shadow, p->shadow, p->white, p->white);
b_printf(b, "pre{background-color:%s;color:%s;"
"border-top:1px solid %s;border-left:1px solid %s;"
"border-right:1px solid %s;border-bottom:1px solid %s;"
"padding:6px;font-family:Courier,monospace;font-size:12px}\n",
p->white, p->text, p->shadow, p->shadow, p->light, p->light);
b_printf(b, "th{background-color:%s;color:%s;text-align:left}\n",
p->dark, p->text);
b_printf(b, "tr.alt td{background-color:%s}\n", p->light);
b_printf(b, "td.panel{padding:10px}\n");
}
static void
page_begin(struct buf *b, const char *title)
{
b_puts(b, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
"\"http://www.w3.org/TR/html4/loose.dtd\">\n<html lang=\"en\">\n<head>\n");
b_puts(b, "<meta http-equiv=\"Content-Type\" "
"content=\"text/html; charset=UTF-8\">\n<title>");
b_html(b, title);
b_puts(b, " - gotea</title>\n<style type=\"text/css\">\n");
css(b);
b_puts(b, "</style>\n</head>\n<body bgcolor=\"");
b_html(b, g_pal->base);
b_puts(b, "\" text=\"");
b_html(b, g_pal->text);
b_puts(b, "\" link=\"");
b_html(b, g_pal->link);
b_puts(b, "\" vlink=\"");
b_html(b, g_pal->visited);
b_puts(b, "\">\n");
}
static void
page_banner(struct buf *b)
{
if (g_pages_mode) {
b_puts(b, "<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" "
"border=\"0\" summary=\"Site banner\" bgcolor=\"");
b_html(b, g_pal->title_bg);
b_puts(b, "\"><tr><td><font color=\"");
b_html(b, g_pal->title_fg);
b_puts(b, "\" size=\"+1\"><b>GOTEA PAGES</b></font> "
"<font color=\"");
b_html(b, g_pal->title_fg);
b_puts(b, "\">project sites</font></td></tr></table>\n");
return;
}
b_puts(b, "<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" "
"border=\"0\" summary=\"Site banner\" bgcolor=\"");
b_html(b, g_pal->title_bg);
b_puts(b, "\"><tr><td><font color=\"");
b_html(b, g_pal->title_fg);
b_puts(b, "\" size=\"+1\"><b>GOTEA</b></font> <font color=\"");
b_html(b, g_pal->title_fg);
b_puts(b, "\">Game of Trees forge</font></td><td align=\"right\">");
href_top(b, "");
b_puts(b, "<font color=\"");
b_html(b, g_pal->title_fg);
b_puts(b, "\">Repositories</font></a> <font color=\"");
b_html(b, g_pal->title_fg);
b_puts(b, "\">|</font> ");
href_top(b, "/about");
b_puts(b, "<font color=\"");
b_html(b, g_pal->title_fg);
b_puts(b, "\">About</font></a></td></tr></table>\n");
}
static void
panel_begin(struct buf *b, const char *title)
{
b_puts(b, "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" "
"border=\"0\" summary=\"Panel\" class=\"bevel-out\"><tr><td>\n");
b_puts(b, "<table width=\"100%\" cellpadding=\"3\" cellspacing=\"0\" "
"border=\"0\" summary=\"Panel title\" class=\"titlebar\"><tr><td><b>");
b_html(b, title);
b_puts(b, "</b></td></tr></table>\n");
b_puts(b, "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" "
"border=\"0\" summary=\"Panel content\"><tr><td class=\"panel\">\n");
}
static void
panel_end(struct buf *b)
{
b_puts(b, "</td></tr></table>\n</td></tr></table>\n");
}
static void
layout_begin(struct buf *b, const char *current, struct repo *repos,
size_t nrepos)
{
size_t i;
b_puts(b, "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" "
"border=\"0\" summary=\"Page layout\"><tr><td width=\"200\" valign=\"top\">\n");
panel_begin(b, "Front Panel");
href_top(b, "");
b_puts(b, "Repositories</a><br>\n");
href_top(b, "/about");
b_puts(b, "About gotea</a><br>\n<hr>\n");
if (nrepos == 0) {
b_puts(b, "<i>no repositories</i><br>\n");
}
for (i = 0; i < nrepos; i++) {
if (current != NULL && strcmp(current, repos[i].name) == 0) {
b_puts(b, "<b>");
b_html(b, repos[i].name);
b_puts(b, "</b><br>\n");
} else {
href_repo(b, "tree", repos[i].name, NULL);
b_html(b, repos[i].name);
b_puts(b, "</a><br>\n");
}
}
panel_end(b);
b_puts(b, "</td><td width=\"10\">&nbsp;</td>"
"<td valign=\"top\">\n");
}
static void
layout_end(struct buf *b)
{
b_puts(b, "</td></tr></table>\n");
}
static void
page_end(struct buf *b)
{
b_puts(b, "<p><font size=\"-1\">gotea &mdash; HTML 4.01 "
"Transitional, no JavaScript. Served by gotea-cgi.</font></p>\n");
b_puts(b, "</body>\n</html>\n");
}
static void
breadcrumb(struct buf *b, const char *repo, const char *path)
{
char *copy = NULL, *s, *slash;
struct buf prefix;
href_top(b, "");
b_puts(b, "Repositories</a>");
if (repo == NULL)
return;
b_puts(b, " / ");
href_repo(b, "tree", repo, NULL);
b_html(b, repo);
b_puts(b, "</a>");
if (path == NULL || *path == '\0')
return;
copy = xstrdup(path);
b_init(&prefix);
s = copy;
while (s != NULL && *s != '\0') {
slash = strchr(s, '/');
if (slash != NULL)
*slash = '\0';
if (prefix.len > 0)
b_putc(&prefix, '/');
b_puts(&prefix, s);
b_puts(b, " / ");
href_repo(b, "tree", repo, prefix.p);
b_html(b, s);
b_puts(b, "</a>");
if (slash == NULL)
break;
s = slash + 1;
}
b_free(&prefix);
free(copy);
}
static int
hex40(const char *s)
{
int i;
for (i = 0; i < 40; i++) {
if (hexval((unsigned char)s[i]) < 0)
return 0;
}
return 1;
}
static void
repo_head(const char *path, char **hash, char **branch, char **subject)
{
char *args[8];
struct buf out, err;
char *line, *next;
int rc, seen_date = 0;
*hash = *branch = *subject = NULL;
b_init(&out);
b_init(&err);
args[0] = (char *)g_got;
args[1] = (char *)"log";
args[2] = (char *)"-r";
args[3] = (char *)path;
args[4] = (char *)"-l";
args[5] = (char *)"1";
args[6] = NULL;
rc = run_got(args, &out, &err);
b_free(&err);
if (rc != 0 || out.p == NULL) {
b_free(&out);
return;
}
line = out.p;
while (line != NULL && *line != '\0') {
next = strchr(line, '\n');
if (next != NULL)
*next++ = '\0';
if (strncmp(line, "commit ", 7) == 0 &&
strlen(line) >= 47 && hex40(line + 7)) {
char *open, *close;
*hash = xmalloc(41);
memcpy(*hash, line + 7, 40);
(*hash)[40] = '\0';
open = strchr(line + 47, '(');
close = open ? strchr(open, ')') : NULL;
if (open != NULL && close != NULL) {
size_t n = (size_t)(close - open - 1);
*branch = xmalloc(n + 1);
memcpy(*branch, open + 1, n);
(*branch)[n] = '\0';
}
} else if (line[0] == ' ' && line[1] != '\0' &&
seen_date && *subject == NULL) {
char *t = line;
while (*t == ' ' || *t == '\t')
t++;
if (*t != '\0')
*subject = xstrdup(t);
} else if (strncmp(line, "date:", 5) == 0) {
seen_date = 1;
}
line = next;
}
b_free(&out);
}
static void
page_error_body(struct buf *b, const char *title, const char *msg,
const char *detail)
{
page_begin(b, title);
page_banner(b);
b_puts(b, "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" "
"border=\"0\" summary=\"Error\"><tr><td>\n");
panel_begin(b, title);
b_puts(b, "<h2>");
b_html(b, title);
b_puts(b, "</h2>\n<p>");
b_html(b, msg);
b_puts(b, "</p>\n");
if (detail != NULL && *detail != '\0') {
b_puts(b, "<p><b>Details</b></p>\n<pre>");
b_html(b, detail);
b_puts(b, "</pre>\n");
}
b_puts(b, "<p>");
href_top(b, "");
b_puts(b, "Return to repositories</a></p>\n");
panel_end(b);
b_puts(b, "</td></tr></table>\n");
page_end(b);
}
static void
page_home(struct buf *b, struct repo *repos, size_t nrepos)
{
size_t i;
page_begin(b, "Repositories");
page_banner(b);
layout_begin(b, NULL, repos, nrepos);
panel_begin(b, "Repositories");
if (nrepos == 0) {
b_puts(b, "<p>No repositories found in <code>");
b_html(b, g_root);
b_puts(b, "</code>.</p>\n");
} else {
b_puts(b, "<table width=\"100%\" cellpadding=\"3\" "
"cellspacing=\"0\" border=\"0\" summary=\"Repositories\">\n");
b_puts(b, "<tr><th>Repository</th><th>Branch</th>"
"<th>Last commit</th></tr>\n");
for (i = 0; i < nrepos; i++) {
char *hash = NULL, *branch = NULL, *subject = NULL;
repo_head(repos[i].path, &hash, &branch, &subject);
b_puts(b, "<tr");
if (i % 2)
b_puts(b, " class=\"alt\"");
b_puts(b, "><td>");
href_repo(b, "tree", repos[i].name, NULL);
b_html(b, repos[i].name);
b_puts(b, "</a></td><td>");
if (branch != NULL)
b_html(b, branch);
else
b_puts(b, "&nbsp;");
b_puts(b, "</td><td>");
if (hash != NULL) {
href_repo(b, "commit", repos[i].name, hash);
b_html(b, subject != NULL ? subject : "(no message)");
b_puts(b, "</a>");
} else {
b_puts(b, "<i>empty repository</i>");
}
b_puts(b, "</td></tr>\n");
free(hash);
free(branch);
free(subject);
}
b_puts(b, "</table>\n");
}
panel_end(b);
layout_end(b);
page_end(b);
}
static int
page_tree(struct buf *b, const char *repo, const char *repo_path,
const char *path, struct repo *repos, size_t nrepos)
{
char *args[10];
struct buf out, err;
int rc, i = 0;
b_init(&out);
b_init(&err);
args[i++] = (char *)g_got;
args[i++] = (char *)"tree";
args[i++] = (char *)"-r";
args[i++] = (char *)repo_path;
args[i++] = (char *)"-c";
args[i++] = (char *)"HEAD";
args[i++] = (char *)"-i";
if (path != NULL && *path != '\0')
args[i++] = (char *)path;
args[i] = NULL;
rc = run_got(args, &out, &err);
if (rc != 0) {
b_free(&out);
b_free(&err);
return 0;
}
page_begin(b, path != NULL && *path != '\0' ? path : repo);
page_banner(b);
layout_begin(b, repo, repos, nrepos);
panel_begin(b, path != NULL && *path != '\0' ? path : repo);
b_puts(b, "<p>");
breadcrumb(b, repo, path);
b_puts(b, " &nbsp; ");
href_repo(b, "log", repo, NULL);
b_puts(b, "[history]</a></p>\n");
if (out.len == 0) {
b_puts(b, "<p><i>empty directory</i></p>\n");
} else {
char *line = out.p, *next;
b_puts(b, "<table width=\"100%\" cellpadding=\"3\" "
"cellspacing=\"0\" border=\"0\" summary=\"Repository entries\">\n");
b_puts(b, "<tr><th width=\"90\">Object</th>"
"<th>Name</th></tr>\n");
i = 0;
while (line != NULL && *line != '\0') {
char *rest, *name, *full;
char kind;
size_t namelen;
next = strchr(line, '\n');
if (next != NULL)
*next++ = '\0';
if (strlen(line) < 42 || line[40] != ' ' ||
!hex40(line)) {
line = next;
continue;
}
rest = line + 41;
name = rest;
namelen = strlen(name);
kind = 'f';
if (namelen > 0) {
char last = name[namelen - 1];
if (last == '/') {
kind = 'd';
name[--namelen] = '\0';
} else if (last == '*') {
kind = 'x';
name[--namelen] = '\0';
} else if (last == '@') {
kind = 'l';
name[--namelen] = '\0';
} else if (last == '$') {
kind = 's';
name[--namelen] = '\0';
}
}
if (path != NULL && *path != '\0') {
struct buf fb;
b_init(&fb);
b_puts(&fb, path);
b_putc(&fb, '/');
b_puts(&fb, name);
full = fb.p;
} else {
full = xstrdup(name);
}
b_puts(b, "<tr");
if (i % 2)
b_puts(b, " class=\"alt\"");
b_puts(b, "><td><code>");
{
char shortid[9];
memcpy(shortid, line, 8);
shortid[8] = '\0';
b_html(b, shortid);
}
b_puts(b, "</code></td><td>");
if (kind == 'd')
href_repo(b, "tree", repo, full);
else
href_repo(b, "blob", repo, full);
if (kind == 'd')
b_puts(b, "[");
b_html(b, name);
if (kind == 'd')
b_puts(b, "]");
b_puts(b, "</a>");
if (kind == 'x')
b_puts(b, " <i>(executable)</i>");
else if (kind == 'l')
b_puts(b, " <i>(symlink)</i>");
else if (kind == 's')
b_puts(b, " <i>(submodule)</i>");
b_puts(b, "</td></tr>\n");
free(full);
i++;
line = next;
}
b_puts(b, "</table>\n");
}
panel_end(b);
layout_end(b);
page_end(b);
b_free(&out);
b_free(&err);
return 1;
}
static int
got_cat_ref(const char *repo_path, const char *ref, const char *path,
struct buf *out, struct buf *err)
{
char *args[9];
args[0] = (char *)g_got;
args[1] = (char *)"cat";
args[2] = (char *)"-r";
args[3] = (char *)repo_path;
args[4] = (char *)"-c";
args[5] = (char *)ref;
args[6] = (char *)path;
args[7] = NULL;
return run_got(args, out, err);
}
static int
got_cat(const char *repo_path, const char *path, struct buf *out,
struct buf *err)
{
return got_cat_ref(repo_path, "HEAD", path, out, err);
}
static int
page_blob(struct buf *b, const char *repo, const char *repo_path,
const char *path, struct repo *repos, size_t nrepos)
{
struct buf out, err;
int rc, binary = 0;
size_t shown;
b_init(&out);
b_init(&err);
rc = got_cat(repo_path, path, &out, &err);
if (rc != 0) {
page_error_body(b, "Not found", "No such file in this repository.",
env_or("GOTEA_DEBUG", NULL) ? err.p : NULL);
b_free(&out);
b_free(&err);
return 0;
}
if (out.len > 0 && memchr(out.p, '\0', out.len) != NULL)
binary = 1;
page_begin(b, path);
page_banner(b);
layout_begin(b, repo, repos, nrepos);
panel_begin(b, path);
b_puts(b, "<p>");
breadcrumb(b, repo, path);
b_puts(b, " &nbsp; ");
href_repo(b, "raw", repo, path);
b_puts(b, "[raw]</a> ");
href_repo(b, "log", repo, NULL);
b_puts(b, "[history]</a></p>\n");
if (binary) {
b_printf(b, "<p><i>Binary file, %lu bytes.</i></p>\n",
(unsigned long)out.len);
} else {
shown = out.len;
if (shown > MAX_BLOB)
shown = MAX_BLOB;
b_puts(b, "<pre>");
b_html(b, out.p);
if (shown < out.len)
b_puts(b, "\n\n[truncated]");
b_puts(b, "</pre>\n");
}
panel_end(b);
layout_end(b);
page_end(b);
b_free(&out);
b_free(&err);
return 1;
}
static void
page_log(struct buf *b, const char *repo, const char *repo_path,
struct repo *repos, size_t nrepos)
{
char *args[8];
struct buf out, err;
char *line, *next;
int rc;
b_init(&out);
b_init(&err);
args[0] = (char *)g_got;
args[1] = (char *)"log";
args[2] = (char *)"-r";
args[3] = (char *)repo_path;
args[4] = (char *)"-l";
args[5] = (char *)"50";
args[6] = NULL;
rc = run_got(args, &out, &err);
if (rc != 0) {
page_error_body(b, "History unavailable",
"got could not read this repository.",
env_or("GOTEA_DEBUG", NULL) ? err.p : NULL);
b_free(&out);
b_free(&err);
return;
}
page_begin(b, "History");
page_banner(b);
layout_begin(b, repo, repos, nrepos);
panel_begin(b, "History");
b_puts(b, "<p>");
href_repo(b, "tree", repo, NULL);
b_html(b, repo);
b_puts(b, "</a> / history &nbsp; ");
href_repo(b, "tree", repo, NULL);
b_puts(b, "[files]</a></p>\n<pre>");
line = out.p;
while (line != NULL && *line != '\0') {
size_t len;
next = strchr(line, '\n');
if (next != NULL)
*next++ = '\0';
len = strlen(line);
if (len >= 47 && strncmp(line, "commit ", 7) == 0 &&
hex40(line + 7)) {
char hash[41];
memcpy(hash, line + 7, 40);
hash[40] = '\0';
href_repo(b, "commit", repo, hash);
b_puts(b, "commit ");
b_html(b, hash);
b_puts(b, "</a>");
b_html(b, line + 47);
} else {
b_html(b, line);
}
b_putc(b, '\n');
line = next;
}
b_puts(b, "</pre>\n");
panel_end(b);
layout_end(b);
page_end(b);
b_free(&out);
b_free(&err);
}
static void
page_commit(struct buf *b, const char *repo, const char *repo_path,
const char *rev, struct repo *repos, size_t nrepos)
{
char *args[10];
struct buf out, err;
int rc;
b_init(&out);
b_init(&err);
args[0] = (char *)g_got;
args[1] = (char *)"log";
args[2] = (char *)"-r";
args[3] = (char *)repo_path;
args[4] = (char *)"-l";
args[5] = (char *)"1";
args[6] = (char *)"-c";
args[7] = (char *)rev;
args[8] = (char *)"-p";
args[9] = NULL;
rc = run_got(args, &out, &err);
if (rc != 0) {
page_error_body(b, "Commit not found",
"got could not resolve that revision.",
env_or("GOTEA_DEBUG", NULL) ? err.p : NULL);
b_free(&out);
b_free(&err);
return;
}
page_begin(b, "Commit");
page_banner(b);
layout_begin(b, repo, repos, nrepos);
panel_begin(b, "Commit");
b_puts(b, "<p>");
href_repo(b, "tree", repo, NULL);
b_html(b, repo);
b_puts(b, "</a> / ");
href_repo(b, "log", repo, NULL);
b_puts(b, "history</a></p>\n<pre>");
b_html(b, out.p);
b_puts(b, "</pre>\n");
panel_end(b);
layout_end(b);
page_end(b);
b_free(&out);
b_free(&err);
}
static int
valid_rev(const char *rev)
{
const unsigned char *p = (const unsigned char *)rev;
if (*p == '\0' || *p == '-' || strlen(rev) > 256)
return 0;
for (; *p; p++) {
if (!( (*p >= 'A' && *p <= 'Z') || (*p >= 'a' && *p <= 'z') ||
(*p >= '0' && *p <= '9') || *p == '.' || *p == '_' ||
*p == '-' || *p == '/'))
return 0;
}
return strstr(rev, "..") == NULL;
}
static const char *
reason(int status)
{
switch (status) {
case 200: return "OK";
case 400: return "Bad Request";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 500: return "Internal Server Error";
case 503: return "Service Unavailable";
default: return "Error";
}
}
static void
send_buf(int status, const char *ctype, struct buf *body, int head_only)
{
if (status != 200)
printf("Status: %d %s\r\n", status, reason(status));
printf("Content-Type: %s\r\n", ctype);
printf("Cache-Control: no-cache\r\n");
printf("X-Content-Type-Options: nosniff\r\n");
printf("\r\n");
if (!head_only && body->p != NULL)
fwrite(body->p, 1, body->len, stdout);
}
static void
send_raw(const char *ctype, const struct buf *body, int head_only)
{
printf("Content-Type: %s\r\n", ctype);
printf("Content-Length: %lu\r\n", (unsigned long)body->len);
printf("Cache-Control: no-cache\r\n");
printf("X-Content-Type-Options: nosniff\r\n");
printf("\r\n");
if (!head_only)
fwrite(body->p, 1, body->len, stdout);
}
static int
serve_raw(const char *repo_path, const char *path)
{
struct buf out, err;
int rc, is_text;
b_init(&out);
b_init(&err);
rc = got_cat(repo_path, path, &out, &err);
b_free(&err);
if (rc != 0) {
b_free(&out);
return 0;
}
is_text = out.len == 0 || memchr(out.p, '\0', out.len) == NULL;
send_raw(is_text ? "text/plain; charset=UTF-8" :
"application/octet-stream", &out, g_head_only);
b_free(&out);
return 1;
}
static void
page_about(struct buf *b, struct repo *repos, size_t nrepos)
{
page_begin(b, "About");
page_banner(b);
layout_begin(b, NULL, repos, nrepos);
panel_begin(b, "About gotea");
b_puts(b, "<h2>gotea</h2>\n");
b_puts(b, "<p>A small, old-school forge frontend for repositories "
"stored in the Git object format and read with "
"<a href=\"https://got.gameoftrees.org/\">got</a>.</p>\n");
b_puts(b, "<p>This interface is HTML 4.01 Transitional with no "
"JavaScript and no external assets. It is meant to stay usable "
"in text browsers and in browsers from the CDE era.</p>\n");
b_puts(b, "<p>The look follows the CDE/Motif palette: grey panels, "
"bevelled borders, navy title bars, and table layout.</p>\n");
b_puts(b, "<h3>Configuration</h3>\n<pre>");
b_html(b, "GOTEA_REPO_ROOT directory containing bare repositories\n"
"GOT_BIN got binary (default: got)\n"
"GOTEA_PALETTE optional key=value palette file\n"
"GOTEA_DEBUG show got stderr on error pages\n"
"SCRIPT_NAME CGI mount point (set by the web server)");
b_puts(b, "</pre>\n");
panel_end(b);
layout_end(b);
page_end(b);
}
static const char *
content_type_for(const char *path)
{
const char *dot = strrchr(path, '.');
if (dot == NULL)
return "application/octet-stream";
if (!strcasecmp(dot, ".html") || !strcasecmp(dot, ".htm"))
return "text/html; charset=UTF-8";
if (!strcasecmp(dot, ".css"))
return "text/css; charset=UTF-8";
if (!strcasecmp(dot, ".txt") || !strcasecmp(dot, ".md"))
return "text/plain; charset=UTF-8";
if (!strcasecmp(dot, ".js"))
return "application/javascript; charset=UTF-8";
if (!strcasecmp(dot, ".json"))
return "application/json; charset=UTF-8";
if (!strcasecmp(dot, ".xml"))
return "application/xml; charset=UTF-8";
if (!strcasecmp(dot, ".svg"))
return "image/svg+xml";
if (!strcasecmp(dot, ".png"))
return "image/png";
if (!strcasecmp(dot, ".jpg") || !strcasecmp(dot, ".jpeg"))
return "image/jpeg";
if (!strcasecmp(dot, ".gif"))
return "image/gif";
if (!strcasecmp(dot, ".ico"))
return "image/x-icon";
if (!strcasecmp(dot, ".webp"))
return "image/webp";
if (!strcasecmp(dot, ".woff2"))
return "font/woff2";
if (!strcasecmp(dot, ".woff"))
return "font/woff";
if (!strcasecmp(dot, ".ttf"))
return "font/ttf";
if (!strcasecmp(dot, ".otf"))
return "font/otf";
if (!strcasecmp(dot, ".pdf"))
return "application/pdf";
return "application/octet-stream";
}
static int
path_hidden(const char *path)
{
const char *p = path;
while (*p) {
if (*p == '.')
return 1;
p = strchr(p, '/');
if (p == NULL)
break;
p++;
}
return 0;
}
static int
path_under(const char *path, const char *prefix)
{
size_t n = strlen(prefix);
if (strncmp(path, prefix, n) != 0)
return 0;
return path[n] == '\0' || path[n] == '/';
}
static int
pages_allowed(const char *repo)
{
const char *file = getenv("GOTEA_PAGES_ALLOW");
FILE *f;
char line[PATHBUF];
if (file == NULL || *file == '\0')
return 0;
f = fopen(file, "r");
if (f == NULL)
return 0;
while (fgets(line, sizeof(line), f) != NULL) {
char *p = line, *end;
while (*p == ' ' || *p == '\t')
p++;
if (*p == '#' || *p == '\n' || *p == '\0')
continue;
end = p + strlen(p);
while (end > p && (end[-1] == '\n' || end[-1] == '\r' ||
end[-1] == ' ' || end[-1] == '\t'))
*--end = '\0';
if (strcmp(p, repo) == 0) {
fclose(f);
return 1;
}
}
fclose(f);
return 0;
}
static void
pages_index(struct buf *b)
{
const char *file = getenv("GOTEA_PAGES_ALLOW");
FILE *f;
char line[PATHBUF];
page_begin(b, "Project sites");
page_banner(b);
panel_begin(b, "Project sites");
f = file != NULL ? fopen(file, "r") : NULL;
if (f == NULL) {
b_puts(b, "<p><i>No project sites published.</i></p>\n");
} else {
b_puts(b, "<ul>\n");
while (fgets(line, sizeof(line), f) != NULL) {
char *p = line, *end;
while (*p == ' ' || *p == '\t')
p++;
if (*p == '#' || *p == '\n' || *p == '\0')
continue;
end = p + strlen(p);
while (end > p && (end[-1] == '\n' ||
end[-1] == '\r' || end[-1] == ' ' ||
end[-1] == '\t'))
*--end = '\0';
if (!valid_repo_name(p))
continue;
b_puts(b, "<li>");
b_puts(b, "<a href=\"");
b_url_path(b, g_script);
b_putc(b, '/');
b_url_path(b, p);
b_puts(b, "/\">");
b_html(b, p);
b_puts(b, "</a></li>\n");
}
fclose(f);
b_puts(b, "</ul>\n");
}
panel_end(b);
page_end(b);
}
static int
read_file(const char *path, struct buf *out)
{
int fd;
struct stat st;
ssize_t n;
fd = open(path, O_RDONLY);
if (fd < 0)
return 0;
if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size < 0 ||
(uintmax_t)st.st_size > 16 * 1024 * 1024) {
close(fd);
return 0;
}
b_reserve(out, (size_t)st.st_size);
while (out->len < (size_t)st.st_size) {
n = read(fd, out->p + out->len,
(size_t)st.st_size - out->len);
if (n < 0) {
if (errno == EINTR)
continue;
close(fd);
return 0;
}
if (n == 0)
break;
out->len += (size_t)n;
out->p[out->len] = '\0';
}
close(fd);
return 1;
}
static void
send_redirect(const char *repo, const char *rel)
{
struct buf loc;
b_init(&loc);
b_url_path(&loc, g_script);
b_putc(&loc, '/');
b_url_path(&loc, repo);
if (rel != NULL && *rel != '\0') {
b_putc(&loc, '/');
b_url_path(&loc, rel);
}
b_putc(&loc, '/');
printf("Status: 301 Moved Permanently\r\n");
printf("Location: %s\r\n", loc.p);
printf("Content-Type: text/html; charset=UTF-8\r\n");
printf("\r\n");
b_free(&loc);
}
/*
* Pages are built by bb in a separate root and served on their own host,
* never from the main application origin.
*/
static int
serve_pages(void)
{
const char *root_env = getenv("GOTEA_PAGES_ROOT");
const char *allow = getenv("GOTEA_PAGES_ALLOW");
char *decoded = NULL, *repo = NULL, *rel = NULL;
char *root_real = NULL, *repo_real = NULL, *cand = NULL;
char *resolved = NULL;
struct path p;
struct buf body, out;
struct stat st;
int status = 200, trailing;
g_pages_mode = 1;
b_init(&body);
b_init(&out);
memset(&p, 0, sizeof(p));
decoded = url_decode(env_or("PATH_INFO", "/"));
if (decoded == NULL) {
page_error_body(&body, "Bad request",
"Malformed URL escape in PATH_INFO.", NULL);
status = 400;
goto done;
}
if (split_path(&p, decoded) != 0) {
page_error_body(&body, "Bad request", "Invalid path.", NULL);
status = 400;
goto done;
}
if (root_env == NULL || *root_env == '\0' ||
allow == NULL || *allow == '\0') {
page_error_body(&body, "Pages unavailable",
"Set GOTEA_PAGES_ROOT and GOTEA_PAGES_ALLOW.", NULL);
status = 503;
goto done;
}
root_real = realpath(root_env, NULL);
if (root_real == NULL) {
page_error_body(&body, "Pages unavailable",
"The pages root does not exist.", NULL);
status = 503;
goto done;
}
if (p.n == 0) {
pages_index(&body);
status = 200;
goto done;
}
if (p.n < 2) {
page_error_body(&body, "Not found", "Unknown project.", NULL);
status = 404;
goto done;
}
repo = xmalloc(strlen(p.seg[0]) + strlen(p.seg[1]) + 2);
sprintf(repo, "%s/%s", p.seg[0], p.seg[1]);
if (!valid_repo_name(repo) || !pages_allowed(repo)) {
page_error_body(&body, "Not found",
"No published site with that name.", NULL);
status = 404;
goto done;
}
{
char dir[PATHBUF];
if (snprintf(dir, sizeof(dir), "%s/%s", root_real, repo) >=
(int)sizeof(dir)) {
page_error_body(&body, "Not found", "Path too long.",
NULL);
status = 404;
goto done;
}
repo_real = realpath(dir, NULL);
}
if (repo_real == NULL) {
page_error_body(&body, "Not found",
"That project has not been published yet.", NULL);
status = 404;
goto done;
}
trailing = decoded[0] != '\0' &&
decoded[strlen(decoded) - 1] == '/';
if (p.n == 2) {
if (!trailing) {
send_redirect(repo, NULL);
status = -1;
goto done;
}
rel = xstrdup("index.html");
} else {
rel = join_segs(&p, 2);
if (path_hidden(rel)) {
page_error_body(&body, "Not found", "Invalid path.",
NULL);
status = 404;
goto done;
}
}
cand = xmalloc(strlen(repo_real) + strlen(rel) + 2);
sprintf(cand, "%s/%s", repo_real, rel);
if (stat(cand, &st) == 0 && S_ISDIR(st.st_mode)) {
if (!trailing) {
send_redirect(repo, rel);
status = -1;
goto done;
}
cand = xrealloc(cand, strlen(cand) + 12);
strcat(cand, "/index.html");
}
resolved = realpath(cand, NULL);
if (resolved == NULL || !path_under(resolved, repo_real)) {
page_error_body(&body, "Not found", "No such page.", NULL);
status = 404;
goto done;
}
if (!read_file(resolved, &out)) {
page_error_body(&body, "Not found", "No such page.", NULL);
status = 404;
goto done;
}
send_raw(content_type_for(resolved), &out, g_head_only);
status = -1;
done:
if (status >= 0)
send_buf(status, "text/html; charset=UTF-8", &body,
g_head_only);
b_free(&body);
b_free(&out);
free(decoded);
free(repo);
free(rel);
free(root_real);
free(repo_real);
free(cand);
free(resolved);
free(p.raw);
return 0;
}
static int
is_action(const char *s)
{
return strcmp(s, "tree") == 0 || strcmp(s, "blob") == 0 ||
strcmp(s, "raw") == 0 || strcmp(s, "log") == 0 ||
strcmp(s, "commit") == 0;
}
/*
* Repositories may be flat ("demo") or nested like Gotea stores them
* ("owner/repo"). Prefer the two-component name when it exists.
*/
static int
resolve_repo(struct path *p, char **name_out, size_t *action_idx,
char **path_out)
{
char *cand = NULL;
if (p->n >= 3) {
struct buf b;
b_init(&b);
b_puts(&b, p->seg[1]);
b_putc(&b, '/');
b_puts(&b, p->seg[2]);
cand = b.p;
if (find_repo(cand, path_out)) {
*name_out = cand;
*action_idx = 3;
return 1;
}
b_free(&b);
}
if (find_repo(p->seg[1], path_out)) {
*name_out = xstrdup(p->seg[1]);
*action_idx = 2;
return 1;
}
return 0;
}
int
main(void)
{
const char *method, *decoded_env, *palette_file;
const char *pages_host, *http_host;
char *decoded = NULL, *repo_path = NULL, *repo_name = NULL;
char *path = NULL;
struct path p;
struct repo *repos;
struct palette pal;
size_t nrepos = 0, action_idx = 0;
struct buf body;
int status = 200;
method = env_or("REQUEST_METHOD", "GET");
g_head_only = strcmp(method, "HEAD") == 0;
g_script = env_or("SCRIPT_NAME", "/cgi-bin/gotea");
g_root = env_or("GOTEA_REPO_ROOT", "./repositories");
g_got = env_or("GOT_BIN", "got");
palette_defaults(&pal);
palette_file = getenv("GOTEA_PALETTE");
palette_load(&pal, palette_file);
g_pal = &pal;
if (strcmp(method, "GET") != 0 && strcmp(method, "HEAD") != 0) {
b_init(&body);
page_error_body(&body, "Method not allowed",
"This CGI only answers GET and HEAD.", NULL);
send_buf(405, "text/html; charset=UTF-8", &body, 0);
b_free(&body);
return 0;
}
pages_host = getenv("GOTEA_PAGES_HOST");
if (pages_host != NULL && *pages_host != '\0') {
http_host = env_or("HTTP_HOST", env_or("SERVER_NAME", ""));
if (strcasecmp(http_host, pages_host) != 0) {
b_init(&body);
g_pages_mode = 1;
page_error_body(&body, "Unknown host",
"This CGI serves project pages on its own host.",
NULL);
send_buf(404, "text/html; charset=UTF-8", &body,
g_head_only);
b_free(&body);
return 0;
}
return serve_pages();
}
decoded_env = env_or("PATH_INFO", "/");
decoded = url_decode(decoded_env);
if (decoded == NULL) {
b_init(&body);
page_error_body(&body, "Bad request",
"Malformed URL escape in PATH_INFO.", NULL);
send_buf(400, "text/html; charset=UTF-8", &body, g_head_only);
b_free(&body);
return 0;
}
if (split_path(&p, decoded) != 0) {
b_init(&body);
page_error_body(&body, "Bad request",
"Invalid path.", NULL);
send_buf(400, "text/html; charset=UTF-8", &body, g_head_only);
b_free(&body);
free(decoded);
return 0;
}
repos = scan_repos(&nrepos);
b_init(&body);
if (p.n == 0) {
page_home(&body, repos, nrepos);
} else if (strcmp(p.seg[0], "about") == 0) {
page_about(&body, repos, nrepos);
} else if (strcmp(p.seg[0], "repo") != 0 || p.n < 2) {
page_error_body(&body, "Not found", "Unknown page.", NULL);
status = 404;
} else if (!resolve_repo(&p, &repo_name, &action_idx, &repo_path)) {
page_error_body(&body, "Repository not found",
"No repository with that name.", NULL);
status = 404;
} else {
const char *action = "tree";
size_t first = action_idx + 1;
if (p.n > action_idx) {
if (!is_action(p.seg[action_idx])) {
page_error_body(&body, "Not found",
"Unknown action.", NULL);
status = 404;
goto done;
}
action = p.seg[action_idx];
}
if (strcmp(action, "tree") == 0) {
path = join_segs(&p, first);
if (!page_tree(&body, repo_name, repo_path, path,
repos, nrepos)) {
/* A file path may be requested as /tree/... */
if (!page_blob(&body, repo_name, repo_path,
path, repos, nrepos))
status = 404;
}
} else if (strcmp(action, "blob") == 0) {
path = join_segs(&p, first);
if (*path == '\0') {
page_error_body(&body, "Not found",
"A file path is required.", NULL);
status = 404;
} else {
if (!page_blob(&body, repo_name, repo_path,
path, repos, nrepos))
status = 404;
}
} else if (strcmp(action, "raw") == 0) {
path = join_segs(&p, first);
if (*path == '\0' || !serve_raw(repo_path, path)) {
page_error_body(&body, "Not found",
"No such file in this repository.", NULL);
status = 404;
} else {
status = -1;
}
} else if (strcmp(action, "log") == 0) {
page_log(&body, repo_name, repo_path, repos, nrepos);
} else if (strcmp(action, "commit") == 0) {
if (p.n != first + 1 || !valid_rev(p.seg[first])) {
page_error_body(&body, "Bad request",
"Invalid revision.", NULL);
status = 400;
} else {
page_commit(&body, repo_name, repo_path,
p.seg[first], repos, nrepos);
}
} else {
page_error_body(&body, "Not found", "Unknown action.",
NULL);
status = 404;
}
}
done:
if (status >= 0)
send_buf(status, "text/html; charset=UTF-8", &body,
g_head_only);
b_free(&body);
free(path);
free(repo_path);
free(repo_name);
free(decoded);
free(p.raw);
free_repos(repos, nrepos);
return 0;
}