git
/
daemon.c
1465 строк · 34.6 Кб
1#define USE_THE_REPOSITORY_VARIABLE2
3#include "git-compat-util.h"4#include "abspath.h"5#include "config.h"6#include "environment.h"7#include "path.h"8#include "pkt-line.h"9#include "protocol.h"10#include "run-command.h"11#include "setup.h"12#include "strbuf.h"13#include "string-list.h"14
15#ifdef NO_INITGROUPS16#define initgroups(x, y) (0) /* nothing */17#endif18
19static enum log_destination {20LOG_DESTINATION_UNSET = -1,21LOG_DESTINATION_NONE = 0,22LOG_DESTINATION_STDERR = 1,23LOG_DESTINATION_SYSLOG = 2,24} log_destination = LOG_DESTINATION_UNSET;25static int verbose;26static int reuseaddr;27static int informative_errors;28
29static const char daemon_usage[] =30"git daemon [--verbose] [--syslog] [--export-all]\n"
31" [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
32" [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
33" [--user-path | --user-path=<path>]\n"
34" [--interpolated-path=<path>]\n"
35" [--reuseaddr] [--pid-file=<file>]\n"
36" [--(enable|disable|allow-override|forbid-override)=<service>]\n"
37" [--access-hook=<path>]\n"
38" [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
39" [--detach] [--user=<user> [--group=<group>]]\n"
40" [--log-destination=(stderr|syslog|none)]\n"
41" [<directory>...]";42
43/* List of acceptable pathname prefixes */
44static const char **ok_paths;45static int strict_paths;46
47/* If this is set, git-daemon-export-ok is not required */
48static int export_all_trees;49
50/* Take all paths relative to this one if non-NULL */
51static const char *base_path;52static const char *interpolated_path;53static int base_path_relaxed;54
55/* If defined, ~user notation is allowed and the string is inserted
56* after ~user/. E.g. a request to git://host/~alice/frotz would
57* go to /home/alice/pub_git/frotz with --user-path=pub_git.
58*/
59static const char *user_path;60
61/* Timeout, and initial timeout */
62static unsigned int timeout;63static unsigned int init_timeout;64
65struct hostinfo {66struct strbuf hostname;67struct strbuf canon_hostname;68struct strbuf ip_address;69struct strbuf tcp_port;70unsigned int hostname_lookup_done:1;71unsigned int saw_extended_args:1;72};73#define HOSTINFO_INIT { \74.hostname = STRBUF_INIT, \75.canon_hostname = STRBUF_INIT, \76.ip_address = STRBUF_INIT, \77.tcp_port = STRBUF_INIT, \78}
79
80static void lookup_hostname(struct hostinfo *hi);81
82static const char *get_canon_hostname(struct hostinfo *hi)83{
84lookup_hostname(hi);85return hi->canon_hostname.buf;86}
87
88static const char *get_ip_address(struct hostinfo *hi)89{
90lookup_hostname(hi);91return hi->ip_address.buf;92}
93
94static void logreport(int priority, const char *err, va_list params)95{
96switch (log_destination) {97case LOG_DESTINATION_SYSLOG: {98char buf[1024];99vsnprintf(buf, sizeof(buf), err, params);100syslog(priority, "%s", buf);101break;102}103case LOG_DESTINATION_STDERR:104/*105* Since stderr is set to buffered mode, the
106* logging of different processes will not overlap
107* unless they overflow the (rather big) buffers.
108*/
109fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());110vfprintf(stderr, err, params);111fputc('\n', stderr);112fflush(stderr);113break;114case LOG_DESTINATION_NONE:115break;116case LOG_DESTINATION_UNSET:117BUG("log destination not initialized correctly");118}119}
120
121__attribute__((format (printf, 1, 2)))122static void logerror(const char *err, ...)123{
124va_list params;125va_start(params, err);126logreport(LOG_ERR, err, params);127va_end(params);128}
129
130__attribute__((format (printf, 1, 2)))131static void loginfo(const char *err, ...)132{
133va_list params;134if (!verbose)135return;136va_start(params, err);137logreport(LOG_INFO, err, params);138va_end(params);139}
140
141static void NORETURN daemon_die(const char *err, va_list params)142{
143logreport(LOG_ERR, err, params);144exit(1);145}
146
147static const char *path_ok(const char *directory, struct hostinfo *hi)148{
149static char rpath[PATH_MAX];150static char interp_path[PATH_MAX];151size_t rlen;152const char *path;153const char *dir;154
155dir = directory;156
157if (daemon_avoid_alias(dir)) {158logerror("'%s': aliased", dir);159return NULL;160}161
162if (*dir == '~') {163if (!user_path) {164logerror("'%s': User-path not allowed", dir);165return NULL;166}167if (*user_path) {168/* Got either "~alice" or "~alice/foo";169* rewrite them to "~alice/%s" or
170* "~alice/%s/foo".
171*/
172int namlen, restlen = strlen(dir);173const char *slash = strchr(dir, '/');174if (!slash)175slash = dir + restlen;176namlen = slash - dir;177restlen -= namlen;178loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);179rlen = snprintf(rpath, sizeof(rpath), "%.*s/%s%.*s",180namlen, dir, user_path, restlen, slash);181if (rlen >= sizeof(rpath)) {182logerror("user-path too large: %s", rpath);183return NULL;184}185dir = rpath;186}187}188else if (interpolated_path && hi->saw_extended_args) {189struct strbuf expanded_path = STRBUF_INIT;190const char *format = interpolated_path;191
192if (*dir != '/') {193/* Allow only absolute */194logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);195return NULL;196}197
198while (strbuf_expand_step(&expanded_path, &format)) {199if (skip_prefix(format, "%", &format))200strbuf_addch(&expanded_path, '%');201else if (skip_prefix(format, "H", &format))202strbuf_addbuf(&expanded_path, &hi->hostname);203else if (skip_prefix(format, "CH", &format))204strbuf_addstr(&expanded_path,205get_canon_hostname(hi));206else if (skip_prefix(format, "IP", &format))207strbuf_addstr(&expanded_path,208get_ip_address(hi));209else if (skip_prefix(format, "P", &format))210strbuf_addbuf(&expanded_path, &hi->tcp_port);211else if (skip_prefix(format, "D", &format))212strbuf_addstr(&expanded_path, directory);213else214strbuf_addch(&expanded_path, '%');215}216
217rlen = strlcpy(interp_path, expanded_path.buf,218sizeof(interp_path));219strbuf_release(&expanded_path);220if (rlen >= sizeof(interp_path)) {221logerror("interpolated path too large: %s",222interp_path);223return NULL;224}225
226loginfo("Interpolated dir '%s'", interp_path);227
228dir = interp_path;229}230else if (base_path) {231if (*dir != '/') {232/* Allow only absolute */233logerror("'%s': Non-absolute path denied (base-path active)", dir);234return NULL;235}236rlen = snprintf(rpath, sizeof(rpath), "%s%s", base_path, dir);237if (rlen >= sizeof(rpath)) {238logerror("base-path too large: %s", rpath);239return NULL;240}241dir = rpath;242}243
244path = enter_repo(dir, strict_paths);245if (!path && base_path && base_path_relaxed) {246/*247* if we fail and base_path_relaxed is enabled, try without
248* prefixing the base path
249*/
250dir = directory;251path = enter_repo(dir, strict_paths);252}253
254if (!path) {255logerror("'%s' does not appear to be a git repository", dir);256return NULL;257}258
259if ( ok_paths && *ok_paths ) {260const char **pp;261int pathlen = strlen(path);262
263/* The validation is done on the paths after enter_repo264* appends optional {.git,.git/.git} and friends, but
265* it does not use getcwd(). So if your /pub is
266* a symlink to /mnt/pub, you can include /pub and
267* do not have to say /mnt/pub.
268* Do not say /pub/.
269*/
270for ( pp = ok_paths ; *pp ; pp++ ) {271int len = strlen(*pp);272if (len <= pathlen &&273!memcmp(*pp, path, len) &&274(path[len] == '\0' ||275(!strict_paths && path[len] == '/')))276return path;277}278}279else {280/* be backwards compatible */281if (!strict_paths)282return path;283}284
285logerror("'%s': not in directory list", path);286return NULL; /* Fallthrough. Deny by default */287}
288
289typedef int (*daemon_service_fn)(const struct strvec *env);290struct daemon_service {291const char *name;292const char *config_name;293daemon_service_fn fn;294int enabled;295int overridable;296};297
298static int daemon_error(const char *dir, const char *msg)299{
300if (!informative_errors)301msg = "access denied or repository not exported";302packet_write_fmt(1, "ERR %s: %s", msg, dir);303return -1;304}
305
306static const char *access_hook;307
308static int run_access_hook(struct daemon_service *service, const char *dir,309const char *path, struct hostinfo *hi)310{
311struct child_process child = CHILD_PROCESS_INIT;312struct strbuf buf = STRBUF_INIT;313char *eol;314int seen_errors = 0;315
316strvec_push(&child.args, access_hook);317strvec_push(&child.args, service->name);318strvec_push(&child.args, path);319strvec_push(&child.args, hi->hostname.buf);320strvec_push(&child.args, get_canon_hostname(hi));321strvec_push(&child.args, get_ip_address(hi));322strvec_push(&child.args, hi->tcp_port.buf);323
324child.use_shell = 1;325child.no_stdin = 1;326child.no_stderr = 1;327child.out = -1;328if (start_command(&child)) {329logerror("daemon access hook '%s' failed to start",330access_hook);331goto error_return;332}333if (strbuf_read(&buf, child.out, 0) < 0) {334logerror("failed to read from pipe to daemon access hook '%s'",335access_hook);336strbuf_reset(&buf);337seen_errors = 1;338}339if (close(child.out) < 0) {340logerror("failed to close pipe to daemon access hook '%s'",341access_hook);342seen_errors = 1;343}344if (finish_command(&child))345seen_errors = 1;346
347if (!seen_errors) {348strbuf_release(&buf);349return 0;350}351
352error_return:353strbuf_ltrim(&buf);354if (!buf.len)355strbuf_addstr(&buf, "service rejected");356eol = strchr(buf.buf, '\n');357if (eol)358*eol = '\0';359errno = EACCES;360daemon_error(dir, buf.buf);361strbuf_release(&buf);362return -1;363}
364
365static int run_service(const char *dir, struct daemon_service *service,366struct hostinfo *hi, const struct strvec *env)367{
368const char *path;369int enabled = service->enabled;370struct strbuf var = STRBUF_INIT;371
372loginfo("Request %s for '%s'", service->name, dir);373
374if (!enabled && !service->overridable) {375logerror("'%s': service not enabled.", service->name);376errno = EACCES;377return daemon_error(dir, "service not enabled");378}379
380if (!(path = path_ok(dir, hi)))381return daemon_error(dir, "no such repository");382
383/*384* Security on the cheap.
385*
386* We want a readable HEAD, usable "objects" directory, and
387* a "git-daemon-export-ok" flag that says that the other side
388* is ok with us doing this.
389*
390* path_ok() uses enter_repo() and checks for included directories.
391* We only need to make sure the repository is exported.
392*/
393
394if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {395logerror("'%s': repository not exported.", path);396errno = EACCES;397return daemon_error(dir, "repository not exported");398}399
400if (service->overridable) {401strbuf_addf(&var, "daemon.%s", service->config_name);402git_config_get_bool(var.buf, &enabled);403strbuf_release(&var);404}405if (!enabled) {406logerror("'%s': service not enabled for '%s'",407service->name, path);408errno = EACCES;409return daemon_error(dir, "service not enabled");410}411
412/*413* Optionally, a hook can choose to deny access to the
414* repository depending on the phase of the moon.
415*/
416if (access_hook && run_access_hook(service, dir, path, hi))417return -1;418
419/*420* We'll ignore SIGTERM from now on, we have a
421* good client.
422*/
423signal(SIGTERM, SIG_IGN);424
425return service->fn(env);426}
427
428static void copy_to_log(int fd)429{
430struct strbuf line = STRBUF_INIT;431FILE *fp;432
433fp = fdopen(fd, "r");434if (!fp) {435logerror("fdopen of error channel failed");436close(fd);437return;438}439
440while (strbuf_getline_lf(&line, fp) != EOF) {441logerror("%s", line.buf);442strbuf_setlen(&line, 0);443}444
445strbuf_release(&line);446fclose(fp);447}
448
449static int run_service_command(struct child_process *cld)450{
451strvec_push(&cld->args, ".");452cld->git_cmd = 1;453cld->err = -1;454if (start_command(cld))455return -1;456
457close(0);458close(1);459
460copy_to_log(cld->err);461
462return finish_command(cld);463}
464
465static int upload_pack(const struct strvec *env)466{
467struct child_process cld = CHILD_PROCESS_INIT;468strvec_pushl(&cld.args, "upload-pack", "--strict", NULL);469strvec_pushf(&cld.args, "--timeout=%u", timeout);470
471strvec_pushv(&cld.env, env->v);472
473return run_service_command(&cld);474}
475
476static int upload_archive(const struct strvec *env)477{
478struct child_process cld = CHILD_PROCESS_INIT;479strvec_push(&cld.args, "upload-archive");480
481strvec_pushv(&cld.env, env->v);482
483return run_service_command(&cld);484}
485
486static int receive_pack(const struct strvec *env)487{
488struct child_process cld = CHILD_PROCESS_INIT;489strvec_push(&cld.args, "receive-pack");490
491strvec_pushv(&cld.env, env->v);492
493return run_service_command(&cld);494}
495
496static struct daemon_service daemon_service[] = {497{ "upload-archive", "uploadarch", upload_archive, 0, 1 },498{ "upload-pack", "uploadpack", upload_pack, 1, 1 },499{ "receive-pack", "receivepack", receive_pack, 0, 1 },500};501
502static void enable_service(const char *name, int ena)503{
504int i;505for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {506if (!strcmp(daemon_service[i].name, name)) {507daemon_service[i].enabled = ena;508return;509}510}511die("No such service %s", name);512}
513
514static void make_service_overridable(const char *name, int ena)515{
516int i;517for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {518if (!strcmp(daemon_service[i].name, name)) {519daemon_service[i].overridable = ena;520return;521}522}523die("No such service %s", name);524}
525
526static void parse_host_and_port(char *hostport, char **host,527char **port)528{
529if (*hostport == '[') {530char *end;531
532end = strchr(hostport, ']');533if (!end)534die("Invalid request ('[' without ']')");535*end = '\0';536*host = hostport + 1;537if (!end[1])538*port = NULL;539else if (end[1] == ':')540*port = end + 2;541else542die("Garbage after end of host part");543} else {544*host = hostport;545*port = strrchr(hostport, ':');546if (*port) {547**port = '\0';548++*port;549}550}551}
552
553/*
554* Sanitize a string from the client so that it's OK to be inserted into a
555* filesystem path. Specifically, we disallow directory separators, runs
556* of "..", and trailing and leading dots, which means that the client
557* cannot escape our base path via ".." traversal.
558*/
559static void sanitize_client(struct strbuf *out, const char *in)560{
561for (; *in; in++) {562if (is_dir_sep(*in))563continue;564if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))565continue;566strbuf_addch(out, *in);567}568
569while (out->len && out->buf[out->len - 1] == '.')570strbuf_setlen(out, out->len - 1);571}
572
573/*
574* Like sanitize_client, but we also perform any canonicalization
575* to make life easier on the admin.
576*/
577static void canonicalize_client(struct strbuf *out, const char *in)578{
579sanitize_client(out, in);580strbuf_tolower(out);581}
582
583/*
584* Read the host as supplied by the client connection.
585*
586* Returns a pointer to the character after the NUL byte terminating the host
587* argument, or 'extra_args' if there is no host argument.
588*/
589static char *parse_host_arg(struct hostinfo *hi, char *extra_args, int buflen)590{
591char *val;592int vallen;593char *end = extra_args + buflen;594
595if (extra_args < end && *extra_args) {596hi->saw_extended_args = 1;597if (strncasecmp("host=", extra_args, 5) == 0) {598val = extra_args + 5;599vallen = strlen(val) + 1;600loginfo("Extended attribute \"host\": %s", val);601if (*val) {602/* Split <host>:<port> at colon. */603char *host;604char *port;605parse_host_and_port(val, &host, &port);606if (port)607sanitize_client(&hi->tcp_port, port);608canonicalize_client(&hi->hostname, host);609hi->hostname_lookup_done = 0;610}611
612/* On to the next one */613extra_args = val + vallen;614}615if (extra_args < end && *extra_args)616die("Invalid request");617}618
619return extra_args;620}
621
622static void parse_extra_args(struct hostinfo *hi, struct strvec *env,623char *extra_args, int buflen)624{
625const char *end = extra_args + buflen;626struct strbuf git_protocol = STRBUF_INIT;627
628/* First look for the host argument */629extra_args = parse_host_arg(hi, extra_args, buflen);630
631/* Look for additional arguments places after a second NUL byte */632for (; extra_args < end; extra_args += strlen(extra_args) + 1) {633const char *arg = extra_args;634
635/*636* Parse the extra arguments, adding most to 'git_protocol'
637* which will be used to set the 'GIT_PROTOCOL' envvar in the
638* service that will be run.
639*
640* If there ends up being a particular arg in the future that
641* git-daemon needs to parse specifically (like the 'host' arg)
642* then it can be parsed here and not added to 'git_protocol'.
643*/
644if (*arg) {645if (git_protocol.len > 0)646strbuf_addch(&git_protocol, ':');647strbuf_addstr(&git_protocol, arg);648}649}650
651if (git_protocol.len > 0) {652loginfo("Extended attribute \"protocol\": %s", git_protocol.buf);653strvec_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=%s",654git_protocol.buf);655}656strbuf_release(&git_protocol);657}
658
659/*
660* Locate canonical hostname and its IP address.
661*/
662static void lookup_hostname(struct hostinfo *hi)663{
664if (!hi->hostname_lookup_done && hi->hostname.len) {665#ifndef NO_IPV6666struct addrinfo hints;667struct addrinfo *ai;668int gai;669static char addrbuf[HOST_NAME_MAX + 1];670
671memset(&hints, 0, sizeof(hints));672hints.ai_flags = AI_CANONNAME;673
674gai = getaddrinfo(hi->hostname.buf, NULL, &hints, &ai);675if (!gai) {676struct sockaddr_in *sin_addr = (void *)ai->ai_addr;677
678inet_ntop(AF_INET, &sin_addr->sin_addr,679addrbuf, sizeof(addrbuf));680strbuf_addstr(&hi->ip_address, addrbuf);681
682if (ai->ai_canonname)683sanitize_client(&hi->canon_hostname,684ai->ai_canonname);685else686strbuf_addbuf(&hi->canon_hostname,687&hi->ip_address);688
689freeaddrinfo(ai);690}691#else692struct hostent *hent;693struct sockaddr_in sa;694char **ap;695static char addrbuf[HOST_NAME_MAX + 1];696
697hent = gethostbyname(hi->hostname.buf);698if (hent) {699ap = hent->h_addr_list;700memset(&sa, 0, sizeof sa);701sa.sin_family = hent->h_addrtype;702sa.sin_port = htons(0);703memcpy(&sa.sin_addr, *ap, hent->h_length);704
705inet_ntop(hent->h_addrtype, &sa.sin_addr,706addrbuf, sizeof(addrbuf));707
708sanitize_client(&hi->canon_hostname, hent->h_name);709strbuf_addstr(&hi->ip_address, addrbuf);710}711#endif712hi->hostname_lookup_done = 1;713}714}
715
716static void hostinfo_clear(struct hostinfo *hi)717{
718strbuf_release(&hi->hostname);719strbuf_release(&hi->canon_hostname);720strbuf_release(&hi->ip_address);721strbuf_release(&hi->tcp_port);722}
723
724static void set_keep_alive(int sockfd)725{
726int ka = 1;727
728if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0) {729if (errno != ENOTSOCK)730logerror("unable to set SO_KEEPALIVE on socket: %s",731strerror(errno));732}733}
734
735static int execute(void)736{
737char *line = packet_buffer;738int pktlen, len, i;739char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");740struct hostinfo hi = HOSTINFO_INIT;741struct strvec env = STRVEC_INIT;742
743if (addr)744loginfo("Connection from %s:%s", addr, port);745
746set_keep_alive(0);747alarm(init_timeout ? init_timeout : timeout);748pktlen = packet_read(0, packet_buffer, sizeof(packet_buffer), 0);749alarm(0);750
751len = strlen(line);752if (len && line[len-1] == '\n')753line[len-1] = 0;754
755/* parse additional args hidden behind a NUL byte */756if (len != pktlen)757parse_extra_args(&hi, &env, line + len + 1, pktlen - len - 1);758
759for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {760struct daemon_service *s = &(daemon_service[i]);761const char *arg;762
763if (skip_prefix(line, "git-", &arg) &&764skip_prefix(arg, s->name, &arg) &&765*arg++ == ' ') {766/*767* Note: The directory here is probably context sensitive,
768* and might depend on the actual service being performed.
769*/
770int rc = run_service(arg, s, &hi, &env);771hostinfo_clear(&hi);772strvec_clear(&env);773return rc;774}775}776
777hostinfo_clear(&hi);778strvec_clear(&env);779logerror("Protocol error: '%s'", line);780return -1;781}
782
783static int addrcmp(const struct sockaddr_storage *s1,784const struct sockaddr_storage *s2)785{
786const struct sockaddr *sa1 = (const struct sockaddr*) s1;787const struct sockaddr *sa2 = (const struct sockaddr*) s2;788
789if (sa1->sa_family != sa2->sa_family)790return sa1->sa_family - sa2->sa_family;791if (sa1->sa_family == AF_INET)792return memcmp(&((struct sockaddr_in *)s1)->sin_addr,793&((struct sockaddr_in *)s2)->sin_addr,794sizeof(struct in_addr));795#ifndef NO_IPV6796if (sa1->sa_family == AF_INET6)797return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,798&((struct sockaddr_in6 *)s2)->sin6_addr,799sizeof(struct in6_addr));800#endif801return 0;802}
803
804static int max_connections = 32;805
806static unsigned int live_children;807
808static struct child {809struct child *next;810struct child_process cld;811struct sockaddr_storage address;812} *firstborn;813
814static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)815{
816struct child *newborn, **cradle;817
818CALLOC_ARRAY(newborn, 1);819live_children++;820memcpy(&newborn->cld, cld, sizeof(*cld));821memcpy(&newborn->address, addr, addrlen);822for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)823if (!addrcmp(&(*cradle)->address, &newborn->address))824break;825newborn->next = *cradle;826*cradle = newborn;827}
828
829/*
830* This gets called if the number of connections grows
831* past "max_connections".
832*
833* We kill the newest connection from a duplicate IP.
834*/
835static void kill_some_child(void)836{
837const struct child *blanket, *next;838
839if (!(blanket = firstborn))840return;841
842for (; (next = blanket->next); blanket = next)843if (!addrcmp(&blanket->address, &next->address)) {844kill(blanket->cld.pid, SIGTERM);845break;846}847}
848
849static void check_dead_children(void)850{
851int status;852pid_t pid;853
854struct child **cradle, *blanket;855for (cradle = &firstborn; (blanket = *cradle);)856if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {857const char *dead = "";858if (status)859dead = " (with error)";860loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);861
862/* remove the child */863*cradle = blanket->next;864live_children--;865child_process_clear(&blanket->cld);866free(blanket);867} else868cradle = &blanket->next;869}
870
871static struct strvec cld_argv = STRVEC_INIT;872static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)873{
874struct child_process cld = CHILD_PROCESS_INIT;875
876if (max_connections && live_children >= max_connections) {877kill_some_child();878sleep(1); /* give it some time to die */879check_dead_children();880if (live_children >= max_connections) {881close(incoming);882logerror("Too many children, dropping connection");883return;884}885}886
887if (addr->sa_family == AF_INET) {888char buf[128] = "";889struct sockaddr_in *sin_addr = (void *) addr;890inet_ntop(addr->sa_family, &sin_addr->sin_addr, buf, sizeof(buf));891strvec_pushf(&cld.env, "REMOTE_ADDR=%s", buf);892strvec_pushf(&cld.env, "REMOTE_PORT=%d",893ntohs(sin_addr->sin_port));894#ifndef NO_IPV6895} else if (addr->sa_family == AF_INET6) {896char buf[128] = "";897struct sockaddr_in6 *sin6_addr = (void *) addr;898inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(buf));899strvec_pushf(&cld.env, "REMOTE_ADDR=[%s]", buf);900strvec_pushf(&cld.env, "REMOTE_PORT=%d",901ntohs(sin6_addr->sin6_port));902#endif903}904
905strvec_pushv(&cld.args, cld_argv.v);906cld.in = incoming;907cld.out = dup(incoming);908
909if (start_command(&cld))910logerror("unable to fork");911else912add_child(&cld, addr, addrlen);913}
914
915static void child_handler(int signo UNUSED)916{
917/*918* Otherwise empty handler because systemcalls will get interrupted
919* upon signal receipt
920* SysV needs the handler to be rearmed
921*/
922signal(SIGCHLD, child_handler);923}
924
925static int set_reuse_addr(int sockfd)926{
927int on = 1;928
929if (!reuseaddr)930return 0;931return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,932&on, sizeof(on));933}
934
935struct socketlist {936int *list;937size_t nr;938size_t alloc;939};940
941static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)942{
943#ifdef NO_IPV6944static char ip[INET_ADDRSTRLEN];945#else946static char ip[INET6_ADDRSTRLEN];947#endif948
949switch (family) {950#ifndef NO_IPV6951case AF_INET6:952inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);953break;954#endif955case AF_INET:956inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);957break;958default:959xsnprintf(ip, sizeof(ip), "<unknown>");960}961return ip;962}
963
964#ifndef NO_IPV6965
966static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)967{
968int socknum = 0;969char pbuf[NI_MAXSERV];970struct addrinfo hints, *ai0, *ai;971int gai;972long flags;973
974xsnprintf(pbuf, sizeof(pbuf), "%d", listen_port);975memset(&hints, 0, sizeof(hints));976hints.ai_family = AF_UNSPEC;977hints.ai_socktype = SOCK_STREAM;978hints.ai_protocol = IPPROTO_TCP;979hints.ai_flags = AI_PASSIVE;980
981gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);982if (gai) {983logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));984return 0;985}986
987for (ai = ai0; ai; ai = ai->ai_next) {988int sockfd;989
990sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);991if (sockfd < 0)992continue;993if (sockfd >= FD_SETSIZE) {994logerror("Socket descriptor too large");995close(sockfd);996continue;997}998
999#ifdef IPV6_V6ONLY1000if (ai->ai_family == AF_INET6) {1001int on = 1;1002setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,1003&on, sizeof(on));1004/* Note: error is not fatal */1005}1006#endif1007
1008if (set_reuse_addr(sockfd)) {1009logerror("Could not set SO_REUSEADDR: %s", strerror(errno));1010close(sockfd);1011continue;1012}1013
1014set_keep_alive(sockfd);1015
1016if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {1017logerror("Could not bind to %s: %s",1018ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),1019strerror(errno));1020close(sockfd);1021continue; /* not fatal */1022}1023if (listen(sockfd, 5) < 0) {1024logerror("Could not listen to %s: %s",1025ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),1026strerror(errno));1027close(sockfd);1028continue; /* not fatal */1029}1030
1031flags = fcntl(sockfd, F_GETFD, 0);1032if (flags >= 0)1033fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);1034
1035ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);1036socklist->list[socklist->nr++] = sockfd;1037socknum++;1038}1039
1040freeaddrinfo(ai0);1041
1042return socknum;1043}
1044
1045#else /* NO_IPV6 */1046
1047static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)1048{
1049struct sockaddr_in sin;1050int sockfd;1051long flags;1052
1053memset(&sin, 0, sizeof sin);1054sin.sin_family = AF_INET;1055sin.sin_port = htons(listen_port);1056
1057if (listen_addr) {1058/* Well, host better be an IP address here. */1059if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)1060return 0;1061} else {1062sin.sin_addr.s_addr = htonl(INADDR_ANY);1063}1064
1065sockfd = socket(AF_INET, SOCK_STREAM, 0);1066if (sockfd < 0)1067return 0;1068
1069if (set_reuse_addr(sockfd)) {1070logerror("Could not set SO_REUSEADDR: %s", strerror(errno));1071close(sockfd);1072return 0;1073}1074
1075set_keep_alive(sockfd);1076
1077if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {1078logerror("Could not bind to %s: %s",1079ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),1080strerror(errno));1081close(sockfd);1082return 0;1083}1084
1085if (listen(sockfd, 5) < 0) {1086logerror("Could not listen to %s: %s",1087ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),1088strerror(errno));1089close(sockfd);1090return 0;1091}1092
1093flags = fcntl(sockfd, F_GETFD, 0);1094if (flags >= 0)1095fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);1096
1097ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);1098socklist->list[socklist->nr++] = sockfd;1099return 1;1100}
1101
1102#endif1103
1104static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)1105{
1106if (!listen_addr->nr)1107setup_named_sock(NULL, listen_port, socklist);1108else {1109int i, socknum;1110for (i = 0; i < listen_addr->nr; i++) {1111socknum = setup_named_sock(listen_addr->items[i].string,1112listen_port, socklist);1113
1114if (socknum == 0)1115logerror("unable to allocate any listen sockets for host %s on port %u",1116listen_addr->items[i].string, listen_port);1117}1118}1119}
1120
1121static int service_loop(struct socketlist *socklist)1122{
1123struct pollfd *pfd;1124int i;1125
1126CALLOC_ARRAY(pfd, socklist->nr);1127
1128for (i = 0; i < socklist->nr; i++) {1129pfd[i].fd = socklist->list[i];1130pfd[i].events = POLLIN;1131}1132
1133signal(SIGCHLD, child_handler);1134
1135for (;;) {1136int i;1137
1138check_dead_children();1139
1140if (poll(pfd, socklist->nr, -1) < 0) {1141if (errno != EINTR) {1142logerror("Poll failed, resuming: %s",1143strerror(errno));1144sleep(1);1145}1146continue;1147}1148
1149for (i = 0; i < socklist->nr; i++) {1150if (pfd[i].revents & POLLIN) {1151union {1152struct sockaddr sa;1153struct sockaddr_in sai;1154#ifndef NO_IPV61155struct sockaddr_in6 sai6;1156#endif1157} ss;1158socklen_t sslen = sizeof(ss);1159int incoming = accept(pfd[i].fd, &ss.sa, &sslen);1160if (incoming < 0) {1161switch (errno) {1162case EAGAIN:1163case EINTR:1164case ECONNABORTED:1165continue;1166default:1167die_errno("accept returned");1168}1169}1170handle(incoming, &ss.sa, sslen);1171}1172}1173}1174}
1175
1176#ifdef NO_POSIX_GOODIES1177
1178struct credentials;1179
1180static void drop_privileges(struct credentials *cred UNUSED)1181{
1182/* nothing */1183}
1184
1185static struct credentials *prepare_credentials(const char *user_name UNUSED,1186const char *group_name UNUSED)1187{
1188die("--user not supported on this platform");1189}
1190
1191#else1192
1193struct credentials {1194struct passwd *pass;1195gid_t gid;1196};1197
1198static void drop_privileges(struct credentials *cred)1199{
1200if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||1201setgid (cred->gid) || setuid(cred->pass->pw_uid)))1202die("cannot drop privileges");1203}
1204
1205static struct credentials *prepare_credentials(const char *user_name,1206const char *group_name)1207{
1208static struct credentials c;1209
1210c.pass = getpwnam(user_name);1211if (!c.pass)1212die("user not found - %s", user_name);1213
1214if (!group_name)1215c.gid = c.pass->pw_gid;1216else {1217struct group *group = getgrnam(group_name);1218if (!group)1219die("group not found - %s", group_name);1220
1221c.gid = group->gr_gid;1222}1223
1224return &c;1225}
1226#endif1227
1228static int serve(struct string_list *listen_addr, int listen_port,1229struct credentials *cred)1230{
1231struct socketlist socklist = { NULL, 0, 0 };1232
1233socksetup(listen_addr, listen_port, &socklist);1234if (socklist.nr == 0)1235die("unable to allocate any listen sockets on port %u",1236listen_port);1237
1238drop_privileges(cred);1239
1240loginfo("Ready to rumble");1241
1242return service_loop(&socklist);1243}
1244
1245int cmd_main(int argc, const char **argv)1246{
1247int listen_port = 0;1248struct string_list listen_addr = STRING_LIST_INIT_DUP;1249int serve_mode = 0, inetd_mode = 0;1250const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;1251int detach = 0;1252struct credentials *cred = NULL;1253int i;1254int ret;1255
1256for (i = 1; i < argc; i++) {1257const char *arg = argv[i];1258const char *v;1259
1260if (skip_prefix(arg, "--listen=", &v)) {1261string_list_append_nodup(&listen_addr, xstrdup_tolower(v));1262continue;1263}1264if (skip_prefix(arg, "--port=", &v)) {1265char *end;1266unsigned long n;1267n = strtoul(v, &end, 0);1268if (*v && !*end) {1269listen_port = n;1270continue;1271}1272}1273if (!strcmp(arg, "--serve")) {1274serve_mode = 1;1275continue;1276}1277if (!strcmp(arg, "--inetd")) {1278inetd_mode = 1;1279continue;1280}1281if (!strcmp(arg, "--verbose")) {1282verbose = 1;1283continue;1284}1285if (!strcmp(arg, "--syslog")) {1286log_destination = LOG_DESTINATION_SYSLOG;1287continue;1288}1289if (skip_prefix(arg, "--log-destination=", &v)) {1290if (!strcmp(v, "syslog")) {1291log_destination = LOG_DESTINATION_SYSLOG;1292continue;1293} else if (!strcmp(v, "stderr")) {1294log_destination = LOG_DESTINATION_STDERR;1295continue;1296} else if (!strcmp(v, "none")) {1297log_destination = LOG_DESTINATION_NONE;1298continue;1299} else1300die("unknown log destination '%s'", v);1301}1302if (!strcmp(arg, "--export-all")) {1303export_all_trees = 1;1304continue;1305}1306if (skip_prefix(arg, "--access-hook=", &v)) {1307access_hook = v;1308continue;1309}1310if (skip_prefix(arg, "--timeout=", &v)) {1311timeout = atoi(v);1312continue;1313}1314if (skip_prefix(arg, "--init-timeout=", &v)) {1315init_timeout = atoi(v);1316continue;1317}1318if (skip_prefix(arg, "--max-connections=", &v)) {1319max_connections = atoi(v);1320if (max_connections < 0)1321max_connections = 0; /* unlimited */1322continue;1323}1324if (!strcmp(arg, "--strict-paths")) {1325strict_paths = 1;1326continue;1327}1328if (skip_prefix(arg, "--base-path=", &v)) {1329base_path = v;1330continue;1331}1332if (!strcmp(arg, "--base-path-relaxed")) {1333base_path_relaxed = 1;1334continue;1335}1336if (skip_prefix(arg, "--interpolated-path=", &v)) {1337interpolated_path = v;1338continue;1339}1340if (!strcmp(arg, "--reuseaddr")) {1341reuseaddr = 1;1342continue;1343}1344if (!strcmp(arg, "--user-path")) {1345user_path = "";1346continue;1347}1348if (skip_prefix(arg, "--user-path=", &v)) {1349user_path = v;1350continue;1351}1352if (skip_prefix(arg, "--pid-file=", &v)) {1353pid_file = v;1354continue;1355}1356if (!strcmp(arg, "--detach")) {1357detach = 1;1358continue;1359}1360if (skip_prefix(arg, "--user=", &v)) {1361user_name = v;1362continue;1363}1364if (skip_prefix(arg, "--group=", &v)) {1365group_name = v;1366continue;1367}1368if (skip_prefix(arg, "--enable=", &v)) {1369enable_service(v, 1);1370continue;1371}1372if (skip_prefix(arg, "--disable=", &v)) {1373enable_service(v, 0);1374continue;1375}1376if (skip_prefix(arg, "--allow-override=", &v)) {1377make_service_overridable(v, 1);1378continue;1379}1380if (skip_prefix(arg, "--forbid-override=", &v)) {1381make_service_overridable(v, 0);1382continue;1383}1384if (!strcmp(arg, "--informative-errors")) {1385informative_errors = 1;1386continue;1387}1388if (!strcmp(arg, "--no-informative-errors")) {1389informative_errors = 0;1390continue;1391}1392if (!strcmp(arg, "--")) {1393ok_paths = &argv[i+1];1394break;1395} else if (arg[0] != '-') {1396ok_paths = &argv[i];1397break;1398}1399
1400usage(daemon_usage);1401}1402
1403if (log_destination == LOG_DESTINATION_UNSET) {1404if (inetd_mode || detach)1405log_destination = LOG_DESTINATION_SYSLOG;1406else1407log_destination = LOG_DESTINATION_STDERR;1408}1409
1410if (log_destination == LOG_DESTINATION_SYSLOG) {1411openlog("git-daemon", LOG_PID, LOG_DAEMON);1412set_die_routine(daemon_die);1413} else1414/* avoid splitting a message in the middle */1415setvbuf(stderr, NULL, _IOFBF, 4096);1416
1417if (inetd_mode && (detach || group_name || user_name))1418die("--detach, --user and --group are incompatible with --inetd");1419
1420if (inetd_mode && (listen_port || (listen_addr.nr > 0)))1421die("--listen= and --port= are incompatible with --inetd");1422else if (listen_port == 0)1423listen_port = DEFAULT_GIT_PORT;1424
1425if (group_name && !user_name)1426die("--group supplied without --user");1427
1428if (user_name)1429cred = prepare_credentials(user_name, group_name);1430
1431if (strict_paths && (!ok_paths || !*ok_paths))1432die("option --strict-paths requires '<directory>' arguments");1433
1434if (base_path && !is_directory(base_path))1435die("base-path '%s' does not exist or is not a directory",1436base_path);1437
1438if (log_destination != LOG_DESTINATION_STDERR) {1439if (!freopen("/dev/null", "w", stderr))1440die_errno("failed to redirect stderr to /dev/null");1441}1442
1443if (inetd_mode || serve_mode) {1444ret = execute();1445} else {1446if (detach) {1447if (daemonize())1448die("--detach not supported on this platform");1449}1450
1451if (pid_file)1452write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid());1453
1454/* prepare argv for serving-processes */1455strvec_push(&cld_argv, argv[0]); /* git-daemon */1456strvec_push(&cld_argv, "--serve");1457for (i = 1; i < argc; ++i)1458strvec_push(&cld_argv, argv[i]);1459
1460ret = serve(&listen_addr, listen_port, cred);1461}1462
1463string_list_clear(&listen_addr, 0);1464return ret;1465}
1466