User Manual: Write "Git" instead of "GIT"
[git.git] / daemon.c
blobce4800621cece33de68991b52419312803875f84
1 #include "cache.h"
2 #include "pkt-line.h"
3 #include "exec_cmd.h"
4 #include "run-command.h"
5 #include "strbuf.h"
7 #include <syslog.h>
9 #ifndef HOST_NAME_MAX
10 #define HOST_NAME_MAX 256
11 #endif
13 #ifndef NI_MAXSERV
14 #define NI_MAXSERV 32
15 #endif
17 static int log_syslog;
18 static int verbose;
19 static int reuseaddr;
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...]";
33 /* List of acceptable pathname prefixes */
34 static char **ok_paths;
35 static int strict_paths;
37 /* If this is set, git-daemon-export-ok is not required */
38 static int export_all_trees;
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;
45 /* Flag indicating client sent extra args. */
46 static int saw_extended_args;
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.
52 static const char *user_path;
54 /* Timeout, and initial timeout */
55 static unsigned int timeout;
56 static unsigned int init_timeout;
58 static char *hostname;
59 static char *canon_hostname;
60 static char *ip_address;
61 static char *tcp_port;
63 static void logreport(int priority, const char *err, va_list params)
65 if (log_syslog) {
66 char buf[1024];
67 vsnprintf(buf, sizeof(buf), err, params);
68 syslog(priority, "%s", buf);
69 } else {
71 * Since stderr is set to linebuffered mode, the
72 * logging of different processes will not overlap
74 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
75 vfprintf(stderr, err, params);
76 fputc('\n', stderr);
80 static void logerror(const char *err, ...)
82 va_list params;
83 va_start(params, err);
84 logreport(LOG_ERR, err, params);
85 va_end(params);
88 static void loginfo(const char *err, ...)
90 va_list params;
91 if (!verbose)
92 return;
93 va_start(params, err);
94 logreport(LOG_INFO, err, params);
95 va_end(params);
98 static void NORETURN daemon_die(const char *err, va_list params)
100 logreport(LOG_ERR, err, params);
101 exit(1);
104 static char *path_ok(char *directory)
106 static char rpath[PATH_MAX];
107 static char interp_path[PATH_MAX];
108 char *path;
109 char *dir;
111 dir = directory;
113 if (daemon_avoid_alias(dir)) {
114 logerror("'%s': aliased", dir);
115 return NULL;
118 if (*dir == '~') {
119 if (!user_path) {
120 logerror("'%s': User-path not allowed", dir);
121 return NULL;
123 if (*user_path) {
124 /* Got either "~alice" or "~alice/foo";
125 * rewrite them to "~alice/%s" or
126 * "~alice/%s/foo".
128 int namlen, restlen = strlen(dir);
129 char *slash = strchr(dir, '/');
130 if (!slash)
131 slash = dir + restlen;
132 namlen = slash - dir;
133 restlen -= namlen;
134 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
135 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
136 namlen, dir, user_path, restlen, slash);
137 dir = rpath;
140 else if (interpolated_path && saw_extended_args) {
141 struct strbuf expanded_path = STRBUF_INIT;
142 struct strbuf_expand_dict_entry dict[] = {
143 { "H", hostname },
144 { "CH", canon_hostname },
145 { "IP", ip_address },
146 { "P", tcp_port },
147 { "D", directory },
148 { "%", "%" },
149 { NULL }
152 if (*dir != '/') {
153 /* Allow only absolute */
154 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
155 return NULL;
158 strbuf_expand(&expanded_path, interpolated_path,
159 strbuf_expand_dict_cb, &dict);
160 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
161 strbuf_release(&expanded_path);
162 loginfo("Interpolated dir '%s'", interp_path);
164 dir = interp_path;
166 else if (base_path) {
167 if (*dir != '/') {
168 /* Allow only absolute */
169 logerror("'%s': Non-absolute path denied (base-path active)", dir);
170 return NULL;
172 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
173 dir = rpath;
176 path = enter_repo(dir, strict_paths);
177 if (!path && base_path && base_path_relaxed) {
179 * if we fail and base_path_relaxed is enabled, try without
180 * prefixing the base path
182 dir = directory;
183 path = enter_repo(dir, strict_paths);
186 if (!path) {
187 logerror("'%s' does not appear to be a git repository", dir);
188 return NULL;
191 if ( ok_paths && *ok_paths ) {
192 char **pp;
193 int pathlen = strlen(path);
195 /* The validation is done on the paths after enter_repo
196 * appends optional {.git,.git/.git} and friends, but
197 * it does not use getcwd(). So if your /pub is
198 * a symlink to /mnt/pub, you can whitelist /pub and
199 * do not have to say /mnt/pub.
200 * Do not say /pub/.
202 for ( pp = ok_paths ; *pp ; pp++ ) {
203 int len = strlen(*pp);
204 if (len <= pathlen &&
205 !memcmp(*pp, path, len) &&
206 (path[len] == '\0' ||
207 (!strict_paths && path[len] == '/')))
208 return path;
211 else {
212 /* be backwards compatible */
213 if (!strict_paths)
214 return path;
217 logerror("'%s': not in whitelist", path);
218 return NULL; /* Fallthrough. Deny by default */
221 typedef int (*daemon_service_fn)(void);
222 struct daemon_service {
223 const char *name;
224 const char *config_name;
225 daemon_service_fn fn;
226 int enabled;
227 int overridable;
230 static struct daemon_service *service_looking_at;
231 static int service_enabled;
233 static int git_daemon_config(const char *var, const char *value, void *cb)
235 if (!prefixcmp(var, "daemon.") &&
236 !strcmp(var + 7, service_looking_at->config_name)) {
237 service_enabled = git_config_bool(var, value);
238 return 0;
241 /* we are not interested in parsing any other configuration here */
242 return 0;
245 static int run_service(char *dir, struct daemon_service *service)
247 const char *path;
248 int enabled = service->enabled;
250 loginfo("Request %s for '%s'", service->name, dir);
252 if (!enabled && !service->overridable) {
253 logerror("'%s': service not enabled.", service->name);
254 errno = EACCES;
255 return -1;
258 if (!(path = path_ok(dir)))
259 return -1;
262 * Security on the cheap.
264 * We want a readable HEAD, usable "objects" directory, and
265 * a "git-daemon-export-ok" flag that says that the other side
266 * is ok with us doing this.
268 * path_ok() uses enter_repo() and does whitelist checking.
269 * We only need to make sure the repository is exported.
272 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
273 logerror("'%s': repository not exported.", path);
274 errno = EACCES;
275 return -1;
278 if (service->overridable) {
279 service_looking_at = service;
280 service_enabled = -1;
281 git_config(git_daemon_config, NULL);
282 if (0 <= service_enabled)
283 enabled = service_enabled;
285 if (!enabled) {
286 logerror("'%s': service not enabled for '%s'",
287 service->name, path);
288 errno = EACCES;
289 return -1;
293 * We'll ignore SIGTERM from now on, we have a
294 * good client.
296 signal(SIGTERM, SIG_IGN);
298 return service->fn();
301 static void copy_to_log(int fd)
303 struct strbuf line = STRBUF_INIT;
304 FILE *fp;
306 fp = fdopen(fd, "r");
307 if (fp == NULL) {
308 logerror("fdopen of error channel failed");
309 close(fd);
310 return;
313 while (strbuf_getline(&line, fp, '\n') != EOF) {
314 logerror("%s", line.buf);
315 strbuf_setlen(&line, 0);
318 strbuf_release(&line);
319 fclose(fp);
322 static int run_service_command(const char **argv)
324 struct child_process cld;
326 memset(&cld, 0, sizeof(cld));
327 cld.argv = argv;
328 cld.git_cmd = 1;
329 cld.err = -1;
330 if (start_command(&cld))
331 return -1;
333 close(0);
334 close(1);
336 copy_to_log(cld.err);
338 return finish_command(&cld);
341 static int upload_pack(void)
343 /* Timeout as string */
344 char timeout_buf[64];
345 const char *argv[] = { "upload-pack", "--strict", timeout_buf, ".", NULL };
347 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
348 return run_service_command(argv);
351 static int upload_archive(void)
353 static const char *argv[] = { "upload-archive", ".", NULL };
354 return run_service_command(argv);
357 static int receive_pack(void)
359 static const char *argv[] = { "receive-pack", ".", NULL };
360 return run_service_command(argv);
363 static struct daemon_service daemon_service[] = {
364 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
365 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
366 { "receive-pack", "receivepack", receive_pack, 0, 1 },
369 static void enable_service(const char *name, int ena)
371 int i;
372 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
373 if (!strcmp(daemon_service[i].name, name)) {
374 daemon_service[i].enabled = ena;
375 return;
378 die("No such service %s", name);
381 static void make_service_overridable(const char *name, int ena)
383 int i;
384 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
385 if (!strcmp(daemon_service[i].name, name)) {
386 daemon_service[i].overridable = ena;
387 return;
390 die("No such service %s", name);
393 static char *xstrdup_tolower(const char *str)
395 char *p, *dup = xstrdup(str);
396 for (p = dup; *p; p++)
397 *p = tolower(*p);
398 return dup;
402 * Read the host as supplied by the client connection.
404 static void parse_host_arg(char *extra_args, int buflen)
406 char *val;
407 int vallen;
408 char *end = extra_args + buflen;
410 if (extra_args < end && *extra_args) {
411 saw_extended_args = 1;
412 if (strncasecmp("host=", extra_args, 5) == 0) {
413 val = extra_args + 5;
414 vallen = strlen(val) + 1;
415 if (*val) {
416 /* Split <host>:<port> at colon. */
417 char *host = val;
418 char *port = strrchr(host, ':');
419 if (port) {
420 *port = 0;
421 port++;
422 free(tcp_port);
423 tcp_port = xstrdup(port);
425 free(hostname);
426 hostname = xstrdup_tolower(host);
429 /* On to the next one */
430 extra_args = val + vallen;
432 if (extra_args < end && *extra_args)
433 die("Invalid request");
437 * Locate canonical hostname and its IP address.
439 if (hostname) {
440 #ifndef NO_IPV6
441 struct addrinfo hints;
442 struct addrinfo *ai;
443 int gai;
444 static char addrbuf[HOST_NAME_MAX + 1];
446 memset(&hints, 0, sizeof(hints));
447 hints.ai_flags = AI_CANONNAME;
449 gai = getaddrinfo(hostname, NULL, &hints, &ai);
450 if (!gai) {
451 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
453 inet_ntop(AF_INET, &sin_addr->sin_addr,
454 addrbuf, sizeof(addrbuf));
455 free(ip_address);
456 ip_address = xstrdup(addrbuf);
458 free(canon_hostname);
459 canon_hostname = xstrdup(ai->ai_canonname ?
460 ai->ai_canonname : ip_address);
462 freeaddrinfo(ai);
464 #else
465 struct hostent *hent;
466 struct sockaddr_in sa;
467 char **ap;
468 static char addrbuf[HOST_NAME_MAX + 1];
470 hent = gethostbyname(hostname);
472 ap = hent->h_addr_list;
473 memset(&sa, 0, sizeof sa);
474 sa.sin_family = hent->h_addrtype;
475 sa.sin_port = htons(0);
476 memcpy(&sa.sin_addr, *ap, hent->h_length);
478 inet_ntop(hent->h_addrtype, &sa.sin_addr,
479 addrbuf, sizeof(addrbuf));
481 free(canon_hostname);
482 canon_hostname = xstrdup(hent->h_name);
483 free(ip_address);
484 ip_address = xstrdup(addrbuf);
485 #endif
490 static int execute(struct sockaddr *addr)
492 static char line[1000];
493 int pktlen, len, i;
495 if (addr) {
496 char addrbuf[256] = "";
497 int port = -1;
499 if (addr->sa_family == AF_INET) {
500 struct sockaddr_in *sin_addr = (void *) addr;
501 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
502 port = ntohs(sin_addr->sin_port);
503 #ifndef NO_IPV6
504 } else if (addr && addr->sa_family == AF_INET6) {
505 struct sockaddr_in6 *sin6_addr = (void *) addr;
507 char *buf = addrbuf;
508 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
509 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
510 strcat(buf, "]");
512 port = ntohs(sin6_addr->sin6_port);
513 #endif
515 loginfo("Connection from %s:%d", addrbuf, port);
516 setenv("REMOTE_ADDR", addrbuf, 1);
518 else {
519 unsetenv("REMOTE_ADDR");
522 alarm(init_timeout ? init_timeout : timeout);
523 pktlen = packet_read_line(0, line, sizeof(line));
524 alarm(0);
526 len = strlen(line);
527 if (pktlen != len)
528 loginfo("Extended attributes (%d bytes) exist <%.*s>",
529 (int) pktlen - len,
530 (int) pktlen - len, line + len + 1);
531 if (len && line[len-1] == '\n') {
532 line[--len] = 0;
533 pktlen--;
536 free(hostname);
537 free(canon_hostname);
538 free(ip_address);
539 free(tcp_port);
540 hostname = canon_hostname = ip_address = tcp_port = NULL;
542 if (len != pktlen)
543 parse_host_arg(line + len + 1, pktlen - len - 1);
545 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
546 struct daemon_service *s = &(daemon_service[i]);
547 int namelen = strlen(s->name);
548 if (!prefixcmp(line, "git-") &&
549 !strncmp(s->name, line + 4, namelen) &&
550 line[namelen + 4] == ' ') {
552 * Note: The directory here is probably context sensitive,
553 * and might depend on the actual service being performed.
555 return run_service(line + namelen + 5, s);
559 logerror("Protocol error: '%s'", line);
560 return -1;
563 static int max_connections = 32;
565 static unsigned int live_children;
567 static struct child {
568 struct child *next;
569 pid_t pid;
570 struct sockaddr_storage address;
571 } *firstborn;
573 static void add_child(pid_t pid, struct sockaddr *addr, int addrlen)
575 struct child *newborn, **cradle;
578 * This must be xcalloc() -- we'll compare the whole sockaddr_storage
579 * but individual address may be shorter.
581 newborn = xcalloc(1, sizeof(*newborn));
582 live_children++;
583 newborn->pid = pid;
584 memcpy(&newborn->address, addr, addrlen);
585 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
586 if (!memcmp(&(*cradle)->address, &newborn->address,
587 sizeof(newborn->address)))
588 break;
589 newborn->next = *cradle;
590 *cradle = newborn;
593 static void remove_child(pid_t pid)
595 struct child **cradle, *blanket;
597 for (cradle = &firstborn; (blanket = *cradle); cradle = &blanket->next)
598 if (blanket->pid == pid) {
599 *cradle = blanket->next;
600 live_children--;
601 free(blanket);
602 break;
607 * This gets called if the number of connections grows
608 * past "max_connections".
610 * We kill the newest connection from a duplicate IP.
612 static void kill_some_child(void)
614 const struct child *blanket, *next;
616 if (!(blanket = firstborn))
617 return;
619 for (; (next = blanket->next); blanket = next)
620 if (!memcmp(&blanket->address, &next->address,
621 sizeof(next->address))) {
622 kill(blanket->pid, SIGTERM);
623 break;
627 static void check_dead_children(void)
629 int status;
630 pid_t pid;
632 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
633 const char *dead = "";
634 remove_child(pid);
635 if (!WIFEXITED(status) || (WEXITSTATUS(status) > 0))
636 dead = " (with error)";
637 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
641 static void handle(int incoming, struct sockaddr *addr, int addrlen)
643 pid_t pid;
645 if (max_connections && live_children >= max_connections) {
646 kill_some_child();
647 sleep(1); /* give it some time to die */
648 check_dead_children();
649 if (live_children >= max_connections) {
650 close(incoming);
651 logerror("Too many children, dropping connection");
652 return;
656 if ((pid = fork())) {
657 close(incoming);
658 if (pid < 0) {
659 logerror("Couldn't fork %s", strerror(errno));
660 return;
663 add_child(pid, addr, addrlen);
664 return;
667 dup2(incoming, 0);
668 dup2(incoming, 1);
669 close(incoming);
671 exit(execute(addr));
674 static void child_handler(int signo)
677 * Otherwise empty handler because systemcalls will get interrupted
678 * upon signal receipt
679 * SysV needs the handler to be rearmed
681 signal(SIGCHLD, child_handler);
684 static int set_reuse_addr(int sockfd)
686 int on = 1;
688 if (!reuseaddr)
689 return 0;
690 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
691 &on, sizeof(on));
694 #ifndef NO_IPV6
696 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
698 int socknum = 0, *socklist = NULL;
699 int maxfd = -1;
700 char pbuf[NI_MAXSERV];
701 struct addrinfo hints, *ai0, *ai;
702 int gai;
703 long flags;
705 sprintf(pbuf, "%d", listen_port);
706 memset(&hints, 0, sizeof(hints));
707 hints.ai_family = AF_UNSPEC;
708 hints.ai_socktype = SOCK_STREAM;
709 hints.ai_protocol = IPPROTO_TCP;
710 hints.ai_flags = AI_PASSIVE;
712 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
713 if (gai)
714 die("getaddrinfo() failed: %s", gai_strerror(gai));
716 for (ai = ai0; ai; ai = ai->ai_next) {
717 int sockfd;
719 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
720 if (sockfd < 0)
721 continue;
722 if (sockfd >= FD_SETSIZE) {
723 logerror("Socket descriptor too large");
724 close(sockfd);
725 continue;
728 #ifdef IPV6_V6ONLY
729 if (ai->ai_family == AF_INET6) {
730 int on = 1;
731 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
732 &on, sizeof(on));
733 /* Note: error is not fatal */
735 #endif
737 if (set_reuse_addr(sockfd)) {
738 close(sockfd);
739 continue;
742 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
743 close(sockfd);
744 continue; /* not fatal */
746 if (listen(sockfd, 5) < 0) {
747 close(sockfd);
748 continue; /* not fatal */
751 flags = fcntl(sockfd, F_GETFD, 0);
752 if (flags >= 0)
753 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
755 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
756 socklist[socknum++] = sockfd;
758 if (maxfd < sockfd)
759 maxfd = sockfd;
762 freeaddrinfo(ai0);
764 *socklist_p = socklist;
765 return socknum;
768 #else /* NO_IPV6 */
770 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
772 struct sockaddr_in sin;
773 int sockfd;
774 long flags;
776 memset(&sin, 0, sizeof sin);
777 sin.sin_family = AF_INET;
778 sin.sin_port = htons(listen_port);
780 if (listen_addr) {
781 /* Well, host better be an IP address here. */
782 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
783 return 0;
784 } else {
785 sin.sin_addr.s_addr = htonl(INADDR_ANY);
788 sockfd = socket(AF_INET, SOCK_STREAM, 0);
789 if (sockfd < 0)
790 return 0;
792 if (set_reuse_addr(sockfd)) {
793 close(sockfd);
794 return 0;
797 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
798 close(sockfd);
799 return 0;
802 if (listen(sockfd, 5) < 0) {
803 close(sockfd);
804 return 0;
807 flags = fcntl(sockfd, F_GETFD, 0);
808 if (flags >= 0)
809 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
811 *socklist_p = xmalloc(sizeof(int));
812 **socklist_p = sockfd;
813 return 1;
816 #endif
818 static int service_loop(int socknum, int *socklist)
820 struct pollfd *pfd;
821 int i;
823 pfd = xcalloc(socknum, sizeof(struct pollfd));
825 for (i = 0; i < socknum; i++) {
826 pfd[i].fd = socklist[i];
827 pfd[i].events = POLLIN;
830 signal(SIGCHLD, child_handler);
832 for (;;) {
833 int i;
835 check_dead_children();
837 if (poll(pfd, socknum, -1) < 0) {
838 if (errno != EINTR) {
839 logerror("Poll failed, resuming: %s",
840 strerror(errno));
841 sleep(1);
843 continue;
846 for (i = 0; i < socknum; i++) {
847 if (pfd[i].revents & POLLIN) {
848 struct sockaddr_storage ss;
849 unsigned int sslen = sizeof(ss);
850 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
851 if (incoming < 0) {
852 switch (errno) {
853 case EAGAIN:
854 case EINTR:
855 case ECONNABORTED:
856 continue;
857 default:
858 die_errno("accept returned");
861 handle(incoming, (struct sockaddr *)&ss, sslen);
867 /* if any standard file descriptor is missing open it to /dev/null */
868 static void sanitize_stdfds(void)
870 int fd = open("/dev/null", O_RDWR, 0);
871 while (fd != -1 && fd < 2)
872 fd = dup(fd);
873 if (fd == -1)
874 die_errno("open /dev/null or dup failed");
875 if (fd > 2)
876 close(fd);
879 static void daemonize(void)
881 switch (fork()) {
882 case 0:
883 break;
884 case -1:
885 die_errno("fork failed");
886 default:
887 exit(0);
889 if (setsid() == -1)
890 die_errno("setsid failed");
891 close(0);
892 close(1);
893 close(2);
894 sanitize_stdfds();
897 static void store_pid(const char *path)
899 FILE *f = fopen(path, "w");
900 if (!f)
901 die_errno("cannot open pid file '%s'", path);
902 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
903 die_errno("failed to write pid file '%s'", path);
906 static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
908 int socknum, *socklist;
910 socknum = socksetup(listen_addr, listen_port, &socklist);
911 if (socknum == 0)
912 die("unable to allocate any listen sockets on host %s port %u",
913 listen_addr, listen_port);
915 if (pass && gid &&
916 (initgroups(pass->pw_name, gid) || setgid (gid) ||
917 setuid(pass->pw_uid)))
918 die("cannot drop privileges");
920 return service_loop(socknum, socklist);
923 int main(int argc, char **argv)
925 int listen_port = 0;
926 char *listen_addr = NULL;
927 int inetd_mode = 0;
928 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
929 int detach = 0;
930 struct passwd *pass = NULL;
931 struct group *group;
932 gid_t gid = 0;
933 int i;
935 git_extract_argv0_path(argv[0]);
937 for (i = 1; i < argc; i++) {
938 char *arg = argv[i];
940 if (!prefixcmp(arg, "--listen=")) {
941 listen_addr = xstrdup_tolower(arg + 9);
942 continue;
944 if (!prefixcmp(arg, "--port=")) {
945 char *end;
946 unsigned long n;
947 n = strtoul(arg+7, &end, 0);
948 if (arg[7] && !*end) {
949 listen_port = n;
950 continue;
953 if (!strcmp(arg, "--inetd")) {
954 inetd_mode = 1;
955 log_syslog = 1;
956 continue;
958 if (!strcmp(arg, "--verbose")) {
959 verbose = 1;
960 continue;
962 if (!strcmp(arg, "--syslog")) {
963 log_syslog = 1;
964 continue;
966 if (!strcmp(arg, "--export-all")) {
967 export_all_trees = 1;
968 continue;
970 if (!prefixcmp(arg, "--timeout=")) {
971 timeout = atoi(arg+10);
972 continue;
974 if (!prefixcmp(arg, "--init-timeout=")) {
975 init_timeout = atoi(arg+15);
976 continue;
978 if (!prefixcmp(arg, "--max-connections=")) {
979 max_connections = atoi(arg+18);
980 if (max_connections < 0)
981 max_connections = 0; /* unlimited */
982 continue;
984 if (!strcmp(arg, "--strict-paths")) {
985 strict_paths = 1;
986 continue;
988 if (!prefixcmp(arg, "--base-path=")) {
989 base_path = arg+12;
990 continue;
992 if (!strcmp(arg, "--base-path-relaxed")) {
993 base_path_relaxed = 1;
994 continue;
996 if (!prefixcmp(arg, "--interpolated-path=")) {
997 interpolated_path = arg+20;
998 continue;
1000 if (!strcmp(arg, "--reuseaddr")) {
1001 reuseaddr = 1;
1002 continue;
1004 if (!strcmp(arg, "--user-path")) {
1005 user_path = "";
1006 continue;
1008 if (!prefixcmp(arg, "--user-path=")) {
1009 user_path = arg + 12;
1010 continue;
1012 if (!prefixcmp(arg, "--pid-file=")) {
1013 pid_file = arg + 11;
1014 continue;
1016 if (!strcmp(arg, "--detach")) {
1017 detach = 1;
1018 log_syslog = 1;
1019 continue;
1021 if (!prefixcmp(arg, "--user=")) {
1022 user_name = arg + 7;
1023 continue;
1025 if (!prefixcmp(arg, "--group=")) {
1026 group_name = arg + 8;
1027 continue;
1029 if (!prefixcmp(arg, "--enable=")) {
1030 enable_service(arg + 9, 1);
1031 continue;
1033 if (!prefixcmp(arg, "--disable=")) {
1034 enable_service(arg + 10, 0);
1035 continue;
1037 if (!prefixcmp(arg, "--allow-override=")) {
1038 make_service_overridable(arg + 17, 1);
1039 continue;
1041 if (!prefixcmp(arg, "--forbid-override=")) {
1042 make_service_overridable(arg + 18, 0);
1043 continue;
1045 if (!strcmp(arg, "--")) {
1046 ok_paths = &argv[i+1];
1047 break;
1048 } else if (arg[0] != '-') {
1049 ok_paths = &argv[i];
1050 break;
1053 usage(daemon_usage);
1056 if (log_syslog) {
1057 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1058 set_die_routine(daemon_die);
1059 } else
1060 /* avoid splitting a message in the middle */
1061 setvbuf(stderr, NULL, _IOLBF, 0);
1063 if (inetd_mode && (group_name || user_name))
1064 die("--user and --group are incompatible with --inetd");
1066 if (inetd_mode && (listen_port || listen_addr))
1067 die("--listen= and --port= are incompatible with --inetd");
1068 else if (listen_port == 0)
1069 listen_port = DEFAULT_GIT_PORT;
1071 if (group_name && !user_name)
1072 die("--group supplied without --user");
1074 if (user_name) {
1075 pass = getpwnam(user_name);
1076 if (!pass)
1077 die("user not found - %s", user_name);
1079 if (!group_name)
1080 gid = pass->pw_gid;
1081 else {
1082 group = getgrnam(group_name);
1083 if (!group)
1084 die("group not found - %s", group_name);
1086 gid = group->gr_gid;
1090 if (strict_paths && (!ok_paths || !*ok_paths))
1091 die("option --strict-paths requires a whitelist");
1093 if (base_path && !is_directory(base_path))
1094 die("base-path '%s' does not exist or is not a directory",
1095 base_path);
1097 if (inetd_mode) {
1098 struct sockaddr_storage ss;
1099 struct sockaddr *peer = (struct sockaddr *)&ss;
1100 socklen_t slen = sizeof(ss);
1102 if (!freopen("/dev/null", "w", stderr))
1103 die_errno("failed to redirect stderr to /dev/null");
1105 if (getpeername(0, peer, &slen))
1106 peer = NULL;
1108 return execute(peer);
1111 if (detach) {
1112 daemonize();
1113 loginfo("Ready to rumble");
1115 else
1116 sanitize_stdfds();
1118 if (pid_file)
1119 store_pid(pid_file);
1121 return serve(listen_addr, listen_port, pass, gid);