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