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