]> gitweb.ps.run Git - ps-cgit/blob - cgit.c
git: update to v2.46.0
[ps-cgit] / cgit.c
1 /* cgit.c: cgi for the git scm
2  *
3  * Copyright (C) 2006-2014 cgit Development Team <cgit@lists.zx2c4.com>
4  *
5  * Licensed under GNU General Public License v2
6  *   (see COPYING for full license text)
7  */
8
9 #define USE_THE_REPOSITORY_VARIABLE
10
11 #include "cgit.h"
12 #include "cache.h"
13 #include "cmd.h"
14 #include "configfile.h"
15 #include "html.h"
16 #include "ui-shared.h"
17 #include "ui-stats.h"
18 #include "ui-blob.h"
19 #include "ui-summary.h"
20 #include "scan-tree.h"
21
22 const char *cgit_version = CGIT_VERSION;
23
24 __attribute__((constructor))
25 static void constructor_environment()
26 {
27         /* Do not look in /etc/ for gitconfig and gitattributes. */
28         setenv("GIT_CONFIG_NOSYSTEM", "1", 1);
29         setenv("GIT_ATTR_NOSYSTEM", "1", 1);
30         unsetenv("HOME");
31         unsetenv("XDG_CONFIG_HOME");
32 }
33
34 static void add_mimetype(const char *name, const char *value)
35 {
36         struct string_list_item *item;
37
38         item = string_list_insert(&ctx.cfg.mimetypes, name);
39         item->util = xstrdup(value);
40 }
41
42 static void process_cached_repolist(const char *path);
43
44 static void repo_config(struct cgit_repo *repo, const char *name, const char *value)
45 {
46         const char *path;
47         struct string_list_item *item;
48
49         if (!strcmp(name, "name"))
50                 repo->name = xstrdup(value);
51         else if (!strcmp(name, "clone-url"))
52                 repo->clone_url = xstrdup(value);
53         else if (!strcmp(name, "desc"))
54                 repo->desc = xstrdup(value);
55         else if (!strcmp(name, "owner"))
56                 repo->owner = xstrdup(value);
57         else if (!strcmp(name, "homepage"))
58                 repo->homepage = xstrdup(value);
59         else if (!strcmp(name, "defbranch"))
60                 repo->defbranch = xstrdup(value);
61         else if (!strcmp(name, "extra-head-content"))
62                 repo->extra_head_content = xstrdup(value);
63         else if (!strcmp(name, "snapshots"))
64                 repo->snapshots = ctx.cfg.snapshots & cgit_parse_snapshots_mask(value);
65         else if (!strcmp(name, "enable-blame"))
66                 repo->enable_blame = atoi(value);
67         else if (!strcmp(name, "enable-commit-graph"))
68                 repo->enable_commit_graph = atoi(value);
69         else if (!strcmp(name, "enable-log-filecount"))
70                 repo->enable_log_filecount = atoi(value);
71         else if (!strcmp(name, "enable-log-linecount"))
72                 repo->enable_log_linecount = atoi(value);
73         else if (!strcmp(name, "enable-remote-branches"))
74                 repo->enable_remote_branches = atoi(value);
75         else if (!strcmp(name, "enable-subject-links"))
76                 repo->enable_subject_links = atoi(value);
77         else if (!strcmp(name, "enable-html-serving"))
78                 repo->enable_html_serving = atoi(value);
79         else if (!strcmp(name, "branch-sort")) {
80                 if (!strcmp(value, "age"))
81                         repo->branch_sort = 1;
82                 if (!strcmp(value, "name"))
83                         repo->branch_sort = 0;
84         } else if (!strcmp(name, "commit-sort")) {
85                 if (!strcmp(value, "date"))
86                         repo->commit_sort = 1;
87                 if (!strcmp(value, "topo"))
88                         repo->commit_sort = 2;
89         } else if (!strcmp(name, "max-stats"))
90                 repo->max_stats = cgit_find_stats_period(value, NULL);
91         else if (!strcmp(name, "module-link"))
92                 repo->module_link= xstrdup(value);
93         else if (skip_prefix(name, "module-link.", &path)) {
94                 item = string_list_append(&repo->submodules, xstrdup(path));
95                 item->util = xstrdup(value);
96         } else if (!strcmp(name, "section"))
97                 repo->section = xstrdup(value);
98         else if (!strcmp(name, "snapshot-prefix"))
99                 repo->snapshot_prefix = xstrdup(value);
100         else if (!strcmp(name, "readme") && value != NULL) {
101                 if (repo->readme.items == ctx.cfg.readme.items)
102                         memset(&repo->readme, 0, sizeof(repo->readme));
103                 string_list_append(&repo->readme, xstrdup(value));
104         } else if (!strcmp(name, "logo") && value != NULL)
105                 repo->logo = xstrdup(value);
106         else if (!strcmp(name, "logo-link") && value != NULL)
107                 repo->logo_link = xstrdup(value);
108         else if (!strcmp(name, "hide"))
109                 repo->hide = atoi(value);
110         else if (!strcmp(name, "ignore"))
111                 repo->ignore = atoi(value);
112         else if (ctx.cfg.enable_filter_overrides) {
113                 if (!strcmp(name, "about-filter"))
114                         repo->about_filter = cgit_new_filter(value, ABOUT);
115                 else if (!strcmp(name, "commit-filter"))
116                         repo->commit_filter = cgit_new_filter(value, COMMIT);
117                 else if (!strcmp(name, "source-filter"))
118                         repo->source_filter = cgit_new_filter(value, SOURCE);
119                 else if (!strcmp(name, "email-filter"))
120                         repo->email_filter = cgit_new_filter(value, EMAIL);
121                 else if (!strcmp(name, "owner-filter"))
122                         repo->owner_filter = cgit_new_filter(value, OWNER);
123         }
124 }
125
126 static void config_cb(const char *name, const char *value)
127 {
128         const char *arg;
129
130         if (!strcmp(name, "section"))
131                 ctx.cfg.section = xstrdup(value);
132         else if (!strcmp(name, "repo.url"))
133                 ctx.repo = cgit_add_repo(value);
134         else if (ctx.repo && !strcmp(name, "repo.path"))
135                 ctx.repo->path = trim_end(value, '/');
136         else if (ctx.repo && skip_prefix(name, "repo.", &arg))
137                 repo_config(ctx.repo, arg, value);
138         else if (!strcmp(name, "readme"))
139                 string_list_append(&ctx.cfg.readme, xstrdup(value));
140         else if (!strcmp(name, "root-title"))
141                 ctx.cfg.root_title = xstrdup(value);
142         else if (!strcmp(name, "root-desc"))
143                 ctx.cfg.root_desc = xstrdup(value);
144         else if (!strcmp(name, "root-readme"))
145                 ctx.cfg.root_readme = xstrdup(value);
146         else if (!strcmp(name, "css"))
147                 string_list_append(&ctx.cfg.css, xstrdup(value));
148         else if (!strcmp(name, "js"))
149                 string_list_append(&ctx.cfg.js, xstrdup(value));
150         else if (!strcmp(name, "favicon"))
151                 ctx.cfg.favicon = xstrdup(value);
152         else if (!strcmp(name, "footer"))
153                 ctx.cfg.footer = xstrdup(value);
154         else if (!strcmp(name, "head-include"))
155                 ctx.cfg.head_include = xstrdup(value);
156         else if (!strcmp(name, "header"))
157                 ctx.cfg.header = xstrdup(value);
158         else if (!strcmp(name, "logo"))
159                 ctx.cfg.logo = xstrdup(value);
160         else if (!strcmp(name, "logo-link"))
161                 ctx.cfg.logo_link = xstrdup(value);
162         else if (!strcmp(name, "module-link"))
163                 ctx.cfg.module_link = xstrdup(value);
164         else if (!strcmp(name, "strict-export"))
165                 ctx.cfg.strict_export = xstrdup(value);
166         else if (!strcmp(name, "virtual-root"))
167                 ctx.cfg.virtual_root = ensure_end(value, '/');
168         else if (!strcmp(name, "noplainemail"))
169                 ctx.cfg.noplainemail = atoi(value);
170         else if (!strcmp(name, "noheader"))
171                 ctx.cfg.noheader = atoi(value);
172         else if (!strcmp(name, "snapshots"))
173                 ctx.cfg.snapshots = cgit_parse_snapshots_mask(value);
174         else if (!strcmp(name, "enable-filter-overrides"))
175                 ctx.cfg.enable_filter_overrides = atoi(value);
176         else if (!strcmp(name, "enable-follow-links"))
177                 ctx.cfg.enable_follow_links = atoi(value);
178         else if (!strcmp(name, "enable-http-clone"))
179                 ctx.cfg.enable_http_clone = atoi(value);
180         else if (!strcmp(name, "enable-index-links"))
181                 ctx.cfg.enable_index_links = atoi(value);
182         else if (!strcmp(name, "enable-index-owner"))
183                 ctx.cfg.enable_index_owner = atoi(value);
184         else if (!strcmp(name, "enable-blame"))
185                 ctx.cfg.enable_blame = atoi(value);
186         else if (!strcmp(name, "enable-commit-graph"))
187                 ctx.cfg.enable_commit_graph = atoi(value);
188         else if (!strcmp(name, "enable-log-filecount"))
189                 ctx.cfg.enable_log_filecount = atoi(value);
190         else if (!strcmp(name, "enable-log-linecount"))
191                 ctx.cfg.enable_log_linecount = atoi(value);
192         else if (!strcmp(name, "enable-remote-branches"))
193                 ctx.cfg.enable_remote_branches = atoi(value);
194         else if (!strcmp(name, "enable-subject-links"))
195                 ctx.cfg.enable_subject_links = atoi(value);
196         else if (!strcmp(name, "enable-html-serving"))
197                 ctx.cfg.enable_html_serving = atoi(value);
198         else if (!strcmp(name, "enable-tree-linenumbers"))
199                 ctx.cfg.enable_tree_linenumbers = atoi(value);
200         else if (!strcmp(name, "enable-git-config"))
201                 ctx.cfg.enable_git_config = atoi(value);
202         else if (!strcmp(name, "max-stats"))
203                 ctx.cfg.max_stats = cgit_find_stats_period(value, NULL);
204         else if (!strcmp(name, "cache-size"))
205                 ctx.cfg.cache_size = atoi(value);
206         else if (!strcmp(name, "cache-root"))
207                 ctx.cfg.cache_root = xstrdup(expand_macros(value));
208         else if (!strcmp(name, "cache-root-ttl"))
209                 ctx.cfg.cache_root_ttl = atoi(value);
210         else if (!strcmp(name, "cache-repo-ttl"))
211                 ctx.cfg.cache_repo_ttl = atoi(value);
212         else if (!strcmp(name, "cache-scanrc-ttl"))
213                 ctx.cfg.cache_scanrc_ttl = atoi(value);
214         else if (!strcmp(name, "cache-static-ttl"))
215                 ctx.cfg.cache_static_ttl = atoi(value);
216         else if (!strcmp(name, "cache-dynamic-ttl"))
217                 ctx.cfg.cache_dynamic_ttl = atoi(value);
218         else if (!strcmp(name, "cache-about-ttl"))
219                 ctx.cfg.cache_about_ttl = atoi(value);
220         else if (!strcmp(name, "cache-snapshot-ttl"))
221                 ctx.cfg.cache_snapshot_ttl = atoi(value);
222         else if (!strcmp(name, "case-sensitive-sort"))
223                 ctx.cfg.case_sensitive_sort = atoi(value);
224         else if (!strcmp(name, "about-filter"))
225                 ctx.cfg.about_filter = cgit_new_filter(value, ABOUT);
226         else if (!strcmp(name, "commit-filter"))
227                 ctx.cfg.commit_filter = cgit_new_filter(value, COMMIT);
228         else if (!strcmp(name, "email-filter"))
229                 ctx.cfg.email_filter = cgit_new_filter(value, EMAIL);
230         else if (!strcmp(name, "owner-filter"))
231                 ctx.cfg.owner_filter = cgit_new_filter(value, OWNER);
232         else if (!strcmp(name, "auth-filter"))
233                 ctx.cfg.auth_filter = cgit_new_filter(value, AUTH);
234         else if (!strcmp(name, "embedded"))
235                 ctx.cfg.embedded = atoi(value);
236         else if (!strcmp(name, "max-atom-items"))
237                 ctx.cfg.max_atom_items = atoi(value);
238         else if (!strcmp(name, "max-message-length"))
239                 ctx.cfg.max_msg_len = atoi(value);
240         else if (!strcmp(name, "max-repodesc-length"))
241                 ctx.cfg.max_repodesc_len = atoi(value);
242         else if (!strcmp(name, "max-blob-size"))
243                 ctx.cfg.max_blob_size = atoi(value);
244         else if (!strcmp(name, "max-repo-count")) {
245                 ctx.cfg.max_repo_count = atoi(value);
246                 if (ctx.cfg.max_repo_count <= 0)
247                         ctx.cfg.max_repo_count = INT_MAX;
248         } else if (!strcmp(name, "max-commit-count"))
249                 ctx.cfg.max_commit_count = atoi(value);
250         else if (!strcmp(name, "project-list"))
251                 ctx.cfg.project_list = xstrdup(expand_macros(value));
252         else if (!strcmp(name, "scan-path"))
253                 if (ctx.cfg.cache_size)
254                         process_cached_repolist(expand_macros(value));
255                 else if (ctx.cfg.project_list)
256                         scan_projects(expand_macros(value),
257                                       ctx.cfg.project_list, repo_config);
258                 else
259                         scan_tree(expand_macros(value), repo_config);
260         else if (!strcmp(name, "scan-hidden-path"))
261                 ctx.cfg.scan_hidden_path = atoi(value);
262         else if (!strcmp(name, "section-from-path"))
263                 ctx.cfg.section_from_path = atoi(value);
264         else if (!strcmp(name, "repository-sort"))
265                 ctx.cfg.repository_sort = xstrdup(value);
266         else if (!strcmp(name, "section-sort"))
267                 ctx.cfg.section_sort = atoi(value);
268         else if (!strcmp(name, "source-filter"))
269                 ctx.cfg.source_filter = cgit_new_filter(value, SOURCE);
270         else if (!strcmp(name, "summary-log"))
271                 ctx.cfg.summary_log = atoi(value);
272         else if (!strcmp(name, "summary-branches"))
273                 ctx.cfg.summary_branches = atoi(value);
274         else if (!strcmp(name, "summary-tags"))
275                 ctx.cfg.summary_tags = atoi(value);
276         else if (!strcmp(name, "side-by-side-diffs"))
277                 ctx.cfg.difftype = atoi(value) ? DIFF_SSDIFF : DIFF_UNIFIED;
278         else if (!strcmp(name, "agefile"))
279                 ctx.cfg.agefile = xstrdup(value);
280         else if (!strcmp(name, "mimetype-file"))
281                 ctx.cfg.mimetype_file = xstrdup(value);
282         else if (!strcmp(name, "renamelimit"))
283                 ctx.cfg.renamelimit = atoi(value);
284         else if (!strcmp(name, "remove-suffix"))
285                 ctx.cfg.remove_suffix = atoi(value);
286         else if (!strcmp(name, "robots"))
287                 ctx.cfg.robots = xstrdup(value);
288         else if (!strcmp(name, "clone-prefix"))
289                 ctx.cfg.clone_prefix = xstrdup(value);
290         else if (!strcmp(name, "clone-url"))
291                 ctx.cfg.clone_url = xstrdup(value);
292         else if (!strcmp(name, "local-time"))
293                 ctx.cfg.local_time = atoi(value);
294         else if (!strcmp(name, "commit-sort")) {
295                 if (!strcmp(value, "date"))
296                         ctx.cfg.commit_sort = 1;
297                 if (!strcmp(value, "topo"))
298                         ctx.cfg.commit_sort = 2;
299         } else if (!strcmp(name, "branch-sort")) {
300                 if (!strcmp(value, "age"))
301                         ctx.cfg.branch_sort = 1;
302                 if (!strcmp(value, "name"))
303                         ctx.cfg.branch_sort = 0;
304         } else if (skip_prefix(name, "mimetype.", &arg))
305                 add_mimetype(arg, value);
306         else if (!strcmp(name, "include"))
307                 parse_configfile(expand_macros(value), config_cb);
308 }
309
310 static void querystring_cb(const char *name, const char *value)
311 {
312         if (!value)
313                 value = "";
314
315         if (!strcmp(name,"r")) {
316                 ctx.qry.repo = xstrdup(value);
317                 ctx.repo = cgit_get_repoinfo(value);
318         } else if (!strcmp(name, "p")) {
319                 ctx.qry.page = xstrdup(value);
320         } else if (!strcmp(name, "url")) {
321                 if (*value == '/')
322                         value++;
323                 ctx.qry.url = xstrdup(value);
324                 cgit_parse_url(value);
325         } else if (!strcmp(name, "qt")) {
326                 ctx.qry.grep = xstrdup(value);
327         } else if (!strcmp(name, "q")) {
328                 ctx.qry.search = xstrdup(value);
329         } else if (!strcmp(name, "h")) {
330                 ctx.qry.head = xstrdup(value);
331                 ctx.qry.has_symref = 1;
332         } else if (!strcmp(name, "id")) {
333                 ctx.qry.oid = xstrdup(value);
334                 ctx.qry.has_oid = 1;
335         } else if (!strcmp(name, "id2")) {
336                 ctx.qry.oid2 = xstrdup(value);
337                 ctx.qry.has_oid = 1;
338         } else if (!strcmp(name, "ofs")) {
339                 ctx.qry.ofs = atoi(value);
340         } else if (!strcmp(name, "path")) {
341                 ctx.qry.path = trim_end(value, '/');
342         } else if (!strcmp(name, "name")) {
343                 ctx.qry.name = xstrdup(value);
344         } else if (!strcmp(name, "s")) {
345                 ctx.qry.sort = xstrdup(value);
346         } else if (!strcmp(name, "showmsg")) {
347                 ctx.qry.showmsg = atoi(value);
348         } else if (!strcmp(name, "period")) {
349                 ctx.qry.period = xstrdup(value);
350         } else if (!strcmp(name, "dt")) {
351                 ctx.qry.difftype = atoi(value);
352                 ctx.qry.has_difftype = 1;
353         } else if (!strcmp(name, "ss")) {
354                 /* No longer generated, but there may be links out there. */
355                 ctx.qry.difftype = atoi(value) ? DIFF_SSDIFF : DIFF_UNIFIED;
356                 ctx.qry.has_difftype = 1;
357         } else if (!strcmp(name, "all")) {
358                 ctx.qry.show_all = atoi(value);
359         } else if (!strcmp(name, "context")) {
360                 ctx.qry.context = atoi(value);
361         } else if (!strcmp(name, "ignorews")) {
362                 ctx.qry.ignorews = atoi(value);
363         } else if (!strcmp(name, "follow")) {
364                 ctx.qry.follow = atoi(value);
365         }
366 }
367
368 static void prepare_context(void)
369 {
370         memset(&ctx, 0, sizeof(ctx));
371         ctx.cfg.agefile = "info/web/last-modified";
372         ctx.cfg.cache_size = 0;
373         ctx.cfg.cache_max_create_time = 5;
374         ctx.cfg.cache_root = CGIT_CACHE_ROOT;
375         ctx.cfg.cache_about_ttl = 15;
376         ctx.cfg.cache_snapshot_ttl = 5;
377         ctx.cfg.cache_repo_ttl = 5;
378         ctx.cfg.cache_root_ttl = 5;
379         ctx.cfg.cache_scanrc_ttl = 15;
380         ctx.cfg.cache_dynamic_ttl = 5;
381         ctx.cfg.cache_static_ttl = -1;
382         ctx.cfg.case_sensitive_sort = 1;
383         ctx.cfg.branch_sort = 0;
384         ctx.cfg.commit_sort = 0;
385         ctx.cfg.logo = "/cgit.png";
386         ctx.cfg.favicon = "/favicon.ico";
387         ctx.cfg.local_time = 0;
388         ctx.cfg.enable_http_clone = 1;
389         ctx.cfg.enable_index_owner = 1;
390         ctx.cfg.enable_tree_linenumbers = 1;
391         ctx.cfg.enable_git_config = 0;
392         ctx.cfg.max_repo_count = 50;
393         ctx.cfg.max_commit_count = 50;
394         ctx.cfg.max_lock_attempts = 5;
395         ctx.cfg.max_msg_len = 80;
396         ctx.cfg.max_repodesc_len = 80;
397         ctx.cfg.max_blob_size = 0;
398         ctx.cfg.max_stats = 0;
399         ctx.cfg.project_list = NULL;
400         ctx.cfg.renamelimit = -1;
401         ctx.cfg.remove_suffix = 0;
402         ctx.cfg.robots = "index, nofollow";
403         ctx.cfg.root_title = "Git repository browser";
404         ctx.cfg.root_desc = "a fast webinterface for the git dscm";
405         ctx.cfg.scan_hidden_path = 0;
406         ctx.cfg.script_name = CGIT_SCRIPT_NAME;
407         ctx.cfg.section = "";
408         ctx.cfg.repository_sort = "name";
409         ctx.cfg.section_sort = 1;
410         ctx.cfg.summary_branches = 10;
411         ctx.cfg.summary_log = 10;
412         ctx.cfg.summary_tags = 10;
413         ctx.cfg.max_atom_items = 10;
414         ctx.cfg.difftype = DIFF_UNIFIED;
415         ctx.env.cgit_config = getenv("CGIT_CONFIG");
416         ctx.env.http_host = getenv("HTTP_HOST");
417         ctx.env.https = getenv("HTTPS");
418         ctx.env.no_http = getenv("NO_HTTP");
419         ctx.env.path_info = getenv("PATH_INFO");
420         ctx.env.query_string = getenv("QUERY_STRING");
421         ctx.env.request_method = getenv("REQUEST_METHOD");
422         ctx.env.script_name = getenv("SCRIPT_NAME");
423         ctx.env.server_name = getenv("SERVER_NAME");
424         ctx.env.server_port = getenv("SERVER_PORT");
425         ctx.env.http_cookie = getenv("HTTP_COOKIE");
426         ctx.env.http_referer = getenv("HTTP_REFERER");
427         ctx.env.content_length = getenv("CONTENT_LENGTH") ? strtoul(getenv("CONTENT_LENGTH"), NULL, 10) : 0;
428         ctx.env.authenticated = 0;
429         ctx.page.mimetype = "text/html";
430         ctx.page.charset = PAGE_ENCODING;
431         ctx.page.filename = NULL;
432         ctx.page.size = 0;
433         ctx.page.modified = time(NULL);
434         ctx.page.expires = ctx.page.modified;
435         ctx.page.etag = NULL;
436         string_list_init_dup(&ctx.cfg.mimetypes);
437         if (ctx.env.script_name)
438                 ctx.cfg.script_name = xstrdup(ctx.env.script_name);
439         if (ctx.env.query_string)
440                 ctx.qry.raw = xstrdup(ctx.env.query_string);
441         if (!ctx.env.cgit_config)
442                 ctx.env.cgit_config = CGIT_CONFIG;
443 }
444
445 struct refmatch {
446         char *req_ref;
447         char *first_ref;
448         int match;
449 };
450
451 static int find_current_ref(const char *refname, const struct object_id *oid,
452                             int flags, void *cb_data)
453 {
454         struct refmatch *info;
455
456         info = (struct refmatch *)cb_data;
457         if (!strcmp(refname, info->req_ref))
458                 info->match = 1;
459         if (!info->first_ref)
460                 info->first_ref = xstrdup(refname);
461         return info->match;
462 }
463
464 static void free_refmatch_inner(struct refmatch *info)
465 {
466         if (info->first_ref)
467                 free(info->first_ref);
468 }
469
470 static char *find_default_branch(struct cgit_repo *repo)
471 {
472         struct refmatch info;
473         char *ref;
474
475         info.req_ref = repo->defbranch;
476         info.first_ref = NULL;
477         info.match = 0;
478         refs_for_each_branch_ref(get_main_ref_store(the_repository),
479                                  find_current_ref, &info);
480         if (info.match)
481                 ref = info.req_ref;
482         else
483                 ref = info.first_ref;
484         if (ref)
485                 ref = xstrdup(ref);
486         free_refmatch_inner(&info);
487
488         return ref;
489 }
490
491 static char *guess_defbranch(void)
492 {
493         const char *ref, *refname;
494         struct object_id oid;
495
496         ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
497                                      "HEAD", 0, &oid, NULL);
498         if (!ref || !skip_prefix(ref, "refs/heads/", &refname))
499                 return "master";
500         return xstrdup(refname);
501 }
502
503 /* The caller must free filename and ref after calling this. */
504 static inline void parse_readme(const char *readme, char **filename, char **ref, struct cgit_repo *repo)
505 {
506         const char *colon;
507
508         *filename = NULL;
509         *ref = NULL;
510
511         if (!readme || !readme[0])
512                 return;
513
514         /* Check if the readme is tracked in the git repo. */
515         colon = strchr(readme, ':');
516         if (colon && strlen(colon) > 1) {
517                 /* If it starts with a colon, we want to use head given
518                  * from query or the default branch */
519                 if (colon == readme && ctx.qry.head)
520                         *ref = xstrdup(ctx.qry.head);
521                 else if (colon == readme && repo->defbranch)
522                         *ref = xstrdup(repo->defbranch);
523                 else
524                         *ref = xstrndup(readme, colon - readme);
525                 readme = colon + 1;
526         }
527
528         /* Prepend repo path to relative readme path unless tracked. */
529         if (!(*ref) && readme[0] != '/')
530                 *filename = fmtalloc("%s/%s", repo->path, readme);
531         else
532                 *filename = xstrdup(readme);
533 }
534 static void choose_readme(struct cgit_repo *repo)
535 {
536         int found;
537         char *filename, *ref;
538         struct string_list_item *entry;
539
540         if (!repo->readme.nr)
541                 return;
542
543         found = 0;
544         for_each_string_list_item(entry, &repo->readme) {
545                 parse_readme(entry->string, &filename, &ref, repo);
546                 if (!filename) {
547                         free(filename);
548                         free(ref);
549                         continue;
550                 }
551                 if (ref) {
552                         if (cgit_ref_path_exists(filename, ref, 1)) {
553                                 found = 1;
554                                 break;
555                         }
556                 }
557                 else if (!access(filename, R_OK)) {
558                         found = 1;
559                         break;
560                 }
561                 free(filename);
562                 free(ref);
563         }
564         repo->readme.strdup_strings = 1;
565         string_list_clear(&repo->readme, 0);
566         repo->readme.strdup_strings = 0;
567         if (found)
568                 string_list_append(&repo->readme, filename)->util = ref;
569 }
570
571 static void print_no_repo_clone_urls(const char *url)
572 {
573         html("<tr><td><a rel='vcs-git' href='");
574         html_url_path(url);
575         html("' title='");
576         html_attr(ctx.repo->name);
577         html(" Git repository'>");
578         html_txt(url);
579         html("</a></td></tr>\n");
580 }
581
582 static void prepare_repo_env(int *nongit)
583 {
584         /* The path to the git repository. */
585         setenv("GIT_DIR", ctx.repo->path, 1);
586
587         /* Setup the git directory and initialize the notes system. Both of these
588          * load local configuration from the git repository, so we do them both while
589          * the HOME variables are unset. */
590         setup_git_directory_gently(nongit);
591         load_display_notes(NULL);
592 }
593
594 static int prepare_repo_cmd(int nongit)
595 {
596         struct object_id oid;
597         int rc;
598
599         if (nongit) {
600                 const char *name = ctx.repo->name;
601                 rc = errno;
602                 ctx.page.title = fmtalloc("%s - %s", ctx.cfg.root_title,
603                                                 "config error");
604                 ctx.repo = NULL;
605                 cgit_print_http_headers();
606                 cgit_print_docstart();
607                 cgit_print_pageheader();
608                 cgit_print_error("Failed to open %s: %s", name,
609                                  rc ? strerror(rc) : "Not a valid git repository");
610                 cgit_print_docend();
611                 return 1;
612         }
613         ctx.page.title = fmtalloc("%s - %s", ctx.repo->name, ctx.repo->desc);
614
615         if (!ctx.repo->defbranch)
616                 ctx.repo->defbranch = guess_defbranch();
617
618         if (!ctx.qry.head) {
619                 ctx.qry.nohead = 1;
620                 ctx.qry.head = find_default_branch(ctx.repo);
621         }
622
623         if (!ctx.qry.head) {
624                 cgit_print_http_headers();
625                 cgit_print_docstart();
626                 cgit_print_pageheader();
627                 cgit_print_error("Repository seems to be empty");
628                 if (!strcmp(ctx.qry.page, "summary")) {
629                         html("<table class='list'><tr class='nohover'><td>&nbsp;</td></tr><tr class='nohover'><th class='left'>Clone</th></tr>\n");
630                         cgit_prepare_repo_env(ctx.repo);
631                         cgit_add_clone_urls(print_no_repo_clone_urls);
632                         html("</table>\n");
633                 }
634                 cgit_print_docend();
635                 return 1;
636         }
637
638         if (repo_get_oid(the_repository, ctx.qry.head, &oid)) {
639                 char *old_head = ctx.qry.head;
640                 ctx.qry.head = xstrdup(ctx.repo->defbranch);
641                 cgit_print_error_page(404, "Not found",
642                                 "Invalid branch: %s", old_head);
643                 free(old_head);
644                 return 1;
645         }
646         string_list_sort(&ctx.repo->submodules);
647         cgit_prepare_repo_env(ctx.repo);
648         choose_readme(ctx.repo);
649         return 0;
650 }
651
652 static inline void open_auth_filter(const char *function)
653 {
654         cgit_open_filter(ctx.cfg.auth_filter, function,
655                 ctx.env.http_cookie ? ctx.env.http_cookie : "",
656                 ctx.env.request_method ? ctx.env.request_method : "",
657                 ctx.env.query_string ? ctx.env.query_string : "",
658                 ctx.env.http_referer ? ctx.env.http_referer : "",
659                 ctx.env.path_info ? ctx.env.path_info : "",
660                 ctx.env.http_host ? ctx.env.http_host : "",
661                 ctx.env.https ? ctx.env.https : "",
662                 ctx.qry.repo ? ctx.qry.repo : "",
663                 ctx.qry.page ? ctx.qry.page : "",
664                 cgit_currentfullurl(),
665                 cgit_loginurl());
666 }
667
668 /* We intentionally keep this rather small, instead of looping and
669  * feeding it to the filter a couple bytes at a time. This way, the
670  * filter itself does not need to handle any denial of service or
671  * buffer bloat issues. If this winds up being too small, people
672  * will complain on the mailing list, and we'll increase it as needed. */
673 #define MAX_AUTHENTICATION_POST_BYTES 4096
674 /* The filter is expected to spit out "Status: " and all headers. */
675 static inline void authenticate_post(void)
676 {
677         char buffer[MAX_AUTHENTICATION_POST_BYTES];
678         ssize_t len;
679
680         open_auth_filter("authenticate-post");
681         len = ctx.env.content_length;
682         if (len > MAX_AUTHENTICATION_POST_BYTES)
683                 len = MAX_AUTHENTICATION_POST_BYTES;
684         if ((len = read(STDIN_FILENO, buffer, len)) < 0)
685                 die_errno("Could not read POST from stdin");
686         if (write(STDOUT_FILENO, buffer, len) < 0)
687                 die_errno("Could not write POST to stdout");
688         cgit_close_filter(ctx.cfg.auth_filter);
689         exit(0);
690 }
691
692 static inline void authenticate_cookie(void)
693 {
694         /* If we don't have an auth_filter, consider all cookies valid, and thus return early. */
695         if (!ctx.cfg.auth_filter) {
696                 ctx.env.authenticated = 1;
697                 return;
698         }
699
700         /* If we're having something POST'd to /login, we're authenticating POST,
701          * instead of the cookie, so call authenticate_post and bail out early.
702          * This pattern here should match /?p=login with POST. */
703         if (ctx.env.request_method && ctx.qry.page && !ctx.repo && \
704             !strcmp(ctx.env.request_method, "POST") && !strcmp(ctx.qry.page, "login")) {
705                 authenticate_post();
706                 return;
707         }
708
709         /* If we've made it this far, we're authenticating the cookie for real, so do that. */
710         open_auth_filter("authenticate-cookie");
711         ctx.env.authenticated = cgit_close_filter(ctx.cfg.auth_filter);
712 }
713
714 static void process_request(void)
715 {
716         struct cgit_cmd *cmd;
717         int nongit = 0;
718
719         /* If we're not yet authenticated, no matter what page we're on,
720          * display the authentication body from the auth_filter. This should
721          * never be cached. */
722         if (!ctx.env.authenticated) {
723                 ctx.page.title = "Authentication Required";
724                 cgit_print_http_headers();
725                 cgit_print_docstart();
726                 cgit_print_pageheader();
727                 open_auth_filter("body");
728                 cgit_close_filter(ctx.cfg.auth_filter);
729                 cgit_print_docend();
730                 return;
731         }
732
733         if (ctx.repo)
734                 prepare_repo_env(&nongit);
735
736         cmd = cgit_get_cmd();
737         if (!cmd) {
738                 ctx.page.title = "cgit error";
739                 cgit_print_error_page(404, "Not found", "Invalid request");
740                 return;
741         }
742
743         if (!ctx.cfg.enable_http_clone && cmd->is_clone) {
744                 ctx.page.title = "cgit error";
745                 cgit_print_error_page(404, "Not found", "Invalid request");
746                 return;
747         }
748
749         if (cmd->want_repo && !ctx.repo) {
750                 cgit_print_error_page(400, "Bad request",
751                                 "No repository selected");
752                 return;
753         }
754
755         /* If cmd->want_vpath is set, assume ctx.qry.path contains a "virtual"
756          * in-project path limit to be made available at ctx.qry.vpath.
757          * Otherwise, no path limit is in effect (ctx.qry.vpath = NULL).
758          */
759         ctx.qry.vpath = cmd->want_vpath ? ctx.qry.path : NULL;
760
761         if (ctx.repo && prepare_repo_cmd(nongit))
762                 return;
763
764         cmd->fn();
765 }
766
767 static int cmp_repos(const void *a, const void *b)
768 {
769         const struct cgit_repo *ra = a, *rb = b;
770         return strcmp(ra->url, rb->url);
771 }
772
773 static char *build_snapshot_setting(int bitmap)
774 {
775         const struct cgit_snapshot_format *f;
776         struct strbuf result = STRBUF_INIT;
777
778         for (f = cgit_snapshot_formats; f->suffix; f++) {
779                 if (cgit_snapshot_format_bit(f) & bitmap) {
780                         if (result.len)
781                                 strbuf_addch(&result, ' ');
782                         strbuf_addstr(&result, f->suffix);
783                 }
784         }
785         return strbuf_detach(&result, NULL);
786 }
787
788 static char *get_first_line(char *txt)
789 {
790         char *t = xstrdup(txt);
791         char *p = strchr(t, '\n');
792         if (p)
793                 *p = '\0';
794         return t;
795 }
796
797 static void print_repo(FILE *f, struct cgit_repo *repo)
798 {
799         struct string_list_item *item;
800         fprintf(f, "repo.url=%s\n", repo->url);
801         fprintf(f, "repo.name=%s\n", repo->name);
802         fprintf(f, "repo.path=%s\n", repo->path);
803         if (repo->owner)
804                 fprintf(f, "repo.owner=%s\n", repo->owner);
805         if (repo->desc) {
806                 char *tmp = get_first_line(repo->desc);
807                 fprintf(f, "repo.desc=%s\n", tmp);
808                 free(tmp);
809         }
810         for_each_string_list_item(item, &repo->readme) {
811                 if (item->util)
812                         fprintf(f, "repo.readme=%s:%s\n", (char *)item->util, item->string);
813                 else
814                         fprintf(f, "repo.readme=%s\n", item->string);
815         }
816         if (repo->defbranch)
817                 fprintf(f, "repo.defbranch=%s\n", repo->defbranch);
818         if (repo->extra_head_content)
819                 fprintf(f, "repo.extra-head-content=%s\n", repo->extra_head_content);
820         if (repo->module_link)
821                 fprintf(f, "repo.module-link=%s\n", repo->module_link);
822         if (repo->section)
823                 fprintf(f, "repo.section=%s\n", repo->section);
824         if (repo->homepage)
825                 fprintf(f, "repo.homepage=%s\n", repo->homepage);
826         if (repo->clone_url)
827                 fprintf(f, "repo.clone-url=%s\n", repo->clone_url);
828         fprintf(f, "repo.enable-blame=%d\n",
829                 repo->enable_blame);
830         fprintf(f, "repo.enable-commit-graph=%d\n",
831                 repo->enable_commit_graph);
832         fprintf(f, "repo.enable-log-filecount=%d\n",
833                 repo->enable_log_filecount);
834         fprintf(f, "repo.enable-log-linecount=%d\n",
835                 repo->enable_log_linecount);
836         if (repo->about_filter && repo->about_filter != ctx.cfg.about_filter)
837                 cgit_fprintf_filter(repo->about_filter, f, "repo.about-filter=");
838         if (repo->commit_filter && repo->commit_filter != ctx.cfg.commit_filter)
839                 cgit_fprintf_filter(repo->commit_filter, f, "repo.commit-filter=");
840         if (repo->source_filter && repo->source_filter != ctx.cfg.source_filter)
841                 cgit_fprintf_filter(repo->source_filter, f, "repo.source-filter=");
842         if (repo->email_filter && repo->email_filter != ctx.cfg.email_filter)
843                 cgit_fprintf_filter(repo->email_filter, f, "repo.email-filter=");
844         if (repo->owner_filter && repo->owner_filter != ctx.cfg.owner_filter)
845                 cgit_fprintf_filter(repo->owner_filter, f, "repo.owner-filter=");
846         if (repo->snapshots != ctx.cfg.snapshots) {
847                 char *tmp = build_snapshot_setting(repo->snapshots);
848                 fprintf(f, "repo.snapshots=%s\n", tmp ? tmp : "");
849                 free(tmp);
850         }
851         if (repo->snapshot_prefix)
852                 fprintf(f, "repo.snapshot-prefix=%s\n", repo->snapshot_prefix);
853         if (repo->max_stats != ctx.cfg.max_stats)
854                 fprintf(f, "repo.max-stats=%s\n",
855                         cgit_find_stats_periodname(repo->max_stats));
856         if (repo->logo)
857                 fprintf(f, "repo.logo=%s\n", repo->logo);
858         if (repo->logo_link)
859                 fprintf(f, "repo.logo-link=%s\n", repo->logo_link);
860         fprintf(f, "repo.enable-remote-branches=%d\n", repo->enable_remote_branches);
861         fprintf(f, "repo.enable-subject-links=%d\n", repo->enable_subject_links);
862         fprintf(f, "repo.enable-html-serving=%d\n", repo->enable_html_serving);
863         if (repo->branch_sort == 1)
864                 fprintf(f, "repo.branch-sort=age\n");
865         if (repo->commit_sort) {
866                 if (repo->commit_sort == 1)
867                         fprintf(f, "repo.commit-sort=date\n");
868                 else if (repo->commit_sort == 2)
869                         fprintf(f, "repo.commit-sort=topo\n");
870         }
871         fprintf(f, "repo.hide=%d\n", repo->hide);
872         fprintf(f, "repo.ignore=%d\n", repo->ignore);
873         fprintf(f, "\n");
874 }
875
876 static void print_repolist(FILE *f, struct cgit_repolist *list, int start)
877 {
878         int i;
879
880         for (i = start; i < list->count; i++)
881                 print_repo(f, &list->repos[i]);
882 }
883
884 /* Scan 'path' for git repositories, save the resulting repolist in 'cached_rc'
885  * and return 0 on success.
886  */
887 static int generate_cached_repolist(const char *path, const char *cached_rc)
888 {
889         struct strbuf locked_rc = STRBUF_INIT;
890         int result = 0;
891         int idx;
892         FILE *f;
893
894         strbuf_addf(&locked_rc, "%s.lock", cached_rc);
895         f = fopen(locked_rc.buf, "wx");
896         if (!f) {
897                 /* Inform about the error unless the lockfile already existed,
898                  * since that only means we've got concurrent requests.
899                  */
900                 result = errno;
901                 if (result != EEXIST)
902                         fprintf(stderr, "[cgit] Error opening %s: %s (%d)\n",
903                                 locked_rc.buf, strerror(result), result);
904                 goto out;
905         }
906         idx = cgit_repolist.count;
907         if (ctx.cfg.project_list)
908                 scan_projects(path, ctx.cfg.project_list, repo_config);
909         else
910                 scan_tree(path, repo_config);
911         print_repolist(f, &cgit_repolist, idx);
912         if (rename(locked_rc.buf, cached_rc))
913                 fprintf(stderr, "[cgit] Error renaming %s to %s: %s (%d)\n",
914                         locked_rc.buf, cached_rc, strerror(errno), errno);
915         fclose(f);
916 out:
917         strbuf_release(&locked_rc);
918         return result;
919 }
920
921 static void process_cached_repolist(const char *path)
922 {
923         struct stat st;
924         struct strbuf cached_rc = STRBUF_INIT;
925         time_t age;
926         unsigned long hash;
927
928         hash = hash_str(path);
929         if (ctx.cfg.project_list)
930                 hash += hash_str(ctx.cfg.project_list);
931         strbuf_addf(&cached_rc, "%s/rc-%8lx", ctx.cfg.cache_root, hash);
932
933         if (stat(cached_rc.buf, &st)) {
934                 /* Nothing is cached, we need to scan without forking. And
935                  * if we fail to generate a cached repolist, we need to
936                  * invoke scan_tree manually.
937                  */
938                 if (generate_cached_repolist(path, cached_rc.buf)) {
939                         if (ctx.cfg.project_list)
940                                 scan_projects(path, ctx.cfg.project_list,
941                                               repo_config);
942                         else
943                                 scan_tree(path, repo_config);
944                 }
945                 goto out;
946         }
947
948         parse_configfile(cached_rc.buf, config_cb);
949
950         /* If the cached configfile hasn't expired, lets exit now */
951         age = time(NULL) - st.st_mtime;
952         if (age <= (ctx.cfg.cache_scanrc_ttl * 60))
953                 goto out;
954
955         /* The cached repolist has been parsed, but it was old. So lets
956          * rescan the specified path and generate a new cached repolist
957          * in a child-process to avoid latency for the current request.
958          */
959         if (fork())
960                 goto out;
961
962         exit(generate_cached_repolist(path, cached_rc.buf));
963 out:
964         strbuf_release(&cached_rc);
965 }
966
967 static void cgit_parse_args(int argc, const char **argv)
968 {
969         int i;
970         const char *arg;
971         int scan = 0;
972
973         for (i = 1; i < argc; i++) {
974                 if (!strcmp(argv[i], "--version")) {
975                         printf("CGit %s | https://git.zx2c4.com/cgit/\n\nCompiled in features:\n", CGIT_VERSION);
976 #ifdef NO_LUA
977                         printf("[-] ");
978 #else
979                         printf("[+] ");
980 #endif
981                         printf("Lua scripting\n");
982 #ifndef HAVE_LINUX_SENDFILE
983                         printf("[-] ");
984 #else
985                         printf("[+] ");
986 #endif
987                         printf("Linux sendfile() usage\n");
988
989                         exit(0);
990                 }
991                 if (skip_prefix(argv[i], "--cache=", &arg)) {
992                         ctx.cfg.cache_root = xstrdup(arg);
993                 } else if (!strcmp(argv[i], "--nohttp")) {
994                         ctx.env.no_http = "1";
995                 } else if (skip_prefix(argv[i], "--query=", &arg)) {
996                         ctx.qry.raw = xstrdup(arg);
997                 } else if (skip_prefix(argv[i], "--repo=", &arg)) {
998                         ctx.qry.repo = xstrdup(arg);
999                 } else if (skip_prefix(argv[i], "--page=", &arg)) {
1000                         ctx.qry.page = xstrdup(arg);
1001                 } else if (skip_prefix(argv[i], "--head=", &arg)) {
1002                         ctx.qry.head = xstrdup(arg);
1003                         ctx.qry.has_symref = 1;
1004                 } else if (skip_prefix(argv[i], "--oid=", &arg)) {
1005                         ctx.qry.oid = xstrdup(arg);
1006                         ctx.qry.has_oid = 1;
1007                 } else if (skip_prefix(argv[i], "--ofs=", &arg)) {
1008                         ctx.qry.ofs = atoi(arg);
1009                 } else if (skip_prefix(argv[i], "--scan-tree=", &arg) ||
1010                            skip_prefix(argv[i], "--scan-path=", &arg)) {
1011                         /*
1012                          * HACK: The global snapshot bit mask defines the set
1013                          * of allowed snapshot formats, but the config file
1014                          * hasn't been parsed yet so the mask is currently 0.
1015                          * By setting all bits high before scanning we make
1016                          * sure that any in-repo cgitrc snapshot setting is
1017                          * respected by scan_tree().
1018                          *
1019                          * NOTE: We assume that there aren't more than 8
1020                          * different snapshot formats supported by cgit...
1021                          */
1022                         ctx.cfg.snapshots = 0xFF;
1023                         scan++;
1024                         scan_tree(arg, repo_config);
1025                 }
1026         }
1027         if (scan) {
1028                 qsort(cgit_repolist.repos, cgit_repolist.count,
1029                         sizeof(struct cgit_repo), cmp_repos);
1030                 print_repolist(stdout, &cgit_repolist, 0);
1031                 exit(0);
1032         }
1033 }
1034
1035 static int calc_ttl(void)
1036 {
1037         if (!ctx.repo)
1038                 return ctx.cfg.cache_root_ttl;
1039
1040         if (!ctx.qry.page)
1041                 return ctx.cfg.cache_repo_ttl;
1042
1043         if (!strcmp(ctx.qry.page, "about"))
1044                 return ctx.cfg.cache_about_ttl;
1045
1046         if (!strcmp(ctx.qry.page, "snapshot"))
1047                 return ctx.cfg.cache_snapshot_ttl;
1048
1049         if (ctx.qry.has_oid)
1050                 return ctx.cfg.cache_static_ttl;
1051
1052         if (ctx.qry.has_symref)
1053                 return ctx.cfg.cache_dynamic_ttl;
1054
1055         return ctx.cfg.cache_repo_ttl;
1056 }
1057
1058 int cmd_main(int argc, const char **argv)
1059 {
1060         const char *path;
1061         int err, ttl;
1062
1063         cgit_init_filters();
1064         atexit(cgit_cleanup_filters);
1065
1066         prepare_context();
1067         cgit_repolist.length = 0;
1068         cgit_repolist.count = 0;
1069         cgit_repolist.repos = NULL;
1070
1071         cgit_parse_args(argc, argv);
1072         parse_configfile(expand_macros(ctx.env.cgit_config), config_cb);
1073         ctx.repo = NULL;
1074         http_parse_querystring(ctx.qry.raw, querystring_cb);
1075
1076         /* If virtual-root isn't specified in cgitrc, lets pretend
1077          * that virtual-root equals SCRIPT_NAME, minus any possibly
1078          * trailing slashes.
1079          */
1080         if (!ctx.cfg.virtual_root && ctx.cfg.script_name)
1081                 ctx.cfg.virtual_root = ensure_end(ctx.cfg.script_name, '/');
1082
1083         /* If no url parameter is specified on the querystring, lets
1084          * use PATH_INFO as url. This allows cgit to work with virtual
1085          * urls without the need for rewriterules in the webserver (as
1086          * long as PATH_INFO is included in the cache lookup key).
1087          */
1088         path = ctx.env.path_info;
1089         if (!ctx.qry.url && path) {
1090                 if (path[0] == '/')
1091                         path++;
1092                 ctx.qry.url = xstrdup(path);
1093                 if (ctx.qry.raw) {
1094                         char *newqry = fmtalloc("%s?%s", path, ctx.qry.raw);
1095                         free(ctx.qry.raw);
1096                         ctx.qry.raw = newqry;
1097                 } else
1098                         ctx.qry.raw = xstrdup(ctx.qry.url);
1099                 cgit_parse_url(ctx.qry.url);
1100         }
1101
1102         /* Before we go any further, we set ctx.env.authenticated by checking to see
1103          * if the supplied cookie is valid. All cookies are valid if there is no
1104          * auth_filter. If there is an auth_filter, the filter decides. */
1105         authenticate_cookie();
1106
1107         ttl = calc_ttl();
1108         if (ttl < 0)
1109                 ctx.page.expires += 10 * 365 * 24 * 60 * 60; /* 10 years */
1110         else
1111                 ctx.page.expires += ttl * 60;
1112         if (!ctx.env.authenticated || (ctx.env.request_method && !strcmp(ctx.env.request_method, "HEAD")))
1113                 ctx.cfg.cache_size = 0;
1114         err = cache_process(ctx.cfg.cache_size, ctx.cfg.cache_root,
1115                             ctx.qry.raw, ttl, process_request);
1116         cgit_cleanup_filters();
1117         if (err)
1118                 cgit_print_error("Error processing page: %s (%d)",
1119                                  strerror(err), err);
1120         return err;
1121 }