Clarify syntax and role of git-add in status output
[git/jr.git] / daemon.c
blobb129b83e4026490c1e6e77861cd6f03a5007d01e
1 #include "cache.h"
2 #include "pkt-line.h"
3 #include "exec_cmd.h"
4 #include "interpolate.h"
6 #include <syslog.h>
8 #ifndef HOST_NAME_MAX
9 #define HOST_NAME_MAX 256
10 #endif
12 static int log_syslog;
13 static int verbose;
14 static int reuseaddr;
16 static const char daemon_usage[] =
17 "git-daemon [--verbose] [--syslog] [--export-all]\n"
18 " [--timeout=n] [--init-timeout=n] [--strict-paths]\n"
19 " [--base-path=path] [--user-path | --user-path=path]\n"
20 " [--interpolated-path=path]\n"
21 " [--reuseaddr] [--detach] [--pid-file=file]\n"
22 " [--[enable|disable|allow-override|forbid-override]=service]\n"
23 " [--inetd | [--listen=host_or_ipaddr] [--port=n]\n"
24 " [--user=user [--group=group]]\n"
25 " [directory...]";
27 /* List of acceptable pathname prefixes */
28 static char **ok_paths;
29 static int strict_paths;
31 /* If this is set, git-daemon-export-ok is not required */
32 static int export_all_trees;
34 /* Take all paths relative to this one if non-NULL */
35 static char *base_path;
36 static char *interpolated_path;
38 /* Flag indicating client sent extra args. */
39 static int saw_extended_args;
41 /* If defined, ~user notation is allowed and the string is inserted
42 * after ~user/. E.g. a request to git://host/~alice/frotz would
43 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
45 static const char *user_path;
47 /* Timeout, and initial timeout */
48 static unsigned int timeout;
49 static unsigned int init_timeout;
52 * Static table for now. Ugh.
53 * Feel free to make dynamic as needed.
55 #define INTERP_SLOT_HOST (0)
56 #define INTERP_SLOT_CANON_HOST (1)
57 #define INTERP_SLOT_IP (2)
58 #define INTERP_SLOT_PORT (3)
59 #define INTERP_SLOT_DIR (4)
60 #define INTERP_SLOT_PERCENT (5)
62 static struct interp interp_table[] = {
63 { "%H", 0},
64 { "%CH", 0},
65 { "%IP", 0},
66 { "%P", 0},
67 { "%D", 0},
68 { "%%", 0},
72 static void logreport(int priority, const char *err, va_list params)
74 /* We should do a single write so that it is atomic and output
75 * of several processes do not get intermingled. */
76 char buf[1024];
77 int buflen;
78 int maxlen, msglen;
80 /* sizeof(buf) should be big enough for "[pid] \n" */
81 buflen = snprintf(buf, sizeof(buf), "[%ld] ", (long) getpid());
83 maxlen = sizeof(buf) - buflen - 1; /* -1 for our own LF */
84 msglen = vsnprintf(buf + buflen, maxlen, err, params);
86 if (log_syslog) {
87 syslog(priority, "%s", buf);
88 return;
91 /* maxlen counted our own LF but also counts space given to
92 * vsnprintf for the terminating NUL. We want to make sure that
93 * we have space for our own LF and NUL after the "meat" of the
94 * message, so truncate it at maxlen - 1.
96 if (msglen > maxlen - 1)
97 msglen = maxlen - 1;
98 else if (msglen < 0)
99 msglen = 0; /* Protect against weird return values. */
100 buflen += msglen;
102 buf[buflen++] = '\n';
103 buf[buflen] = '\0';
105 write(2, buf, buflen);
108 static void logerror(const char *err, ...)
110 va_list params;
111 va_start(params, err);
112 logreport(LOG_ERR, err, params);
113 va_end(params);
116 static void loginfo(const char *err, ...)
118 va_list params;
119 if (!verbose)
120 return;
121 va_start(params, err);
122 logreport(LOG_INFO, err, params);
123 va_end(params);
126 static void NORETURN daemon_die(const char *err, va_list params)
128 logreport(LOG_ERR, err, params);
129 exit(1);
132 static int avoid_alias(char *p)
134 int sl, ndot;
137 * This resurrects the belts and suspenders paranoia check by HPA
138 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
139 * does not do getcwd() based path canonicalizations.
141 * sl becomes true immediately after seeing '/' and continues to
142 * be true as long as dots continue after that without intervening
143 * non-dot character.
145 if (!p || (*p != '/' && *p != '~'))
146 return -1;
147 sl = 1; ndot = 0;
148 p++;
150 while (1) {
151 char ch = *p++;
152 if (sl) {
153 if (ch == '.')
154 ndot++;
155 else if (ch == '/') {
156 if (ndot < 3)
157 /* reject //, /./ and /../ */
158 return -1;
159 ndot = 0;
161 else if (ch == 0) {
162 if (0 < ndot && ndot < 3)
163 /* reject /.$ and /..$ */
164 return -1;
165 return 0;
167 else
168 sl = ndot = 0;
170 else if (ch == 0)
171 return 0;
172 else if (ch == '/') {
173 sl = 1;
174 ndot = 0;
179 static char *path_ok(struct interp *itable)
181 static char rpath[PATH_MAX];
182 static char interp_path[PATH_MAX];
183 char *path;
184 char *dir;
186 dir = itable[INTERP_SLOT_DIR].value;
188 if (avoid_alias(dir)) {
189 logerror("'%s': aliased", dir);
190 return NULL;
193 if (*dir == '~') {
194 if (!user_path) {
195 logerror("'%s': User-path not allowed", dir);
196 return NULL;
198 if (*user_path) {
199 /* Got either "~alice" or "~alice/foo";
200 * rewrite them to "~alice/%s" or
201 * "~alice/%s/foo".
203 int namlen, restlen = strlen(dir);
204 char *slash = strchr(dir, '/');
205 if (!slash)
206 slash = dir + restlen;
207 namlen = slash - dir;
208 restlen -= namlen;
209 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
210 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
211 namlen, dir, user_path, restlen, slash);
212 dir = rpath;
215 else if (interpolated_path && saw_extended_args) {
216 if (*dir != '/') {
217 /* Allow only absolute */
218 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
219 return NULL;
222 interpolate(interp_path, PATH_MAX, interpolated_path,
223 interp_table, ARRAY_SIZE(interp_table));
224 loginfo("Interpolated dir '%s'", interp_path);
226 dir = interp_path;
228 else if (base_path) {
229 if (*dir != '/') {
230 /* Allow only absolute */
231 logerror("'%s': Non-absolute path denied (base-path active)", dir);
232 return NULL;
234 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
235 dir = rpath;
238 path = enter_repo(dir, strict_paths);
240 if (!path) {
241 logerror("'%s': unable to chdir or not a git archive", dir);
242 return NULL;
245 if ( ok_paths && *ok_paths ) {
246 char **pp;
247 int pathlen = strlen(path);
249 /* The validation is done on the paths after enter_repo
250 * appends optional {.git,.git/.git} and friends, but
251 * it does not use getcwd(). So if your /pub is
252 * a symlink to /mnt/pub, you can whitelist /pub and
253 * do not have to say /mnt/pub.
254 * Do not say /pub/.
256 for ( pp = ok_paths ; *pp ; pp++ ) {
257 int len = strlen(*pp);
258 if (len <= pathlen &&
259 !memcmp(*pp, path, len) &&
260 (path[len] == '\0' ||
261 (!strict_paths && path[len] == '/')))
262 return path;
265 else {
266 /* be backwards compatible */
267 if (!strict_paths)
268 return path;
271 logerror("'%s': not in whitelist", path);
272 return NULL; /* Fallthrough. Deny by default */
275 typedef int (*daemon_service_fn)(void);
276 struct daemon_service {
277 const char *name;
278 const char *config_name;
279 daemon_service_fn fn;
280 int enabled;
281 int overridable;
284 static struct daemon_service *service_looking_at;
285 static int service_enabled;
287 static int git_daemon_config(const char *var, const char *value)
289 if (!strncmp(var, "daemon.", 7) &&
290 !strcmp(var + 7, service_looking_at->config_name)) {
291 service_enabled = git_config_bool(var, value);
292 return 0;
295 /* we are not interested in parsing any other configuration here */
296 return 0;
299 static int run_service(struct interp *itable, struct daemon_service *service)
301 const char *path;
302 int enabled = service->enabled;
304 loginfo("Request %s for '%s'",
305 service->name,
306 itable[INTERP_SLOT_DIR].value);
308 if (!enabled && !service->overridable) {
309 logerror("'%s': service not enabled.", service->name);
310 errno = EACCES;
311 return -1;
314 if (!(path = path_ok(itable)))
315 return -1;
318 * Security on the cheap.
320 * We want a readable HEAD, usable "objects" directory, and
321 * a "git-daemon-export-ok" flag that says that the other side
322 * is ok with us doing this.
324 * path_ok() uses enter_repo() and does whitelist checking.
325 * We only need to make sure the repository is exported.
328 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
329 logerror("'%s': repository not exported.", path);
330 errno = EACCES;
331 return -1;
334 if (service->overridable) {
335 service_looking_at = service;
336 service_enabled = -1;
337 git_config(git_daemon_config);
338 if (0 <= service_enabled)
339 enabled = service_enabled;
341 if (!enabled) {
342 logerror("'%s': service not enabled for '%s'",
343 service->name, path);
344 errno = EACCES;
345 return -1;
349 * We'll ignore SIGTERM from now on, we have a
350 * good client.
352 signal(SIGTERM, SIG_IGN);
354 return service->fn();
357 static int upload_pack(void)
359 /* Timeout as string */
360 char timeout_buf[64];
362 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
364 /* git-upload-pack only ever reads stuff, so this is safe */
365 execl_git_cmd("upload-pack", "--strict", timeout_buf, ".", NULL);
366 return -1;
369 static int upload_archive(void)
371 execl_git_cmd("upload-archive", ".", NULL);
372 return -1;
375 static struct daemon_service daemon_service[] = {
376 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
377 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
380 static void enable_service(const char *name, int ena) {
381 int i;
382 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
383 if (!strcmp(daemon_service[i].name, name)) {
384 daemon_service[i].enabled = ena;
385 return;
388 die("No such service %s", name);
391 static void make_service_overridable(const char *name, int ena) {
392 int i;
393 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
394 if (!strcmp(daemon_service[i].name, name)) {
395 daemon_service[i].overridable = ena;
396 return;
399 die("No such service %s", name);
403 * Separate the "extra args" information as supplied by the client connection.
404 * Any resulting data is squirrelled away in the given interpolation table.
406 static void parse_extra_args(struct interp *table, char *extra_args, int buflen)
408 char *val;
409 int vallen;
410 char *end = extra_args + buflen;
412 while (extra_args < end && *extra_args) {
413 saw_extended_args = 1;
414 if (strncasecmp("host=", extra_args, 5) == 0) {
415 val = extra_args + 5;
416 vallen = strlen(val) + 1;
417 if (*val) {
418 /* Split <host>:<port> at colon. */
419 char *host = val;
420 char *port = strrchr(host, ':');
421 if (port) {
422 *port = 0;
423 port++;
424 interp_set_entry(table, INTERP_SLOT_PORT, port);
426 interp_set_entry(table, INTERP_SLOT_HOST, host);
429 /* On to the next one */
430 extra_args = val + vallen;
435 void fill_in_extra_table_entries(struct interp *itable)
437 char *hp;
440 * Replace literal host with lowercase-ized hostname.
442 hp = interp_table[INTERP_SLOT_HOST].value;
443 if (!hp)
444 return;
445 for ( ; *hp; hp++)
446 *hp = tolower(*hp);
449 * Locate canonical hostname and its IP address.
451 #ifndef NO_IPV6
453 struct addrinfo hints;
454 struct addrinfo *ai, *ai0;
455 int gai;
456 static char addrbuf[HOST_NAME_MAX + 1];
458 memset(&hints, 0, sizeof(hints));
459 hints.ai_flags = AI_CANONNAME;
461 gai = getaddrinfo(interp_table[INTERP_SLOT_HOST].value, 0, &hints, &ai0);
462 if (!gai) {
463 for (ai = ai0; ai; ai = ai->ai_next) {
464 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
466 inet_ntop(AF_INET, &sin_addr->sin_addr,
467 addrbuf, sizeof(addrbuf));
468 interp_set_entry(interp_table,
469 INTERP_SLOT_CANON_HOST, ai->ai_canonname);
470 interp_set_entry(interp_table,
471 INTERP_SLOT_IP, addrbuf);
472 break;
474 freeaddrinfo(ai0);
477 #else
479 struct hostent *hent;
480 struct sockaddr_in sa;
481 char **ap;
482 static char addrbuf[HOST_NAME_MAX + 1];
484 hent = gethostbyname(interp_table[INTERP_SLOT_HOST].value);
486 ap = hent->h_addr_list;
487 memset(&sa, 0, sizeof sa);
488 sa.sin_family = hent->h_addrtype;
489 sa.sin_port = htons(0);
490 memcpy(&sa.sin_addr, *ap, hent->h_length);
492 inet_ntop(hent->h_addrtype, &sa.sin_addr,
493 addrbuf, sizeof(addrbuf));
495 interp_set_entry(interp_table, INTERP_SLOT_CANON_HOST, hent->h_name);
496 interp_set_entry(interp_table, INTERP_SLOT_IP, addrbuf);
498 #endif
502 static int execute(struct sockaddr *addr)
504 static char line[1000];
505 int pktlen, len, i;
507 if (addr) {
508 char addrbuf[256] = "";
509 int port = -1;
511 if (addr->sa_family == AF_INET) {
512 struct sockaddr_in *sin_addr = (void *) addr;
513 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
514 port = sin_addr->sin_port;
515 #ifndef NO_IPV6
516 } else if (addr && addr->sa_family == AF_INET6) {
517 struct sockaddr_in6 *sin6_addr = (void *) addr;
519 char *buf = addrbuf;
520 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
521 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
522 strcat(buf, "]");
524 port = sin6_addr->sin6_port;
525 #endif
527 loginfo("Connection from %s:%d", addrbuf, port);
530 alarm(init_timeout ? init_timeout : timeout);
531 pktlen = packet_read_line(0, line, sizeof(line));
532 alarm(0);
534 len = strlen(line);
535 if (pktlen != len)
536 loginfo("Extended attributes (%d bytes) exist <%.*s>",
537 (int) pktlen - len,
538 (int) pktlen - len, line + len + 1);
539 if (len && line[len-1] == '\n') {
540 line[--len] = 0;
541 pktlen--;
545 * Initialize the path interpolation table for this connection.
547 interp_clear_table(interp_table, ARRAY_SIZE(interp_table));
548 interp_set_entry(interp_table, INTERP_SLOT_PERCENT, "%");
550 if (len != pktlen) {
551 parse_extra_args(interp_table, line + len + 1, pktlen - len - 1);
552 fill_in_extra_table_entries(interp_table);
555 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
556 struct daemon_service *s = &(daemon_service[i]);
557 int namelen = strlen(s->name);
558 if (!strncmp("git-", line, 4) &&
559 !strncmp(s->name, line + 4, namelen) &&
560 line[namelen + 4] == ' ') {
562 * Note: The directory here is probably context sensitive,
563 * and might depend on the actual service being performed.
565 interp_set_entry(interp_table,
566 INTERP_SLOT_DIR, line + namelen + 5);
567 return run_service(interp_table, s);
571 logerror("Protocol error: '%s'", line);
572 return -1;
577 * We count spawned/reaped separately, just to avoid any
578 * races when updating them from signals. The SIGCHLD handler
579 * will only update children_reaped, and the fork logic will
580 * only update children_spawned.
582 * MAX_CHILDREN should be a power-of-two to make the modulus
583 * operation cheap. It should also be at least twice
584 * the maximum number of connections we will ever allow.
586 #define MAX_CHILDREN 128
588 static int max_connections = 25;
590 /* These are updated by the signal handler */
591 static volatile unsigned int children_reaped;
592 static pid_t dead_child[MAX_CHILDREN];
594 /* These are updated by the main loop */
595 static unsigned int children_spawned;
596 static unsigned int children_deleted;
598 static struct child {
599 pid_t pid;
600 int addrlen;
601 struct sockaddr_storage address;
602 } live_child[MAX_CHILDREN];
604 static void add_child(int idx, pid_t pid, struct sockaddr *addr, int addrlen)
606 live_child[idx].pid = pid;
607 live_child[idx].addrlen = addrlen;
608 memcpy(&live_child[idx].address, addr, addrlen);
612 * Walk from "deleted" to "spawned", and remove child "pid".
614 * We move everything up by one, since the new "deleted" will
615 * be one higher.
617 static void remove_child(pid_t pid, unsigned deleted, unsigned spawned)
619 struct child n;
621 deleted %= MAX_CHILDREN;
622 spawned %= MAX_CHILDREN;
623 if (live_child[deleted].pid == pid) {
624 live_child[deleted].pid = -1;
625 return;
627 n = live_child[deleted];
628 for (;;) {
629 struct child m;
630 deleted = (deleted + 1) % MAX_CHILDREN;
631 if (deleted == spawned)
632 die("could not find dead child %d\n", pid);
633 m = live_child[deleted];
634 live_child[deleted] = n;
635 if (m.pid == pid)
636 return;
637 n = m;
642 * This gets called if the number of connections grows
643 * past "max_connections".
645 * We _should_ start off by searching for connections
646 * from the same IP, and if there is some address wth
647 * multiple connections, we should kill that first.
649 * As it is, we just "randomly" kill 25% of the connections,
650 * and our pseudo-random generator sucks too. I have no
651 * shame.
653 * Really, this is just a place-holder for a _real_ algorithm.
655 static void kill_some_children(int signo, unsigned start, unsigned stop)
657 start %= MAX_CHILDREN;
658 stop %= MAX_CHILDREN;
659 while (start != stop) {
660 if (!(start & 3))
661 kill(live_child[start].pid, signo);
662 start = (start + 1) % MAX_CHILDREN;
666 static void check_max_connections(void)
668 for (;;) {
669 int active;
670 unsigned spawned, reaped, deleted;
672 spawned = children_spawned;
673 reaped = children_reaped;
674 deleted = children_deleted;
676 while (deleted < reaped) {
677 pid_t pid = dead_child[deleted % MAX_CHILDREN];
678 remove_child(pid, deleted, spawned);
679 deleted++;
681 children_deleted = deleted;
683 active = spawned - deleted;
684 if (active <= max_connections)
685 break;
687 /* Kill some unstarted connections with SIGTERM */
688 kill_some_children(SIGTERM, deleted, spawned);
689 if (active <= max_connections << 1)
690 break;
692 /* If the SIGTERM thing isn't helping use SIGKILL */
693 kill_some_children(SIGKILL, deleted, spawned);
694 sleep(1);
698 static void handle(int incoming, struct sockaddr *addr, int addrlen)
700 pid_t pid = fork();
702 if (pid) {
703 unsigned idx;
705 close(incoming);
706 if (pid < 0)
707 return;
709 idx = children_spawned % MAX_CHILDREN;
710 children_spawned++;
711 add_child(idx, pid, addr, addrlen);
713 check_max_connections();
714 return;
717 dup2(incoming, 0);
718 dup2(incoming, 1);
719 close(incoming);
721 exit(execute(addr));
724 static void child_handler(int signo)
726 for (;;) {
727 int status;
728 pid_t pid = waitpid(-1, &status, WNOHANG);
730 if (pid > 0) {
731 unsigned reaped = children_reaped;
732 dead_child[reaped % MAX_CHILDREN] = pid;
733 children_reaped = reaped + 1;
734 /* XXX: Custom logging, since we don't wanna getpid() */
735 if (verbose) {
736 const char *dead = "";
737 if (!WIFEXITED(status) || WEXITSTATUS(status) > 0)
738 dead = " (with error)";
739 if (log_syslog)
740 syslog(LOG_INFO, "[%d] Disconnected%s", pid, dead);
741 else
742 fprintf(stderr, "[%d] Disconnected%s\n", pid, dead);
744 continue;
746 break;
750 static int set_reuse_addr(int sockfd)
752 int on = 1;
754 if (!reuseaddr)
755 return 0;
756 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
757 &on, sizeof(on));
760 #ifndef NO_IPV6
762 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
764 int socknum = 0, *socklist = NULL;
765 int maxfd = -1;
766 char pbuf[NI_MAXSERV];
767 struct addrinfo hints, *ai0, *ai;
768 int gai;
770 sprintf(pbuf, "%d", listen_port);
771 memset(&hints, 0, sizeof(hints));
772 hints.ai_family = AF_UNSPEC;
773 hints.ai_socktype = SOCK_STREAM;
774 hints.ai_protocol = IPPROTO_TCP;
775 hints.ai_flags = AI_PASSIVE;
777 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
778 if (gai)
779 die("getaddrinfo() failed: %s\n", gai_strerror(gai));
781 for (ai = ai0; ai; ai = ai->ai_next) {
782 int sockfd;
784 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
785 if (sockfd < 0)
786 continue;
787 if (sockfd >= FD_SETSIZE) {
788 error("too large socket descriptor.");
789 close(sockfd);
790 continue;
793 #ifdef IPV6_V6ONLY
794 if (ai->ai_family == AF_INET6) {
795 int on = 1;
796 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
797 &on, sizeof(on));
798 /* Note: error is not fatal */
800 #endif
802 if (set_reuse_addr(sockfd)) {
803 close(sockfd);
804 continue;
807 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
808 close(sockfd);
809 continue; /* not fatal */
811 if (listen(sockfd, 5) < 0) {
812 close(sockfd);
813 continue; /* not fatal */
816 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
817 socklist[socknum++] = sockfd;
819 if (maxfd < sockfd)
820 maxfd = sockfd;
823 freeaddrinfo(ai0);
825 *socklist_p = socklist;
826 return socknum;
829 #else /* NO_IPV6 */
831 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
833 struct sockaddr_in sin;
834 int sockfd;
836 memset(&sin, 0, sizeof sin);
837 sin.sin_family = AF_INET;
838 sin.sin_port = htons(listen_port);
840 if (listen_addr) {
841 /* Well, host better be an IP address here. */
842 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
843 return 0;
844 } else {
845 sin.sin_addr.s_addr = htonl(INADDR_ANY);
848 sockfd = socket(AF_INET, SOCK_STREAM, 0);
849 if (sockfd < 0)
850 return 0;
852 if (set_reuse_addr(sockfd)) {
853 close(sockfd);
854 return 0;
857 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
858 close(sockfd);
859 return 0;
862 if (listen(sockfd, 5) < 0) {
863 close(sockfd);
864 return 0;
867 *socklist_p = xmalloc(sizeof(int));
868 **socklist_p = sockfd;
869 return 1;
872 #endif
874 static int service_loop(int socknum, int *socklist)
876 struct pollfd *pfd;
877 int i;
879 pfd = xcalloc(socknum, sizeof(struct pollfd));
881 for (i = 0; i < socknum; i++) {
882 pfd[i].fd = socklist[i];
883 pfd[i].events = POLLIN;
886 signal(SIGCHLD, child_handler);
888 for (;;) {
889 int i;
891 if (poll(pfd, socknum, -1) < 0) {
892 if (errno != EINTR) {
893 error("poll failed, resuming: %s",
894 strerror(errno));
895 sleep(1);
897 continue;
900 for (i = 0; i < socknum; i++) {
901 if (pfd[i].revents & POLLIN) {
902 struct sockaddr_storage ss;
903 unsigned int sslen = sizeof(ss);
904 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
905 if (incoming < 0) {
906 switch (errno) {
907 case EAGAIN:
908 case EINTR:
909 case ECONNABORTED:
910 continue;
911 default:
912 die("accept returned %s", strerror(errno));
915 handle(incoming, (struct sockaddr *)&ss, sslen);
921 /* if any standard file descriptor is missing open it to /dev/null */
922 static void sanitize_stdfds(void)
924 int fd = open("/dev/null", O_RDWR, 0);
925 while (fd != -1 && fd < 2)
926 fd = dup(fd);
927 if (fd == -1)
928 die("open /dev/null or dup failed: %s", strerror(errno));
929 if (fd > 2)
930 close(fd);
933 static void daemonize(void)
935 switch (fork()) {
936 case 0:
937 break;
938 case -1:
939 die("fork failed: %s", strerror(errno));
940 default:
941 exit(0);
943 if (setsid() == -1)
944 die("setsid failed: %s", strerror(errno));
945 close(0);
946 close(1);
947 close(2);
948 sanitize_stdfds();
951 static void store_pid(const char *path)
953 FILE *f = fopen(path, "w");
954 if (!f)
955 die("cannot open pid file %s: %s", path, strerror(errno));
956 fprintf(f, "%d\n", getpid());
957 fclose(f);
960 static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
962 int socknum, *socklist;
964 socknum = socksetup(listen_addr, listen_port, &socklist);
965 if (socknum == 0)
966 die("unable to allocate any listen sockets on host %s port %u",
967 listen_addr, listen_port);
969 if (pass && gid &&
970 (initgroups(pass->pw_name, gid) || setgid (gid) ||
971 setuid(pass->pw_uid)))
972 die("cannot drop privileges");
974 return service_loop(socknum, socklist);
977 int main(int argc, char **argv)
979 int listen_port = 0;
980 char *listen_addr = NULL;
981 int inetd_mode = 0;
982 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
983 int detach = 0;
984 struct passwd *pass = NULL;
985 struct group *group;
986 gid_t gid = 0;
987 int i;
989 /* Without this we cannot rely on waitpid() to tell
990 * what happened to our children.
992 signal(SIGCHLD, SIG_DFL);
994 for (i = 1; i < argc; i++) {
995 char *arg = argv[i];
997 if (!strncmp(arg, "--listen=", 9)) {
998 char *p = arg + 9;
999 char *ph = listen_addr = xmalloc(strlen(arg + 9) + 1);
1000 while (*p)
1001 *ph++ = tolower(*p++);
1002 *ph = 0;
1003 continue;
1005 if (!strncmp(arg, "--port=", 7)) {
1006 char *end;
1007 unsigned long n;
1008 n = strtoul(arg+7, &end, 0);
1009 if (arg[7] && !*end) {
1010 listen_port = n;
1011 continue;
1014 if (!strcmp(arg, "--inetd")) {
1015 inetd_mode = 1;
1016 log_syslog = 1;
1017 continue;
1019 if (!strcmp(arg, "--verbose")) {
1020 verbose = 1;
1021 continue;
1023 if (!strcmp(arg, "--syslog")) {
1024 log_syslog = 1;
1025 continue;
1027 if (!strcmp(arg, "--export-all")) {
1028 export_all_trees = 1;
1029 continue;
1031 if (!strncmp(arg, "--timeout=", 10)) {
1032 timeout = atoi(arg+10);
1033 continue;
1035 if (!strncmp(arg, "--init-timeout=", 15)) {
1036 init_timeout = atoi(arg+15);
1037 continue;
1039 if (!strcmp(arg, "--strict-paths")) {
1040 strict_paths = 1;
1041 continue;
1043 if (!strncmp(arg, "--base-path=", 12)) {
1044 base_path = arg+12;
1045 continue;
1047 if (!strncmp(arg, "--interpolated-path=", 20)) {
1048 interpolated_path = arg+20;
1049 continue;
1051 if (!strcmp(arg, "--reuseaddr")) {
1052 reuseaddr = 1;
1053 continue;
1055 if (!strcmp(arg, "--user-path")) {
1056 user_path = "";
1057 continue;
1059 if (!strncmp(arg, "--user-path=", 12)) {
1060 user_path = arg + 12;
1061 continue;
1063 if (!strncmp(arg, "--pid-file=", 11)) {
1064 pid_file = arg + 11;
1065 continue;
1067 if (!strcmp(arg, "--detach")) {
1068 detach = 1;
1069 log_syslog = 1;
1070 continue;
1072 if (!strncmp(arg, "--user=", 7)) {
1073 user_name = arg + 7;
1074 continue;
1076 if (!strncmp(arg, "--group=", 8)) {
1077 group_name = arg + 8;
1078 continue;
1080 if (!strncmp(arg, "--enable=", 9)) {
1081 enable_service(arg + 9, 1);
1082 continue;
1084 if (!strncmp(arg, "--disable=", 10)) {
1085 enable_service(arg + 10, 0);
1086 continue;
1088 if (!strncmp(arg, "--allow-override=", 17)) {
1089 make_service_overridable(arg + 17, 1);
1090 continue;
1092 if (!strncmp(arg, "--forbid-override=", 18)) {
1093 make_service_overridable(arg + 18, 0);
1094 continue;
1096 if (!strcmp(arg, "--")) {
1097 ok_paths = &argv[i+1];
1098 break;
1099 } else if (arg[0] != '-') {
1100 ok_paths = &argv[i];
1101 break;
1104 usage(daemon_usage);
1107 if (inetd_mode && (group_name || user_name))
1108 die("--user and --group are incompatible with --inetd");
1110 if (inetd_mode && (listen_port || listen_addr))
1111 die("--listen= and --port= are incompatible with --inetd");
1112 else if (listen_port == 0)
1113 listen_port = DEFAULT_GIT_PORT;
1115 if (group_name && !user_name)
1116 die("--group supplied without --user");
1118 if (user_name) {
1119 pass = getpwnam(user_name);
1120 if (!pass)
1121 die("user not found - %s", user_name);
1123 if (!group_name)
1124 gid = pass->pw_gid;
1125 else {
1126 group = getgrnam(group_name);
1127 if (!group)
1128 die("group not found - %s", group_name);
1130 gid = group->gr_gid;
1134 if (log_syslog) {
1135 openlog("git-daemon", 0, LOG_DAEMON);
1136 set_die_routine(daemon_die);
1139 if (strict_paths && (!ok_paths || !*ok_paths))
1140 die("option --strict-paths requires a whitelist");
1142 if (inetd_mode) {
1143 struct sockaddr_storage ss;
1144 struct sockaddr *peer = (struct sockaddr *)&ss;
1145 socklen_t slen = sizeof(ss);
1147 freopen("/dev/null", "w", stderr);
1149 if (getpeername(0, peer, &slen))
1150 peer = NULL;
1152 return execute(peer);
1155 if (detach)
1156 daemonize();
1157 else
1158 sanitize_stdfds();
1160 if (pid_file)
1161 store_pid(pid_file);
1163 return serve(listen_addr, listen_port, pass, gid);