Blob


1 /*
2 * Copyright (c) 2022 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/tree.h>
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/socket.h>
23 #include <sys/un.h>
24 #include <sys/wait.h>
26 #include <fcntl.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <event.h>
30 #include <limits.h>
31 #include <pwd.h>
32 #include <imsg.h>
33 #include <sha1.h>
34 #include <signal.h>
35 #include <siphash.h>
36 #include <stdarg.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <syslog.h>
41 #include <unistd.h>
43 #include "got_error.h"
44 #include "got_opentemp.h"
45 #include "got_path.h"
46 #include "got_repository.h"
47 #include "got_object.h"
48 #include "got_reference.h"
50 #include "got_lib_delta.h"
51 #include "got_lib_object.h"
52 #include "got_lib_object_cache.h"
53 #include "got_lib_sha1.h"
54 #include "got_lib_gitproto.h"
55 #include "got_lib_pack.h"
56 #include "got_lib_repository.h"
58 #include "gotd.h"
59 #include "log.h"
60 #include "listen.h"
61 #include "auth.h"
62 #include "repo_read.h"
63 #include "repo_write.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 struct gotd_client {
70 STAILQ_ENTRY(gotd_client) entry;
71 enum gotd_client_state state;
72 struct gotd_client_capability *capabilities;
73 size_t ncapa_alloc;
74 size_t ncapabilities;
75 uint32_t id;
76 int fd;
77 int delta_cache_fd;
78 struct gotd_imsgev iev;
79 struct event tmo;
80 uid_t euid;
81 gid_t egid;
82 struct gotd_child_proc *repo_read;
83 struct gotd_child_proc *repo_write;
84 struct gotd_child_proc *auth;
85 int required_auth;
86 char *packfile_path;
87 char *packidx_path;
88 int nref_updates;
89 };
90 STAILQ_HEAD(gotd_clients, gotd_client);
92 static struct gotd_clients gotd_clients[GOTD_CLIENT_TABLE_SIZE];
93 static SIPHASH_KEY clients_hash_key;
94 volatile int client_cnt;
95 static struct timeval auth_timeout = { 5, 0 };
96 static struct gotd gotd;
98 void gotd_sighdlr(int sig, short event, void *arg);
99 static void gotd_shutdown(void);
100 static const struct got_error *start_repo_child(struct gotd_client *,
101 enum gotd_procid, struct gotd_repo *, char *, const char *, int, int);
102 static const struct got_error *start_auth_child(struct gotd_client *, int,
103 struct gotd_repo *, char *, const char *, int, int);
104 static void kill_proc(struct gotd_child_proc *, int);
106 __dead static void
107 usage()
109 fprintf(stderr, "usage: %s [-dv] [-f config-file]\n", getprogname());
110 exit(1);
113 static int
114 unix_socket_listen(const char *unix_socket_path, uid_t uid, gid_t gid)
116 struct sockaddr_un sun;
117 int fd = -1;
118 mode_t old_umask, mode;
120 fd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK| SOCK_CLOEXEC, 0);
121 if (fd == -1) {
122 log_warn("socket");
123 return -1;
126 sun.sun_family = AF_UNIX;
127 if (strlcpy(sun.sun_path, unix_socket_path,
128 sizeof(sun.sun_path)) >= sizeof(sun.sun_path)) {
129 log_warnx("%s: name too long", unix_socket_path);
130 close(fd);
131 return -1;
134 if (unlink(unix_socket_path) == -1) {
135 if (errno != ENOENT) {
136 log_warn("unlink %s", unix_socket_path);
137 close(fd);
138 return -1;
142 old_umask = umask(S_IXUSR|S_IXGRP|S_IWOTH|S_IROTH|S_IXOTH);
143 mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH;
145 if (bind(fd, (struct sockaddr *)&sun, sizeof(sun)) == -1) {
146 log_warn("bind: %s", unix_socket_path);
147 close(fd);
148 umask(old_umask);
149 return -1;
152 umask(old_umask);
154 if (chmod(unix_socket_path, mode) == -1) {
155 log_warn("chmod %o %s", mode, unix_socket_path);
156 close(fd);
157 unlink(unix_socket_path);
158 return -1;
161 if (chown(unix_socket_path, uid, gid) == -1) {
162 log_warn("chown %s uid=%d gid=%d", unix_socket_path, uid, gid);
163 close(fd);
164 unlink(unix_socket_path);
165 return -1;
168 if (listen(fd, GOTD_UNIX_SOCKET_BACKLOG) == -1) {
169 log_warn("listen");
170 close(fd);
171 unlink(unix_socket_path);
172 return -1;
175 return fd;
178 static uint64_t
179 client_hash(uint32_t client_id)
181 return SipHash24(&clients_hash_key, &client_id, sizeof(client_id));
184 static void
185 add_client(struct gotd_client *client)
187 uint64_t slot = client_hash(client->id) % nitems(gotd_clients);
188 STAILQ_INSERT_HEAD(&gotd_clients[slot], client, entry);
189 client_cnt++;
192 static struct gotd_client *
193 find_client(uint32_t client_id)
195 uint64_t slot;
196 struct gotd_client *c;
198 slot = client_hash(client_id) % nitems(gotd_clients);
199 STAILQ_FOREACH(c, &gotd_clients[slot], entry) {
200 if (c->id == client_id)
201 return c;
204 return NULL;
207 static struct gotd_child_proc *
208 get_client_proc(struct gotd_client *client)
210 if (client->repo_read && client->repo_write) {
211 fatalx("uid %d is reading and writing in the same session",
212 client->euid);
213 /* NOTREACHED */
216 if (client->repo_read)
217 return client->repo_read;
218 else if (client->repo_write)
219 return client->repo_write;
221 return NULL;
224 static struct gotd_client *
225 find_client_by_proc_fd(int fd)
227 uint64_t slot;
229 for (slot = 0; slot < nitems(gotd_clients); slot++) {
230 struct gotd_client *c;
232 STAILQ_FOREACH(c, &gotd_clients[slot], entry) {
233 struct gotd_child_proc *proc = get_client_proc(c);
234 if (proc && proc->iev.ibuf.fd == fd)
235 return c;
236 if (c->auth && c->auth->iev.ibuf.fd == fd)
237 return c;
241 return NULL;
244 static int
245 client_is_reading(struct gotd_client *client)
247 return client->repo_read != NULL;
250 static int
251 client_is_writing(struct gotd_client *client)
253 return client->repo_write != NULL;
256 static const struct got_error *
257 ensure_client_is_reading(struct gotd_client *client)
259 if (!client_is_reading(client)) {
260 return got_error_fmt(GOT_ERR_BAD_PACKET,
261 "uid %d made a read-request but is not reading from "
262 "a repository", client->euid);
265 return NULL;
268 static const struct got_error *
269 ensure_client_is_writing(struct gotd_client *client)
271 if (!client_is_writing(client)) {
272 return got_error_fmt(GOT_ERR_BAD_PACKET,
273 "uid %d made a write-request but is not writing to "
274 "a repository", client->euid);
277 return NULL;
280 static const struct got_error *
281 ensure_client_is_not_writing(struct gotd_client *client)
283 if (client_is_writing(client)) {
284 return got_error_fmt(GOT_ERR_BAD_PACKET,
285 "uid %d made a read-request but is writing to "
286 "a repository", client->euid);
289 return NULL;
292 static const struct got_error *
293 ensure_client_is_not_reading(struct gotd_client *client)
295 if (client_is_reading(client)) {
296 return got_error_fmt(GOT_ERR_BAD_PACKET,
297 "uid %d made a write-request but is reading from "
298 "a repository", client->euid);
301 return NULL;
304 static void
305 wait_for_child(pid_t child_pid)
307 pid_t pid;
308 int status;
310 log_debug("waiting for child PID %ld to terminate",
311 (long)child_pid);
313 do {
314 pid = waitpid(child_pid, &status, WNOHANG);
315 if (pid == -1) {
316 if (errno != EINTR && errno != ECHILD)
317 fatal("wait");
318 } else if (WIFSIGNALED(status)) {
319 log_warnx("child PID %ld terminated; signal %d",
320 (long)pid, WTERMSIG(status));
322 } while (pid != -1 || (pid == -1 && errno == EINTR));
325 static void
326 kill_auth_proc(struct gotd_client *client)
328 struct gotd_child_proc *proc;
330 if (client->auth == NULL)
331 return;
333 proc = client->auth;
334 client->auth = NULL;
336 event_del(&proc->iev.ev);
337 msgbuf_clear(&proc->iev.ibuf.w);
338 close(proc->iev.ibuf.fd);
339 kill_proc(proc, 0);
340 wait_for_child(proc->pid);
341 free(proc);
344 static void
345 disconnect(struct gotd_client *client)
347 struct gotd_imsg_disconnect idisconnect;
348 struct gotd_child_proc *proc = get_client_proc(client);
349 struct gotd_child_proc *listen_proc = &gotd.listen_proc;
350 uint64_t slot;
352 log_debug("uid %d: disconnecting", client->euid);
354 kill_auth_proc(client);
356 idisconnect.client_id = client->id;
357 if (proc) {
358 if (gotd_imsg_compose_event(&proc->iev,
359 GOTD_IMSG_DISCONNECT, PROC_GOTD, -1,
360 &idisconnect, sizeof(idisconnect)) == -1)
361 log_warn("imsg compose DISCONNECT");
363 msgbuf_clear(&proc->iev.ibuf.w);
364 close(proc->iev.ibuf.fd);
365 kill_proc(proc, 0);
366 wait_for_child(proc->pid);
367 free(proc);
368 proc = NULL;
371 if (gotd_imsg_compose_event(&listen_proc->iev,
372 GOTD_IMSG_DISCONNECT, PROC_GOTD, -1,
373 &idisconnect, sizeof(idisconnect)) == -1)
374 log_warn("imsg compose DISCONNECT");
376 slot = client_hash(client->id) % nitems(gotd_clients);
377 STAILQ_REMOVE(&gotd_clients[slot], client, gotd_client, entry);
378 imsg_clear(&client->iev.ibuf);
379 event_del(&client->iev.ev);
380 evtimer_del(&client->tmo);
381 close(client->fd);
382 if (client->delta_cache_fd != -1)
383 close(client->delta_cache_fd);
384 if (client->packfile_path) {
385 if (unlink(client->packfile_path) == -1 && errno != ENOENT)
386 log_warn("unlink %s: ", client->packfile_path);
387 free(client->packfile_path);
389 if (client->packidx_path) {
390 if (unlink(client->packidx_path) == -1 && errno != ENOENT)
391 log_warn("unlink %s: ", client->packidx_path);
392 free(client->packidx_path);
394 free(client->capabilities);
395 free(client);
396 client_cnt--;
399 static void
400 disconnect_on_error(struct gotd_client *client, const struct got_error *err)
402 struct imsgbuf ibuf;
404 log_warnx("uid %d: %s", client->euid, err->msg);
405 if (err->code != GOT_ERR_EOF) {
406 imsg_init(&ibuf, client->fd);
407 gotd_imsg_send_error(&ibuf, 0, PROC_GOTD, err);
408 imsg_clear(&ibuf);
410 disconnect(client);
413 static const struct got_error *
414 send_repo_info(struct gotd_imsgev *iev, struct gotd_repo *repo)
416 const struct got_error *err = NULL;
417 struct gotd_imsg_info_repo irepo;
419 memset(&irepo, 0, sizeof(irepo));
421 if (strlcpy(irepo.repo_name, repo->name, sizeof(irepo.repo_name))
422 >= sizeof(irepo.repo_name))
423 return got_error_msg(GOT_ERR_NO_SPACE, "repo name too long");
424 if (strlcpy(irepo.repo_path, repo->path, sizeof(irepo.repo_path))
425 >= sizeof(irepo.repo_path))
426 return got_error_msg(GOT_ERR_NO_SPACE, "repo path too long");
428 if (gotd_imsg_compose_event(iev, GOTD_IMSG_INFO_REPO, PROC_GOTD, -1,
429 &irepo, sizeof(irepo)) == -1) {
430 err = got_error_from_errno("imsg compose INFO_REPO");
431 if (err)
432 return err;
435 return NULL;
438 static const struct got_error *
439 send_capability(struct gotd_client_capability *capa, struct gotd_imsgev* iev)
441 const struct got_error *err = NULL;
442 struct gotd_imsg_capability icapa;
443 size_t len;
444 struct ibuf *wbuf;
446 memset(&icapa, 0, sizeof(icapa));
448 icapa.key_len = strlen(capa->key);
449 len = sizeof(icapa) + icapa.key_len;
450 if (capa->value) {
451 icapa.value_len = strlen(capa->value);
452 len += icapa.value_len;
455 wbuf = imsg_create(&iev->ibuf, GOTD_IMSG_CAPABILITY, 0, 0, len);
456 if (wbuf == NULL) {
457 err = got_error_from_errno("imsg_create CAPABILITY");
458 return err;
461 if (imsg_add(wbuf, &icapa, sizeof(icapa)) == -1)
462 return got_error_from_errno("imsg_add CAPABILITY");
463 if (imsg_add(wbuf, capa->key, icapa.key_len) == -1)
464 return got_error_from_errno("imsg_add CAPABILITY");
465 if (capa->value) {
466 if (imsg_add(wbuf, capa->value, icapa.value_len) == -1)
467 return got_error_from_errno("imsg_add CAPABILITY");
470 wbuf->fd = -1;
471 imsg_close(&iev->ibuf, wbuf);
473 gotd_imsg_event_add(iev);
475 return NULL;
478 static const struct got_error *
479 send_client_info(struct gotd_imsgev *iev, struct gotd_client *client)
481 const struct got_error *err = NULL;
482 struct gotd_imsg_info_client iclient;
483 struct gotd_child_proc *proc;
484 size_t i;
486 memset(&iclient, 0, sizeof(iclient));
487 iclient.euid = client->euid;
488 iclient.egid = client->egid;
490 proc = get_client_proc(client);
491 if (proc) {
492 if (strlcpy(iclient.repo_name, proc->repo_path,
493 sizeof(iclient.repo_name)) >= sizeof(iclient.repo_name)) {
494 return got_error_msg(GOT_ERR_NO_SPACE,
495 "repo name too long");
497 if (client_is_writing(client))
498 iclient.is_writing = 1;
501 iclient.state = client->state;
502 iclient.ncapabilities = client->ncapabilities;
504 if (gotd_imsg_compose_event(iev, GOTD_IMSG_INFO_CLIENT, PROC_GOTD, -1,
505 &iclient, sizeof(iclient)) == -1) {
506 err = got_error_from_errno("imsg compose INFO_CLIENT");
507 if (err)
508 return err;
511 for (i = 0; i < client->ncapabilities; i++) {
512 struct gotd_client_capability *capa;
513 capa = &client->capabilities[i];
514 err = send_capability(capa, iev);
515 if (err)
516 return err;
519 return NULL;
522 static const struct got_error *
523 send_info(struct gotd_client *client)
525 const struct got_error *err = NULL;
526 struct gotd_imsg_info info;
527 uint64_t slot;
528 struct gotd_repo *repo;
530 if (client->euid != 0)
531 return got_error_set_errno(EPERM, "info");
533 info.pid = gotd.pid;
534 info.verbosity = gotd.verbosity;
535 info.nrepos = gotd.nrepos;
536 info.nclients = client_cnt - 1;
538 if (gotd_imsg_compose_event(&client->iev, GOTD_IMSG_INFO, PROC_GOTD, -1,
539 &info, sizeof(info)) == -1) {
540 err = got_error_from_errno("imsg compose INFO");
541 if (err)
542 return err;
545 TAILQ_FOREACH(repo, &gotd.repos, entry) {
546 err = send_repo_info(&client->iev, repo);
547 if (err)
548 return err;
551 for (slot = 0; slot < nitems(gotd_clients); slot++) {
552 struct gotd_client *c;
553 STAILQ_FOREACH(c, &gotd_clients[slot], entry) {
554 if (c->id == client->id)
555 continue;
556 err = send_client_info(&client->iev, c);
557 if (err)
558 return err;
562 return NULL;
565 static const struct got_error *
566 stop_gotd(struct gotd_client *client)
569 if (client->euid != 0)
570 return got_error_set_errno(EPERM, "stop");
572 gotd_shutdown();
573 /* NOTREACHED */
574 return NULL;
577 static struct gotd_repo *
578 find_repo_by_name(const char *repo_name)
580 struct gotd_repo *repo;
581 size_t namelen;
583 TAILQ_FOREACH(repo, &gotd.repos, entry) {
584 namelen = strlen(repo->name);
585 if (strncmp(repo->name, repo_name, namelen) != 0)
586 continue;
587 if (repo_name[namelen] == '\0' ||
588 strcmp(&repo_name[namelen], ".git") == 0)
589 return repo;
592 return NULL;
595 static const struct got_error *
596 start_client_session(struct gotd_client *client, struct imsg *imsg)
598 const struct got_error *err;
599 struct gotd_imsg_list_refs ireq;
600 struct gotd_repo *repo = NULL;
601 size_t datalen;
603 log_debug("list-refs request from uid %d", client->euid);
605 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
606 if (datalen != sizeof(ireq))
607 return got_error(GOT_ERR_PRIVSEP_LEN);
609 memcpy(&ireq, imsg->data, datalen);
611 if (ireq.client_is_reading) {
612 err = ensure_client_is_not_writing(client);
613 if (err)
614 return err;
615 repo = find_repo_by_name(ireq.repo_name);
616 if (repo == NULL)
617 return got_error(GOT_ERR_NOT_GIT_REPO);
618 err = start_auth_child(client, GOTD_AUTH_READ, repo,
619 gotd.argv0, gotd.confpath, gotd.daemonize,
620 gotd.verbosity);
621 if (err)
622 return err;
623 } else {
624 err = ensure_client_is_not_reading(client);
625 if (err)
626 return err;
627 repo = find_repo_by_name(ireq.repo_name);
628 if (repo == NULL)
629 return got_error(GOT_ERR_NOT_GIT_REPO);
630 err = start_auth_child(client,
631 GOTD_AUTH_READ | GOTD_AUTH_WRITE,
632 repo, gotd.argv0, gotd.confpath, gotd.daemonize,
633 gotd.verbosity);
634 if (err)
635 return err;
638 /* Flow continues upon authentication successs/failure or timeout. */
639 return NULL;
642 static const struct got_error *
643 forward_want(struct gotd_client *client, struct imsg *imsg)
645 struct gotd_imsg_want ireq;
646 struct gotd_imsg_want iwant;
647 size_t datalen;
649 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
650 if (datalen != sizeof(ireq))
651 return got_error(GOT_ERR_PRIVSEP_LEN);
653 memcpy(&ireq, imsg->data, datalen);
655 memset(&iwant, 0, sizeof(iwant));
656 memcpy(iwant.object_id, ireq.object_id, SHA1_DIGEST_LENGTH);
657 iwant.client_id = client->id;
659 if (gotd_imsg_compose_event(&client->repo_read->iev, GOTD_IMSG_WANT,
660 PROC_GOTD, -1, &iwant, sizeof(iwant)) == -1)
661 return got_error_from_errno("imsg compose WANT");
663 return NULL;
666 static const struct got_error *
667 forward_ref_update(struct gotd_client *client, struct imsg *imsg)
669 const struct got_error *err = NULL;
670 struct gotd_imsg_ref_update ireq;
671 struct gotd_imsg_ref_update *iref = NULL;
672 size_t datalen;
674 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
675 if (datalen < sizeof(ireq))
676 return got_error(GOT_ERR_PRIVSEP_LEN);
677 memcpy(&ireq, imsg->data, sizeof(ireq));
678 if (datalen != sizeof(ireq) + ireq.name_len)
679 return got_error(GOT_ERR_PRIVSEP_LEN);
681 iref = malloc(datalen);
682 if (iref == NULL)
683 return got_error_from_errno("malloc");
684 memcpy(iref, imsg->data, datalen);
686 iref->client_id = client->id;
687 if (gotd_imsg_compose_event(&client->repo_write->iev,
688 GOTD_IMSG_REF_UPDATE, PROC_GOTD, -1, iref, datalen) == -1)
689 err = got_error_from_errno("imsg compose REF_UPDATE");
690 free(iref);
691 return err;
694 static const struct got_error *
695 forward_have(struct gotd_client *client, struct imsg *imsg)
697 struct gotd_imsg_have ireq;
698 struct gotd_imsg_have ihave;
699 size_t datalen;
701 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
702 if (datalen != sizeof(ireq))
703 return got_error(GOT_ERR_PRIVSEP_LEN);
705 memcpy(&ireq, imsg->data, datalen);
707 memset(&ihave, 0, sizeof(ihave));
708 memcpy(ihave.object_id, ireq.object_id, SHA1_DIGEST_LENGTH);
709 ihave.client_id = client->id;
711 if (gotd_imsg_compose_event(&client->repo_read->iev, GOTD_IMSG_HAVE,
712 PROC_GOTD, -1, &ihave, sizeof(ihave)) == -1)
713 return got_error_from_errno("imsg compose HAVE");
715 return NULL;
718 static int
719 client_has_capability(struct gotd_client *client, const char *capastr)
721 struct gotd_client_capability *capa;
722 size_t i;
724 if (client->ncapabilities == 0)
725 return 0;
727 for (i = 0; i < client->ncapabilities; i++) {
728 capa = &client->capabilities[i];
729 if (strcmp(capa->key, capastr) == 0)
730 return 1;
733 return 0;
736 static const struct got_error *
737 recv_capabilities(struct gotd_client *client, struct imsg *imsg)
739 struct gotd_imsg_capabilities icapas;
740 size_t datalen;
742 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
743 if (datalen != sizeof(icapas))
744 return got_error(GOT_ERR_PRIVSEP_LEN);
745 memcpy(&icapas, imsg->data, sizeof(icapas));
747 client->ncapa_alloc = icapas.ncapabilities;
748 client->capabilities = calloc(client->ncapa_alloc,
749 sizeof(*client->capabilities));
750 if (client->capabilities == NULL) {
751 client->ncapa_alloc = 0;
752 return got_error_from_errno("calloc");
755 log_debug("expecting %zu capabilities from uid %d",
756 client->ncapa_alloc, client->euid);
757 return NULL;
760 static const struct got_error *
761 recv_capability(struct gotd_client *client, struct imsg *imsg)
763 struct gotd_imsg_capability icapa;
764 struct gotd_client_capability *capa;
765 size_t datalen;
766 char *key, *value = NULL;
768 if (client->capabilities == NULL ||
769 client->ncapabilities >= client->ncapa_alloc) {
770 return got_error_msg(GOT_ERR_BAD_REQUEST,
771 "unexpected capability received");
774 memset(&icapa, 0, sizeof(icapa));
776 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
777 if (datalen < sizeof(icapa))
778 return got_error(GOT_ERR_PRIVSEP_LEN);
779 memcpy(&icapa, imsg->data, sizeof(icapa));
781 if (datalen != sizeof(icapa) + icapa.key_len + icapa.value_len)
782 return got_error(GOT_ERR_PRIVSEP_LEN);
784 key = malloc(icapa.key_len + 1);
785 if (key == NULL)
786 return got_error_from_errno("malloc");
787 if (icapa.value_len > 0) {
788 value = malloc(icapa.value_len + 1);
789 if (value == NULL) {
790 free(key);
791 return got_error_from_errno("malloc");
795 memcpy(key, imsg->data + sizeof(icapa), icapa.key_len);
796 key[icapa.key_len] = '\0';
797 if (value) {
798 memcpy(value, imsg->data + sizeof(icapa) + icapa.key_len,
799 icapa.value_len);
800 value[icapa.value_len] = '\0';
803 capa = &client->capabilities[client->ncapabilities++];
804 capa->key = key;
805 capa->value = value;
807 if (value)
808 log_debug("uid %d: capability %s=%s", client->euid, key, value);
809 else
810 log_debug("uid %d: capability %s", client->euid, key);
812 return NULL;
815 static const struct got_error *
816 send_packfile(struct gotd_client *client)
818 const struct got_error *err = NULL;
819 struct gotd_imsg_send_packfile ipack;
820 struct gotd_imsg_packfile_pipe ipipe;
821 int pipe[2];
823 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe) == -1)
824 return got_error_from_errno("socketpair");
826 memset(&ipack, 0, sizeof(ipack));
827 memset(&ipipe, 0, sizeof(ipipe));
829 ipack.client_id = client->id;
830 if (client_has_capability(client, GOT_CAPA_SIDE_BAND_64K))
831 ipack.report_progress = 1;
833 client->delta_cache_fd = got_opentempfd();
834 if (client->delta_cache_fd == -1)
835 return got_error_from_errno("got_opentempfd");
837 if (gotd_imsg_compose_event(&client->repo_read->iev,
838 GOTD_IMSG_SEND_PACKFILE, PROC_GOTD, client->delta_cache_fd,
839 &ipack, sizeof(ipack)) == -1) {
840 err = got_error_from_errno("imsg compose SEND_PACKFILE");
841 close(pipe[0]);
842 close(pipe[1]);
843 return err;
846 ipipe.client_id = client->id;
848 /* Send pack pipe end 0 to repo_read. */
849 if (gotd_imsg_compose_event(&client->repo_read->iev,
850 GOTD_IMSG_PACKFILE_PIPE, PROC_GOTD, pipe[0],
851 &ipipe, sizeof(ipipe)) == -1) {
852 err = got_error_from_errno("imsg compose PACKFILE_PIPE");
853 close(pipe[1]);
854 return err;
857 /* Send pack pipe end 1 to gotsh(1) (expects just an fd, no data). */
858 if (gotd_imsg_compose_event(&client->iev,
859 GOTD_IMSG_PACKFILE_PIPE, PROC_GOTD, pipe[1], NULL, 0) == -1)
860 err = got_error_from_errno("imsg compose PACKFILE_PIPE");
862 return err;
865 static const struct got_error *
866 recv_packfile(struct gotd_client *client)
868 const struct got_error *err = NULL;
869 struct gotd_imsg_recv_packfile ipack;
870 struct gotd_imsg_packfile_pipe ipipe;
871 struct gotd_imsg_packidx_file ifile;
872 char *basepath = NULL, *pack_path = NULL, *idx_path = NULL;
873 int packfd = -1, idxfd = -1;
874 int pipe[2] = { -1, -1 };
876 if (client->packfile_path) {
877 return got_error_fmt(GOT_ERR_PRIVSEP_MSG,
878 "uid %d already has a pack file", client->euid);
881 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe) == -1)
882 return got_error_from_errno("socketpair");
884 memset(&ipipe, 0, sizeof(ipipe));
885 ipipe.client_id = client->id;
887 /* Send pack pipe end 0 to repo_write. */
888 if (gotd_imsg_compose_event(&client->repo_write->iev,
889 GOTD_IMSG_PACKFILE_PIPE, PROC_GOTD, pipe[0],
890 &ipipe, sizeof(ipipe)) == -1) {
891 err = got_error_from_errno("imsg compose PACKFILE_PIPE");
892 pipe[0] = -1;
893 goto done;
895 pipe[0] = -1;
897 /* Send pack pipe end 1 to gotsh(1) (expects just an fd, no data). */
898 if (gotd_imsg_compose_event(&client->iev,
899 GOTD_IMSG_PACKFILE_PIPE, PROC_GOTD, pipe[1], NULL, 0) == -1)
900 err = got_error_from_errno("imsg compose PACKFILE_PIPE");
901 pipe[1] = -1;
903 if (asprintf(&basepath, "%s/%s/receiving-from-uid-%d.pack",
904 client->repo_write->repo_path, GOT_OBJECTS_PACK_DIR,
905 client->euid) == -1) {
906 err = got_error_from_errno("asprintf");
907 goto done;
910 err = got_opentemp_named_fd(&pack_path, &packfd, basepath, "");
911 if (err)
912 goto done;
914 free(basepath);
915 if (asprintf(&basepath, "%s/%s/receiving-from-uid-%d.idx",
916 client->repo_write->repo_path, GOT_OBJECTS_PACK_DIR,
917 client->euid) == -1) {
918 err = got_error_from_errno("asprintf");
919 basepath = NULL;
920 goto done;
922 err = got_opentemp_named_fd(&idx_path, &idxfd, basepath, "");
923 if (err)
924 goto done;
926 memset(&ifile, 0, sizeof(ifile));
927 ifile.client_id = client->id;
928 if (gotd_imsg_compose_event(&client->repo_write->iev,
929 GOTD_IMSG_PACKIDX_FILE, PROC_GOTD, idxfd,
930 &ifile, sizeof(ifile)) == -1) {
931 err = got_error_from_errno("imsg compose PACKIDX_FILE");
932 idxfd = -1;
933 goto done;
935 idxfd = -1;
937 memset(&ipack, 0, sizeof(ipack));
938 ipack.client_id = client->id;
939 if (client_has_capability(client, GOT_CAPA_REPORT_STATUS))
940 ipack.report_status = 1;
942 if (gotd_imsg_compose_event(&client->repo_write->iev,
943 GOTD_IMSG_RECV_PACKFILE, PROC_GOTD, packfd,
944 &ipack, sizeof(ipack)) == -1) {
945 err = got_error_from_errno("imsg compose RECV_PACKFILE");
946 packfd = -1;
947 goto done;
949 packfd = -1;
951 done:
952 free(basepath);
953 if (pipe[0] != -1 && close(pipe[0]) == -1 && err == NULL)
954 err = got_error_from_errno("close");
955 if (pipe[1] != -1 && close(pipe[1]) == -1 && err == NULL)
956 err = got_error_from_errno("close");
957 if (packfd != -1 && close(packfd) == -1 && err == NULL)
958 err = got_error_from_errno("close");
959 if (idxfd != -1 && close(idxfd) == -1 && err == NULL)
960 err = got_error_from_errno("close");
961 if (err) {
962 free(pack_path);
963 free(idx_path);
964 } else {
965 client->packfile_path = pack_path;
966 client->packidx_path = idx_path;
968 return err;
971 static void
972 gotd_request(int fd, short events, void *arg)
974 struct gotd_imsgev *iev = arg;
975 struct imsgbuf *ibuf = &iev->ibuf;
976 struct gotd_client *client = iev->handler_arg;
977 const struct got_error *err = NULL;
978 struct imsg imsg;
979 ssize_t n;
981 if (events & EV_WRITE) {
982 while (ibuf->w.queued) {
983 n = msgbuf_write(&ibuf->w);
984 if (n == -1 && errno == EPIPE) {
985 /*
986 * The client has closed its socket.
987 * This can happen when Git clients are
988 * done sending pack file data.
989 */
990 msgbuf_clear(&ibuf->w);
991 continue;
992 } else if (n == -1 && errno != EAGAIN) {
993 err = got_error_from_errno("imsg_flush");
994 disconnect_on_error(client, err);
995 return;
997 if (n == 0) {
998 /* Connection closed. */
999 err = got_error(GOT_ERR_EOF);
1000 disconnect_on_error(client, err);
1001 return;
1005 /* Disconnect gotctl(8) now that messages have been sent. */
1006 if (!client_is_reading(client) && !client_is_writing(client)) {
1007 disconnect(client);
1008 return;
1012 if ((events & EV_READ) == 0)
1013 return;
1015 memset(&imsg, 0, sizeof(imsg));
1017 while (err == NULL) {
1018 err = gotd_imsg_recv(&imsg, ibuf, 0);
1019 if (err) {
1020 if (err->code == GOT_ERR_PRIVSEP_READ)
1021 err = NULL;
1022 break;
1025 evtimer_del(&client->tmo);
1027 switch (imsg.hdr.type) {
1028 case GOTD_IMSG_INFO:
1029 err = send_info(client);
1030 break;
1031 case GOTD_IMSG_STOP:
1032 err = stop_gotd(client);
1033 break;
1034 case GOTD_IMSG_LIST_REFS:
1035 if (client->state != GOTD_STATE_EXPECT_LIST_REFS) {
1036 err = got_error_msg(GOT_ERR_BAD_REQUEST,
1037 "unexpected list-refs request received");
1038 break;
1040 err = start_client_session(client, &imsg);
1041 if (err)
1042 break;
1043 break;
1044 case GOTD_IMSG_CAPABILITIES:
1045 if (client->state != GOTD_STATE_EXPECT_CAPABILITIES) {
1046 err = got_error_msg(GOT_ERR_BAD_REQUEST,
1047 "unexpected capabilities received");
1048 break;
1050 log_debug("receiving capabilities from uid %d",
1051 client->euid);
1052 err = recv_capabilities(client, &imsg);
1053 break;
1054 case GOTD_IMSG_CAPABILITY:
1055 if (client->state != GOTD_STATE_EXPECT_CAPABILITIES) {
1056 err = got_error_msg(GOT_ERR_BAD_REQUEST,
1057 "unexpected capability received");
1058 break;
1060 err = recv_capability(client, &imsg);
1061 if (err || client->ncapabilities < client->ncapa_alloc)
1062 break;
1063 if (client_is_reading(client)) {
1064 client->state = GOTD_STATE_EXPECT_WANT;
1065 log_debug("uid %d: expecting want-lines",
1066 client->euid);
1067 } else if (client_is_writing(client)) {
1068 client->state = GOTD_STATE_EXPECT_REF_UPDATE;
1069 log_debug("uid %d: expecting ref-update-lines",
1070 client->euid);
1071 } else
1072 fatalx("client %d is both reading and writing",
1073 client->euid);
1074 break;
1075 case GOTD_IMSG_WANT:
1076 if (client->state != GOTD_STATE_EXPECT_WANT) {
1077 err = got_error_msg(GOT_ERR_BAD_REQUEST,
1078 "unexpected want-line received");
1079 break;
1081 log_debug("received want-line from uid %d",
1082 client->euid);
1083 err = ensure_client_is_reading(client);
1084 if (err)
1085 break;
1086 err = forward_want(client, &imsg);
1087 break;
1088 case GOTD_IMSG_REF_UPDATE:
1089 if (client->state != GOTD_STATE_EXPECT_REF_UPDATE) {
1090 err = got_error_msg(GOT_ERR_BAD_REQUEST,
1091 "unexpected ref-update-line received");
1092 break;
1094 log_debug("received ref-update-line from uid %d",
1095 client->euid);
1096 err = ensure_client_is_writing(client);
1097 if (err)
1098 break;
1099 err = forward_ref_update(client, &imsg);
1100 if (err)
1101 break;
1102 client->state = GOTD_STATE_EXPECT_MORE_REF_UPDATES;
1103 break;
1104 case GOTD_IMSG_HAVE:
1105 if (client->state != GOTD_STATE_EXPECT_HAVE) {
1106 err = got_error_msg(GOT_ERR_BAD_REQUEST,
1107 "unexpected have-line received");
1108 break;
1110 log_debug("received have-line from uid %d",
1111 client->euid);
1112 err = ensure_client_is_reading(client);
1113 if (err)
1114 break;
1115 err = forward_have(client, &imsg);
1116 if (err)
1117 break;
1118 break;
1119 case GOTD_IMSG_FLUSH:
1120 if (client->state == GOTD_STATE_EXPECT_WANT ||
1121 client->state == GOTD_STATE_EXPECT_HAVE) {
1122 err = ensure_client_is_reading(client);
1123 if (err)
1124 break;
1125 } else if (client->state ==
1126 GOTD_STATE_EXPECT_MORE_REF_UPDATES) {
1127 err = ensure_client_is_writing(client);
1128 if (err)
1129 break;
1130 } else {
1131 err = got_error_msg(GOT_ERR_BAD_REQUEST,
1132 "unexpected flush-pkt received");
1133 break;
1135 log_debug("received flush-pkt from uid %d",
1136 client->euid);
1137 if (client->state == GOTD_STATE_EXPECT_WANT) {
1138 client->state = GOTD_STATE_EXPECT_HAVE;
1139 log_debug("uid %d: expecting have-lines",
1140 client->euid);
1141 } else if (client->state == GOTD_STATE_EXPECT_HAVE) {
1142 client->state = GOTD_STATE_EXPECT_DONE;
1143 log_debug("uid %d: expecting 'done'",
1144 client->euid);
1145 } else if (client->state ==
1146 GOTD_STATE_EXPECT_MORE_REF_UPDATES) {
1147 client->state = GOTD_STATE_EXPECT_PACKFILE;
1148 log_debug("uid %d: expecting packfile",
1149 client->euid);
1150 err = recv_packfile(client);
1151 } else {
1152 /* should not happen, see above */
1153 err = got_error_msg(GOT_ERR_BAD_REQUEST,
1154 "unexpected client state");
1155 break;
1157 break;
1158 case GOTD_IMSG_DONE:
1159 if (client->state != GOTD_STATE_EXPECT_HAVE &&
1160 client->state != GOTD_STATE_EXPECT_DONE) {
1161 err = got_error_msg(GOT_ERR_BAD_REQUEST,
1162 "unexpected flush-pkt received");
1163 break;
1165 log_debug("received 'done' from uid %d", client->euid);
1166 err = ensure_client_is_reading(client);
1167 if (err)
1168 break;
1169 client->state = GOTD_STATE_DONE;
1170 err = send_packfile(client);
1171 break;
1172 default:
1173 err = got_error(GOT_ERR_PRIVSEP_MSG);
1174 break;
1177 imsg_free(&imsg);
1180 if (err) {
1181 if (err->code != GOT_ERR_EOF ||
1182 client->state != GOTD_STATE_EXPECT_PACKFILE)
1183 disconnect_on_error(client, err);
1184 } else {
1185 gotd_imsg_event_add(&client->iev);
1186 if (client->state == GOTD_STATE_EXPECT_LIST_REFS)
1187 evtimer_add(&client->tmo, &auth_timeout);
1188 else
1189 evtimer_add(&client->tmo, &gotd.request_timeout);
1193 static void
1194 gotd_request_timeout(int fd, short events, void *arg)
1196 struct gotd_client *client = arg;
1198 log_debug("disconnecting uid %d due to timeout", client->euid);
1199 disconnect(client);
1202 static const struct got_error *
1203 recv_connect(uint32_t *client_id, struct imsg *imsg)
1205 const struct got_error *err = NULL;
1206 struct gotd_imsg_connect iconnect;
1207 size_t datalen;
1208 int s = -1;
1209 struct gotd_client *client = NULL;
1211 *client_id = 0;
1213 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1214 if (datalen != sizeof(iconnect))
1215 return got_error(GOT_ERR_PRIVSEP_LEN);
1216 memcpy(&iconnect, imsg->data, sizeof(iconnect));
1218 s = imsg->fd;
1219 if (s == -1) {
1220 err = got_error(GOT_ERR_PRIVSEP_NO_FD);
1221 goto done;
1224 if (find_client(iconnect.client_id)) {
1225 err = got_error_msg(GOT_ERR_CLIENT_ID, "duplicate client ID");
1226 goto done;
1229 client = calloc(1, sizeof(*client));
1230 if (client == NULL) {
1231 err = got_error_from_errno("calloc");
1232 goto done;
1235 *client_id = iconnect.client_id;
1237 client->state = GOTD_STATE_EXPECT_LIST_REFS;
1238 client->id = iconnect.client_id;
1239 client->fd = s;
1240 s = -1;
1241 client->delta_cache_fd = -1;
1242 /* The auth process will verify UID/GID for us. */
1243 client->euid = iconnect.euid;
1244 client->egid = iconnect.egid;
1245 client->nref_updates = -1;
1247 imsg_init(&client->iev.ibuf, client->fd);
1248 client->iev.handler = gotd_request;
1249 client->iev.events = EV_READ;
1250 client->iev.handler_arg = client;
1252 event_set(&client->iev.ev, client->fd, EV_READ, gotd_request,
1253 &client->iev);
1254 gotd_imsg_event_add(&client->iev);
1256 evtimer_set(&client->tmo, gotd_request_timeout, client);
1258 add_client(client);
1259 log_debug("%s: new client uid %d connected on fd %d", __func__,
1260 client->euid, client->fd);
1261 done:
1262 if (err) {
1263 struct gotd_child_proc *listen_proc = &gotd.listen_proc;
1264 struct gotd_imsg_disconnect idisconnect;
1266 idisconnect.client_id = client->id;
1267 if (gotd_imsg_compose_event(&listen_proc->iev,
1268 GOTD_IMSG_DISCONNECT, PROC_GOTD, -1,
1269 &idisconnect, sizeof(idisconnect)) == -1)
1270 log_warn("imsg compose DISCONNECT");
1272 if (s != -1)
1273 close(s);
1276 return err;
1279 static const char *gotd_proc_names[PROC_MAX] = {
1280 "parent",
1281 "listen",
1282 "auth",
1283 "repo_read",
1284 "repo_write"
1287 static void
1288 kill_proc(struct gotd_child_proc *proc, int fatal)
1290 if (fatal) {
1291 log_warnx("sending SIGKILL to PID %d", proc->pid);
1292 kill(proc->pid, SIGKILL);
1293 } else
1294 kill(proc->pid, SIGTERM);
1297 static void
1298 gotd_shutdown(void)
1300 struct gotd_child_proc *proc;
1301 uint64_t slot;
1303 for (slot = 0; slot < nitems(gotd_clients); slot++) {
1304 struct gotd_client *c, *tmp;
1306 STAILQ_FOREACH_SAFE(c, &gotd_clients[slot], entry, tmp)
1307 disconnect(c);
1310 proc = &gotd.listen_proc;
1311 msgbuf_clear(&proc->iev.ibuf.w);
1312 close(proc->iev.ibuf.fd);
1313 kill_proc(proc, 0);
1314 wait_for_child(proc->pid);
1316 log_info("terminating");
1317 exit(0);
1320 void
1321 gotd_sighdlr(int sig, short event, void *arg)
1324 * Normal signal handler rules don't apply because libevent
1325 * decouples for us.
1328 switch (sig) {
1329 case SIGHUP:
1330 log_info("%s: ignoring SIGHUP", __func__);
1331 break;
1332 case SIGUSR1:
1333 log_info("%s: ignoring SIGUSR1", __func__);
1334 break;
1335 case SIGTERM:
1336 case SIGINT:
1337 gotd_shutdown();
1338 log_warnx("gotd terminating");
1339 exit(0);
1340 break;
1341 default:
1342 fatalx("unexpected signal");
1346 static const struct got_error *
1347 ensure_proc_is_reading(struct gotd_client *client,
1348 struct gotd_child_proc *proc)
1350 if (!client_is_reading(client)) {
1351 kill_proc(proc, 1);
1352 return got_error_fmt(GOT_ERR_BAD_PACKET,
1353 "PID %d handled a read-request for uid %d but this "
1354 "user is not reading from a repository", proc->pid,
1355 client->euid);
1358 return NULL;
1361 static const struct got_error *
1362 ensure_proc_is_writing(struct gotd_client *client,
1363 struct gotd_child_proc *proc)
1365 if (!client_is_writing(client)) {
1366 kill_proc(proc, 1);
1367 return got_error_fmt(GOT_ERR_BAD_PACKET,
1368 "PID %d handled a write-request for uid %d but this "
1369 "user is not writing to a repository", proc->pid,
1370 client->euid);
1373 return NULL;
1376 static int
1377 verify_imsg_src(struct gotd_client *client, struct gotd_child_proc *proc,
1378 struct imsg *imsg)
1380 const struct got_error *err;
1381 struct gotd_child_proc *client_proc;
1382 int ret = 0;
1384 if (proc->type == PROC_REPO_READ || proc->type == PROC_REPO_WRITE) {
1385 client_proc = get_client_proc(client);
1386 if (client_proc == NULL)
1387 fatalx("no process found for uid %d", client->euid);
1388 if (proc->pid != client_proc->pid) {
1389 kill_proc(proc, 1);
1390 log_warnx("received message from PID %d for uid %d, "
1391 "while PID %d is the process serving this user",
1392 proc->pid, client->euid, client_proc->pid);
1393 return 0;
1397 switch (imsg->hdr.type) {
1398 case GOTD_IMSG_ERROR:
1399 ret = 1;
1400 break;
1401 case GOTD_IMSG_CONNECT:
1402 if (proc->type != PROC_LISTEN) {
1403 err = got_error_fmt(GOT_ERR_BAD_PACKET,
1404 "new connection for uid %d from PID %d "
1405 "which is not the listen process",
1406 proc->pid, client->euid);
1407 } else
1408 ret = 1;
1409 break;
1410 case GOTD_IMSG_ACCESS_GRANTED:
1411 if (proc->type != PROC_AUTH) {
1412 err = got_error_fmt(GOT_ERR_BAD_PACKET,
1413 "authentication of uid %d from PID %d "
1414 "which is not the auth process",
1415 proc->pid, client->euid);
1416 } else
1417 ret = 1;
1418 break;
1419 case GOTD_IMSG_REPO_CHILD_READY:
1420 if (proc->type != PROC_REPO_READ &&
1421 proc->type != PROC_REPO_WRITE) {
1422 err = got_error_fmt(GOT_ERR_BAD_PACKET,
1423 "unexpected \"ready\" signal from PID %d",
1424 proc->pid);
1425 } else
1426 ret = 1;
1427 break;
1428 case GOTD_IMSG_PACKFILE_DONE:
1429 err = ensure_proc_is_reading(client, proc);
1430 if (err)
1431 log_warnx("uid %d: %s", client->euid, err->msg);
1432 else
1433 ret = 1;
1434 break;
1435 case GOTD_IMSG_PACKFILE_INSTALL:
1436 case GOTD_IMSG_REF_UPDATES_START:
1437 case GOTD_IMSG_REF_UPDATE:
1438 err = ensure_proc_is_writing(client, proc);
1439 if (err)
1440 log_warnx("uid %d: %s", client->euid, err->msg);
1441 else
1442 ret = 1;
1443 break;
1444 default:
1445 log_debug("%s: unexpected imsg %d", __func__, imsg->hdr.type);
1446 break;
1449 return ret;
1452 static const struct got_error *
1453 list_refs_request(struct gotd_client *client, struct gotd_imsgev *iev)
1455 static const struct got_error *err;
1456 struct gotd_imsg_list_refs_internal ilref;
1457 int fd;
1459 memset(&ilref, 0, sizeof(ilref));
1460 ilref.client_id = client->id;
1462 fd = dup(client->fd);
1463 if (fd == -1)
1464 return got_error_from_errno("dup");
1466 if (gotd_imsg_compose_event(iev, GOTD_IMSG_LIST_REFS_INTERNAL,
1467 PROC_GOTD, fd, &ilref, sizeof(ilref)) == -1) {
1468 err = got_error_from_errno("imsg compose WANT");
1469 close(fd);
1470 return err;
1473 client->state = GOTD_STATE_EXPECT_CAPABILITIES;
1474 log_debug("uid %d: expecting capabilities", client->euid);
1475 return NULL;
1478 static const struct got_error *
1479 recv_packfile_done(uint32_t *client_id, struct imsg *imsg)
1481 struct gotd_imsg_packfile_done idone;
1482 size_t datalen;
1484 log_debug("packfile-done received");
1486 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1487 if (datalen != sizeof(idone))
1488 return got_error(GOT_ERR_PRIVSEP_LEN);
1489 memcpy(&idone, imsg->data, sizeof(idone));
1491 *client_id = idone.client_id;
1492 return NULL;
1495 static const struct got_error *
1496 recv_packfile_install(uint32_t *client_id, struct imsg *imsg)
1498 struct gotd_imsg_packfile_install inst;
1499 size_t datalen;
1501 log_debug("packfile-install received");
1503 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1504 if (datalen != sizeof(inst))
1505 return got_error(GOT_ERR_PRIVSEP_LEN);
1506 memcpy(&inst, imsg->data, sizeof(inst));
1508 *client_id = inst.client_id;
1509 return NULL;
1512 static const struct got_error *
1513 recv_ref_updates_start(uint32_t *client_id, struct imsg *imsg)
1515 struct gotd_imsg_ref_updates_start istart;
1516 size_t datalen;
1518 log_debug("ref-updates-start received");
1520 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1521 if (datalen != sizeof(istart))
1522 return got_error(GOT_ERR_PRIVSEP_LEN);
1523 memcpy(&istart, imsg->data, sizeof(istart));
1525 *client_id = istart.client_id;
1526 return NULL;
1529 static const struct got_error *
1530 recv_ref_update(uint32_t *client_id, struct imsg *imsg)
1532 struct gotd_imsg_ref_update iref;
1533 size_t datalen;
1535 log_debug("ref-update received");
1537 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1538 if (datalen < sizeof(iref))
1539 return got_error(GOT_ERR_PRIVSEP_LEN);
1540 memcpy(&iref, imsg->data, sizeof(iref));
1542 *client_id = iref.client_id;
1543 return NULL;
1546 static const struct got_error *
1547 send_ref_update_ok(struct gotd_client *client,
1548 struct gotd_imsg_ref_update *iref, const char *refname)
1550 struct gotd_imsg_ref_update_ok iok;
1551 struct ibuf *wbuf;
1552 size_t len;
1554 memset(&iok, 0, sizeof(iok));
1555 iok.client_id = client->id;
1556 memcpy(iok.old_id, iref->old_id, SHA1_DIGEST_LENGTH);
1557 memcpy(iok.new_id, iref->new_id, SHA1_DIGEST_LENGTH);
1558 iok.name_len = strlen(refname);
1560 len = sizeof(iok) + iok.name_len;
1561 wbuf = imsg_create(&client->iev.ibuf, GOTD_IMSG_REF_UPDATE_OK,
1562 PROC_GOTD, gotd.pid, len);
1563 if (wbuf == NULL)
1564 return got_error_from_errno("imsg_create REF_UPDATE_OK");
1566 if (imsg_add(wbuf, &iok, sizeof(iok)) == -1)
1567 return got_error_from_errno("imsg_add REF_UPDATE_OK");
1568 if (imsg_add(wbuf, refname, iok.name_len) == -1)
1569 return got_error_from_errno("imsg_add REF_UPDATE_OK");
1571 wbuf->fd = -1;
1572 imsg_close(&client->iev.ibuf, wbuf);
1573 gotd_imsg_event_add(&client->iev);
1574 return NULL;
1577 static void
1578 send_refs_updated(struct gotd_client *client)
1580 if (gotd_imsg_compose_event(&client->iev,
1581 GOTD_IMSG_REFS_UPDATED, PROC_GOTD, -1, NULL, 0) == -1)
1582 log_warn("imsg compose REFS_UPDATED");
1585 static const struct got_error *
1586 send_ref_update_ng(struct gotd_client *client,
1587 struct gotd_imsg_ref_update *iref, const char *refname,
1588 const char *reason)
1590 const struct got_error *ng_err;
1591 struct gotd_imsg_ref_update_ng ing;
1592 struct ibuf *wbuf;
1593 size_t len;
1595 memset(&ing, 0, sizeof(ing));
1596 ing.client_id = client->id;
1597 memcpy(ing.old_id, iref->old_id, SHA1_DIGEST_LENGTH);
1598 memcpy(ing.new_id, iref->new_id, SHA1_DIGEST_LENGTH);
1599 ing.name_len = strlen(refname);
1601 ng_err = got_error_fmt(GOT_ERR_REF_BUSY, "%s", reason);
1602 ing.reason_len = strlen(ng_err->msg);
1604 len = sizeof(ing) + ing.name_len + ing.reason_len;
1605 wbuf = imsg_create(&client->iev.ibuf, GOTD_IMSG_REF_UPDATE_NG,
1606 PROC_GOTD, gotd.pid, len);
1607 if (wbuf == NULL)
1608 return got_error_from_errno("imsg_create REF_UPDATE_NG");
1610 if (imsg_add(wbuf, &ing, sizeof(ing)) == -1)
1611 return got_error_from_errno("imsg_add REF_UPDATE_NG");
1612 if (imsg_add(wbuf, refname, ing.name_len) == -1)
1613 return got_error_from_errno("imsg_add REF_UPDATE_NG");
1614 if (imsg_add(wbuf, ng_err->msg, ing.reason_len) == -1)
1615 return got_error_from_errno("imsg_add REF_UPDATE_NG");
1617 wbuf->fd = -1;
1618 imsg_close(&client->iev.ibuf, wbuf);
1619 gotd_imsg_event_add(&client->iev);
1620 return NULL;
1623 static const struct got_error *
1624 install_pack(struct gotd_client *client, const char *repo_path,
1625 struct imsg *imsg)
1627 const struct got_error *err = NULL;
1628 struct gotd_imsg_packfile_install inst;
1629 char hex[SHA1_DIGEST_STRING_LENGTH];
1630 size_t datalen;
1631 char *packfile_path = NULL, *packidx_path = NULL;
1633 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1634 if (datalen != sizeof(inst))
1635 return got_error(GOT_ERR_PRIVSEP_LEN);
1636 memcpy(&inst, imsg->data, sizeof(inst));
1638 if (client->packfile_path == NULL)
1639 return got_error_msg(GOT_ERR_BAD_REQUEST,
1640 "client has no pack file");
1641 if (client->packidx_path == NULL)
1642 return got_error_msg(GOT_ERR_BAD_REQUEST,
1643 "client has no pack file index");
1645 if (got_sha1_digest_to_str(inst.pack_sha1, hex, sizeof(hex)) == NULL)
1646 return got_error_msg(GOT_ERR_NO_SPACE,
1647 "could not convert pack file SHA1 to hex");
1649 if (asprintf(&packfile_path, "/%s/%s/pack-%s.pack",
1650 repo_path, GOT_OBJECTS_PACK_DIR, hex) == -1) {
1651 err = got_error_from_errno("asprintf");
1652 goto done;
1655 if (asprintf(&packidx_path, "/%s/%s/pack-%s.idx",
1656 repo_path, GOT_OBJECTS_PACK_DIR, hex) == -1) {
1657 err = got_error_from_errno("asprintf");
1658 goto done;
1661 if (rename(client->packfile_path, packfile_path) == -1) {
1662 err = got_error_from_errno3("rename", client->packfile_path,
1663 packfile_path);
1664 goto done;
1667 free(client->packfile_path);
1668 client->packfile_path = NULL;
1670 if (rename(client->packidx_path, packidx_path) == -1) {
1671 err = got_error_from_errno3("rename", client->packidx_path,
1672 packidx_path);
1673 goto done;
1676 free(client->packidx_path);
1677 client->packidx_path = NULL;
1678 done:
1679 free(packfile_path);
1680 free(packidx_path);
1681 return err;
1684 static const struct got_error *
1685 begin_ref_updates(struct gotd_client *client, struct imsg *imsg)
1687 struct gotd_imsg_ref_updates_start istart;
1688 size_t datalen;
1690 if (client->nref_updates != -1)
1691 return got_error(GOT_ERR_PRIVSEP_MSG);
1693 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1694 if (datalen != sizeof(istart))
1695 return got_error(GOT_ERR_PRIVSEP_LEN);
1696 memcpy(&istart, imsg->data, sizeof(istart));
1698 if (istart.nref_updates <= 0)
1699 return got_error(GOT_ERR_PRIVSEP_MSG);
1701 client->nref_updates = istart.nref_updates;
1702 return NULL;
1705 static const struct got_error *
1706 update_ref(struct gotd_client *client, const char *repo_path,
1707 struct imsg *imsg)
1709 const struct got_error *err = NULL;
1710 struct got_repository *repo = NULL;
1711 struct got_reference *ref = NULL;
1712 struct gotd_imsg_ref_update iref;
1713 struct got_object_id old_id, new_id;
1714 struct got_object_id *id = NULL;
1715 struct got_object *obj = NULL;
1716 char *refname = NULL;
1717 size_t datalen;
1718 int locked = 0;
1720 log_debug("update-ref from uid %d", client->euid);
1722 if (client->nref_updates <= 0)
1723 return got_error(GOT_ERR_PRIVSEP_MSG);
1725 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1726 if (datalen < sizeof(iref))
1727 return got_error(GOT_ERR_PRIVSEP_LEN);
1728 memcpy(&iref, imsg->data, sizeof(iref));
1729 if (datalen != sizeof(iref) + iref.name_len)
1730 return got_error(GOT_ERR_PRIVSEP_LEN);
1731 refname = malloc(iref.name_len + 1);
1732 if (refname == NULL)
1733 return got_error_from_errno("malloc");
1734 memcpy(refname, imsg->data + sizeof(iref), iref.name_len);
1735 refname[iref.name_len] = '\0';
1737 log_debug("updating ref %s for uid %d", refname, client->euid);
1739 err = got_repo_open(&repo, repo_path, NULL, NULL);
1740 if (err)
1741 goto done;
1743 memcpy(old_id.sha1, iref.old_id, SHA1_DIGEST_LENGTH);
1744 memcpy(new_id.sha1, iref.new_id, SHA1_DIGEST_LENGTH);
1745 err = got_object_open(&obj, repo, &new_id);
1746 if (err)
1747 goto done;
1749 if (iref.ref_is_new) {
1750 err = got_ref_open(&ref, repo, refname, 0);
1751 if (err) {
1752 if (err->code != GOT_ERR_NOT_REF)
1753 goto done;
1754 err = got_ref_alloc(&ref, refname, &new_id);
1755 if (err)
1756 goto done;
1757 err = got_ref_write(ref, repo); /* will lock/unlock */
1758 if (err)
1759 goto done;
1760 } else {
1761 err = got_error_fmt(GOT_ERR_REF_BUSY,
1762 "%s has been created by someone else "
1763 "while transaction was in progress",
1764 got_ref_get_name(ref));
1765 goto done;
1767 } else {
1768 err = got_ref_open(&ref, repo, refname, 1 /* lock */);
1769 if (err)
1770 goto done;
1771 locked = 1;
1773 err = got_ref_resolve(&id, repo, ref);
1774 if (err)
1775 goto done;
1777 if (got_object_id_cmp(id, &old_id) != 0) {
1778 err = got_error_fmt(GOT_ERR_REF_BUSY,
1779 "%s has been modified by someone else "
1780 "while transaction was in progress",
1781 got_ref_get_name(ref));
1782 goto done;
1785 err = got_ref_change_ref(ref, &new_id);
1786 if (err)
1787 goto done;
1789 err = got_ref_write(ref, repo);
1790 if (err)
1791 goto done;
1793 free(id);
1794 id = NULL;
1796 done:
1797 if (err) {
1798 if (err->code == GOT_ERR_LOCKFILE_TIMEOUT) {
1799 err = got_error_fmt(GOT_ERR_LOCKFILE_TIMEOUT,
1800 "could not acquire exclusive file lock for %s",
1801 refname);
1803 send_ref_update_ng(client, &iref, refname, err->msg);
1804 } else
1805 send_ref_update_ok(client, &iref, refname);
1807 if (client->nref_updates > 0) {
1808 client->nref_updates--;
1809 if (client->nref_updates == 0)
1810 send_refs_updated(client);
1813 if (locked) {
1814 const struct got_error *unlock_err;
1815 unlock_err = got_ref_unlock(ref);
1816 if (unlock_err && err == NULL)
1817 err = unlock_err;
1819 if (ref)
1820 got_ref_close(ref);
1821 if (obj)
1822 got_object_close(obj);
1823 if (repo)
1824 got_repo_close(repo);
1825 free(refname);
1826 free(id);
1827 return err;
1830 static void
1831 gotd_dispatch_listener(int fd, short event, void *arg)
1833 struct gotd_imsgev *iev = arg;
1834 struct imsgbuf *ibuf = &iev->ibuf;
1835 struct gotd_child_proc *proc = &gotd.listen_proc;
1836 ssize_t n;
1837 int shut = 0;
1838 struct imsg imsg;
1840 if (proc->iev.ibuf.fd != fd)
1841 fatalx("%s: unexpected fd %d", __func__, fd);
1843 if (event & EV_READ) {
1844 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
1845 fatal("imsg_read error");
1846 if (n == 0) {
1847 /* Connection closed. */
1848 shut = 1;
1849 goto done;
1853 if (event & EV_WRITE) {
1854 n = msgbuf_write(&ibuf->w);
1855 if (n == -1 && errno != EAGAIN)
1856 fatal("msgbuf_write");
1857 if (n == 0) {
1858 /* Connection closed. */
1859 shut = 1;
1860 goto done;
1864 for (;;) {
1865 const struct got_error *err = NULL;
1866 struct gotd_client *client = NULL;
1867 uint32_t client_id = 0;
1868 int do_disconnect = 0;
1870 if ((n = imsg_get(ibuf, &imsg)) == -1)
1871 fatal("%s: imsg_get error", __func__);
1872 if (n == 0) /* No more messages. */
1873 break;
1875 switch (imsg.hdr.type) {
1876 case GOTD_IMSG_ERROR:
1877 do_disconnect = 1;
1878 err = gotd_imsg_recv_error(&client_id, &imsg);
1879 break;
1880 case GOTD_IMSG_CONNECT:
1881 err = recv_connect(&client_id, &imsg);
1882 break;
1883 default:
1884 log_debug("unexpected imsg %d", imsg.hdr.type);
1885 break;
1888 client = find_client(client_id);
1889 if (client == NULL) {
1890 log_warnx("%s: client not found", __func__);
1891 imsg_free(&imsg);
1892 continue;
1895 if (err)
1896 log_warnx("uid %d: %s", client->euid, err->msg);
1898 if (do_disconnect) {
1899 if (err)
1900 disconnect_on_error(client, err);
1901 else
1902 disconnect(client);
1905 imsg_free(&imsg);
1907 done:
1908 if (!shut) {
1909 gotd_imsg_event_add(iev);
1910 } else {
1911 /* This pipe is dead. Remove its event handler */
1912 event_del(&iev->ev);
1913 event_loopexit(NULL);
1917 static void
1918 gotd_dispatch_auth_child(int fd, short event, void *arg)
1920 const struct got_error *err = NULL;
1921 struct gotd_imsgev *iev = arg;
1922 struct imsgbuf *ibuf = &iev->ibuf;
1923 struct gotd_client *client;
1924 struct gotd_repo *repo = NULL;
1925 ssize_t n;
1926 int shut = 0;
1927 struct imsg imsg;
1928 uint32_t client_id = 0;
1929 int do_disconnect = 0;
1930 enum gotd_procid proc_type;
1932 client = find_client_by_proc_fd(fd);
1933 if (client == NULL)
1934 fatalx("cannot find client for fd %d", fd);
1936 if (client->auth == NULL)
1937 fatalx("cannot find auth child process for fd %d", fd);
1939 if (event & EV_READ) {
1940 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
1941 fatal("imsg_read error");
1942 if (n == 0) {
1943 /* Connection closed. */
1944 shut = 1;
1945 goto done;
1949 if (event & EV_WRITE) {
1950 n = msgbuf_write(&ibuf->w);
1951 if (n == -1 && errno != EAGAIN)
1952 fatal("msgbuf_write");
1953 if (n == 0) {
1954 /* Connection closed. */
1955 shut = 1;
1957 goto done;
1960 if (client->auth->iev.ibuf.fd != fd)
1961 fatalx("%s: unexpected fd %d", __func__, fd);
1963 if ((n = imsg_get(ibuf, &imsg)) == -1)
1964 fatal("%s: imsg_get error", __func__);
1965 if (n == 0) /* No more messages. */
1966 return;
1968 evtimer_del(&client->tmo);
1970 switch (imsg.hdr.type) {
1971 case GOTD_IMSG_ERROR:
1972 do_disconnect = 1;
1973 err = gotd_imsg_recv_error(&client_id, &imsg);
1974 break;
1975 case GOTD_IMSG_ACCESS_GRANTED:
1976 break;
1977 default:
1978 do_disconnect = 1;
1979 log_debug("unexpected imsg %d", imsg.hdr.type);
1980 break;
1983 if (!verify_imsg_src(client, client->auth, &imsg)) {
1984 do_disconnect = 1;
1985 log_debug("dropping imsg type %d from PID %d",
1986 imsg.hdr.type, client->auth->pid);
1988 imsg_free(&imsg);
1990 if (do_disconnect) {
1991 if (err)
1992 disconnect_on_error(client, err);
1993 else
1994 disconnect(client);
1995 goto done;
1998 repo = find_repo_by_name(client->auth->repo_name);
1999 if (repo == NULL) {
2000 err = got_error(GOT_ERR_NOT_GIT_REPO);
2001 goto done;
2003 kill_auth_proc(client);
2005 log_info("authenticated uid %d for repository %s\n",
2006 client->euid, repo->name);
2008 if (client->required_auth & GOTD_AUTH_WRITE)
2009 proc_type = PROC_REPO_WRITE;
2010 else
2011 proc_type = PROC_REPO_READ;
2013 err = start_repo_child(client, proc_type, repo, gotd.argv0,
2014 gotd.confpath, gotd.daemonize, gotd.verbosity);
2015 done:
2016 if (err)
2017 log_warnx("uid %d: %s", client->euid, err->msg);
2019 /* We might have killed the auth process by now. */
2020 if (client->auth != NULL) {
2021 if (!shut) {
2022 gotd_imsg_event_add(iev);
2023 } else {
2024 /* This pipe is dead. Remove its event handler */
2025 event_del(&iev->ev);
2030 static void
2031 gotd_dispatch_repo_child(int fd, short event, void *arg)
2033 struct gotd_imsgev *iev = arg;
2034 struct imsgbuf *ibuf = &iev->ibuf;
2035 struct gotd_child_proc *proc = NULL;
2036 struct gotd_client *client = NULL;
2037 ssize_t n;
2038 int shut = 0;
2039 struct imsg imsg;
2041 if (event & EV_READ) {
2042 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
2043 fatal("imsg_read error");
2044 if (n == 0) {
2045 /* Connection closed. */
2046 shut = 1;
2047 goto done;
2051 if (event & EV_WRITE) {
2052 n = msgbuf_write(&ibuf->w);
2053 if (n == -1 && errno != EAGAIN)
2054 fatal("msgbuf_write");
2055 if (n == 0) {
2056 /* Connection closed. */
2057 shut = 1;
2058 goto done;
2062 client = find_client_by_proc_fd(fd);
2063 if (client == NULL)
2064 fatalx("cannot find client for fd %d", fd);
2066 proc = get_client_proc(client);
2067 if (proc == NULL)
2068 fatalx("cannot find child process for fd %d", fd);
2070 for (;;) {
2071 const struct got_error *err = NULL;
2072 uint32_t client_id = 0;
2073 int do_disconnect = 0;
2074 int do_list_refs = 0, do_ref_updates = 0, do_ref_update = 0;
2075 int do_packfile_install = 0;
2077 if ((n = imsg_get(ibuf, &imsg)) == -1)
2078 fatal("%s: imsg_get error", __func__);
2079 if (n == 0) /* No more messages. */
2080 break;
2082 switch (imsg.hdr.type) {
2083 case GOTD_IMSG_ERROR:
2084 do_disconnect = 1;
2085 err = gotd_imsg_recv_error(&client_id, &imsg);
2086 break;
2087 case GOTD_IMSG_REPO_CHILD_READY:
2088 do_list_refs = 1;
2089 break;
2090 case GOTD_IMSG_PACKFILE_DONE:
2091 do_disconnect = 1;
2092 err = recv_packfile_done(&client_id, &imsg);
2093 break;
2094 case GOTD_IMSG_PACKFILE_INSTALL:
2095 err = recv_packfile_install(&client_id, &imsg);
2096 if (err == NULL)
2097 do_packfile_install = 1;
2098 break;
2099 case GOTD_IMSG_REF_UPDATES_START:
2100 err = recv_ref_updates_start(&client_id, &imsg);
2101 if (err == NULL)
2102 do_ref_updates = 1;
2103 break;
2104 case GOTD_IMSG_REF_UPDATE:
2105 err = recv_ref_update(&client_id, &imsg);
2106 if (err == NULL)
2107 do_ref_update = 1;
2108 break;
2109 default:
2110 log_debug("unexpected imsg %d", imsg.hdr.type);
2111 break;
2114 if (!verify_imsg_src(client, proc, &imsg)) {
2115 log_debug("dropping imsg type %d from PID %d",
2116 imsg.hdr.type, proc->pid);
2117 imsg_free(&imsg);
2118 continue;
2120 if (err)
2121 log_warnx("uid %d: %s", client->euid, err->msg);
2123 if (do_disconnect) {
2124 if (err)
2125 disconnect_on_error(client, err);
2126 else
2127 disconnect(client);
2128 } else {
2129 if (do_list_refs)
2130 err = list_refs_request(client, iev);
2131 else if (do_packfile_install)
2132 err = install_pack(client, proc->repo_path,
2133 &imsg);
2134 else if (do_ref_updates)
2135 err = begin_ref_updates(client, &imsg);
2136 else if (do_ref_update)
2137 err = update_ref(client, proc->repo_path,
2138 &imsg);
2139 if (err)
2140 log_warnx("uid %d: %s", client->euid, err->msg);
2142 imsg_free(&imsg);
2144 done:
2145 if (!shut) {
2146 gotd_imsg_event_add(iev);
2147 } else {
2148 /* This pipe is dead. Remove its event handler */
2149 event_del(&iev->ev);
2150 event_loopexit(NULL);
2154 static pid_t
2155 start_child(enum gotd_procid proc_id, const char *repo_path,
2156 char *argv0, const char *confpath, int fd, int daemonize, int verbosity)
2158 char *argv[11];
2159 int argc = 0;
2160 pid_t pid;
2162 switch (pid = fork()) {
2163 case -1:
2164 fatal("cannot fork");
2165 case 0:
2166 break;
2167 default:
2168 close(fd);
2169 return pid;
2172 if (fd != GOTD_FILENO_MSG_PIPE) {
2173 if (dup2(fd, GOTD_FILENO_MSG_PIPE) == -1)
2174 fatal("cannot setup imsg fd");
2175 } else if (fcntl(fd, F_SETFD, 0) == -1)
2176 fatal("cannot setup imsg fd");
2178 argv[argc++] = argv0;
2179 switch (proc_id) {
2180 case PROC_LISTEN:
2181 argv[argc++] = (char *)"-L";
2182 break;
2183 case PROC_AUTH:
2184 argv[argc++] = (char *)"-A";
2185 break;
2186 case PROC_REPO_READ:
2187 argv[argc++] = (char *)"-R";
2188 break;
2189 case PROC_REPO_WRITE:
2190 argv[argc++] = (char *)"-W";
2191 break;
2192 default:
2193 fatalx("invalid process id %d", proc_id);
2196 argv[argc++] = (char *)"-f";
2197 argv[argc++] = (char *)confpath;
2199 if (repo_path) {
2200 argv[argc++] = (char *)"-P";
2201 argv[argc++] = (char *)repo_path;
2204 if (!daemonize)
2205 argv[argc++] = (char *)"-d";
2206 if (verbosity > 0)
2207 argv[argc++] = (char *)"-v";
2208 if (verbosity > 1)
2209 argv[argc++] = (char *)"-v";
2210 argv[argc++] = NULL;
2212 execvp(argv0, argv);
2213 fatal("execvp");
2216 static void
2217 start_listener(char *argv0, const char *confpath, int daemonize, int verbosity)
2219 struct gotd_child_proc *proc = &gotd.listen_proc;
2221 proc->type = PROC_LISTEN;
2223 if (socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK,
2224 PF_UNSPEC, proc->pipe) == -1)
2225 fatal("socketpair");
2227 proc->pid = start_child(proc->type, NULL, argv0, confpath,
2228 proc->pipe[1], daemonize, verbosity);
2229 imsg_init(&proc->iev.ibuf, proc->pipe[0]);
2230 proc->iev.handler = gotd_dispatch_listener;
2231 proc->iev.events = EV_READ;
2232 proc->iev.handler_arg = NULL;
2235 static const struct got_error *
2236 start_repo_child(struct gotd_client *client, enum gotd_procid proc_type,
2237 struct gotd_repo *repo, char *argv0, const char *confpath,
2238 int daemonize, int verbosity)
2240 struct gotd_child_proc *proc;
2242 if (proc_type != PROC_REPO_READ && proc_type != PROC_REPO_WRITE)
2243 return got_error_msg(GOT_ERR_NOT_IMPL, "bad process type");
2245 proc = calloc(1, sizeof(*proc));
2246 if (proc == NULL)
2247 return got_error_from_errno("calloc");
2249 proc->type = proc_type;
2250 if (strlcpy(proc->repo_name, repo->name,
2251 sizeof(proc->repo_name)) >= sizeof(proc->repo_name))
2252 fatalx("repository name too long: %s", repo->name);
2253 log_debug("starting %s for repository %s",
2254 proc->type == PROC_REPO_READ ? "reader" : "writer", repo->name);
2255 if (realpath(repo->path, proc->repo_path) == NULL)
2256 fatal("%s", repo->path);
2257 if (socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK,
2258 PF_UNSPEC, proc->pipe) == -1)
2259 fatal("socketpair");
2260 proc->pid = start_child(proc->type, proc->repo_path, argv0,
2261 confpath, proc->pipe[1], daemonize, verbosity);
2262 imsg_init(&proc->iev.ibuf, proc->pipe[0]);
2263 log_debug("proc %s %s is on fd %d",
2264 gotd_proc_names[proc->type], proc->repo_path,
2265 proc->pipe[0]);
2266 proc->iev.handler = gotd_dispatch_repo_child;
2267 proc->iev.events = EV_READ;
2268 proc->iev.handler_arg = NULL;
2269 event_set(&proc->iev.ev, proc->iev.ibuf.fd, EV_READ,
2270 gotd_dispatch_repo_child, &proc->iev);
2271 gotd_imsg_event_add(&proc->iev);
2273 if (proc->type == PROC_REPO_READ)
2274 client->repo_read = proc;
2275 else
2276 client->repo_write = proc;
2278 return NULL;
2281 static const struct got_error *
2282 start_auth_child(struct gotd_client *client, int required_auth,
2283 struct gotd_repo *repo, char *argv0, const char *confpath,
2284 int daemonize, int verbosity)
2286 const struct got_error *err = NULL;
2287 struct gotd_child_proc *proc;
2288 struct gotd_imsg_auth iauth;
2289 int fd;
2291 memset(&iauth, 0, sizeof(iauth));
2293 fd = dup(client->fd);
2294 if (fd == -1)
2295 return got_error_from_errno("dup");
2297 proc = calloc(1, sizeof(*proc));
2298 if (proc == NULL) {
2299 err = got_error_from_errno("calloc");
2300 close(fd);
2301 return err;
2304 proc->type = PROC_AUTH;
2305 if (strlcpy(proc->repo_name, repo->name,
2306 sizeof(proc->repo_name)) >= sizeof(proc->repo_name))
2307 fatalx("repository name too long: %s", repo->name);
2308 log_debug("starting auth for uid %d repository %s",
2309 client->euid, repo->name);
2310 if (realpath(repo->path, proc->repo_path) == NULL)
2311 fatal("%s", repo->path);
2312 if (socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK,
2313 PF_UNSPEC, proc->pipe) == -1)
2314 fatal("socketpair");
2315 proc->pid = start_child(proc->type, proc->repo_path, argv0,
2316 confpath, proc->pipe[1], daemonize, verbosity);
2317 imsg_init(&proc->iev.ibuf, proc->pipe[0]);
2318 log_debug("proc %s %s is on fd %d",
2319 gotd_proc_names[proc->type], proc->repo_path,
2320 proc->pipe[0]);
2321 proc->iev.handler = gotd_dispatch_auth_child;
2322 proc->iev.events = EV_READ;
2323 proc->iev.handler_arg = NULL;
2324 event_set(&proc->iev.ev, proc->iev.ibuf.fd, EV_READ,
2325 gotd_dispatch_auth_child, &proc->iev);
2326 gotd_imsg_event_add(&proc->iev);
2328 iauth.euid = client->euid;
2329 iauth.egid = client->egid;
2330 iauth.required_auth = required_auth;
2331 iauth.client_id = client->id;
2332 if (gotd_imsg_compose_event(&proc->iev, GOTD_IMSG_AUTHENTICATE,
2333 PROC_GOTD, fd, &iauth, sizeof(iauth)) == -1) {
2334 log_warn("imsg compose AUTHENTICATE");
2335 close(fd);
2336 /* Let the auth_timeout handler tidy up. */
2339 client->auth = proc;
2340 client->required_auth = required_auth;
2341 return NULL;
2344 static void
2345 apply_unveil_repo_readonly(const char *repo_path)
2347 if (unveil(repo_path, "r") == -1)
2348 fatal("unveil %s", repo_path);
2350 if (unveil(NULL, NULL) == -1)
2351 fatal("unveil");
2354 static void
2355 apply_unveil_none(void)
2357 if (unveil("/", "") == -1)
2358 fatal("unveil");
2360 if (unveil(NULL, NULL) == -1)
2361 fatal("unveil");
2364 static void
2365 apply_unveil(void)
2367 struct gotd_repo *repo;
2369 if (unveil(gotd.argv0, "x") == -1)
2370 fatal("unveil %s", gotd.argv0);
2372 TAILQ_FOREACH(repo, &gotd.repos, entry) {
2373 if (unveil(repo->path, "rwc") == -1)
2374 fatal("unveil %s", repo->path);
2377 if (unveil(GOT_TMPDIR_STR, "rwc") == -1)
2378 fatal("unveil %s", GOT_TMPDIR_STR);
2380 if (unveil(NULL, NULL) == -1)
2381 fatal("unveil");
2384 int
2385 main(int argc, char **argv)
2387 const struct got_error *error = NULL;
2388 int ch, fd = -1, daemonize = 1, verbosity = 0, noaction = 0;
2389 const char *confpath = GOTD_CONF_PATH;
2390 char *argv0 = argv[0];
2391 char title[2048];
2392 struct passwd *pw = NULL;
2393 char *repo_path = NULL;
2394 enum gotd_procid proc_id = PROC_GOTD;
2395 struct event evsigint, evsigterm, evsighup, evsigusr1;
2396 int *pack_fds = NULL, *temp_fds = NULL;
2398 log_init(1, LOG_DAEMON); /* Log to stderr until daemonized. */
2400 while ((ch = getopt(argc, argv, "Adf:LnP:RvW")) != -1) {
2401 switch (ch) {
2402 case 'A':
2403 proc_id = PROC_AUTH;
2404 break;
2405 case 'd':
2406 daemonize = 0;
2407 break;
2408 case 'f':
2409 confpath = optarg;
2410 break;
2411 case 'L':
2412 proc_id = PROC_LISTEN;
2413 break;
2414 case 'n':
2415 noaction = 1;
2416 break;
2417 case 'P':
2418 repo_path = realpath(optarg, NULL);
2419 if (repo_path == NULL)
2420 fatal("realpath '%s'", optarg);
2421 break;
2422 case 'R':
2423 proc_id = PROC_REPO_READ;
2424 break;
2425 case 'v':
2426 if (verbosity < 3)
2427 verbosity++;
2428 break;
2429 case 'W':
2430 proc_id = PROC_REPO_WRITE;
2431 break;
2432 default:
2433 usage();
2437 argc -= optind;
2438 argv += optind;
2440 if (argc != 0)
2441 usage();
2443 /* Require an absolute path in argv[0] for reliable re-exec. */
2444 if (!got_path_is_absolute(argv0))
2445 fatalx("bad path \"%s\": must be an absolute path", argv0);
2447 if (geteuid() && (proc_id == PROC_GOTD || proc_id == PROC_LISTEN))
2448 fatalx("need root privileges");
2450 log_init(daemonize ? 0 : 1, LOG_DAEMON);
2451 log_setverbose(verbosity);
2453 if (parse_config(confpath, proc_id, &gotd) != 0)
2454 return 1;
2456 gotd.argv0 = argv0;
2457 gotd.daemonize = daemonize;
2458 gotd.verbosity = verbosity;
2459 gotd.confpath = confpath;
2461 if (proc_id == PROC_GOTD &&
2462 (gotd.nrepos == 0 || TAILQ_EMPTY(&gotd.repos)))
2463 fatalx("no repository defined in configuration file");
2465 pw = getpwnam(gotd.user_name);
2466 if (pw == NULL)
2467 fatalx("user %s not found", gotd.user_name);
2469 if (pw->pw_uid == 0) {
2470 fatalx("cannot run %s as %s: the user running %s "
2471 "must not be the superuser",
2472 getprogname(), pw->pw_name, getprogname());
2475 if (proc_id == PROC_LISTEN &&
2476 !got_path_is_absolute(gotd.unix_socket_path))
2477 fatalx("bad unix socket path \"%s\": must be an absolute path",
2478 gotd.unix_socket_path);
2480 if (noaction)
2481 return 0;
2483 if (proc_id == PROC_GOTD) {
2484 gotd.pid = getpid();
2485 snprintf(title, sizeof(title), "%s", gotd_proc_names[proc_id]);
2486 start_listener(argv0, confpath, daemonize, verbosity);
2487 arc4random_buf(&clients_hash_key, sizeof(clients_hash_key));
2488 if (daemonize && daemon(1, 0) == -1)
2489 fatal("daemon");
2490 } else if (proc_id == PROC_LISTEN) {
2491 snprintf(title, sizeof(title), "%s", gotd_proc_names[proc_id]);
2492 if (verbosity) {
2493 log_info("socket: %s", gotd.unix_socket_path);
2494 log_info("user: %s", pw->pw_name);
2497 fd = unix_socket_listen(gotd.unix_socket_path, pw->pw_uid,
2498 pw->pw_gid);
2499 if (fd == -1) {
2500 fatal("cannot listen on unix socket %s",
2501 gotd.unix_socket_path);
2503 if (daemonize && daemon(0, 0) == -1)
2504 fatal("daemon");
2505 } else if (proc_id == PROC_AUTH) {
2506 snprintf(title, sizeof(title), "%s %s",
2507 gotd_proc_names[proc_id], repo_path);
2508 if (daemonize && daemon(0, 0) == -1)
2509 fatal("daemon");
2510 } else if (proc_id == PROC_REPO_READ || proc_id == PROC_REPO_WRITE) {
2511 error = got_repo_pack_fds_open(&pack_fds);
2512 if (error != NULL)
2513 fatalx("cannot open pack tempfiles: %s", error->msg);
2514 error = got_repo_temp_fds_open(&temp_fds);
2515 if (error != NULL)
2516 fatalx("cannot open pack tempfiles: %s", error->msg);
2517 if (repo_path == NULL)
2518 fatalx("repository path not specified");
2519 snprintf(title, sizeof(title), "%s %s",
2520 gotd_proc_names[proc_id], repo_path);
2521 if (daemonize && daemon(0, 0) == -1)
2522 fatal("daemon");
2523 } else
2524 fatal("invalid process id %d", proc_id);
2526 setproctitle("%s", title);
2527 log_procinit(title);
2529 /* Drop root privileges. */
2530 if (setgid(pw->pw_gid) == -1)
2531 fatal("setgid %d failed", pw->pw_gid);
2532 if (setuid(pw->pw_uid) == -1)
2533 fatal("setuid %d failed", pw->pw_uid);
2535 event_init();
2537 switch (proc_id) {
2538 case PROC_GOTD:
2539 #ifndef PROFILE
2540 if (pledge("stdio rpath wpath cpath proc exec "
2541 "sendfd recvfd fattr flock unveil", NULL) == -1)
2542 err(1, "pledge");
2543 #endif
2544 break;
2545 case PROC_LISTEN:
2546 #ifndef PROFILE
2547 if (pledge("stdio sendfd unix unveil", NULL) == -1)
2548 err(1, "pledge");
2549 #endif
2551 * Ensure that AF_UNIX bind(2) cannot be used with any other
2552 * sockets by revoking all filesystem access via unveil(2).
2554 apply_unveil_none();
2556 listen_main(title, fd, gotd.connection_limits,
2557 gotd.nconnection_limits);
2558 /* NOTREACHED */
2559 break;
2560 case PROC_AUTH:
2561 #ifndef PROFILE
2562 if (pledge("stdio getpw recvfd unix unveil", NULL) == -1)
2563 err(1, "pledge");
2564 #endif
2566 * We need the "unix" pledge promise for getpeername(2) only.
2567 * Ensure that AF_UNIX bind(2) cannot be used by revoking all
2568 * filesystem access via unveil(2). Access to password database
2569 * files will still work since "getpw" bypasses unveil(2).
2571 apply_unveil_none();
2573 auth_main(title, &gotd.repos, repo_path);
2574 /* NOTREACHED */
2575 break;
2576 case PROC_REPO_READ:
2577 #ifndef PROFILE
2578 if (pledge("stdio rpath recvfd unveil", NULL) == -1)
2579 err(1, "pledge");
2580 #endif
2581 apply_unveil_repo_readonly(repo_path);
2582 repo_read_main(title, repo_path, pack_fds, temp_fds);
2583 /* NOTREACHED */
2584 exit(0);
2585 case PROC_REPO_WRITE:
2586 #ifndef PROFILE
2587 if (pledge("stdio rpath recvfd unveil", NULL) == -1)
2588 err(1, "pledge");
2589 #endif
2590 apply_unveil_repo_readonly(repo_path);
2591 repo_write_main(title, repo_path, pack_fds, temp_fds);
2592 /* NOTREACHED */
2593 exit(0);
2594 default:
2595 fatal("invalid process id %d", proc_id);
2598 if (proc_id != PROC_GOTD)
2599 fatal("invalid process id %d", proc_id);
2601 apply_unveil();
2603 signal_set(&evsigint, SIGINT, gotd_sighdlr, NULL);
2604 signal_set(&evsigterm, SIGTERM, gotd_sighdlr, NULL);
2605 signal_set(&evsighup, SIGHUP, gotd_sighdlr, NULL);
2606 signal_set(&evsigusr1, SIGUSR1, gotd_sighdlr, NULL);
2607 signal(SIGPIPE, SIG_IGN);
2609 signal_add(&evsigint, NULL);
2610 signal_add(&evsigterm, NULL);
2611 signal_add(&evsighup, NULL);
2612 signal_add(&evsigusr1, NULL);
2614 gotd_imsg_event_add(&gotd.listen_proc.iev);
2616 event_dispatch();
2618 if (pack_fds)
2619 got_repo_pack_fds_close(pack_fds);
2620 free(repo_path);
2621 return 0;