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