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