daemon: use run-command api for async serving
[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"
3a3a29c1 6#include "string-list.h"
f8ff0c06 7
695dffe2
JS
8#ifndef HOST_NAME_MAX
9#define HOST_NAME_MAX 256
10#endif
11
415e7b87
PW
12#ifndef NI_MAXSERV
13#define NI_MAXSERV 32
14#endif
15
9048fe1c 16static int log_syslog;
f8ff0c06 17static int verbose;
1955fabf 18static int reuseaddr;
f8ff0c06 19
960deccb 20static const char daemon_usage[] =
1b1dd23f 21"git daemon [--verbose] [--syslog] [--export-all]\n"
62b4698e
ŠN
22" [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
23" [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
24" [--user-path | --user-path=<path>]\n"
25" [--interpolated-path=<path>]\n"
26" [--reuseaddr] [--detach] [--pid-file=<file>]\n"
27" [--(enable|disable|allow-override|forbid-override)=<service>]\n"
28" [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
29" [--user=<user> [--group=<group>]]\n"
30" [<directory>...]";
4ae95682
PA
31
32/* List of acceptable pathname prefixes */
96f1e58f
DR
33static char **ok_paths;
34static int strict_paths;
4ae95682
PA
35
36/* If this is set, git-daemon-export-ok is not required */
96f1e58f 37static int export_all_trees;
f8ff0c06 38
b21c31c9 39/* Take all paths relative to this one if non-NULL */
96f1e58f 40static char *base_path;
49ba83fb 41static char *interpolated_path;
73a7a656 42static int base_path_relaxed;
49ba83fb
JL
43
44/* Flag indicating client sent extra args. */
45static int saw_extended_args;
b21c31c9 46
603968d2
JH
47/* If defined, ~user notation is allowed and the string is inserted
48 * after ~user/. E.g. a request to git://host/~alice/frotz would
49 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
50 */
96f1e58f 51static const char *user_path;
603968d2 52
960deccb 53/* Timeout, and initial timeout */
96f1e58f
DR
54static unsigned int timeout;
55static unsigned int init_timeout;
f8ff0c06 56
9d7ca667
RS
57static char *hostname;
58static char *canon_hostname;
59static char *ip_address;
60static char *tcp_port;
49ba83fb 61
9048fe1c 62static void logreport(int priority, const char *err, va_list params)
f8ff0c06 63{
9048fe1c 64 if (log_syslog) {
6a992e9e
SB
65 char buf[1024];
66 vsnprintf(buf, sizeof(buf), err, params);
9048fe1c 67 syslog(priority, "%s", buf);
460c2010
JH
68 } else {
69 /*
70 * Since stderr is set to linebuffered mode, the
6a992e9e
SB
71 * logging of different processes will not overlap
72 */
85e72830 73 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
6a992e9e
SB
74 vfprintf(stderr, err, params);
75 fputc('\n', stderr);
76 }
f8ff0c06
PB
77}
78
28bea9e5 79__attribute__((format (printf, 1, 2)))
cdda4745 80static void logerror(const char *err, ...)
f8ff0c06
PB
81{
82 va_list params;
83 va_start(params, err);
9048fe1c 84 logreport(LOG_ERR, err, params);
f8ff0c06
PB
85 va_end(params);
86}
87
28bea9e5 88__attribute__((format (printf, 1, 2)))
cdda4745 89static void loginfo(const char *err, ...)
f8ff0c06
PB
90{
91 va_list params;
92 if (!verbose)
93 return;
94 va_start(params, err);
9048fe1c 95 logreport(LOG_INFO, err, params);
f8ff0c06
PB
96 va_end(params);
97}
a87e8be2 98
ad8b4f56
ML
99static void NORETURN daemon_die(const char *err, va_list params)
100{
101 logreport(LOG_ERR, err, params);
102 exit(1);
103}
104
a47551c3 105static char *path_ok(char *directory)
4ae95682 106{
603968d2 107 static char rpath[PATH_MAX];
49ba83fb 108 static char interp_path[PATH_MAX];
d79374c7 109 char *path;
49ba83fb
JL
110 char *dir;
111
9d7ca667 112 dir = directory;
d79374c7 113
34b6cb8b 114 if (daemon_avoid_alias(dir)) {
d79374c7
JH
115 logerror("'%s': aliased", dir);
116 return NULL;
117 }
118
603968d2
JH
119 if (*dir == '~') {
120 if (!user_path) {
121 logerror("'%s': User-path not allowed", dir);
122 return NULL;
123 }
124 if (*user_path) {
125 /* Got either "~alice" or "~alice/foo";
126 * rewrite them to "~alice/%s" or
127 * "~alice/%s/foo".
128 */
129 int namlen, restlen = strlen(dir);
130 char *slash = strchr(dir, '/');
131 if (!slash)
132 slash = dir + restlen;
133 namlen = slash - dir;
134 restlen -= namlen;
135 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
136 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
137 namlen, dir, user_path, restlen, slash);
138 dir = rpath;
139 }
140 }
49ba83fb 141 else if (interpolated_path && saw_extended_args) {
9d7ca667 142 struct strbuf expanded_path = STRBUF_INIT;
66dbfd55
GV
143 struct strbuf_expand_dict_entry dict[6];
144
145 dict[0].placeholder = "H"; dict[0].value = hostname;
146 dict[1].placeholder = "CH"; dict[1].value = canon_hostname;
147 dict[2].placeholder = "IP"; dict[2].value = ip_address;
148 dict[3].placeholder = "P"; dict[3].value = tcp_port;
149 dict[4].placeholder = "D"; dict[4].value = directory;
150 dict[5].placeholder = NULL; dict[5].value = NULL;
49ba83fb
JL
151 if (*dir != '/') {
152 /* Allow only absolute */
153 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
154 return NULL;
155 }
156
9d7ca667
RS
157 strbuf_expand(&expanded_path, interpolated_path,
158 strbuf_expand_dict_cb, &dict);
159 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
160 strbuf_release(&expanded_path);
49ba83fb
JL
161 loginfo("Interpolated dir '%s'", interp_path);
162
163 dir = interp_path;
164 }
603968d2
JH
165 else if (base_path) {
166 if (*dir != '/') {
167 /* Allow only absolute */
1fda3d55 168 logerror("'%s': Non-absolute path denied (base-path active)", dir);
b21c31c9
PB
169 return NULL;
170 }
49ba83fb
JL
171 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
172 dir = rpath;
b21c31c9
PB
173 }
174
a583971f
RS
175 path = enter_repo(dir, strict_paths);
176 if (!path && base_path && base_path_relaxed) {
73a7a656
JA
177 /*
178 * if we fail and base_path_relaxed is enabled, try without
179 * prefixing the base path
180 */
a583971f
RS
181 dir = directory;
182 path = enter_repo(dir, strict_paths);
183 }
3e04c62d 184
4dbd1352 185 if (!path) {
05ac6b34 186 logerror("'%s' does not appear to be a git repository", dir);
4dbd1352 187 return NULL;
4ae95682
PA
188 }
189
190 if ( ok_paths && *ok_paths ) {
ce335fe0 191 char **pp;
4dbd1352 192 int pathlen = strlen(path);
4ae95682 193
ce335fe0 194 /* The validation is done on the paths after enter_repo
a6080a0a 195 * appends optional {.git,.git/.git} and friends, but
d79374c7
JH
196 * it does not use getcwd(). So if your /pub is
197 * a symlink to /mnt/pub, you can whitelist /pub and
198 * do not have to say /mnt/pub.
199 * Do not say /pub/.
ce335fe0 200 */
4ae95682
PA
201 for ( pp = ok_paths ; *pp ; pp++ ) {
202 int len = strlen(*pp);
ce335fe0
JH
203 if (len <= pathlen &&
204 !memcmp(*pp, path, len) &&
205 (path[len] == '\0' ||
206 (!strict_paths && path[len] == '/')))
207 return path;
4ae95682 208 }
4dbd1352
AE
209 }
210 else {
211 /* be backwards compatible */
212 if (!strict_paths)
213 return path;
4ae95682
PA
214 }
215
4dbd1352
AE
216 logerror("'%s': not in whitelist", path);
217 return NULL; /* Fallthrough. Deny by default */
4ae95682 218}
a87e8be2 219
d819e4e6
JH
220typedef int (*daemon_service_fn)(void);
221struct daemon_service {
222 const char *name;
223 const char *config_name;
224 daemon_service_fn fn;
225 int enabled;
226 int overridable;
227};
228
229static struct daemon_service *service_looking_at;
230static int service_enabled;
231
ef90d6d4 232static int git_daemon_config(const char *var, const char *value, void *cb)
d819e4e6 233{
cc44c765 234 if (!prefixcmp(var, "daemon.") &&
d819e4e6
JH
235 !strcmp(var + 7, service_looking_at->config_name)) {
236 service_enabled = git_config_bool(var, value);
237 return 0;
238 }
239
240 /* we are not interested in parsing any other configuration here */
241 return 0;
242}
243
a47551c3 244static int run_service(char *dir, struct daemon_service *service)
a87e8be2 245{
4dbd1352 246 const char *path;
d819e4e6
JH
247 int enabled = service->enabled;
248
a47551c3 249 loginfo("Request %s for '%s'", service->name, dir);
4dbd1352 250
d819e4e6
JH
251 if (!enabled && !service->overridable) {
252 logerror("'%s': service not enabled.", service->name);
253 errno = EACCES;
254 return -1;
255 }
4ae95682 256
a47551c3 257 if (!(path = path_ok(dir)))
a87e8be2 258 return -1;
47888f0f 259
a87e8be2
LT
260 /*
261 * Security on the cheap.
262 *
a935c397 263 * We want a readable HEAD, usable "objects" directory, and
a87e8be2
LT
264 * a "git-daemon-export-ok" flag that says that the other side
265 * is ok with us doing this.
4dbd1352
AE
266 *
267 * path_ok() uses enter_repo() and does whitelist checking.
268 * We only need to make sure the repository is exported.
a87e8be2 269 */
4dbd1352 270
3e04c62d 271 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
4dbd1352 272 logerror("'%s': repository not exported.", path);
3e04c62d
PA
273 errno = EACCES;
274 return -1;
275 }
276
d819e4e6
JH
277 if (service->overridable) {
278 service_looking_at = service;
279 service_enabled = -1;
ef90d6d4 280 git_config(git_daemon_config, NULL);
d819e4e6
JH
281 if (0 <= service_enabled)
282 enabled = service_enabled;
283 }
284 if (!enabled) {
285 logerror("'%s': service not enabled for '%s'",
286 service->name, path);
287 errno = EACCES;
288 return -1;
289 }
290
02d57da4
LT
291 /*
292 * We'll ignore SIGTERM from now on, we have a
293 * good client.
294 */
295 signal(SIGTERM, SIG_IGN);
296
d819e4e6
JH
297 return service->fn();
298}
299
5d87dd4f
JS
300static void copy_to_log(int fd)
301{
302 struct strbuf line = STRBUF_INIT;
303 FILE *fp;
304
305 fp = fdopen(fd, "r");
306 if (fp == NULL) {
307 logerror("fdopen of error channel failed");
308 close(fd);
309 return;
310 }
311
312 while (strbuf_getline(&line, fp, '\n') != EOF) {
313 logerror("%s", line.buf);
314 strbuf_setlen(&line, 0);
315 }
316
317 strbuf_release(&line);
318 fclose(fp);
319}
320
321static int run_service_command(const char **argv)
322{
323 struct child_process cld;
324
325 memset(&cld, 0, sizeof(cld));
326 cld.argv = argv;
327 cld.git_cmd = 1;
328 cld.err = -1;
329 if (start_command(&cld))
330 return -1;
331
332 close(0);
333 close(1);
334
335 copy_to_log(cld.err);
336
337 return finish_command(&cld);
338}
339
d819e4e6
JH
340static int upload_pack(void)
341{
342 /* Timeout as string */
343 char timeout_buf[64];
66dbfd55
GV
344 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
345
346 argv[2] = timeout_buf;
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;
30e15602 617 struct child_process cld;
df076bdb 618 struct sockaddr_storage address;
3bd62c21 619} *firstborn;
66e631de 620
30e15602 621static void add_child(struct child_process *cld, 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++;
30e15602 627 memcpy(&newborn->cld, cld, sizeof(*cld));
460c2010
JH
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
66e631de
LT
636/*
637 * This gets called if the number of connections grows
638 * past "max_connections".
639 *
3bd62c21 640 * We kill the newest connection from a duplicate IP.
66e631de 641 */
3bd62c21 642static void kill_some_child(void)
66e631de 643{
460c2010 644 const struct child *blanket, *next;
66e631de 645
460c2010
JH
646 if (!(blanket = firstborn))
647 return;
695605b5 648
460c2010 649 for (; (next = blanket->next); blanket = next)
15515b73 650 if (!addrcmp(&blanket->address, &next->address)) {
30e15602 651 kill(blanket->cld.pid, SIGTERM);
460c2010
JH
652 break;
653 }
a5a9126b
JS
654}
655
3bd62c21 656static void check_dead_children(void)
a87e8be2 657{
3bd62c21
SB
658 int status;
659 pid_t pid;
02d57da4 660
30e15602
EFL
661 struct child **cradle, *blanket;
662 for (cradle = &firstborn; (blanket = *cradle);)
663 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
664 const char *dead = "";
665 if (status)
666 dead = " (with error)";
667 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
668
669 /* remove the child */
670 *cradle = blanket->next;
671 live_children--;
672 free(blanket);
673 } else
674 cradle = &blanket->next;
02d57da4
LT
675}
676
30e15602 677static char **cld_argv;
7fa09084 678static void handle(int incoming, struct sockaddr *addr, int addrlen)
02d57da4 679{
30e15602 680 struct child_process cld = { 0 };
02d57da4 681
3bd62c21
SB
682 if (max_connections && live_children >= max_connections) {
683 kill_some_child();
460c2010 684 sleep(1); /* give it some time to die */
3bd62c21
SB
685 check_dead_children();
686 if (live_children >= max_connections) {
687 close(incoming);
688 logerror("Too many children, dropping connection");
689 return;
690 }
691 }
02d57da4 692
30e15602
EFL
693 cld.argv = (const char **)cld_argv;
694 cld.in = incoming;
695 cld.out = dup(incoming);
a87e8be2 696
30e15602
EFL
697 if (start_command(&cld))
698 logerror("unable to fork");
699 else
700 add_child(&cld, addr, addrlen);
a87e8be2 701 close(incoming);
a87e8be2
LT
702}
703
eaa94919
LT
704static void child_handler(int signo)
705{
460c2010
JH
706 /*
707 * Otherwise empty handler because systemcalls will get interrupted
695605b5
SB
708 * upon signal receipt
709 * SysV needs the handler to be rearmed
710 */
bd7b371e 711 signal(SIGCHLD, child_handler);
eaa94919
LT
712}
713
1955fabf
MW
714static int set_reuse_addr(int sockfd)
715{
716 int on = 1;
717
718 if (!reuseaddr)
719 return 0;
720 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
721 &on, sizeof(on));
722}
723
2caa3215
AS
724struct socketlist {
725 int *list;
726 size_t nr;
727 size_t alloc;
728};
729
6573faff
PA
730#ifndef NO_IPV6
731
2caa3215 732static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
a87e8be2 733{
2caa3215 734 int socknum = 0;
df076bdb 735 int maxfd = -1;
df076bdb 736 char pbuf[NI_MAXSERV];
6573faff
PA
737 struct addrinfo hints, *ai0, *ai;
738 int gai;
20276889 739 long flags;
df076bdb 740
dd467629 741 sprintf(pbuf, "%d", listen_port);
df076bdb
YH
742 memset(&hints, 0, sizeof(hints));
743 hints.ai_family = AF_UNSPEC;
744 hints.ai_socktype = SOCK_STREAM;
745 hints.ai_protocol = IPPROTO_TCP;
746 hints.ai_flags = AI_PASSIVE;
747
dd467629 748 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
2caa3215
AS
749 if (gai) {
750 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
751 return 0;
752 }
df076bdb 753
df076bdb
YH
754 for (ai = ai0; ai; ai = ai->ai_next) {
755 int sockfd;
df076bdb
YH
756
757 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
758 if (sockfd < 0)
759 continue;
760 if (sockfd >= FD_SETSIZE) {
df0daf8a 761 logerror("Socket descriptor too large");
df076bdb
YH
762 close(sockfd);
763 continue;
764 }
765
766#ifdef IPV6_V6ONLY
767 if (ai->ai_family == AF_INET6) {
768 int on = 1;
769 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
770 &on, sizeof(on));
771 /* Note: error is not fatal */
772 }
773#endif
774
1955fabf
MW
775 if (set_reuse_addr(sockfd)) {
776 close(sockfd);
0032d548 777 continue;
1955fabf
MW
778 }
779
df076bdb
YH
780 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
781 close(sockfd);
782 continue; /* not fatal */
783 }
784 if (listen(sockfd, 5) < 0) {
785 close(sockfd);
786 continue; /* not fatal */
787 }
788
20276889
AJ
789 flags = fcntl(sockfd, F_GETFD, 0);
790 if (flags >= 0)
791 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
792
2caa3215
AS
793 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
794 socklist->list[socklist->nr++] = sockfd;
795 socknum++;
df076bdb 796
df076bdb
YH
797 if (maxfd < sockfd)
798 maxfd = sockfd;
799 }
800
801 freeaddrinfo(ai0);
802
6573faff
PA
803 return socknum;
804}
805
806#else /* NO_IPV6 */
807
2caa3215 808static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
6573faff
PA
809{
810 struct sockaddr_in sin;
811 int sockfd;
20276889 812 long flags;
6573faff 813
dd467629
JL
814 memset(&sin, 0, sizeof sin);
815 sin.sin_family = AF_INET;
816 sin.sin_port = htons(listen_port);
817
818 if (listen_addr) {
819 /* Well, host better be an IP address here. */
820 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
821 return 0;
822 } else {
823 sin.sin_addr.s_addr = htonl(INADDR_ANY);
824 }
825
6573faff
PA
826 sockfd = socket(AF_INET, SOCK_STREAM, 0);
827 if (sockfd < 0)
828 return 0;
829
1955fabf
MW
830 if (set_reuse_addr(sockfd)) {
831 close(sockfd);
832 return 0;
833 }
834
6573faff
PA
835 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
836 close(sockfd);
837 return 0;
838 }
a87e8be2 839
f35230fb
PS
840 if (listen(sockfd, 5) < 0) {
841 close(sockfd);
842 return 0;
843 }
844
20276889
AJ
845 flags = fcntl(sockfd, F_GETFD, 0);
846 if (flags >= 0)
847 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
848
2caa3215
AS
849 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
850 socklist->list[socklist->nr++] = sockfd;
f35230fb 851 return 1;
6573faff
PA
852}
853
854#endif
855
3a3a29c1 856static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
2caa3215 857{
3a3a29c1
AS
858 if (!listen_addr->nr)
859 setup_named_sock(NULL, listen_port, socklist);
860 else {
861 int i, socknum;
862 for (i = 0; i < listen_addr->nr; i++) {
863 socknum = setup_named_sock(listen_addr->items[i].string,
864 listen_port, socklist);
865
866 if (socknum == 0)
867 logerror("unable to allocate any listen sockets for host %s on port %u",
868 listen_addr->items[i].string, listen_port);
869 }
870 }
2caa3215
AS
871}
872
873static int service_loop(struct socketlist *socklist)
6573faff
PA
874{
875 struct pollfd *pfd;
876 int i;
877
2caa3215 878 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
6573faff 879
2caa3215
AS
880 for (i = 0; i < socklist->nr; i++) {
881 pfd[i].fd = socklist->list[i];
6573faff
PA
882 pfd[i].events = POLLIN;
883 }
9220282a
PA
884
885 signal(SIGCHLD, child_handler);
a87e8be2
LT
886
887 for (;;) {
df076bdb 888 int i;
6573faff 889
695605b5
SB
890 check_dead_children();
891
2caa3215 892 if (poll(pfd, socklist->nr, -1) < 0) {
1eef0b33 893 if (errno != EINTR) {
df0daf8a 894 logerror("Poll failed, resuming: %s",
1eef0b33
JH
895 strerror(errno));
896 sleep(1);
897 }
df076bdb
YH
898 continue;
899 }
900
2caa3215 901 for (i = 0; i < socklist->nr; i++) {
6573faff 902 if (pfd[i].revents & POLLIN) {
df076bdb 903 struct sockaddr_storage ss;
7626e49e 904 unsigned int sslen = sizeof(ss);
6573faff 905 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
df076bdb
YH
906 if (incoming < 0) {
907 switch (errno) {
908 case EAGAIN:
909 case EINTR:
910 case ECONNABORTED:
911 continue;
912 default:
d824cbba 913 die_errno("accept returned");
df076bdb
YH
914 }
915 }
916 handle(incoming, (struct sockaddr *)&ss, sslen);
a87e8be2
LT
917 }
918 }
a87e8be2
LT
919 }
920}
921
258e93a1
ML
922/* if any standard file descriptor is missing open it to /dev/null */
923static void sanitize_stdfds(void)
924{
925 int fd = open("/dev/null", O_RDWR, 0);
926 while (fd != -1 && fd < 2)
927 fd = dup(fd);
928 if (fd == -1)
d824cbba 929 die_errno("open /dev/null or dup failed");
258e93a1
ML
930 if (fd > 2)
931 close(fd);
932}
933
a5262768
ML
934static void daemonize(void)
935{
936 switch (fork()) {
937 case 0:
938 break;
939 case -1:
d824cbba 940 die_errno("fork failed");
a5262768
ML
941 default:
942 exit(0);
943 }
944 if (setsid() == -1)
d824cbba 945 die_errno("setsid failed");
a5262768
ML
946 close(0);
947 close(1);
948 close(2);
949 sanitize_stdfds();
950}
951
45ed5d7f
ML
952static void store_pid(const char *path)
953{
954 FILE *f = fopen(path, "w");
955 if (!f)
d824cbba 956 die_errno("cannot open pid file '%s'", path);
85e72830 957 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
d824cbba 958 die_errno("failed to write pid file '%s'", path);
45ed5d7f
ML
959}
960
3a3a29c1 961static int serve(struct string_list *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
6573faff 962{
2caa3215 963 struct socketlist socklist = { NULL, 0, 0 };
4ae22d96 964
2caa3215
AS
965 socksetup(listen_addr, listen_port, &socklist);
966 if (socklist.nr == 0)
3a3a29c1
AS
967 die("unable to allocate any listen sockets on port %u",
968 listen_port);
4ae22d96 969
678dac6b
TS
970 if (pass && gid &&
971 (initgroups(pass->pw_name, gid) || setgid (gid) ||
972 setuid(pass->pw_uid)))
973 die("cannot drop privileges");
974
2caa3215 975 return service_loop(&socklist);
4ae22d96 976}
6573faff 977
a87e8be2
LT
978int main(int argc, char **argv)
979{
dd467629 980 int listen_port = 0;
3a3a29c1 981 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
30e15602 982 int serve_mode = 0, inetd_mode = 0;
678dac6b 983 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
a5262768 984 int detach = 0;
678dac6b
TS
985 struct passwd *pass = NULL;
986 struct group *group;
987 gid_t gid = 0;
a87e8be2
LT
988 int i;
989
2fb3f6db
SP
990 git_extract_argv0_path(argv[0]);
991
a87e8be2
LT
992 for (i = 1; i < argc; i++) {
993 char *arg = argv[i];
994
cc44c765 995 if (!prefixcmp(arg, "--listen=")) {
3a3a29c1 996 string_list_append(&listen_addr, xstrdup_tolower(arg + 9));
6720e95b 997 continue;
dd467629 998 }
cc44c765 999 if (!prefixcmp(arg, "--port=")) {
a87e8be2
LT
1000 char *end;
1001 unsigned long n;
1002 n = strtoul(arg+7, &end, 0);
1003 if (arg[7] && !*end) {
dd467629 1004 listen_port = n;
a87e8be2
LT
1005 continue;
1006 }
1007 }
30e15602
EFL
1008 if (!strcmp(arg, "--serve")) {
1009 serve_mode = 1;
1010 continue;
1011 }
e64e1b79
LT
1012 if (!strcmp(arg, "--inetd")) {
1013 inetd_mode = 1;
a8883288 1014 log_syslog = 1;
e64e1b79
LT
1015 continue;
1016 }
f8ff0c06
PB
1017 if (!strcmp(arg, "--verbose")) {
1018 verbose = 1;
1019 continue;
1020 }
9048fe1c
PB
1021 if (!strcmp(arg, "--syslog")) {
1022 log_syslog = 1;
9048fe1c
PB
1023 continue;
1024 }
4ae95682
PA
1025 if (!strcmp(arg, "--export-all")) {
1026 export_all_trees = 1;
1027 continue;
1028 }
cc44c765 1029 if (!prefixcmp(arg, "--timeout=")) {
960deccb 1030 timeout = atoi(arg+10);
a8883288 1031 continue;
960deccb 1032 }
cc44c765 1033 if (!prefixcmp(arg, "--init-timeout=")) {
960deccb 1034 init_timeout = atoi(arg+15);
a8883288 1035 continue;
960deccb 1036 }
3bd62c21
SB
1037 if (!prefixcmp(arg, "--max-connections=")) {
1038 max_connections = atoi(arg+18);
1039 if (max_connections < 0)
1040 max_connections = 0; /* unlimited */
1041 continue;
1042 }
4dbd1352
AE
1043 if (!strcmp(arg, "--strict-paths")) {
1044 strict_paths = 1;
1045 continue;
1046 }
cc44c765 1047 if (!prefixcmp(arg, "--base-path=")) {
b21c31c9
PB
1048 base_path = arg+12;
1049 continue;
1050 }
73a7a656
JA
1051 if (!strcmp(arg, "--base-path-relaxed")) {
1052 base_path_relaxed = 1;
1053 continue;
1054 }
cc44c765 1055 if (!prefixcmp(arg, "--interpolated-path=")) {
49ba83fb
JL
1056 interpolated_path = arg+20;
1057 continue;
1058 }
1955fabf
MW
1059 if (!strcmp(arg, "--reuseaddr")) {
1060 reuseaddr = 1;
1061 continue;
1062 }
603968d2
JH
1063 if (!strcmp(arg, "--user-path")) {
1064 user_path = "";
1065 continue;
1066 }
cc44c765 1067 if (!prefixcmp(arg, "--user-path=")) {
603968d2
JH
1068 user_path = arg + 12;
1069 continue;
1070 }
cc44c765 1071 if (!prefixcmp(arg, "--pid-file=")) {
45ed5d7f
ML
1072 pid_file = arg + 11;
1073 continue;
1074 }
a5262768
ML
1075 if (!strcmp(arg, "--detach")) {
1076 detach = 1;
1077 log_syslog = 1;
1078 continue;
1079 }
cc44c765 1080 if (!prefixcmp(arg, "--user=")) {
678dac6b
TS
1081 user_name = arg + 7;
1082 continue;
1083 }
cc44c765 1084 if (!prefixcmp(arg, "--group=")) {
678dac6b
TS
1085 group_name = arg + 8;
1086 continue;
1087 }
cc44c765 1088 if (!prefixcmp(arg, "--enable=")) {
d819e4e6
JH
1089 enable_service(arg + 9, 1);
1090 continue;
1091 }
cc44c765 1092 if (!prefixcmp(arg, "--disable=")) {
d819e4e6
JH
1093 enable_service(arg + 10, 0);
1094 continue;
1095 }
cc44c765 1096 if (!prefixcmp(arg, "--allow-override=")) {
74c0cc21 1097 make_service_overridable(arg + 17, 1);
d819e4e6
JH
1098 continue;
1099 }
cc44c765 1100 if (!prefixcmp(arg, "--forbid-override=")) {
74c0cc21 1101 make_service_overridable(arg + 18, 0);
d819e4e6
JH
1102 continue;
1103 }
4ae95682
PA
1104 if (!strcmp(arg, "--")) {
1105 ok_paths = &argv[i+1];
1106 break;
1107 } else if (arg[0] != '-') {
1108 ok_paths = &argv[i];
1109 break;
1110 }
e64e1b79 1111
a87e8be2
LT
1112 usage(daemon_usage);
1113 }
1114
22665bba 1115 if (log_syslog) {
6a992e9e 1116 openlog("git-daemon", LOG_PID, LOG_DAEMON);
22665bba 1117 set_die_routine(daemon_die);
460c2010 1118 } else
48196afd
JH
1119 /* avoid splitting a message in the middle */
1120 setvbuf(stderr, NULL, _IOLBF, 0);
22665bba 1121
678dac6b
TS
1122 if (inetd_mode && (group_name || user_name))
1123 die("--user and --group are incompatible with --inetd");
1124
3a3a29c1 1125 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
dd467629
JL
1126 die("--listen= and --port= are incompatible with --inetd");
1127 else if (listen_port == 0)
1128 listen_port = DEFAULT_GIT_PORT;
1129
678dac6b
TS
1130 if (group_name && !user_name)
1131 die("--group supplied without --user");
1132
1133 if (user_name) {
1134 pass = getpwnam(user_name);
1135 if (!pass)
1136 die("user not found - %s", user_name);
1137
1138 if (!group_name)
1139 gid = pass->pw_gid;
1140 else {
1141 group = getgrnam(group_name);
1142 if (!group)
1143 die("group not found - %s", group_name);
1144
1145 gid = group->gr_gid;
1146 }
1147 }
1148
ad8b4f56
ML
1149 if (strict_paths && (!ok_paths || !*ok_paths))
1150 die("option --strict-paths requires a whitelist");
1151
90b4a71c
JH
1152 if (base_path && !is_directory(base_path))
1153 die("base-path '%s' does not exist or is not a directory",
1154 base_path);
20632071 1155
7c3693f1 1156 if (inetd_mode) {
30e15602
EFL
1157 if (!freopen("/dev/null", "w", stderr))
1158 die_errno("failed to redirect stderr to /dev/null");
1159 }
1160
1161 if (inetd_mode || serve_mode) {
5b276ee4
DW
1162 struct sockaddr_storage ss;
1163 struct sockaddr *peer = (struct sockaddr *)&ss;
1164 socklen_t slen = sizeof(ss);
1165
5b276ee4 1166 if (getpeername(0, peer, &slen))
30e15602
EFL
1167 return execute(NULL);
1168 else
1169 return execute(peer);
7c3693f1 1170 }
bce8230d 1171
6a992e9e 1172 if (detach) {
a5262768 1173 daemonize();
6a992e9e
SB
1174 loginfo("Ready to rumble");
1175 }
a5262768
ML
1176 else
1177 sanitize_stdfds();
258e93a1 1178
45ed5d7f
ML
1179 if (pid_file)
1180 store_pid(pid_file);
1181
30e15602
EFL
1182 /* prepare argv for serving-processes */
1183 cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1184 for (i = 0; i < argc; ++i)
1185 cld_argv[i] = argv[i];
1186 cld_argv[argc] = "--serve";
1187 cld_argv[argc+1] = NULL;
1188
3a3a29c1 1189 return serve(&listen_addr, listen_port, pass, gid);
a87e8be2 1190}