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