Makefile: pass CPPFLAGS through to fllow customization
[git/git.git] / daemon.c
CommitLineData
979e32fa 1#include "cache.h"
85023577 2#include "pkt-line.h"
77cb17e9 3#include "exec_cmd.h"
5d87dd4f
JS
4#include "run-command.h"
5#include "strbuf.h"
f8ff0c06 6
85023577
JH
7#include <syslog.h>
8
695dffe2
JS
9#ifndef HOST_NAME_MAX
10#define HOST_NAME_MAX 256
11#endif
12
415e7b87
PW
13#ifndef NI_MAXSERV
14#define NI_MAXSERV 32
15#endif
16
9048fe1c 17static int log_syslog;
f8ff0c06 18static int verbose;
1955fabf 19static int reuseaddr;
f8ff0c06 20
960deccb 21static const char daemon_usage[] =
1b1dd23f 22"git daemon [--verbose] [--syslog] [--export-all]\n"
3bd62c21
SB
23" [--timeout=n] [--init-timeout=n] [--max-connections=n]\n"
24" [--strict-paths] [--base-path=path] [--base-path-relaxed]\n"
73a7a656 25" [--user-path | --user-path=path]\n"
49ba83fb 26" [--interpolated-path=path]\n"
678dac6b 27" [--reuseaddr] [--detach] [--pid-file=file]\n"
d9edcbd6 28" [--[enable|disable|allow-override|forbid-override]=service]\n"
dd467629
JL
29" [--inetd | [--listen=host_or_ipaddr] [--port=n]\n"
30" [--user=user [--group=group]]\n"
31" [directory...]";
4ae95682
PA
32
33/* List of acceptable pathname prefixes */
96f1e58f
DR
34static char **ok_paths;
35static int strict_paths;
4ae95682
PA
36
37/* If this is set, git-daemon-export-ok is not required */
96f1e58f 38static int export_all_trees;
f8ff0c06 39
b21c31c9 40/* Take all paths relative to this one if non-NULL */
96f1e58f 41static char *base_path;
49ba83fb 42static char *interpolated_path;
73a7a656 43static int base_path_relaxed;
49ba83fb
JL
44
45/* Flag indicating client sent extra args. */
46static int saw_extended_args;
b21c31c9 47
603968d2
JH
48/* If defined, ~user notation is allowed and the string is inserted
49 * after ~user/. E.g. a request to git://host/~alice/frotz would
50 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
51 */
96f1e58f 52static const char *user_path;
603968d2 53
960deccb 54/* Timeout, and initial timeout */
96f1e58f
DR
55static unsigned int timeout;
56static unsigned int init_timeout;
f8ff0c06 57
9d7ca667
RS
58static char *hostname;
59static char *canon_hostname;
60static char *ip_address;
61static char *tcp_port;
49ba83fb 62
9048fe1c 63static void logreport(int priority, const char *err, va_list params)
f8ff0c06 64{
9048fe1c 65 if (log_syslog) {
6a992e9e
SB
66 char buf[1024];
67 vsnprintf(buf, sizeof(buf), err, params);
9048fe1c 68 syslog(priority, "%s", buf);
460c2010
JH
69 } else {
70 /*
71 * Since stderr is set to linebuffered mode, the
6a992e9e
SB
72 * logging of different processes will not overlap
73 */
85e72830 74 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
6a992e9e
SB
75 vfprintf(stderr, err, params);
76 fputc('\n', stderr);
77 }
f8ff0c06
PB
78}
79
28bea9e5 80__attribute__((format (printf, 1, 2)))
cdda4745 81static void logerror(const char *err, ...)
f8ff0c06
PB
82{
83 va_list params;
84 va_start(params, err);
9048fe1c 85 logreport(LOG_ERR, err, params);
f8ff0c06
PB
86 va_end(params);
87}
88
28bea9e5 89__attribute__((format (printf, 1, 2)))
cdda4745 90static void loginfo(const char *err, ...)
f8ff0c06
PB
91{
92 va_list params;
93 if (!verbose)
94 return;
95 va_start(params, err);
9048fe1c 96 logreport(LOG_INFO, err, params);
f8ff0c06
PB
97 va_end(params);
98}
a87e8be2 99
ad8b4f56
ML
100static void NORETURN daemon_die(const char *err, va_list params)
101{
102 logreport(LOG_ERR, err, params);
103 exit(1);
104}
105
a47551c3 106static char *path_ok(char *directory)
4ae95682 107{
603968d2 108 static char rpath[PATH_MAX];
49ba83fb 109 static char interp_path[PATH_MAX];
d79374c7 110 char *path;
49ba83fb
JL
111 char *dir;
112
9d7ca667 113 dir = directory;
d79374c7 114
34b6cb8b 115 if (daemon_avoid_alias(dir)) {
d79374c7
JH
116 logerror("'%s': aliased", dir);
117 return NULL;
118 }
119
603968d2
JH
120 if (*dir == '~') {
121 if (!user_path) {
122 logerror("'%s': User-path not allowed", dir);
123 return NULL;
124 }
125 if (*user_path) {
126 /* Got either "~alice" or "~alice/foo";
127 * rewrite them to "~alice/%s" or
128 * "~alice/%s/foo".
129 */
130 int namlen, restlen = strlen(dir);
131 char *slash = strchr(dir, '/');
132 if (!slash)
133 slash = dir + restlen;
134 namlen = slash - dir;
135 restlen -= namlen;
136 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
137 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
138 namlen, dir, user_path, restlen, slash);
139 dir = rpath;
140 }
141 }
49ba83fb 142 else if (interpolated_path && saw_extended_args) {
9d7ca667
RS
143 struct strbuf expanded_path = STRBUF_INIT;
144 struct strbuf_expand_dict_entry dict[] = {
145 { "H", hostname },
146 { "CH", canon_hostname },
147 { "IP", ip_address },
148 { "P", tcp_port },
149 { "D", directory },
9d7ca667
RS
150 { NULL }
151 };
152
49ba83fb
JL
153 if (*dir != '/') {
154 /* Allow only absolute */
155 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
156 return NULL;
157 }
158
9d7ca667
RS
159 strbuf_expand(&expanded_path, interpolated_path,
160 strbuf_expand_dict_cb, &dict);
161 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
162 strbuf_release(&expanded_path);
49ba83fb
JL
163 loginfo("Interpolated dir '%s'", interp_path);
164
165 dir = interp_path;
166 }
603968d2
JH
167 else if (base_path) {
168 if (*dir != '/') {
169 /* Allow only absolute */
1fda3d55 170 logerror("'%s': Non-absolute path denied (base-path active)", dir);
b21c31c9
PB
171 return NULL;
172 }
49ba83fb
JL
173 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
174 dir = rpath;
b21c31c9
PB
175 }
176
a583971f
RS
177 path = enter_repo(dir, strict_paths);
178 if (!path && base_path && base_path_relaxed) {
73a7a656
JA
179 /*
180 * if we fail and base_path_relaxed is enabled, try without
181 * prefixing the base path
182 */
a583971f
RS
183 dir = directory;
184 path = enter_repo(dir, strict_paths);
185 }
3e04c62d 186
4dbd1352 187 if (!path) {
05ac6b34 188 logerror("'%s' does not appear to be a git repository", dir);
4dbd1352 189 return NULL;
4ae95682
PA
190 }
191
192 if ( ok_paths && *ok_paths ) {
ce335fe0 193 char **pp;
4dbd1352 194 int pathlen = strlen(path);
4ae95682 195
ce335fe0 196 /* The validation is done on the paths after enter_repo
a6080a0a 197 * appends optional {.git,.git/.git} and friends, but
d79374c7
JH
198 * it does not use getcwd(). So if your /pub is
199 * a symlink to /mnt/pub, you can whitelist /pub and
200 * do not have to say /mnt/pub.
201 * Do not say /pub/.
ce335fe0 202 */
4ae95682
PA
203 for ( pp = ok_paths ; *pp ; pp++ ) {
204 int len = strlen(*pp);
ce335fe0
JH
205 if (len <= pathlen &&
206 !memcmp(*pp, path, len) &&
207 (path[len] == '\0' ||
208 (!strict_paths && path[len] == '/')))
209 return path;
4ae95682 210 }
4dbd1352
AE
211 }
212 else {
213 /* be backwards compatible */
214 if (!strict_paths)
215 return path;
4ae95682
PA
216 }
217
4dbd1352
AE
218 logerror("'%s': not in whitelist", path);
219 return NULL; /* Fallthrough. Deny by default */
4ae95682 220}
a87e8be2 221
d819e4e6
JH
222typedef int (*daemon_service_fn)(void);
223struct daemon_service {
224 const char *name;
225 const char *config_name;
226 daemon_service_fn fn;
227 int enabled;
228 int overridable;
229};
230
231static struct daemon_service *service_looking_at;
232static int service_enabled;
233
ef90d6d4 234static int git_daemon_config(const char *var, const char *value, void *cb)
d819e4e6 235{
cc44c765 236 if (!prefixcmp(var, "daemon.") &&
d819e4e6
JH
237 !strcmp(var + 7, service_looking_at->config_name)) {
238 service_enabled = git_config_bool(var, value);
239 return 0;
240 }
241
242 /* we are not interested in parsing any other configuration here */
243 return 0;
244}
245
a47551c3 246static int run_service(char *dir, struct daemon_service *service)
a87e8be2 247{
4dbd1352 248 const char *path;
d819e4e6
JH
249 int enabled = service->enabled;
250
a47551c3 251 loginfo("Request %s for '%s'", service->name, dir);
4dbd1352 252
d819e4e6
JH
253 if (!enabled && !service->overridable) {
254 logerror("'%s': service not enabled.", service->name);
255 errno = EACCES;
256 return -1;
257 }
4ae95682 258
a47551c3 259 if (!(path = path_ok(dir)))
a87e8be2 260 return -1;
47888f0f 261
a87e8be2
LT
262 /*
263 * Security on the cheap.
264 *
a935c397 265 * We want a readable HEAD, usable "objects" directory, and
a87e8be2
LT
266 * a "git-daemon-export-ok" flag that says that the other side
267 * is ok with us doing this.
4dbd1352
AE
268 *
269 * path_ok() uses enter_repo() and does whitelist checking.
270 * We only need to make sure the repository is exported.
a87e8be2 271 */
4dbd1352 272
3e04c62d 273 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
4dbd1352 274 logerror("'%s': repository not exported.", path);
3e04c62d
PA
275 errno = EACCES;
276 return -1;
277 }
278
d819e4e6
JH
279 if (service->overridable) {
280 service_looking_at = service;
281 service_enabled = -1;
ef90d6d4 282 git_config(git_daemon_config, NULL);
d819e4e6
JH
283 if (0 <= service_enabled)
284 enabled = service_enabled;
285 }
286 if (!enabled) {
287 logerror("'%s': service not enabled for '%s'",
288 service->name, path);
289 errno = EACCES;
290 return -1;
291 }
292
02d57da4
LT
293 /*
294 * We'll ignore SIGTERM from now on, we have a
295 * good client.
296 */
297 signal(SIGTERM, SIG_IGN);
298
d819e4e6
JH
299 return service->fn();
300}
301
5d87dd4f
JS
302static void copy_to_log(int fd)
303{
304 struct strbuf line = STRBUF_INIT;
305 FILE *fp;
306
307 fp = fdopen(fd, "r");
308 if (fp == NULL) {
309 logerror("fdopen of error channel failed");
310 close(fd);
311 return;
312 }
313
314 while (strbuf_getline(&line, fp, '\n') != EOF) {
315 logerror("%s", line.buf);
316 strbuf_setlen(&line, 0);
317 }
318
319 strbuf_release(&line);
320 fclose(fp);
321}
322
323static int run_service_command(const char **argv)
324{
325 struct child_process cld;
326
327 memset(&cld, 0, sizeof(cld));
328 cld.argv = argv;
329 cld.git_cmd = 1;
330 cld.err = -1;
331 if (start_command(&cld))
332 return -1;
333
334 close(0);
335 close(1);
336
337 copy_to_log(cld.err);
338
339 return finish_command(&cld);
340}
341
d819e4e6
JH
342static int upload_pack(void)
343{
344 /* Timeout as string */
345 char timeout_buf[64];
5d87dd4f 346 const char *argv[] = { "upload-pack", "--strict", timeout_buf, ".", NULL };
d819e4e6 347
960deccb 348 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
5d87dd4f 349 return run_service_command(argv);
a87e8be2
LT
350}
351
39345a21
FBH
352static int upload_archive(void)
353{
5d87dd4f
JS
354 static const char *argv[] = { "upload-archive", ".", NULL };
355 return run_service_command(argv);
39345a21
FBH
356}
357
4b3b1e1e
LT
358static int receive_pack(void)
359{
5d87dd4f
JS
360 static const char *argv[] = { "receive-pack", ".", NULL };
361 return run_service_command(argv);
4b3b1e1e
LT
362}
363
d819e4e6 364static struct daemon_service daemon_service[] = {
39345a21 365 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
d819e4e6 366 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
4b3b1e1e 367 { "receive-pack", "receivepack", receive_pack, 0, 1 },
d819e4e6
JH
368};
369
f3fa1838
JH
370static void enable_service(const char *name, int ena)
371{
d819e4e6
JH
372 int i;
373 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
374 if (!strcmp(daemon_service[i].name, name)) {
375 daemon_service[i].enabled = ena;
376 return;
377 }
378 }
379 die("No such service %s", name);
380}
381
f3fa1838
JH
382static void make_service_overridable(const char *name, int ena)
383{
d819e4e6
JH
384 int i;
385 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
386 if (!strcmp(daemon_service[i].name, name)) {
387 daemon_service[i].overridable = ena;
388 return;
389 }
390 }
391 die("No such service %s", name);
392}
393
6720e95b
RS
394static char *xstrdup_tolower(const char *str)
395{
396 char *p, *dup = xstrdup(str);
397 for (p = dup; *p; p++)
398 *p = tolower(*p);
399 return dup;
400}
401
e8dbd76d
IL
402static void parse_host_and_port(char *hostport, char **host,
403 char **port)
404{
405 if (*hostport == '[') {
406 char *end;
407
408 end = strchr(hostport, ']');
409 if (!end)
9517e6b8 410 die("Invalid request ('[' without ']')");
e8dbd76d
IL
411 *end = '\0';
412 *host = hostport + 1;
413 if (!end[1])
414 *port = NULL;
415 else if (end[1] == ':')
416 *port = end + 2;
417 else
418 die("Garbage after end of host part");
419 } else {
420 *host = hostport;
421 *port = strrchr(hostport, ':');
422 if (*port) {
e9bd3235 423 **port = '\0';
e8dbd76d
IL
424 ++*port;
425 }
426 }
427}
428
eb30aed7 429/*
73bb33a9 430 * Read the host as supplied by the client connection.
eb30aed7 431 */
73bb33a9 432static void parse_host_arg(char *extra_args, int buflen)
49ba83fb
JL
433{
434 char *val;
435 int vallen;
436 char *end = extra_args + buflen;
437
73bb33a9 438 if (extra_args < end && *extra_args) {
49ba83fb
JL
439 saw_extended_args = 1;
440 if (strncasecmp("host=", extra_args, 5) == 0) {
441 val = extra_args + 5;
442 vallen = strlen(val) + 1;
443 if (*val) {
eb30aed7 444 /* Split <host>:<port> at colon. */
e8dbd76d
IL
445 char *host;
446 char *port;
447 parse_host_and_port(val, &host, &port);
dd467629 448 if (port) {
9d7ca667
RS
449 free(tcp_port);
450 tcp_port = xstrdup(port);
dd467629 451 }
9d7ca667 452 free(hostname);
6720e95b 453 hostname = xstrdup_tolower(host);
49ba83fb 454 }
eb30aed7 455
49ba83fb
JL
456 /* On to the next one */
457 extra_args = val + vallen;
458 }
73bb33a9
SP
459 if (extra_args < end && *extra_args)
460 die("Invalid request");
49ba83fb 461 }
dd467629 462
dd467629
JL
463 /*
464 * Locate canonical hostname and its IP address.
465 */
6720e95b 466 if (hostname) {
dd467629 467#ifndef NO_IPV6
dd467629 468 struct addrinfo hints;
3e8a00ae 469 struct addrinfo *ai;
dd467629
JL
470 int gai;
471 static char addrbuf[HOST_NAME_MAX + 1];
472
473 memset(&hints, 0, sizeof(hints));
474 hints.ai_flags = AI_CANONNAME;
475
2af202be 476 gai = getaddrinfo(hostname, NULL, &hints, &ai);
dd467629 477 if (!gai) {
3e8a00ae
BK
478 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
479
480 inet_ntop(AF_INET, &sin_addr->sin_addr,
481 addrbuf, sizeof(addrbuf));
482 free(ip_address);
483 ip_address = xstrdup(addrbuf);
484
485 free(canon_hostname);
486 canon_hostname = xstrdup(ai->ai_canonname ?
487 ai->ai_canonname : ip_address);
488
489 freeaddrinfo(ai);
dd467629 490 }
dd467629 491#else
dd467629
JL
492 struct hostent *hent;
493 struct sockaddr_in sa;
494 char **ap;
495 static char addrbuf[HOST_NAME_MAX + 1];
496
9d7ca667 497 hent = gethostbyname(hostname);
dd467629
JL
498
499 ap = hent->h_addr_list;
500 memset(&sa, 0, sizeof sa);
501 sa.sin_family = hent->h_addrtype;
502 sa.sin_port = htons(0);
503 memcpy(&sa.sin_addr, *ap, hent->h_length);
504
505 inet_ntop(hent->h_addrtype, &sa.sin_addr,
506 addrbuf, sizeof(addrbuf));
eb30aed7 507
9d7ca667
RS
508 free(canon_hostname);
509 canon_hostname = xstrdup(hent->h_name);
510 free(ip_address);
511 ip_address = xstrdup(addrbuf);
dd467629 512#endif
6720e95b 513 }
dd467629
JL
514}
515
516
5b276ee4 517static int execute(struct sockaddr *addr)
a87e8be2 518{
7d80694a 519 static char line[1000];
d819e4e6 520 int pktlen, len, i;
7d80694a 521
5b276ee4
DW
522 if (addr) {
523 char addrbuf[256] = "";
524 int port = -1;
525
526 if (addr->sa_family == AF_INET) {
527 struct sockaddr_in *sin_addr = (void *) addr;
528 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
c67359be 529 port = ntohs(sin_addr->sin_port);
5b276ee4
DW
530#ifndef NO_IPV6
531 } else if (addr && addr->sa_family == AF_INET6) {
532 struct sockaddr_in6 *sin6_addr = (void *) addr;
533
534 char *buf = addrbuf;
535 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
536 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
537 strcat(buf, "]");
538
c67359be 539 port = ntohs(sin6_addr->sin6_port);
5b276ee4
DW
540#endif
541 }
542 loginfo("Connection from %s:%d", addrbuf, port);
53ffb878
JH
543 setenv("REMOTE_ADDR", addrbuf, 1);
544 }
545 else {
546 unsetenv("REMOTE_ADDR");
5b276ee4
DW
547 }
548
960deccb 549 alarm(init_timeout ? init_timeout : timeout);
5ad312be 550 pktlen = packet_read_line(0, line, sizeof(line));
960deccb 551 alarm(0);
7d80694a 552
5ad312be
JL
553 len = strlen(line);
554 if (pktlen != len)
555 loginfo("Extended attributes (%d bytes) exist <%.*s>",
556 (int) pktlen - len,
557 (int) pktlen - len, line + len + 1);
83543a24 558 if (len && line[len-1] == '\n') {
7d80694a 559 line[--len] = 0;
83543a24
JH
560 pktlen--;
561 }
7d80694a 562
9d7ca667
RS
563 free(hostname);
564 free(canon_hostname);
565 free(ip_address);
566 free(tcp_port);
a47551c3 567 hostname = canon_hostname = ip_address = tcp_port = NULL;
eb30aed7 568
d433ed0b 569 if (len != pktlen)
73bb33a9 570 parse_host_arg(line + len + 1, pktlen - len - 1);
49ba83fb 571
d819e4e6
JH
572 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
573 struct daemon_service *s = &(daemon_service[i]);
574 int namelen = strlen(s->name);
599065a3 575 if (!prefixcmp(line, "git-") &&
d819e4e6 576 !strncmp(s->name, line + 4, namelen) &&
49ba83fb 577 line[namelen + 4] == ' ') {
eb30aed7
JL
578 /*
579 * Note: The directory here is probably context sensitive,
580 * and might depend on the actual service being performed.
581 */
a47551c3 582 return run_service(line + namelen + 5, s);
49ba83fb 583 }
d819e4e6 584 }
a87e8be2 585
f8ff0c06 586 logerror("Protocol error: '%s'", line);
a87e8be2
LT
587 return -1;
588}
589
15515b73
EFL
590static int addrcmp(const struct sockaddr_storage *s1,
591 const struct sockaddr_storage *s2)
592{
3aff874a
BC
593 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
594 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
595
596 if (sa1->sa_family != sa2->sa_family)
597 return sa1->sa_family - sa2->sa_family;
598 if (sa1->sa_family == AF_INET)
15515b73
EFL
599 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
600 &((struct sockaddr_in *)s2)->sin_addr,
601 sizeof(struct in_addr));
602#ifndef NO_IPV6
3aff874a 603 if (sa1->sa_family == AF_INET6)
15515b73
EFL
604 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
605 &((struct sockaddr_in6 *)s2)->sin6_addr,
606 sizeof(struct in6_addr));
607#endif
608 return 0;
609}
610
3bd62c21 611static int max_connections = 32;
66e631de 612
3bd62c21 613static unsigned int live_children;
66e631de 614
4d8fa916 615static struct child {
3bd62c21 616 struct child *next;
66e631de 617 pid_t pid;
df076bdb 618 struct sockaddr_storage address;
3bd62c21 619} *firstborn;
66e631de 620
3bd62c21 621static void add_child(pid_t pid, struct sockaddr *addr, int addrlen)
66e631de 622{
460c2010
JH
623 struct child *newborn, **cradle;
624
460c2010
JH
625 newborn = xcalloc(1, sizeof(*newborn));
626 live_children++;
627 newborn->pid = pid;
628 memcpy(&newborn->address, addr, addrlen);
629 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
15515b73 630 if (!addrcmp(&(*cradle)->address, &newborn->address))
460c2010
JH
631 break;
632 newborn->next = *cradle;
633 *cradle = newborn;
66e631de
LT
634}
635
3bd62c21 636static void remove_child(pid_t pid)
66e631de 637{
3bd62c21 638 struct child **cradle, *blanket;
66e631de 639
3bd62c21
SB
640 for (cradle = &firstborn; (blanket = *cradle); cradle = &blanket->next)
641 if (blanket->pid == pid) {
642 *cradle = blanket->next;
643 live_children--;
644 free(blanket);
645 break;
646 }
66e631de
LT
647}
648
649/*
650 * This gets called if the number of connections grows
651 * past "max_connections".
652 *
3bd62c21 653 * We kill the newest connection from a duplicate IP.
66e631de 654 */
3bd62c21 655static void kill_some_child(void)
66e631de 656{
460c2010 657 const struct child *blanket, *next;
66e631de 658
460c2010
JH
659 if (!(blanket = firstborn))
660 return;
695605b5 661
460c2010 662 for (; (next = blanket->next); blanket = next)
15515b73 663 if (!addrcmp(&blanket->address, &next->address)) {
460c2010
JH
664 kill(blanket->pid, SIGTERM);
665 break;
666 }
a5a9126b
JS
667}
668
3bd62c21 669static void check_dead_children(void)
a87e8be2 670{
3bd62c21
SB
671 int status;
672 pid_t pid;
02d57da4 673
460c2010 674 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
3bd62c21
SB
675 const char *dead = "";
676 remove_child(pid);
460c2010 677 if (!WIFEXITED(status) || (WEXITSTATUS(status) > 0))
3bd62c21 678 dead = " (with error)";
85e72830 679 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
02d57da4
LT
680 }
681}
682
7fa09084 683static void handle(int incoming, struct sockaddr *addr, int addrlen)
02d57da4 684{
3bd62c21 685 pid_t pid;
02d57da4 686
3bd62c21
SB
687 if (max_connections && live_children >= max_connections) {
688 kill_some_child();
460c2010 689 sleep(1); /* give it some time to die */
3bd62c21
SB
690 check_dead_children();
691 if (live_children >= max_connections) {
692 close(incoming);
693 logerror("Too many children, dropping connection");
694 return;
695 }
696 }
02d57da4 697
3bd62c21 698 if ((pid = fork())) {
02d57da4 699 close(incoming);
3bd62c21
SB
700 if (pid < 0) {
701 logerror("Couldn't fork %s", strerror(errno));
02d57da4 702 return;
3bd62c21 703 }
02d57da4 704
3bd62c21 705 add_child(pid, addr, addrlen);
a87e8be2
LT
706 return;
707 }
708
709 dup2(incoming, 0);
710 dup2(incoming, 1);
711 close(incoming);
f8ff0c06 712
5b276ee4 713 exit(execute(addr));
a87e8be2
LT
714}
715
eaa94919
LT
716static void child_handler(int signo)
717{
460c2010
JH
718 /*
719 * Otherwise empty handler because systemcalls will get interrupted
695605b5
SB
720 * upon signal receipt
721 * SysV needs the handler to be rearmed
722 */
bd7b371e 723 signal(SIGCHLD, child_handler);
eaa94919
LT
724}
725
1955fabf
MW
726static int set_reuse_addr(int sockfd)
727{
728 int on = 1;
729
730 if (!reuseaddr)
731 return 0;
732 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
733 &on, sizeof(on));
734}
735
6573faff
PA
736#ifndef NO_IPV6
737
dd467629 738static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
a87e8be2 739{
df076bdb
YH
740 int socknum = 0, *socklist = NULL;
741 int maxfd = -1;
df076bdb 742 char pbuf[NI_MAXSERV];
6573faff
PA
743 struct addrinfo hints, *ai0, *ai;
744 int gai;
20276889 745 long flags;
df076bdb 746
dd467629 747 sprintf(pbuf, "%d", listen_port);
df076bdb
YH
748 memset(&hints, 0, sizeof(hints));
749 hints.ai_family = AF_UNSPEC;
750 hints.ai_socktype = SOCK_STREAM;
751 hints.ai_protocol = IPPROTO_TCP;
752 hints.ai_flags = AI_PASSIVE;
753
dd467629 754 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
df076bdb 755 if (gai)
d7530708 756 die("getaddrinfo() failed: %s", gai_strerror(gai));
df076bdb 757
df076bdb
YH
758 for (ai = ai0; ai; ai = ai->ai_next) {
759 int sockfd;
df076bdb
YH
760
761 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
762 if (sockfd < 0)
763 continue;
764 if (sockfd >= FD_SETSIZE) {
df0daf8a 765 logerror("Socket descriptor too large");
df076bdb
YH
766 close(sockfd);
767 continue;
768 }
769
770#ifdef IPV6_V6ONLY
771 if (ai->ai_family == AF_INET6) {
772 int on = 1;
773 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
774 &on, sizeof(on));
775 /* Note: error is not fatal */
776 }
777#endif
778
1955fabf
MW
779 if (set_reuse_addr(sockfd)) {
780 close(sockfd);
0032d548 781 continue;
1955fabf
MW
782 }
783
df076bdb
YH
784 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
785 close(sockfd);
786 continue; /* not fatal */
787 }
788 if (listen(sockfd, 5) < 0) {
789 close(sockfd);
790 continue; /* not fatal */
791 }
792
20276889
AJ
793 flags = fcntl(sockfd, F_GETFD, 0);
794 if (flags >= 0)
795 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
796
83572c1a 797 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
df076bdb
YH
798 socklist[socknum++] = sockfd;
799
df076bdb
YH
800 if (maxfd < sockfd)
801 maxfd = sockfd;
802 }
803
804 freeaddrinfo(ai0);
805
6573faff
PA
806 *socklist_p = socklist;
807 return socknum;
808}
809
810#else /* NO_IPV6 */
811
100690b6 812static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
6573faff
PA
813{
814 struct sockaddr_in sin;
815 int sockfd;
20276889 816 long flags;
6573faff 817
dd467629
JL
818 memset(&sin, 0, sizeof sin);
819 sin.sin_family = AF_INET;
820 sin.sin_port = htons(listen_port);
821
822 if (listen_addr) {
823 /* Well, host better be an IP address here. */
824 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
825 return 0;
826 } else {
827 sin.sin_addr.s_addr = htonl(INADDR_ANY);
828 }
829
6573faff
PA
830 sockfd = socket(AF_INET, SOCK_STREAM, 0);
831 if (sockfd < 0)
832 return 0;
833
1955fabf
MW
834 if (set_reuse_addr(sockfd)) {
835 close(sockfd);
836 return 0;
837 }
838
6573faff
PA
839 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
840 close(sockfd);
841 return 0;
842 }
a87e8be2 843
f35230fb
PS
844 if (listen(sockfd, 5) < 0) {
845 close(sockfd);
846 return 0;
847 }
848
20276889
AJ
849 flags = fcntl(sockfd, F_GETFD, 0);
850 if (flags >= 0)
851 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
852
1b4713fb 853 *socklist_p = xmalloc(sizeof(int));
6573faff 854 **socklist_p = sockfd;
f35230fb 855 return 1;
6573faff
PA
856}
857
858#endif
859
860static int service_loop(int socknum, int *socklist)
861{
862 struct pollfd *pfd;
863 int i;
864
695605b5 865 pfd = xcalloc(socknum, sizeof(struct pollfd));
6573faff
PA
866
867 for (i = 0; i < socknum; i++) {
868 pfd[i].fd = socklist[i];
869 pfd[i].events = POLLIN;
870 }
9220282a
PA
871
872 signal(SIGCHLD, child_handler);
a87e8be2
LT
873
874 for (;;) {
df076bdb 875 int i;
6573faff 876
695605b5
SB
877 check_dead_children();
878
879 if (poll(pfd, socknum, -1) < 0) {
1eef0b33 880 if (errno != EINTR) {
df0daf8a 881 logerror("Poll failed, resuming: %s",
1eef0b33
JH
882 strerror(errno));
883 sleep(1);
884 }
df076bdb
YH
885 continue;
886 }
887
888 for (i = 0; i < socknum; i++) {
6573faff 889 if (pfd[i].revents & POLLIN) {
df076bdb 890 struct sockaddr_storage ss;
7626e49e 891 unsigned int sslen = sizeof(ss);
6573faff 892 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
df076bdb
YH
893 if (incoming < 0) {
894 switch (errno) {
895 case EAGAIN:
896 case EINTR:
897 case ECONNABORTED:
898 continue;
899 default:
d824cbba 900 die_errno("accept returned");
df076bdb
YH
901 }
902 }
903 handle(incoming, (struct sockaddr *)&ss, sslen);
a87e8be2
LT
904 }
905 }
a87e8be2
LT
906 }
907}
908
258e93a1
ML
909/* if any standard file descriptor is missing open it to /dev/null */
910static void sanitize_stdfds(void)
911{
912 int fd = open("/dev/null", O_RDWR, 0);
913 while (fd != -1 && fd < 2)
914 fd = dup(fd);
915 if (fd == -1)
d824cbba 916 die_errno("open /dev/null or dup failed");
258e93a1
ML
917 if (fd > 2)
918 close(fd);
919}
920
a5262768
ML
921static void daemonize(void)
922{
923 switch (fork()) {
924 case 0:
925 break;
926 case -1:
d824cbba 927 die_errno("fork failed");
a5262768
ML
928 default:
929 exit(0);
930 }
931 if (setsid() == -1)
d824cbba 932 die_errno("setsid failed");
a5262768
ML
933 close(0);
934 close(1);
935 close(2);
936 sanitize_stdfds();
937}
938
45ed5d7f
ML
939static void store_pid(const char *path)
940{
941 FILE *f = fopen(path, "w");
942 if (!f)
d824cbba 943 die_errno("cannot open pid file '%s'", path);
85e72830 944 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
d824cbba 945 die_errno("failed to write pid file '%s'", path);
45ed5d7f
ML
946}
947
dd467629 948static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
6573faff
PA
949{
950 int socknum, *socklist;
4ae22d96 951
dd467629 952 socknum = socksetup(listen_addr, listen_port, &socklist);
6573faff 953 if (socknum == 0)
dd467629
JL
954 die("unable to allocate any listen sockets on host %s port %u",
955 listen_addr, listen_port);
4ae22d96 956
678dac6b
TS
957 if (pass && gid &&
958 (initgroups(pass->pw_name, gid) || setgid (gid) ||
959 setuid(pass->pw_uid)))
960 die("cannot drop privileges");
961
6573faff 962 return service_loop(socknum, socklist);
4ae22d96 963}
6573faff 964
a87e8be2
LT
965int main(int argc, char **argv)
966{
dd467629
JL
967 int listen_port = 0;
968 char *listen_addr = NULL;
e64e1b79 969 int inetd_mode = 0;
678dac6b 970 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
a5262768 971 int detach = 0;
678dac6b
TS
972 struct passwd *pass = NULL;
973 struct group *group;
974 gid_t gid = 0;
a87e8be2
LT
975 int i;
976
2fb3f6db
SP
977 git_extract_argv0_path(argv[0]);
978
a87e8be2
LT
979 for (i = 1; i < argc; i++) {
980 char *arg = argv[i];
981
cc44c765 982 if (!prefixcmp(arg, "--listen=")) {
6720e95b
RS
983 listen_addr = xstrdup_tolower(arg + 9);
984 continue;
dd467629 985 }
cc44c765 986 if (!prefixcmp(arg, "--port=")) {
a87e8be2
LT
987 char *end;
988 unsigned long n;
989 n = strtoul(arg+7, &end, 0);
990 if (arg[7] && !*end) {
dd467629 991 listen_port = n;
a87e8be2
LT
992 continue;
993 }
994 }
e64e1b79
LT
995 if (!strcmp(arg, "--inetd")) {
996 inetd_mode = 1;
a8883288 997 log_syslog = 1;
e64e1b79
LT
998 continue;
999 }
f8ff0c06
PB
1000 if (!strcmp(arg, "--verbose")) {
1001 verbose = 1;
1002 continue;
1003 }
9048fe1c
PB
1004 if (!strcmp(arg, "--syslog")) {
1005 log_syslog = 1;
9048fe1c
PB
1006 continue;
1007 }
4ae95682
PA
1008 if (!strcmp(arg, "--export-all")) {
1009 export_all_trees = 1;
1010 continue;
1011 }
cc44c765 1012 if (!prefixcmp(arg, "--timeout=")) {
960deccb 1013 timeout = atoi(arg+10);
a8883288 1014 continue;
960deccb 1015 }
cc44c765 1016 if (!prefixcmp(arg, "--init-timeout=")) {
960deccb 1017 init_timeout = atoi(arg+15);
a8883288 1018 continue;
960deccb 1019 }
3bd62c21
SB
1020 if (!prefixcmp(arg, "--max-connections=")) {
1021 max_connections = atoi(arg+18);
1022 if (max_connections < 0)
1023 max_connections = 0; /* unlimited */
1024 continue;
1025 }
4dbd1352
AE
1026 if (!strcmp(arg, "--strict-paths")) {
1027 strict_paths = 1;
1028 continue;
1029 }
cc44c765 1030 if (!prefixcmp(arg, "--base-path=")) {
b21c31c9
PB
1031 base_path = arg+12;
1032 continue;
1033 }
73a7a656
JA
1034 if (!strcmp(arg, "--base-path-relaxed")) {
1035 base_path_relaxed = 1;
1036 continue;
1037 }
cc44c765 1038 if (!prefixcmp(arg, "--interpolated-path=")) {
49ba83fb
JL
1039 interpolated_path = arg+20;
1040 continue;
1041 }
1955fabf
MW
1042 if (!strcmp(arg, "--reuseaddr")) {
1043 reuseaddr = 1;
1044 continue;
1045 }
603968d2
JH
1046 if (!strcmp(arg, "--user-path")) {
1047 user_path = "";
1048 continue;
1049 }
cc44c765 1050 if (!prefixcmp(arg, "--user-path=")) {
603968d2
JH
1051 user_path = arg + 12;
1052 continue;
1053 }
cc44c765 1054 if (!prefixcmp(arg, "--pid-file=")) {
45ed5d7f
ML
1055 pid_file = arg + 11;
1056 continue;
1057 }
a5262768
ML
1058 if (!strcmp(arg, "--detach")) {
1059 detach = 1;
1060 log_syslog = 1;
1061 continue;
1062 }
cc44c765 1063 if (!prefixcmp(arg, "--user=")) {
678dac6b
TS
1064 user_name = arg + 7;
1065 continue;
1066 }
cc44c765 1067 if (!prefixcmp(arg, "--group=")) {
678dac6b
TS
1068 group_name = arg + 8;
1069 continue;
1070 }
cc44c765 1071 if (!prefixcmp(arg, "--enable=")) {
d819e4e6
JH
1072 enable_service(arg + 9, 1);
1073 continue;
1074 }
cc44c765 1075 if (!prefixcmp(arg, "--disable=")) {
d819e4e6
JH
1076 enable_service(arg + 10, 0);
1077 continue;
1078 }
cc44c765 1079 if (!prefixcmp(arg, "--allow-override=")) {
74c0cc21 1080 make_service_overridable(arg + 17, 1);
d819e4e6
JH
1081 continue;
1082 }
cc44c765 1083 if (!prefixcmp(arg, "--forbid-override=")) {
74c0cc21 1084 make_service_overridable(arg + 18, 0);
d819e4e6
JH
1085 continue;
1086 }
4ae95682
PA
1087 if (!strcmp(arg, "--")) {
1088 ok_paths = &argv[i+1];
1089 break;
1090 } else if (arg[0] != '-') {
1091 ok_paths = &argv[i];
1092 break;
1093 }
e64e1b79 1094
a87e8be2
LT
1095 usage(daemon_usage);
1096 }
1097
22665bba 1098 if (log_syslog) {
6a992e9e 1099 openlog("git-daemon", LOG_PID, LOG_DAEMON);
22665bba 1100 set_die_routine(daemon_die);
460c2010 1101 } else
48196afd
JH
1102 /* avoid splitting a message in the middle */
1103 setvbuf(stderr, NULL, _IOLBF, 0);
22665bba 1104
678dac6b
TS
1105 if (inetd_mode && (group_name || user_name))
1106 die("--user and --group are incompatible with --inetd");
1107
dd467629
JL
1108 if (inetd_mode && (listen_port || listen_addr))
1109 die("--listen= and --port= are incompatible with --inetd");
1110 else if (listen_port == 0)
1111 listen_port = DEFAULT_GIT_PORT;
1112
678dac6b
TS
1113 if (group_name && !user_name)
1114 die("--group supplied without --user");
1115
1116 if (user_name) {
1117 pass = getpwnam(user_name);
1118 if (!pass)
1119 die("user not found - %s", user_name);
1120
1121 if (!group_name)
1122 gid = pass->pw_gid;
1123 else {
1124 group = getgrnam(group_name);
1125 if (!group)
1126 die("group not found - %s", group_name);
1127
1128 gid = group->gr_gid;
1129 }
1130 }
1131
ad8b4f56
ML
1132 if (strict_paths && (!ok_paths || !*ok_paths))
1133 die("option --strict-paths requires a whitelist");
1134
90b4a71c
JH
1135 if (base_path && !is_directory(base_path))
1136 die("base-path '%s' does not exist or is not a directory",
1137 base_path);
20632071 1138
7c3693f1 1139 if (inetd_mode) {
5b276ee4
DW
1140 struct sockaddr_storage ss;
1141 struct sockaddr *peer = (struct sockaddr *)&ss;
1142 socklen_t slen = sizeof(ss);
1143
c569b1fe 1144 if (!freopen("/dev/null", "w", stderr))
d824cbba 1145 die_errno("failed to redirect stderr to /dev/null");
5b276ee4
DW
1146
1147 if (getpeername(0, peer, &slen))
1148 peer = NULL;
1149
1150 return execute(peer);
7c3693f1 1151 }
bce8230d 1152
6a992e9e 1153 if (detach) {
a5262768 1154 daemonize();
6a992e9e
SB
1155 loginfo("Ready to rumble");
1156 }
a5262768
ML
1157 else
1158 sanitize_stdfds();
258e93a1 1159
45ed5d7f
ML
1160 if (pid_file)
1161 store_pid(pid_file);
1162
dd467629 1163 return serve(listen_addr, listen_port, pass, gid);
a87e8be2 1164}