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