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