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