4 #include "run-command.h"
10 #include "string-list.h"
11 #include "thread-utils.h"
13 #include "argv-array.h"
19 struct child_process *helper;
29 no_disconnect_req : 1;
32 /* These go from remote name (as in "list") to private name */
33 struct refspec *refspecs;
35 /* Transport options for fetch-pack/send-pack (should one of
38 struct git_transport_options transport_options;
41 static void sendline(struct helper_data *helper, struct strbuf *buffer)
44 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
45 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
47 die_errno("Full write to remote helper failed");
50 static int recvline_fh(FILE *helper, struct strbuf *buffer)
54 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
55 if (strbuf_getline(buffer, helper, '\n') == EOF) {
57 fprintf(stderr, "Debug: Remote helper quit.\n");
62 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
66 static int recvline(struct helper_data *helper, struct strbuf *buffer)
68 return recvline_fh(helper->out, buffer);
71 static void xchgline(struct helper_data *helper, struct strbuf *buffer)
73 sendline(helper, buffer);
74 recvline(helper, buffer);
77 static void write_constant(int fd, const char *str)
80 fprintf(stderr, "Debug: Remote helper: -> %s", str);
81 if (write_in_full(fd, str, strlen(str)) != strlen(str))
82 die_errno("Full write to remote helper failed");
85 static const char *remove_ext_force(const char *url)
88 const char *colon = strchr(url, ':');
89 if (colon && colon[1] == ':')
95 static void do_take_over(struct transport *transport)
97 struct helper_data *data;
98 data = (struct helper_data *)transport->data;
99 transport_take_over(transport, data->helper);
104 static struct child_process *get_helper(struct transport *transport)
106 struct helper_data *data = transport->data;
107 struct argv_array argv = ARGV_ARRAY_INIT;
108 struct strbuf buf = STRBUF_INIT;
109 struct child_process *helper;
110 const char **refspecs = NULL;
112 int refspec_alloc = 0;
115 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
116 const char *helper_env[] = {
125 helper = xcalloc(1, sizeof(*helper));
129 argv_array_pushf(&argv, "git-remote-%s", data->name);
130 argv_array_push(&argv, transport->remote->name);
131 argv_array_push(&argv, remove_ext_force(transport->url));
132 helper->argv = argv_array_detach(&argv, NULL);
134 helper->silent_exec_failure = 1;
136 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
137 helper->env = helper_env;
139 code = start_command(helper);
140 if (code < 0 && errno == ENOENT)
141 die("Unable to find remote helper for '%s'", data->name);
145 data->helper = helper;
146 data->no_disconnect_req = 0;
149 * Open the output as FILE* so strbuf_getline() can be used.
150 * Do this with duped fd because fclose() will close the fd,
151 * and stuff like taking over will require the fd to remain.
153 duped = dup(helper->out);
155 die_errno("Can't dup helper output fd");
156 data->out = xfdopen(duped, "r");
158 write_constant(helper->in, "capabilities\n");
163 recvline(data, &buf);
168 if (*buf.buf == '*') {
169 capname = buf.buf + 1;
175 fprintf(stderr, "Debug: Got cap %s\n", capname);
176 if (!strcmp(capname, "fetch"))
178 else if (!strcmp(capname, "option"))
180 else if (!strcmp(capname, "push"))
182 else if (!strcmp(capname, "import"))
184 else if (!strcmp(capname, "bidi-import"))
185 data->bidi_import = 1;
186 else if (!strcmp(capname, "export"))
188 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
192 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
193 } else if (!strcmp(capname, "connect")) {
195 } else if (!strcmp(capname, "signed-tags")) {
196 data->signed_tags = 1;
197 } else if (!prefixcmp(capname, "export-marks ")) {
198 struct strbuf arg = STRBUF_INIT;
199 strbuf_addstr(&arg, "--export-marks=");
200 strbuf_addstr(&arg, capname + strlen("export-marks "));
201 data->export_marks = strbuf_detach(&arg, NULL);
202 } else if (!prefixcmp(capname, "import-marks")) {
203 struct strbuf arg = STRBUF_INIT;
204 strbuf_addstr(&arg, "--import-marks=");
205 strbuf_addstr(&arg, capname + strlen("import-marks "));
206 data->import_marks = strbuf_detach(&arg, NULL);
207 } else if (mandatory) {
208 die("Unknown mandatory capability %s. This remote "
209 "helper probably needs newer version of Git.",
215 data->refspec_nr = refspec_nr;
216 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
217 for (i = 0; i < refspec_nr; i++) {
218 free((char *)refspecs[i]);
222 strbuf_release(&buf);
224 fprintf(stderr, "Debug: Capabilities complete.\n");
228 static int disconnect_helper(struct transport *transport)
230 struct helper_data *data = transport->data;
235 fprintf(stderr, "Debug: Disconnecting.\n");
236 if (!data->no_disconnect_req) {
238 * Ignore write errors; there's nothing we can do,
239 * since we're about to close the pipe anyway. And the
240 * most likely error is EPIPE due to the helper dying
241 * to report an error itself.
243 sigchain_push(SIGPIPE, SIG_IGN);
244 xwrite(data->helper->in, "\n", 1);
245 sigchain_pop(SIGPIPE);
247 close(data->helper->in);
248 close(data->helper->out);
250 res = finish_command(data->helper);
251 argv_array_free_detached(data->helper->argv);
258 static const char *unsupported_options[] = {
259 TRANS_OPT_UPLOADPACK,
260 TRANS_OPT_RECEIVEPACK,
264 static const char *boolean_options[] = {
270 static int set_helper_option(struct transport *transport,
271 const char *name, const char *value)
273 struct helper_data *data = transport->data;
274 struct strbuf buf = STRBUF_INIT;
275 int i, ret, is_bool = 0;
277 get_helper(transport);
282 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
283 if (!strcmp(name, unsupported_options[i]))
287 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
288 if (!strcmp(name, boolean_options[i])) {
294 strbuf_addf(&buf, "option %s ", name);
296 strbuf_addstr(&buf, value ? "true" : "false");
298 quote_c_style(value, &buf, NULL, 0);
299 strbuf_addch(&buf, '\n');
301 xchgline(data, &buf);
303 if (!strcmp(buf.buf, "ok"))
305 else if (!prefixcmp(buf.buf, "error")) {
307 } else if (!strcmp(buf.buf, "unsupported"))
310 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
313 strbuf_release(&buf);
317 static void standard_options(struct transport *t)
323 set_helper_option(t, "progress", t->progress ? "true" : "false");
325 n = snprintf(buf, sizeof(buf), "%d", v + 1);
326 if (n >= sizeof(buf))
327 die("impossibly large verbosity value");
328 set_helper_option(t, "verbosity", buf);
331 static int release_helper(struct transport *transport)
334 struct helper_data *data = transport->data;
335 free_refspec(data->refspec_nr, data->refspecs);
336 data->refspecs = NULL;
337 res = disconnect_helper(transport);
338 free(transport->data);
342 static int fetch_with_fetch(struct transport *transport,
343 int nr_heads, struct ref **to_fetch)
345 struct helper_data *data = transport->data;
347 struct strbuf buf = STRBUF_INIT;
349 standard_options(transport);
351 for (i = 0; i < nr_heads; i++) {
352 const struct ref *posn = to_fetch[i];
353 if (posn->status & REF_STATUS_UPTODATE)
356 strbuf_addf(&buf, "fetch %s %s\n",
357 sha1_to_hex(posn->old_sha1), posn->name);
360 strbuf_addch(&buf, '\n');
361 sendline(data, &buf);
364 recvline(data, &buf);
366 if (!prefixcmp(buf.buf, "lock ")) {
367 const char *name = buf.buf + 5;
368 if (transport->pack_lockfile)
369 warning("%s also locked %s", data->name, name);
371 transport->pack_lockfile = xstrdup(name);
376 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
378 strbuf_release(&buf);
382 static int get_importer(struct transport *transport, struct child_process *fastimport)
384 struct child_process *helper = get_helper(transport);
385 struct helper_data *data = transport->data;
386 struct argv_array argv = ARGV_ARRAY_INIT;
387 int cat_blob_fd, code;
388 memset(fastimport, 0, sizeof(*fastimport));
389 fastimport->in = helper->out;
390 argv_array_push(&argv, "fast-import");
391 argv_array_push(&argv, debug ? "--stats" : "--quiet");
393 if (data->bidi_import) {
394 cat_blob_fd = xdup(helper->in);
395 argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
397 fastimport->argv = argv.argv;
398 fastimport->git_cmd = 1;
400 code = start_command(fastimport);
404 static int get_exporter(struct transport *transport,
405 struct child_process *fastexport,
406 struct string_list *revlist_args)
408 struct helper_data *data = transport->data;
409 struct child_process *helper = get_helper(transport);
411 memset(fastexport, 0, sizeof(*fastexport));
413 /* we need to duplicate helper->in because we want to use it after
414 * fastexport is done with it. */
415 fastexport->out = dup(helper->in);
416 fastexport->argv = xcalloc(6 + revlist_args->nr, sizeof(*fastexport->argv));
417 fastexport->argv[argc++] = "fast-export";
418 fastexport->argv[argc++] = "--use-done-feature";
419 fastexport->argv[argc++] = data->signed_tags ?
420 "--signed-tags=verbatim" : "--signed-tags=warn-strip";
421 if (data->export_marks)
422 fastexport->argv[argc++] = data->export_marks;
423 if (data->import_marks)
424 fastexport->argv[argc++] = data->import_marks;
426 for (i = 0; i < revlist_args->nr; i++)
427 fastexport->argv[argc++] = revlist_args->items[i].string;
429 fastexport->git_cmd = 1;
430 return start_command(fastexport);
433 static int fetch_with_import(struct transport *transport,
434 int nr_heads, struct ref **to_fetch)
436 struct child_process fastimport;
437 struct helper_data *data = transport->data;
440 struct strbuf buf = STRBUF_INIT;
442 get_helper(transport);
444 if (get_importer(transport, &fastimport))
445 die("Couldn't run fast-import");
447 for (i = 0; i < nr_heads; i++) {
449 if (posn->status & REF_STATUS_UPTODATE)
452 strbuf_addf(&buf, "import %s\n", posn->name);
453 sendline(data, &buf);
457 write_constant(data->helper->in, "\n");
459 * remote-helpers that advertise the bidi-import capability are required to
460 * buffer the complete batch of import commands until this newline before
461 * sending data to fast-import.
462 * These helpers read back data from fast-import on their stdin, which could
463 * be mixed with import commands, otherwise.
466 if (finish_command(&fastimport))
467 die("Error while running fast-import");
468 argv_array_free_detached(fastimport.argv);
471 * The fast-import stream of a remote helper that advertises
472 * the "refspec" capability writes to the refs named after the
473 * right hand side of the first refspec matching each ref we
476 * (If no "refspec" capability was specified, for historical
477 * reasons we default to *:*.)
479 * Store the result in to_fetch[i].old_sha1. Callers such
480 * as "git fetch" can use the value to write feedback to the
481 * terminal, populate FETCH_HEAD, and determine what new value
482 * should be written to peer_ref if the update is a
483 * fast-forward or this is a forced update.
485 for (i = 0; i < nr_heads; i++) {
488 if (posn->status & REF_STATUS_UPTODATE)
491 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
493 private = xstrdup(posn->name);
495 read_ref(private, posn->old_sha1);
499 strbuf_release(&buf);
503 static int process_connect_service(struct transport *transport,
504 const char *name, const char *exec)
506 struct helper_data *data = transport->data;
507 struct strbuf cmdbuf = STRBUF_INIT;
508 struct child_process *helper;
509 int r, duped, ret = 0;
512 helper = get_helper(transport);
515 * Yes, dup the pipe another time, as we need unbuffered version
516 * of input pipe as FILE*. fclose() closes the underlying fd and
517 * stream buffering only can be changed before first I/O operation
520 duped = dup(helper->out);
522 die_errno("Can't dup helper output fd");
523 input = xfdopen(duped, "r");
524 setvbuf(input, NULL, _IONBF, 0);
527 * Handle --upload-pack and friends. This is fire and forget...
528 * just warn if it fails.
530 if (strcmp(name, exec)) {
531 r = set_helper_option(transport, "servpath", exec);
533 warning("Setting remote service path not supported by protocol.");
535 warning("Invalid remote service path.");
539 strbuf_addf(&cmdbuf, "connect %s\n", name);
543 sendline(data, &cmdbuf);
544 recvline_fh(input, &cmdbuf);
545 if (!strcmp(cmdbuf.buf, "")) {
546 data->no_disconnect_req = 1;
548 fprintf(stderr, "Debug: Smart transport connection "
551 } else if (!strcmp(cmdbuf.buf, "fallback")) {
553 fprintf(stderr, "Debug: Falling back to dumb "
556 die("Unknown response to connect: %s",
564 static int process_connect(struct transport *transport,
567 struct helper_data *data = transport->data;
571 name = for_push ? "git-receive-pack" : "git-upload-pack";
573 exec = data->transport_options.receivepack;
575 exec = data->transport_options.uploadpack;
577 return process_connect_service(transport, name, exec);
580 static int connect_helper(struct transport *transport, const char *name,
581 const char *exec, int fd[2])
583 struct helper_data *data = transport->data;
585 /* Get_helper so connect is inited. */
586 get_helper(transport);
588 die("Operation not supported by protocol.");
590 if (!process_connect_service(transport, name, exec))
591 die("Can't connect to subservice %s.", name);
593 fd[0] = data->helper->out;
594 fd[1] = data->helper->in;
598 static int fetch(struct transport *transport,
599 int nr_heads, struct ref **to_fetch)
601 struct helper_data *data = transport->data;
604 if (process_connect(transport, 0)) {
605 do_take_over(transport);
606 return transport->fetch(transport, nr_heads, to_fetch);
610 for (i = 0; i < nr_heads; i++)
611 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
618 return fetch_with_fetch(transport, nr_heads, to_fetch);
621 return fetch_with_import(transport, nr_heads, to_fetch);
626 static void push_update_ref_status(struct strbuf *buf,
628 struct ref *remote_refs)
633 if (!prefixcmp(buf->buf, "ok ")) {
634 status = REF_STATUS_OK;
635 refname = buf->buf + 3;
636 } else if (!prefixcmp(buf->buf, "error ")) {
637 status = REF_STATUS_REMOTE_REJECT;
638 refname = buf->buf + 6;
640 die("expected ok/error, helper said '%s'", buf->buf);
642 msg = strchr(refname, ' ');
644 struct strbuf msg_buf = STRBUF_INIT;
648 if (!unquote_c_style(&msg_buf, msg, &end))
649 msg = strbuf_detach(&msg_buf, NULL);
652 strbuf_release(&msg_buf);
654 if (!strcmp(msg, "no match")) {
655 status = REF_STATUS_NONE;
659 else if (!strcmp(msg, "up to date")) {
660 status = REF_STATUS_UPTODATE;
664 else if (!strcmp(msg, "non-fast forward")) {
665 status = REF_STATUS_REJECT_NONFASTFORWARD;
669 else if (!strcmp(msg, "already exists")) {
670 status = REF_STATUS_REJECT_ALREADY_EXISTS;
674 else if (!strcmp(msg, "fetch first")) {
675 status = REF_STATUS_REJECT_FETCH_FIRST;
679 else if (!strcmp(msg, "needs force")) {
680 status = REF_STATUS_REJECT_NEEDS_FORCE;
687 *ref = find_ref_by_name(*ref, refname);
689 *ref = find_ref_by_name(remote_refs, refname);
691 warning("helper reported unexpected status of %s", refname);
695 if ((*ref)->status != REF_STATUS_NONE) {
697 * Earlier, the ref was marked not to be pushed, so ignore the ref
698 * status reported by the remote helper if the latter is 'no match'.
700 if (status == REF_STATUS_NONE)
704 (*ref)->status = status;
705 (*ref)->remote_status = msg;
708 static void push_update_refs_status(struct helper_data *data,
709 struct ref *remote_refs)
711 struct strbuf buf = STRBUF_INIT;
712 struct ref *ref = remote_refs;
714 recvline(data, &buf);
718 push_update_ref_status(&buf, &ref, remote_refs);
720 strbuf_release(&buf);
723 static int push_refs_with_push(struct transport *transport,
724 struct ref *remote_refs, int flags)
726 int force_all = flags & TRANSPORT_PUSH_FORCE;
727 int mirror = flags & TRANSPORT_PUSH_MIRROR;
728 struct helper_data *data = transport->data;
729 struct strbuf buf = STRBUF_INIT;
732 get_helper(transport);
736 for (ref = remote_refs; ref; ref = ref->next) {
737 if (!ref->peer_ref && !mirror)
740 /* Check for statuses set by set_ref_status_for_push() */
741 switch (ref->status) {
742 case REF_STATUS_REJECT_NONFASTFORWARD:
743 case REF_STATUS_REJECT_ALREADY_EXISTS:
744 case REF_STATUS_UPTODATE:
753 strbuf_addstr(&buf, "push ");
754 if (!ref->deletion) {
756 strbuf_addch(&buf, '+');
758 strbuf_addstr(&buf, ref->peer_ref->name);
760 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
762 strbuf_addch(&buf, ':');
763 strbuf_addstr(&buf, ref->name);
764 strbuf_addch(&buf, '\n');
769 standard_options(transport);
771 if (flags & TRANSPORT_PUSH_DRY_RUN) {
772 if (set_helper_option(transport, "dry-run", "true") != 0)
773 die("helper %s does not support dry-run", data->name);
776 strbuf_addch(&buf, '\n');
777 sendline(data, &buf);
778 strbuf_release(&buf);
780 push_update_refs_status(data, remote_refs);
784 static int push_refs_with_export(struct transport *transport,
785 struct ref *remote_refs, int flags)
788 struct child_process *helper, exporter;
789 struct helper_data *data = transport->data;
790 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
791 struct strbuf buf = STRBUF_INIT;
793 helper = get_helper(transport);
795 write_constant(helper->in, "export\n");
799 for (ref = remote_refs; ref; ref = ref->next) {
801 unsigned char sha1[20];
805 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
806 if (private && !get_sha1(private, sha1)) {
807 strbuf_addf(&buf, "^%s", private);
808 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
809 hashcpy(ref->old_sha1, sha1);
814 die("remote-helpers do not support ref deletion");
818 string_list_append(&revlist_args, ref->peer_ref->name);
822 if (get_exporter(transport, &exporter, &revlist_args))
823 die("Couldn't run fast-export");
825 if (finish_command(&exporter))
826 die("Error while running fast-export");
827 push_update_refs_status(data, remote_refs);
831 static int push_refs(struct transport *transport,
832 struct ref *remote_refs, int flags)
834 struct helper_data *data = transport->data;
836 if (process_connect(transport, 1)) {
837 do_take_over(transport);
838 return transport->push_refs(transport, remote_refs, flags);
842 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
843 "Perhaps you should specify a branch such as 'master'.\n");
848 return push_refs_with_push(transport, remote_refs, flags);
851 return push_refs_with_export(transport, remote_refs, flags);
857 static int has_attribute(const char *attrs, const char *attr) {
864 const char *space = strchrnul(attrs, ' ');
865 if (len == space - attrs && !strncmp(attrs, attr, len))
873 static struct ref *get_refs_list(struct transport *transport, int for_push)
875 struct helper_data *data = transport->data;
876 struct child_process *helper;
877 struct ref *ret = NULL;
878 struct ref **tail = &ret;
880 struct strbuf buf = STRBUF_INIT;
882 helper = get_helper(transport);
884 if (process_connect(transport, for_push)) {
885 do_take_over(transport);
886 return transport->get_refs_list(transport, for_push);
889 if (data->push && for_push)
890 write_str_in_full(helper->in, "list for-push\n");
892 write_str_in_full(helper->in, "list\n");
896 recvline(data, &buf);
901 eov = strchr(buf.buf, ' ');
903 die("Malformed response in ref list: %s", buf.buf);
904 eon = strchr(eov + 1, ' ');
908 *tail = alloc_ref(eov + 1);
909 if (buf.buf[0] == '@')
910 (*tail)->symref = xstrdup(buf.buf + 1);
911 else if (buf.buf[0] != '?')
912 get_sha1_hex(buf.buf, (*tail)->old_sha1);
914 if (has_attribute(eon + 1, "unchanged")) {
915 (*tail)->status |= REF_STATUS_UPTODATE;
916 read_ref((*tail)->name, (*tail)->old_sha1);
919 tail = &((*tail)->next);
922 fprintf(stderr, "Debug: Read ref listing.\n");
923 strbuf_release(&buf);
925 for (posn = ret; posn; posn = posn->next)
926 resolve_remote_symref(posn, ret);
931 int transport_helper_init(struct transport *transport, const char *name)
933 struct helper_data *data = xcalloc(sizeof(*data), 1);
936 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
939 transport->data = data;
940 transport->set_option = set_helper_option;
941 transport->get_refs_list = get_refs_list;
942 transport->fetch = fetch;
943 transport->push_refs = push_refs;
944 transport->disconnect = release_helper;
945 transport->connect = connect_helper;
946 transport->smart_options = &(data->transport_options);
951 * Linux pipes can buffer 65536 bytes at once (and most platforms can
952 * buffer less), so attempt reads and writes with up to that size.
954 #define BUFFERSIZE 65536
955 /* This should be enough to hold debugging message. */
956 #define PBUFFERSIZE 8192
958 /* Print bidirectional transfer loop debug message. */
959 static void transfer_debug(const char *fmt, ...)
962 char msgbuf[PBUFFERSIZE];
963 static int debug_enabled = -1;
965 if (debug_enabled < 0)
966 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
971 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
973 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
976 /* Stream state: More data may be coming in this direction. */
977 #define SSTATE_TRANSFERING 0
979 * Stream state: No more data coming in this direction, flushing rest of
982 #define SSTATE_FLUSHING 1
983 /* Stream state: Transfer in this direction finished. */
984 #define SSTATE_FINISHED 2
986 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
987 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
988 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
990 /* Unidirectional transfer. */
991 struct unidirectional_transfer {
996 /* Is source socket? */
998 /* Is destination socket? */
1000 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1003 char buf[BUFFERSIZE];
1006 /* Name of source. */
1007 const char *src_name;
1008 /* Name of destination. */
1009 const char *dest_name;
1012 /* Closes the target (for writing) if transfer has finished. */
1013 static void udt_close_if_finished(struct unidirectional_transfer *t)
1015 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1016 t->state = SSTATE_FINISHED;
1017 if (t->dest_is_sock)
1018 shutdown(t->dest, SHUT_WR);
1021 transfer_debug("Closed %s.", t->dest_name);
1026 * Tries to read read data from source into buffer. If buffer is full,
1027 * no data is read. Returns 0 on success, -1 on error.
1029 static int udt_do_read(struct unidirectional_transfer *t)
1033 if (t->bufuse == BUFFERSIZE)
1034 return 0; /* No space for more. */
1036 transfer_debug("%s is readable", t->src_name);
1037 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1038 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1040 error("read(%s) failed: %s", t->src_name, strerror(errno));
1042 } else if (bytes == 0) {
1043 transfer_debug("%s EOF (with %i bytes in buffer)",
1044 t->src_name, t->bufuse);
1045 t->state = SSTATE_FLUSHING;
1046 } else if (bytes > 0) {
1048 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1049 (int)bytes, t->src_name, (int)t->bufuse);
1054 /* Tries to write data from buffer into destination. If buffer is empty,
1055 * no data is written. Returns 0 on success, -1 on error.
1057 static int udt_do_write(struct unidirectional_transfer *t)
1062 return 0; /* Nothing to write. */
1064 transfer_debug("%s is writable", t->dest_name);
1065 bytes = write(t->dest, t->buf, t->bufuse);
1066 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1068 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1070 } else if (bytes > 0) {
1073 memmove(t->buf, t->buf + bytes, t->bufuse);
1074 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1075 (int)bytes, t->dest_name, (int)t->bufuse);
1081 /* State of bidirectional transfer loop. */
1082 struct bidirectional_transfer_state {
1083 /* Direction from program to git. */
1084 struct unidirectional_transfer ptg;
1085 /* Direction from git to program. */
1086 struct unidirectional_transfer gtp;
1089 static void *udt_copy_task_routine(void *udt)
1091 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1092 while (t->state != SSTATE_FINISHED) {
1093 if (STATE_NEEDS_READING(t->state))
1096 if (STATE_NEEDS_WRITING(t->state))
1097 if (udt_do_write(t))
1099 if (STATE_NEEDS_CLOSING(t->state))
1100 udt_close_if_finished(t);
1102 return udt; /* Just some non-NULL value. */
1108 * Join thread, with apporiate errors on failure. Name is name for the
1109 * thread (for error messages). Returns 0 on success, 1 on failure.
1111 static int tloop_join(pthread_t thread, const char *name)
1115 err = pthread_join(thread, &tret);
1117 error("%s thread failed", name);
1121 error("%s thread failed to join: %s", name, strerror(err));
1128 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1131 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1133 pthread_t gtp_thread;
1134 pthread_t ptg_thread;
1137 err = pthread_create(>p_thread, NULL, udt_copy_task_routine,
1140 die("Can't start thread for copying data: %s", strerror(err));
1141 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1144 die("Can't start thread for copying data: %s", strerror(err));
1146 ret |= tloop_join(gtp_thread, "Git to program copy");
1147 ret |= tloop_join(ptg_thread, "Program to git copy");
1152 /* Close the source and target (for writing) for transfer. */
1153 static void udt_kill_transfer(struct unidirectional_transfer *t)
1155 t->state = SSTATE_FINISHED;
1157 * Socket read end left open isn't a disaster if nobody
1158 * attempts to read from it (mingw compat headers do not
1161 * We can't fully close the socket since otherwise gtp
1162 * task would first close the socket it sends data to
1163 * while closing the ptg file descriptors.
1165 if (!t->src_is_sock)
1167 if (t->dest_is_sock)
1168 shutdown(t->dest, SHUT_WR);
1174 * Join process, with apporiate errors on failure. Name is name for the
1175 * process (for error messages). Returns 0 on success, 1 on failure.
1177 static int tloop_join(pid_t pid, const char *name)
1180 if (waitpid(pid, &tret, 0) < 0) {
1181 error("%s process failed to wait: %s", name, strerror(errno));
1184 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1185 error("%s process failed", name);
1192 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1195 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1200 /* Fork thread #1: git to program. */
1203 die_errno("Can't start thread for copying data");
1204 else if (pid1 == 0) {
1205 udt_kill_transfer(&s->ptg);
1206 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1209 /* Fork thread #2: program to git. */
1212 die_errno("Can't start thread for copying data");
1213 else if (pid2 == 0) {
1214 udt_kill_transfer(&s->gtp);
1215 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1219 * Close both streams in parent as to not interfere with
1220 * end of file detection and wait for both tasks to finish.
1222 udt_kill_transfer(&s->gtp);
1223 udt_kill_transfer(&s->ptg);
1224 ret |= tloop_join(pid1, "Git to program copy");
1225 ret |= tloop_join(pid2, "Program to git copy");
1231 * Copies data from stdin to output and from input to stdout simultaneously.
1232 * Additionally filtering through given filter. If filter is NULL, uses
1235 int bidirectional_transfer_loop(int input, int output)
1237 struct bidirectional_transfer_state state;
1239 /* Fill the state fields. */
1240 state.ptg.src = input;
1242 state.ptg.src_is_sock = (input == output);
1243 state.ptg.dest_is_sock = 0;
1244 state.ptg.state = SSTATE_TRANSFERING;
1245 state.ptg.bufuse = 0;
1246 state.ptg.src_name = "remote input";
1247 state.ptg.dest_name = "stdout";
1250 state.gtp.dest = output;
1251 state.gtp.src_is_sock = 0;
1252 state.gtp.dest_is_sock = (input == output);
1253 state.gtp.state = SSTATE_TRANSFERING;
1254 state.gtp.bufuse = 0;
1255 state.gtp.src_name = "stdin";
1256 state.gtp.dest_name = "remote output";
1258 return tloop_spawnwait_tasks(&state);