THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1401 lines
32KB

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