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