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