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