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