Merge branch 'cb/git-daemon-tests'
[git/git.git] / daemon.c
CommitLineData
979e32fa 1#include "cache.h"
85023577 2#include "pkt-line.h"
77cb17e9 3#include "exec_cmd.h"
5d87dd4f
JS
4#include "run-command.h"
5#include "strbuf.h"
3a3a29c1 6#include "string-list.h"
f8ff0c06 7
695dffe2
JS
8#ifndef HOST_NAME_MAX
9#define HOST_NAME_MAX 256
10#endif
11
415e7b87
PW
12#ifndef NI_MAXSERV
13#define NI_MAXSERV 32
14#endif
15
2844923d
MD
16#ifdef NO_INITGROUPS
17#define initgroups(x, y) (0) /* nothing */
18#endif
19
9048fe1c 20static int log_syslog;
f8ff0c06 21static int verbose;
1955fabf 22static int reuseaddr;
d5570f4d 23static int informative_errors;
f8ff0c06 24
960deccb 25static const char daemon_usage[] =
1b1dd23f 26"git daemon [--verbose] [--syslog] [--export-all]\n"
62b4698e
ŠN
27" [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
28" [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
29" [--user-path | --user-path=<path>]\n"
30" [--interpolated-path=<path>]\n"
9cddf56e 31" [--reuseaddr] [--pid-file=<file>]\n"
62b4698e
ŠN
32" [--(enable|disable|allow-override|forbid-override)=<service>]\n"
33" [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
9cddf56e 34" [--detach] [--user=<user> [--group=<group>]]\n"
62b4698e 35" [<directory>...]";
4ae95682
PA
36
37/* List of acceptable pathname prefixes */
96f1e58f
DR
38static char **ok_paths;
39static int strict_paths;
4ae95682
PA
40
41/* If this is set, git-daemon-export-ok is not required */
96f1e58f 42static int export_all_trees;
f8ff0c06 43
b21c31c9 44/* Take all paths relative to this one if non-NULL */
96f1e58f 45static char *base_path;
49ba83fb 46static char *interpolated_path;
73a7a656 47static int base_path_relaxed;
49ba83fb
JL
48
49/* Flag indicating client sent extra args. */
50static int saw_extended_args;
b21c31c9 51
603968d2
JH
52/* If defined, ~user notation is allowed and the string is inserted
53 * after ~user/. E.g. a request to git://host/~alice/frotz would
54 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
55 */
96f1e58f 56static const char *user_path;
603968d2 57
960deccb 58/* Timeout, and initial timeout */
96f1e58f
DR
59static unsigned int timeout;
60static unsigned int init_timeout;
f8ff0c06 61
9d7ca667
RS
62static char *hostname;
63static char *canon_hostname;
64static char *ip_address;
65static char *tcp_port;
49ba83fb 66
9048fe1c 67static void logreport(int priority, const char *err, va_list params)
f8ff0c06 68{
9048fe1c 69 if (log_syslog) {
6a992e9e
SB
70 char buf[1024];
71 vsnprintf(buf, sizeof(buf), err, params);
9048fe1c 72 syslog(priority, "%s", buf);
460c2010
JH
73 } else {
74 /*
48cfaea1 75 * Since stderr is set to buffered mode, the
6a992e9e 76 * logging of different processes will not overlap
48cfaea1 77 * unless they overflow the (rather big) buffers.
6a992e9e 78 */
85e72830 79 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
6a992e9e
SB
80 vfprintf(stderr, err, params);
81 fputc('\n', stderr);
48cfaea1 82 fflush(stderr);
6a992e9e 83 }
f8ff0c06
PB
84}
85
28bea9e5 86__attribute__((format (printf, 1, 2)))
cdda4745 87static void logerror(const char *err, ...)
f8ff0c06
PB
88{
89 va_list params;
90 va_start(params, err);
9048fe1c 91 logreport(LOG_ERR, err, params);
f8ff0c06
PB
92 va_end(params);
93}
94
28bea9e5 95__attribute__((format (printf, 1, 2)))
cdda4745 96static void loginfo(const char *err, ...)
f8ff0c06
PB
97{
98 va_list params;
99 if (!verbose)
100 return;
101 va_start(params, err);
9048fe1c 102 logreport(LOG_INFO, err, params);
f8ff0c06
PB
103 va_end(params);
104}
a87e8be2 105
ad8b4f56
ML
106static void NORETURN daemon_die(const char *err, va_list params)
107{
108 logreport(LOG_ERR, err, params);
109 exit(1);
110}
111
1c64b48e 112static const char *path_ok(char *directory)
4ae95682 113{
603968d2 114 static char rpath[PATH_MAX];
49ba83fb 115 static char interp_path[PATH_MAX];
1c64b48e 116 const char *path;
49ba83fb
JL
117 char *dir;
118
9d7ca667 119 dir = directory;
d79374c7 120
34b6cb8b 121 if (daemon_avoid_alias(dir)) {
d79374c7
JH
122 logerror("'%s': aliased", dir);
123 return NULL;
124 }
125
603968d2
JH
126 if (*dir == '~') {
127 if (!user_path) {
128 logerror("'%s': User-path not allowed", dir);
129 return NULL;
130 }
131 if (*user_path) {
132 /* Got either "~alice" or "~alice/foo";
133 * rewrite them to "~alice/%s" or
134 * "~alice/%s/foo".
135 */
136 int namlen, restlen = strlen(dir);
137 char *slash = strchr(dir, '/');
138 if (!slash)
139 slash = dir + restlen;
140 namlen = slash - dir;
141 restlen -= namlen;
142 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
143 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
144 namlen, dir, user_path, restlen, slash);
145 dir = rpath;
146 }
147 }
49ba83fb 148 else if (interpolated_path && saw_extended_args) {
9d7ca667 149 struct strbuf expanded_path = STRBUF_INIT;
66dbfd55
GV
150 struct strbuf_expand_dict_entry dict[6];
151
152 dict[0].placeholder = "H"; dict[0].value = hostname;
153 dict[1].placeholder = "CH"; dict[1].value = canon_hostname;
154 dict[2].placeholder = "IP"; dict[2].value = ip_address;
155 dict[3].placeholder = "P"; dict[3].value = tcp_port;
156 dict[4].placeholder = "D"; dict[4].value = directory;
157 dict[5].placeholder = NULL; dict[5].value = NULL;
49ba83fb
JL
158 if (*dir != '/') {
159 /* Allow only absolute */
160 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
161 return NULL;
162 }
163
9d7ca667
RS
164 strbuf_expand(&expanded_path, interpolated_path,
165 strbuf_expand_dict_cb, &dict);
166 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
167 strbuf_release(&expanded_path);
49ba83fb
JL
168 loginfo("Interpolated dir '%s'", interp_path);
169
170 dir = interp_path;
171 }
603968d2
JH
172 else if (base_path) {
173 if (*dir != '/') {
174 /* Allow only absolute */
1fda3d55 175 logerror("'%s': Non-absolute path denied (base-path active)", dir);
b21c31c9
PB
176 return NULL;
177 }
49ba83fb
JL
178 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
179 dir = rpath;
b21c31c9
PB
180 }
181
a583971f
RS
182 path = enter_repo(dir, strict_paths);
183 if (!path && base_path && base_path_relaxed) {
73a7a656
JA
184 /*
185 * if we fail and base_path_relaxed is enabled, try without
186 * prefixing the base path
187 */
a583971f
RS
188 dir = directory;
189 path = enter_repo(dir, strict_paths);
190 }
3e04c62d 191
4dbd1352 192 if (!path) {
05ac6b34 193 logerror("'%s' does not appear to be a git repository", dir);
4dbd1352 194 return NULL;
4ae95682
PA
195 }
196
197 if ( ok_paths && *ok_paths ) {
ce335fe0 198 char **pp;
4dbd1352 199 int pathlen = strlen(path);
4ae95682 200
ce335fe0 201 /* The validation is done on the paths after enter_repo
a6080a0a 202 * appends optional {.git,.git/.git} and friends, but
d79374c7
JH
203 * it does not use getcwd(). So if your /pub is
204 * a symlink to /mnt/pub, you can whitelist /pub and
205 * do not have to say /mnt/pub.
206 * Do not say /pub/.
ce335fe0 207 */
4ae95682
PA
208 for ( pp = ok_paths ; *pp ; pp++ ) {
209 int len = strlen(*pp);
ce335fe0
JH
210 if (len <= pathlen &&
211 !memcmp(*pp, path, len) &&
212 (path[len] == '\0' ||
213 (!strict_paths && path[len] == '/')))
214 return path;
4ae95682 215 }
4dbd1352
AE
216 }
217 else {
218 /* be backwards compatible */
219 if (!strict_paths)
220 return path;
4ae95682
PA
221 }
222
4dbd1352
AE
223 logerror("'%s': not in whitelist", path);
224 return NULL; /* Fallthrough. Deny by default */
4ae95682 225}
a87e8be2 226
d819e4e6
JH
227typedef int (*daemon_service_fn)(void);
228struct daemon_service {
229 const char *name;
230 const char *config_name;
231 daemon_service_fn fn;
232 int enabled;
233 int overridable;
234};
235
236static struct daemon_service *service_looking_at;
237static int service_enabled;
238
ef90d6d4 239static int git_daemon_config(const char *var, const char *value, void *cb)
d819e4e6 240{
cc44c765 241 if (!prefixcmp(var, "daemon.") &&
d819e4e6
JH
242 !strcmp(var + 7, service_looking_at->config_name)) {
243 service_enabled = git_config_bool(var, value);
244 return 0;
245 }
246
247 /* we are not interested in parsing any other configuration here */
248 return 0;
249}
250
d5570f4d
JK
251static int daemon_error(const char *dir, const char *msg)
252{
253 if (!informative_errors)
254 msg = "access denied or repository not exported";
255 packet_write(1, "ERR %s: %s", msg, dir);
256 return -1;
257}
258
a47551c3 259static int run_service(char *dir, struct daemon_service *service)
a87e8be2 260{
4dbd1352 261 const char *path;
d819e4e6
JH
262 int enabled = service->enabled;
263
a47551c3 264 loginfo("Request %s for '%s'", service->name, dir);
4dbd1352 265
d819e4e6
JH
266 if (!enabled && !service->overridable) {
267 logerror("'%s': service not enabled.", service->name);
268 errno = EACCES;
d5570f4d 269 return daemon_error(dir, "service not enabled");
d819e4e6 270 }
4ae95682 271
a47551c3 272 if (!(path = path_ok(dir)))
d5570f4d 273 return daemon_error(dir, "no such repository");
47888f0f 274
a87e8be2
LT
275 /*
276 * Security on the cheap.
277 *
a935c397 278 * We want a readable HEAD, usable "objects" directory, and
a87e8be2
LT
279 * a "git-daemon-export-ok" flag that says that the other side
280 * is ok with us doing this.
4dbd1352
AE
281 *
282 * path_ok() uses enter_repo() and does whitelist checking.
283 * We only need to make sure the repository is exported.
a87e8be2 284 */
4dbd1352 285
3e04c62d 286 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
4dbd1352 287 logerror("'%s': repository not exported.", path);
3e04c62d 288 errno = EACCES;
d5570f4d 289 return daemon_error(dir, "repository not exported");
3e04c62d
PA
290 }
291
d819e4e6
JH
292 if (service->overridable) {
293 service_looking_at = service;
294 service_enabled = -1;
ef90d6d4 295 git_config(git_daemon_config, NULL);
d819e4e6
JH
296 if (0 <= service_enabled)
297 enabled = service_enabled;
298 }
299 if (!enabled) {
300 logerror("'%s': service not enabled for '%s'",
301 service->name, path);
302 errno = EACCES;
d5570f4d 303 return daemon_error(dir, "service not enabled");
d819e4e6
JH
304 }
305
02d57da4
LT
306 /*
307 * We'll ignore SIGTERM from now on, we have a
308 * good client.
309 */
310 signal(SIGTERM, SIG_IGN);
311
d819e4e6
JH
312 return service->fn();
313}
314
5d87dd4f
JS
315static void copy_to_log(int fd)
316{
317 struct strbuf line = STRBUF_INIT;
318 FILE *fp;
319
320 fp = fdopen(fd, "r");
321 if (fp == NULL) {
322 logerror("fdopen of error channel failed");
323 close(fd);
324 return;
325 }
326
327 while (strbuf_getline(&line, fp, '\n') != EOF) {
328 logerror("%s", line.buf);
329 strbuf_setlen(&line, 0);
330 }
331
332 strbuf_release(&line);
333 fclose(fp);
334}
335
336static int run_service_command(const char **argv)
337{
338 struct child_process cld;
339
340 memset(&cld, 0, sizeof(cld));
341 cld.argv = argv;
342 cld.git_cmd = 1;
343 cld.err = -1;
344 if (start_command(&cld))
345 return -1;
346
347 close(0);
348 close(1);
349
350 copy_to_log(cld.err);
351
352 return finish_command(&cld);
353}
354
d819e4e6
JH
355static int upload_pack(void)
356{
357 /* Timeout as string */
358 char timeout_buf[64];
66dbfd55
GV
359 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
360
361 argv[2] = timeout_buf;
d819e4e6 362
960deccb 363 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
5d87dd4f 364 return run_service_command(argv);
a87e8be2
LT
365}
366
39345a21
FBH
367static int upload_archive(void)
368{
5d87dd4f
JS
369 static const char *argv[] = { "upload-archive", ".", NULL };
370 return run_service_command(argv);
39345a21
FBH
371}
372
4b3b1e1e
LT
373static int receive_pack(void)
374{
5d87dd4f
JS
375 static const char *argv[] = { "receive-pack", ".", NULL };
376 return run_service_command(argv);
4b3b1e1e
LT
377}
378
d819e4e6 379static struct daemon_service daemon_service[] = {
39345a21 380 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
d819e4e6 381 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
4b3b1e1e 382 { "receive-pack", "receivepack", receive_pack, 0, 1 },
d819e4e6
JH
383};
384
f3fa1838
JH
385static void enable_service(const char *name, int ena)
386{
d819e4e6
JH
387 int i;
388 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
389 if (!strcmp(daemon_service[i].name, name)) {
390 daemon_service[i].enabled = ena;
391 return;
392 }
393 }
394 die("No such service %s", name);
395}
396
f3fa1838
JH
397static void make_service_overridable(const char *name, int ena)
398{
d819e4e6
JH
399 int i;
400 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
401 if (!strcmp(daemon_service[i].name, name)) {
402 daemon_service[i].overridable = ena;
403 return;
404 }
405 }
406 die("No such service %s", name);
407}
408
6720e95b
RS
409static char *xstrdup_tolower(const char *str)
410{
411 char *p, *dup = xstrdup(str);
412 for (p = dup; *p; p++)
413 *p = tolower(*p);
414 return dup;
415}
416
e8dbd76d
IL
417static void parse_host_and_port(char *hostport, char **host,
418 char **port)
419{
420 if (*hostport == '[') {
421 char *end;
422
423 end = strchr(hostport, ']');
424 if (!end)
9517e6b8 425 die("Invalid request ('[' without ']')");
e8dbd76d
IL
426 *end = '\0';
427 *host = hostport + 1;
428 if (!end[1])
429 *port = NULL;
430 else if (end[1] == ':')
431 *port = end + 2;
432 else
433 die("Garbage after end of host part");
434 } else {
435 *host = hostport;
436 *port = strrchr(hostport, ':');
437 if (*port) {
e9bd3235 438 **port = '\0';
e8dbd76d
IL
439 ++*port;
440 }
441 }
442}
443
eb30aed7 444/*
73bb33a9 445 * Read the host as supplied by the client connection.
eb30aed7 446 */
73bb33a9 447static void parse_host_arg(char *extra_args, int buflen)
49ba83fb
JL
448{
449 char *val;
450 int vallen;
451 char *end = extra_args + buflen;
452
73bb33a9 453 if (extra_args < end && *extra_args) {
49ba83fb
JL
454 saw_extended_args = 1;
455 if (strncasecmp("host=", extra_args, 5) == 0) {
456 val = extra_args + 5;
457 vallen = strlen(val) + 1;
458 if (*val) {
eb30aed7 459 /* Split <host>:<port> at colon. */
e8dbd76d
IL
460 char *host;
461 char *port;
462 parse_host_and_port(val, &host, &port);
dd467629 463 if (port) {
9d7ca667
RS
464 free(tcp_port);
465 tcp_port = xstrdup(port);
dd467629 466 }
9d7ca667 467 free(hostname);
6720e95b 468 hostname = xstrdup_tolower(host);
49ba83fb 469 }
eb30aed7 470
49ba83fb
JL
471 /* On to the next one */
472 extra_args = val + vallen;
473 }
73bb33a9
SP
474 if (extra_args < end && *extra_args)
475 die("Invalid request");
49ba83fb 476 }
dd467629 477
dd467629
JL
478 /*
479 * Locate canonical hostname and its IP address.
480 */
6720e95b 481 if (hostname) {
dd467629 482#ifndef NO_IPV6
dd467629 483 struct addrinfo hints;
3e8a00ae 484 struct addrinfo *ai;
dd467629
JL
485 int gai;
486 static char addrbuf[HOST_NAME_MAX + 1];
487
488 memset(&hints, 0, sizeof(hints));
489 hints.ai_flags = AI_CANONNAME;
490
2af202be 491 gai = getaddrinfo(hostname, NULL, &hints, &ai);
dd467629 492 if (!gai) {
3e8a00ae
BK
493 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
494
495 inet_ntop(AF_INET, &sin_addr->sin_addr,
496 addrbuf, sizeof(addrbuf));
497 free(ip_address);
498 ip_address = xstrdup(addrbuf);
499
500 free(canon_hostname);
501 canon_hostname = xstrdup(ai->ai_canonname ?
502 ai->ai_canonname : ip_address);
503
504 freeaddrinfo(ai);
dd467629 505 }
dd467629 506#else
dd467629
JL
507 struct hostent *hent;
508 struct sockaddr_in sa;
509 char **ap;
510 static char addrbuf[HOST_NAME_MAX + 1];
511
9d7ca667 512 hent = gethostbyname(hostname);
dd467629
JL
513
514 ap = hent->h_addr_list;
515 memset(&sa, 0, sizeof sa);
516 sa.sin_family = hent->h_addrtype;
517 sa.sin_port = htons(0);
518 memcpy(&sa.sin_addr, *ap, hent->h_length);
519
520 inet_ntop(hent->h_addrtype, &sa.sin_addr,
521 addrbuf, sizeof(addrbuf));
eb30aed7 522
9d7ca667
RS
523 free(canon_hostname);
524 canon_hostname = xstrdup(hent->h_name);
525 free(ip_address);
526 ip_address = xstrdup(addrbuf);
dd467629 527#endif
6720e95b 528 }
dd467629
JL
529}
530
531
f9c87be6 532static int execute(void)
a87e8be2 533{
7d80694a 534 static char line[1000];
d819e4e6 535 int pktlen, len, i;
f9c87be6 536 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
7d80694a 537
f9c87be6
EFL
538 if (addr)
539 loginfo("Connection from %s:%s", addr, port);
5b276ee4 540
960deccb 541 alarm(init_timeout ? init_timeout : timeout);
5ad312be 542 pktlen = packet_read_line(0, line, sizeof(line));
960deccb 543 alarm(0);
7d80694a 544
5ad312be
JL
545 len = strlen(line);
546 if (pktlen != len)
547 loginfo("Extended attributes (%d bytes) exist <%.*s>",
548 (int) pktlen - len,
549 (int) pktlen - len, line + len + 1);
83543a24 550 if (len && line[len-1] == '\n') {
7d80694a 551 line[--len] = 0;
83543a24
JH
552 pktlen--;
553 }
7d80694a 554
9d7ca667
RS
555 free(hostname);
556 free(canon_hostname);
557 free(ip_address);
558 free(tcp_port);
a47551c3 559 hostname = canon_hostname = ip_address = tcp_port = NULL;
eb30aed7 560
d433ed0b 561 if (len != pktlen)
73bb33a9 562 parse_host_arg(line + len + 1, pktlen - len - 1);
49ba83fb 563
d819e4e6
JH
564 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
565 struct daemon_service *s = &(daemon_service[i]);
566 int namelen = strlen(s->name);
599065a3 567 if (!prefixcmp(line, "git-") &&
d819e4e6 568 !strncmp(s->name, line + 4, namelen) &&
49ba83fb 569 line[namelen + 4] == ' ') {
eb30aed7
JL
570 /*
571 * Note: The directory here is probably context sensitive,
572 * and might depend on the actual service being performed.
573 */
a47551c3 574 return run_service(line + namelen + 5, s);
49ba83fb 575 }
d819e4e6 576 }
a87e8be2 577
f8ff0c06 578 logerror("Protocol error: '%s'", line);
a87e8be2
LT
579 return -1;
580}
581
15515b73
EFL
582static int addrcmp(const struct sockaddr_storage *s1,
583 const struct sockaddr_storage *s2)
584{
3aff874a
BC
585 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
586 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
587
588 if (sa1->sa_family != sa2->sa_family)
589 return sa1->sa_family - sa2->sa_family;
590 if (sa1->sa_family == AF_INET)
15515b73
EFL
591 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
592 &((struct sockaddr_in *)s2)->sin_addr,
593 sizeof(struct in_addr));
594#ifndef NO_IPV6
3aff874a 595 if (sa1->sa_family == AF_INET6)
15515b73
EFL
596 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
597 &((struct sockaddr_in6 *)s2)->sin6_addr,
598 sizeof(struct in6_addr));
599#endif
600 return 0;
601}
602
3bd62c21 603static int max_connections = 32;
66e631de 604
3bd62c21 605static unsigned int live_children;
66e631de 606
4d8fa916 607static struct child {
3bd62c21 608 struct child *next;
30e15602 609 struct child_process cld;
df076bdb 610 struct sockaddr_storage address;
3bd62c21 611} *firstborn;
66e631de 612
c295cf06 613static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
66e631de 614{
460c2010
JH
615 struct child *newborn, **cradle;
616
460c2010
JH
617 newborn = xcalloc(1, sizeof(*newborn));
618 live_children++;
30e15602 619 memcpy(&newborn->cld, cld, sizeof(*cld));
460c2010
JH
620 memcpy(&newborn->address, addr, addrlen);
621 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
15515b73 622 if (!addrcmp(&(*cradle)->address, &newborn->address))
460c2010
JH
623 break;
624 newborn->next = *cradle;
625 *cradle = newborn;
66e631de
LT
626}
627
66e631de
LT
628/*
629 * This gets called if the number of connections grows
630 * past "max_connections".
631 *
3bd62c21 632 * We kill the newest connection from a duplicate IP.
66e631de 633 */
3bd62c21 634static void kill_some_child(void)
66e631de 635{
460c2010 636 const struct child *blanket, *next;
66e631de 637
460c2010
JH
638 if (!(blanket = firstborn))
639 return;
695605b5 640
460c2010 641 for (; (next = blanket->next); blanket = next)
15515b73 642 if (!addrcmp(&blanket->address, &next->address)) {
30e15602 643 kill(blanket->cld.pid, SIGTERM);
460c2010
JH
644 break;
645 }
a5a9126b
JS
646}
647
3bd62c21 648static void check_dead_children(void)
a87e8be2 649{
3bd62c21
SB
650 int status;
651 pid_t pid;
02d57da4 652
30e15602
EFL
653 struct child **cradle, *blanket;
654 for (cradle = &firstborn; (blanket = *cradle);)
655 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
656 const char *dead = "";
657 if (status)
658 dead = " (with error)";
659 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
660
661 /* remove the child */
662 *cradle = blanket->next;
663 live_children--;
664 free(blanket);
665 } else
666 cradle = &blanket->next;
02d57da4
LT
667}
668
30e15602 669static char **cld_argv;
c295cf06 670static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
02d57da4 671{
c2e86add 672 struct child_process cld = { NULL };
f9c87be6
EFL
673 char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
674 char *env[] = { addrbuf, portbuf, NULL };
02d57da4 675
3bd62c21
SB
676 if (max_connections && live_children >= max_connections) {
677 kill_some_child();
460c2010 678 sleep(1); /* give it some time to die */
3bd62c21
SB
679 check_dead_children();
680 if (live_children >= max_connections) {
681 close(incoming);
682 logerror("Too many children, dropping connection");
683 return;
684 }
685 }
02d57da4 686
f9c87be6
EFL
687 if (addr->sa_family == AF_INET) {
688 struct sockaddr_in *sin_addr = (void *) addr;
689 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
690 sizeof(addrbuf) - 12);
691 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
692 ntohs(sin_addr->sin_port));
693#ifndef NO_IPV6
694 } else if (addr && addr->sa_family == AF_INET6) {
695 struct sockaddr_in6 *sin6_addr = (void *) addr;
696
697 char *buf = addrbuf + 12;
698 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
699 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
700 sizeof(addrbuf) - 13);
701 strcat(buf, "]");
702
703 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
704 ntohs(sin6_addr->sin6_port));
705#endif
706 }
707
708 cld.env = (const char **)env;
30e15602
EFL
709 cld.argv = (const char **)cld_argv;
710 cld.in = incoming;
711 cld.out = dup(incoming);
a87e8be2 712
30e15602
EFL
713 if (start_command(&cld))
714 logerror("unable to fork");
715 else
716 add_child(&cld, addr, addrlen);
a87e8be2 717 close(incoming);
a87e8be2
LT
718}
719
eaa94919
LT
720static void child_handler(int signo)
721{
460c2010
JH
722 /*
723 * Otherwise empty handler because systemcalls will get interrupted
695605b5
SB
724 * upon signal receipt
725 * SysV needs the handler to be rearmed
726 */
bd7b371e 727 signal(SIGCHLD, child_handler);
eaa94919
LT
728}
729
1955fabf
MW
730static int set_reuse_addr(int sockfd)
731{
732 int on = 1;
733
734 if (!reuseaddr)
735 return 0;
736 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
737 &on, sizeof(on));
738}
739
2caa3215
AS
740struct socketlist {
741 int *list;
742 size_t nr;
743 size_t alloc;
744};
745
089d82e8
NTND
746static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
747{
748#ifdef NO_IPV6
749 static char ip[INET_ADDRSTRLEN];
750#else
751 static char ip[INET6_ADDRSTRLEN];
752#endif
753
754 switch (family) {
755#ifndef NO_IPV6
756 case AF_INET6:
757 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
758 break;
759#endif
760 case AF_INET:
761 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
762 break;
763 default:
764 strcpy(ip, "<unknown>");
765 }
766 return ip;
767}
768
6573faff
PA
769#ifndef NO_IPV6
770
2caa3215 771static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
a87e8be2 772{
2caa3215 773 int socknum = 0;
df076bdb 774 int maxfd = -1;
df076bdb 775 char pbuf[NI_MAXSERV];
6573faff
PA
776 struct addrinfo hints, *ai0, *ai;
777 int gai;
20276889 778 long flags;
df076bdb 779
dd467629 780 sprintf(pbuf, "%d", listen_port);
df076bdb
YH
781 memset(&hints, 0, sizeof(hints));
782 hints.ai_family = AF_UNSPEC;
783 hints.ai_socktype = SOCK_STREAM;
784 hints.ai_protocol = IPPROTO_TCP;
785 hints.ai_flags = AI_PASSIVE;
786
dd467629 787 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
2caa3215
AS
788 if (gai) {
789 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
790 return 0;
791 }
df076bdb 792
df076bdb
YH
793 for (ai = ai0; ai; ai = ai->ai_next) {
794 int sockfd;
df076bdb
YH
795
796 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
797 if (sockfd < 0)
798 continue;
799 if (sockfd >= FD_SETSIZE) {
df0daf8a 800 logerror("Socket descriptor too large");
df076bdb
YH
801 close(sockfd);
802 continue;
803 }
804
805#ifdef IPV6_V6ONLY
806 if (ai->ai_family == AF_INET6) {
807 int on = 1;
808 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
809 &on, sizeof(on));
810 /* Note: error is not fatal */
811 }
812#endif
813
1955fabf 814 if (set_reuse_addr(sockfd)) {
089d82e8 815 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1955fabf 816 close(sockfd);
0032d548 817 continue;
1955fabf
MW
818 }
819
df076bdb 820 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
089d82e8
NTND
821 logerror("Could not bind to %s: %s",
822 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
823 strerror(errno));
df076bdb
YH
824 close(sockfd);
825 continue; /* not fatal */
826 }
827 if (listen(sockfd, 5) < 0) {
089d82e8
NTND
828 logerror("Could not listen to %s: %s",
829 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
830 strerror(errno));
df076bdb
YH
831 close(sockfd);
832 continue; /* not fatal */
833 }
834
20276889
AJ
835 flags = fcntl(sockfd, F_GETFD, 0);
836 if (flags >= 0)
837 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
838
2caa3215
AS
839 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
840 socklist->list[socklist->nr++] = sockfd;
841 socknum++;
df076bdb 842
df076bdb
YH
843 if (maxfd < sockfd)
844 maxfd = sockfd;
845 }
846
847 freeaddrinfo(ai0);
848
6573faff
PA
849 return socknum;
850}
851
852#else /* NO_IPV6 */
853
2caa3215 854static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
6573faff
PA
855{
856 struct sockaddr_in sin;
857 int sockfd;
20276889 858 long flags;
6573faff 859
dd467629
JL
860 memset(&sin, 0, sizeof sin);
861 sin.sin_family = AF_INET;
862 sin.sin_port = htons(listen_port);
863
864 if (listen_addr) {
865 /* Well, host better be an IP address here. */
866 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
867 return 0;
868 } else {
869 sin.sin_addr.s_addr = htonl(INADDR_ANY);
870 }
871
6573faff
PA
872 sockfd = socket(AF_INET, SOCK_STREAM, 0);
873 if (sockfd < 0)
874 return 0;
875
1955fabf 876 if (set_reuse_addr(sockfd)) {
089d82e8 877 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1955fabf
MW
878 close(sockfd);
879 return 0;
880 }
881
6573faff 882 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
089d82e8
NTND
883 logerror("Could not listen to %s: %s",
884 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
885 strerror(errno));
6573faff
PA
886 close(sockfd);
887 return 0;
888 }
a87e8be2 889
f35230fb 890 if (listen(sockfd, 5) < 0) {
089d82e8
NTND
891 logerror("Could not listen to %s: %s",
892 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
893 strerror(errno));
f35230fb
PS
894 close(sockfd);
895 return 0;
896 }
897
20276889
AJ
898 flags = fcntl(sockfd, F_GETFD, 0);
899 if (flags >= 0)
900 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
901
2caa3215
AS
902 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
903 socklist->list[socklist->nr++] = sockfd;
f35230fb 904 return 1;
6573faff
PA
905}
906
907#endif
908
3a3a29c1 909static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
2caa3215 910{
3a3a29c1
AS
911 if (!listen_addr->nr)
912 setup_named_sock(NULL, listen_port, socklist);
913 else {
914 int i, socknum;
915 for (i = 0; i < listen_addr->nr; i++) {
916 socknum = setup_named_sock(listen_addr->items[i].string,
917 listen_port, socklist);
918
919 if (socknum == 0)
920 logerror("unable to allocate any listen sockets for host %s on port %u",
921 listen_addr->items[i].string, listen_port);
922 }
923 }
2caa3215
AS
924}
925
926static int service_loop(struct socketlist *socklist)
6573faff
PA
927{
928 struct pollfd *pfd;
929 int i;
930
2caa3215 931 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
6573faff 932
2caa3215
AS
933 for (i = 0; i < socklist->nr; i++) {
934 pfd[i].fd = socklist->list[i];
6573faff
PA
935 pfd[i].events = POLLIN;
936 }
9220282a
PA
937
938 signal(SIGCHLD, child_handler);
a87e8be2
LT
939
940 for (;;) {
df076bdb 941 int i;
6573faff 942
695605b5
SB
943 check_dead_children();
944
2caa3215 945 if (poll(pfd, socklist->nr, -1) < 0) {
1eef0b33 946 if (errno != EINTR) {
df0daf8a 947 logerror("Poll failed, resuming: %s",
1eef0b33
JH
948 strerror(errno));
949 sleep(1);
950 }
df076bdb
YH
951 continue;
952 }
953
2caa3215 954 for (i = 0; i < socklist->nr; i++) {
6573faff 955 if (pfd[i].revents & POLLIN) {
f9c87be6
EFL
956 union {
957 struct sockaddr sa;
958 struct sockaddr_in sai;
959#ifndef NO_IPV6
960 struct sockaddr_in6 sai6;
961#endif
962 } ss;
c295cf06 963 socklen_t sslen = sizeof(ss);
f9c87be6 964 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
df076bdb
YH
965 if (incoming < 0) {
966 switch (errno) {
967 case EAGAIN:
968 case EINTR:
969 case ECONNABORTED:
970 continue;
971 default:
d824cbba 972 die_errno("accept returned");
df076bdb
YH
973 }
974 }
f9c87be6 975 handle(incoming, &ss.sa, sslen);
a87e8be2
LT
976 }
977 }
a87e8be2
LT
978 }
979}
980
258e93a1
ML
981/* if any standard file descriptor is missing open it to /dev/null */
982static void sanitize_stdfds(void)
983{
984 int fd = open("/dev/null", O_RDWR, 0);
985 while (fd != -1 && fd < 2)
986 fd = dup(fd);
987 if (fd == -1)
d824cbba 988 die_errno("open /dev/null or dup failed");
258e93a1
ML
989 if (fd > 2)
990 close(fd);
991}
992
a666b472
EFL
993#ifdef NO_POSIX_GOODIES
994
995struct credentials;
996
997static void drop_privileges(struct credentials *cred)
998{
999 /* nothing */
1000}
1001
1002static void daemonize(void)
1003{
1004 die("--detach not supported on this platform");
1005}
1006
1007static struct credentials *prepare_credentials(const char *user_name,
1008 const char *group_name)
1009{
1010 die("--user not supported on this platform");
1011}
1012
1013#else
1014
1015struct credentials {
1016 struct passwd *pass;
1017 gid_t gid;
1018};
1019
1020static void drop_privileges(struct credentials *cred)
1021{
1022 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1023 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1024 die("cannot drop privileges");
1025}
1026
1027static struct credentials *prepare_credentials(const char *user_name,
1028 const char *group_name)
1029{
1030 static struct credentials c;
1031
1032 c.pass = getpwnam(user_name);
1033 if (!c.pass)
1034 die("user not found - %s", user_name);
1035
1036 if (!group_name)
1037 c.gid = c.pass->pw_gid;
1038 else {
1039 struct group *group = getgrnam(group_name);
1040 if (!group)
1041 die("group not found - %s", group_name);
1042
1043 c.gid = group->gr_gid;
1044 }
1045
1046 return &c;
1047}
1048
a5262768
ML
1049static void daemonize(void)
1050{
1051 switch (fork()) {
1052 case 0:
1053 break;
1054 case -1:
d824cbba 1055 die_errno("fork failed");
a5262768
ML
1056 default:
1057 exit(0);
1058 }
1059 if (setsid() == -1)
d824cbba 1060 die_errno("setsid failed");
a5262768
ML
1061 close(0);
1062 close(1);
1063 close(2);
1064 sanitize_stdfds();
1065}
a666b472 1066#endif
a5262768 1067
45ed5d7f
ML
1068static void store_pid(const char *path)
1069{
1070 FILE *f = fopen(path, "w");
1071 if (!f)
d824cbba 1072 die_errno("cannot open pid file '%s'", path);
85e72830 1073 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
d824cbba 1074 die_errno("failed to write pid file '%s'", path);
45ed5d7f
ML
1075}
1076
a666b472
EFL
1077static int serve(struct string_list *listen_addr, int listen_port,
1078 struct credentials *cred)
6573faff 1079{
2caa3215 1080 struct socketlist socklist = { NULL, 0, 0 };
4ae22d96 1081
2caa3215
AS
1082 socksetup(listen_addr, listen_port, &socklist);
1083 if (socklist.nr == 0)
3a3a29c1
AS
1084 die("unable to allocate any listen sockets on port %u",
1085 listen_port);
4ae22d96 1086
a666b472 1087 drop_privileges(cred);
678dac6b 1088
f6a34cfb
CB
1089 loginfo("Ready to rumble");
1090
2caa3215 1091 return service_loop(&socklist);
4ae22d96 1092}
6573faff 1093
a87e8be2
LT
1094int main(int argc, char **argv)
1095{
dd467629 1096 int listen_port = 0;
3a3a29c1 1097 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
30e15602 1098 int serve_mode = 0, inetd_mode = 0;
678dac6b 1099 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
a5262768 1100 int detach = 0;
a666b472 1101 struct credentials *cred = NULL;
a87e8be2
LT
1102 int i;
1103
5e9637c6
ÆAB
1104 git_setup_gettext();
1105
2fb3f6db
SP
1106 git_extract_argv0_path(argv[0]);
1107
a87e8be2
LT
1108 for (i = 1; i < argc; i++) {
1109 char *arg = argv[i];
1110
cc44c765 1111 if (!prefixcmp(arg, "--listen=")) {
3a3a29c1 1112 string_list_append(&listen_addr, xstrdup_tolower(arg + 9));
6720e95b 1113 continue;
dd467629 1114 }
cc44c765 1115 if (!prefixcmp(arg, "--port=")) {
a87e8be2
LT
1116 char *end;
1117 unsigned long n;
1118 n = strtoul(arg+7, &end, 0);
1119 if (arg[7] && !*end) {
dd467629 1120 listen_port = n;
a87e8be2
LT
1121 continue;
1122 }
1123 }
30e15602
EFL
1124 if (!strcmp(arg, "--serve")) {
1125 serve_mode = 1;
1126 continue;
1127 }
e64e1b79
LT
1128 if (!strcmp(arg, "--inetd")) {
1129 inetd_mode = 1;
a8883288 1130 log_syslog = 1;
e64e1b79
LT
1131 continue;
1132 }
f8ff0c06
PB
1133 if (!strcmp(arg, "--verbose")) {
1134 verbose = 1;
1135 continue;
1136 }
9048fe1c
PB
1137 if (!strcmp(arg, "--syslog")) {
1138 log_syslog = 1;
9048fe1c
PB
1139 continue;
1140 }
4ae95682
PA
1141 if (!strcmp(arg, "--export-all")) {
1142 export_all_trees = 1;
1143 continue;
1144 }
cc44c765 1145 if (!prefixcmp(arg, "--timeout=")) {
960deccb 1146 timeout = atoi(arg+10);
a8883288 1147 continue;
960deccb 1148 }
cc44c765 1149 if (!prefixcmp(arg, "--init-timeout=")) {
960deccb 1150 init_timeout = atoi(arg+15);
a8883288 1151 continue;
960deccb 1152 }
3bd62c21
SB
1153 if (!prefixcmp(arg, "--max-connections=")) {
1154 max_connections = atoi(arg+18);
1155 if (max_connections < 0)
1156 max_connections = 0; /* unlimited */
1157 continue;
1158 }
4dbd1352
AE
1159 if (!strcmp(arg, "--strict-paths")) {
1160 strict_paths = 1;
1161 continue;
1162 }
cc44c765 1163 if (!prefixcmp(arg, "--base-path=")) {
b21c31c9
PB
1164 base_path = arg+12;
1165 continue;
1166 }
73a7a656
JA
1167 if (!strcmp(arg, "--base-path-relaxed")) {
1168 base_path_relaxed = 1;
1169 continue;
1170 }
cc44c765 1171 if (!prefixcmp(arg, "--interpolated-path=")) {
49ba83fb
JL
1172 interpolated_path = arg+20;
1173 continue;
1174 }
1955fabf
MW
1175 if (!strcmp(arg, "--reuseaddr")) {
1176 reuseaddr = 1;
1177 continue;
1178 }
603968d2
JH
1179 if (!strcmp(arg, "--user-path")) {
1180 user_path = "";
1181 continue;
1182 }
cc44c765 1183 if (!prefixcmp(arg, "--user-path=")) {
603968d2
JH
1184 user_path = arg + 12;
1185 continue;
1186 }
cc44c765 1187 if (!prefixcmp(arg, "--pid-file=")) {
45ed5d7f
ML
1188 pid_file = arg + 11;
1189 continue;
1190 }
a5262768
ML
1191 if (!strcmp(arg, "--detach")) {
1192 detach = 1;
1193 log_syslog = 1;
1194 continue;
1195 }
cc44c765 1196 if (!prefixcmp(arg, "--user=")) {
678dac6b
TS
1197 user_name = arg + 7;
1198 continue;
1199 }
cc44c765 1200 if (!prefixcmp(arg, "--group=")) {
678dac6b
TS
1201 group_name = arg + 8;
1202 continue;
1203 }
cc44c765 1204 if (!prefixcmp(arg, "--enable=")) {
d819e4e6
JH
1205 enable_service(arg + 9, 1);
1206 continue;
1207 }
cc44c765 1208 if (!prefixcmp(arg, "--disable=")) {
d819e4e6
JH
1209 enable_service(arg + 10, 0);
1210 continue;
1211 }
cc44c765 1212 if (!prefixcmp(arg, "--allow-override=")) {
74c0cc21 1213 make_service_overridable(arg + 17, 1);
d819e4e6
JH
1214 continue;
1215 }
cc44c765 1216 if (!prefixcmp(arg, "--forbid-override=")) {
74c0cc21 1217 make_service_overridable(arg + 18, 0);
d819e4e6
JH
1218 continue;
1219 }
d5570f4d
JK
1220 if (!prefixcmp(arg, "--informative-errors")) {
1221 informative_errors = 1;
1222 continue;
1223 }
1224 if (!prefixcmp(arg, "--no-informative-errors")) {
1225 informative_errors = 0;
1226 continue;
1227 }
4ae95682
PA
1228 if (!strcmp(arg, "--")) {
1229 ok_paths = &argv[i+1];
1230 break;
1231 } else if (arg[0] != '-') {
1232 ok_paths = &argv[i];
1233 break;
1234 }
e64e1b79 1235
a87e8be2
LT
1236 usage(daemon_usage);
1237 }
1238
22665bba 1239 if (log_syslog) {
6a992e9e 1240 openlog("git-daemon", LOG_PID, LOG_DAEMON);
22665bba 1241 set_die_routine(daemon_die);
460c2010 1242 } else
48196afd 1243 /* avoid splitting a message in the middle */
48cfaea1 1244 setvbuf(stderr, NULL, _IOFBF, 4096);
22665bba 1245
9cddf56e
EFL
1246 if (inetd_mode && (detach || group_name || user_name))
1247 die("--detach, --user and --group are incompatible with --inetd");
678dac6b 1248
3a3a29c1 1249 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
dd467629
JL
1250 die("--listen= and --port= are incompatible with --inetd");
1251 else if (listen_port == 0)
1252 listen_port = DEFAULT_GIT_PORT;
1253
678dac6b
TS
1254 if (group_name && !user_name)
1255 die("--group supplied without --user");
1256
a666b472
EFL
1257 if (user_name)
1258 cred = prepare_credentials(user_name, group_name);
678dac6b 1259
ad8b4f56
ML
1260 if (strict_paths && (!ok_paths || !*ok_paths))
1261 die("option --strict-paths requires a whitelist");
1262
90b4a71c
JH
1263 if (base_path && !is_directory(base_path))
1264 die("base-path '%s' does not exist or is not a directory",
1265 base_path);
20632071 1266
7c3693f1 1267 if (inetd_mode) {
30e15602
EFL
1268 if (!freopen("/dev/null", "w", stderr))
1269 die_errno("failed to redirect stderr to /dev/null");
1270 }
1271
f9c87be6
EFL
1272 if (inetd_mode || serve_mode)
1273 return execute();
bce8230d 1274
f6a34cfb 1275 if (detach)
a5262768
ML
1276 daemonize();
1277 else
1278 sanitize_stdfds();
258e93a1 1279
45ed5d7f
ML
1280 if (pid_file)
1281 store_pid(pid_file);
1282
30e15602
EFL
1283 /* prepare argv for serving-processes */
1284 cld_argv = xmalloc(sizeof (char *) * (argc + 2));
081f84ee
JN
1285 cld_argv[0] = argv[0]; /* git-daemon */
1286 cld_argv[1] = "--serve";
1287 for (i = 1; i < argc; ++i)
1288 cld_argv[i+1] = argv[i];
30e15602
EFL
1289 cld_argv[argc+1] = NULL;
1290
a666b472 1291 return serve(&listen_addr, listen_port, cred);
a87e8be2 1292}