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.

1172 lines
26KB

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