4 #include "run-command.h"
10 #include "string-list.h"
11 #include "thread-utils.h"
13 #include "argv-array.h"
20 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, const char *name)
54 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
55 if (strbuf_getline(buffer, helper, '\n') == EOF) {
57 fprintf(stderr, "Debug: Remote helper quit.\n");
58 die("Reading from helper 'git-remote-%s' failed", name);
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, helper->name);
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 (!prefixcmp(capname, "export-marks ")) {
196 struct strbuf arg = STRBUF_INIT;
197 strbuf_addstr(&arg, "--export-marks=");
198 strbuf_addstr(&arg, capname + strlen("export-marks "));
199 data->export_marks = strbuf_detach(&arg, NULL);
200 } else if (!prefixcmp(capname, "import-marks")) {
201 struct strbuf arg = STRBUF_INIT;
202 strbuf_addstr(&arg, "--import-marks=");
203 strbuf_addstr(&arg, capname + strlen("import-marks "));
204 data->import_marks = strbuf_detach(&arg, NULL);
205 } else if (mandatory) {
206 die("Unknown mandatory capability %s. This remote "
207 "helper probably needs newer version of Git.",
213 data->refspec_nr = refspec_nr;
214 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
215 for (i = 0; i < refspec_nr; i++) {
216 free((char *)refspecs[i]);
219 } else if (data->import || data->bidi_import || data->export) {
220 warning("This remote helper should implement refspec capability.");
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(5 + revlist_args->nr, sizeof(*fastexport->argv));
417 fastexport->argv[argc++] = "fast-export";
418 fastexport->argv[argc++] = "--use-done-feature";
419 if (data->export_marks)
420 fastexport->argv[argc++] = data->export_marks;
421 if (data->import_marks)
422 fastexport->argv[argc++] = data->import_marks;
424 for (i = 0; i < revlist_args->nr; i++)
425 fastexport->argv[argc++] = revlist_args->items[i].string;
427 fastexport->git_cmd = 1;
428 return start_command(fastexport);
431 static int fetch_with_import(struct transport *transport,
432 int nr_heads, struct ref **to_fetch)
434 struct child_process fastimport;
435 struct helper_data *data = transport->data;
438 struct strbuf buf = STRBUF_INIT;
440 get_helper(transport);
442 if (get_importer(transport, &fastimport))
443 die("Couldn't run fast-import");
445 for (i = 0; i < nr_heads; i++) {
447 if (posn->status & REF_STATUS_UPTODATE)
450 strbuf_addf(&buf, "import %s\n", posn->name);
451 sendline(data, &buf);
455 write_constant(data->helper->in, "\n");
457 * remote-helpers that advertise the bidi-import capability are required to
458 * buffer the complete batch of import commands until this newline before
459 * sending data to fast-import.
460 * These helpers read back data from fast-import on their stdin, which could
461 * be mixed with import commands, otherwise.
464 if (finish_command(&fastimport))
465 die("Error while running fast-import");
466 argv_array_free_detached(fastimport.argv);
469 * The fast-import stream of a remote helper that advertises
470 * the "refspec" capability writes to the refs named after the
471 * right hand side of the first refspec matching each ref we
474 * (If no "refspec" capability was specified, for historical
475 * reasons we default to the equivalent of *:*.)
477 * Store the result in to_fetch[i].old_sha1. Callers such
478 * as "git fetch" can use the value to write feedback to the
479 * terminal, populate FETCH_HEAD, and determine what new value
480 * should be written to peer_ref if the update is a
481 * fast-forward or this is a forced update.
483 for (i = 0; i < nr_heads; i++) {
486 if (posn->status & REF_STATUS_UPTODATE)
489 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
491 private = xstrdup(posn->name);
493 read_ref(private, posn->old_sha1);
497 strbuf_release(&buf);
501 static int process_connect_service(struct transport *transport,
502 const char *name, const char *exec)
504 struct helper_data *data = transport->data;
505 struct strbuf cmdbuf = STRBUF_INIT;
506 struct child_process *helper;
507 int r, duped, ret = 0;
510 helper = get_helper(transport);
513 * Yes, dup the pipe another time, as we need unbuffered version
514 * of input pipe as FILE*. fclose() closes the underlying fd and
515 * stream buffering only can be changed before first I/O operation
518 duped = dup(helper->out);
520 die_errno("Can't dup helper output fd");
521 input = xfdopen(duped, "r");
522 setvbuf(input, NULL, _IONBF, 0);
525 * Handle --upload-pack and friends. This is fire and forget...
526 * just warn if it fails.
528 if (strcmp(name, exec)) {
529 r = set_helper_option(transport, "servpath", exec);
531 warning("Setting remote service path not supported by protocol.");
533 warning("Invalid remote service path.");
537 strbuf_addf(&cmdbuf, "connect %s\n", name);
541 sendline(data, &cmdbuf);
542 recvline_fh(input, &cmdbuf, name);
543 if (!strcmp(cmdbuf.buf, "")) {
544 data->no_disconnect_req = 1;
546 fprintf(stderr, "Debug: Smart transport connection "
549 } else if (!strcmp(cmdbuf.buf, "fallback")) {
551 fprintf(stderr, "Debug: Falling back to dumb "
554 die("Unknown response to connect: %s",
562 static int process_connect(struct transport *transport,
565 struct helper_data *data = transport->data;
569 name = for_push ? "git-receive-pack" : "git-upload-pack";
571 exec = data->transport_options.receivepack;
573 exec = data->transport_options.uploadpack;
575 return process_connect_service(transport, name, exec);
578 static int connect_helper(struct transport *transport, const char *name,
579 const char *exec, int fd[2])
581 struct helper_data *data = transport->data;
583 /* Get_helper so connect is inited. */
584 get_helper(transport);
586 die("Operation not supported by protocol.");
588 if (!process_connect_service(transport, name, exec))
589 die("Can't connect to subservice %s.", name);
591 fd[0] = data->helper->out;
592 fd[1] = data->helper->in;
596 static int fetch(struct transport *transport,
597 int nr_heads, struct ref **to_fetch)
599 struct helper_data *data = transport->data;
602 if (process_connect(transport, 0)) {
603 do_take_over(transport);
604 return transport->fetch(transport, nr_heads, to_fetch);
608 for (i = 0; i < nr_heads; i++)
609 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
616 return fetch_with_fetch(transport, nr_heads, to_fetch);
619 return fetch_with_import(transport, nr_heads, to_fetch);
624 static int push_update_ref_status(struct strbuf *buf,
626 struct ref *remote_refs)
631 if (!prefixcmp(buf->buf, "ok ")) {
632 status = REF_STATUS_OK;
633 refname = buf->buf + 3;
634 } else if (!prefixcmp(buf->buf, "error ")) {
635 status = REF_STATUS_REMOTE_REJECT;
636 refname = buf->buf + 6;
638 die("expected ok/error, helper said '%s'", buf->buf);
640 msg = strchr(refname, ' ');
642 struct strbuf msg_buf = STRBUF_INIT;
646 if (!unquote_c_style(&msg_buf, msg, &end))
647 msg = strbuf_detach(&msg_buf, NULL);
650 strbuf_release(&msg_buf);
652 if (!strcmp(msg, "no match")) {
653 status = REF_STATUS_NONE;
657 else if (!strcmp(msg, "up to date")) {
658 status = REF_STATUS_UPTODATE;
662 else if (!strcmp(msg, "non-fast forward")) {
663 status = REF_STATUS_REJECT_NONFASTFORWARD;
667 else if (!strcmp(msg, "already exists")) {
668 status = REF_STATUS_REJECT_ALREADY_EXISTS;
672 else if (!strcmp(msg, "fetch first")) {
673 status = REF_STATUS_REJECT_FETCH_FIRST;
677 else if (!strcmp(msg, "needs force")) {
678 status = REF_STATUS_REJECT_NEEDS_FORCE;
685 *ref = find_ref_by_name(*ref, refname);
687 *ref = find_ref_by_name(remote_refs, refname);
689 warning("helper reported unexpected status of %s", refname);
693 if ((*ref)->status != REF_STATUS_NONE) {
695 * Earlier, the ref was marked not to be pushed, so ignore the ref
696 * status reported by the remote helper if the latter is 'no match'.
698 if (status == REF_STATUS_NONE)
702 (*ref)->status = status;
703 (*ref)->remote_status = msg;
704 return !(status == REF_STATUS_OK);
707 static void push_update_refs_status(struct helper_data *data,
708 struct ref *remote_refs)
710 struct strbuf buf = STRBUF_INIT;
711 struct ref *ref = remote_refs;
715 recvline(data, &buf);
719 if (push_update_ref_status(&buf, &ref, remote_refs))
725 /* propagate back the update to the remote namespace */
726 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
729 update_ref("update by helper", private, ref->new_sha1, NULL, 0, 0);
732 strbuf_release(&buf);
735 static int push_refs_with_push(struct transport *transport,
736 struct ref *remote_refs, int flags)
738 int force_all = flags & TRANSPORT_PUSH_FORCE;
739 int mirror = flags & TRANSPORT_PUSH_MIRROR;
740 struct helper_data *data = transport->data;
741 struct strbuf buf = STRBUF_INIT;
744 get_helper(transport);
748 for (ref = remote_refs; ref; ref = ref->next) {
749 if (!ref->peer_ref && !mirror)
752 /* Check for statuses set by set_ref_status_for_push() */
753 switch (ref->status) {
754 case REF_STATUS_REJECT_NONFASTFORWARD:
755 case REF_STATUS_REJECT_ALREADY_EXISTS:
756 case REF_STATUS_UPTODATE:
765 strbuf_addstr(&buf, "push ");
766 if (!ref->deletion) {
768 strbuf_addch(&buf, '+');
770 strbuf_addstr(&buf, ref->peer_ref->name);
772 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
774 strbuf_addch(&buf, ':');
775 strbuf_addstr(&buf, ref->name);
776 strbuf_addch(&buf, '\n');
781 standard_options(transport);
783 if (flags & TRANSPORT_PUSH_DRY_RUN) {
784 if (set_helper_option(transport, "dry-run", "true") != 0)
785 die("helper %s does not support dry-run", data->name);
788 strbuf_addch(&buf, '\n');
789 sendline(data, &buf);
790 strbuf_release(&buf);
792 push_update_refs_status(data, remote_refs);
796 static int push_refs_with_export(struct transport *transport,
797 struct ref *remote_refs, int flags)
800 struct child_process *helper, exporter;
801 struct helper_data *data = transport->data;
802 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
803 struct strbuf buf = STRBUF_INIT;
806 die("remote-helper doesn't support push; refspec needed");
808 helper = get_helper(transport);
810 write_constant(helper->in, "export\n");
814 for (ref = remote_refs; ref; ref = ref->next) {
816 unsigned char sha1[20];
819 die("remote-helpers do not support ref deletion");
821 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
822 if (private && !get_sha1(private, sha1)) {
823 strbuf_addf(&buf, "^%s", private);
824 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
825 hashcpy(ref->old_sha1, sha1);
830 string_list_append(&revlist_args, ref->peer_ref->name);
833 if (get_exporter(transport, &exporter, &revlist_args))
834 die("Couldn't run fast-export");
836 if (finish_command(&exporter))
837 die("Error while running fast-export");
838 push_update_refs_status(data, remote_refs);
842 static int push_refs(struct transport *transport,
843 struct ref *remote_refs, int flags)
845 struct helper_data *data = transport->data;
847 if (process_connect(transport, 1)) {
848 do_take_over(transport);
849 return transport->push_refs(transport, remote_refs, flags);
853 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
854 "Perhaps you should specify a branch such as 'master'.\n");
859 return push_refs_with_push(transport, remote_refs, flags);
862 return push_refs_with_export(transport, remote_refs, flags);
868 static int has_attribute(const char *attrs, const char *attr) {
875 const char *space = strchrnul(attrs, ' ');
876 if (len == space - attrs && !strncmp(attrs, attr, len))
884 static struct ref *get_refs_list(struct transport *transport, int for_push)
886 struct helper_data *data = transport->data;
887 struct child_process *helper;
888 struct ref *ret = NULL;
889 struct ref **tail = &ret;
891 struct strbuf buf = STRBUF_INIT;
893 helper = get_helper(transport);
895 if (process_connect(transport, for_push)) {
896 do_take_over(transport);
897 return transport->get_refs_list(transport, for_push);
900 if (data->push && for_push)
901 write_str_in_full(helper->in, "list for-push\n");
903 write_str_in_full(helper->in, "list\n");
907 recvline(data, &buf);
912 eov = strchr(buf.buf, ' ');
914 die("Malformed response in ref list: %s", buf.buf);
915 eon = strchr(eov + 1, ' ');
919 *tail = alloc_ref(eov + 1);
920 if (buf.buf[0] == '@')
921 (*tail)->symref = xstrdup(buf.buf + 1);
922 else if (buf.buf[0] != '?')
923 get_sha1_hex(buf.buf, (*tail)->old_sha1);
925 if (has_attribute(eon + 1, "unchanged")) {
926 (*tail)->status |= REF_STATUS_UPTODATE;
927 read_ref((*tail)->name, (*tail)->old_sha1);
930 tail = &((*tail)->next);
933 fprintf(stderr, "Debug: Read ref listing.\n");
934 strbuf_release(&buf);
936 for (posn = ret; posn; posn = posn->next)
937 resolve_remote_symref(posn, ret);
942 int transport_helper_init(struct transport *transport, const char *name)
944 struct helper_data *data = xcalloc(sizeof(*data), 1);
947 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
950 transport->data = data;
951 transport->set_option = set_helper_option;
952 transport->get_refs_list = get_refs_list;
953 transport->fetch = fetch;
954 transport->push_refs = push_refs;
955 transport->disconnect = release_helper;
956 transport->connect = connect_helper;
957 transport->smart_options = &(data->transport_options);
962 * Linux pipes can buffer 65536 bytes at once (and most platforms can
963 * buffer less), so attempt reads and writes with up to that size.
965 #define BUFFERSIZE 65536
966 /* This should be enough to hold debugging message. */
967 #define PBUFFERSIZE 8192
969 /* Print bidirectional transfer loop debug message. */
970 static void transfer_debug(const char *fmt, ...)
973 char msgbuf[PBUFFERSIZE];
974 static int debug_enabled = -1;
976 if (debug_enabled < 0)
977 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
982 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
984 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
987 /* Stream state: More data may be coming in this direction. */
988 #define SSTATE_TRANSFERING 0
990 * Stream state: No more data coming in this direction, flushing rest of
993 #define SSTATE_FLUSHING 1
994 /* Stream state: Transfer in this direction finished. */
995 #define SSTATE_FINISHED 2
997 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
998 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
999 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1001 /* Unidirectional transfer. */
1002 struct unidirectional_transfer {
1007 /* Is source socket? */
1009 /* Is destination socket? */
1011 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
1014 char buf[BUFFERSIZE];
1017 /* Name of source. */
1018 const char *src_name;
1019 /* Name of destination. */
1020 const char *dest_name;
1023 /* Closes the target (for writing) if transfer has finished. */
1024 static void udt_close_if_finished(struct unidirectional_transfer *t)
1026 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1027 t->state = SSTATE_FINISHED;
1028 if (t->dest_is_sock)
1029 shutdown(t->dest, SHUT_WR);
1032 transfer_debug("Closed %s.", t->dest_name);
1037 * Tries to read read data from source into buffer. If buffer is full,
1038 * no data is read. Returns 0 on success, -1 on error.
1040 static int udt_do_read(struct unidirectional_transfer *t)
1044 if (t->bufuse == BUFFERSIZE)
1045 return 0; /* No space for more. */
1047 transfer_debug("%s is readable", t->src_name);
1048 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1049 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1051 error("read(%s) failed: %s", t->src_name, strerror(errno));
1053 } else if (bytes == 0) {
1054 transfer_debug("%s EOF (with %i bytes in buffer)",
1055 t->src_name, t->bufuse);
1056 t->state = SSTATE_FLUSHING;
1057 } else if (bytes > 0) {
1059 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1060 (int)bytes, t->src_name, (int)t->bufuse);
1065 /* Tries to write data from buffer into destination. If buffer is empty,
1066 * no data is written. Returns 0 on success, -1 on error.
1068 static int udt_do_write(struct unidirectional_transfer *t)
1073 return 0; /* Nothing to write. */
1075 transfer_debug("%s is writable", t->dest_name);
1076 bytes = write(t->dest, t->buf, t->bufuse);
1077 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1079 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1081 } else if (bytes > 0) {
1084 memmove(t->buf, t->buf + bytes, t->bufuse);
1085 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1086 (int)bytes, t->dest_name, (int)t->bufuse);
1092 /* State of bidirectional transfer loop. */
1093 struct bidirectional_transfer_state {
1094 /* Direction from program to git. */
1095 struct unidirectional_transfer ptg;
1096 /* Direction from git to program. */
1097 struct unidirectional_transfer gtp;
1100 static void *udt_copy_task_routine(void *udt)
1102 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1103 while (t->state != SSTATE_FINISHED) {
1104 if (STATE_NEEDS_READING(t->state))
1107 if (STATE_NEEDS_WRITING(t->state))
1108 if (udt_do_write(t))
1110 if (STATE_NEEDS_CLOSING(t->state))
1111 udt_close_if_finished(t);
1113 return udt; /* Just some non-NULL value. */
1119 * Join thread, with apporiate errors on failure. Name is name for the
1120 * thread (for error messages). Returns 0 on success, 1 on failure.
1122 static int tloop_join(pthread_t thread, const char *name)
1126 err = pthread_join(thread, &tret);
1128 error("%s thread failed", name);
1132 error("%s thread failed to join: %s", name, strerror(err));
1139 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1142 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1144 pthread_t gtp_thread;
1145 pthread_t ptg_thread;
1148 err = pthread_create(>p_thread, NULL, udt_copy_task_routine,
1151 die("Can't start thread for copying data: %s", strerror(err));
1152 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1155 die("Can't start thread for copying data: %s", strerror(err));
1157 ret |= tloop_join(gtp_thread, "Git to program copy");
1158 ret |= tloop_join(ptg_thread, "Program to git copy");
1163 /* Close the source and target (for writing) for transfer. */
1164 static void udt_kill_transfer(struct unidirectional_transfer *t)
1166 t->state = SSTATE_FINISHED;
1168 * Socket read end left open isn't a disaster if nobody
1169 * attempts to read from it (mingw compat headers do not
1172 * We can't fully close the socket since otherwise gtp
1173 * task would first close the socket it sends data to
1174 * while closing the ptg file descriptors.
1176 if (!t->src_is_sock)
1178 if (t->dest_is_sock)
1179 shutdown(t->dest, SHUT_WR);
1185 * Join process, with apporiate errors on failure. Name is name for the
1186 * process (for error messages). Returns 0 on success, 1 on failure.
1188 static int tloop_join(pid_t pid, const char *name)
1191 if (waitpid(pid, &tret, 0) < 0) {
1192 error("%s process failed to wait: %s", name, strerror(errno));
1195 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1196 error("%s process failed", name);
1203 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1206 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1211 /* Fork thread #1: git to program. */
1214 die_errno("Can't start thread for copying data");
1215 else if (pid1 == 0) {
1216 udt_kill_transfer(&s->ptg);
1217 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1220 /* Fork thread #2: program to git. */
1223 die_errno("Can't start thread for copying data");
1224 else if (pid2 == 0) {
1225 udt_kill_transfer(&s->gtp);
1226 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1230 * Close both streams in parent as to not interfere with
1231 * end of file detection and wait for both tasks to finish.
1233 udt_kill_transfer(&s->gtp);
1234 udt_kill_transfer(&s->ptg);
1235 ret |= tloop_join(pid1, "Git to program copy");
1236 ret |= tloop_join(pid2, "Program to git copy");
1242 * Copies data from stdin to output and from input to stdout simultaneously.
1243 * Additionally filtering through given filter. If filter is NULL, uses
1246 int bidirectional_transfer_loop(int input, int output)
1248 struct bidirectional_transfer_state state;
1250 /* Fill the state fields. */
1251 state.ptg.src = input;
1253 state.ptg.src_is_sock = (input == output);
1254 state.ptg.dest_is_sock = 0;
1255 state.ptg.state = SSTATE_TRANSFERING;
1256 state.ptg.bufuse = 0;
1257 state.ptg.src_name = "remote input";
1258 state.ptg.dest_name = "stdout";
1261 state.gtp.dest = output;
1262 state.gtp.src_is_sock = 0;
1263 state.gtp.dest_is_sock = (input == output);
1264 state.gtp.state = SSTATE_TRANSFERING;
1265 state.gtp.bufuse = 0;
1266 state.gtp.src_name = "stdin";
1267 state.gtp.dest_name = "remote output";
1269 return tloop_spawnwait_tasks(&state);