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