1#include "cache.h"
2#include "pkt-line.h"
3#include "exec_cmd.h"
4#include "interpolate.h"
5
6#include <syslog.h>
7
8#ifndef HOST_NAME_MAX
9#define HOST_NAME_MAX 256
10#endif
11
12#ifndef NI_MAXSERV
13#define NI_MAXSERV 32
14#endif
15
16static int log_syslog;
17static int verbose;
18static int reuseaddr;
19static int child_handler_pipe[2];
20
21static const char daemon_usage[] =
22"git daemon [--verbose] [--syslog] [--export-all]\n"
23" [--timeout=n] [--init-timeout=n] [--strict-paths]\n"
24" [--base-path=path] [--base-path-relaxed]\n"
25" [--user-path | --user-path=path]\n"
26" [--interpolated-path=path]\n"
27" [--reuseaddr] [--detach] [--pid-file=file]\n"
28" [--[enable|disable|allow-override|forbid-override]=service]\n"
29" [--inetd | [--listen=host_or_ipaddr] [--port=n]\n"
30" [--user=user [--group=group]]\n"
31" [directory...]";
32
33/* List of acceptable pathname prefixes */
34static char **ok_paths;
35static int strict_paths;
36
37/* If this is set, git-daemon-export-ok is not required */
38static int export_all_trees;
39
40/* Take all paths relative to this one if non-NULL */
41static char *base_path;
42static char *interpolated_path;
43static int base_path_relaxed;
44
45/* Flag indicating client sent extra args. */
46static int saw_extended_args;
47
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 */
52static const char *user_path;
53
54/* Timeout, and initial timeout */
55static unsigned int timeout;
56static unsigned int init_timeout;
57
58/*
59 * Static table for now. Ugh.
60 * Feel free to make dynamic as needed.
61 */
62#define INTERP_SLOT_HOST (0)
63#define INTERP_SLOT_CANON_HOST (1)
64#define INTERP_SLOT_IP (2)
65#define INTERP_SLOT_PORT (3)
66#define INTERP_SLOT_DIR (4)
67#define INTERP_SLOT_PERCENT (5)
68
69static struct interp interp_table[] = {
70 { "%H", 0},
71 { "%CH", 0},
72 { "%IP", 0},
73 { "%P", 0},
74 { "%D", 0},
75 { "%%", 0},
76};
77
78
79static void logreport(int priority, const char *err, va_list params)
80{
81 /* We should do a single write so that it is atomic and output
82 * of several processes do not get intermingled. */
83 char buf[1024];
84 int buflen;
85 int maxlen, msglen;
86
87 /* sizeof(buf) should be big enough for "[pid] \n" */
88 buflen = snprintf(buf, sizeof(buf), "[%ld] ", (long) getpid());
89
90 maxlen = sizeof(buf) - buflen - 1; /* -1 for our own LF */
91 msglen = vsnprintf(buf + buflen, maxlen, err, params);
92
93 if (log_syslog) {
94 syslog(priority, "%s", buf);
95 return;
96 }
97
98 /* maxlen counted our own LF but also counts space given to
99 * vsnprintf for the terminating NUL. We want to make sure that
100 * we have space for our own LF and NUL after the "meat" of the
101 * message, so truncate it at maxlen - 1.
102 */
103 if (msglen > maxlen - 1)
104 msglen = maxlen - 1;
105 else if (msglen < 0)
106 msglen = 0; /* Protect against weird return values. */
107 buflen += msglen;
108
109 buf[buflen++] = '\n';
110 buf[buflen] = '\0';
111
112 write_in_full(2, buf, buflen);
113}
114
115static void logerror(const char *err, ...)
116{
117 va_list params;
118 va_start(params, err);
119 logreport(LOG_ERR, err, params);
120 va_end(params);
121}
122
123static void loginfo(const char *err, ...)
124{
125 va_list params;
126 if (!verbose)
127 return;
128 va_start(params, err);
129 logreport(LOG_INFO, err, params);
130 va_end(params);
131}
132
133static void NORETURN daemon_die(const char *err, va_list params)
134{
135 logreport(LOG_ERR, err, params);
136 exit(1);
137}
138
139static int avoid_alias(char *p)
140{
141 int sl, ndot;
142
143 /*
144 * This resurrects the belts and suspenders paranoia check by HPA
145 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
146 * does not do getcwd() based path canonicalizations.
147 *
148 * sl becomes true immediately after seeing '/' and continues to
149 * be true as long as dots continue after that without intervening
150 * non-dot character.
151 */
152 if (!p || (*p != '/' && *p != '~'))
153 return -1;
154 sl = 1; ndot = 0;
155 p++;
156
157 while (1) {
158 char ch = *p++;
159 if (sl) {
160 if (ch == '.')
161 ndot++;
162 else if (ch == '/') {
163 if (ndot < 3)
164 /* reject //, /./ and /../ */
165 return -1;
166 ndot = 0;
167 }
168 else if (ch == 0) {
169 if (0 < ndot && ndot < 3)
170 /* reject /.$ and /..$ */
171 return -1;
172 return 0;
173 }
174 else
175 sl = ndot = 0;
176 }
177 else if (ch == 0)
178 return 0;
179 else if (ch == '/') {
180 sl = 1;
181 ndot = 0;
182 }
183 }
184}
185
186static char *path_ok(struct interp *itable)
187{
188 static char rpath[PATH_MAX];
189 static char interp_path[PATH_MAX];
190 int retried_path = 0;
191 char *path;
192 char *dir;
193
194 dir = itable[INTERP_SLOT_DIR].value;
195
196 if (avoid_alias(dir)) {
197 logerror("'%s': aliased", dir);
198 return NULL;
199 }
200
201 if (*dir == '~') {
202 if (!user_path) {
203 logerror("'%s': User-path not allowed", dir);
204 return NULL;
205 }
206 if (*user_path) {
207 /* Got either "~alice" or "~alice/foo";
208 * rewrite them to "~alice/%s" or
209 * "~alice/%s/foo".
210 */
211 int namlen, restlen = strlen(dir);
212 char *slash = strchr(dir, '/');
213 if (!slash)
214 slash = dir + restlen;
215 namlen = slash - dir;
216 restlen -= namlen;
217 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
218 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
219 namlen, dir, user_path, restlen, slash);
220 dir = rpath;
221 }
222 }
223 else if (interpolated_path && saw_extended_args) {
224 if (*dir != '/') {
225 /* Allow only absolute */
226 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
227 return NULL;
228 }
229
230 interpolate(interp_path, PATH_MAX, interpolated_path,
231 interp_table, ARRAY_SIZE(interp_table));
232 loginfo("Interpolated dir '%s'", interp_path);
233
234 dir = interp_path;
235 }
236 else if (base_path) {
237 if (*dir != '/') {
238 /* Allow only absolute */
239 logerror("'%s': Non-absolute path denied (base-path active)", dir);
240 return NULL;
241 }
242 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
243 dir = rpath;
244 }
245
246 do {
247 path = enter_repo(dir, strict_paths);
248 if (path)
249 break;
250
251 /*
252 * if we fail and base_path_relaxed is enabled, try without
253 * prefixing the base path
254 */
255 if (base_path && base_path_relaxed && !retried_path) {
256 dir = itable[INTERP_SLOT_DIR].value;
257 retried_path = 1;
258 continue;
259 }
260 break;
261 } while (1);
262
263 if (!path) {
264 logerror("'%s': unable to chdir or not a git archive", dir);
265 return NULL;
266 }
267
268 if ( ok_paths && *ok_paths ) {
269 char **pp;
270 int pathlen = strlen(path);
271
272 /* The validation is done on the paths after enter_repo
273 * appends optional {.git,.git/.git} and friends, but
274 * it does not use getcwd(). So if your /pub is
275 * a symlink to /mnt/pub, you can whitelist /pub and
276 * do not have to say /mnt/pub.
277 * Do not say /pub/.
278 */
279 for ( pp = ok_paths ; *pp ; pp++ ) {
280 int len = strlen(*pp);
281 if (len <= pathlen &&
282 !memcmp(*pp, path, len) &&
283 (path[len] == '\0' ||
284 (!strict_paths && path[len] == '/')))
285 return path;
286 }
287 }
288 else {
289 /* be backwards compatible */
290 if (!strict_paths)
291 return path;
292 }
293
294 logerror("'%s': not in whitelist", path);
295 return NULL; /* Fallthrough. Deny by default */
296}
297
298typedef int (*daemon_service_fn)(void);
299struct daemon_service {
300 const char *name;
301 const char *config_name;
302 daemon_service_fn fn;
303 int enabled;
304 int overridable;
305};
306
307static struct daemon_service *service_looking_at;
308static int service_enabled;
309
310static int git_daemon_config(const char *var, const char *value, void *cb)
311{
312 if (!prefixcmp(var, "daemon.") &&
313 !strcmp(var + 7, service_looking_at->config_name)) {
314 service_enabled = git_config_bool(var, value);
315 return 0;
316 }
317
318 /* we are not interested in parsing any other configuration here */
319 return 0;
320}
321
322static int run_service(struct interp *itable, struct daemon_service *service)
323{
324 const char *path;
325 int enabled = service->enabled;
326
327 loginfo("Request %s for '%s'",
328 service->name,
329 itable[INTERP_SLOT_DIR].value);
330
331 if (!enabled && !service->overridable) {
332 logerror("'%s': service not enabled.", service->name);
333 errno = EACCES;
334 return -1;
335 }
336
337 if (!(path = path_ok(itable)))
338 return -1;
339
340 /*
341 * Security on the cheap.
342 *
343 * We want a readable HEAD, usable "objects" directory, and
344 * a "git-daemon-export-ok" flag that says that the other side
345 * is ok with us doing this.
346 *
347 * path_ok() uses enter_repo() and does whitelist checking.
348 * We only need to make sure the repository is exported.
349 */
350
351 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
352 logerror("'%s': repository not exported.", path);
353 errno = EACCES;
354 return -1;
355 }
356
357 if (service->overridable) {
358 service_looking_at = service;
359 service_enabled = -1;
360 git_config(git_daemon_config, NULL);
361 if (0 <= service_enabled)
362 enabled = service_enabled;
363 }
364 if (!enabled) {
365 logerror("'%s': service not enabled for '%s'",
366 service->name, path);
367 errno = EACCES;
368 return -1;
369 }
370
371 /*
372 * We'll ignore SIGTERM from now on, we have a
373 * good client.
374 */
375 signal(SIGTERM, SIG_IGN);
376
377 return service->fn();
378}
379
380static int upload_pack(void)
381{
382 /* Timeout as string */
383 char timeout_buf[64];
384
385 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
386
387 /* git-upload-pack only ever reads stuff, so this is safe */
388 execl_git_cmd("upload-pack", "--strict", timeout_buf, ".", NULL);
389 return -1;
390}
391
392static int upload_archive(void)
393{
394 execl_git_cmd("upload-archive", ".", NULL);
395 return -1;
396}
397
398static int receive_pack(void)
399{
400 execl_git_cmd("receive-pack", ".", NULL);
401 return -1;
402}
403
404static struct daemon_service daemon_service[] = {
405 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
406 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
407 { "receive-pack", "receivepack", receive_pack, 0, 1 },
408};
409
410static void enable_service(const char *name, int ena)
411{
412 int i;
413 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
414 if (!strcmp(daemon_service[i].name, name)) {
415 daemon_service[i].enabled = ena;
416 return;
417 }
418 }
419 die("No such service %s", name);
420}
421
422static void make_service_overridable(const char *name, int ena)
423{
424 int i;
425 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
426 if (!strcmp(daemon_service[i].name, name)) {
427 daemon_service[i].overridable = ena;
428 return;
429 }
430 }
431 die("No such service %s", name);
432}
433
434/*
435 * Separate the "extra args" information as supplied by the client connection.
436 * Any resulting data is squirreled away in the given interpolation table.
437 */
438static void parse_extra_args(struct interp *table, char *extra_args, int buflen)
439{
440 char *val;
441 int vallen;
442 char *end = extra_args + buflen;
443
444 while (extra_args < end && *extra_args) {
445 saw_extended_args = 1;
446 if (strncasecmp("host=", extra_args, 5) == 0) {
447 val = extra_args + 5;
448 vallen = strlen(val) + 1;
449 if (*val) {
450 /* Split <host>:<port> at colon. */
451 char *host = val;
452 char *port = strrchr(host, ':');
453 if (port) {
454 *port = 0;
455 port++;
456 interp_set_entry(table, INTERP_SLOT_PORT, port);
457 }
458 interp_set_entry(table, INTERP_SLOT_HOST, host);
459 }
460
461 /* On to the next one */
462 extra_args = val + vallen;
463 }
464 }
465}
466
467static void fill_in_extra_table_entries(struct interp *itable)
468{
469 char *hp;
470
471 /*
472 * Replace literal host with lowercase-ized hostname.
473 */
474 hp = interp_table[INTERP_SLOT_HOST].value;
475 if (!hp)
476 return;
477 for ( ; *hp; hp++)
478 *hp = tolower(*hp);
479
480 /*
481 * Locate canonical hostname and its IP address.
482 */
483#ifndef NO_IPV6
484 {
485 struct addrinfo hints;
486 struct addrinfo *ai, *ai0;
487 int gai;
488 static char addrbuf[HOST_NAME_MAX + 1];
489
490 memset(&hints, 0, sizeof(hints));
491 hints.ai_flags = AI_CANONNAME;
492
493 gai = getaddrinfo(interp_table[INTERP_SLOT_HOST].value, 0, &hints, &ai0);
494 if (!gai) {
495 for (ai = ai0; ai; ai = ai->ai_next) {
496 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
497
498 inet_ntop(AF_INET, &sin_addr->sin_addr,
499 addrbuf, sizeof(addrbuf));
500 interp_set_entry(interp_table,
501 INTERP_SLOT_CANON_HOST, ai->ai_canonname);
502 interp_set_entry(interp_table,
503 INTERP_SLOT_IP, addrbuf);
504 break;
505 }
506 freeaddrinfo(ai0);
507 }
508 }
509#else
510 {
511 struct hostent *hent;
512 struct sockaddr_in sa;
513 char **ap;
514 static char addrbuf[HOST_NAME_MAX + 1];
515
516 hent = gethostbyname(interp_table[INTERP_SLOT_HOST].value);
517
518 ap = hent->h_addr_list;
519 memset(&sa, 0, sizeof sa);
520 sa.sin_family = hent->h_addrtype;
521 sa.sin_port = htons(0);
522 memcpy(&sa.sin_addr, *ap, hent->h_length);
523
524 inet_ntop(hent->h_addrtype, &sa.sin_addr,
525 addrbuf, sizeof(addrbuf));
526
527 interp_set_entry(interp_table, INTERP_SLOT_CANON_HOST, hent->h_name);
528 interp_set_entry(interp_table, INTERP_SLOT_IP, addrbuf);
529 }
530#endif
531}
532
533
534static int execute(struct sockaddr *addr)
535{
536 static char line[1000];
537 int pktlen, len, i;
538
539 if (addr) {
540 char addrbuf[256] = "";
541 int port = -1;
542
543 if (addr->sa_family == AF_INET) {
544 struct sockaddr_in *sin_addr = (void *) addr;
545 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
546 port = ntohs(sin_addr->sin_port);
547#ifndef NO_IPV6
548 } else if (addr && addr->sa_family == AF_INET6) {
549 struct sockaddr_in6 *sin6_addr = (void *) addr;
550
551 char *buf = addrbuf;
552 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
553 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
554 strcat(buf, "]");
555
556 port = ntohs(sin6_addr->sin6_port);
557#endif
558 }
559 loginfo("Connection from %s:%d", addrbuf, port);
560 }
561
562 alarm(init_timeout ? init_timeout : timeout);
563 pktlen = packet_read_line(0, line, sizeof(line));
564 alarm(0);
565
566 len = strlen(line);
567 if (pktlen != len)
568 loginfo("Extended attributes (%d bytes) exist <%.*s>",
569 (int) pktlen - len,
570 (int) pktlen - len, line + len + 1);
571 if (len && line[len-1] == '\n') {
572 line[--len] = 0;
573 pktlen--;
574 }
575
576 /*
577 * Initialize the path interpolation table for this connection.
578 */
579 interp_clear_table(interp_table, ARRAY_SIZE(interp_table));
580 interp_set_entry(interp_table, INTERP_SLOT_PERCENT, "%");
581
582 if (len != pktlen) {
583 parse_extra_args(interp_table, line + len + 1, pktlen - len - 1);
584 fill_in_extra_table_entries(interp_table);
585 }
586
587 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
588 struct daemon_service *s = &(daemon_service[i]);
589 int namelen = strlen(s->name);
590 if (!prefixcmp(line, "git-") &&
591 !strncmp(s->name, line + 4, namelen) &&
592 line[namelen + 4] == ' ') {
593 /*
594 * Note: The directory here is probably context sensitive,
595 * and might depend on the actual service being performed.
596 */
597 interp_set_entry(interp_table,
598 INTERP_SLOT_DIR, line + namelen + 5);
599 return run_service(interp_table, s);
600 }
601 }
602
603 logerror("Protocol error: '%s'", line);
604 return -1;
605}
606
607
608/*
609 * We count spawned/reaped separately, just to avoid any
610 * races when updating them from signals. The SIGCHLD handler
611 * will only update children_reaped, and the fork logic will
612 * only update children_spawned.
613 *
614 * MAX_CHILDREN should be a power-of-two to make the modulus
615 * operation cheap. It should also be at least twice
616 * the maximum number of connections we will ever allow.
617 */
618#define MAX_CHILDREN 128
619
620static int max_connections = 25;
621
622/* These are updated by the signal handler */
623static volatile unsigned int children_reaped;
624static pid_t dead_child[MAX_CHILDREN];
625
626/* These are updated by the main loop */
627static unsigned int children_spawned;
628static unsigned int children_deleted;
629
630static struct child {
631 pid_t pid;
632 int addrlen;
633 struct sockaddr_storage address;
634} live_child[MAX_CHILDREN];
635
636static void add_child(int idx, pid_t pid, struct sockaddr *addr, int addrlen)
637{
638 live_child[idx].pid = pid;
639 live_child[idx].addrlen = addrlen;
640 memcpy(&live_child[idx].address, addr, addrlen);
641}
642
643/*
644 * Walk from "deleted" to "spawned", and remove child "pid".
645 *
646 * We move everything up by one, since the new "deleted" will
647 * be one higher.
648 */
649static void remove_child(pid_t pid, unsigned deleted, unsigned spawned)
650{
651 struct child n;
652
653 deleted %= MAX_CHILDREN;
654 spawned %= MAX_CHILDREN;
655 if (live_child[deleted].pid == pid) {
656 live_child[deleted].pid = -1;
657 return;
658 }
659 n = live_child[deleted];
660 for (;;) {
661 struct child m;
662 deleted = (deleted + 1) % MAX_CHILDREN;
663 if (deleted == spawned)
664 die("could not find dead child %d\n", pid);
665 m = live_child[deleted];
666 live_child[deleted] = n;
667 if (m.pid == pid)
668 return;
669 n = m;
670 }
671}
672
673/*
674 * This gets called if the number of connections grows
675 * past "max_connections".
676 *
677 * We _should_ start off by searching for connections
678 * from the same IP, and if there is some address wth
679 * multiple connections, we should kill that first.
680 *
681 * As it is, we just "randomly" kill 25% of the connections,
682 * and our pseudo-random generator sucks too. I have no
683 * shame.
684 *
685 * Really, this is just a place-holder for a _real_ algorithm.
686 */
687static void kill_some_children(int signo, unsigned start, unsigned stop)
688{
689 start %= MAX_CHILDREN;
690 stop %= MAX_CHILDREN;
691 while (start != stop) {
692 if (!(start & 3))
693 kill(live_child[start].pid, signo);
694 start = (start + 1) % MAX_CHILDREN;
695 }
696}
697
698static void check_dead_children(void)
699{
700 unsigned spawned, reaped, deleted;
701
702 spawned = children_spawned;
703 reaped = children_reaped;
704 deleted = children_deleted;
705
706 while (deleted < reaped) {
707 pid_t pid = dead_child[deleted % MAX_CHILDREN];
708 const char *dead = pid < 0 ? " (with error)" : "";
709
710 if (pid < 0)
711 pid = -pid;
712
713 /* XXX: Custom logging, since we don't wanna getpid() */
714 if (verbose) {
715 if (log_syslog)
716 syslog(LOG_INFO, "[%d] Disconnected%s",
717 pid, dead);
718 else
719 fprintf(stderr, "[%d] Disconnected%s\n",
720 pid, dead);
721 }
722 remove_child(pid, deleted, spawned);
723 deleted++;
724 }
725 children_deleted = deleted;
726}
727
728static void check_max_connections(void)
729{
730 for (;;) {
731 int active;
732 unsigned spawned, deleted;
733
734 check_dead_children();
735
736 spawned = children_spawned;
737 deleted = children_deleted;
738
739 active = spawned - deleted;
740 if (active <= max_connections)
741 break;
742
743 /* Kill some unstarted connections with SIGTERM */
744 kill_some_children(SIGTERM, deleted, spawned);
745 if (active <= max_connections << 1)
746 break;
747
748 /* If the SIGTERM thing isn't helping use SIGKILL */
749 kill_some_children(SIGKILL, deleted, spawned);
750 sleep(1);
751 }
752}
753
754static void handle(int incoming, struct sockaddr *addr, int addrlen)
755{
756 pid_t pid = fork();
757
758 if (pid) {
759 unsigned idx;
760
761 close(incoming);
762 if (pid < 0)
763 return;
764
765 idx = children_spawned % MAX_CHILDREN;
766 children_spawned++;
767 add_child(idx, pid, addr, addrlen);
768
769 check_max_connections();
770 return;
771 }
772
773 dup2(incoming, 0);
774 dup2(incoming, 1);
775 close(incoming);
776
777 exit(execute(addr));
778}
779
780static void child_handler(int signo)
781{
782 for (;;) {
783 int status;
784 pid_t pid = waitpid(-1, &status, WNOHANG);
785
786 if (pid > 0) {
787 unsigned reaped = children_reaped;
788 if (!WIFEXITED(status) || WEXITSTATUS(status) > 0)
789 pid = -pid;
790 dead_child[reaped % MAX_CHILDREN] = pid;
791 children_reaped = reaped + 1;
792 write(child_handler_pipe[1], &status, 1);
793 continue;
794 }
795 break;
796 }
797}
798
799static int set_reuse_addr(int sockfd)
800{
801 int on = 1;
802
803 if (!reuseaddr)
804 return 0;
805 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
806 &on, sizeof(on));
807}
808
809#ifndef NO_IPV6
810
811static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
812{
813 int socknum = 0, *socklist = NULL;
814 int maxfd = -1;
815 char pbuf[NI_MAXSERV];
816 struct addrinfo hints, *ai0, *ai;
817 int gai;
818 long flags;
819
820 sprintf(pbuf, "%d", listen_port);
821 memset(&hints, 0, sizeof(hints));
822 hints.ai_family = AF_UNSPEC;
823 hints.ai_socktype = SOCK_STREAM;
824 hints.ai_protocol = IPPROTO_TCP;
825 hints.ai_flags = AI_PASSIVE;
826
827 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
828 if (gai)
829 die("getaddrinfo() failed: %s\n", gai_strerror(gai));
830
831 for (ai = ai0; ai; ai = ai->ai_next) {
832 int sockfd;
833
834 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
835 if (sockfd < 0)
836 continue;
837 if (sockfd >= FD_SETSIZE) {
838 error("too large socket descriptor.");
839 close(sockfd);
840 continue;
841 }
842
843#ifdef IPV6_V6ONLY
844 if (ai->ai_family == AF_INET6) {
845 int on = 1;
846 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
847 &on, sizeof(on));
848 /* Note: error is not fatal */
849 }
850#endif
851
852 if (set_reuse_addr(sockfd)) {
853 close(sockfd);
854 continue;
855 }
856
857 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
858 close(sockfd);
859 continue; /* not fatal */
860 }
861 if (listen(sockfd, 5) < 0) {
862 close(sockfd);
863 continue; /* not fatal */
864 }
865
866 flags = fcntl(sockfd, F_GETFD, 0);
867 if (flags >= 0)
868 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
869
870 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
871 socklist[socknum++] = sockfd;
872
873 if (maxfd < sockfd)
874 maxfd = sockfd;
875 }
876
877 freeaddrinfo(ai0);
878
879 *socklist_p = socklist;
880 return socknum;
881}
882
883#else /* NO_IPV6 */
884
885static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
886{
887 struct sockaddr_in sin;
888 int sockfd;
889 long flags;
890
891 memset(&sin, 0, sizeof sin);
892 sin.sin_family = AF_INET;
893 sin.sin_port = htons(listen_port);
894
895 if (listen_addr) {
896 /* Well, host better be an IP address here. */
897 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
898 return 0;
899 } else {
900 sin.sin_addr.s_addr = htonl(INADDR_ANY);
901 }
902
903 sockfd = socket(AF_INET, SOCK_STREAM, 0);
904 if (sockfd < 0)
905 return 0;
906
907 if (set_reuse_addr(sockfd)) {
908 close(sockfd);
909 return 0;
910 }
911
912 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
913 close(sockfd);
914 return 0;
915 }
916
917 if (listen(sockfd, 5) < 0) {
918 close(sockfd);
919 return 0;
920 }
921
922 flags = fcntl(sockfd, F_GETFD, 0);
923 if (flags >= 0)
924 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
925
926 *socklist_p = xmalloc(sizeof(int));
927 **socklist_p = sockfd;
928 return 1;
929}
930
931#endif
932
933static int service_loop(int socknum, int *socklist)
934{
935 struct pollfd *pfd;
936 int i;
937
938 if (pipe(child_handler_pipe) < 0)
939 die ("Could not set up pipe for child handler");
940
941 pfd = xcalloc(socknum + 1, sizeof(struct pollfd));
942
943 for (i = 0; i < socknum; i++) {
944 pfd[i].fd = socklist[i];
945 pfd[i].events = POLLIN;
946 }
947 pfd[socknum].fd = child_handler_pipe[0];
948 pfd[socknum].events = POLLIN;
949
950 signal(SIGCHLD, child_handler);
951
952 for (;;) {
953 int i;
954
955 if (poll(pfd, socknum + 1, -1) < 0) {
956 if (errno != EINTR) {
957 error("poll failed, resuming: %s",
958 strerror(errno));
959 sleep(1);
960 }
961 continue;
962 }
963 if (pfd[socknum].revents & POLLIN) {
964 read(child_handler_pipe[0], &i, 1);
965 check_dead_children();
966 }
967
968 for (i = 0; i < socknum; i++) {
969 if (pfd[i].revents & POLLIN) {
970 struct sockaddr_storage ss;
971 unsigned int sslen = sizeof(ss);
972 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
973 if (incoming < 0) {
974 switch (errno) {
975 case EAGAIN:
976 case EINTR:
977 case ECONNABORTED:
978 continue;
979 default:
980 die("accept returned %s", strerror(errno));
981 }
982 }
983 handle(incoming, (struct sockaddr *)&ss, sslen);
984 }
985 }
986 }
987}
988
989/* if any standard file descriptor is missing open it to /dev/null */
990static void sanitize_stdfds(void)
991{
992 int fd = open("/dev/null", O_RDWR, 0);
993 while (fd != -1 && fd < 2)
994 fd = dup(fd);
995 if (fd == -1)
996 die("open /dev/null or dup failed: %s", strerror(errno));
997 if (fd > 2)
998 close(fd);
999}
1000
1001static void daemonize(void)
1002{
1003 switch (fork()) {
1004 case 0:
1005 break;
1006 case -1:
1007 die("fork failed: %s", strerror(errno));
1008 default:
1009 exit(0);
1010 }
1011 if (setsid() == -1)
1012 die("setsid failed: %s", strerror(errno));
1013 close(0);
1014 close(1);
1015 close(2);
1016 sanitize_stdfds();
1017}
1018
1019static void store_pid(const char *path)
1020{
1021 FILE *f = fopen(path, "w");
1022 if (!f)
1023 die("cannot open pid file %s: %s", path, strerror(errno));
1024 if (fprintf(f, "%d\n", getpid()) < 0 || fclose(f) != 0)
1025 die("failed to write pid file %s: %s", path, strerror(errno));
1026}
1027
1028static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
1029{
1030 int socknum, *socklist;
1031
1032 socknum = socksetup(listen_addr, listen_port, &socklist);
1033 if (socknum == 0)
1034 die("unable to allocate any listen sockets on host %s port %u",
1035 listen_addr, listen_port);
1036
1037 if (pass && gid &&
1038 (initgroups(pass->pw_name, gid) || setgid (gid) ||
1039 setuid(pass->pw_uid)))
1040 die("cannot drop privileges");
1041
1042 return service_loop(socknum, socklist);
1043}
1044
1045int main(int argc, char **argv)
1046{
1047 int listen_port = 0;
1048 char *listen_addr = NULL;
1049 int inetd_mode = 0;
1050 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1051 int detach = 0;
1052 struct passwd *pass = NULL;
1053 struct group *group;
1054 gid_t gid = 0;
1055 int i;
1056
1057 /* Without this we cannot rely on waitpid() to tell
1058 * what happened to our children.
1059 */
1060 signal(SIGCHLD, SIG_DFL);
1061
1062 for (i = 1; i < argc; i++) {
1063 char *arg = argv[i];
1064
1065 if (!prefixcmp(arg, "--listen=")) {
1066 char *p = arg + 9;
1067 char *ph = listen_addr = xmalloc(strlen(arg + 9) + 1);
1068 while (*p)
1069 *ph++ = tolower(*p++);
1070 *ph = 0;
1071 continue;
1072 }
1073 if (!prefixcmp(arg, "--port=")) {
1074 char *end;
1075 unsigned long n;
1076 n = strtoul(arg+7, &end, 0);
1077 if (arg[7] && !*end) {
1078 listen_port = n;
1079 continue;
1080 }
1081 }
1082 if (!strcmp(arg, "--inetd")) {
1083 inetd_mode = 1;
1084 log_syslog = 1;
1085 continue;
1086 }
1087 if (!strcmp(arg, "--verbose")) {
1088 verbose = 1;
1089 continue;
1090 }
1091 if (!strcmp(arg, "--syslog")) {
1092 log_syslog = 1;
1093 continue;
1094 }
1095 if (!strcmp(arg, "--export-all")) {
1096 export_all_trees = 1;
1097 continue;
1098 }
1099 if (!prefixcmp(arg, "--timeout=")) {
1100 timeout = atoi(arg+10);
1101 continue;
1102 }
1103 if (!prefixcmp(arg, "--init-timeout=")) {
1104 init_timeout = atoi(arg+15);
1105 continue;
1106 }
1107 if (!strcmp(arg, "--strict-paths")) {
1108 strict_paths = 1;
1109 continue;
1110 }
1111 if (!prefixcmp(arg, "--base-path=")) {
1112 base_path = arg+12;
1113 continue;
1114 }
1115 if (!strcmp(arg, "--base-path-relaxed")) {
1116 base_path_relaxed = 1;
1117 continue;
1118 }
1119 if (!prefixcmp(arg, "--interpolated-path=")) {
1120 interpolated_path = arg+20;
1121 continue;
1122 }
1123 if (!strcmp(arg, "--reuseaddr")) {
1124 reuseaddr = 1;
1125 continue;
1126 }
1127 if (!strcmp(arg, "--user-path")) {
1128 user_path = "";
1129 continue;
1130 }
1131 if (!prefixcmp(arg, "--user-path=")) {
1132 user_path = arg + 12;
1133 continue;
1134 }
1135 if (!prefixcmp(arg, "--pid-file=")) {
1136 pid_file = arg + 11;
1137 continue;
1138 }
1139 if (!strcmp(arg, "--detach")) {
1140 detach = 1;
1141 log_syslog = 1;
1142 continue;
1143 }
1144 if (!prefixcmp(arg, "--user=")) {
1145 user_name = arg + 7;
1146 continue;
1147 }
1148 if (!prefixcmp(arg, "--group=")) {
1149 group_name = arg + 8;
1150 continue;
1151 }
1152 if (!prefixcmp(arg, "--enable=")) {
1153 enable_service(arg + 9, 1);
1154 continue;
1155 }
1156 if (!prefixcmp(arg, "--disable=")) {
1157 enable_service(arg + 10, 0);
1158 continue;
1159 }
1160 if (!prefixcmp(arg, "--allow-override=")) {
1161 make_service_overridable(arg + 17, 1);
1162 continue;
1163 }
1164 if (!prefixcmp(arg, "--forbid-override=")) {
1165 make_service_overridable(arg + 18, 0);
1166 continue;
1167 }
1168 if (!strcmp(arg, "--")) {
1169 ok_paths = &argv[i+1];
1170 break;
1171 } else if (arg[0] != '-') {
1172 ok_paths = &argv[i];
1173 break;
1174 }
1175
1176 usage(daemon_usage);
1177 }
1178
1179 if (log_syslog) {
1180 openlog("git-daemon", 0, LOG_DAEMON);
1181 set_die_routine(daemon_die);
1182 }
1183
1184 if (inetd_mode && (group_name || user_name))
1185 die("--user and --group are incompatible with --inetd");
1186
1187 if (inetd_mode && (listen_port || listen_addr))
1188 die("--listen= and --port= are incompatible with --inetd");
1189 else if (listen_port == 0)
1190 listen_port = DEFAULT_GIT_PORT;
1191
1192 if (group_name && !user_name)
1193 die("--group supplied without --user");
1194
1195 if (user_name) {
1196 pass = getpwnam(user_name);
1197 if (!pass)
1198 die("user not found - %s", user_name);
1199
1200 if (!group_name)
1201 gid = pass->pw_gid;
1202 else {
1203 group = getgrnam(group_name);
1204 if (!group)
1205 die("group not found - %s", group_name);
1206
1207 gid = group->gr_gid;
1208 }
1209 }
1210
1211 if (strict_paths && (!ok_paths || !*ok_paths))
1212 die("option --strict-paths requires a whitelist");
1213
1214 if (base_path) {
1215 struct stat st;
1216
1217 if (stat(base_path, &st) || !S_ISDIR(st.st_mode))
1218 die("base-path '%s' does not exist or "
1219 "is not a directory", base_path);
1220 }
1221
1222 if (inetd_mode) {
1223 struct sockaddr_storage ss;
1224 struct sockaddr *peer = (struct sockaddr *)&ss;
1225 socklen_t slen = sizeof(ss);
1226
1227 freopen("/dev/null", "w", stderr);
1228
1229 if (getpeername(0, peer, &slen))
1230 peer = NULL;
1231
1232 return execute(peer);
1233 }
1234
1235 if (detach)
1236 daemonize();
1237 else
1238 sanitize_stdfds();
1239
1240 if (pid_file)
1241 store_pid(pid_file);
1242
1243 return serve(listen_addr, listen_port, pass, gid);
1244}