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/stat.h>
19 #include <sys/tree.h>
20 #include <sys/types.h>
22 #include <event.h>
23 #include <errno.h>
24 #include <imsg.h>
25 #include <signal.h>
26 #include <siphash.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <limits.h>
31 #include <poll.h>
32 #include <sha1.h>
33 #include <sha2.h>
34 #include <unistd.h>
35 #include <zlib.h>
37 #include "buf.h"
39 #include "got_error.h"
40 #include "got_repository.h"
41 #include "got_object.h"
42 #include "got_reference.h"
43 #include "got_path.h"
45 #include "got_lib_delta.h"
46 #include "got_lib_delta_cache.h"
47 #include "got_lib_hash.h"
48 #include "got_lib_object.h"
49 #include "got_lib_object_cache.h"
50 #include "got_lib_object_idset.h"
51 #include "got_lib_object_parse.h"
52 #include "got_lib_ratelimit.h"
53 #include "got_lib_pack.h"
54 #include "got_lib_pack_index.h"
55 #include "got_lib_repository.h"
56 #include "got_lib_poll.h"
58 #include "log.h"
59 #include "gotd.h"
60 #include "repo_write.h"
62 #ifndef nitems
63 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
64 #endif
66 static struct repo_write {
67 pid_t pid;
68 const char *title;
69 struct got_repository *repo;
70 int *pack_fds;
71 int *temp_fds;
72 int session_fd;
73 struct gotd_imsgev session_iev;
74 struct got_pathlist_head *protected_tag_namespaces;
75 struct got_pathlist_head *protected_branch_namespaces;
76 struct got_pathlist_head *protected_branches;
77 } repo_write;
79 struct gotd_ref_update {
80 STAILQ_ENTRY(gotd_ref_update) entry;
81 struct got_reference *ref;
82 int ref_is_new;
83 int delete_ref;
84 struct got_object_id old_id;
85 struct got_object_id new_id;
86 };
87 STAILQ_HEAD(gotd_ref_updates, gotd_ref_update);
89 static struct repo_write_client {
90 uint32_t id;
91 int fd;
92 int pack_pipe;
93 struct got_pack pack;
94 uint8_t pack_sha1[SHA1_DIGEST_LENGTH];
95 int packidx_fd;
96 struct gotd_ref_updates ref_updates;
97 int nref_updates;
98 int nref_del;
99 int nref_new;
100 int nref_move;
101 } repo_write_client;
103 static volatile sig_atomic_t sigint_received;
104 static volatile sig_atomic_t sigterm_received;
106 static void
107 catch_sigint(int signo)
109 sigint_received = 1;
112 static void
113 catch_sigterm(int signo)
115 sigterm_received = 1;
118 static const struct got_error *
119 check_cancelled(void *arg)
121 if (sigint_received || sigterm_received)
122 return got_error(GOT_ERR_CANCELLED);
124 return NULL;
127 static const struct got_error *
128 send_peeled_tag_ref(struct got_reference *ref, struct got_object *obj,
129 struct imsgbuf *ibuf)
131 const struct got_error *err = NULL;
132 struct got_tag_object *tag;
133 size_t namelen, len;
134 char *peeled_refname = NULL;
135 struct got_object_id *id;
136 struct ibuf *wbuf;
138 err = got_object_tag_open(&tag, repo_write.repo, obj);
139 if (err)
140 return err;
142 if (asprintf(&peeled_refname, "%s^{}", got_ref_get_name(ref)) == -1) {
143 err = got_error_from_errno("asprintf");
144 goto done;
147 id = got_object_tag_get_object_id(tag);
148 namelen = strlen(peeled_refname);
150 len = sizeof(struct gotd_imsg_ref) + namelen;
151 if (len > MAX_IMSGSIZE - IMSG_HEADER_SIZE) {
152 err = got_error(GOT_ERR_NO_SPACE);
153 goto done;
156 wbuf = imsg_create(ibuf, GOTD_IMSG_REF, PROC_REPO_WRITE,
157 repo_write.pid, len);
158 if (wbuf == NULL) {
159 err = got_error_from_errno("imsg_create REF");
160 goto done;
163 /* Keep in sync with struct gotd_imsg_ref definition. */
164 if (imsg_add(wbuf, id->sha1, SHA1_DIGEST_LENGTH) == -1) {
165 err = got_error_from_errno("imsg_add REF");
166 goto done;
168 if (imsg_add(wbuf, &namelen, sizeof(namelen)) == -1) {
169 err = got_error_from_errno("imsg_add REF");
170 goto done;
172 if (imsg_add(wbuf, peeled_refname, namelen) == -1) {
173 err = got_error_from_errno("imsg_add REF");
174 goto done;
177 imsg_close(ibuf, wbuf);
178 done:
179 got_object_tag_close(tag);
180 return err;
183 static const struct got_error *
184 send_ref(struct got_reference *ref, struct imsgbuf *ibuf)
186 const struct got_error *err;
187 const char *refname = got_ref_get_name(ref);
188 size_t namelen;
189 struct got_object_id *id = NULL;
190 struct got_object *obj = NULL;
191 size_t len;
192 struct ibuf *wbuf;
194 namelen = strlen(refname);
196 len = sizeof(struct gotd_imsg_ref) + namelen;
197 if (len > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
198 return got_error(GOT_ERR_NO_SPACE);
200 err = got_ref_resolve(&id, repo_write.repo, ref);
201 if (err)
202 return err;
204 wbuf = imsg_create(ibuf, GOTD_IMSG_REF, PROC_REPO_WRITE,
205 repo_write.pid, len);
206 if (wbuf == NULL) {
207 err = got_error_from_errno("imsg_create REF");
208 goto done;
211 /* Keep in sync with struct gotd_imsg_ref definition. */
212 if (imsg_add(wbuf, id->sha1, SHA1_DIGEST_LENGTH) == -1)
213 return got_error_from_errno("imsg_add REF");
214 if (imsg_add(wbuf, &namelen, sizeof(namelen)) == -1)
215 return got_error_from_errno("imsg_add REF");
216 if (imsg_add(wbuf, refname, namelen) == -1)
217 return got_error_from_errno("imsg_add REF");
219 imsg_close(ibuf, wbuf);
221 err = got_object_open(&obj, repo_write.repo, id);
222 if (err)
223 goto done;
224 if (obj->type == GOT_OBJ_TYPE_TAG)
225 err = send_peeled_tag_ref(ref, obj, ibuf);
226 done:
227 if (obj)
228 got_object_close(obj);
229 free(id);
230 return err;
233 static const struct got_error *
234 list_refs(struct imsg *imsg)
236 const struct got_error *err;
237 struct repo_write_client *client = &repo_write_client;
238 struct got_reflist_head refs;
239 struct got_reflist_entry *re;
240 struct gotd_imsg_list_refs_internal ireq;
241 size_t datalen;
242 struct gotd_imsg_reflist irefs;
243 struct imsgbuf ibuf;
244 int client_fd;
246 TAILQ_INIT(&refs);
248 client_fd = imsg_get_fd(imsg);
249 if (client_fd == -1)
250 return got_error(GOT_ERR_PRIVSEP_NO_FD);
252 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
253 if (datalen != sizeof(ireq))
254 return got_error(GOT_ERR_PRIVSEP_LEN);
255 memcpy(&ireq, imsg->data, sizeof(ireq));
257 if (ireq.client_id == 0)
258 return got_error(GOT_ERR_CLIENT_ID);
259 if (client->id != 0) {
260 return got_error_msg(GOT_ERR_CLIENT_ID,
261 "duplicate list-refs request");
263 client->id = ireq.client_id;
264 client->fd = client_fd;
265 client->nref_updates = 0;
266 client->nref_del = 0;
267 client->nref_new = 0;
268 client->nref_move = 0;
270 imsg_init(&ibuf, client_fd);
272 err = got_ref_list(&refs, repo_write.repo, "",
273 got_ref_cmp_by_name, NULL);
274 if (err)
275 return err;
277 memset(&irefs, 0, sizeof(irefs));
278 TAILQ_FOREACH(re, &refs, entry) {
279 struct got_object_id *id;
280 int obj_type;
282 if (got_ref_is_symbolic(re->ref))
283 continue;
285 irefs.nrefs++;
287 /* Account for a peeled tag refs. */
288 err = got_ref_resolve(&id, repo_write.repo, re->ref);
289 if (err)
290 goto done;
291 err = got_object_get_type(&obj_type, repo_write.repo, id);
292 free(id);
293 if (err)
294 goto done;
295 if (obj_type == GOT_OBJ_TYPE_TAG)
296 irefs.nrefs++;
299 if (imsg_compose(&ibuf, GOTD_IMSG_REFLIST, PROC_REPO_WRITE,
300 repo_write.pid, -1, &irefs, sizeof(irefs)) == -1) {
301 err = got_error_from_errno("imsg_compose REFLIST");
302 goto done;
305 TAILQ_FOREACH(re, &refs, entry) {
306 if (got_ref_is_symbolic(re->ref))
307 continue;
308 err = send_ref(re->ref, &ibuf);
309 if (err)
310 goto done;
313 err = gotd_imsg_flush(&ibuf);
314 done:
315 got_ref_list_free(&refs);
316 imsg_clear(&ibuf);
317 return err;
320 static const struct got_error *
321 validate_namespace(const char *namespace)
323 size_t len = strlen(namespace);
325 if (len < 5 || strncmp("refs/", namespace, 5) != 0 ||
326 namespace[len -1] != '/') {
327 return got_error_fmt(GOT_ERR_BAD_REF_NAME,
328 "reference namespace '%s'", namespace);
331 return NULL;
334 static const struct got_error *
335 protect_ref_namespace(const char *refname, const char *namespace)
337 const struct got_error *err;
339 err = validate_namespace(namespace);
340 if (err)
341 return err;
343 if (strncmp(namespace, refname, strlen(namespace)) == 0)
344 return got_error_fmt(GOT_ERR_REFS_PROTECTED, "%s", namespace);
346 return NULL;
349 static const struct got_error *
350 verify_object_type(struct got_object_id *id, int expected_obj_type,
351 struct got_pack *pack, struct got_packidx *packidx)
353 const struct got_error *err;
354 char hex[SHA1_DIGEST_STRING_LENGTH];
355 struct got_object *obj;
356 int idx;
357 const char *typestr;
359 idx = got_packidx_get_object_idx(packidx, id);
360 if (idx == -1) {
361 got_sha1_digest_to_str(id->sha1, hex, sizeof(hex));
362 return got_error_fmt(GOT_ERR_BAD_PACKFILE,
363 "object %s is missing from pack file", hex);
366 err = got_object_open_from_packfile(&obj, id, pack, packidx,
367 idx, repo_write.repo);
368 if (err)
369 return err;
371 if (obj->type != expected_obj_type) {
372 got_sha1_digest_to_str(id->sha1, hex, sizeof(hex));
373 got_object_type_label(&typestr, expected_obj_type);
374 err = got_error_fmt(GOT_ERR_OBJ_TYPE,
375 "%s is not pointing at a %s object", hex, typestr);
377 got_object_close(obj);
378 return err;
381 static const struct got_error *
382 protect_tag_namespace(const char *namespace, struct got_pack *pack,
383 struct got_packidx *packidx, struct gotd_ref_update *ref_update)
385 const struct got_error *err;
387 err = validate_namespace(namespace);
388 if (err)
389 return err;
391 if (strncmp(namespace, got_ref_get_name(ref_update->ref),
392 strlen(namespace)) != 0)
393 return NULL;
395 if (!ref_update->ref_is_new)
396 return got_error_fmt(GOT_ERR_REFS_PROTECTED, "%s", namespace);
398 return verify_object_type(&ref_update->new_id, GOT_OBJ_TYPE_TAG,
399 pack, packidx);
402 static const struct got_error *
403 protect_require_yca(struct got_object_id *tip_id,
404 size_t max_commits_to_traverse, struct got_pack *pack,
405 struct got_packidx *packidx, struct got_reference *ref)
407 const struct got_error *err;
408 uint8_t *buf = NULL;
409 size_t len;
410 struct got_object_id *expected_yca_id = NULL;
411 struct got_object *obj = NULL;
412 struct got_commit_object *commit = NULL;
413 char hex[SHA1_DIGEST_STRING_LENGTH];
414 const struct got_object_id_queue *parent_ids;
415 struct got_object_id_queue ids;
416 struct got_object_qid *pid, *qid;
417 struct got_object_idset *traversed_set = NULL;
418 int found_yca = 0, obj_type;
420 STAILQ_INIT(&ids);
422 err = got_ref_resolve(&expected_yca_id, repo_write.repo, ref);
423 if (err)
424 return err;
426 err = got_object_get_type(&obj_type, repo_write.repo, expected_yca_id);
427 if (err)
428 goto done;
430 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
431 got_sha1_digest_to_str(expected_yca_id->sha1, hex, sizeof(hex));
432 err = got_error_fmt(GOT_ERR_OBJ_TYPE,
433 "%s is not pointing at a commit object", hex);
434 goto done;
437 traversed_set = got_object_idset_alloc();
438 if (traversed_set == NULL) {
439 err = got_error_from_errno("got_object_idset_alloc");
440 goto done;
443 err = got_object_qid_alloc(&qid, tip_id);
444 if (err)
445 goto done;
446 STAILQ_INSERT_TAIL(&ids, qid, entry);
447 while (!STAILQ_EMPTY(&ids)) {
448 err = check_cancelled(NULL);
449 if (err)
450 break;
452 qid = STAILQ_FIRST(&ids);
453 if (got_object_id_cmp(&qid->id, expected_yca_id) == 0) {
454 found_yca = 1;
455 break;
458 if (got_object_idset_num_elements(traversed_set) >=
459 max_commits_to_traverse)
460 break;
462 if (got_object_idset_contains(traversed_set, &qid->id)) {
463 STAILQ_REMOVE_HEAD(&ids, entry);
464 got_object_qid_free(qid);
465 qid = NULL;
466 continue;
468 err = got_object_idset_add(traversed_set, &qid->id, NULL);
469 if (err)
470 goto done;
472 err = got_object_open(&obj, repo_write.repo, &qid->id);
473 if (err && err->code != GOT_ERR_NO_OBJ)
474 goto done;
475 err = NULL;
476 if (obj) {
477 err = got_object_commit_open(&commit, repo_write.repo,
478 obj);
479 if (err)
480 goto done;
481 } else {
482 int idx;
484 idx = got_packidx_get_object_idx(packidx, &qid->id);
485 if (idx == -1) {
486 got_sha1_digest_to_str(qid->id.sha1,
487 hex, sizeof(hex));
488 err = got_error_fmt(GOT_ERR_BAD_PACKFILE,
489 "object %s is missing from pack file", hex);
490 goto done;
493 err = got_object_open_from_packfile(&obj, &qid->id,
494 pack, packidx, idx, repo_write.repo);
495 if (err)
496 goto done;
498 if (obj->type != GOT_OBJ_TYPE_COMMIT) {
499 got_sha1_digest_to_str(qid->id.sha1,
500 hex, sizeof(hex));
501 err = got_error_fmt(GOT_ERR_OBJ_TYPE,
502 "%s is not pointing at a commit object",
503 hex);
504 goto done;
507 err = got_packfile_extract_object_to_mem(&buf, &len,
508 obj, pack);
509 if (err)
510 goto done;
512 err = got_object_parse_commit(&commit, buf, len);
513 if (err)
514 goto done;
516 free(buf);
517 buf = NULL;
520 got_object_close(obj);
521 obj = NULL;
523 STAILQ_REMOVE_HEAD(&ids, entry);
524 got_object_qid_free(qid);
525 qid = NULL;
527 if (got_object_commit_get_nparents(commit) == 0)
528 break;
530 parent_ids = got_object_commit_get_parent_ids(commit);
531 STAILQ_FOREACH(pid, parent_ids, entry) {
532 err = check_cancelled(NULL);
533 if (err)
534 goto done;
535 err = got_object_qid_alloc(&qid, &pid->id);
536 if (err)
537 goto done;
538 STAILQ_INSERT_TAIL(&ids, qid, entry);
539 qid = NULL;
541 got_object_commit_close(commit);
542 commit = NULL;
545 if (!found_yca) {
546 err = got_error_fmt(GOT_ERR_REF_PROTECTED, "%s",
547 got_ref_get_name(ref));
549 done:
550 got_object_idset_free(traversed_set);
551 got_object_id_queue_free(&ids);
552 free(buf);
553 if (obj)
554 got_object_close(obj);
555 if (commit)
556 got_object_commit_close(commit);
557 free(expected_yca_id);
558 return err;
561 static const struct got_error *
562 protect_branch_namespace(const char *namespace, struct got_pack *pack,
563 struct got_packidx *packidx, struct gotd_ref_update *ref_update)
565 const struct got_error *err;
567 err = validate_namespace(namespace);
568 if (err)
569 return err;
571 if (strncmp(namespace, got_ref_get_name(ref_update->ref),
572 strlen(namespace)) != 0)
573 return NULL;
575 if (ref_update->ref_is_new) {
576 return verify_object_type(&ref_update->new_id,
577 GOT_OBJ_TYPE_COMMIT, pack, packidx);
580 return protect_require_yca(&ref_update->new_id,
581 be32toh(packidx->hdr.fanout_table[0xff]), pack, packidx,
582 ref_update->ref);
585 static const struct got_error *
586 protect_branch(const char *refname, struct got_pack *pack,
587 struct got_packidx *packidx, struct gotd_ref_update *ref_update)
589 if (strcmp(refname, got_ref_get_name(ref_update->ref)) != 0)
590 return NULL;
592 /* Always allow new branches to be created. */
593 if (ref_update->ref_is_new) {
594 return verify_object_type(&ref_update->new_id,
595 GOT_OBJ_TYPE_COMMIT, pack, packidx);
598 return protect_require_yca(&ref_update->new_id,
599 be32toh(packidx->hdr.fanout_table[0xff]), pack, packidx,
600 ref_update->ref);
603 static const struct got_error *
604 recv_ref_update(struct imsg *imsg)
606 static const char zero_id[SHA1_DIGEST_LENGTH];
607 const struct got_error *err = NULL;
608 struct repo_write_client *client = &repo_write_client;
609 struct gotd_imsg_ref_update iref;
610 size_t datalen;
611 char *refname = NULL;
612 struct got_reference *ref = NULL;
613 struct got_object_id *id = NULL;
614 struct imsgbuf ibuf;
615 struct gotd_ref_update *ref_update = NULL;
617 log_debug("ref-update received");
619 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
620 if (datalen < sizeof(iref))
621 return got_error(GOT_ERR_PRIVSEP_LEN);
622 memcpy(&iref, imsg->data, sizeof(iref));
623 if (datalen != sizeof(iref) + iref.name_len)
624 return got_error(GOT_ERR_PRIVSEP_LEN);
626 imsg_init(&ibuf, client->fd);
628 refname = strndup(imsg->data + sizeof(iref), iref.name_len);
629 if (refname == NULL)
630 return got_error_from_errno("strndup");
632 ref_update = calloc(1, sizeof(*ref_update));
633 if (ref_update == NULL) {
634 err = got_error_from_errno("malloc");
635 goto done;
638 memcpy(ref_update->old_id.sha1, iref.old_id, SHA1_DIGEST_LENGTH);
639 memcpy(ref_update->new_id.sha1, iref.new_id, SHA1_DIGEST_LENGTH);
641 err = got_ref_open(&ref, repo_write.repo, refname, 0);
642 if (err) {
643 if (err->code != GOT_ERR_NOT_REF)
644 goto done;
645 if (memcmp(ref_update->new_id.sha1,
646 zero_id, sizeof(zero_id)) == 0) {
647 err = got_error_fmt(GOT_ERR_BAD_OBJ_ID,
648 "%s", refname);
649 goto done;
651 err = got_ref_alloc(&ref, refname, &ref_update->new_id);
652 if (err)
653 goto done;
654 ref_update->ref_is_new = 1;
655 client->nref_new++;
657 if (got_ref_is_symbolic(ref)) {
658 err = got_error_fmt(GOT_ERR_BAD_REF_TYPE,
659 "'%s' is a symbolic reference and cannot "
660 "be updated", got_ref_get_name(ref));
661 goto done;
663 if (strncmp("refs/", got_ref_get_name(ref), 5) != 0) {
664 err = got_error_fmt(GOT_ERR_BAD_REF_NAME,
665 "%s: does not begin with 'refs/'",
666 got_ref_get_name(ref));
667 goto done;
670 err = protect_ref_namespace(got_ref_get_name(ref), "refs/got/");
671 if (err)
672 goto done;
673 err = protect_ref_namespace(got_ref_get_name(ref), "refs/remotes/");
674 if (err)
675 goto done;
677 if (!ref_update->ref_is_new) {
678 /*
679 * Ensure the client's idea of this update is still valid.
680 * At this point we can only return an error, to prevent
681 * the client from uploading a pack file which will likely
682 * have to be discarded.
683 */
684 err = got_ref_resolve(&id, repo_write.repo, ref);
685 if (err)
686 goto done;
688 if (got_object_id_cmp(id, &ref_update->old_id) != 0) {
689 err = got_error_fmt(GOT_ERR_REF_BUSY,
690 "%s has been modified by someone else "
691 "while transaction was in progress",
692 got_ref_get_name(ref));
693 goto done;
697 gotd_imsg_send_ack(&ref_update->new_id, &ibuf, PROC_REPO_WRITE,
698 repo_write.pid);
700 ref_update->ref = ref;
701 if (memcmp(ref_update->new_id.sha1, zero_id, sizeof(zero_id)) == 0) {
702 ref_update->delete_ref = 1;
703 client->nref_del++;
705 STAILQ_INSERT_HEAD(&client->ref_updates, ref_update, entry);
706 client->nref_updates++;
707 ref = NULL;
708 ref_update = NULL;
709 done:
710 if (ref)
711 got_ref_close(ref);
712 free(ref_update);
713 free(refname);
714 free(id);
715 return err;
718 static const struct got_error *
719 pack_index_progress(void *arg, uint32_t nobj_total, uint32_t nobj_indexed,
720 uint32_t nobj_loose, uint32_t nobj_resolved)
722 int p_indexed = 0, p_resolved = 0;
723 int nobj_delta = nobj_total - nobj_loose;
725 if (nobj_total > 0)
726 p_indexed = (nobj_indexed * 100) / nobj_total;
728 if (nobj_delta > 0)
729 p_resolved = (nobj_resolved * 100) / nobj_delta;
731 if (p_resolved > 0) {
732 log_debug("indexing %d objects %d%%; resolving %d deltas %d%%",
733 nobj_total, p_indexed, nobj_delta, p_resolved);
734 } else
735 log_debug("indexing %d objects %d%%", nobj_total, p_indexed);
737 return NULL;
740 static const struct got_error *
741 read_more_pack_stream(int infd, BUF *buf, size_t minsize)
743 const struct got_error *err = NULL;
744 uint8_t readahead[65536];
745 size_t have, newlen;
747 err = got_poll_read_full(infd, &have,
748 readahead, sizeof(readahead), minsize);
749 if (err)
750 return err;
752 err = buf_append(&newlen, buf, readahead, have);
753 if (err)
754 return err;
755 return NULL;
758 static const struct got_error *
759 copy_object_type_and_size(uint8_t *type, uint64_t *size, int infd, int outfd,
760 off_t *outsize, BUF *buf, size_t *buf_pos, struct got_hash *ctx)
762 const struct got_error *err = NULL;
763 uint8_t t = 0;
764 uint64_t s = 0;
765 uint8_t sizebuf[8];
766 size_t i = 0;
767 off_t obj_offset = *outsize;
769 do {
770 /* We do not support size values which don't fit in 64 bit. */
771 if (i > 9)
772 return got_error_fmt(GOT_ERR_OBJ_TOO_LARGE,
773 "packfile offset %lld", (long long)obj_offset);
775 if (buf_len(buf) - *buf_pos < sizeof(sizebuf[0])) {
776 err = read_more_pack_stream(infd, buf,
777 sizeof(sizebuf[0]));
778 if (err)
779 return err;
782 sizebuf[i] = buf_getc(buf, *buf_pos);
783 *buf_pos += sizeof(sizebuf[i]);
785 if (i == 0) {
786 t = (sizebuf[i] & GOT_PACK_OBJ_SIZE0_TYPE_MASK) >>
787 GOT_PACK_OBJ_SIZE0_TYPE_MASK_SHIFT;
788 s = (sizebuf[i] & GOT_PACK_OBJ_SIZE0_VAL_MASK);
789 } else {
790 size_t shift = 4 + 7 * (i - 1);
791 s |= ((sizebuf[i] & GOT_PACK_OBJ_SIZE_VAL_MASK) <<
792 shift);
794 i++;
795 } while (sizebuf[i - 1] & GOT_PACK_OBJ_SIZE_MORE);
797 err = got_pack_hwrite(outfd, sizebuf, i, ctx);
798 if (err)
799 return err;
800 *outsize += i;
802 *type = t;
803 *size = s;
804 return NULL;
807 static const struct got_error *
808 copy_ref_delta(int infd, int outfd, off_t *outsize, BUF *buf, size_t *buf_pos,
809 struct got_hash *ctx)
811 const struct got_error *err = NULL;
812 size_t remain = buf_len(buf) - *buf_pos;
814 if (remain < SHA1_DIGEST_LENGTH) {
815 err = read_more_pack_stream(infd, buf,
816 SHA1_DIGEST_LENGTH - remain);
817 if (err)
818 return err;
821 err = got_pack_hwrite(outfd, buf_get(buf) + *buf_pos,
822 SHA1_DIGEST_LENGTH, ctx);
823 if (err)
824 return err;
826 *buf_pos += SHA1_DIGEST_LENGTH;
827 return NULL;
830 static const struct got_error *
831 copy_offset_delta(int infd, int outfd, off_t *outsize, BUF *buf, size_t *buf_pos,
832 struct got_hash *ctx)
834 const struct got_error *err = NULL;
835 uint64_t o = 0;
836 uint8_t offbuf[8];
837 size_t i = 0;
838 off_t obj_offset = *outsize;
840 do {
841 /* We do not support offset values which don't fit in 64 bit. */
842 if (i > 8)
843 return got_error_fmt(GOT_ERR_OBJ_TOO_LARGE,
844 "packfile offset %lld", (long long)obj_offset);
846 if (buf_len(buf) - *buf_pos < sizeof(offbuf[0])) {
847 err = read_more_pack_stream(infd, buf,
848 sizeof(offbuf[0]));
849 if (err)
850 return err;
853 offbuf[i] = buf_getc(buf, *buf_pos);
854 *buf_pos += sizeof(offbuf[i]);
856 if (i == 0)
857 o = (offbuf[i] & GOT_PACK_OBJ_DELTA_OFF_VAL_MASK);
858 else {
859 o++;
860 o <<= 7;
861 o += (offbuf[i] & GOT_PACK_OBJ_DELTA_OFF_VAL_MASK);
863 i++;
864 } while (offbuf[i - 1] & GOT_PACK_OBJ_DELTA_OFF_MORE);
866 if (o < sizeof(struct got_packfile_hdr) || o > *outsize)
867 return got_error(GOT_ERR_PACK_OFFSET);
869 err = got_pack_hwrite(outfd, offbuf, i, ctx);
870 if (err)
871 return err;
873 *outsize += i;
874 return NULL;
877 static const struct got_error *
878 copy_zstream(int infd, int outfd, off_t *outsize, BUF *buf, size_t *buf_pos,
879 struct got_hash *ctx)
881 const struct got_error *err = NULL;
882 z_stream z;
883 int zret;
884 char voidbuf[1024];
885 size_t consumed_total = 0;
886 off_t zstream_offset = *outsize;
888 memset(&z, 0, sizeof(z));
890 z.zalloc = Z_NULL;
891 z.zfree = Z_NULL;
892 zret = inflateInit(&z);
893 if (zret != Z_OK) {
894 if (zret == Z_ERRNO)
895 return got_error_from_errno("inflateInit");
896 if (zret == Z_MEM_ERROR) {
897 errno = ENOMEM;
898 return got_error_from_errno("inflateInit");
900 return got_error_msg(GOT_ERR_DECOMPRESSION,
901 "inflateInit failed");
904 while (zret != Z_STREAM_END) {
905 size_t last_total_in, consumed;
907 /*
908 * Decompress into the void. Object data will be parsed
909 * later, when the pack file is indexed. For now, we just
910 * want to locate the end of the compressed stream.
911 */
912 while (zret != Z_STREAM_END && buf_len(buf) - *buf_pos > 0) {
913 last_total_in = z.total_in;
914 z.next_in = buf_get(buf) + *buf_pos;
915 z.avail_in = buf_len(buf) - *buf_pos;
916 z.next_out = voidbuf;
917 z.avail_out = sizeof(voidbuf);
919 zret = inflate(&z, Z_SYNC_FLUSH);
920 if (zret != Z_OK && zret != Z_BUF_ERROR &&
921 zret != Z_STREAM_END) {
922 err = got_error_fmt(GOT_ERR_DECOMPRESSION,
923 "packfile offset %lld",
924 (long long)zstream_offset);
925 goto done;
927 consumed = z.total_in - last_total_in;
929 err = got_pack_hwrite(outfd, buf_get(buf) + *buf_pos,
930 consumed, ctx);
931 if (err)
932 goto done;
934 err = buf_discard(buf, *buf_pos + consumed);
935 if (err)
936 goto done;
937 *buf_pos = 0;
939 consumed_total += consumed;
942 if (zret != Z_STREAM_END) {
943 err = read_more_pack_stream(infd, buf, 1);
944 if (err)
945 goto done;
949 if (err == NULL)
950 *outsize += consumed_total;
951 done:
952 inflateEnd(&z);
953 return err;
956 static const struct got_error *
957 validate_object_type(int obj_type)
959 switch (obj_type) {
960 case GOT_OBJ_TYPE_BLOB:
961 case GOT_OBJ_TYPE_COMMIT:
962 case GOT_OBJ_TYPE_TREE:
963 case GOT_OBJ_TYPE_TAG:
964 case GOT_OBJ_TYPE_REF_DELTA:
965 case GOT_OBJ_TYPE_OFFSET_DELTA:
966 return NULL;
967 default:
968 break;
971 return got_error(GOT_ERR_OBJ_TYPE);
974 static const struct got_error *
975 ensure_all_objects_exist_locally(struct gotd_ref_updates *ref_updates)
977 const struct got_error *err = NULL;
978 struct gotd_ref_update *ref_update;
979 struct got_object *obj;
981 STAILQ_FOREACH(ref_update, ref_updates, entry) {
982 err = got_object_open(&obj, repo_write.repo,
983 &ref_update->new_id);
984 if (err)
985 return err;
986 got_object_close(obj);
989 return NULL;
992 static const struct got_error *
993 recv_packdata(off_t *outsize, uint32_t *nobj, uint8_t *sha1,
994 int infd, int outfd)
996 const struct got_error *err;
997 struct repo_write_client *client = &repo_write_client;
998 struct got_packfile_hdr hdr;
999 size_t have;
1000 uint32_t nhave = 0;
1001 struct got_hash ctx;
1002 uint8_t expected_sha1[SHA1_DIGEST_LENGTH];
1003 char hex[SHA1_DIGEST_STRING_LENGTH];
1004 BUF *buf = NULL;
1005 size_t buf_pos = 0, remain;
1006 ssize_t w;
1008 *outsize = 0;
1009 *nobj = 0;
1011 /* if only deleting references there's nothing to read */
1012 if (client->nref_updates == client->nref_del)
1013 return NULL;
1015 got_hash_init(&ctx, GOT_HASH_SHA1);
1017 err = got_poll_read_full(infd, &have, &hdr, sizeof(hdr), sizeof(hdr));
1018 if (err)
1019 return err;
1020 if (have != sizeof(hdr))
1021 return got_error_msg(GOT_ERR_BAD_PACKFILE, "short pack file");
1022 *outsize += have;
1024 if (hdr.signature != htobe32(GOT_PACKFILE_SIGNATURE))
1025 return got_error_msg(GOT_ERR_BAD_PACKFILE,
1026 "bad packfile signature");
1027 if (hdr.version != htobe32(GOT_PACKFILE_VERSION))
1028 return got_error_msg(GOT_ERR_BAD_PACKFILE,
1029 "bad packfile version");
1031 *nobj = be32toh(hdr.nobjects);
1032 if (*nobj == 0) {
1034 * Clients which are creating new references only
1035 * will send us an empty pack file.
1037 if (client->nref_updates > 0 &&
1038 client->nref_updates == client->nref_new)
1039 return NULL;
1042 * Clients which only move existing refs will send us an empty
1043 * pack file. All referenced objects must exist locally.
1045 err = ensure_all_objects_exist_locally(&client->ref_updates);
1046 if (err) {
1047 if (err->code != GOT_ERR_NO_OBJ)
1048 return err;
1049 return got_error_msg(GOT_ERR_BAD_PACKFILE,
1050 "bad packfile with zero objects");
1053 client->nref_move = client->nref_updates;
1054 return NULL;
1057 log_debug("expecting %d objects", *nobj);
1059 err = got_pack_hwrite(outfd, &hdr, sizeof(hdr), &ctx);
1060 if (err)
1061 return err;
1063 err = buf_alloc(&buf, 65536);
1064 if (err)
1065 return err;
1067 while (nhave != *nobj) {
1068 uint8_t obj_type;
1069 uint64_t obj_size;
1071 err = copy_object_type_and_size(&obj_type, &obj_size,
1072 infd, outfd, outsize, buf, &buf_pos, &ctx);
1073 if (err)
1074 goto done;
1076 err = validate_object_type(obj_type);
1077 if (err)
1078 goto done;
1080 if (obj_type == GOT_OBJ_TYPE_REF_DELTA) {
1081 err = copy_ref_delta(infd, outfd, outsize,
1082 buf, &buf_pos, &ctx);
1083 if (err)
1084 goto done;
1085 } else if (obj_type == GOT_OBJ_TYPE_OFFSET_DELTA) {
1086 err = copy_offset_delta(infd, outfd, outsize,
1087 buf, &buf_pos, &ctx);
1088 if (err)
1089 goto done;
1092 err = copy_zstream(infd, outfd, outsize, buf, &buf_pos, &ctx);
1093 if (err)
1094 goto done;
1096 nhave++;
1099 log_debug("received %u objects", *nobj);
1101 got_hash_final(&ctx, expected_sha1);
1103 remain = buf_len(buf) - buf_pos;
1104 if (remain < SHA1_DIGEST_LENGTH) {
1105 err = read_more_pack_stream(infd, buf,
1106 SHA1_DIGEST_LENGTH - remain);
1107 if (err)
1108 return err;
1111 got_sha1_digest_to_str(expected_sha1, hex, sizeof(hex));
1112 log_debug("expect SHA1: %s", hex);
1113 got_sha1_digest_to_str(buf_get(buf) + buf_pos, hex, sizeof(hex));
1114 log_debug("actual SHA1: %s", hex);
1116 if (memcmp(buf_get(buf) + buf_pos, expected_sha1,
1117 SHA1_DIGEST_LENGTH) != 0) {
1118 err = got_error(GOT_ERR_PACKFILE_CSUM);
1119 goto done;
1122 memcpy(sha1, expected_sha1, SHA1_DIGEST_LENGTH);
1124 w = write(outfd, expected_sha1, SHA1_DIGEST_LENGTH);
1125 if (w == -1) {
1126 err = got_error_from_errno("write");
1127 goto done;
1129 if (w != SHA1_DIGEST_LENGTH) {
1130 err = got_error(GOT_ERR_IO);
1131 goto done;
1134 *outsize += SHA1_DIGEST_LENGTH;
1136 if (fsync(outfd) == -1) {
1137 err = got_error_from_errno("fsync");
1138 goto done;
1140 if (lseek(outfd, 0L, SEEK_SET) == -1) {
1141 err = got_error_from_errno("lseek");
1142 goto done;
1144 done:
1145 buf_free(buf);
1146 return err;
1149 static const struct got_error *
1150 report_pack_status(const struct got_error *unpack_err)
1152 const struct got_error *err = NULL;
1153 struct repo_write_client *client = &repo_write_client;
1154 struct gotd_imsg_packfile_status istatus;
1155 struct ibuf *wbuf;
1156 struct imsgbuf ibuf;
1157 const char *unpack_ok = "unpack ok\n";
1158 size_t len;
1160 imsg_init(&ibuf, client->fd);
1162 if (unpack_err)
1163 istatus.reason_len = strlen(unpack_err->msg);
1164 else
1165 istatus.reason_len = strlen(unpack_ok);
1167 len = sizeof(istatus) + istatus.reason_len;
1168 wbuf = imsg_create(&ibuf, GOTD_IMSG_PACKFILE_STATUS, PROC_REPO_WRITE,
1169 repo_write.pid, len);
1170 if (wbuf == NULL) {
1171 err = got_error_from_errno("imsg_create PACKFILE_STATUS");
1172 goto done;
1175 if (imsg_add(wbuf, &istatus, sizeof(istatus)) == -1) {
1176 err = got_error_from_errno("imsg_add PACKFILE_STATUS");
1177 goto done;
1180 if (imsg_add(wbuf, err ? err->msg : unpack_ok,
1181 istatus.reason_len) == -1) {
1182 err = got_error_from_errno("imsg_add PACKFILE_STATUS");
1183 goto done;
1186 imsg_close(&ibuf, wbuf);
1188 err = gotd_imsg_flush(&ibuf);
1189 done:
1190 imsg_clear(&ibuf);
1191 return err;
1194 static const struct got_error *
1195 recv_packfile(int *have_packfile, struct imsg *imsg)
1197 const struct got_error *err = NULL, *unpack_err;
1198 struct repo_write_client *client = &repo_write_client;
1199 struct gotd_imsg_recv_packfile ireq;
1200 FILE *tempfiles[3] = { NULL, NULL, NULL };
1201 struct repo_tempfile {
1202 int fd;
1203 int idx;
1204 } repo_tempfiles[3] = { { - 1, - 1 }, { - 1, - 1 }, { - 1, - 1 }, };
1205 int i;
1206 size_t datalen;
1207 struct imsgbuf ibuf;
1208 struct got_ratelimit rl;
1209 struct got_pack *pack = NULL;
1210 off_t pack_filesize = 0;
1211 uint32_t nobj = 0;
1213 log_debug("packfile request received");
1215 *have_packfile = 0;
1216 got_ratelimit_init(&rl, 2, 0);
1218 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1219 if (datalen != sizeof(ireq))
1220 return got_error(GOT_ERR_PRIVSEP_LEN);
1221 memcpy(&ireq, imsg->data, sizeof(ireq));
1223 if (client->pack_pipe == -1 || client->packidx_fd == -1)
1224 return got_error(GOT_ERR_PRIVSEP_NO_FD);
1226 imsg_init(&ibuf, client->fd);
1228 pack = &client->pack;
1229 memset(pack, 0, sizeof(*pack));
1230 pack->fd = imsg_get_fd(imsg);
1231 if (pack->fd == -1)
1232 return got_error(GOT_ERR_PRIVSEP_NO_FD);
1234 err = got_delta_cache_alloc(&pack->delta_cache);
1235 if (err)
1236 return err;
1238 for (i = 0; i < nitems(repo_tempfiles); i++) {
1239 struct repo_tempfile *t = &repo_tempfiles[i];
1240 err = got_repo_temp_fds_get(&t->fd, &t->idx, repo_write.repo);
1241 if (err)
1242 goto done;
1245 for (i = 0; i < nitems(tempfiles); i++) {
1246 int fd;
1247 FILE *f;
1249 fd = dup(repo_tempfiles[i].fd);
1250 if (fd == -1) {
1251 err = got_error_from_errno("dup");
1252 goto done;
1254 f = fdopen(fd, "w+");
1255 if (f == NULL) {
1256 err = got_error_from_errno("fdopen");
1257 close(fd);
1258 goto done;
1260 tempfiles[i] = f;
1263 err = gotd_imsg_flush(&ibuf);
1264 if (err)
1265 goto done;
1267 log_debug("receiving pack data");
1268 unpack_err = recv_packdata(&pack_filesize, &nobj,
1269 client->pack_sha1, client->pack_pipe, pack->fd);
1270 if (ireq.report_status) {
1271 err = report_pack_status(unpack_err);
1272 if (err) {
1273 /* Git clients hang up after sending the pack file. */
1274 if (err->code == GOT_ERR_EOF)
1275 err = NULL;
1278 if (unpack_err)
1279 err = unpack_err;
1280 if (err)
1281 goto done;
1283 log_debug("pack data received");
1286 * Clients which are creating new references only will
1287 * send us an empty pack file.
1289 if (nobj == 0 &&
1290 pack_filesize == sizeof(struct got_packfile_hdr) &&
1291 client->nref_updates > 0 &&
1292 client->nref_updates == client->nref_new)
1293 goto done;
1296 * Clients which are deleting references only will send
1297 * no pack file.
1299 if (nobj == 0 &&
1300 client->nref_del > 0 &&
1301 client->nref_updates == client->nref_del)
1302 goto done;
1305 * Clients which only move existing refs will send us an empty
1306 * pack file. All referenced objects must exist locally.
1308 if (nobj == 0 &&
1309 pack_filesize == sizeof(struct got_packfile_hdr) &&
1310 client->nref_move > 0 &&
1311 client->nref_updates == client->nref_move)
1312 goto done;
1314 pack->filesize = pack_filesize;
1315 *have_packfile = 1;
1317 log_debug("begin indexing pack (%lld bytes in size)",
1318 (long long)pack->filesize);
1319 err = got_pack_index(pack, client->packidx_fd,
1320 tempfiles[0], tempfiles[1], tempfiles[2], client->pack_sha1,
1321 pack_index_progress, NULL, &rl);
1322 if (err)
1323 goto done;
1324 log_debug("done indexing pack");
1326 if (fsync(client->packidx_fd) == -1) {
1327 err = got_error_from_errno("fsync");
1328 goto done;
1330 if (lseek(client->packidx_fd, 0L, SEEK_SET) == -1)
1331 err = got_error_from_errno("lseek");
1332 done:
1333 if (close(client->pack_pipe) == -1 && err == NULL)
1334 err = got_error_from_errno("close");
1335 client->pack_pipe = -1;
1336 for (i = 0; i < nitems(repo_tempfiles); i++) {
1337 struct repo_tempfile *t = &repo_tempfiles[i];
1338 if (t->idx != -1)
1339 got_repo_temp_fds_put(t->idx, repo_write.repo);
1341 for (i = 0; i < nitems(tempfiles); i++) {
1342 if (tempfiles[i] && fclose(tempfiles[i]) == EOF && err == NULL)
1343 err = got_error_from_errno("fclose");
1345 if (err)
1346 got_pack_close(pack);
1347 imsg_clear(&ibuf);
1348 return err;
1351 static const struct got_error *
1352 verify_packfile(void)
1354 const struct got_error *err = NULL, *close_err;
1355 struct repo_write_client *client = &repo_write_client;
1356 struct gotd_ref_update *ref_update;
1357 struct got_packidx *packidx = NULL;
1358 struct stat sb;
1359 char *id_str = NULL;
1360 struct got_object *obj = NULL;
1361 struct got_pathlist_entry *pe;
1362 char hex[SHA1_DIGEST_STRING_LENGTH];
1364 if (STAILQ_EMPTY(&client->ref_updates)) {
1365 return got_error_msg(GOT_ERR_BAD_REQUEST,
1366 "cannot verify pack file without any ref-updates");
1369 if (client->pack.fd == -1) {
1370 return got_error_msg(GOT_ERR_BAD_REQUEST,
1371 "invalid pack file handle during pack verification");
1373 if (client->packidx_fd == -1) {
1374 return got_error_msg(GOT_ERR_BAD_REQUEST,
1375 "invalid pack index handle during pack verification");
1378 if (fstat(client->packidx_fd, &sb) == -1)
1379 return got_error_from_errno("pack index fstat");
1381 packidx = malloc(sizeof(*packidx));
1382 memset(packidx, 0, sizeof(*packidx));
1383 packidx->fd = client->packidx_fd;
1384 client->packidx_fd = -1;
1385 packidx->len = sb.st_size;
1387 err = got_packidx_init_hdr(packidx, 1, client->pack.filesize);
1388 if (err)
1389 return err;
1391 STAILQ_FOREACH(ref_update, &client->ref_updates, entry) {
1392 if (ref_update->delete_ref)
1393 continue;
1395 TAILQ_FOREACH(pe, repo_write.protected_tag_namespaces, entry) {
1396 err = protect_tag_namespace(pe->path, &client->pack,
1397 packidx, ref_update);
1398 if (err)
1399 goto done;
1403 * Objects which already exist in our repository need
1404 * not be present in the pack file.
1406 err = got_object_open(&obj, repo_write.repo,
1407 &ref_update->new_id);
1408 if (err && err->code != GOT_ERR_NO_OBJ)
1409 goto done;
1410 err = NULL;
1411 if (obj) {
1412 got_object_close(obj);
1413 obj = NULL;
1414 } else {
1415 int idx = got_packidx_get_object_idx(packidx,
1416 &ref_update->new_id);
1417 if (idx == -1) {
1418 got_sha1_digest_to_str(ref_update->new_id.sha1,
1419 hex, sizeof(hex));
1420 err = got_error_fmt(GOT_ERR_BAD_PACKFILE,
1421 "object %s is missing from pack file",
1422 hex);
1423 goto done;
1427 TAILQ_FOREACH(pe, repo_write.protected_branch_namespaces,
1428 entry) {
1429 err = protect_branch_namespace(pe->path,
1430 &client->pack, packidx, ref_update);
1431 if (err)
1432 goto done;
1434 TAILQ_FOREACH(pe, repo_write.protected_branches, entry) {
1435 err = protect_branch(pe->path, &client->pack,
1436 packidx, ref_update);
1437 if (err)
1438 goto done;
1442 done:
1443 close_err = got_packidx_close(packidx);
1444 if (close_err && err == NULL)
1445 err = close_err;
1446 free(id_str);
1447 if (obj)
1448 got_object_close(obj);
1449 return err;
1452 static const struct got_error *
1453 protect_refs_from_deletion(void)
1455 const struct got_error *err = NULL;
1456 struct repo_write_client *client = &repo_write_client;
1457 struct gotd_ref_update *ref_update;
1458 struct got_pathlist_entry *pe;
1459 const char *refname;
1461 STAILQ_FOREACH(ref_update, &client->ref_updates, entry) {
1462 if (!ref_update->delete_ref)
1463 continue;
1465 refname = got_ref_get_name(ref_update->ref);
1467 TAILQ_FOREACH(pe, repo_write.protected_tag_namespaces, entry) {
1468 err = protect_ref_namespace(refname, pe->path);
1469 if (err)
1470 return err;
1473 TAILQ_FOREACH(pe, repo_write.protected_branch_namespaces,
1474 entry) {
1475 err = protect_ref_namespace(refname, pe->path);
1476 if (err)
1477 return err;
1480 TAILQ_FOREACH(pe, repo_write.protected_branches, entry) {
1481 if (strcmp(refname, pe->path) == 0) {
1482 return got_error_fmt(GOT_ERR_REF_PROTECTED,
1483 "%s", refname);
1488 return NULL;
1491 static const struct got_error *
1492 install_packfile(struct gotd_imsgev *iev)
1494 struct repo_write_client *client = &repo_write_client;
1495 struct gotd_imsg_packfile_install inst;
1496 int ret;
1498 memset(&inst, 0, sizeof(inst));
1499 inst.client_id = client->id;
1500 memcpy(inst.pack_sha1, client->pack_sha1, SHA1_DIGEST_LENGTH);
1502 ret = gotd_imsg_compose_event(iev, GOTD_IMSG_PACKFILE_INSTALL,
1503 PROC_REPO_WRITE, -1, &inst, sizeof(inst));
1504 if (ret == -1)
1505 return got_error_from_errno("imsg_compose PACKFILE_INSTALL");
1507 return NULL;
1510 static const struct got_error *
1511 send_ref_updates_start(int nref_updates, struct gotd_imsgev *iev)
1513 struct repo_write_client *client = &repo_write_client;
1514 struct gotd_imsg_ref_updates_start istart;
1515 int ret;
1517 memset(&istart, 0, sizeof(istart));
1518 istart.nref_updates = nref_updates;
1519 istart.client_id = client->id;
1521 ret = gotd_imsg_compose_event(iev, GOTD_IMSG_REF_UPDATES_START,
1522 PROC_REPO_WRITE, -1, &istart, sizeof(istart));
1523 if (ret == -1)
1524 return got_error_from_errno("imsg_compose REF_UPDATES_START");
1526 return NULL;
1530 static const struct got_error *
1531 send_ref_update(struct gotd_ref_update *ref_update, struct gotd_imsgev *iev)
1533 struct repo_write_client *client = &repo_write_client;
1534 struct gotd_imsg_ref_update iref;
1535 const char *refname = got_ref_get_name(ref_update->ref);
1536 struct ibuf *wbuf;
1537 size_t len;
1539 memset(&iref, 0, sizeof(iref));
1540 memcpy(iref.old_id, ref_update->old_id.sha1, SHA1_DIGEST_LENGTH);
1541 memcpy(iref.new_id, ref_update->new_id.sha1, SHA1_DIGEST_LENGTH);
1542 iref.ref_is_new = ref_update->ref_is_new;
1543 iref.delete_ref = ref_update->delete_ref;
1544 iref.client_id = client->id;
1545 iref.name_len = strlen(refname);
1547 len = sizeof(iref) + iref.name_len;
1548 wbuf = imsg_create(&iev->ibuf, GOTD_IMSG_REF_UPDATE, PROC_REPO_WRITE,
1549 repo_write.pid, len);
1550 if (wbuf == NULL)
1551 return got_error_from_errno("imsg_create REF_UPDATE");
1553 if (imsg_add(wbuf, &iref, sizeof(iref)) == -1)
1554 return got_error_from_errno("imsg_add REF_UPDATE");
1555 if (imsg_add(wbuf, refname, iref.name_len) == -1)
1556 return got_error_from_errno("imsg_add REF_UPDATE");
1558 imsg_close(&iev->ibuf, wbuf);
1560 gotd_imsg_event_add(iev);
1561 return NULL;
1564 static const struct got_error *
1565 update_refs(struct gotd_imsgev *iev)
1567 const struct got_error *err = NULL;
1568 struct repo_write_client *client = &repo_write_client;
1569 struct gotd_ref_update *ref_update;
1571 err = send_ref_updates_start(client->nref_updates, iev);
1572 if (err)
1573 return err;
1575 STAILQ_FOREACH(ref_update, &client->ref_updates, entry) {
1576 err = send_ref_update(ref_update, iev);
1577 if (err)
1578 goto done;
1580 done:
1581 return err;
1584 static const struct got_error *
1585 receive_pack_pipe(struct imsg *imsg, struct gotd_imsgev *iev)
1587 struct repo_write_client *client = &repo_write_client;
1588 struct gotd_imsg_packfile_pipe ireq;
1589 size_t datalen;
1591 log_debug("receiving pack pipe descriptor");
1593 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1594 if (datalen != sizeof(ireq))
1595 return got_error(GOT_ERR_PRIVSEP_LEN);
1596 memcpy(&ireq, imsg->data, sizeof(ireq));
1598 if (client->pack_pipe != -1)
1599 return got_error(GOT_ERR_PRIVSEP_MSG);
1601 client->pack_pipe = imsg_get_fd(imsg);
1602 if (client->pack_pipe == -1)
1603 return got_error(GOT_ERR_PRIVSEP_NO_FD);
1605 return NULL;
1608 static const struct got_error *
1609 receive_pack_idx(struct imsg *imsg, struct gotd_imsgev *iev)
1611 struct repo_write_client *client = &repo_write_client;
1612 struct gotd_imsg_packidx_file ireq;
1613 size_t datalen;
1615 log_debug("receiving pack index output file");
1617 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1618 if (datalen != sizeof(ireq))
1619 return got_error(GOT_ERR_PRIVSEP_LEN);
1620 memcpy(&ireq, imsg->data, sizeof(ireq));
1622 if (client->packidx_fd != -1)
1623 return got_error(GOT_ERR_PRIVSEP_MSG);
1625 client->packidx_fd = imsg_get_fd(imsg);
1626 if (client->packidx_fd == -1)
1627 return got_error(GOT_ERR_PRIVSEP_NO_FD);
1629 return NULL;
1632 static void
1633 repo_write_dispatch_session(int fd, short event, void *arg)
1635 const struct got_error *err = NULL;
1636 struct gotd_imsgev *iev = arg;
1637 struct imsgbuf *ibuf = &iev->ibuf;
1638 struct imsg imsg;
1639 struct repo_write_client *client = &repo_write_client;
1640 ssize_t n;
1641 int shut = 0, have_packfile = 0;
1643 if (event & EV_READ) {
1644 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
1645 fatal("imsg_read error");
1646 if (n == 0) /* Connection closed. */
1647 shut = 1;
1650 if (event & EV_WRITE) {
1651 n = msgbuf_write(&ibuf->w);
1652 if (n == -1 && errno != EAGAIN)
1653 fatal("msgbuf_write");
1654 if (n == 0) /* Connection closed. */
1655 shut = 1;
1658 for (;;) {
1659 if ((n = imsg_get(ibuf, &imsg)) == -1)
1660 fatal("%s: imsg_get error", __func__);
1661 if (n == 0) /* No more messages. */
1662 break;
1664 if (imsg.hdr.type != GOTD_IMSG_LIST_REFS_INTERNAL &&
1665 client->id == 0) {
1666 err = got_error(GOT_ERR_PRIVSEP_MSG);
1667 break;
1670 switch (imsg.hdr.type) {
1671 case GOTD_IMSG_LIST_REFS_INTERNAL:
1672 err = list_refs(&imsg);
1673 if (err)
1674 log_warnx("ls-refs: %s", err->msg);
1675 break;
1676 case GOTD_IMSG_REF_UPDATE:
1677 err = recv_ref_update(&imsg);
1678 if (err)
1679 log_warnx("ref-update: %s", err->msg);
1680 break;
1681 case GOTD_IMSG_PACKFILE_PIPE:
1682 err = receive_pack_pipe(&imsg, iev);
1683 if (err) {
1684 log_warnx("receiving pack pipe: %s", err->msg);
1685 break;
1687 break;
1688 case GOTD_IMSG_PACKIDX_FILE:
1689 err = receive_pack_idx(&imsg, iev);
1690 if (err) {
1691 log_warnx("receiving pack index: %s",
1692 err->msg);
1693 break;
1695 break;
1696 case GOTD_IMSG_RECV_PACKFILE:
1697 err = protect_refs_from_deletion();
1698 if (err)
1699 break;
1700 err = recv_packfile(&have_packfile, &imsg);
1701 if (err) {
1702 log_warnx("receive packfile: %s", err->msg);
1703 break;
1705 if (have_packfile) {
1706 err = verify_packfile();
1707 if (err) {
1708 log_warnx("verify packfile: %s",
1709 err->msg);
1710 break;
1712 err = install_packfile(iev);
1713 if (err) {
1714 log_warnx("install packfile: %s",
1715 err->msg);
1716 break;
1719 err = update_refs(iev);
1720 if (err) {
1721 log_warnx("update refs: %s", err->msg);
1723 break;
1724 default:
1725 log_debug("unexpected imsg %d", imsg.hdr.type);
1726 break;
1729 imsg_free(&imsg);
1732 if (!shut && check_cancelled(NULL) == NULL) {
1733 if (err &&
1734 gotd_imsg_send_error_event(iev, PROC_REPO_WRITE,
1735 client->id, err) == -1) {
1736 log_warnx("could not send error to parent: %s",
1737 err->msg);
1739 gotd_imsg_event_add(iev);
1740 } else {
1741 /* This pipe is dead. Remove its event handler */
1742 event_del(&iev->ev);
1743 event_loopexit(NULL);
1747 static const struct got_error *
1748 recv_connect(struct imsg *imsg)
1750 struct gotd_imsgev *iev = &repo_write.session_iev;
1751 size_t datalen;
1753 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1754 if (datalen != 0)
1755 return got_error(GOT_ERR_PRIVSEP_LEN);
1757 if (repo_write.session_fd != -1)
1758 return got_error(GOT_ERR_PRIVSEP_MSG);
1760 repo_write.session_fd = imsg_get_fd(imsg);
1761 if (repo_write.session_fd == -1)
1762 return got_error(GOT_ERR_PRIVSEP_NO_FD);
1764 imsg_init(&iev->ibuf, repo_write.session_fd);
1765 iev->handler = repo_write_dispatch_session;
1766 iev->events = EV_READ;
1767 iev->handler_arg = NULL;
1768 event_set(&iev->ev, iev->ibuf.fd, EV_READ,
1769 repo_write_dispatch_session, iev);
1770 gotd_imsg_event_add(iev);
1772 return NULL;
1775 static void
1776 repo_write_dispatch(int fd, short event, void *arg)
1778 const struct got_error *err = NULL;
1779 struct gotd_imsgev *iev = arg;
1780 struct imsgbuf *ibuf = &iev->ibuf;
1781 struct imsg imsg;
1782 ssize_t n;
1783 int shut = 0;
1784 struct repo_write_client *client = &repo_write_client;
1786 if (event & EV_READ) {
1787 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
1788 fatal("imsg_read error");
1789 if (n == 0) /* Connection closed. */
1790 shut = 1;
1793 if (event & EV_WRITE) {
1794 n = msgbuf_write(&ibuf->w);
1795 if (n == -1 && errno != EAGAIN)
1796 fatal("msgbuf_write");
1797 if (n == 0) /* Connection closed. */
1798 shut = 1;
1801 while (err == NULL && check_cancelled(NULL) == NULL) {
1802 if ((n = imsg_get(ibuf, &imsg)) == -1)
1803 fatal("%s: imsg_get", __func__);
1804 if (n == 0) /* No more messages. */
1805 break;
1807 switch (imsg.hdr.type) {
1808 case GOTD_IMSG_CONNECT_REPO_CHILD:
1809 err = recv_connect(&imsg);
1810 break;
1811 default:
1812 log_debug("unexpected imsg %d", imsg.hdr.type);
1813 break;
1816 imsg_free(&imsg);
1819 if (!shut && check_cancelled(NULL) == NULL) {
1820 if (err &&
1821 gotd_imsg_send_error_event(iev, PROC_REPO_WRITE,
1822 client->id, err) == -1) {
1823 log_warnx("could not send error to parent: %s",
1824 err->msg);
1826 gotd_imsg_event_add(iev);
1827 } else {
1828 /* This pipe is dead. Remove its event handler */
1829 event_del(&iev->ev);
1830 event_loopexit(NULL);
1834 void
1835 repo_write_main(const char *title, const char *repo_path,
1836 int *pack_fds, int *temp_fds,
1837 struct got_pathlist_head *protected_tag_namespaces,
1838 struct got_pathlist_head *protected_branch_namespaces,
1839 struct got_pathlist_head *protected_branches)
1841 const struct got_error *err = NULL;
1842 struct repo_write_client *client = &repo_write_client;
1843 struct gotd_imsgev iev;
1845 client->fd = -1;
1846 client->pack_pipe = -1;
1847 client->packidx_fd = -1;
1848 client->pack.fd = -1;
1850 repo_write.title = title;
1851 repo_write.pid = getpid();
1852 repo_write.pack_fds = pack_fds;
1853 repo_write.temp_fds = temp_fds;
1854 repo_write.session_fd = -1;
1855 repo_write.session_iev.ibuf.fd = -1;
1856 repo_write.protected_tag_namespaces = protected_tag_namespaces;
1857 repo_write.protected_branch_namespaces = protected_branch_namespaces;
1858 repo_write.protected_branches = protected_branches;
1860 STAILQ_INIT(&repo_write_client.ref_updates);
1862 err = got_repo_open(&repo_write.repo, repo_path, NULL, pack_fds);
1863 if (err)
1864 goto done;
1865 if (!got_repo_is_bare(repo_write.repo)) {
1866 err = got_error_msg(GOT_ERR_NOT_GIT_REPO,
1867 "bare git repository required");
1868 goto done;
1871 got_repo_temp_fds_set(repo_write.repo, temp_fds);
1873 signal(SIGINT, catch_sigint);
1874 signal(SIGTERM, catch_sigterm);
1875 signal(SIGPIPE, SIG_IGN);
1876 signal(SIGHUP, SIG_IGN);
1878 imsg_init(&iev.ibuf, GOTD_FILENO_MSG_PIPE);
1879 iev.handler = repo_write_dispatch;
1880 iev.events = EV_READ;
1881 iev.handler_arg = NULL;
1882 event_set(&iev.ev, iev.ibuf.fd, EV_READ, repo_write_dispatch, &iev);
1883 if (gotd_imsg_compose_event(&iev, GOTD_IMSG_REPO_CHILD_READY,
1884 PROC_REPO_WRITE, -1, NULL, 0) == -1) {
1885 err = got_error_from_errno("imsg compose REPO_CHILD_READY");
1886 goto done;
1889 event_dispatch();
1890 done:
1891 if (err)
1892 log_warnx("%s: %s", title, err->msg);
1893 repo_write_shutdown();
1896 void
1897 repo_write_shutdown(void)
1899 struct repo_write_client *client = &repo_write_client;
1900 struct gotd_ref_update *ref_update;
1902 log_debug("shutting down");
1904 while (!STAILQ_EMPTY(&client->ref_updates)) {
1905 ref_update = STAILQ_FIRST(&client->ref_updates);
1906 STAILQ_REMOVE_HEAD(&client->ref_updates, entry);
1907 got_ref_close(ref_update->ref);
1908 free(ref_update);
1911 got_pack_close(&client->pack);
1912 if (client->fd != -1)
1913 close(client->fd);
1914 if (client->pack_pipe != -1)
1915 close(client->pack_pipe);
1916 if (client->packidx_fd != -1)
1917 close(client->packidx_fd);
1919 if (repo_write.repo)
1920 got_repo_close(repo_write.repo);
1921 got_repo_pack_fds_close(repo_write.pack_fds);
1922 got_repo_temp_fds_close(repo_write.temp_fds);
1923 if (repo_write.session_fd != -1)
1924 close(repo_write.session_fd);
1925 exit(0);