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