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.

1171 lines
25KB

  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 <syslog.h>
  7. #ifndef HOST_NAME_MAX
  8. #define HOST_NAME_MAX 256
  9. #endif
  10. #ifndef NI_MAXSERV
  11. #define NI_MAXSERV 32
  12. #endif
  13. static int log_syslog;
  14. static int verbose;
  15. static int reuseaddr;
  16. static const char daemon_usage[] =
  17. "git daemon [--verbose] [--syslog] [--export-all]\n"
  18. " [--timeout=n] [--init-timeout=n] [--max-connections=n]\n"
  19. " [--strict-paths] [--base-path=path] [--base-path-relaxed]\n"
  20. " [--user-path | --user-path=path]\n"
  21. " [--interpolated-path=path]\n"
  22. " [--reuseaddr] [--detach] [--pid-file=file]\n"
  23. " [--[enable|disable|allow-override|forbid-override]=service]\n"
  24. " [--inetd | [--listen=host_or_ipaddr] [--port=n]\n"
  25. " [--user=user [--group=group]]\n"
  26. " [directory...]";
  27. /* List of acceptable pathname prefixes */
  28. static char **ok_paths;
  29. static int strict_paths;
  30. /* If this is set, git-daemon-export-ok is not required */
  31. static int export_all_trees;
  32. /* Take all paths relative to this one if non-NULL */
  33. static char *base_path;
  34. static char *interpolated_path;
  35. static int base_path_relaxed;
  36. /* Flag indicating client sent extra args. */
  37. static int saw_extended_args;
  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. static char *hostname;
  47. static char *canon_hostname;
  48. static char *ip_address;
  49. static char *tcp_port;
  50. static void logreport(int priority, const char *err, va_list params)
  51. {
  52. if (log_syslog) {
  53. char buf[1024];
  54. vsnprintf(buf, sizeof(buf), err, params);
  55. syslog(priority, "%s", buf);
  56. } else {
  57. /*
  58. * Since stderr is set to linebuffered mode, the
  59. * logging of different processes will not overlap
  60. */
  61. fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
  62. vfprintf(stderr, err, params);
  63. fputc('\n', stderr);
  64. }
  65. }
  66. static void logerror(const char *err, ...)
  67. {
  68. va_list params;
  69. va_start(params, err);
  70. logreport(LOG_ERR, err, params);
  71. va_end(params);
  72. }
  73. static void loginfo(const char *err, ...)
  74. {
  75. va_list params;
  76. if (!verbose)
  77. return;
  78. va_start(params, err);
  79. logreport(LOG_INFO, err, params);
  80. va_end(params);
  81. }
  82. static void NORETURN daemon_die(const char *err, va_list params)
  83. {
  84. logreport(LOG_ERR, err, params);
  85. exit(1);
  86. }
  87. static int avoid_alias(char *p)
  88. {
  89. int sl, ndot;
  90. /*
  91. * This resurrects the belts and suspenders paranoia check by HPA
  92. * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
  93. * does not do getcwd() based path canonicalizations.
  94. *
  95. * sl becomes true immediately after seeing '/' and continues to
  96. * be true as long as dots continue after that without intervening
  97. * non-dot character.
  98. */
  99. if (!p || (*p != '/' && *p != '~'))
  100. return -1;
  101. sl = 1; ndot = 0;
  102. p++;
  103. while (1) {
  104. char ch = *p++;
  105. if (sl) {
  106. if (ch == '.')
  107. ndot++;
  108. else if (ch == '/') {
  109. if (ndot < 3)
  110. /* reject //, /./ and /../ */
  111. return -1;
  112. ndot = 0;
  113. }
  114. else if (ch == 0) {
  115. if (0 < ndot && ndot < 3)
  116. /* reject /.$ and /..$ */
  117. return -1;
  118. return 0;
  119. }
  120. else
  121. sl = ndot = 0;
  122. }
  123. else if (ch == 0)
  124. return 0;
  125. else if (ch == '/') {
  126. sl = 1;
  127. ndot = 0;
  128. }
  129. }
  130. }
  131. static char *path_ok(char *directory)
  132. {
  133. static char rpath[PATH_MAX];
  134. static char interp_path[PATH_MAX];
  135. char *path;
  136. char *dir;
  137. dir = directory;
  138. if (avoid_alias(dir)) {
  139. logerror("'%s': aliased", dir);
  140. return NULL;
  141. }
  142. if (*dir == '~') {
  143. if (!user_path) {
  144. logerror("'%s': User-path not allowed", dir);
  145. return NULL;
  146. }
  147. if (*user_path) {
  148. /* Got either "~alice" or "~alice/foo";
  149. * rewrite them to "~alice/%s" or
  150. * "~alice/%s/foo".
  151. */
  152. int namlen, restlen = strlen(dir);
  153. char *slash = strchr(dir, '/');
  154. if (!slash)
  155. slash = dir + restlen;
  156. namlen = slash - dir;
  157. restlen -= namlen;
  158. loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
  159. snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
  160. namlen, dir, user_path, restlen, slash);
  161. dir = rpath;
  162. }
  163. }
  164. else if (interpolated_path && saw_extended_args) {
  165. struct strbuf expanded_path = STRBUF_INIT;
  166. struct strbuf_expand_dict_entry dict[] = {
  167. { "H", hostname },
  168. { "CH", canon_hostname },
  169. { "IP", ip_address },
  170. { "P", tcp_port },
  171. { "D", directory },
  172. { "%", "%" },
  173. { NULL }
  174. };
  175. if (*dir != '/') {
  176. /* Allow only absolute */
  177. logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
  178. return NULL;
  179. }
  180. strbuf_expand(&expanded_path, interpolated_path,
  181. strbuf_expand_dict_cb, &dict);
  182. strlcpy(interp_path, expanded_path.buf, PATH_MAX);
  183. strbuf_release(&expanded_path);
  184. loginfo("Interpolated dir '%s'", interp_path);
  185. dir = interp_path;
  186. }
  187. else if (base_path) {
  188. if (*dir != '/') {
  189. /* Allow only absolute */
  190. logerror("'%s': Non-absolute path denied (base-path active)", dir);
  191. return NULL;
  192. }
  193. snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
  194. dir = rpath;
  195. }
  196. path = enter_repo(dir, strict_paths);
  197. if (!path && base_path && base_path_relaxed) {
  198. /*
  199. * if we fail and base_path_relaxed is enabled, try without
  200. * prefixing the base path
  201. */
  202. dir = directory;
  203. path = enter_repo(dir, strict_paths);
  204. }
  205. if (!path) {
  206. logerror("'%s' does not appear to be a git repository", dir);
  207. return NULL;
  208. }
  209. if ( ok_paths && *ok_paths ) {
  210. char **pp;
  211. int pathlen = strlen(path);
  212. /* The validation is done on the paths after enter_repo
  213. * appends optional {.git,.git/.git} and friends, but
  214. * it does not use getcwd(). So if your /pub is
  215. * a symlink to /mnt/pub, you can whitelist /pub and
  216. * do not have to say /mnt/pub.
  217. * Do not say /pub/.
  218. */
  219. for ( pp = ok_paths ; *pp ; pp++ ) {
  220. int len = strlen(*pp);
  221. if (len <= pathlen &&
  222. !memcmp(*pp, path, len) &&
  223. (path[len] == '\0' ||
  224. (!strict_paths && path[len] == '/')))
  225. return path;
  226. }
  227. }
  228. else {
  229. /* be backwards compatible */
  230. if (!strict_paths)
  231. return path;
  232. }
  233. logerror("'%s': not in whitelist", path);
  234. return NULL; /* Fallthrough. Deny by default */
  235. }
  236. typedef int (*daemon_service_fn)(void);
  237. struct daemon_service {
  238. const char *name;
  239. const char *config_name;
  240. daemon_service_fn fn;
  241. int enabled;
  242. int overridable;
  243. };
  244. static struct daemon_service *service_looking_at;
  245. static int service_enabled;
  246. static int git_daemon_config(const char *var, const char *value, void *cb)
  247. {
  248. if (!prefixcmp(var, "daemon.") &&
  249. !strcmp(var + 7, service_looking_at->config_name)) {
  250. service_enabled = git_config_bool(var, value);
  251. return 0;
  252. }
  253. /* we are not interested in parsing any other configuration here */
  254. return 0;
  255. }
  256. static int run_service(char *dir, struct daemon_service *service)
  257. {
  258. const char *path;
  259. int enabled = service->enabled;
  260. loginfo("Request %s for '%s'", service->name, dir);
  261. if (!enabled && !service->overridable) {
  262. logerror("'%s': service not enabled.", service->name);
  263. errno = EACCES;
  264. return -1;
  265. }
  266. if (!(path = path_ok(dir)))
  267. return -1;
  268. /*
  269. * Security on the cheap.
  270. *
  271. * We want a readable HEAD, usable "objects" directory, and
  272. * a "git-daemon-export-ok" flag that says that the other side
  273. * is ok with us doing this.
  274. *
  275. * path_ok() uses enter_repo() and does whitelist checking.
  276. * We only need to make sure the repository is exported.
  277. */
  278. if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
  279. logerror("'%s': repository not exported.", path);
  280. errno = EACCES;
  281. return -1;
  282. }
  283. if (service->overridable) {
  284. service_looking_at = service;
  285. service_enabled = -1;
  286. git_config(git_daemon_config, NULL);
  287. if (0 <= service_enabled)
  288. enabled = service_enabled;
  289. }
  290. if (!enabled) {
  291. logerror("'%s': service not enabled for '%s'",
  292. service->name, path);
  293. errno = EACCES;
  294. return -1;
  295. }
  296. /*
  297. * We'll ignore SIGTERM from now on, we have a
  298. * good client.
  299. */
  300. signal(SIGTERM, SIG_IGN);
  301. return service->fn();
  302. }
  303. static void copy_to_log(int fd)
  304. {
  305. struct strbuf line = STRBUF_INIT;
  306. FILE *fp;
  307. fp = fdopen(fd, "r");
  308. if (fp == NULL) {
  309. logerror("fdopen of error channel failed");
  310. close(fd);
  311. return;
  312. }
  313. while (strbuf_getline(&line, fp, '\n') != EOF) {
  314. logerror("%s", line.buf);
  315. strbuf_setlen(&line, 0);
  316. }
  317. strbuf_release(&line);
  318. fclose(fp);
  319. }
  320. static int run_service_command(const char **argv)
  321. {
  322. struct child_process cld;
  323. memset(&cld, 0, sizeof(cld));
  324. cld.argv = argv;
  325. cld.git_cmd = 1;
  326. cld.err = -1;
  327. if (start_command(&cld))
  328. return -1;
  329. close(0);
  330. close(1);
  331. copy_to_log(cld.err);
  332. return finish_command(&cld);
  333. }
  334. static int upload_pack(void)
  335. {
  336. /* Timeout as string */
  337. char timeout_buf[64];
  338. const char *argv[] = { "upload-pack", "--strict", timeout_buf, ".", NULL };
  339. snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
  340. return run_service_command(argv);
  341. }
  342. static int upload_archive(void)
  343. {
  344. static const char *argv[] = { "upload-archive", ".", NULL };
  345. return run_service_command(argv);
  346. }
  347. static int receive_pack(void)
  348. {
  349. static const char *argv[] = { "receive-pack", ".", NULL };
  350. return run_service_command(argv);
  351. }
  352. static struct daemon_service daemon_service[] = {
  353. { "upload-archive", "uploadarch", upload_archive, 0, 1 },
  354. { "upload-pack", "uploadpack", upload_pack, 1, 1 },
  355. { "receive-pack", "receivepack", receive_pack, 0, 1 },
  356. };
  357. static void enable_service(const char *name, int ena)
  358. {
  359. int i;
  360. for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
  361. if (!strcmp(daemon_service[i].name, name)) {
  362. daemon_service[i].enabled = ena;
  363. return;
  364. }
  365. }
  366. die("No such service %s", name);
  367. }
  368. static void make_service_overridable(const char *name, int ena)
  369. {
  370. int i;
  371. for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
  372. if (!strcmp(daemon_service[i].name, name)) {
  373. daemon_service[i].overridable = ena;
  374. return;
  375. }
  376. }
  377. die("No such service %s", name);
  378. }
  379. static char *xstrdup_tolower(const char *str)
  380. {
  381. char *p, *dup = xstrdup(str);
  382. for (p = dup; *p; p++)
  383. *p = tolower(*p);
  384. return dup;
  385. }
  386. /*
  387. * Read the host as supplied by the client connection.
  388. */
  389. static void parse_host_arg(char *extra_args, int buflen)
  390. {
  391. char *val;
  392. int vallen;
  393. char *end = extra_args + buflen;
  394. if (extra_args < end && *extra_args) {
  395. saw_extended_args = 1;
  396. if (strncasecmp("host=", extra_args, 5) == 0) {
  397. val = extra_args + 5;
  398. vallen = strlen(val) + 1;
  399. if (*val) {
  400. /* Split <host>:<port> at colon. */
  401. char *host = val;
  402. char *port = strrchr(host, ':');
  403. if (port) {
  404. *port = 0;
  405. port++;
  406. free(tcp_port);
  407. tcp_port = xstrdup(port);
  408. }
  409. free(hostname);
  410. hostname = xstrdup_tolower(host);
  411. }
  412. /* On to the next one */
  413. extra_args = val + vallen;
  414. }
  415. if (extra_args < end && *extra_args)
  416. die("Invalid request");
  417. }
  418. /*
  419. * Locate canonical hostname and its IP address.
  420. */
  421. if (hostname) {
  422. #ifndef NO_IPV6
  423. struct addrinfo hints;
  424. struct addrinfo *ai;
  425. int gai;
  426. static char addrbuf[HOST_NAME_MAX + 1];
  427. memset(&hints, 0, sizeof(hints));
  428. hints.ai_flags = AI_CANONNAME;
  429. gai = getaddrinfo(hostname, 0, &hints, &ai);
  430. if (!gai) {
  431. struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
  432. inet_ntop(AF_INET, &sin_addr->sin_addr,
  433. addrbuf, sizeof(addrbuf));
  434. free(ip_address);
  435. ip_address = xstrdup(addrbuf);
  436. free(canon_hostname);
  437. canon_hostname = xstrdup(ai->ai_canonname ?
  438. ai->ai_canonname : ip_address);
  439. freeaddrinfo(ai);
  440. }
  441. #else
  442. struct hostent *hent;
  443. struct sockaddr_in sa;
  444. char **ap;
  445. static char addrbuf[HOST_NAME_MAX + 1];
  446. hent = gethostbyname(hostname);
  447. ap = hent->h_addr_list;
  448. memset(&sa, 0, sizeof sa);
  449. sa.sin_family = hent->h_addrtype;
  450. sa.sin_port = htons(0);
  451. memcpy(&sa.sin_addr, *ap, hent->h_length);
  452. inet_ntop(hent->h_addrtype, &sa.sin_addr,
  453. addrbuf, sizeof(addrbuf));
  454. free(canon_hostname);
  455. canon_hostname = xstrdup(hent->h_name);
  456. free(ip_address);
  457. ip_address = xstrdup(addrbuf);
  458. #endif
  459. }
  460. }
  461. static int execute(struct sockaddr *addr)
  462. {
  463. static char line[1000];
  464. int pktlen, len, i;
  465. if (addr) {
  466. char addrbuf[256] = "";
  467. int port = -1;
  468. if (addr->sa_family == AF_INET) {
  469. struct sockaddr_in *sin_addr = (void *) addr;
  470. inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
  471. port = ntohs(sin_addr->sin_port);
  472. #ifndef NO_IPV6
  473. } else if (addr && addr->sa_family == AF_INET6) {
  474. struct sockaddr_in6 *sin6_addr = (void *) addr;
  475. char *buf = addrbuf;
  476. *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
  477. inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
  478. strcat(buf, "]");
  479. port = ntohs(sin6_addr->sin6_port);
  480. #endif
  481. }
  482. loginfo("Connection from %s:%d", addrbuf, port);
  483. setenv("REMOTE_ADDR", addrbuf, 1);
  484. }
  485. else {
  486. unsetenv("REMOTE_ADDR");
  487. }
  488. alarm(init_timeout ? init_timeout : timeout);
  489. pktlen = packet_read_line(0, line, sizeof(line));
  490. alarm(0);
  491. len = strlen(line);
  492. if (pktlen != len)
  493. loginfo("Extended attributes (%d bytes) exist <%.*s>",
  494. (int) pktlen - len,
  495. (int) pktlen - len, line + len + 1);
  496. if (len && line[len-1] == '\n') {
  497. line[--len] = 0;
  498. pktlen--;
  499. }
  500. free(hostname);
  501. free(canon_hostname);
  502. free(ip_address);
  503. free(tcp_port);
  504. hostname = canon_hostname = ip_address = tcp_port = NULL;
  505. if (len != pktlen)
  506. parse_host_arg(line + len + 1, pktlen - len - 1);
  507. for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
  508. struct daemon_service *s = &(daemon_service[i]);
  509. int namelen = strlen(s->name);
  510. if (!prefixcmp(line, "git-") &&
  511. !strncmp(s->name, line + 4, namelen) &&
  512. line[namelen + 4] == ' ') {
  513. /*
  514. * Note: The directory here is probably context sensitive,
  515. * and might depend on the actual service being performed.
  516. */
  517. return run_service(line + namelen + 5, s);
  518. }
  519. }
  520. logerror("Protocol error: '%s'", line);
  521. return -1;
  522. }
  523. static int max_connections = 32;
  524. static unsigned int live_children;
  525. static struct child {
  526. struct child *next;
  527. pid_t pid;
  528. struct sockaddr_storage address;
  529. } *firstborn;
  530. static void add_child(pid_t pid, struct sockaddr *addr, int addrlen)
  531. {
  532. struct child *newborn, **cradle;
  533. /*
  534. * This must be xcalloc() -- we'll compare the whole sockaddr_storage
  535. * but individual address may be shorter.
  536. */
  537. newborn = xcalloc(1, sizeof(*newborn));
  538. live_children++;
  539. newborn->pid = pid;
  540. memcpy(&newborn->address, addr, addrlen);
  541. for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
  542. if (!memcmp(&(*cradle)->address, &newborn->address,
  543. sizeof(newborn->address)))
  544. break;
  545. newborn->next = *cradle;
  546. *cradle = newborn;
  547. }
  548. static void remove_child(pid_t pid)
  549. {
  550. struct child **cradle, *blanket;
  551. for (cradle = &firstborn; (blanket = *cradle); cradle = &blanket->next)
  552. if (blanket->pid == pid) {
  553. *cradle = blanket->next;
  554. live_children--;
  555. free(blanket);
  556. break;
  557. }
  558. }
  559. /*
  560. * This gets called if the number of connections grows
  561. * past "max_connections".
  562. *
  563. * We kill the newest connection from a duplicate IP.
  564. */
  565. static void kill_some_child(void)
  566. {
  567. const struct child *blanket, *next;
  568. if (!(blanket = firstborn))
  569. return;
  570. for (; (next = blanket->next); blanket = next)
  571. if (!memcmp(&blanket->address, &next->address,
  572. sizeof(next->address))) {
  573. kill(blanket->pid, SIGTERM);
  574. break;
  575. }
  576. }
  577. static void check_dead_children(void)
  578. {
  579. int status;
  580. pid_t pid;
  581. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  582. const char *dead = "";
  583. remove_child(pid);
  584. if (!WIFEXITED(status) || (WEXITSTATUS(status) > 0))
  585. dead = " (with error)";
  586. loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
  587. }
  588. }
  589. static void handle(int incoming, struct sockaddr *addr, int addrlen)
  590. {
  591. pid_t pid;
  592. if (max_connections && live_children >= max_connections) {
  593. kill_some_child();
  594. sleep(1); /* give it some time to die */
  595. check_dead_children();
  596. if (live_children >= max_connections) {
  597. close(incoming);
  598. logerror("Too many children, dropping connection");
  599. return;
  600. }
  601. }
  602. if ((pid = fork())) {
  603. close(incoming);
  604. if (pid < 0) {
  605. logerror("Couldn't fork %s", strerror(errno));
  606. return;
  607. }
  608. add_child(pid, addr, addrlen);
  609. return;
  610. }
  611. dup2(incoming, 0);
  612. dup2(incoming, 1);
  613. close(incoming);
  614. exit(execute(addr));
  615. }
  616. static void child_handler(int signo)
  617. {
  618. /*
  619. * Otherwise empty handler because systemcalls will get interrupted
  620. * upon signal receipt
  621. * SysV needs the handler to be rearmed
  622. */
  623. signal(SIGCHLD, child_handler);
  624. }
  625. static int set_reuse_addr(int sockfd)
  626. {
  627. int on = 1;
  628. if (!reuseaddr)
  629. return 0;
  630. return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
  631. &on, sizeof(on));
  632. }
  633. #ifndef NO_IPV6
  634. static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
  635. {
  636. int socknum = 0, *socklist = NULL;
  637. int maxfd = -1;
  638. char pbuf[NI_MAXSERV];
  639. struct addrinfo hints, *ai0, *ai;
  640. int gai;
  641. long flags;
  642. sprintf(pbuf, "%d", listen_port);
  643. memset(&hints, 0, sizeof(hints));
  644. hints.ai_family = AF_UNSPEC;
  645. hints.ai_socktype = SOCK_STREAM;
  646. hints.ai_protocol = IPPROTO_TCP;
  647. hints.ai_flags = AI_PASSIVE;
  648. gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
  649. if (gai)
  650. die("getaddrinfo() failed: %s", gai_strerror(gai));
  651. for (ai = ai0; ai; ai = ai->ai_next) {
  652. int sockfd;
  653. sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  654. if (sockfd < 0)
  655. continue;
  656. if (sockfd >= FD_SETSIZE) {
  657. logerror("Socket descriptor too large");
  658. close(sockfd);
  659. continue;
  660. }
  661. #ifdef IPV6_V6ONLY
  662. if (ai->ai_family == AF_INET6) {
  663. int on = 1;
  664. setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
  665. &on, sizeof(on));
  666. /* Note: error is not fatal */
  667. }
  668. #endif
  669. if (set_reuse_addr(sockfd)) {
  670. close(sockfd);
  671. continue;
  672. }
  673. if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
  674. close(sockfd);
  675. continue; /* not fatal */
  676. }
  677. if (listen(sockfd, 5) < 0) {
  678. close(sockfd);
  679. continue; /* not fatal */
  680. }
  681. flags = fcntl(sockfd, F_GETFD, 0);
  682. if (flags >= 0)
  683. fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
  684. socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
  685. socklist[socknum++] = sockfd;
  686. if (maxfd < sockfd)
  687. maxfd = sockfd;
  688. }
  689. freeaddrinfo(ai0);
  690. *socklist_p = socklist;
  691. return socknum;
  692. }
  693. #else /* NO_IPV6 */
  694. static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
  695. {
  696. struct sockaddr_in sin;
  697. int sockfd;
  698. long flags;
  699. memset(&sin, 0, sizeof sin);
  700. sin.sin_family = AF_INET;
  701. sin.sin_port = htons(listen_port);
  702. if (listen_addr) {
  703. /* Well, host better be an IP address here. */
  704. if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
  705. return 0;
  706. } else {
  707. sin.sin_addr.s_addr = htonl(INADDR_ANY);
  708. }
  709. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  710. if (sockfd < 0)
  711. return 0;
  712. if (set_reuse_addr(sockfd)) {
  713. close(sockfd);
  714. return 0;
  715. }
  716. if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
  717. close(sockfd);
  718. return 0;
  719. }
  720. if (listen(sockfd, 5) < 0) {
  721. close(sockfd);
  722. return 0;
  723. }
  724. flags = fcntl(sockfd, F_GETFD, 0);
  725. if (flags >= 0)
  726. fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
  727. *socklist_p = xmalloc(sizeof(int));
  728. **socklist_p = sockfd;
  729. return 1;
  730. }
  731. #endif
  732. static int service_loop(int socknum, int *socklist)
  733. {
  734. struct pollfd *pfd;
  735. int i;
  736. pfd = xcalloc(socknum, sizeof(struct pollfd));
  737. for (i = 0; i < socknum; i++) {
  738. pfd[i].fd = socklist[i];
  739. pfd[i].events = POLLIN;
  740. }
  741. signal(SIGCHLD, child_handler);
  742. for (;;) {
  743. int i;
  744. check_dead_children();
  745. if (poll(pfd, socknum, -1) < 0) {
  746. if (errno != EINTR) {
  747. logerror("Poll failed, resuming: %s",
  748. strerror(errno));
  749. sleep(1);
  750. }
  751. continue;
  752. }
  753. for (i = 0; i < socknum; i++) {
  754. if (pfd[i].revents & POLLIN) {
  755. struct sockaddr_storage ss;
  756. unsigned int sslen = sizeof(ss);
  757. int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
  758. if (incoming < 0) {
  759. switch (errno) {
  760. case EAGAIN:
  761. case EINTR:
  762. case ECONNABORTED:
  763. continue;
  764. default:
  765. die("accept returned %s", strerror(errno));
  766. }
  767. }
  768. handle(incoming, (struct sockaddr *)&ss, sslen);
  769. }
  770. }
  771. }
  772. }
  773. /* if any standard file descriptor is missing open it to /dev/null */
  774. static void sanitize_stdfds(void)
  775. {
  776. int fd = open("/dev/null", O_RDWR, 0);
  777. while (fd != -1 && fd < 2)
  778. fd = dup(fd);
  779. if (fd == -1)
  780. die("open /dev/null or dup failed: %s", strerror(errno));
  781. if (fd > 2)
  782. close(fd);
  783. }
  784. static void daemonize(void)
  785. {
  786. switch (fork()) {
  787. case 0:
  788. break;
  789. case -1:
  790. die("fork failed: %s", strerror(errno));
  791. default:
  792. exit(0);
  793. }
  794. if (setsid() == -1)
  795. die("setsid failed: %s", strerror(errno));
  796. close(0);
  797. close(1);
  798. close(2);
  799. sanitize_stdfds();
  800. }
  801. static void store_pid(const char *path)
  802. {
  803. FILE *f = fopen(path, "w");
  804. if (!f)
  805. die("cannot open pid file %s: %s", path, strerror(errno));
  806. if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
  807. die("failed to write pid file %s: %s", path, strerror(errno));
  808. }
  809. static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
  810. {
  811. int socknum, *socklist;
  812. socknum = socksetup(listen_addr, listen_port, &socklist);
  813. if (socknum == 0)
  814. die("unable to allocate any listen sockets on host %s port %u",
  815. listen_addr, listen_port);
  816. if (pass && gid &&
  817. (initgroups(pass->pw_name, gid) || setgid (gid) ||
  818. setuid(pass->pw_uid)))
  819. die("cannot drop privileges");
  820. return service_loop(socknum, socklist);
  821. }
  822. int main(int argc, char **argv)
  823. {
  824. int listen_port = 0;
  825. char *listen_addr = NULL;
  826. int inetd_mode = 0;
  827. const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
  828. int detach = 0;
  829. struct passwd *pass = NULL;
  830. struct group *group;
  831. gid_t gid = 0;
  832. int i;
  833. git_extract_argv0_path(argv[0]);
  834. for (i = 1; i < argc; i++) {
  835. char *arg = argv[i];
  836. if (!prefixcmp(arg, "--listen=")) {
  837. listen_addr = xstrdup_tolower(arg + 9);
  838. continue;
  839. }
  840. if (!prefixcmp(arg, "--port=")) {
  841. char *end;
  842. unsigned long n;
  843. n = strtoul(arg+7, &end, 0);
  844. if (arg[7] && !*end) {
  845. listen_port = n;
  846. continue;
  847. }
  848. }
  849. if (!strcmp(arg, "--inetd")) {
  850. inetd_mode = 1;
  851. log_syslog = 1;
  852. continue;
  853. }
  854. if (!strcmp(arg, "--verbose")) {
  855. verbose = 1;
  856. continue;
  857. }
  858. if (!strcmp(arg, "--syslog")) {
  859. log_syslog = 1;
  860. continue;
  861. }
  862. if (!strcmp(arg, "--export-all")) {
  863. export_all_trees = 1;
  864. continue;
  865. }
  866. if (!prefixcmp(arg, "--timeout=")) {
  867. timeout = atoi(arg+10);
  868. continue;
  869. }
  870. if (!prefixcmp(arg, "--init-timeout=")) {
  871. init_timeout = atoi(arg+15);
  872. continue;
  873. }
  874. if (!prefixcmp(arg, "--max-connections=")) {
  875. max_connections = atoi(arg+18);
  876. if (max_connections < 0)
  877. max_connections = 0; /* unlimited */
  878. continue;
  879. }
  880. if (!strcmp(arg, "--strict-paths")) {
  881. strict_paths = 1;
  882. continue;
  883. }
  884. if (!prefixcmp(arg, "--base-path=")) {
  885. base_path = arg+12;
  886. continue;
  887. }
  888. if (!strcmp(arg, "--base-path-relaxed")) {
  889. base_path_relaxed = 1;
  890. continue;
  891. }
  892. if (!prefixcmp(arg, "--interpolated-path=")) {
  893. interpolated_path = arg+20;
  894. continue;
  895. }
  896. if (!strcmp(arg, "--reuseaddr")) {
  897. reuseaddr = 1;
  898. continue;
  899. }
  900. if (!strcmp(arg, "--user-path")) {
  901. user_path = "";
  902. continue;
  903. }
  904. if (!prefixcmp(arg, "--user-path=")) {
  905. user_path = arg + 12;
  906. continue;
  907. }
  908. if (!prefixcmp(arg, "--pid-file=")) {
  909. pid_file = arg + 11;
  910. continue;
  911. }
  912. if (!strcmp(arg, "--detach")) {
  913. detach = 1;
  914. log_syslog = 1;
  915. continue;
  916. }
  917. if (!prefixcmp(arg, "--user=")) {
  918. user_name = arg + 7;
  919. continue;
  920. }
  921. if (!prefixcmp(arg, "--group=")) {
  922. group_name = arg + 8;
  923. continue;
  924. }
  925. if (!prefixcmp(arg, "--enable=")) {
  926. enable_service(arg + 9, 1);
  927. continue;
  928. }
  929. if (!prefixcmp(arg, "--disable=")) {
  930. enable_service(arg + 10, 0);
  931. continue;
  932. }
  933. if (!prefixcmp(arg, "--allow-override=")) {
  934. make_service_overridable(arg + 17, 1);
  935. continue;
  936. }
  937. if (!prefixcmp(arg, "--forbid-override=")) {
  938. make_service_overridable(arg + 18, 0);
  939. continue;
  940. }
  941. if (!strcmp(arg, "--")) {
  942. ok_paths = &argv[i+1];
  943. break;
  944. } else if (arg[0] != '-') {
  945. ok_paths = &argv[i];
  946. break;
  947. }
  948. usage(daemon_usage);
  949. }
  950. if (log_syslog) {
  951. openlog("git-daemon", LOG_PID, LOG_DAEMON);
  952. set_die_routine(daemon_die);
  953. } else
  954. /* avoid splitting a message in the middle */
  955. setvbuf(stderr, NULL, _IOLBF, 0);
  956. if (inetd_mode && (group_name || user_name))
  957. die("--user and --group are incompatible with --inetd");
  958. if (inetd_mode && (listen_port || listen_addr))
  959. die("--listen= and --port= are incompatible with --inetd");
  960. else if (listen_port == 0)
  961. listen_port = DEFAULT_GIT_PORT;
  962. if (group_name && !user_name)
  963. die("--group supplied without --user");
  964. if (user_name) {
  965. pass = getpwnam(user_name);
  966. if (!pass)
  967. die("user not found - %s", user_name);
  968. if (!group_name)
  969. gid = pass->pw_gid;
  970. else {
  971. group = getgrnam(group_name);
  972. if (!group)
  973. die("group not found - %s", group_name);
  974. gid = group->gr_gid;
  975. }
  976. }
  977. if (strict_paths && (!ok_paths || !*ok_paths))
  978. die("option --strict-paths requires a whitelist");
  979. if (base_path && !is_directory(base_path))
  980. die("base-path '%s' does not exist or is not a directory",
  981. base_path);
  982. if (inetd_mode) {
  983. struct sockaddr_storage ss;
  984. struct sockaddr *peer = (struct sockaddr *)&ss;
  985. socklen_t slen = sizeof(ss);
  986. if (!freopen("/dev/null", "w", stderr))
  987. die("failed to redirect stderr to /dev/null: %s",
  988. strerror(errno));
  989. if (getpeername(0, peer, &slen))
  990. peer = NULL;
  991. return execute(peer);
  992. }
  993. if (detach) {
  994. daemonize();
  995. loginfo("Ready to rumble");
  996. }
  997. else
  998. sanitize_stdfds();
  999. if (pid_file)
  1000. store_pid(pid_file);
  1001. return serve(listen_addr, listen_port, pass, gid);
  1002. }