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