]> gitweb.ps.run Git - ps-cgit/blob - cgit.c
use favicon by default
[ps-cgit] / cgit.c
1 /* cgit.c: cgi for the git scm
2  *
3  * Copyright (C) 2006 Lars Hjemli
4  * Copyright (C) 2010-2013 Jason A. Donenfeld <Jason@zx2c4.com>
5  *
6  * Licensed under GNU General Public License v2
7  *   (see COPYING for full license text)
8  */
9
10 #include "cgit.h"
11 #include "cache.h"
12 #include "cmd.h"
13 #include "configfile.h"
14 #include "html.h"
15 #include "ui-shared.h"
16 #include "ui-stats.h"
17 #include "ui-blob.h"
18 #include "ui-summary.h"
19 #include "scan-tree.h"
20
21 const char *cgit_version = CGIT_VERSION;
22
23 static void add_mimetype(const char *name, const char *value)
24 {
25         struct string_list_item *item;
26
27         item = string_list_insert(&ctx.cfg.mimetypes, xstrdup(name));
28         item->util = xstrdup(value);
29 }
30
31 static struct cgit_filter *new_filter(const char *cmd, filter_type filtertype)
32 {
33         struct cgit_filter *f;
34         int args_size = 0;
35         int extra_args;
36
37         if (!cmd || !cmd[0])
38                 return NULL;
39
40         switch (filtertype) {
41                 case SOURCE:
42                 case ABOUT:
43                         extra_args = 1;
44                         break;
45
46                 case COMMIT:
47                 default:
48                         extra_args = 0;
49                         break;
50         }
51
52         f = xmalloc(sizeof(struct cgit_filter));
53         f->cmd = xstrdup(cmd);
54         args_size = (2 + extra_args) * sizeof(char *);
55         f->argv = xmalloc(args_size);
56         memset(f->argv, 0, args_size);
57         f->argv[0] = f->cmd;
58         return f;
59 }
60
61 static void process_cached_repolist(const char *path);
62
63 static void repo_config(struct cgit_repo *repo, const char *name, const char *value)
64 {
65         struct string_list_item *item;
66
67         if (!strcmp(name, "name"))
68                 repo->name = xstrdup(value);
69         else if (!strcmp(name, "clone-url"))
70                 repo->clone_url = xstrdup(value);
71         else if (!strcmp(name, "desc"))
72                 repo->desc = xstrdup(value);
73         else if (!strcmp(name, "owner"))
74                 repo->owner = xstrdup(value);
75         else if (!strcmp(name, "defbranch"))
76                 repo->defbranch = xstrdup(value);
77         else if (!strcmp(name, "snapshots"))
78                 repo->snapshots = ctx.cfg.snapshots & cgit_parse_snapshots_mask(value);
79         else if (!strcmp(name, "enable-commit-graph"))
80                 repo->enable_commit_graph = atoi(value);
81         else if (!strcmp(name, "enable-log-filecount"))
82                 repo->enable_log_filecount = atoi(value);
83         else if (!strcmp(name, "enable-log-linecount"))
84                 repo->enable_log_linecount = atoi(value);
85         else if (!strcmp(name, "enable-remote-branches"))
86                 repo->enable_remote_branches = atoi(value);
87         else if (!strcmp(name, "enable-subject-links"))
88                 repo->enable_subject_links = atoi(value);
89         else if (!strcmp(name, "branch-sort")) {
90                 if (!strcmp(value, "age"))
91                         repo->branch_sort = 1;
92                 if (!strcmp(value, "name"))
93                         repo->branch_sort = 0;
94         } else if (!strcmp(name, "commit-sort")) {
95                 if (!strcmp(value, "date"))
96                         repo->commit_sort = 1;
97                 if (!strcmp(value, "topo"))
98                         repo->commit_sort = 2;
99         } else if (!strcmp(name, "max-stats"))
100                 repo->max_stats = cgit_find_stats_period(value, NULL);
101         else if (!strcmp(name, "module-link"))
102                 repo->module_link= xstrdup(value);
103         else if (!prefixcmp(name, "module-link.")) {
104                 item = string_list_append(&repo->submodules, xstrdup(name + 12));
105                 item->util = xstrdup(value);
106         } else if (!strcmp(name, "section"))
107                 repo->section = xstrdup(value);
108         else if (!strcmp(name, "readme") && value != NULL) {
109                 if (repo->readme.items == ctx.cfg.readme.items)
110                         memset(&repo->readme, 0, sizeof(repo->readme));
111                 string_list_append(&repo->readme, xstrdup(value));
112         } else if (!strcmp(name, "logo") && value != NULL)
113                 repo->logo = xstrdup(value);
114         else if (!strcmp(name, "logo-link") && value != NULL)
115                 repo->logo_link = xstrdup(value);
116         else if (ctx.cfg.enable_filter_overrides) {
117                 if (!strcmp(name, "about-filter"))
118                         repo->about_filter = new_filter(value, ABOUT);
119                 else if (!strcmp(name, "commit-filter"))
120                         repo->commit_filter = new_filter(value, COMMIT);
121                 else if (!strcmp(name, "source-filter"))
122                         repo->source_filter = new_filter(value, SOURCE);
123         }
124 }
125
126 static void config_cb(const char *name, const char *value)
127 {
128         if (!strcmp(name, "section") || !strcmp(name, "repo.group"))
129                 ctx.cfg.section = xstrdup(value);
130         else if (!strcmp(name, "repo.url"))
131                 ctx.repo = cgit_add_repo(value);
132         else if (ctx.repo && !strcmp(name, "repo.path"))
133                 ctx.repo->path = trim_end(value, '/');
134         else if (ctx.repo && !prefixcmp(name, "repo."))
135                 repo_config(ctx.repo, name + 5, value);
136         else if (!strcmp(name, "readme") && value != NULL)
137                 string_list_append(&ctx.cfg.readme, xstrdup(value));
138         else if (!strcmp(name, "root-title"))
139                 ctx.cfg.root_title = xstrdup(value);
140         else if (!strcmp(name, "root-desc"))
141                 ctx.cfg.root_desc = xstrdup(value);
142         else if (!strcmp(name, "root-readme"))
143                 ctx.cfg.root_readme = xstrdup(value);
144         else if (!strcmp(name, "css"))
145                 ctx.cfg.css = xstrdup(value);
146         else if (!strcmp(name, "favicon"))
147                 ctx.cfg.favicon = xstrdup(value);
148         else if (!strcmp(name, "footer"))
149                 ctx.cfg.footer = xstrdup(value);
150         else if (!strcmp(name, "head-include"))
151                 ctx.cfg.head_include = xstrdup(value);
152         else if (!strcmp(name, "header"))
153                 ctx.cfg.header = xstrdup(value);
154         else if (!strcmp(name, "logo"))
155                 ctx.cfg.logo = xstrdup(value);
156         else if (!strcmp(name, "index-header"))
157                 ctx.cfg.index_header = xstrdup(value);
158         else if (!strcmp(name, "index-info"))
159                 ctx.cfg.index_info = 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, "nocache"))
169                 ctx.cfg.nocache = atoi(value);
170         else if (!strcmp(name, "noplainemail"))
171                 ctx.cfg.noplainemail = atoi(value);
172         else if (!strcmp(name, "noheader"))
173                 ctx.cfg.noheader = atoi(value);
174         else if (!strcmp(name, "snapshots"))
175                 ctx.cfg.snapshots = cgit_parse_snapshots_mask(value);
176         else if (!strcmp(name, "enable-filter-overrides"))
177                 ctx.cfg.enable_filter_overrides = 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-commit-graph"))
185                 ctx.cfg.enable_commit_graph = atoi(value);
186         else if (!strcmp(name, "enable-log-filecount"))
187                 ctx.cfg.enable_log_filecount = atoi(value);
188         else if (!strcmp(name, "enable-log-linecount"))
189                 ctx.cfg.enable_log_linecount = atoi(value);
190         else if (!strcmp(name, "enable-remote-branches"))
191                 ctx.cfg.enable_remote_branches = atoi(value);
192         else if (!strcmp(name, "enable-subject-links"))
193                 ctx.cfg.enable_subject_links = atoi(value);
194         else if (!strcmp(name, "enable-tree-linenumbers"))
195                 ctx.cfg.enable_tree_linenumbers = atoi(value);
196         else if (!strcmp(name, "enable-git-config"))
197                 ctx.cfg.enable_git_config = atoi(value);
198         else if (!strcmp(name, "max-stats"))
199                 ctx.cfg.max_stats = cgit_find_stats_period(value, NULL);
200         else if (!strcmp(name, "cache-size"))
201                 ctx.cfg.cache_size = atoi(value);
202         else if (!strcmp(name, "cache-root"))
203                 ctx.cfg.cache_root = xstrdup(expand_macros(value));
204         else if (!strcmp(name, "cache-root-ttl"))
205                 ctx.cfg.cache_root_ttl = atoi(value);
206         else if (!strcmp(name, "cache-repo-ttl"))
207                 ctx.cfg.cache_repo_ttl = atoi(value);
208         else if (!strcmp(name, "cache-scanrc-ttl"))
209                 ctx.cfg.cache_scanrc_ttl = atoi(value);
210         else if (!strcmp(name, "cache-static-ttl"))
211                 ctx.cfg.cache_static_ttl = atoi(value);
212         else if (!strcmp(name, "cache-dynamic-ttl"))
213                 ctx.cfg.cache_dynamic_ttl = atoi(value);
214         else if (!strcmp(name, "case-sensitive-sort"))
215                 ctx.cfg.case_sensitive_sort = atoi(value);
216         else if (!strcmp(name, "about-filter"))
217                 ctx.cfg.about_filter = new_filter(value, ABOUT);
218         else if (!strcmp(name, "commit-filter"))
219                 ctx.cfg.commit_filter = new_filter(value, COMMIT);
220         else if (!strcmp(name, "embedded"))
221                 ctx.cfg.embedded = atoi(value);
222         else if (!strcmp(name, "max-atom-items"))
223                 ctx.cfg.max_atom_items = atoi(value);
224         else if (!strcmp(name, "max-message-length"))
225                 ctx.cfg.max_msg_len = atoi(value);
226         else if (!strcmp(name, "max-repodesc-length"))
227                 ctx.cfg.max_repodesc_len = atoi(value);
228         else if (!strcmp(name, "max-blob-size"))
229                 ctx.cfg.max_blob_size = atoi(value);
230         else if (!strcmp(name, "max-repo-count"))
231                 ctx.cfg.max_repo_count = atoi(value);
232         else if (!strcmp(name, "max-commit-count"))
233                 ctx.cfg.max_commit_count = atoi(value);
234         else if (!strcmp(name, "project-list"))
235                 ctx.cfg.project_list = xstrdup(expand_macros(value));
236         else if (!strcmp(name, "scan-path"))
237                 if (!ctx.cfg.nocache && ctx.cfg.cache_size)
238                         process_cached_repolist(expand_macros(value));
239                 else if (ctx.cfg.project_list)
240                         scan_projects(expand_macros(value),
241                                       ctx.cfg.project_list, repo_config);
242                 else
243                         scan_tree(expand_macros(value), repo_config);
244         else if (!strcmp(name, "scan-hidden-path"))
245                 ctx.cfg.scan_hidden_path = atoi(value);
246         else if (!strcmp(name, "section-from-path"))
247                 ctx.cfg.section_from_path = atoi(value);
248         else if (!strcmp(name, "repository-sort"))
249                 ctx.cfg.repository_sort = xstrdup(value);
250         else if (!strcmp(name, "section-sort"))
251                 ctx.cfg.section_sort = atoi(value);
252         else if (!strcmp(name, "source-filter"))
253                 ctx.cfg.source_filter = new_filter(value, SOURCE);
254         else if (!strcmp(name, "summary-log"))
255                 ctx.cfg.summary_log = atoi(value);
256         else if (!strcmp(name, "summary-branches"))
257                 ctx.cfg.summary_branches = atoi(value);
258         else if (!strcmp(name, "summary-tags"))
259                 ctx.cfg.summary_tags = atoi(value);
260         else if (!strcmp(name, "side-by-side-diffs"))
261                 ctx.cfg.ssdiff = atoi(value);
262         else if (!strcmp(name, "agefile"))
263                 ctx.cfg.agefile = xstrdup(value);
264         else if (!strcmp(name, "mimetype-file"))
265                 ctx.cfg.mimetype_file = xstrdup(value);
266         else if (!strcmp(name, "renamelimit"))
267                 ctx.cfg.renamelimit = atoi(value);
268         else if (!strcmp(name, "remove-suffix"))
269                 ctx.cfg.remove_suffix = atoi(value);
270         else if (!strcmp(name, "robots"))
271                 ctx.cfg.robots = xstrdup(value);
272         else if (!strcmp(name, "clone-prefix"))
273                 ctx.cfg.clone_prefix = xstrdup(value);
274         else if (!strcmp(name, "clone-url"))
275                 ctx.cfg.clone_url = xstrdup(value);
276         else if (!strcmp(name, "local-time"))
277                 ctx.cfg.local_time = atoi(value);
278         else if (!strcmp(name, "commit-sort")) {
279                 if (!strcmp(value, "date"))
280                         ctx.cfg.commit_sort = 1;
281                 if (!strcmp(value, "topo"))
282                         ctx.cfg.commit_sort = 2;
283         } else if (!strcmp(name, "branch-sort")) {
284                 if (!strcmp(value, "age"))
285                         ctx.cfg.branch_sort = 1;
286                 if (!strcmp(value, "name"))
287                         ctx.cfg.branch_sort = 0;
288         } else if (!prefixcmp(name, "mimetype."))
289                 add_mimetype(name + 9, value);
290         else if (!strcmp(name, "include"))
291                 parse_configfile(expand_macros(value), config_cb);
292 }
293
294 static void querystring_cb(const char *name, const char *value)
295 {
296         if (!value)
297                 value = "";
298
299         if (!strcmp(name,"r")) {
300                 ctx.qry.repo = xstrdup(value);
301                 ctx.repo = cgit_get_repoinfo(value);
302         } else if (!strcmp(name, "p")) {
303                 ctx.qry.page = xstrdup(value);
304         } else if (!strcmp(name, "url")) {
305                 if (*value == '/')
306                         value++;
307                 ctx.qry.url = xstrdup(value);
308                 cgit_parse_url(value);
309         } else if (!strcmp(name, "qt")) {
310                 ctx.qry.grep = xstrdup(value);
311         } else if (!strcmp(name, "q")) {
312                 ctx.qry.search = xstrdup(value);
313         } else if (!strcmp(name, "h")) {
314                 ctx.qry.head = xstrdup(value);
315                 ctx.qry.has_symref = 1;
316         } else if (!strcmp(name, "id")) {
317                 ctx.qry.sha1 = xstrdup(value);
318                 ctx.qry.has_sha1 = 1;
319         } else if (!strcmp(name, "id2")) {
320                 ctx.qry.sha2 = xstrdup(value);
321                 ctx.qry.has_sha1 = 1;
322         } else if (!strcmp(name, "ofs")) {
323                 ctx.qry.ofs = atoi(value);
324         } else if (!strcmp(name, "path")) {
325                 ctx.qry.path = trim_end(value, '/');
326         } else if (!strcmp(name, "name")) {
327                 ctx.qry.name = xstrdup(value);
328         } else if (!strcmp(name, "mimetype")) {
329                 ctx.qry.mimetype = xstrdup(value);
330         } else if (!strcmp(name, "s")) {
331                 ctx.qry.sort = xstrdup(value);
332         } else if (!strcmp(name, "showmsg")) {
333                 ctx.qry.showmsg = atoi(value);
334         } else if (!strcmp(name, "period")) {
335                 ctx.qry.period = xstrdup(value);
336         } else if (!strcmp(name, "ss")) {
337                 ctx.qry.ssdiff = atoi(value);
338                 ctx.qry.has_ssdiff = 1;
339         } else if (!strcmp(name, "all")) {
340                 ctx.qry.show_all = atoi(value);
341         } else if (!strcmp(name, "context")) {
342                 ctx.qry.context = atoi(value);
343         } else if (!strcmp(name, "ignorews")) {
344                 ctx.qry.ignorews = atoi(value);
345         }
346 }
347
348 static void prepare_context(struct cgit_context *ctx)
349 {
350         memset(ctx, 0, sizeof(*ctx));
351         ctx->cfg.agefile = "info/web/last-modified";
352         ctx->cfg.nocache = 0;
353         ctx->cfg.cache_size = 0;
354         ctx->cfg.cache_dynamic_ttl = 5;
355         ctx->cfg.cache_max_create_time = 5;
356         ctx->cfg.cache_repo_ttl = 5;
357         ctx->cfg.cache_root = CGIT_CACHE_ROOT;
358         ctx->cfg.cache_root_ttl = 5;
359         ctx->cfg.cache_scanrc_ttl = 15;
360         ctx->cfg.cache_static_ttl = -1;
361         ctx->cfg.case_sensitive_sort = 1;
362         ctx->cfg.branch_sort = 0;
363         ctx->cfg.commit_sort = 0;
364         ctx->cfg.css = "/cgit.css";
365         ctx->cfg.logo = "/cgit.png";
366         ctx->cfg.favicon = "/favicon.ico";
367         ctx->cfg.local_time = 0;
368         ctx->cfg.enable_http_clone = 1;
369         ctx->cfg.enable_index_owner = 1;
370         ctx->cfg.enable_tree_linenumbers = 1;
371         ctx->cfg.enable_git_config = 0;
372         ctx->cfg.max_repo_count = 50;
373         ctx->cfg.max_commit_count = 50;
374         ctx->cfg.max_lock_attempts = 5;
375         ctx->cfg.max_msg_len = 80;
376         ctx->cfg.max_repodesc_len = 80;
377         ctx->cfg.max_blob_size = 0;
378         ctx->cfg.max_stats = 0;
379         ctx->cfg.project_list = NULL;
380         ctx->cfg.renamelimit = -1;
381         ctx->cfg.remove_suffix = 0;
382         ctx->cfg.robots = "index, nofollow";
383         ctx->cfg.root_title = "Git repository browser";
384         ctx->cfg.root_desc = "a fast webinterface for the git dscm";
385         ctx->cfg.scan_hidden_path = 0;
386         ctx->cfg.script_name = CGIT_SCRIPT_NAME;
387         ctx->cfg.section = "";
388         ctx->cfg.repository_sort = "name";
389         ctx->cfg.section_sort = 1;
390         ctx->cfg.summary_branches = 10;
391         ctx->cfg.summary_log = 10;
392         ctx->cfg.summary_tags = 10;
393         ctx->cfg.max_atom_items = 10;
394         ctx->cfg.ssdiff = 0;
395         ctx->env.cgit_config = getenv("CGIT_CONFIG");
396         ctx->env.http_host = getenv("HTTP_HOST");
397         ctx->env.https = getenv("HTTPS");
398         ctx->env.no_http = getenv("NO_HTTP");
399         ctx->env.path_info = getenv("PATH_INFO");
400         ctx->env.query_string = getenv("QUERY_STRING");
401         ctx->env.request_method = getenv("REQUEST_METHOD");
402         ctx->env.script_name = getenv("SCRIPT_NAME");
403         ctx->env.server_name = getenv("SERVER_NAME");
404         ctx->env.server_port = getenv("SERVER_PORT");
405         ctx->page.mimetype = "text/html";
406         ctx->page.charset = PAGE_ENCODING;
407         ctx->page.filename = NULL;
408         ctx->page.size = 0;
409         ctx->page.modified = time(NULL);
410         ctx->page.expires = ctx->page.modified;
411         ctx->page.etag = NULL;
412         memset(&ctx->cfg.mimetypes, 0, sizeof(struct string_list));
413         if (ctx->env.script_name)
414                 ctx->cfg.script_name = xstrdup(ctx->env.script_name);
415         if (ctx->env.query_string)
416                 ctx->qry.raw = xstrdup(ctx->env.query_string);
417         if (!ctx->env.cgit_config)
418                 ctx->env.cgit_config = CGIT_CONFIG;
419 }
420
421 struct refmatch {
422         char *req_ref;
423         char *first_ref;
424         int match;
425 };
426
427 static int find_current_ref(const char *refname, const unsigned char *sha1,
428                             int flags, void *cb_data)
429 {
430         struct refmatch *info;
431
432         info = (struct refmatch *)cb_data;
433         if (!strcmp(refname, info->req_ref))
434                 info->match = 1;
435         if (!info->first_ref)
436                 info->first_ref = xstrdup(refname);
437         return info->match;
438 }
439
440 static void free_refmatch_inner(struct refmatch *info)
441 {
442         if (info->first_ref)
443                 free(info->first_ref);
444 }
445
446 static char *find_default_branch(struct cgit_repo *repo)
447 {
448         struct refmatch info;
449         char *ref;
450
451         info.req_ref = repo->defbranch;
452         info.first_ref = NULL;
453         info.match = 0;
454         for_each_branch_ref(find_current_ref, &info);
455         if (info.match)
456                 ref = info.req_ref;
457         else
458                 ref = info.first_ref;
459         if (ref)
460                 ref = xstrdup(ref);
461         free_refmatch_inner(&info);
462
463         return ref;
464 }
465
466 static char *guess_defbranch(void)
467 {
468         const char *ref;
469         unsigned char sha1[20];
470
471         ref = resolve_ref_unsafe("HEAD", sha1, 0, NULL);
472         if (!ref || prefixcmp(ref, "refs/heads/"))
473                 return "master";
474         return xstrdup(ref + 11);
475 }
476 /* The caller must free filename and ref after calling this. */
477 static inline void parse_readme(const char *readme, char **filename, char **ref, struct cgit_repo *repo)
478 {
479         const char *colon;
480
481         *filename = NULL;
482         *ref = NULL;
483
484         if (!readme || !readme[0])
485                 return;
486
487         /* Check if the readme is tracked in the git repo. */
488         colon = strchr(readme, ':');
489         if (colon && strlen(colon) > 1) {
490                 /* If it starts with a colon, we want to use
491                  * the default branch */
492                 if (colon == readme && repo->defbranch)
493                         *ref = xstrdup(repo->defbranch);
494                 else
495                         *ref = xstrndup(readme, colon - readme);
496                 readme = colon + 1;
497         }
498
499         /* Prepend repo path to relative readme path unless tracked. */
500         if (!(*ref) && readme[0] != '/')
501                 *filename = fmtalloc("%s/%s", repo->path, readme);
502         else
503                 *filename = xstrdup(readme);
504 }
505 static void choose_readme(struct cgit_repo *repo)
506 {
507         int found;
508         char *filename, *ref;
509         struct string_list_item *entry;
510
511         if (!repo->readme.nr)
512                 return;
513
514         found = 0;
515         for_each_string_list_item(entry, &repo->readme) {
516                 parse_readme(entry->string, &filename, &ref, repo);
517                 if (!filename) {
518                         free(filename);
519                         free(ref);
520                         continue;
521                 }
522                 /* If there's only one item, we skip the possibly expensive
523                  * selection process. */
524                 if (repo->readme.nr == 1) {
525                         found = 1;
526                         break;
527                 }
528                 if (ref) {
529                         if (cgit_ref_path_exists(filename, ref, 1)) {
530                                 found = 1;
531                                 break;
532                         }
533                 }
534                 else if (!access(filename, R_OK)) {
535                         found = 1;
536                         break;
537                 }
538                 free(filename);
539                 free(ref);
540         }
541         repo->readme.strdup_strings = 1;
542         string_list_clear(&repo->readme, 0);
543         repo->readme.strdup_strings = 0;
544         if (found)
545                 string_list_append(&repo->readme, filename)->util = ref;
546 }
547
548 static int prepare_repo_cmd(struct cgit_context *ctx)
549 {
550         unsigned char sha1[20];
551         int nongit = 0;
552         int rc;
553
554         /* The path to the git repository. */
555         setenv("GIT_DIR", ctx->repo->path, 1);
556
557         /* Do not look in /etc/ for gitconfig and gitattributes. */
558         setenv("GIT_CONFIG_NOSYSTEM", "1", 1);
559         setenv("GIT_ATTR_NOSYSTEM", "1", 1);
560         unsetenv("HOME");
561         unsetenv("XDG_CONFIG_HOME");
562
563         /* Setup the git directory and initialize the notes system. Both of these
564          * load local configuration from the git repository, so we do them both while
565          * the HOME variables are unset. */
566         setup_git_directory_gently(&nongit);
567         init_display_notes(NULL);
568
569         if (nongit) {
570                 const char *name = ctx->repo->name;
571                 rc = errno;
572                 ctx->page.title = fmtalloc("%s - %s", ctx->cfg.root_title,
573                                                 "config error");
574                 ctx->repo = NULL;
575                 cgit_print_http_headers(ctx);
576                 cgit_print_docstart(ctx);
577                 cgit_print_pageheader(ctx);
578                 cgit_print_error("Failed to open %s: %s", name,
579                                  rc ? strerror(rc) : "Not a valid git repository");
580                 cgit_print_docend();
581                 return 1;
582         }
583         ctx->page.title = fmtalloc("%s - %s", ctx->repo->name, ctx->repo->desc);
584
585         if (!ctx->repo->defbranch)
586                 ctx->repo->defbranch = guess_defbranch();
587
588         if (!ctx->qry.head) {
589                 ctx->qry.nohead = 1;
590                 ctx->qry.head = find_default_branch(ctx->repo);
591         }
592
593         if (!ctx->qry.head) {
594                 cgit_print_http_headers(ctx);
595                 cgit_print_docstart(ctx);
596                 cgit_print_pageheader(ctx);
597                 cgit_print_error("Repository seems to be empty");
598                 cgit_print_docend();
599                 return 1;
600         }
601
602         if (get_sha1(ctx->qry.head, sha1)) {
603                 char *tmp = xstrdup(ctx->qry.head);
604                 ctx->qry.head = ctx->repo->defbranch;
605                 ctx->page.status = 404;
606                 ctx->page.statusmsg = "Not found";
607                 cgit_print_http_headers(ctx);
608                 cgit_print_docstart(ctx);
609                 cgit_print_pageheader(ctx);
610                 cgit_print_error("Invalid branch: %s", tmp);
611                 cgit_print_docend();
612                 return 1;
613         }
614         sort_string_list(&ctx->repo->submodules);
615         cgit_prepare_repo_env(ctx->repo);
616         choose_readme(ctx->repo);
617         return 0;
618 }
619
620 static void process_request(void *cbdata)
621 {
622         struct cgit_context *ctx = cbdata;
623         struct cgit_cmd *cmd;
624
625         cmd = cgit_get_cmd(ctx);
626         if (!cmd) {
627                 ctx->page.title = "cgit error";
628                 ctx->page.status = 404;
629                 ctx->page.statusmsg = "Not found";
630                 cgit_print_http_headers(ctx);
631                 cgit_print_docstart(ctx);
632                 cgit_print_pageheader(ctx);
633                 cgit_print_error("Invalid request");
634                 cgit_print_docend();
635                 return;
636         }
637
638         if (!ctx->cfg.enable_http_clone && cmd->is_clone) {
639                 html_status(404, "Not found", 0);
640                 return;
641         }
642
643         /* If cmd->want_vpath is set, assume ctx->qry.path contains a "virtual"
644          * in-project path limit to be made available at ctx->qry.vpath.
645          * Otherwise, no path limit is in effect (ctx->qry.vpath = NULL).
646          */
647         ctx->qry.vpath = cmd->want_vpath ? ctx->qry.path : NULL;
648
649         if (cmd->want_repo && !ctx->repo) {
650                 cgit_print_http_headers(ctx);
651                 cgit_print_docstart(ctx);
652                 cgit_print_pageheader(ctx);
653                 cgit_print_error("No repository selected");
654                 cgit_print_docend();
655                 return;
656         }
657
658         if (ctx->repo && prepare_repo_cmd(ctx))
659                 return;
660
661         if (cmd->want_layout) {
662                 cgit_print_http_headers(ctx);
663                 cgit_print_docstart(ctx);
664                 cgit_print_pageheader(ctx);
665         }
666
667         cmd->fn(ctx);
668
669         if (cmd->want_layout)
670                 cgit_print_docend();
671 }
672
673 static int cmp_repos(const void *a, const void *b)
674 {
675         const struct cgit_repo *ra = a, *rb = b;
676         return strcmp(ra->url, rb->url);
677 }
678
679 static char *build_snapshot_setting(int bitmap)
680 {
681         const struct cgit_snapshot_format *f;
682         struct strbuf result = STRBUF_INIT;
683
684         for (f = cgit_snapshot_formats; f->suffix; f++) {
685                 if (f->bit & bitmap) {
686                         if (result.len)
687                                 strbuf_addch(&result, ' ');
688                         strbuf_addstr(&result, f->suffix);
689                 }
690         }
691         return strbuf_detach(&result, NULL);
692 }
693
694 static char *get_first_line(char *txt)
695 {
696         char *t = xstrdup(txt);
697         char *p = strchr(t, '\n');
698         if (p)
699                 *p = '\0';
700         return t;
701 }
702
703 static void print_repo(FILE *f, struct cgit_repo *repo)
704 {
705         struct string_list_item *item;
706         fprintf(f, "repo.url=%s\n", repo->url);
707         fprintf(f, "repo.name=%s\n", repo->name);
708         fprintf(f, "repo.path=%s\n", repo->path);
709         if (repo->owner)
710                 fprintf(f, "repo.owner=%s\n", repo->owner);
711         if (repo->desc) {
712                 char *tmp = get_first_line(repo->desc);
713                 fprintf(f, "repo.desc=%s\n", tmp);
714                 free(tmp);
715         }
716         for_each_string_list_item(item, &repo->readme) {
717                 if (item->util)
718                         fprintf(f, "repo.readme=%s:%s\n", (char *)item->util, item->string);
719                 else
720                         fprintf(f, "repo.readme=%s\n", item->string);
721         }
722         if (repo->defbranch)
723                 fprintf(f, "repo.defbranch=%s\n", repo->defbranch);
724         if (repo->module_link)
725                 fprintf(f, "repo.module-link=%s\n", repo->module_link);
726         if (repo->section)
727                 fprintf(f, "repo.section=%s\n", repo->section);
728         if (repo->clone_url)
729                 fprintf(f, "repo.clone-url=%s\n", repo->clone_url);
730         fprintf(f, "repo.enable-commit-graph=%d\n",
731                 repo->enable_commit_graph);
732         fprintf(f, "repo.enable-log-filecount=%d\n",
733                 repo->enable_log_filecount);
734         fprintf(f, "repo.enable-log-linecount=%d\n",
735                 repo->enable_log_linecount);
736         if (repo->about_filter && repo->about_filter != ctx.cfg.about_filter)
737                 fprintf(f, "repo.about-filter=%s\n", repo->about_filter->cmd);
738         if (repo->commit_filter && repo->commit_filter != ctx.cfg.commit_filter)
739                 fprintf(f, "repo.commit-filter=%s\n", repo->commit_filter->cmd);
740         if (repo->source_filter && repo->source_filter != ctx.cfg.source_filter)
741                 fprintf(f, "repo.source-filter=%s\n", repo->source_filter->cmd);
742         if (repo->snapshots != ctx.cfg.snapshots) {
743                 char *tmp = build_snapshot_setting(repo->snapshots);
744                 fprintf(f, "repo.snapshots=%s\n", tmp ? tmp : "");
745                 free(tmp);
746         }
747         if (repo->max_stats != ctx.cfg.max_stats)
748                 fprintf(f, "repo.max-stats=%s\n",
749                         cgit_find_stats_periodname(repo->max_stats));
750         if (repo->logo)
751                 fprintf(f, "repo.logo=%s\n", repo->logo);
752         if (repo->logo_link)
753                 fprintf(f, "repo.logo-link=%s\n", repo->logo_link);
754         fprintf(f, "repo.enable-remote-branches=%d\n", repo->enable_remote_branches);
755         fprintf(f, "repo.enable-subject-links=%d\n", repo->enable_subject_links);
756         if (repo->branch_sort == 1)
757                 fprintf(f, "repo.branch-sort=age\n");
758         if (repo->commit_sort) {
759                 if (repo->commit_sort == 1)
760                         fprintf(f, "repo.commit-sort=date\n");
761                 else if (repo->commit_sort == 2)
762                         fprintf(f, "repo.commit-sort=topo\n");
763         }
764         fprintf(f, "\n");
765 }
766
767 static void print_repolist(FILE *f, struct cgit_repolist *list, int start)
768 {
769         int i;
770
771         for (i = start; i < list->count; i++)
772                 print_repo(f, &list->repos[i]);
773 }
774
775 /* Scan 'path' for git repositories, save the resulting repolist in 'cached_rc'
776  * and return 0 on success.
777  */
778 static int generate_cached_repolist(const char *path, const char *cached_rc)
779 {
780         struct strbuf locked_rc = STRBUF_INIT;
781         int result = 0;
782         int idx;
783         FILE *f;
784
785         strbuf_addf(&locked_rc, "%s.lock", cached_rc);
786         f = fopen(locked_rc.buf, "wx");
787         if (!f) {
788                 /* Inform about the error unless the lockfile already existed,
789                  * since that only means we've got concurrent requests.
790                  */
791                 result = errno;
792                 if (result != EEXIST)
793                         fprintf(stderr, "[cgit] Error opening %s: %s (%d)\n",
794                                 locked_rc.buf, strerror(result), result);
795                 goto out;
796         }
797         idx = cgit_repolist.count;
798         if (ctx.cfg.project_list)
799                 scan_projects(path, ctx.cfg.project_list, repo_config);
800         else
801                 scan_tree(path, repo_config);
802         print_repolist(f, &cgit_repolist, idx);
803         if (rename(locked_rc.buf, cached_rc))
804                 fprintf(stderr, "[cgit] Error renaming %s to %s: %s (%d)\n",
805                         locked_rc.buf, cached_rc, strerror(errno), errno);
806         fclose(f);
807 out:
808         strbuf_release(&locked_rc);
809         return result;
810 }
811
812 static void process_cached_repolist(const char *path)
813 {
814         struct stat st;
815         struct strbuf cached_rc = STRBUF_INIT;
816         time_t age;
817         unsigned long hash;
818
819         hash = hash_str(path);
820         if (ctx.cfg.project_list)
821                 hash += hash_str(ctx.cfg.project_list);
822         strbuf_addf(&cached_rc, "%s/rc-%8lx", ctx.cfg.cache_root, hash);
823
824         if (stat(cached_rc.buf, &st)) {
825                 /* Nothing is cached, we need to scan without forking. And
826                  * if we fail to generate a cached repolist, we need to
827                  * invoke scan_tree manually.
828                  */
829                 if (generate_cached_repolist(path, cached_rc.buf)) {
830                         if (ctx.cfg.project_list)
831                                 scan_projects(path, ctx.cfg.project_list,
832                                               repo_config);
833                         else
834                                 scan_tree(path, repo_config);
835                 }
836                 goto out;
837         }
838
839         parse_configfile(cached_rc.buf, config_cb);
840
841         /* If the cached configfile hasn't expired, lets exit now */
842         age = time(NULL) - st.st_mtime;
843         if (age <= (ctx.cfg.cache_scanrc_ttl * 60))
844                 goto out;
845
846         /* The cached repolist has been parsed, but it was old. So lets
847          * rescan the specified path and generate a new cached repolist
848          * in a child-process to avoid latency for the current request.
849          */
850         if (fork())
851                 goto out;
852
853         exit(generate_cached_repolist(path, cached_rc.buf));
854 out:
855         strbuf_release(&cached_rc);
856 }
857
858 static void cgit_parse_args(int argc, const char **argv)
859 {
860         int i;
861         int scan = 0;
862
863         for (i = 1; i < argc; i++) {
864                 if (!strncmp(argv[i], "--cache=", 8)) {
865                         ctx.cfg.cache_root = xstrdup(argv[i] + 8);
866                 }
867                 if (!strcmp(argv[i], "--nocache")) {
868                         ctx.cfg.nocache = 1;
869                 }
870                 if (!strcmp(argv[i], "--nohttp")) {
871                         ctx.env.no_http = "1";
872                 }
873                 if (!strncmp(argv[i], "--query=", 8)) {
874                         ctx.qry.raw = xstrdup(argv[i] + 8);
875                 }
876                 if (!strncmp(argv[i], "--repo=", 7)) {
877                         ctx.qry.repo = xstrdup(argv[i] + 7);
878                 }
879                 if (!strncmp(argv[i], "--page=", 7)) {
880                         ctx.qry.page = xstrdup(argv[i] + 7);
881                 }
882                 if (!strncmp(argv[i], "--head=", 7)) {
883                         ctx.qry.head = xstrdup(argv[i] + 7);
884                         ctx.qry.has_symref = 1;
885                 }
886                 if (!strncmp(argv[i], "--sha1=", 7)) {
887                         ctx.qry.sha1 = xstrdup(argv[i] + 7);
888                         ctx.qry.has_sha1 = 1;
889                 }
890                 if (!strncmp(argv[i], "--ofs=", 6)) {
891                         ctx.qry.ofs = atoi(argv[i] + 6);
892                 }
893                 if (!strncmp(argv[i], "--scan-tree=", 12) ||
894                     !strncmp(argv[i], "--scan-path=", 12)) {
895                         /* HACK: the global snapshot bitmask defines the
896                          * set of allowed snapshot formats, but the config
897                          * file hasn't been parsed yet so the mask is
898                          * currently 0. By setting all bits high before
899                          * scanning we make sure that any in-repo cgitrc
900                          * snapshot setting is respected by scan_tree().
901                          * BTW: we assume that there'll never be more than
902                          * 255 different snapshot formats supported by cgit...
903                          */
904                         ctx.cfg.snapshots = 0xFF;
905                         scan++;
906                         scan_tree(argv[i] + 12, repo_config);
907                 }
908         }
909         if (scan) {
910                 qsort(cgit_repolist.repos, cgit_repolist.count,
911                         sizeof(struct cgit_repo), cmp_repos);
912                 print_repolist(stdout, &cgit_repolist, 0);
913                 exit(0);
914         }
915 }
916
917 static int calc_ttl()
918 {
919         if (!ctx.repo)
920                 return ctx.cfg.cache_root_ttl;
921
922         if (!ctx.qry.page)
923                 return ctx.cfg.cache_repo_ttl;
924
925         if (ctx.qry.has_symref)
926                 return ctx.cfg.cache_dynamic_ttl;
927
928         if (ctx.qry.has_sha1)
929                 return ctx.cfg.cache_static_ttl;
930
931         return ctx.cfg.cache_repo_ttl;
932 }
933
934 int main(int argc, const char **argv)
935 {
936         const char *path;
937         int err, ttl;
938
939         prepare_context(&ctx);
940         cgit_repolist.length = 0;
941         cgit_repolist.count = 0;
942         cgit_repolist.repos = NULL;
943
944         cgit_parse_args(argc, argv);
945         parse_configfile(expand_macros(ctx.env.cgit_config), config_cb);
946         ctx.repo = NULL;
947         http_parse_querystring(ctx.qry.raw, querystring_cb);
948
949         /* If virtual-root isn't specified in cgitrc, lets pretend
950          * that virtual-root equals SCRIPT_NAME, minus any possibly
951          * trailing slashes.
952          */
953         if (!ctx.cfg.virtual_root && ctx.cfg.script_name)
954                 ctx.cfg.virtual_root = ensure_end(ctx.cfg.script_name, '/');
955
956         /* If no url parameter is specified on the querystring, lets
957          * use PATH_INFO as url. This allows cgit to work with virtual
958          * urls without the need for rewriterules in the webserver (as
959          * long as PATH_INFO is included in the cache lookup key).
960          */
961         path = ctx.env.path_info;
962         if (!ctx.qry.url && path) {
963                 if (path[0] == '/')
964                         path++;
965                 ctx.qry.url = xstrdup(path);
966                 if (ctx.qry.raw) {
967                         char *newqry = fmtalloc("%s?%s", path, ctx.qry.raw);
968                         free(ctx.qry.raw);
969                         ctx.qry.raw = newqry;
970                 } else
971                         ctx.qry.raw = xstrdup(ctx.qry.url);
972                 cgit_parse_url(ctx.qry.url);
973         }
974
975         ttl = calc_ttl();
976         ctx.page.expires += ttl * 60;
977         if (ctx.env.request_method && !strcmp(ctx.env.request_method, "HEAD"))
978                 ctx.cfg.nocache = 1;
979         if (ctx.cfg.nocache)
980                 ctx.cfg.cache_size = 0;
981         err = cache_process(ctx.cfg.cache_size, ctx.cfg.cache_root,
982                             ctx.qry.raw, ttl, process_request, &ctx);
983         if (err)
984                 cgit_print_error("Error processing page: %s (%d)",
985                                  strerror(err), err);
986         return err;
987 }