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