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