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