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.

1151 lines
25KB

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