http-backend: Fix bad treatment of uintmax_t in Content-Length
[git/git.git] / http-backend.c
CommitLineData
2f4038ab
SP
1#include "cache.h"
2#include "refs.h"
3#include "pkt-line.h"
4#include "object.h"
5#include "tag.h"
6#include "exec_cmd.h"
556cfa3b
SP
7#include "run-command.h"
8#include "string-list.h"
2f4038ab
SP
9
10static const char content_type[] = "Content-Type";
11static const char content_length[] = "Content-Length";
12static const char last_modified[] = "Last-Modified";
5abb013b 13static int getanyfile = 1;
2f4038ab 14
556cfa3b
SP
15static struct string_list *query_params;
16
17struct rpc_service {
18 const char *name;
19 const char *config_name;
20 signed enabled : 2;
21};
22
23static struct rpc_service rpc_service[] = {
24 { "upload-pack", "uploadpack", 1 },
25 { "receive-pack", "receivepack", -1 },
26};
27
28static int decode_char(const char *q)
29{
30 int i;
31 unsigned char val = 0;
32 for (i = 0; i < 2; i++) {
33 unsigned char c = *q++;
34 val <<= 4;
35 if (c >= '0' && c <= '9')
36 val += c - '0';
37 else if (c >= 'a' && c <= 'f')
38 val += c - 'a' + 10;
39 else if (c >= 'A' && c <= 'F')
40 val += c - 'A' + 10;
41 else
42 return -1;
43 }
44 return val;
45}
46
47static char *decode_parameter(const char **query, int is_name)
48{
49 const char *q = *query;
50 struct strbuf out;
51
52 strbuf_init(&out, 16);
53 do {
54 unsigned char c = *q;
55
56 if (!c)
57 break;
58 if (c == '&' || (is_name && c == '=')) {
59 q++;
60 break;
61 }
62
63 if (c == '%') {
64 int val = decode_char(q + 1);
65 if (0 <= val) {
66 strbuf_addch(&out, val);
67 q += 3;
68 continue;
69 }
70 }
71
72 if (c == '+')
73 strbuf_addch(&out, ' ');
74 else
75 strbuf_addch(&out, c);
76 q++;
77 } while (1);
78 *query = q;
79 return strbuf_detach(&out, NULL);
80}
81
82static struct string_list *get_parameters(void)
83{
84 if (!query_params) {
85 const char *query = getenv("QUERY_STRING");
86
87 query_params = xcalloc(1, sizeof(*query_params));
88 while (query && *query) {
89 char *name = decode_parameter(&query, 1);
90 char *value = decode_parameter(&query, 0);
91 struct string_list_item *i;
92
93 i = string_list_lookup(name, query_params);
94 if (!i)
95 i = string_list_insert(name, query_params);
96 else
97 free(i->util);
98 i->util = value;
99 }
100 }
101 return query_params;
102}
103
104static const char *get_parameter(const char *name)
105{
106 struct string_list_item *i;
107 i = string_list_lookup(name, get_parameters());
108 return i ? i->util : NULL;
109}
110
2f4038ab
SP
111static void format_write(int fd, const char *fmt, ...)
112{
113 static char buffer[1024];
114
115 va_list args;
116 unsigned n;
117
118 va_start(args, fmt);
119 n = vsnprintf(buffer, sizeof(buffer), fmt, args);
120 va_end(args);
121 if (n >= sizeof(buffer))
122 die("protocol error: impossibly long line");
123
124 safe_write(fd, buffer, n);
125}
126
127static void http_status(unsigned code, const char *msg)
128{
129 format_write(1, "Status: %u %s\r\n", code, msg);
130}
131
132static void hdr_str(const char *name, const char *value)
133{
134 format_write(1, "%s: %s\r\n", name, value);
135}
136
4a5328d6 137static void hdr_int(const char *name, uintmax_t value)
2f4038ab
SP
138{
139 format_write(1, "%s: %" PRIuMAX "\r\n", name, value);
140}
141
142static void hdr_date(const char *name, unsigned long when)
143{
144 const char *value = show_date(when, 0, DATE_RFC2822);
145 hdr_str(name, value);
146}
147
148static void hdr_nocache(void)
149{
150 hdr_str("Expires", "Fri, 01 Jan 1980 00:00:00 GMT");
151 hdr_str("Pragma", "no-cache");
152 hdr_str("Cache-Control", "no-cache, max-age=0, must-revalidate");
153}
154
155static void hdr_cache_forever(void)
156{
157 unsigned long now = time(NULL);
158 hdr_date("Date", now);
159 hdr_date("Expires", now + 31536000);
160 hdr_str("Cache-Control", "public, max-age=31536000");
161}
162
163static void end_headers(void)
164{
165 safe_write(1, "\r\n", 2);
166}
167
168static NORETURN void not_found(const char *err, ...)
169{
170 va_list params;
171
172 http_status(404, "Not Found");
173 hdr_nocache();
174 end_headers();
175
176 va_start(params, err);
177 if (err && *err)
178 vfprintf(stderr, err, params);
179 va_end(params);
180 exit(0);
181}
182
556cfa3b
SP
183static NORETURN void forbidden(const char *err, ...)
184{
185 va_list params;
186
187 http_status(403, "Forbidden");
188 hdr_nocache();
189 end_headers();
190
191 va_start(params, err);
192 if (err && *err)
193 vfprintf(stderr, err, params);
194 va_end(params);
195 exit(0);
196}
197
5abb013b
SP
198static void select_getanyfile(void)
199{
200 if (!getanyfile)
201 forbidden("Unsupported service: getanyfile");
202}
203
2f4038ab
SP
204static void send_strbuf(const char *type, struct strbuf *buf)
205{
206 hdr_int(content_length, buf->len);
207 hdr_str(content_type, type);
208 end_headers();
209 safe_write(1, buf->buf, buf->len);
210}
211
92815b33 212static void send_local_file(const char *the_type, const char *name)
2f4038ab
SP
213{
214 const char *p = git_path("%s", name);
215 size_t buf_alloc = 8192;
216 char *buf = xmalloc(buf_alloc);
217 int fd;
218 struct stat sb;
2f4038ab
SP
219
220 fd = open(p, O_RDONLY);
221 if (fd < 0)
222 not_found("Cannot open '%s': %s", p, strerror(errno));
223 if (fstat(fd, &sb) < 0)
224 die_errno("Cannot stat '%s'", p);
225
4a5328d6 226 hdr_int(content_length, sb.st_size);
2f4038ab
SP
227 hdr_str(content_type, the_type);
228 hdr_date(last_modified, sb.st_mtime);
229 end_headers();
230
4a5328d6 231 for (;;) {
2f4038ab
SP
232 ssize_t n = xread(fd, buf, buf_alloc);
233 if (n < 0)
234 die_errno("Cannot read '%s'", p);
235 if (!n)
236 break;
237 safe_write(1, buf, n);
238 }
239 close(fd);
240 free(buf);
241}
242
243static void get_text_file(char *name)
244{
5abb013b 245 select_getanyfile();
2f4038ab 246 hdr_nocache();
92815b33 247 send_local_file("text/plain", name);
2f4038ab
SP
248}
249
250static void get_loose_object(char *name)
251{
5abb013b 252 select_getanyfile();
2f4038ab 253 hdr_cache_forever();
92815b33 254 send_local_file("application/x-git-loose-object", name);
2f4038ab
SP
255}
256
257static void get_pack_file(char *name)
258{
5abb013b 259 select_getanyfile();
2f4038ab 260 hdr_cache_forever();
92815b33 261 send_local_file("application/x-git-packed-objects", name);
2f4038ab
SP
262}
263
264static void get_idx_file(char *name)
265{
5abb013b 266 select_getanyfile();
2f4038ab 267 hdr_cache_forever();
92815b33 268 send_local_file("application/x-git-packed-objects-toc", name);
2f4038ab
SP
269}
270
556cfa3b
SP
271static int http_config(const char *var, const char *value, void *cb)
272{
5abb013b
SP
273 if (!strcmp(var, "http.getanyfile")) {
274 getanyfile = git_config_bool(var, value);
556cfa3b
SP
275 return 0;
276 }
277
5abb013b
SP
278 if (!prefixcmp(var, "http.")) {
279 int i;
280
281 for (i = 0; i < ARRAY_SIZE(rpc_service); i++) {
282 struct rpc_service *svc = &rpc_service[i];
283 if (!strcmp(var + 5, svc->config_name)) {
284 svc->enabled = git_config_bool(var, value);
285 return 0;
286 }
287 }
288 }
289
556cfa3b
SP
290 /* we are not interested in parsing any other configuration here */
291 return 0;
292}
293
294static struct rpc_service *select_service(const char *name)
295{
296 struct rpc_service *svc = NULL;
297 int i;
298
299 if (prefixcmp(name, "git-"))
300 forbidden("Unsupported service: '%s'", name);
301
302 for (i = 0; i < ARRAY_SIZE(rpc_service); i++) {
303 struct rpc_service *s = &rpc_service[i];
304 if (!strcmp(s->name, name + 4)) {
305 svc = s;
306 break;
307 }
308 }
309
310 if (!svc)
311 forbidden("Unsupported service: '%s'", name);
312
556cfa3b
SP
313 if (svc->enabled < 0) {
314 const char *user = getenv("REMOTE_USER");
315 svc->enabled = (user && *user) ? 1 : 0;
316 }
317 if (!svc->enabled)
318 forbidden("Service not enabled: '%s'", svc->name);
319 return svc;
320}
321
322static void inflate_request(const char *prog_name, int out)
323{
324 z_stream stream;
325 unsigned char in_buf[8192];
326 unsigned char out_buf[8192];
327 unsigned long cnt = 0;
328 int ret;
329
330 memset(&stream, 0, sizeof(stream));
331 ret = inflateInit2(&stream, (15 + 16));
332 if (ret != Z_OK)
333 die("cannot start zlib inflater, zlib err %d", ret);
334
335 while (1) {
336 ssize_t n = xread(0, in_buf, sizeof(in_buf));
337 if (n <= 0)
338 die("request ended in the middle of the gzip stream");
339
340 stream.next_in = in_buf;
341 stream.avail_in = n;
342
343 while (0 < stream.avail_in) {
344 int ret;
345
346 stream.next_out = out_buf;
347 stream.avail_out = sizeof(out_buf);
348
349 ret = inflate(&stream, Z_NO_FLUSH);
350 if (ret != Z_OK && ret != Z_STREAM_END)
351 die("zlib error inflating request, result %d", ret);
352
353 n = stream.total_out - cnt;
354 if (write_in_full(out, out_buf, n) != n)
355 die("%s aborted reading request", prog_name);
356 cnt += n;
357
358 if (ret == Z_STREAM_END)
359 goto done;
360 }
361 }
362
363done:
364 inflateEnd(&stream);
365 close(out);
366}
367
368static void run_service(const char **argv)
369{
370 const char *encoding = getenv("HTTP_CONTENT_ENCODING");
371 const char *user = getenv("REMOTE_USER");
372 const char *host = getenv("REMOTE_ADDR");
373 char *env[3];
374 struct strbuf buf = STRBUF_INIT;
375 int gzipped_request = 0;
376 struct child_process cld;
377
378 if (encoding && !strcmp(encoding, "gzip"))
379 gzipped_request = 1;
380 else if (encoding && !strcmp(encoding, "x-gzip"))
381 gzipped_request = 1;
382
383 if (!user || !*user)
384 user = "anonymous";
385 if (!host || !*host)
386 host = "(none)";
387
388 memset(&env, 0, sizeof(env));
389 strbuf_addf(&buf, "GIT_COMMITTER_NAME=%s", user);
390 env[0] = strbuf_detach(&buf, NULL);
391
392 strbuf_addf(&buf, "GIT_COMMITTER_EMAIL=%s@http.%s", user, host);
393 env[1] = strbuf_detach(&buf, NULL);
394 env[2] = NULL;
395
396 memset(&cld, 0, sizeof(cld));
397 cld.argv = argv;
398 cld.env = (const char *const *)env;
399 if (gzipped_request)
400 cld.in = -1;
401 cld.git_cmd = 1;
402 if (start_command(&cld))
403 exit(1);
404
405 close(1);
406 if (gzipped_request)
407 inflate_request(argv[0], cld.in);
408 else
409 close(0);
410
411 if (finish_command(&cld))
412 exit(1);
413 free(env[0]);
414 free(env[1]);
415 strbuf_release(&buf);
416}
417
2f4038ab
SP
418static int show_text_ref(const char *name, const unsigned char *sha1,
419 int flag, void *cb_data)
420{
421 struct strbuf *buf = cb_data;
422 struct object *o = parse_object(sha1);
423 if (!o)
424 return 0;
425
426 strbuf_addf(buf, "%s\t%s\n", sha1_to_hex(sha1), name);
427 if (o->type == OBJ_TAG) {
428 o = deref_tag(o, name, 0);
429 if (!o)
430 return 0;
431 strbuf_addf(buf, "%s\t%s^{}\n", sha1_to_hex(o->sha1), name);
432 }
433 return 0;
434}
435
436static void get_info_refs(char *arg)
437{
556cfa3b 438 const char *service_name = get_parameter("service");
2f4038ab
SP
439 struct strbuf buf = STRBUF_INIT;
440
2f4038ab 441 hdr_nocache();
556cfa3b
SP
442
443 if (service_name) {
444 const char *argv[] = {NULL /* service name */,
445 "--stateless-rpc", "--advertise-refs",
446 ".", NULL};
447 struct rpc_service *svc = select_service(service_name);
448
449 strbuf_addf(&buf, "application/x-git-%s-advertisement",
450 svc->name);
451 hdr_str(content_type, buf.buf);
452 end_headers();
453
454 packet_write(1, "# service=git-%s\n", svc->name);
455 packet_flush(1);
456
457 argv[0] = svc->name;
458 run_service(argv);
459
460 } else {
5abb013b 461 select_getanyfile();
556cfa3b
SP
462 for_each_ref(show_text_ref, &buf);
463 send_strbuf("text/plain", &buf);
464 }
2f4038ab
SP
465 strbuf_release(&buf);
466}
467
468static void get_info_packs(char *arg)
469{
470 size_t objdirlen = strlen(get_object_directory());
471 struct strbuf buf = STRBUF_INIT;
472 struct packed_git *p;
473 size_t cnt = 0;
474
5abb013b 475 select_getanyfile();
2f4038ab
SP
476 prepare_packed_git();
477 for (p = packed_git; p; p = p->next) {
478 if (p->pack_local)
479 cnt++;
480 }
481
482 strbuf_grow(&buf, cnt * 53 + 2);
483 for (p = packed_git; p; p = p->next) {
484 if (p->pack_local)
485 strbuf_addf(&buf, "P %s\n", p->pack_name + objdirlen + 6);
486 }
487 strbuf_addch(&buf, '\n');
488
489 hdr_nocache();
490 send_strbuf("text/plain; charset=utf-8", &buf);
491 strbuf_release(&buf);
492}
493
556cfa3b
SP
494static void check_content_type(const char *accepted_type)
495{
496 const char *actual_type = getenv("CONTENT_TYPE");
497
498 if (!actual_type)
499 actual_type = "";
500
501 if (strcmp(actual_type, accepted_type)) {
502 http_status(415, "Unsupported Media Type");
503 hdr_nocache();
504 end_headers();
505 format_write(1,
506 "Expected POST with Content-Type '%s',"
507 " but received '%s' instead.\n",
508 accepted_type, actual_type);
509 exit(0);
510 }
511}
512
513static void service_rpc(char *service_name)
514{
515 const char *argv[] = {NULL, "--stateless-rpc", ".", NULL};
516 struct rpc_service *svc = select_service(service_name);
517 struct strbuf buf = STRBUF_INIT;
518
519 strbuf_reset(&buf);
520 strbuf_addf(&buf, "application/x-git-%s-request", svc->name);
521 check_content_type(buf.buf);
522
523 hdr_nocache();
524
525 strbuf_reset(&buf);
526 strbuf_addf(&buf, "application/x-git-%s-result", svc->name);
527 hdr_str(content_type, buf.buf);
528
529 end_headers();
530
531 argv[0] = svc->name;
532 run_service(argv);
533 strbuf_release(&buf);
534}
535
2f4038ab
SP
536static NORETURN void die_webcgi(const char *err, va_list params)
537{
538 char buffer[1000];
539
540 http_status(500, "Internal Server Error");
541 hdr_nocache();
542 end_headers();
543
544 vsnprintf(buffer, sizeof(buffer), err, params);
545 fprintf(stderr, "fatal: %s\n", buffer);
546 exit(0);
547}
548
917adc03
ML
549static char* getdir(void)
550{
551 struct strbuf buf = STRBUF_INIT;
552 char *pathinfo = getenv("PATH_INFO");
553 char *root = getenv("GIT_PROJECT_ROOT");
554 char *path = getenv("PATH_TRANSLATED");
555
556 if (root && *root) {
557 if (!pathinfo || !*pathinfo)
558 die("GIT_PROJECT_ROOT is set but PATH_INFO is not");
34b6cb8b
SP
559 if (daemon_avoid_alias(pathinfo))
560 die("'%s': aliased", pathinfo);
917adc03 561 strbuf_addstr(&buf, root);
34b6cb8b
SP
562 if (buf.buf[buf.len - 1] != '/')
563 strbuf_addch(&buf, '/');
564 if (pathinfo[0] == '/')
565 pathinfo++;
917adc03
ML
566 strbuf_addstr(&buf, pathinfo);
567 return strbuf_detach(&buf, NULL);
568 } else if (path && *path) {
569 return xstrdup(path);
570 } else
571 die("No GIT_PROJECT_ROOT or PATH_TRANSLATED from server");
572 return NULL;
573}
574
2f4038ab
SP
575static struct service_cmd {
576 const char *method;
577 const char *pattern;
578 void (*imp)(char *);
579} services[] = {
580 {"GET", "/HEAD$", get_text_file},
581 {"GET", "/info/refs$", get_info_refs},
582 {"GET", "/objects/info/alternates$", get_text_file},
583 {"GET", "/objects/info/http-alternates$", get_text_file},
584 {"GET", "/objects/info/packs$", get_info_packs},
585 {"GET", "/objects/[0-9a-f]{2}/[0-9a-f]{38}$", get_loose_object},
586 {"GET", "/objects/pack/pack-[0-9a-f]{40}\\.pack$", get_pack_file},
556cfa3b
SP
587 {"GET", "/objects/pack/pack-[0-9a-f]{40}\\.idx$", get_idx_file},
588
589 {"POST", "/git-upload-pack$", service_rpc},
590 {"POST", "/git-receive-pack$", service_rpc}
2f4038ab
SP
591};
592
593int main(int argc, char **argv)
594{
595 char *method = getenv("REQUEST_METHOD");
917adc03 596 char *dir;
2f4038ab
SP
597 struct service_cmd *cmd = NULL;
598 char *cmd_arg = NULL;
599 int i;
600
601 git_extract_argv0_path(argv[0]);
602 set_die_routine(die_webcgi);
603
604 if (!method)
605 die("No REQUEST_METHOD from server");
606 if (!strcmp(method, "HEAD"))
607 method = "GET";
917adc03 608 dir = getdir();
2f4038ab
SP
609
610 for (i = 0; i < ARRAY_SIZE(services); i++) {
611 struct service_cmd *c = &services[i];
612 regex_t re;
613 regmatch_t out[1];
614
615 if (regcomp(&re, c->pattern, REG_EXTENDED))
616 die("Bogus regex in service table: %s", c->pattern);
617 if (!regexec(&re, dir, 1, out, 0)) {
618 size_t n = out[0].rm_eo - out[0].rm_so;
619
620 if (strcmp(method, c->method)) {
621 const char *proto = getenv("SERVER_PROTOCOL");
622 if (proto && !strcmp(proto, "HTTP/1.1"))
623 http_status(405, "Method Not Allowed");
624 else
625 http_status(400, "Bad Request");
626 hdr_nocache();
627 end_headers();
628 return 0;
629 }
630
631 cmd = c;
632 cmd_arg = xmalloc(n);
633 strncpy(cmd_arg, dir + out[0].rm_so + 1, n);
634 cmd_arg[n] = '\0';
635 dir[out[0].rm_so] = 0;
636 break;
637 }
638 regfree(&re);
639 }
640
641 if (!cmd)
642 not_found("Request not supported: '%s'", dir);
643
644 setup_path();
645 if (!enter_repo(dir, 0))
646 not_found("Not a git repository: '%s'", dir);
647
5abb013b 648 git_config(http_config, NULL);
2f4038ab
SP
649 cmd->imp(cmd_arg);
650 return 0;
651}