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