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