notes-cache: convert to struct object_id
[alt-git.git] / daemon.c
blobac7181a4832672ef1e599324a15868d1b06f8fc0
1 #include "cache.h"
2 #include "pkt-line.h"
3 #include "run-command.h"
4 #include "strbuf.h"
5 #include "string-list.h"
7 #ifdef NO_INITGROUPS
8 #define initgroups(x, y) (0) /* nothing */
9 #endif
11 static int log_syslog;
12 static int verbose;
13 static int reuseaddr;
14 static int informative_errors;
16 static const char daemon_usage[] =
17 "git daemon [--verbose] [--syslog] [--export-all]\n"
18 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
19 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
20 " [--user-path | --user-path=<path>]\n"
21 " [--interpolated-path=<path>]\n"
22 " [--reuseaddr] [--pid-file=<file>]\n"
23 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
24 " [--access-hook=<path>]\n"
25 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
26 " [--detach] [--user=<user> [--group=<group>]]\n"
27 " [<directory>...]";
29 /* List of acceptable pathname prefixes */
30 static const char **ok_paths;
31 static int strict_paths;
33 /* If this is set, git-daemon-export-ok is not required */
34 static int export_all_trees;
36 /* Take all paths relative to this one if non-NULL */
37 static const char *base_path;
38 static const char *interpolated_path;
39 static int base_path_relaxed;
41 /* If defined, ~user notation is allowed and the string is inserted
42 * after ~user/. E.g. a request to git://host/~alice/frotz would
43 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
45 static const char *user_path;
47 /* Timeout, and initial timeout */
48 static unsigned int timeout;
49 static unsigned int init_timeout;
51 struct hostinfo {
52 struct strbuf hostname;
53 struct strbuf canon_hostname;
54 struct strbuf ip_address;
55 struct strbuf tcp_port;
56 unsigned int hostname_lookup_done:1;
57 unsigned int saw_extended_args:1;
60 static void lookup_hostname(struct hostinfo *hi);
62 static const char *get_canon_hostname(struct hostinfo *hi)
64 lookup_hostname(hi);
65 return hi->canon_hostname.buf;
68 static const char *get_ip_address(struct hostinfo *hi)
70 lookup_hostname(hi);
71 return hi->ip_address.buf;
74 static void logreport(int priority, const char *err, va_list params)
76 if (log_syslog) {
77 char buf[1024];
78 vsnprintf(buf, sizeof(buf), err, params);
79 syslog(priority, "%s", buf);
80 } else {
82 * Since stderr is set to buffered mode, the
83 * logging of different processes will not overlap
84 * unless they overflow the (rather big) buffers.
86 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
87 vfprintf(stderr, err, params);
88 fputc('\n', stderr);
89 fflush(stderr);
93 __attribute__((format (printf, 1, 2)))
94 static void logerror(const char *err, ...)
96 va_list params;
97 va_start(params, err);
98 logreport(LOG_ERR, err, params);
99 va_end(params);
102 __attribute__((format (printf, 1, 2)))
103 static void loginfo(const char *err, ...)
105 va_list params;
106 if (!verbose)
107 return;
108 va_start(params, err);
109 logreport(LOG_INFO, err, params);
110 va_end(params);
113 static void NORETURN daemon_die(const char *err, va_list params)
115 logreport(LOG_ERR, err, params);
116 exit(1);
119 struct expand_path_context {
120 const char *directory;
121 struct hostinfo *hostinfo;
124 static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
126 struct expand_path_context *context = ctx;
127 struct hostinfo *hi = context->hostinfo;
129 switch (placeholder[0]) {
130 case 'H':
131 strbuf_addbuf(sb, &hi->hostname);
132 return 1;
133 case 'C':
134 if (placeholder[1] == 'H') {
135 strbuf_addstr(sb, get_canon_hostname(hi));
136 return 2;
138 break;
139 case 'I':
140 if (placeholder[1] == 'P') {
141 strbuf_addstr(sb, get_ip_address(hi));
142 return 2;
144 break;
145 case 'P':
146 strbuf_addbuf(sb, &hi->tcp_port);
147 return 1;
148 case 'D':
149 strbuf_addstr(sb, context->directory);
150 return 1;
152 return 0;
155 static const char *path_ok(const char *directory, struct hostinfo *hi)
157 static char rpath[PATH_MAX];
158 static char interp_path[PATH_MAX];
159 size_t rlen;
160 const char *path;
161 const char *dir;
163 dir = directory;
165 if (daemon_avoid_alias(dir)) {
166 logerror("'%s': aliased", dir);
167 return NULL;
170 if (*dir == '~') {
171 if (!user_path) {
172 logerror("'%s': User-path not allowed", dir);
173 return NULL;
175 if (*user_path) {
176 /* Got either "~alice" or "~alice/foo";
177 * rewrite them to "~alice/%s" or
178 * "~alice/%s/foo".
180 int namlen, restlen = strlen(dir);
181 const char *slash = strchr(dir, '/');
182 if (!slash)
183 slash = dir + restlen;
184 namlen = slash - dir;
185 restlen -= namlen;
186 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
187 rlen = snprintf(rpath, sizeof(rpath), "%.*s/%s%.*s",
188 namlen, dir, user_path, restlen, slash);
189 if (rlen >= sizeof(rpath)) {
190 logerror("user-path too large: %s", rpath);
191 return NULL;
193 dir = rpath;
196 else if (interpolated_path && hi->saw_extended_args) {
197 struct strbuf expanded_path = STRBUF_INIT;
198 struct expand_path_context context;
200 context.directory = directory;
201 context.hostinfo = hi;
203 if (*dir != '/') {
204 /* Allow only absolute */
205 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
206 return NULL;
209 strbuf_expand(&expanded_path, interpolated_path,
210 expand_path, &context);
212 rlen = strlcpy(interp_path, expanded_path.buf,
213 sizeof(interp_path));
214 if (rlen >= sizeof(interp_path)) {
215 logerror("interpolated path too large: %s",
216 interp_path);
217 return NULL;
220 strbuf_release(&expanded_path);
221 loginfo("Interpolated dir '%s'", interp_path);
223 dir = interp_path;
225 else if (base_path) {
226 if (*dir != '/') {
227 /* Allow only absolute */
228 logerror("'%s': Non-absolute path denied (base-path active)", dir);
229 return NULL;
231 rlen = snprintf(rpath, sizeof(rpath), "%s%s", base_path, dir);
232 if (rlen >= sizeof(rpath)) {
233 logerror("base-path too large: %s", rpath);
234 return NULL;
236 dir = rpath;
239 path = enter_repo(dir, strict_paths);
240 if (!path && base_path && base_path_relaxed) {
242 * if we fail and base_path_relaxed is enabled, try without
243 * prefixing the base path
245 dir = directory;
246 path = enter_repo(dir, strict_paths);
249 if (!path) {
250 logerror("'%s' does not appear to be a git repository", dir);
251 return NULL;
254 if ( ok_paths && *ok_paths ) {
255 const char **pp;
256 int pathlen = strlen(path);
258 /* The validation is done on the paths after enter_repo
259 * appends optional {.git,.git/.git} and friends, but
260 * it does not use getcwd(). So if your /pub is
261 * a symlink to /mnt/pub, you can whitelist /pub and
262 * do not have to say /mnt/pub.
263 * Do not say /pub/.
265 for ( pp = ok_paths ; *pp ; pp++ ) {
266 int len = strlen(*pp);
267 if (len <= pathlen &&
268 !memcmp(*pp, path, len) &&
269 (path[len] == '\0' ||
270 (!strict_paths && path[len] == '/')))
271 return path;
274 else {
275 /* be backwards compatible */
276 if (!strict_paths)
277 return path;
280 logerror("'%s': not in whitelist", path);
281 return NULL; /* Fallthrough. Deny by default */
284 typedef int (*daemon_service_fn)(void);
285 struct daemon_service {
286 const char *name;
287 const char *config_name;
288 daemon_service_fn fn;
289 int enabled;
290 int overridable;
293 static int daemon_error(const char *dir, const char *msg)
295 if (!informative_errors)
296 msg = "access denied or repository not exported";
297 packet_write_fmt(1, "ERR %s: %s", msg, dir);
298 return -1;
301 static const char *access_hook;
303 static int run_access_hook(struct daemon_service *service, const char *dir,
304 const char *path, struct hostinfo *hi)
306 struct child_process child = CHILD_PROCESS_INIT;
307 struct strbuf buf = STRBUF_INIT;
308 const char *argv[8];
309 const char **arg = argv;
310 char *eol;
311 int seen_errors = 0;
313 *arg++ = access_hook;
314 *arg++ = service->name;
315 *arg++ = path;
316 *arg++ = hi->hostname.buf;
317 *arg++ = get_canon_hostname(hi);
318 *arg++ = get_ip_address(hi);
319 *arg++ = hi->tcp_port.buf;
320 *arg = NULL;
322 child.use_shell = 1;
323 child.argv = argv;
324 child.no_stdin = 1;
325 child.no_stderr = 1;
326 child.out = -1;
327 if (start_command(&child)) {
328 logerror("daemon access hook '%s' failed to start",
329 access_hook);
330 goto error_return;
332 if (strbuf_read(&buf, child.out, 0) < 0) {
333 logerror("failed to read from pipe to daemon access hook '%s'",
334 access_hook);
335 strbuf_reset(&buf);
336 seen_errors = 1;
338 if (close(child.out) < 0) {
339 logerror("failed to close pipe to daemon access hook '%s'",
340 access_hook);
341 seen_errors = 1;
343 if (finish_command(&child))
344 seen_errors = 1;
346 if (!seen_errors) {
347 strbuf_release(&buf);
348 return 0;
351 error_return:
352 strbuf_ltrim(&buf);
353 if (!buf.len)
354 strbuf_addstr(&buf, "service rejected");
355 eol = strchr(buf.buf, '\n');
356 if (eol)
357 *eol = '\0';
358 errno = EACCES;
359 daemon_error(dir, buf.buf);
360 strbuf_release(&buf);
361 return -1;
364 static int run_service(const char *dir, struct daemon_service *service,
365 struct hostinfo *hi)
367 const char *path;
368 int enabled = service->enabled;
369 struct strbuf var = STRBUF_INIT;
371 loginfo("Request %s for '%s'", service->name, dir);
373 if (!enabled && !service->overridable) {
374 logerror("'%s': service not enabled.", service->name);
375 errno = EACCES;
376 return daemon_error(dir, "service not enabled");
379 if (!(path = path_ok(dir, hi)))
380 return daemon_error(dir, "no such repository");
383 * Security on the cheap.
385 * We want a readable HEAD, usable "objects" directory, and
386 * a "git-daemon-export-ok" flag that says that the other side
387 * is ok with us doing this.
389 * path_ok() uses enter_repo() and does whitelist checking.
390 * We only need to make sure the repository is exported.
393 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
394 logerror("'%s': repository not exported.", path);
395 errno = EACCES;
396 return daemon_error(dir, "repository not exported");
399 if (service->overridable) {
400 strbuf_addf(&var, "daemon.%s", service->config_name);
401 git_config_get_bool(var.buf, &enabled);
402 strbuf_release(&var);
404 if (!enabled) {
405 logerror("'%s': service not enabled for '%s'",
406 service->name, path);
407 errno = EACCES;
408 return daemon_error(dir, "service not enabled");
412 * Optionally, a hook can choose to deny access to the
413 * repository depending on the phase of the moon.
415 if (access_hook && run_access_hook(service, dir, path, hi))
416 return -1;
419 * We'll ignore SIGTERM from now on, we have a
420 * good client.
422 signal(SIGTERM, SIG_IGN);
424 return service->fn();
427 static void copy_to_log(int fd)
429 struct strbuf line = STRBUF_INIT;
430 FILE *fp;
432 fp = fdopen(fd, "r");
433 if (fp == NULL) {
434 logerror("fdopen of error channel failed");
435 close(fd);
436 return;
439 while (strbuf_getline_lf(&line, fp) != EOF) {
440 logerror("%s", line.buf);
441 strbuf_setlen(&line, 0);
444 strbuf_release(&line);
445 fclose(fp);
448 static int run_service_command(struct child_process *cld)
450 argv_array_push(&cld->args, ".");
451 cld->git_cmd = 1;
452 cld->err = -1;
453 if (start_command(cld))
454 return -1;
456 close(0);
457 close(1);
459 copy_to_log(cld->err);
461 return finish_command(cld);
464 static int upload_pack(void)
466 struct child_process cld = CHILD_PROCESS_INIT;
467 argv_array_pushl(&cld.args, "upload-pack", "--strict", NULL);
468 argv_array_pushf(&cld.args, "--timeout=%u", timeout);
469 return run_service_command(&cld);
472 static int upload_archive(void)
474 struct child_process cld = CHILD_PROCESS_INIT;
475 argv_array_push(&cld.args, "upload-archive");
476 return run_service_command(&cld);
479 static int receive_pack(void)
481 struct child_process cld = CHILD_PROCESS_INIT;
482 argv_array_push(&cld.args, "receive-pack");
483 return run_service_command(&cld);
486 static struct daemon_service daemon_service[] = {
487 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
488 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
489 { "receive-pack", "receivepack", receive_pack, 0, 1 },
492 static void enable_service(const char *name, int ena)
494 int i;
495 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
496 if (!strcmp(daemon_service[i].name, name)) {
497 daemon_service[i].enabled = ena;
498 return;
501 die("No such service %s", name);
504 static void make_service_overridable(const char *name, int ena)
506 int i;
507 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
508 if (!strcmp(daemon_service[i].name, name)) {
509 daemon_service[i].overridable = ena;
510 return;
513 die("No such service %s", name);
516 static void parse_host_and_port(char *hostport, char **host,
517 char **port)
519 if (*hostport == '[') {
520 char *end;
522 end = strchr(hostport, ']');
523 if (!end)
524 die("Invalid request ('[' without ']')");
525 *end = '\0';
526 *host = hostport + 1;
527 if (!end[1])
528 *port = NULL;
529 else if (end[1] == ':')
530 *port = end + 2;
531 else
532 die("Garbage after end of host part");
533 } else {
534 *host = hostport;
535 *port = strrchr(hostport, ':');
536 if (*port) {
537 **port = '\0';
538 ++*port;
544 * Sanitize a string from the client so that it's OK to be inserted into a
545 * filesystem path. Specifically, we disallow slashes, runs of "..", and
546 * trailing and leading dots, which means that the client cannot escape
547 * our base path via ".." traversal.
549 static void sanitize_client(struct strbuf *out, const char *in)
551 for (; *in; in++) {
552 if (*in == '/')
553 continue;
554 if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
555 continue;
556 strbuf_addch(out, *in);
559 while (out->len && out->buf[out->len - 1] == '.')
560 strbuf_setlen(out, out->len - 1);
564 * Like sanitize_client, but we also perform any canonicalization
565 * to make life easier on the admin.
567 static void canonicalize_client(struct strbuf *out, const char *in)
569 sanitize_client(out, in);
570 strbuf_tolower(out);
574 * Read the host as supplied by the client connection.
576 static void parse_host_arg(struct hostinfo *hi, char *extra_args, int buflen)
578 char *val;
579 int vallen;
580 char *end = extra_args + buflen;
582 if (extra_args < end && *extra_args) {
583 hi->saw_extended_args = 1;
584 if (strncasecmp("host=", extra_args, 5) == 0) {
585 val = extra_args + 5;
586 vallen = strlen(val) + 1;
587 if (*val) {
588 /* Split <host>:<port> at colon. */
589 char *host;
590 char *port;
591 parse_host_and_port(val, &host, &port);
592 if (port)
593 sanitize_client(&hi->tcp_port, port);
594 canonicalize_client(&hi->hostname, host);
595 hi->hostname_lookup_done = 0;
598 /* On to the next one */
599 extra_args = val + vallen;
601 if (extra_args < end && *extra_args)
602 die("Invalid request");
607 * Locate canonical hostname and its IP address.
609 static void lookup_hostname(struct hostinfo *hi)
611 if (!hi->hostname_lookup_done && hi->hostname.len) {
612 #ifndef NO_IPV6
613 struct addrinfo hints;
614 struct addrinfo *ai;
615 int gai;
616 static char addrbuf[HOST_NAME_MAX + 1];
618 memset(&hints, 0, sizeof(hints));
619 hints.ai_flags = AI_CANONNAME;
621 gai = getaddrinfo(hi->hostname.buf, NULL, &hints, &ai);
622 if (!gai) {
623 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
625 inet_ntop(AF_INET, &sin_addr->sin_addr,
626 addrbuf, sizeof(addrbuf));
627 strbuf_addstr(&hi->ip_address, addrbuf);
629 if (ai->ai_canonname)
630 sanitize_client(&hi->canon_hostname,
631 ai->ai_canonname);
632 else
633 strbuf_addbuf(&hi->canon_hostname,
634 &hi->ip_address);
636 freeaddrinfo(ai);
638 #else
639 struct hostent *hent;
640 struct sockaddr_in sa;
641 char **ap;
642 static char addrbuf[HOST_NAME_MAX + 1];
644 hent = gethostbyname(hi->hostname.buf);
645 if (hent) {
646 ap = hent->h_addr_list;
647 memset(&sa, 0, sizeof sa);
648 sa.sin_family = hent->h_addrtype;
649 sa.sin_port = htons(0);
650 memcpy(&sa.sin_addr, *ap, hent->h_length);
652 inet_ntop(hent->h_addrtype, &sa.sin_addr,
653 addrbuf, sizeof(addrbuf));
655 sanitize_client(&hi->canon_hostname, hent->h_name);
656 strbuf_addstr(&hi->ip_address, addrbuf);
658 #endif
659 hi->hostname_lookup_done = 1;
663 static void hostinfo_init(struct hostinfo *hi)
665 memset(hi, 0, sizeof(*hi));
666 strbuf_init(&hi->hostname, 0);
667 strbuf_init(&hi->canon_hostname, 0);
668 strbuf_init(&hi->ip_address, 0);
669 strbuf_init(&hi->tcp_port, 0);
672 static void hostinfo_clear(struct hostinfo *hi)
674 strbuf_release(&hi->hostname);
675 strbuf_release(&hi->canon_hostname);
676 strbuf_release(&hi->ip_address);
677 strbuf_release(&hi->tcp_port);
680 static void set_keep_alive(int sockfd)
682 int ka = 1;
684 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0) {
685 if (errno != ENOTSOCK)
686 logerror("unable to set SO_KEEPALIVE on socket: %s",
687 strerror(errno));
691 static int execute(void)
693 char *line = packet_buffer;
694 int pktlen, len, i;
695 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
696 struct hostinfo hi;
698 hostinfo_init(&hi);
700 if (addr)
701 loginfo("Connection from %s:%s", addr, port);
703 set_keep_alive(0);
704 alarm(init_timeout ? init_timeout : timeout);
705 pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
706 alarm(0);
708 len = strlen(line);
709 if (pktlen != len)
710 loginfo("Extended attributes (%d bytes) exist <%.*s>",
711 (int) pktlen - len,
712 (int) pktlen - len, line + len + 1);
713 if (len && line[len-1] == '\n') {
714 line[--len] = 0;
715 pktlen--;
718 if (len != pktlen)
719 parse_host_arg(&hi, line + len + 1, pktlen - len - 1);
721 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
722 struct daemon_service *s = &(daemon_service[i]);
723 const char *arg;
725 if (skip_prefix(line, "git-", &arg) &&
726 skip_prefix(arg, s->name, &arg) &&
727 *arg++ == ' ') {
729 * Note: The directory here is probably context sensitive,
730 * and might depend on the actual service being performed.
732 int rc = run_service(arg, s, &hi);
733 hostinfo_clear(&hi);
734 return rc;
738 hostinfo_clear(&hi);
739 logerror("Protocol error: '%s'", line);
740 return -1;
743 static int addrcmp(const struct sockaddr_storage *s1,
744 const struct sockaddr_storage *s2)
746 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
747 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
749 if (sa1->sa_family != sa2->sa_family)
750 return sa1->sa_family - sa2->sa_family;
751 if (sa1->sa_family == AF_INET)
752 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
753 &((struct sockaddr_in *)s2)->sin_addr,
754 sizeof(struct in_addr));
755 #ifndef NO_IPV6
756 if (sa1->sa_family == AF_INET6)
757 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
758 &((struct sockaddr_in6 *)s2)->sin6_addr,
759 sizeof(struct in6_addr));
760 #endif
761 return 0;
764 static int max_connections = 32;
766 static unsigned int live_children;
768 static struct child {
769 struct child *next;
770 struct child_process cld;
771 struct sockaddr_storage address;
772 } *firstborn;
774 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
776 struct child *newborn, **cradle;
778 newborn = xcalloc(1, sizeof(*newborn));
779 live_children++;
780 memcpy(&newborn->cld, cld, sizeof(*cld));
781 memcpy(&newborn->address, addr, addrlen);
782 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
783 if (!addrcmp(&(*cradle)->address, &newborn->address))
784 break;
785 newborn->next = *cradle;
786 *cradle = newborn;
790 * This gets called if the number of connections grows
791 * past "max_connections".
793 * We kill the newest connection from a duplicate IP.
795 static void kill_some_child(void)
797 const struct child *blanket, *next;
799 if (!(blanket = firstborn))
800 return;
802 for (; (next = blanket->next); blanket = next)
803 if (!addrcmp(&blanket->address, &next->address)) {
804 kill(blanket->cld.pid, SIGTERM);
805 break;
809 static void check_dead_children(void)
811 int status;
812 pid_t pid;
814 struct child **cradle, *blanket;
815 for (cradle = &firstborn; (blanket = *cradle);)
816 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
817 const char *dead = "";
818 if (status)
819 dead = " (with error)";
820 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
822 /* remove the child */
823 *cradle = blanket->next;
824 live_children--;
825 child_process_clear(&blanket->cld);
826 free(blanket);
827 } else
828 cradle = &blanket->next;
831 static struct argv_array cld_argv = ARGV_ARRAY_INIT;
832 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
834 struct child_process cld = CHILD_PROCESS_INIT;
836 if (max_connections && live_children >= max_connections) {
837 kill_some_child();
838 sleep(1); /* give it some time to die */
839 check_dead_children();
840 if (live_children >= max_connections) {
841 close(incoming);
842 logerror("Too many children, dropping connection");
843 return;
847 if (addr->sa_family == AF_INET) {
848 char buf[128] = "";
849 struct sockaddr_in *sin_addr = (void *) addr;
850 inet_ntop(addr->sa_family, &sin_addr->sin_addr, buf, sizeof(buf));
851 argv_array_pushf(&cld.env_array, "REMOTE_ADDR=%s", buf);
852 argv_array_pushf(&cld.env_array, "REMOTE_PORT=%d",
853 ntohs(sin_addr->sin_port));
854 #ifndef NO_IPV6
855 } else if (addr->sa_family == AF_INET6) {
856 char buf[128] = "";
857 struct sockaddr_in6 *sin6_addr = (void *) addr;
858 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(buf));
859 argv_array_pushf(&cld.env_array, "REMOTE_ADDR=[%s]", buf);
860 argv_array_pushf(&cld.env_array, "REMOTE_PORT=%d",
861 ntohs(sin6_addr->sin6_port));
862 #endif
865 cld.argv = cld_argv.argv;
866 cld.in = incoming;
867 cld.out = dup(incoming);
869 if (start_command(&cld))
870 logerror("unable to fork");
871 else
872 add_child(&cld, addr, addrlen);
875 static void child_handler(int signo)
878 * Otherwise empty handler because systemcalls will get interrupted
879 * upon signal receipt
880 * SysV needs the handler to be rearmed
882 signal(SIGCHLD, child_handler);
885 static int set_reuse_addr(int sockfd)
887 int on = 1;
889 if (!reuseaddr)
890 return 0;
891 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
892 &on, sizeof(on));
895 struct socketlist {
896 int *list;
897 size_t nr;
898 size_t alloc;
901 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
903 #ifdef NO_IPV6
904 static char ip[INET_ADDRSTRLEN];
905 #else
906 static char ip[INET6_ADDRSTRLEN];
907 #endif
909 switch (family) {
910 #ifndef NO_IPV6
911 case AF_INET6:
912 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
913 break;
914 #endif
915 case AF_INET:
916 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
917 break;
918 default:
919 xsnprintf(ip, sizeof(ip), "<unknown>");
921 return ip;
924 #ifndef NO_IPV6
926 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
928 int socknum = 0;
929 char pbuf[NI_MAXSERV];
930 struct addrinfo hints, *ai0, *ai;
931 int gai;
932 long flags;
934 xsnprintf(pbuf, sizeof(pbuf), "%d", listen_port);
935 memset(&hints, 0, sizeof(hints));
936 hints.ai_family = AF_UNSPEC;
937 hints.ai_socktype = SOCK_STREAM;
938 hints.ai_protocol = IPPROTO_TCP;
939 hints.ai_flags = AI_PASSIVE;
941 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
942 if (gai) {
943 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
944 return 0;
947 for (ai = ai0; ai; ai = ai->ai_next) {
948 int sockfd;
950 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
951 if (sockfd < 0)
952 continue;
953 if (sockfd >= FD_SETSIZE) {
954 logerror("Socket descriptor too large");
955 close(sockfd);
956 continue;
959 #ifdef IPV6_V6ONLY
960 if (ai->ai_family == AF_INET6) {
961 int on = 1;
962 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
963 &on, sizeof(on));
964 /* Note: error is not fatal */
966 #endif
968 if (set_reuse_addr(sockfd)) {
969 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
970 close(sockfd);
971 continue;
974 set_keep_alive(sockfd);
976 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
977 logerror("Could not bind to %s: %s",
978 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
979 strerror(errno));
980 close(sockfd);
981 continue; /* not fatal */
983 if (listen(sockfd, 5) < 0) {
984 logerror("Could not listen to %s: %s",
985 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
986 strerror(errno));
987 close(sockfd);
988 continue; /* not fatal */
991 flags = fcntl(sockfd, F_GETFD, 0);
992 if (flags >= 0)
993 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
995 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
996 socklist->list[socklist->nr++] = sockfd;
997 socknum++;
1000 freeaddrinfo(ai0);
1002 return socknum;
1005 #else /* NO_IPV6 */
1007 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
1009 struct sockaddr_in sin;
1010 int sockfd;
1011 long flags;
1013 memset(&sin, 0, sizeof sin);
1014 sin.sin_family = AF_INET;
1015 sin.sin_port = htons(listen_port);
1017 if (listen_addr) {
1018 /* Well, host better be an IP address here. */
1019 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
1020 return 0;
1021 } else {
1022 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1025 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1026 if (sockfd < 0)
1027 return 0;
1029 if (set_reuse_addr(sockfd)) {
1030 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1031 close(sockfd);
1032 return 0;
1035 set_keep_alive(sockfd);
1037 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1038 logerror("Could not bind to %s: %s",
1039 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1040 strerror(errno));
1041 close(sockfd);
1042 return 0;
1045 if (listen(sockfd, 5) < 0) {
1046 logerror("Could not listen to %s: %s",
1047 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1048 strerror(errno));
1049 close(sockfd);
1050 return 0;
1053 flags = fcntl(sockfd, F_GETFD, 0);
1054 if (flags >= 0)
1055 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1057 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1058 socklist->list[socklist->nr++] = sockfd;
1059 return 1;
1062 #endif
1064 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1066 if (!listen_addr->nr)
1067 setup_named_sock(NULL, listen_port, socklist);
1068 else {
1069 int i, socknum;
1070 for (i = 0; i < listen_addr->nr; i++) {
1071 socknum = setup_named_sock(listen_addr->items[i].string,
1072 listen_port, socklist);
1074 if (socknum == 0)
1075 logerror("unable to allocate any listen sockets for host %s on port %u",
1076 listen_addr->items[i].string, listen_port);
1081 static int service_loop(struct socketlist *socklist)
1083 struct pollfd *pfd;
1084 int i;
1086 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
1088 for (i = 0; i < socklist->nr; i++) {
1089 pfd[i].fd = socklist->list[i];
1090 pfd[i].events = POLLIN;
1093 signal(SIGCHLD, child_handler);
1095 for (;;) {
1096 int i;
1098 check_dead_children();
1100 if (poll(pfd, socklist->nr, -1) < 0) {
1101 if (errno != EINTR) {
1102 logerror("Poll failed, resuming: %s",
1103 strerror(errno));
1104 sleep(1);
1106 continue;
1109 for (i = 0; i < socklist->nr; i++) {
1110 if (pfd[i].revents & POLLIN) {
1111 union {
1112 struct sockaddr sa;
1113 struct sockaddr_in sai;
1114 #ifndef NO_IPV6
1115 struct sockaddr_in6 sai6;
1116 #endif
1117 } ss;
1118 socklen_t sslen = sizeof(ss);
1119 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1120 if (incoming < 0) {
1121 switch (errno) {
1122 case EAGAIN:
1123 case EINTR:
1124 case ECONNABORTED:
1125 continue;
1126 default:
1127 die_errno("accept returned");
1130 handle(incoming, &ss.sa, sslen);
1136 #ifdef NO_POSIX_GOODIES
1138 struct credentials;
1140 static void drop_privileges(struct credentials *cred)
1142 /* nothing */
1145 static struct credentials *prepare_credentials(const char *user_name,
1146 const char *group_name)
1148 die("--user not supported on this platform");
1151 #else
1153 struct credentials {
1154 struct passwd *pass;
1155 gid_t gid;
1158 static void drop_privileges(struct credentials *cred)
1160 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1161 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1162 die("cannot drop privileges");
1165 static struct credentials *prepare_credentials(const char *user_name,
1166 const char *group_name)
1168 static struct credentials c;
1170 c.pass = getpwnam(user_name);
1171 if (!c.pass)
1172 die("user not found - %s", user_name);
1174 if (!group_name)
1175 c.gid = c.pass->pw_gid;
1176 else {
1177 struct group *group = getgrnam(group_name);
1178 if (!group)
1179 die("group not found - %s", group_name);
1181 c.gid = group->gr_gid;
1184 return &c;
1186 #endif
1188 static int serve(struct string_list *listen_addr, int listen_port,
1189 struct credentials *cred)
1191 struct socketlist socklist = { NULL, 0, 0 };
1193 socksetup(listen_addr, listen_port, &socklist);
1194 if (socklist.nr == 0)
1195 die("unable to allocate any listen sockets on port %u",
1196 listen_port);
1198 drop_privileges(cred);
1200 loginfo("Ready to rumble");
1202 return service_loop(&socklist);
1205 int cmd_main(int argc, const char **argv)
1207 int listen_port = 0;
1208 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1209 int serve_mode = 0, inetd_mode = 0;
1210 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1211 int detach = 0;
1212 struct credentials *cred = NULL;
1213 int i;
1215 for (i = 1; i < argc; i++) {
1216 const char *arg = argv[i];
1217 const char *v;
1219 if (skip_prefix(arg, "--listen=", &v)) {
1220 string_list_append(&listen_addr, xstrdup_tolower(v));
1221 continue;
1223 if (skip_prefix(arg, "--port=", &v)) {
1224 char *end;
1225 unsigned long n;
1226 n = strtoul(v, &end, 0);
1227 if (*v && !*end) {
1228 listen_port = n;
1229 continue;
1232 if (!strcmp(arg, "--serve")) {
1233 serve_mode = 1;
1234 continue;
1236 if (!strcmp(arg, "--inetd")) {
1237 inetd_mode = 1;
1238 log_syslog = 1;
1239 continue;
1241 if (!strcmp(arg, "--verbose")) {
1242 verbose = 1;
1243 continue;
1245 if (!strcmp(arg, "--syslog")) {
1246 log_syslog = 1;
1247 continue;
1249 if (!strcmp(arg, "--export-all")) {
1250 export_all_trees = 1;
1251 continue;
1253 if (skip_prefix(arg, "--access-hook=", &v)) {
1254 access_hook = v;
1255 continue;
1257 if (skip_prefix(arg, "--timeout=", &v)) {
1258 timeout = atoi(v);
1259 continue;
1261 if (skip_prefix(arg, "--init-timeout=", &v)) {
1262 init_timeout = atoi(v);
1263 continue;
1265 if (skip_prefix(arg, "--max-connections=", &v)) {
1266 max_connections = atoi(v);
1267 if (max_connections < 0)
1268 max_connections = 0; /* unlimited */
1269 continue;
1271 if (!strcmp(arg, "--strict-paths")) {
1272 strict_paths = 1;
1273 continue;
1275 if (skip_prefix(arg, "--base-path=", &v)) {
1276 base_path = v;
1277 continue;
1279 if (!strcmp(arg, "--base-path-relaxed")) {
1280 base_path_relaxed = 1;
1281 continue;
1283 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1284 interpolated_path = v;
1285 continue;
1287 if (!strcmp(arg, "--reuseaddr")) {
1288 reuseaddr = 1;
1289 continue;
1291 if (!strcmp(arg, "--user-path")) {
1292 user_path = "";
1293 continue;
1295 if (skip_prefix(arg, "--user-path=", &v)) {
1296 user_path = v;
1297 continue;
1299 if (skip_prefix(arg, "--pid-file=", &v)) {
1300 pid_file = v;
1301 continue;
1303 if (!strcmp(arg, "--detach")) {
1304 detach = 1;
1305 log_syslog = 1;
1306 continue;
1308 if (skip_prefix(arg, "--user=", &v)) {
1309 user_name = v;
1310 continue;
1312 if (skip_prefix(arg, "--group=", &v)) {
1313 group_name = v;
1314 continue;
1316 if (skip_prefix(arg, "--enable=", &v)) {
1317 enable_service(v, 1);
1318 continue;
1320 if (skip_prefix(arg, "--disable=", &v)) {
1321 enable_service(v, 0);
1322 continue;
1324 if (skip_prefix(arg, "--allow-override=", &v)) {
1325 make_service_overridable(v, 1);
1326 continue;
1328 if (skip_prefix(arg, "--forbid-override=", &v)) {
1329 make_service_overridable(v, 0);
1330 continue;
1332 if (!strcmp(arg, "--informative-errors")) {
1333 informative_errors = 1;
1334 continue;
1336 if (!strcmp(arg, "--no-informative-errors")) {
1337 informative_errors = 0;
1338 continue;
1340 if (!strcmp(arg, "--")) {
1341 ok_paths = &argv[i+1];
1342 break;
1343 } else if (arg[0] != '-') {
1344 ok_paths = &argv[i];
1345 break;
1348 usage(daemon_usage);
1351 if (log_syslog) {
1352 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1353 set_die_routine(daemon_die);
1354 } else
1355 /* avoid splitting a message in the middle */
1356 setvbuf(stderr, NULL, _IOFBF, 4096);
1358 if (inetd_mode && (detach || group_name || user_name))
1359 die("--detach, --user and --group are incompatible with --inetd");
1361 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1362 die("--listen= and --port= are incompatible with --inetd");
1363 else if (listen_port == 0)
1364 listen_port = DEFAULT_GIT_PORT;
1366 if (group_name && !user_name)
1367 die("--group supplied without --user");
1369 if (user_name)
1370 cred = prepare_credentials(user_name, group_name);
1372 if (strict_paths && (!ok_paths || !*ok_paths))
1373 die("option --strict-paths requires a whitelist");
1375 if (base_path && !is_directory(base_path))
1376 die("base-path '%s' does not exist or is not a directory",
1377 base_path);
1379 if (inetd_mode) {
1380 if (!freopen("/dev/null", "w", stderr))
1381 die_errno("failed to redirect stderr to /dev/null");
1384 if (inetd_mode || serve_mode)
1385 return execute();
1387 if (detach) {
1388 if (daemonize())
1389 die("--detach not supported on this platform");
1392 if (pid_file)
1393 write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid());
1395 /* prepare argv for serving-processes */
1396 argv_array_push(&cld_argv, argv[0]); /* git-daemon */
1397 argv_array_push(&cld_argv, "--serve");
1398 for (i = 1; i < argc; ++i)
1399 argv_array_push(&cld_argv, argv[i]);
1401 return serve(&listen_addr, listen_port, cred);