1#include "cache.h"
2#include "pkt-line.h"
3#include "exec_cmd.h"
4#include "run-command.h"
5#include "strbuf.h"
6#include "string-list.h"
7
8#ifndef HOST_NAME_MAX
9#define HOST_NAME_MAX 256
10#endif
11
12#ifdef NO_INITGROUPS
13#define initgroups(x, y) (0) /* nothing */
14#endif
15
16static int log_syslog;
17static int verbose;
18static int reuseaddr;
19static int informative_errors;
20
21static const char daemon_usage[] =
22"git daemon [--verbose] [--syslog] [--export-all]\n"
23" [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
24" [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
25" [--user-path | --user-path=<path>]\n"
26" [--interpolated-path=<path>]\n"
27" [--reuseaddr] [--pid-file=<file>]\n"
28" [--(enable|disable|allow-override|forbid-override)=<service>]\n"
29" [--access-hook=<path>]\n"
30" [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
31" [--detach] [--user=<user> [--group=<group>]]\n"
32" [<directory>...]";
33
34/* List of acceptable pathname prefixes */
35static char **ok_paths;
36static int strict_paths;
37
38/* If this is set, git-daemon-export-ok is not required */
39static int export_all_trees;
40
41/* Take all paths relative to this one if non-NULL */
42static const char *base_path;
43static const char *interpolated_path;
44static int base_path_relaxed;
45
46/* Flag indicating client sent extra args. */
47static int saw_extended_args;
48
49/* If defined, ~user notation is allowed and the string is inserted
50 * after ~user/. E.g. a request to git://host/~alice/frotz would
51 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
52 */
53static const char *user_path;
54
55/* Timeout, and initial timeout */
56static unsigned int timeout;
57static unsigned int init_timeout;
58
59static char *hostname;
60static char *canon_hostname;
61static char *ip_address;
62static char *tcp_port;
63
64static void logreport(int priority, const char *err, va_list params)
65{
66 if (log_syslog) {
67 char buf[1024];
68 vsnprintf(buf, sizeof(buf), err, params);
69 syslog(priority, "%s", buf);
70 } else {
71 /*
72 * Since stderr is set to buffered mode, the
73 * logging of different processes will not overlap
74 * unless they overflow the (rather big) buffers.
75 */
76 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
77 vfprintf(stderr, err, params);
78 fputc('\n', stderr);
79 fflush(stderr);
80 }
81}
82
83__attribute__((format (printf, 1, 2)))
84static void logerror(const char *err, ...)
85{
86 va_list params;
87 va_start(params, err);
88 logreport(LOG_ERR, err, params);
89 va_end(params);
90}
91
92__attribute__((format (printf, 1, 2)))
93static void loginfo(const char *err, ...)
94{
95 va_list params;
96 if (!verbose)
97 return;
98 va_start(params, err);
99 logreport(LOG_INFO, err, params);
100 va_end(params);
101}
102
103static void NORETURN daemon_die(const char *err, va_list params)
104{
105 logreport(LOG_ERR, err, params);
106 exit(1);
107}
108
109static const char *path_ok(const char *directory)
110{
111 static char rpath[PATH_MAX];
112 static char interp_path[PATH_MAX];
113 const char *path;
114 const char *dir;
115
116 dir = directory;
117
118 if (daemon_avoid_alias(dir)) {
119 logerror("'%s': aliased", dir);
120 return NULL;
121 }
122
123 if (*dir == '~') {
124 if (!user_path) {
125 logerror("'%s': User-path not allowed", dir);
126 return NULL;
127 }
128 if (*user_path) {
129 /* Got either "~alice" or "~alice/foo";
130 * rewrite them to "~alice/%s" or
131 * "~alice/%s/foo".
132 */
133 int namlen, restlen = strlen(dir);
134 const char *slash = strchr(dir, '/');
135 if (!slash)
136 slash = dir + restlen;
137 namlen = slash - dir;
138 restlen -= namlen;
139 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
140 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
141 namlen, dir, user_path, restlen, slash);
142 dir = rpath;
143 }
144 }
145 else if (interpolated_path && saw_extended_args) {
146 struct strbuf expanded_path = STRBUF_INIT;
147 struct strbuf_expand_dict_entry dict[6];
148
149 dict[0].placeholder = "H"; dict[0].value = hostname;
150 dict[1].placeholder = "CH"; dict[1].value = canon_hostname;
151 dict[2].placeholder = "IP"; dict[2].value = ip_address;
152 dict[3].placeholder = "P"; dict[3].value = tcp_port;
153 dict[4].placeholder = "D"; dict[4].value = directory;
154 dict[5].placeholder = NULL; dict[5].value = NULL;
155 if (*dir != '/') {
156 /* Allow only absolute */
157 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
158 return NULL;
159 }
160
161 strbuf_expand(&expanded_path, interpolated_path,
162 strbuf_expand_dict_cb, &dict);
163 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
164 strbuf_release(&expanded_path);
165 loginfo("Interpolated dir '%s'", interp_path);
166
167 dir = interp_path;
168 }
169 else if (base_path) {
170 if (*dir != '/') {
171 /* Allow only absolute */
172 logerror("'%s': Non-absolute path denied (base-path active)", dir);
173 return NULL;
174 }
175 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
176 dir = rpath;
177 }
178
179 path = enter_repo(dir, strict_paths);
180 if (!path && base_path && base_path_relaxed) {
181 /*
182 * if we fail and base_path_relaxed is enabled, try without
183 * prefixing the base path
184 */
185 dir = directory;
186 path = enter_repo(dir, strict_paths);
187 }
188
189 if (!path) {
190 logerror("'%s' does not appear to be a git repository", dir);
191 return NULL;
192 }
193
194 if ( ok_paths && *ok_paths ) {
195 char **pp;
196 int pathlen = strlen(path);
197
198 /* The validation is done on the paths after enter_repo
199 * appends optional {.git,.git/.git} and friends, but
200 * it does not use getcwd(). So if your /pub is
201 * a symlink to /mnt/pub, you can whitelist /pub and
202 * do not have to say /mnt/pub.
203 * Do not say /pub/.
204 */
205 for ( pp = ok_paths ; *pp ; pp++ ) {
206 int len = strlen(*pp);
207 if (len <= pathlen &&
208 !memcmp(*pp, path, len) &&
209 (path[len] == '\0' ||
210 (!strict_paths && path[len] == '/')))
211 return path;
212 }
213 }
214 else {
215 /* be backwards compatible */
216 if (!strict_paths)
217 return path;
218 }
219
220 logerror("'%s': not in whitelist", path);
221 return NULL; /* Fallthrough. Deny by default */
222}
223
224typedef int (*daemon_service_fn)(void);
225struct daemon_service {
226 const char *name;
227 const char *config_name;
228 daemon_service_fn fn;
229 int enabled;
230 int overridable;
231};
232
233static int daemon_error(const char *dir, const char *msg)
234{
235 if (!informative_errors)
236 msg = "access denied or repository not exported";
237 packet_write(1, "ERR %s: %s", msg, dir);
238 return -1;
239}
240
241static const char *access_hook;
242
243static int run_access_hook(struct daemon_service *service, const char *dir, const char *path)
244{
245 struct child_process child;
246 struct strbuf buf = STRBUF_INIT;
247 const char *argv[8];
248 const char **arg = argv;
249 char *eol;
250 int seen_errors = 0;
251
252#define STRARG(x) ((x) ? (x) : "")
253 *arg++ = access_hook;
254 *arg++ = service->name;
255 *arg++ = path;
256 *arg++ = STRARG(hostname);
257 *arg++ = STRARG(canon_hostname);
258 *arg++ = STRARG(ip_address);
259 *arg++ = STRARG(tcp_port);
260 *arg = NULL;
261#undef STRARG
262
263 memset(&child, 0, sizeof(child));
264 child.use_shell = 1;
265 child.argv = argv;
266 child.no_stdin = 1;
267 child.no_stderr = 1;
268 child.out = -1;
269 if (start_command(&child)) {
270 logerror("daemon access hook '%s' failed to start",
271 access_hook);
272 goto error_return;
273 }
274 if (strbuf_read(&buf, child.out, 0) < 0) {
275 logerror("failed to read from pipe to daemon access hook '%s'",
276 access_hook);
277 strbuf_reset(&buf);
278 seen_errors = 1;
279 }
280 if (close(child.out) < 0) {
281 logerror("failed to close pipe to daemon access hook '%s'",
282 access_hook);
283 seen_errors = 1;
284 }
285 if (finish_command(&child))
286 seen_errors = 1;
287
288 if (!seen_errors) {
289 strbuf_release(&buf);
290 return 0;
291 }
292
293error_return:
294 strbuf_ltrim(&buf);
295 if (!buf.len)
296 strbuf_addstr(&buf, "service rejected");
297 eol = strchr(buf.buf, '\n');
298 if (eol)
299 *eol = '\0';
300 errno = EACCES;
301 daemon_error(dir, buf.buf);
302 strbuf_release(&buf);
303 return -1;
304}
305
306static int run_service(const char *dir, struct daemon_service *service)
307{
308 const char *path;
309 int enabled = service->enabled;
310 struct strbuf var = STRBUF_INIT;
311
312 loginfo("Request %s for '%s'", service->name, dir);
313
314 if (!enabled && !service->overridable) {
315 logerror("'%s': service not enabled.", service->name);
316 errno = EACCES;
317 return daemon_error(dir, "service not enabled");
318 }
319
320 if (!(path = path_ok(dir)))
321 return daemon_error(dir, "no such repository");
322
323 /*
324 * Security on the cheap.
325 *
326 * We want a readable HEAD, usable "objects" directory, and
327 * a "git-daemon-export-ok" flag that says that the other side
328 * is ok with us doing this.
329 *
330 * path_ok() uses enter_repo() and does whitelist checking.
331 * We only need to make sure the repository is exported.
332 */
333
334 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
335 logerror("'%s': repository not exported.", path);
336 errno = EACCES;
337 return daemon_error(dir, "repository not exported");
338 }
339
340 if (service->overridable) {
341 strbuf_addf(&var, "daemon.%s", service->config_name);
342 git_config_get_bool(var.buf, &enabled);
343 strbuf_release(&var);
344 }
345 if (!enabled) {
346 logerror("'%s': service not enabled for '%s'",
347 service->name, path);
348 errno = EACCES;
349 return daemon_error(dir, "service not enabled");
350 }
351
352 /*
353 * Optionally, a hook can choose to deny access to the
354 * repository depending on the phase of the moon.
355 */
356 if (access_hook && run_access_hook(service, dir, path))
357 return -1;
358
359 /*
360 * We'll ignore SIGTERM from now on, we have a
361 * good client.
362 */
363 signal(SIGTERM, SIG_IGN);
364
365 return service->fn();
366}
367
368static void copy_to_log(int fd)
369{
370 struct strbuf line = STRBUF_INIT;
371 FILE *fp;
372
373 fp = fdopen(fd, "r");
374 if (fp == NULL) {
375 logerror("fdopen of error channel failed");
376 close(fd);
377 return;
378 }
379
380 while (strbuf_getline(&line, fp, '\n') != EOF) {
381 logerror("%s", line.buf);
382 strbuf_setlen(&line, 0);
383 }
384
385 strbuf_release(&line);
386 fclose(fp);
387}
388
389static int run_service_command(const char **argv)
390{
391 struct child_process cld;
392
393 memset(&cld, 0, sizeof(cld));
394 cld.argv = argv;
395 cld.git_cmd = 1;
396 cld.err = -1;
397 if (start_command(&cld))
398 return -1;
399
400 close(0);
401 close(1);
402
403 copy_to_log(cld.err);
404
405 return finish_command(&cld);
406}
407
408static int upload_pack(void)
409{
410 /* Timeout as string */
411 char timeout_buf[64];
412 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
413
414 argv[2] = timeout_buf;
415
416 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
417 return run_service_command(argv);
418}
419
420static int upload_archive(void)
421{
422 static const char *argv[] = { "upload-archive", ".", NULL };
423 return run_service_command(argv);
424}
425
426static int receive_pack(void)
427{
428 static const char *argv[] = { "receive-pack", ".", NULL };
429 return run_service_command(argv);
430}
431
432static struct daemon_service daemon_service[] = {
433 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
434 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
435 { "receive-pack", "receivepack", receive_pack, 0, 1 },
436};
437
438static void enable_service(const char *name, int ena)
439{
440 int i;
441 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
442 if (!strcmp(daemon_service[i].name, name)) {
443 daemon_service[i].enabled = ena;
444 return;
445 }
446 }
447 die("No such service %s", name);
448}
449
450static void make_service_overridable(const char *name, int ena)
451{
452 int i;
453 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
454 if (!strcmp(daemon_service[i].name, name)) {
455 daemon_service[i].overridable = ena;
456 return;
457 }
458 }
459 die("No such service %s", name);
460}
461
462static void parse_host_and_port(char *hostport, char **host,
463 char **port)
464{
465 if (*hostport == '[') {
466 char *end;
467
468 end = strchr(hostport, ']');
469 if (!end)
470 die("Invalid request ('[' without ']')");
471 *end = '\0';
472 *host = hostport + 1;
473 if (!end[1])
474 *port = NULL;
475 else if (end[1] == ':')
476 *port = end + 2;
477 else
478 die("Garbage after end of host part");
479 } else {
480 *host = hostport;
481 *port = strrchr(hostport, ':');
482 if (*port) {
483 **port = '\0';
484 ++*port;
485 }
486 }
487}
488
489/*
490 * Read the host as supplied by the client connection.
491 */
492static void parse_host_arg(char *extra_args, int buflen)
493{
494 char *val;
495 int vallen;
496 char *end = extra_args + buflen;
497
498 if (extra_args < end && *extra_args) {
499 saw_extended_args = 1;
500 if (strncasecmp("host=", extra_args, 5) == 0) {
501 val = extra_args + 5;
502 vallen = strlen(val) + 1;
503 if (*val) {
504 /* Split <host>:<port> at colon. */
505 char *host;
506 char *port;
507 parse_host_and_port(val, &host, &port);
508 if (port) {
509 free(tcp_port);
510 tcp_port = xstrdup(port);
511 }
512 free(hostname);
513 hostname = xstrdup_tolower(host);
514 }
515
516 /* On to the next one */
517 extra_args = val + vallen;
518 }
519 if (extra_args < end && *extra_args)
520 die("Invalid request");
521 }
522
523 /*
524 * Locate canonical hostname and its IP address.
525 */
526 if (hostname) {
527#ifndef NO_IPV6
528 struct addrinfo hints;
529 struct addrinfo *ai;
530 int gai;
531 static char addrbuf[HOST_NAME_MAX + 1];
532
533 memset(&hints, 0, sizeof(hints));
534 hints.ai_flags = AI_CANONNAME;
535
536 gai = getaddrinfo(hostname, NULL, &hints, &ai);
537 if (!gai) {
538 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
539
540 inet_ntop(AF_INET, &sin_addr->sin_addr,
541 addrbuf, sizeof(addrbuf));
542 free(ip_address);
543 ip_address = xstrdup(addrbuf);
544
545 free(canon_hostname);
546 canon_hostname = xstrdup(ai->ai_canonname ?
547 ai->ai_canonname : ip_address);
548
549 freeaddrinfo(ai);
550 }
551#else
552 struct hostent *hent;
553 struct sockaddr_in sa;
554 char **ap;
555 static char addrbuf[HOST_NAME_MAX + 1];
556
557 hent = gethostbyname(hostname);
558
559 ap = hent->h_addr_list;
560 memset(&sa, 0, sizeof sa);
561 sa.sin_family = hent->h_addrtype;
562 sa.sin_port = htons(0);
563 memcpy(&sa.sin_addr, *ap, hent->h_length);
564
565 inet_ntop(hent->h_addrtype, &sa.sin_addr,
566 addrbuf, sizeof(addrbuf));
567
568 free(canon_hostname);
569 canon_hostname = xstrdup(hent->h_name);
570 free(ip_address);
571 ip_address = xstrdup(addrbuf);
572#endif
573 }
574}
575
576
577static int execute(void)
578{
579 char *line = packet_buffer;
580 int pktlen, len, i;
581 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
582
583 if (addr)
584 loginfo("Connection from %s:%s", addr, port);
585
586 alarm(init_timeout ? init_timeout : timeout);
587 pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
588 alarm(0);
589
590 len = strlen(line);
591 if (pktlen != len)
592 loginfo("Extended attributes (%d bytes) exist <%.*s>",
593 (int) pktlen - len,
594 (int) pktlen - len, line + len + 1);
595 if (len && line[len-1] == '\n') {
596 line[--len] = 0;
597 pktlen--;
598 }
599
600 free(hostname);
601 free(canon_hostname);
602 free(ip_address);
603 free(tcp_port);
604 hostname = canon_hostname = ip_address = tcp_port = NULL;
605
606 if (len != pktlen)
607 parse_host_arg(line + len + 1, pktlen - len - 1);
608
609 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
610 struct daemon_service *s = &(daemon_service[i]);
611 const char *arg;
612
613 if (skip_prefix(line, "git-", &arg) &&
614 skip_prefix(arg, s->name, &arg) &&
615 *arg++ == ' ') {
616 /*
617 * Note: The directory here is probably context sensitive,
618 * and might depend on the actual service being performed.
619 */
620 return run_service(arg, s);
621 }
622 }
623
624 logerror("Protocol error: '%s'", line);
625 return -1;
626}
627
628static int addrcmp(const struct sockaddr_storage *s1,
629 const struct sockaddr_storage *s2)
630{
631 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
632 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
633
634 if (sa1->sa_family != sa2->sa_family)
635 return sa1->sa_family - sa2->sa_family;
636 if (sa1->sa_family == AF_INET)
637 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
638 &((struct sockaddr_in *)s2)->sin_addr,
639 sizeof(struct in_addr));
640#ifndef NO_IPV6
641 if (sa1->sa_family == AF_INET6)
642 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
643 &((struct sockaddr_in6 *)s2)->sin6_addr,
644 sizeof(struct in6_addr));
645#endif
646 return 0;
647}
648
649static int max_connections = 32;
650
651static unsigned int live_children;
652
653static struct child {
654 struct child *next;
655 struct child_process cld;
656 struct sockaddr_storage address;
657} *firstborn;
658
659static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
660{
661 struct child *newborn, **cradle;
662
663 newborn = xcalloc(1, sizeof(*newborn));
664 live_children++;
665 memcpy(&newborn->cld, cld, sizeof(*cld));
666 memcpy(&newborn->address, addr, addrlen);
667 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
668 if (!addrcmp(&(*cradle)->address, &newborn->address))
669 break;
670 newborn->next = *cradle;
671 *cradle = newborn;
672}
673
674/*
675 * This gets called if the number of connections grows
676 * past "max_connections".
677 *
678 * We kill the newest connection from a duplicate IP.
679 */
680static void kill_some_child(void)
681{
682 const struct child *blanket, *next;
683
684 if (!(blanket = firstborn))
685 return;
686
687 for (; (next = blanket->next); blanket = next)
688 if (!addrcmp(&blanket->address, &next->address)) {
689 kill(blanket->cld.pid, SIGTERM);
690 break;
691 }
692}
693
694static void check_dead_children(void)
695{
696 int status;
697 pid_t pid;
698
699 struct child **cradle, *blanket;
700 for (cradle = &firstborn; (blanket = *cradle);)
701 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
702 const char *dead = "";
703 if (status)
704 dead = " (with error)";
705 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
706
707 /* remove the child */
708 *cradle = blanket->next;
709 live_children--;
710 free(blanket);
711 } else
712 cradle = &blanket->next;
713}
714
715static char **cld_argv;
716static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
717{
718 struct child_process cld = { NULL };
719 char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
720 char *env[] = { addrbuf, portbuf, NULL };
721
722 if (max_connections && live_children >= max_connections) {
723 kill_some_child();
724 sleep(1); /* give it some time to die */
725 check_dead_children();
726 if (live_children >= max_connections) {
727 close(incoming);
728 logerror("Too many children, dropping connection");
729 return;
730 }
731 }
732
733 if (addr->sa_family == AF_INET) {
734 struct sockaddr_in *sin_addr = (void *) addr;
735 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
736 sizeof(addrbuf) - 12);
737 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
738 ntohs(sin_addr->sin_port));
739#ifndef NO_IPV6
740 } else if (addr->sa_family == AF_INET6) {
741 struct sockaddr_in6 *sin6_addr = (void *) addr;
742
743 char *buf = addrbuf + 12;
744 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
745 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
746 sizeof(addrbuf) - 13);
747 strcat(buf, "]");
748
749 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
750 ntohs(sin6_addr->sin6_port));
751#endif
752 }
753
754 cld.env = (const char **)env;
755 cld.argv = (const char **)cld_argv;
756 cld.in = incoming;
757 cld.out = dup(incoming);
758
759 if (start_command(&cld))
760 logerror("unable to fork");
761 else
762 add_child(&cld, addr, addrlen);
763}
764
765static void child_handler(int signo)
766{
767 /*
768 * Otherwise empty handler because systemcalls will get interrupted
769 * upon signal receipt
770 * SysV needs the handler to be rearmed
771 */
772 signal(SIGCHLD, child_handler);
773}
774
775static int set_reuse_addr(int sockfd)
776{
777 int on = 1;
778
779 if (!reuseaddr)
780 return 0;
781 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
782 &on, sizeof(on));
783}
784
785struct socketlist {
786 int *list;
787 size_t nr;
788 size_t alloc;
789};
790
791static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
792{
793#ifdef NO_IPV6
794 static char ip[INET_ADDRSTRLEN];
795#else
796 static char ip[INET6_ADDRSTRLEN];
797#endif
798
799 switch (family) {
800#ifndef NO_IPV6
801 case AF_INET6:
802 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
803 break;
804#endif
805 case AF_INET:
806 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
807 break;
808 default:
809 strcpy(ip, "<unknown>");
810 }
811 return ip;
812}
813
814#ifndef NO_IPV6
815
816static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
817{
818 int socknum = 0;
819 int maxfd = -1;
820 char pbuf[NI_MAXSERV];
821 struct addrinfo hints, *ai0, *ai;
822 int gai;
823 long flags;
824
825 sprintf(pbuf, "%d", listen_port);
826 memset(&hints, 0, sizeof(hints));
827 hints.ai_family = AF_UNSPEC;
828 hints.ai_socktype = SOCK_STREAM;
829 hints.ai_protocol = IPPROTO_TCP;
830 hints.ai_flags = AI_PASSIVE;
831
832 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
833 if (gai) {
834 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
835 return 0;
836 }
837
838 for (ai = ai0; ai; ai = ai->ai_next) {
839 int sockfd;
840
841 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
842 if (sockfd < 0)
843 continue;
844 if (sockfd >= FD_SETSIZE) {
845 logerror("Socket descriptor too large");
846 close(sockfd);
847 continue;
848 }
849
850#ifdef IPV6_V6ONLY
851 if (ai->ai_family == AF_INET6) {
852 int on = 1;
853 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
854 &on, sizeof(on));
855 /* Note: error is not fatal */
856 }
857#endif
858
859 if (set_reuse_addr(sockfd)) {
860 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
861 close(sockfd);
862 continue;
863 }
864
865 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
866 logerror("Could not bind to %s: %s",
867 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
868 strerror(errno));
869 close(sockfd);
870 continue; /* not fatal */
871 }
872 if (listen(sockfd, 5) < 0) {
873 logerror("Could not listen to %s: %s",
874 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
875 strerror(errno));
876 close(sockfd);
877 continue; /* not fatal */
878 }
879
880 flags = fcntl(sockfd, F_GETFD, 0);
881 if (flags >= 0)
882 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
883
884 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
885 socklist->list[socklist->nr++] = sockfd;
886 socknum++;
887
888 if (maxfd < sockfd)
889 maxfd = sockfd;
890 }
891
892 freeaddrinfo(ai0);
893
894 return socknum;
895}
896
897#else /* NO_IPV6 */
898
899static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
900{
901 struct sockaddr_in sin;
902 int sockfd;
903 long flags;
904
905 memset(&sin, 0, sizeof sin);
906 sin.sin_family = AF_INET;
907 sin.sin_port = htons(listen_port);
908
909 if (listen_addr) {
910 /* Well, host better be an IP address here. */
911 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
912 return 0;
913 } else {
914 sin.sin_addr.s_addr = htonl(INADDR_ANY);
915 }
916
917 sockfd = socket(AF_INET, SOCK_STREAM, 0);
918 if (sockfd < 0)
919 return 0;
920
921 if (set_reuse_addr(sockfd)) {
922 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
923 close(sockfd);
924 return 0;
925 }
926
927 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
928 logerror("Could not listen to %s: %s",
929 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
930 strerror(errno));
931 close(sockfd);
932 return 0;
933 }
934
935 if (listen(sockfd, 5) < 0) {
936 logerror("Could not listen to %s: %s",
937 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
938 strerror(errno));
939 close(sockfd);
940 return 0;
941 }
942
943 flags = fcntl(sockfd, F_GETFD, 0);
944 if (flags >= 0)
945 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
946
947 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
948 socklist->list[socklist->nr++] = sockfd;
949 return 1;
950}
951
952#endif
953
954static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
955{
956 if (!listen_addr->nr)
957 setup_named_sock(NULL, listen_port, socklist);
958 else {
959 int i, socknum;
960 for (i = 0; i < listen_addr->nr; i++) {
961 socknum = setup_named_sock(listen_addr->items[i].string,
962 listen_port, socklist);
963
964 if (socknum == 0)
965 logerror("unable to allocate any listen sockets for host %s on port %u",
966 listen_addr->items[i].string, listen_port);
967 }
968 }
969}
970
971static int service_loop(struct socketlist *socklist)
972{
973 struct pollfd *pfd;
974 int i;
975
976 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
977
978 for (i = 0; i < socklist->nr; i++) {
979 pfd[i].fd = socklist->list[i];
980 pfd[i].events = POLLIN;
981 }
982
983 signal(SIGCHLD, child_handler);
984
985 for (;;) {
986 int i;
987
988 check_dead_children();
989
990 if (poll(pfd, socklist->nr, -1) < 0) {
991 if (errno != EINTR) {
992 logerror("Poll failed, resuming: %s",
993 strerror(errno));
994 sleep(1);
995 }
996 continue;
997 }
998
999 for (i = 0; i < socklist->nr; i++) {
1000 if (pfd[i].revents & POLLIN) {
1001 union {
1002 struct sockaddr sa;
1003 struct sockaddr_in sai;
1004#ifndef NO_IPV6
1005 struct sockaddr_in6 sai6;
1006#endif
1007 } ss;
1008 socklen_t sslen = sizeof(ss);
1009 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1010 if (incoming < 0) {
1011 switch (errno) {
1012 case EAGAIN:
1013 case EINTR:
1014 case ECONNABORTED:
1015 continue;
1016 default:
1017 die_errno("accept returned");
1018 }
1019 }
1020 handle(incoming, &ss.sa, sslen);
1021 }
1022 }
1023 }
1024}
1025
1026#ifdef NO_POSIX_GOODIES
1027
1028struct credentials;
1029
1030static void drop_privileges(struct credentials *cred)
1031{
1032 /* nothing */
1033}
1034
1035static struct credentials *prepare_credentials(const char *user_name,
1036 const char *group_name)
1037{
1038 die("--user not supported on this platform");
1039}
1040
1041#else
1042
1043struct credentials {
1044 struct passwd *pass;
1045 gid_t gid;
1046};
1047
1048static void drop_privileges(struct credentials *cred)
1049{
1050 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1051 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1052 die("cannot drop privileges");
1053}
1054
1055static struct credentials *prepare_credentials(const char *user_name,
1056 const char *group_name)
1057{
1058 static struct credentials c;
1059
1060 c.pass = getpwnam(user_name);
1061 if (!c.pass)
1062 die("user not found - %s", user_name);
1063
1064 if (!group_name)
1065 c.gid = c.pass->pw_gid;
1066 else {
1067 struct group *group = getgrnam(group_name);
1068 if (!group)
1069 die("group not found - %s", group_name);
1070
1071 c.gid = group->gr_gid;
1072 }
1073
1074 return &c;
1075}
1076#endif
1077
1078static void store_pid(const char *path)
1079{
1080 FILE *f = fopen(path, "w");
1081 if (!f)
1082 die_errno("cannot open pid file '%s'", path);
1083 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1084 die_errno("failed to write pid file '%s'", path);
1085}
1086
1087static int serve(struct string_list *listen_addr, int listen_port,
1088 struct credentials *cred)
1089{
1090 struct socketlist socklist = { NULL, 0, 0 };
1091
1092 socksetup(listen_addr, listen_port, &socklist);
1093 if (socklist.nr == 0)
1094 die("unable to allocate any listen sockets on port %u",
1095 listen_port);
1096
1097 drop_privileges(cred);
1098
1099 loginfo("Ready to rumble");
1100
1101 return service_loop(&socklist);
1102}
1103
1104int main(int argc, char **argv)
1105{
1106 int listen_port = 0;
1107 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1108 int serve_mode = 0, inetd_mode = 0;
1109 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1110 int detach = 0;
1111 struct credentials *cred = NULL;
1112 int i;
1113
1114 git_setup_gettext();
1115
1116 git_extract_argv0_path(argv[0]);
1117
1118 for (i = 1; i < argc; i++) {
1119 char *arg = argv[i];
1120 const char *v;
1121
1122 if (skip_prefix(arg, "--listen=", &v)) {
1123 string_list_append(&listen_addr, xstrdup_tolower(v));
1124 continue;
1125 }
1126 if (skip_prefix(arg, "--port=", &v)) {
1127 char *end;
1128 unsigned long n;
1129 n = strtoul(v, &end, 0);
1130 if (*v && !*end) {
1131 listen_port = n;
1132 continue;
1133 }
1134 }
1135 if (!strcmp(arg, "--serve")) {
1136 serve_mode = 1;
1137 continue;
1138 }
1139 if (!strcmp(arg, "--inetd")) {
1140 inetd_mode = 1;
1141 log_syslog = 1;
1142 continue;
1143 }
1144 if (!strcmp(arg, "--verbose")) {
1145 verbose = 1;
1146 continue;
1147 }
1148 if (!strcmp(arg, "--syslog")) {
1149 log_syslog = 1;
1150 continue;
1151 }
1152 if (!strcmp(arg, "--export-all")) {
1153 export_all_trees = 1;
1154 continue;
1155 }
1156 if (skip_prefix(arg, "--access-hook=", &v)) {
1157 access_hook = v;
1158 continue;
1159 }
1160 if (skip_prefix(arg, "--timeout=", &v)) {
1161 timeout = atoi(v);
1162 continue;
1163 }
1164 if (skip_prefix(arg, "--init-timeout=", &v)) {
1165 init_timeout = atoi(v);
1166 continue;
1167 }
1168 if (skip_prefix(arg, "--max-connections=", &v)) {
1169 max_connections = atoi(v);
1170 if (max_connections < 0)
1171 max_connections = 0; /* unlimited */
1172 continue;
1173 }
1174 if (!strcmp(arg, "--strict-paths")) {
1175 strict_paths = 1;
1176 continue;
1177 }
1178 if (skip_prefix(arg, "--base-path=", &v)) {
1179 base_path = v;
1180 continue;
1181 }
1182 if (!strcmp(arg, "--base-path-relaxed")) {
1183 base_path_relaxed = 1;
1184 continue;
1185 }
1186 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1187 interpolated_path = v;
1188 continue;
1189 }
1190 if (!strcmp(arg, "--reuseaddr")) {
1191 reuseaddr = 1;
1192 continue;
1193 }
1194 if (!strcmp(arg, "--user-path")) {
1195 user_path = "";
1196 continue;
1197 }
1198 if (skip_prefix(arg, "--user-path=", &v)) {
1199 user_path = v;
1200 continue;
1201 }
1202 if (skip_prefix(arg, "--pid-file=", &v)) {
1203 pid_file = v;
1204 continue;
1205 }
1206 if (!strcmp(arg, "--detach")) {
1207 detach = 1;
1208 log_syslog = 1;
1209 continue;
1210 }
1211 if (skip_prefix(arg, "--user=", &v)) {
1212 user_name = v;
1213 continue;
1214 }
1215 if (skip_prefix(arg, "--group=", &v)) {
1216 group_name = v;
1217 continue;
1218 }
1219 if (skip_prefix(arg, "--enable=", &v)) {
1220 enable_service(v, 1);
1221 continue;
1222 }
1223 if (skip_prefix(arg, "--disable=", &v)) {
1224 enable_service(v, 0);
1225 continue;
1226 }
1227 if (skip_prefix(arg, "--allow-override=", &v)) {
1228 make_service_overridable(v, 1);
1229 continue;
1230 }
1231 if (skip_prefix(arg, "--forbid-override=", &v)) {
1232 make_service_overridable(v, 0);
1233 continue;
1234 }
1235 if (!strcmp(arg, "--informative-errors")) {
1236 informative_errors = 1;
1237 continue;
1238 }
1239 if (!strcmp(arg, "--no-informative-errors")) {
1240 informative_errors = 0;
1241 continue;
1242 }
1243 if (!strcmp(arg, "--")) {
1244 ok_paths = &argv[i+1];
1245 break;
1246 } else if (arg[0] != '-') {
1247 ok_paths = &argv[i];
1248 break;
1249 }
1250
1251 usage(daemon_usage);
1252 }
1253
1254 if (log_syslog) {
1255 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1256 set_die_routine(daemon_die);
1257 } else
1258 /* avoid splitting a message in the middle */
1259 setvbuf(stderr, NULL, _IOFBF, 4096);
1260
1261 if (inetd_mode && (detach || group_name || user_name))
1262 die("--detach, --user and --group are incompatible with --inetd");
1263
1264 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1265 die("--listen= and --port= are incompatible with --inetd");
1266 else if (listen_port == 0)
1267 listen_port = DEFAULT_GIT_PORT;
1268
1269 if (group_name && !user_name)
1270 die("--group supplied without --user");
1271
1272 if (user_name)
1273 cred = prepare_credentials(user_name, group_name);
1274
1275 if (strict_paths && (!ok_paths || !*ok_paths))
1276 die("option --strict-paths requires a whitelist");
1277
1278 if (base_path && !is_directory(base_path))
1279 die("base-path '%s' does not exist or is not a directory",
1280 base_path);
1281
1282 if (inetd_mode) {
1283 if (!freopen("/dev/null", "w", stderr))
1284 die_errno("failed to redirect stderr to /dev/null");
1285 }
1286
1287 if (inetd_mode || serve_mode)
1288 return execute();
1289
1290 if (detach) {
1291 if (daemonize())
1292 die("--detach not supported on this platform");
1293 } else
1294 sanitize_stdfds();
1295
1296 if (pid_file)
1297 store_pid(pid_file);
1298
1299 /* prepare argv for serving-processes */
1300 cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1301 cld_argv[0] = argv[0]; /* git-daemon */
1302 cld_argv[1] = "--serve";
1303 for (i = 1; i < argc; ++i)
1304 cld_argv[i+1] = argv[i];
1305 cld_argv[argc+1] = NULL;
1306
1307 return serve(&listen_addr, listen_port, cred);
1308}