Code

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