Blob


1 /*
2 * Copyright (c) 2019 Ori Bernstein <ori@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/types.h>
18 #include <sys/queue.h>
19 #include <sys/uio.h>
20 #include <sys/time.h>
21 #include <sys/stat.h>
22 #include <sys/syslimits.h>
24 #include <stdint.h>
25 #include <errno.h>
26 #include <imsg.h>
27 #include <limits.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <ctype.h>
33 #include <sha1.h>
34 #include <fcntl.h>
35 #include <unistd.h>
36 #include <zlib.h>
37 #include <err.h>
39 #include "got_error.h"
40 #include "got_object.h"
41 #include "got_path.h"
42 #include "got_version.h"
43 #include "got_fetch.h"
44 #include "got_reference.h"
46 #include "got_lib_sha1.h"
47 #include "got_lib_delta.h"
48 #include "got_lib_object.h"
49 #include "got_lib_object_parse.h"
50 #include "got_lib_privsep.h"
51 #include "got_lib_pack.h"
53 #ifndef nitems
54 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
55 #endif
57 struct got_object *indexed;
58 static int chattygot;
59 static struct got_object_id zhash = {.sha1={0}};
61 static const struct got_error *
62 readn(ssize_t *off, int fd, void *buf, size_t n)
63 {
64 ssize_t r;
66 *off = 0;
67 while (*off != n) {
68 r = read(fd, buf + *off, n - *off);
69 if (r == -1)
70 return got_error_from_errno("read");
71 if (r == 0)
72 return NULL;
73 *off += r;
74 }
75 return NULL;
76 }
78 static const struct got_error *
79 flushpkt(int fd)
80 {
81 ssize_t w;
83 if (chattygot > 1)
84 fprintf(stderr, "%s: writepkt: 0000\n", getprogname());
86 w = write(fd, "0000", 4);
87 if (w == -1)
88 return got_error_from_errno("write");
89 if (w != 4)
90 return got_error(GOT_ERR_IO);
91 return NULL;
92 }
94 /*
95 * Packet header contains a 4-byte hexstring which specifies the length
96 * of data which follows.
97 */
98 static const struct got_error *
99 read_pkthdr(int *datalen, int fd)
101 static const struct got_error *err = NULL;
102 char lenstr[5];
103 long len;
104 char *e;
105 int n, i;
106 ssize_t r;
108 *datalen = 0;
110 err = readn(&r, fd, lenstr, 4);
111 if (err)
112 return err;
113 if (r == 0) {
114 /* implicit "0000" */
115 if (chattygot > 1)
116 fprintf(stderr, "%s: readpkt: 0000\n", getprogname());
117 return NULL;
119 if (r != 4)
120 return got_error_msg(GOT_ERR_BAD_PACKET,
121 "wrong packet header length");
123 lenstr[4] = '\0';
124 for (i = 0; i < 4; i++) {
125 if (!isprint((unsigned char)lenstr[i]))
126 return got_error_msg(GOT_ERR_BAD_PACKET,
127 "unprintable character in packet length field");
129 for (i = 0; i < 4; i++) {
130 if (!isxdigit((unsigned char)lenstr[i])) {
131 if (chattygot)
132 fprintf(stderr, "%s: bad length: '%s'\n",
133 getprogname(), lenstr);
134 return got_error_msg(GOT_ERR_BAD_PACKET,
135 "packet length not specified in hex");
138 errno = 0;
139 len = strtol(lenstr, &e, 16);
140 if (lenstr[0] == '\0' || *e != '\0')
141 return got_error(GOT_ERR_BAD_PACKET);
142 if (errno == ERANGE && (len == LONG_MAX || len == LONG_MIN))
143 return got_error_msg(GOT_ERR_BAD_PACKET, "bad packet length");
144 if (len > INT_MAX || len < INT_MIN)
145 return got_error_msg(GOT_ERR_BAD_PACKET, "bad packet length");
146 n = len;
147 if (n == 0)
148 return NULL;
149 if (n <= 4)
150 return got_error_msg(GOT_ERR_BAD_PACKET, "packet too short");
151 n -= 4;
153 *datalen = n;
154 return NULL;
157 static const struct got_error *
158 readpkt(int *outlen, int fd, char *buf, int buflen)
160 const struct got_error *err = NULL;
161 int datalen, i;
162 ssize_t n;
164 err = read_pkthdr(&datalen, fd);
165 if (err)
166 return err;
168 if (datalen > buflen)
169 return got_error(GOT_ERR_NO_SPACE);
171 err = readn(&n, fd, buf, datalen);
172 if (err)
173 return err;
174 if (n != datalen)
175 return got_error_msg(GOT_ERR_BAD_PACKET, "short packet");
177 if (chattygot > 1) {
178 fprintf(stderr, "%s: readpkt: %zd:\t", getprogname(), n);
179 for (i = 0; i < n; i++) {
180 if (isprint(buf[i]))
181 fputc(buf[i], stderr);
182 else
183 fprintf(stderr, "[0x%.2x]", buf[i]);
185 fputc('\n', stderr);
188 *outlen = n;
189 return NULL;
192 static const struct got_error *
193 writepkt(int fd, char *buf, int nbuf)
195 char len[5];
196 int i;
197 ssize_t w;
199 if (snprintf(len, sizeof(len), "%04x", nbuf + 4) >= sizeof(len))
200 return got_error(GOT_ERR_NO_SPACE);
201 w = write(fd, len, 4);
202 if (w == -1)
203 return got_error_from_errno("write");
204 if (w != 4)
205 return got_error(GOT_ERR_IO);
206 w = write(fd, buf, nbuf);
207 if (w == -1)
208 return got_error_from_errno("write");
209 if (w != nbuf)
210 return got_error(GOT_ERR_IO);
211 if (chattygot > 1) {
212 fprintf(stderr, "%s: writepkt: %s:\t", getprogname(), len);
213 for (i = 0; i < nbuf; i++) {
214 if (isprint(buf[i]))
215 fputc(buf[i], stderr);
216 else
217 fprintf(stderr, "[0x%.2x]", buf[i]);
219 fputc('\n', stderr);
221 return NULL;
224 static void
225 match_remote_ref(struct got_pathlist_head *have_refs,
226 struct got_object_id *my_id, char *refname)
228 struct got_pathlist_entry *pe;
230 /* XXX zero-hash signifies we don't have this ref;
231 * we should use a flag instead */
232 memset(my_id, 0, sizeof(*my_id));
234 TAILQ_FOREACH(pe, have_refs, entry) {
235 struct got_object_id *id = pe->data;
236 if (strcmp(pe->path, refname) == 0) {
237 memcpy(my_id, id, sizeof(*my_id));
238 break;
243 static int
244 match_branch(const char *branch, const char *wanted_branch)
246 if (strncmp(branch, "refs/heads/", 11) != 0)
247 return 0;
249 if (strncmp(wanted_branch, "refs/heads/", 11) == 0)
250 wanted_branch += 11;
252 return (strcmp(branch + 11, wanted_branch) == 0);
255 static int
256 match_wanted_ref(const char *refname, const char *wanted_ref)
258 if (strncmp(refname, "refs/", 5) != 0)
259 return 0;
260 refname += 5;
262 /*
263 * Prevent fetching of references that won't make any
264 * sense outside of the remote repository's context.
265 */
266 if (strncmp(refname, "got/", 4) == 0)
267 return 0;
268 if (strncmp(refname, "remotes/", 8) == 0)
269 return 0;
271 if (strncmp(wanted_ref, "refs/", 5) == 0)
272 wanted_ref += 5;
274 /* Allow prefix match. */
275 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
276 return 1;
278 /* Allow exact match. */
279 return (strcmp(refname, wanted_ref) == 0);
282 static const struct got_error *
283 tokenize_refline(char **tokens, char *line, int len, int maxtokens)
285 const struct got_error *err = NULL;
286 char *p;
287 size_t i, n = 0;
289 for (i = 0; i < maxtokens; i++)
290 tokens[i] = NULL;
292 for (i = 0; n < len && i < maxtokens; i++) {
293 while (isspace(*line)) {
294 line++;
295 n++;
297 p = line;
298 while (*line != '\0' &&
299 (!isspace(*line) || i == maxtokens - 1)) {
300 line++;
301 n++;
303 tokens[i] = strndup(p, line - p);
304 if (tokens[i] == NULL) {
305 err = got_error_from_errno("strndup");
306 goto done;
308 /* Skip \0 field-delimiter at end of token. */
309 while (line[0] == '\0' && n < len) {
310 line++;
311 n++;
314 if (i <= 2)
315 err = got_error(GOT_ERR_NOT_REF);
316 done:
317 if (err) {
318 int j;
319 for (j = 0; j < i; j++) {
320 free(tokens[j]);
321 tokens[j] = NULL;
324 return err;
327 static const struct got_error *
328 parse_refline(char **id_str, char **refname, char **server_capabilities,
329 char *line, int len)
331 const struct got_error *err = NULL;
332 char *tokens[3];
334 err = tokenize_refline(tokens, line, len, nitems(tokens));
335 if (err)
336 return err;
338 if (tokens[0])
339 *id_str = tokens[0];
340 if (tokens[1])
341 *refname = tokens[1];
342 if (tokens[2]) {
343 char *p;
344 *server_capabilities = tokens[2];
345 p = strrchr(*server_capabilities, '\n');
346 if (p)
347 *p = '\0';
350 return NULL;
353 #define GOT_CAPA_AGENT "agent"
354 #define GOT_CAPA_OFS_DELTA "ofs-delta"
355 #define GOT_CAPA_SIDE_BAND_64K "side-band-64k"
357 #define GOT_SIDEBAND_PACKFILE_DATA 1
358 #define GOT_SIDEBAND_PROGRESS_INFO 2
359 #define GOT_SIDEBAND_ERROR_INFO 3
362 struct got_capability {
363 const char *key;
364 const char *value;
365 };
366 static const struct got_capability got_capabilities[] = {
367 { GOT_CAPA_AGENT, "got/" GOT_VERSION_STR },
368 { GOT_CAPA_OFS_DELTA, NULL },
369 { GOT_CAPA_SIDE_BAND_64K, NULL },
370 };
372 static const struct got_error *
373 match_capability(char **my_capabilities, const char *capa,
374 const struct got_capability *mycapa)
376 char *equalsign;
377 char *s;
379 equalsign = strchr(capa, '=');
380 if (equalsign) {
381 if (strncmp(capa, mycapa->key, equalsign - capa) != 0)
382 return NULL;
383 } else {
384 if (strcmp(capa, mycapa->key) != 0)
385 return NULL;
388 if (asprintf(&s, "%s %s%s%s",
389 *my_capabilities != NULL ? *my_capabilities : "",
390 mycapa->key,
391 mycapa->value != NULL ? "=" : "",
392 mycapa->value != NULL? mycapa->value : "") == -1)
393 return got_error_from_errno("asprintf");
395 free(*my_capabilities);
396 *my_capabilities = s;
397 return NULL;
400 static const struct got_error *
401 add_symref(struct got_pathlist_head *symrefs, char *capa)
403 const struct got_error *err = NULL;
404 char *colon, *name = NULL, *target = NULL;
406 /* Need at least "A:B" */
407 if (strlen(capa) < 3)
408 return NULL;
410 colon = strchr(capa, ':');
411 if (colon == NULL)
412 return NULL;
414 *colon = '\0';
415 name = strdup(capa);
416 if (name == NULL)
417 return got_error_from_errno("strdup");
419 target = strdup(colon + 1);
420 if (target == NULL) {
421 err = got_error_from_errno("strdup");
422 goto done;
425 /* We can't validate the ref itself here. The main process will. */
426 err = got_pathlist_append(symrefs, name, target);
427 done:
428 if (err) {
429 free(name);
430 free(target);
432 return err;
435 static const struct got_error *
436 match_capabilities(char **my_capabilities, struct got_pathlist_head *symrefs,
437 char *server_capabilities)
439 const struct got_error *err = NULL;
440 char *capa, *equalsign;
441 int i;
443 *my_capabilities = NULL;
444 do {
445 capa = strsep(&server_capabilities, " ");
446 if (capa == NULL)
447 return NULL;
449 equalsign = strchr(capa, '=');
450 if (equalsign != NULL &&
451 strncmp(capa, "symref", equalsign - capa) == 0) {
452 err = add_symref(symrefs, equalsign + 1);
453 if (err)
454 break;
455 continue;
458 for (i = 0; i < nitems(got_capabilities); i++) {
459 err = match_capability(my_capabilities,
460 capa, &got_capabilities[i]);
461 if (err)
462 break;
464 } while (capa);
466 if (*my_capabilities == NULL) {
467 *my_capabilities = strdup("");
468 if (*my_capabilities == NULL)
469 err = got_error_from_errno("strdup");
471 return err;
474 static const struct got_error *
475 send_fetch_server_progress(struct imsgbuf *ibuf, const char *msg, size_t msglen)
477 if (msglen > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
478 return got_error(GOT_ERR_NO_SPACE);
480 if (msglen == 0)
481 return NULL;
483 if (imsg_compose(ibuf, GOT_IMSG_FETCH_SERVER_PROGRESS, 0, 0, -1,
484 msg, msglen) == -1)
485 return got_error_from_errno(
486 "imsg_compose FETCH_SERVER_PROGRESS");
488 return got_privsep_flush_imsg(ibuf);
491 static const struct got_error *
492 send_fetch_download_progress(struct imsgbuf *ibuf, off_t bytes)
494 if (imsg_compose(ibuf, GOT_IMSG_FETCH_DOWNLOAD_PROGRESS, 0, 0, -1,
495 &bytes, sizeof(bytes)) == -1)
496 return got_error_from_errno(
497 "imsg_compose FETCH_DOWNLOAD_PROGRESS");
499 return got_privsep_flush_imsg(ibuf);
502 static const struct got_error *
503 send_fetch_done(struct imsgbuf *ibuf, uint8_t *pack_sha1)
505 if (imsg_compose(ibuf, GOT_IMSG_FETCH_DONE, 0, 0, -1,
506 pack_sha1, SHA1_DIGEST_LENGTH) == -1)
507 return got_error_from_errno("imsg_compose FETCH");
508 return got_privsep_flush_imsg(ibuf);
513 static const struct got_error *
514 fetch_progress(struct imsgbuf *ibuf, const char *buf, size_t len)
516 int i;
518 if (len == 0)
519 return NULL;
521 /*
522 * Truncate messages which exceed the maximum imsg payload size.
523 * Server may send up to 64k.
524 */
525 if (len > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
526 len = MAX_IMSGSIZE - IMSG_HEADER_SIZE;
528 /* Only allow printable ASCII. */
529 for (i = 0; i < len; i++) {
530 if (isprint((unsigned char)buf[i]) ||
531 isspace((unsigned char)buf[i]))
532 continue;
533 return got_error_msg(GOT_ERR_BAD_PACKET,
534 "non-printable progress message received from server");
537 return send_fetch_server_progress(ibuf, buf, len);
540 static const struct got_error *
541 fetch_error(const char *buf, size_t len)
543 static char msg[1024];
544 int i;
546 for (i = 0; i < len && i < sizeof(msg) - 1; i++) {
547 if (!isprint(buf[i]))
548 return got_error_msg(GOT_ERR_BAD_PACKET,
549 "non-printable error message received from server");
550 msg[i] = buf[i];
552 msg[i] = '\0';
553 return got_error_msg(GOT_ERR_FETCH_FAILED, msg);
556 static const struct got_error *
557 send_fetch_symrefs(struct imsgbuf *ibuf, struct got_pathlist_head *symrefs)
559 const struct got_error *err = NULL;
560 struct ibuf *wbuf;
561 size_t len, nsymrefs = 0;
562 struct got_pathlist_entry *pe;
564 len = sizeof(struct got_imsg_fetch_symrefs);
565 TAILQ_FOREACH(pe, symrefs, entry) {
566 const char *target = pe->data;
567 len += sizeof(struct got_imsg_fetch_symref) +
568 pe->path_len + strlen(target);
569 nsymrefs++;
572 if (len >= MAX_IMSGSIZE - IMSG_HEADER_SIZE)
573 return got_error(GOT_ERR_NO_SPACE);
575 wbuf = imsg_create(ibuf, GOT_IMSG_FETCH_SYMREFS, 0, 0, len);
576 if (wbuf == NULL)
577 return got_error_from_errno("imsg_create FETCH_SYMREFS");
579 /* Keep in sync with struct got_imsg_fetch_symrefs definition! */
580 if (imsg_add(wbuf, &nsymrefs, sizeof(nsymrefs)) == -1) {
581 err = got_error_from_errno("imsg_add FETCH_SYMREFS");
582 ibuf_free(wbuf);
583 return err;
586 TAILQ_FOREACH(pe, symrefs, entry) {
587 const char *name = pe->path;
588 size_t name_len = pe->path_len;
589 const char *target = pe->data;
590 size_t target_len = strlen(target);
592 /* Keep in sync with struct got_imsg_fetch_symref definition! */
593 if (imsg_add(wbuf, &name_len, sizeof(name_len)) == -1) {
594 err = got_error_from_errno("imsg_add FETCH_SYMREFS");
595 ibuf_free(wbuf);
596 return err;
598 if (imsg_add(wbuf, &target_len, sizeof(target_len)) == -1) {
599 err = got_error_from_errno("imsg_add FETCH_SYMREFS");
600 ibuf_free(wbuf);
601 return err;
603 if (imsg_add(wbuf, name, name_len) == -1) {
604 err = got_error_from_errno("imsg_add FETCH_SYMREFS");
605 ibuf_free(wbuf);
606 return err;
608 if (imsg_add(wbuf, target, target_len) == -1) {
609 err = got_error_from_errno("imsg_add FETCH_SYMREFS");
610 ibuf_free(wbuf);
611 return err;
615 wbuf->fd = -1;
616 imsg_close(ibuf, wbuf);
617 return got_privsep_flush_imsg(ibuf);
620 static const struct got_error *
621 send_fetch_ref(struct imsgbuf *ibuf, struct got_object_id *refid,
622 const char *refname)
624 const struct got_error *err = NULL;
625 struct ibuf *wbuf;
626 size_t len, reflen = strlen(refname);
628 len = sizeof(struct got_imsg_fetch_ref) + reflen;
629 if (len >= MAX_IMSGSIZE - IMSG_HEADER_SIZE)
630 return got_error(GOT_ERR_NO_SPACE);
632 wbuf = imsg_create(ibuf, GOT_IMSG_FETCH_REF, 0, 0, len);
633 if (wbuf == NULL)
634 return got_error_from_errno("imsg_create FETCH_REF");
636 /* Keep in sync with struct got_imsg_fetch_ref definition! */
637 if (imsg_add(wbuf, refid->sha1, SHA1_DIGEST_LENGTH) == -1) {
638 err = got_error_from_errno("imsg_add FETCH_REF");
639 ibuf_free(wbuf);
640 return err;
642 if (imsg_add(wbuf, refname, reflen) == -1) {
643 err = got_error_from_errno("imsg_add FETCH_REF");
644 ibuf_free(wbuf);
645 return err;
648 wbuf->fd = -1;
649 imsg_close(ibuf, wbuf);
650 return got_privsep_flush_imsg(ibuf);
653 static const struct got_error *
654 fetch_pack(int fd, int packfd, uint8_t *pack_sha1,
655 struct got_pathlist_head *have_refs, int fetch_all_branches,
656 struct got_pathlist_head *wanted_branches,
657 struct got_pathlist_head *wanted_refs, int list_refs_only,
658 struct imsgbuf *ibuf)
660 const struct got_error *err = NULL;
661 char buf[GOT_FETCH_PKTMAX];
662 char hashstr[SHA1_DIGEST_STRING_LENGTH];
663 struct got_object_id *have, *want;
664 int is_firstpkt = 1, nref = 0, refsz = 16;
665 int i, n, nwant = 0, nhave = 0, acked = 0;
666 off_t packsz = 0, last_reported_packsz = 0;
667 char *id_str = NULL, *refname = NULL;
668 char *server_capabilities = NULL, *my_capabilities = NULL;
669 const char *default_branch = NULL;
670 struct got_pathlist_head symrefs;
671 struct got_pathlist_entry *pe;
672 int sent_my_capabilites = 0, have_sidebands = 0;
673 int found_branch = 0;
674 SHA1_CTX sha1_ctx;
675 uint8_t sha1_buf[SHA1_DIGEST_LENGTH];
676 size_t sha1_buf_len = 0;
677 ssize_t w;
679 TAILQ_INIT(&symrefs);
680 SHA1Init(&sha1_ctx);
682 have = malloc(refsz * sizeof(have[0]));
683 if (have == NULL)
684 return got_error_from_errno("malloc");
685 want = malloc(refsz * sizeof(want[0]));
686 if (want == NULL) {
687 err = got_error_from_errno("malloc");
688 goto done;
690 while (1) {
691 err = readpkt(&n, fd, buf, sizeof(buf));
692 if (err)
693 goto done;
694 if (n == 0)
695 break;
696 if (n >= 4 && strncmp(buf, "ERR ", 4) == 0) {
697 err = fetch_error(&buf[4], n - 4);
698 goto done;
700 err = parse_refline(&id_str, &refname, &server_capabilities,
701 buf, n);
702 if (err)
703 goto done;
704 if (is_firstpkt) {
705 if (chattygot && server_capabilities[0] != '\0')
706 fprintf(stderr, "%s: server capabilities: %s\n",
707 getprogname(), server_capabilities);
708 err = match_capabilities(&my_capabilities, &symrefs,
709 server_capabilities);
710 if (err)
711 goto done;
712 if (chattygot)
713 fprintf(stderr, "%s: my capabilities:%s\n",
714 getprogname(), my_capabilities);
715 err = send_fetch_symrefs(ibuf, &symrefs);
716 if (err)
717 goto done;
718 is_firstpkt = 0;
719 if (!fetch_all_branches) {
720 TAILQ_FOREACH(pe, &symrefs, entry) {
721 const char *name = pe->path;
722 const char *symref_target = pe->data;
723 if (strcmp(name, GOT_REF_HEAD) != 0)
724 continue;
725 default_branch = symref_target;
726 break;
729 continue;
731 if (strstr(refname, "^{}")) {
732 if (chattygot) {
733 fprintf(stderr, "%s: ignoring %s\n",
734 getprogname(), refname);
736 continue;
739 if (strncmp(refname, "refs/heads/", 11) == 0) {
740 if (fetch_all_branches || list_refs_only) {
741 found_branch = 1;
742 } else if (!TAILQ_EMPTY(wanted_branches)) {
743 TAILQ_FOREACH(pe, wanted_branches, entry) {
744 if (match_branch(refname, pe->path))
745 break;
747 if (pe == NULL) {
748 if (chattygot) {
749 fprintf(stderr,
750 "%s: ignoring %s\n",
751 getprogname(), refname);
753 continue;
755 found_branch = 1;
756 } else if (default_branch != NULL) {
757 if (!match_branch(refname, default_branch)) {
758 if (chattygot) {
759 fprintf(stderr,
760 "%s: ignoring %s\n",
761 getprogname(), refname);
763 continue;
765 found_branch = 1;
767 } else if (strncmp(refname, "refs/tags/", 10) != 0) {
768 if (!TAILQ_EMPTY(wanted_refs)) {
769 TAILQ_FOREACH(pe, wanted_refs, entry) {
770 if (match_wanted_ref(refname, pe->path))
771 break;
773 if (pe == NULL) {
774 if (chattygot) {
775 fprintf(stderr,
776 "%s: ignoring %s\n",
777 getprogname(), refname);
779 continue;
781 found_branch = 1;
782 } else if (!list_refs_only) {
783 if (chattygot) {
784 fprintf(stderr, "%s: ignoring %s\n",
785 getprogname(), refname);
787 continue;
791 if (refsz == nref + 1) {
792 refsz *= 2;
793 have = reallocarray(have, refsz, sizeof(have[0]));
794 if (have == NULL) {
795 err = got_error_from_errno("reallocarray");
796 goto done;
798 want = reallocarray(want, refsz, sizeof(want[0]));
799 if (want == NULL) {
800 err = got_error_from_errno("reallocarray");
801 goto done;
804 if (!got_parse_sha1_digest(want[nref].sha1, id_str)) {
805 err = got_error(GOT_ERR_BAD_OBJ_ID_STR);
806 goto done;
808 match_remote_ref(have_refs, &have[nref], refname);
809 err = send_fetch_ref(ibuf, &want[nref], refname);
810 if (err)
811 goto done;
813 if (chattygot)
814 fprintf(stderr, "%s: %s will be fetched\n",
815 getprogname(), refname);
816 if (chattygot > 1) {
817 char *theirs, *mine;
818 err = got_object_id_str(&theirs, &want[nref]);
819 if (err)
820 goto done;
821 err = got_object_id_str(&mine, &have[nref]);
822 if (err) {
823 free(theirs);
824 goto done;
826 fprintf(stderr, "%s: remote: %s\n%s: local: %s\n",
827 getprogname(), theirs, getprogname(), mine);
828 free(theirs);
829 free(mine);
831 nref++;
834 if (list_refs_only)
835 goto done;
837 /* Abort if we haven't found any branch to fetch. */
838 if (!found_branch) {
839 err = got_error(GOT_ERR_FETCH_NO_BRANCH);
840 goto done;
843 for (i = 0; i < nref; i++) {
844 if (got_object_id_cmp(&have[i], &want[i]) == 0)
845 continue;
846 got_sha1_digest_to_str(want[i].sha1, hashstr, sizeof(hashstr));
847 n = snprintf(buf, sizeof(buf), "want %s%s\n", hashstr,
848 sent_my_capabilites ? "" : my_capabilities);
849 if (n >= sizeof(buf)) {
850 err = got_error(GOT_ERR_NO_SPACE);
851 goto done;
853 err = writepkt(fd, buf, n);
854 if (err)
855 goto done;
856 sent_my_capabilites = 1;
857 nwant++;
859 err = flushpkt(fd);
860 if (err)
861 goto done;
863 if (nwant == 0)
864 goto done;
866 for (i = 0; i < nref; i++) {
867 if (got_object_id_cmp(&have[i], &zhash) == 0)
868 continue;
869 got_sha1_digest_to_str(have[i].sha1, hashstr, sizeof(hashstr));
870 n = snprintf(buf, sizeof(buf), "have %s\n", hashstr);
871 if (n >= sizeof(buf)) {
872 err = got_error(GOT_ERR_NO_SPACE);
873 goto done;
875 err = writepkt(fd, buf, n);
876 if (err)
877 goto done;
878 nhave++;
881 while (nhave > 0 && !acked) {
882 struct got_object_id common_id;
884 /* The server should ACK the object IDs we need. */
885 err = readpkt(&n, fd, buf, sizeof(buf));
886 if (err)
887 goto done;
888 if (n >= 4 && strncmp(buf, "ERR ", 4) == 0) {
889 err = fetch_error(&buf[4], n - 4);
890 goto done;
892 if (n >= 4 && strncmp(buf, "NAK\n", 4) == 0) {
893 /* Server has not located our objects yet. */
894 continue;
896 if (n < 4 + SHA1_DIGEST_STRING_LENGTH ||
897 strncmp(buf, "ACK ", 4) != 0) {
898 err = got_error_msg(GOT_ERR_BAD_PACKET,
899 "unexpected message from server");
900 goto done;
902 if (!got_parse_sha1_digest(common_id.sha1, buf + 4)) {
903 err = got_error_msg(GOT_ERR_BAD_PACKET,
904 "bad object ID in ACK packet from server");
905 goto done;
907 acked++;
910 n = snprintf(buf, sizeof(buf), "done\n");
911 err = writepkt(fd, buf, n);
912 if (err)
913 goto done;
915 if (nhave == 0) {
916 err = readpkt(&n, fd, buf, sizeof(buf));
917 if (err)
918 goto done;
919 if (n != 4 || strncmp(buf, "NAK\n", n) != 0) {
920 err = got_error_msg(GOT_ERR_BAD_PACKET,
921 "unexpected message from server");
922 goto done;
926 if (chattygot)
927 fprintf(stderr, "%s: fetching...\n", getprogname());
929 if (my_capabilities != NULL &&
930 strstr(my_capabilities, GOT_CAPA_SIDE_BAND_64K) != NULL)
931 have_sidebands = 1;
933 while (1) {
934 ssize_t r = 0;
935 int datalen = -1;
937 if (have_sidebands) {
938 err = read_pkthdr(&datalen, fd);
939 if (err)
940 goto done;
941 if (datalen <= 0)
942 break;
944 /* Read sideband channel ID (one byte). */
945 r = read(fd, buf, 1);
946 if (r == -1) {
947 err = got_error_from_errno("read");
948 goto done;
950 if (r != 1) {
951 err = got_error_msg(GOT_ERR_BAD_PACKET,
952 "short packet");
953 goto done;
955 if (datalen > sizeof(buf) - 5) {
956 err = got_error_msg(GOT_ERR_BAD_PACKET,
957 "bad packet length");
958 goto done;
960 datalen--; /* sideband ID has been read */
961 if (buf[0] == GOT_SIDEBAND_PACKFILE_DATA) {
962 /* Read packfile data. */
963 err = readn(&r, fd, buf, datalen);
964 if (err)
965 goto done;
966 if (r != datalen) {
967 err = got_error_msg(GOT_ERR_BAD_PACKET,
968 "packet too short");
969 goto done;
971 } else if (buf[0] == GOT_SIDEBAND_PROGRESS_INFO) {
972 err = readn(&r, fd, buf, datalen);
973 if (err)
974 goto done;
975 if (r != datalen) {
976 err = got_error_msg(GOT_ERR_BAD_PACKET,
977 "packet too short");
978 goto done;
980 err = fetch_progress(ibuf, buf, r);
981 if (err)
982 goto done;
983 continue;
984 } else if (buf[0] == GOT_SIDEBAND_ERROR_INFO) {
985 err = readn(&r, fd, buf, datalen);
986 if (err)
987 goto done;
988 if (r != datalen) {
989 err = got_error_msg(GOT_ERR_BAD_PACKET,
990 "packet too short");
991 goto done;
993 err = fetch_error(buf, r);
994 goto done;
995 } else {
996 err = got_error_msg(GOT_ERR_BAD_PACKET,
997 "unknown side-band received from server");
998 goto done;
1000 } else {
1001 /* No sideband channel. Every byte is packfile data. */
1002 err = readn(&r, fd, buf, sizeof buf);
1003 if (err)
1004 goto done;
1005 if (r <= 0)
1006 break;
1010 * An expected SHA1 checksum sits at the end of the pack file.
1011 * Since we don't know the file size ahead of time we have to
1012 * keep SHA1_DIGEST_LENGTH bytes buffered and avoid mixing
1013 * those bytes into our SHA1 checksum computation until we
1014 * know for sure that additional pack file data bytes follow.
1016 * We can assume r > 0 since otherwise the loop would exit.
1018 if (r < SHA1_DIGEST_LENGTH) {
1019 if (sha1_buf_len < SHA1_DIGEST_LENGTH) {
1021 * If there's enough buffered + read data to
1022 * fill up the buffer then shift a sufficient
1023 * amount of bytes out at the front to make
1024 * room, mixing those bytes into the checksum.
1026 while (sha1_buf_len > 0 &&
1027 sha1_buf_len + r > SHA1_DIGEST_LENGTH) {
1028 SHA1Update(&sha1_ctx, sha1_buf, 1);
1029 memmove(sha1_buf, sha1_buf + 1, 1);
1030 sha1_buf_len--;
1033 /* Buffer potential checksum bytes. */
1034 memcpy(sha1_buf + sha1_buf_len, buf, r);
1035 sha1_buf_len += r;
1036 } else {
1038 * Mix in previously buffered bytes which
1039 * are not part of the checksum after all.
1041 SHA1Update(&sha1_ctx, sha1_buf, r);
1043 /* Update potential checksum buffer. */
1044 memmove(sha1_buf, sha1_buf + r,
1045 sha1_buf_len - r);
1046 memcpy(sha1_buf + sha1_buf_len - r, buf, r);
1048 } else {
1049 /* Mix in any previously buffered bytes. */
1050 SHA1Update(&sha1_ctx, sha1_buf, sha1_buf_len);
1052 /* Mix in bytes read minus potential checksum bytes. */
1053 SHA1Update(&sha1_ctx, buf, r - SHA1_DIGEST_LENGTH);
1055 /* Buffer potential checksum bytes. */
1056 memcpy(sha1_buf, buf + r - SHA1_DIGEST_LENGTH,
1057 SHA1_DIGEST_LENGTH);
1058 sha1_buf_len = SHA1_DIGEST_LENGTH;
1061 /* Write packfile data to temporary pack file. */
1062 w = write(packfd, buf, r);
1063 if (w == -1) {
1064 err = got_error_from_errno("write");
1065 goto done;
1067 if (w != r) {
1068 err = got_error(GOT_ERR_IO);
1069 goto done;
1071 packsz += w;
1073 /* Don't send too many progress privsep messages. */
1074 if (packsz > last_reported_packsz + 1024) {
1075 err = send_fetch_download_progress(ibuf, packsz);
1076 if (err)
1077 goto done;
1078 last_reported_packsz = packsz;
1081 err = send_fetch_download_progress(ibuf, packsz);
1082 if (err)
1083 goto done;
1085 SHA1Final(pack_sha1, &sha1_ctx);
1086 if (sha1_buf_len != SHA1_DIGEST_LENGTH ||
1087 memcmp(pack_sha1, sha1_buf, sha1_buf_len) != 0) {
1088 err = got_error_msg(GOT_ERR_BAD_PACKFILE,
1089 "pack file checksum mismatch");
1091 done:
1092 TAILQ_FOREACH(pe, &symrefs, entry) {
1093 free((void *)pe->path);
1094 free(pe->data);
1096 got_pathlist_free(&symrefs);
1097 free(have);
1098 free(want);
1099 free(id_str);
1100 free(refname);
1101 free(server_capabilities);
1102 return err;
1106 int
1107 main(int argc, char **argv)
1109 const struct got_error *err = NULL;
1110 int fetchfd, packfd = -1, i;
1111 uint8_t pack_sha1[SHA1_DIGEST_LENGTH];
1112 struct imsgbuf ibuf;
1113 struct imsg imsg;
1114 struct got_pathlist_head have_refs;
1115 struct got_pathlist_head wanted_branches;
1116 struct got_pathlist_head wanted_refs;
1117 struct got_pathlist_entry *pe;
1118 struct got_imsg_fetch_request fetch_req;
1119 struct got_imsg_fetch_have_ref href;
1120 struct got_imsg_fetch_wanted_branch wbranch;
1121 struct got_imsg_fetch_wanted_ref wref;
1122 size_t datalen;
1123 #if 0
1124 static int attached;
1125 while (!attached)
1126 sleep (1);
1127 #endif
1129 TAILQ_INIT(&have_refs);
1130 TAILQ_INIT(&wanted_branches);
1131 TAILQ_INIT(&wanted_refs);
1133 imsg_init(&ibuf, GOT_IMSG_FD_CHILD);
1134 #ifndef PROFILE
1135 /* revoke access to most system calls */
1136 if (pledge("stdio recvfd", NULL) == -1) {
1137 err = got_error_from_errno("pledge");
1138 got_privsep_send_error(&ibuf, err);
1139 return 1;
1141 #endif
1142 if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
1143 if (err->code == GOT_ERR_PRIVSEP_PIPE)
1144 err = NULL;
1145 goto done;
1147 if (imsg.hdr.type == GOT_IMSG_STOP)
1148 goto done;
1149 if (imsg.hdr.type != GOT_IMSG_FETCH_REQUEST) {
1150 err = got_error(GOT_ERR_PRIVSEP_MSG);
1151 goto done;
1153 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
1154 if (datalen < sizeof(fetch_req)) {
1155 err = got_error(GOT_ERR_PRIVSEP_LEN);
1156 goto done;
1158 memcpy(&fetch_req, imsg.data, sizeof(fetch_req));
1159 fetchfd = imsg.fd;
1160 imsg_free(&imsg);
1162 if (fetch_req.verbosity > 0)
1163 chattygot += fetch_req.verbosity;
1165 for (i = 0; i < fetch_req.n_have_refs; i++) {
1166 struct got_object_id *id;
1167 char *refname;
1169 if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
1170 if (err->code == GOT_ERR_PRIVSEP_PIPE)
1171 err = NULL;
1172 goto done;
1174 if (imsg.hdr.type == GOT_IMSG_STOP)
1175 goto done;
1176 if (imsg.hdr.type != GOT_IMSG_FETCH_HAVE_REF) {
1177 err = got_error(GOT_ERR_PRIVSEP_MSG);
1178 goto done;
1180 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
1181 if (datalen < sizeof(href)) {
1182 err = got_error(GOT_ERR_PRIVSEP_LEN);
1183 goto done;
1185 memcpy(&href, imsg.data, sizeof(href));
1186 if (datalen - sizeof(href) < href.name_len) {
1187 err = got_error(GOT_ERR_PRIVSEP_LEN);
1188 goto done;
1190 refname = malloc(href.name_len + 1);
1191 if (refname == NULL) {
1192 err = got_error_from_errno("malloc");
1193 goto done;
1195 memcpy(refname, imsg.data + sizeof(href), href.name_len);
1196 refname[href.name_len] = '\0';
1198 id = malloc(sizeof(*id));
1199 if (id == NULL) {
1200 free(refname);
1201 err = got_error_from_errno("malloc");
1202 goto done;
1204 memcpy(id->sha1, href.id, SHA1_DIGEST_LENGTH);
1205 err = got_pathlist_append(&have_refs, refname, id);
1206 if (err) {
1207 free(refname);
1208 free(id);
1209 goto done;
1212 imsg_free(&imsg);
1215 for (i = 0; i < fetch_req.n_wanted_branches; i++) {
1216 char *refname;
1218 if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
1219 if (err->code == GOT_ERR_PRIVSEP_PIPE)
1220 err = NULL;
1221 goto done;
1223 if (imsg.hdr.type == GOT_IMSG_STOP)
1224 goto done;
1225 if (imsg.hdr.type != GOT_IMSG_FETCH_WANTED_BRANCH) {
1226 err = got_error(GOT_ERR_PRIVSEP_MSG);
1227 goto done;
1229 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
1230 if (datalen < sizeof(wbranch)) {
1231 err = got_error(GOT_ERR_PRIVSEP_LEN);
1232 goto done;
1234 memcpy(&wbranch, imsg.data, sizeof(wbranch));
1235 if (datalen - sizeof(wbranch) < wbranch.name_len) {
1236 err = got_error(GOT_ERR_PRIVSEP_LEN);
1237 goto done;
1239 refname = malloc(wbranch.name_len + 1);
1240 if (refname == NULL) {
1241 err = got_error_from_errno("malloc");
1242 goto done;
1244 memcpy(refname, imsg.data + sizeof(wbranch), wbranch.name_len);
1245 refname[wbranch.name_len] = '\0';
1247 err = got_pathlist_append(&wanted_branches, refname, NULL);
1248 if (err) {
1249 free(refname);
1250 goto done;
1253 imsg_free(&imsg);
1256 for (i = 0; i < fetch_req.n_wanted_refs; i++) {
1257 char *refname;
1259 if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
1260 if (err->code == GOT_ERR_PRIVSEP_PIPE)
1261 err = NULL;
1262 goto done;
1264 if (imsg.hdr.type == GOT_IMSG_STOP)
1265 goto done;
1266 if (imsg.hdr.type != GOT_IMSG_FETCH_WANTED_REF) {
1267 err = got_error(GOT_ERR_PRIVSEP_MSG);
1268 goto done;
1270 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
1271 if (datalen < sizeof(wref)) {
1272 err = got_error(GOT_ERR_PRIVSEP_LEN);
1273 goto done;
1275 memcpy(&wref, imsg.data, sizeof(wref));
1276 if (datalen - sizeof(wref) < wref.name_len) {
1277 err = got_error(GOT_ERR_PRIVSEP_LEN);
1278 goto done;
1280 refname = malloc(wref.name_len + 1);
1281 if (refname == NULL) {
1282 err = got_error_from_errno("malloc");
1283 goto done;
1285 memcpy(refname, imsg.data + sizeof(wref), wref.name_len);
1286 refname[wref.name_len] = '\0';
1288 err = got_pathlist_append(&wanted_refs, refname, NULL);
1289 if (err) {
1290 free(refname);
1291 goto done;
1294 imsg_free(&imsg);
1297 if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
1298 if (err->code == GOT_ERR_PRIVSEP_PIPE)
1299 err = NULL;
1300 goto done;
1302 if (imsg.hdr.type == GOT_IMSG_STOP)
1303 goto done;
1304 if (imsg.hdr.type != GOT_IMSG_FETCH_OUTFD) {
1305 err = got_error(GOT_ERR_PRIVSEP_MSG);
1306 goto done;
1308 if (imsg.hdr.len - IMSG_HEADER_SIZE != 0) {
1309 err = got_error(GOT_ERR_PRIVSEP_LEN);
1310 goto done;
1312 packfd = imsg.fd;
1314 err = fetch_pack(fetchfd, packfd, pack_sha1, &have_refs,
1315 fetch_req.fetch_all_branches, &wanted_branches,
1316 &wanted_refs, fetch_req.list_refs_only, &ibuf);
1317 done:
1318 TAILQ_FOREACH(pe, &have_refs, entry) {
1319 free((char *)pe->path);
1320 free(pe->data);
1322 got_pathlist_free(&have_refs);
1323 TAILQ_FOREACH(pe, &wanted_branches, entry)
1324 free((char *)pe->path);
1325 got_pathlist_free(&wanted_branches);
1326 if (fetchfd != -1 && close(fetchfd) == -1 && err == NULL)
1327 err = got_error_from_errno("close");
1328 if (packfd != -1 && close(packfd) == -1 && err == NULL)
1329 err = got_error_from_errno("close");
1330 if (err != NULL)
1331 got_privsep_send_error(&ibuf, err);
1332 else
1333 err = send_fetch_done(&ibuf, pack_sha1);
1334 if (err != NULL) {
1335 fprintf(stderr, "%s: %s\n", getprogname(), err->msg);
1336 got_privsep_send_error(&ibuf, err);
1339 exit(0);