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