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