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