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
;
28 no_disconnect_req
: 1;
31 /* These go from remote name (as in "list") to private name */
32 struct refspec
*refspecs
;
34 /* Transport options for fetch-pack/send-pack (should one of
37 struct git_transport_options transport_options
;
40 static void sendline(struct helper_data
*helper
, struct strbuf
*buffer
)
43 fprintf(stderr
, "Debug: Remote helper: -> %s", buffer
->buf
);
44 if (write_in_full(helper
->helper
->in
, buffer
->buf
, buffer
->len
)
46 die_errno("Full write to remote helper failed");
49 static int recvline_fh(FILE *helper
, struct strbuf
*buffer
)
53 fprintf(stderr
, "Debug: Remote helper: Waiting...\n");
54 if (strbuf_getline(buffer
, helper
, '\n') == EOF
) {
56 fprintf(stderr
, "Debug: Remote helper quit.\n");
61 fprintf(stderr
, "Debug: Remote helper: <- %s\n", buffer
->buf
);
65 static int recvline(struct helper_data
*helper
, struct strbuf
*buffer
)
67 return recvline_fh(helper
->out
, buffer
);
70 static void xchgline(struct helper_data
*helper
, struct strbuf
*buffer
)
72 sendline(helper
, buffer
);
73 recvline(helper
, buffer
);
76 static void write_constant(int fd
, const char *str
)
79 fprintf(stderr
, "Debug: Remote helper: -> %s", str
);
80 if (write_in_full(fd
, str
, strlen(str
)) != strlen(str
))
81 die_errno("Full write to remote helper failed");
84 static const char *remove_ext_force(const char *url
)
87 const char *colon
= strchr(url
, ':');
88 if (colon
&& colon
[1] == ':')
94 static void do_take_over(struct transport
*transport
)
96 struct helper_data
*data
;
97 data
= (struct helper_data
*)transport
->data
;
98 transport_take_over(transport
, data
->helper
);
103 static struct child_process
*get_helper(struct transport
*transport
)
105 struct helper_data
*data
= transport
->data
;
106 struct argv_array argv
= ARGV_ARRAY_INIT
;
107 struct strbuf buf
= STRBUF_INIT
;
108 struct child_process
*helper
;
109 const char **refspecs
= NULL
;
111 int refspec_alloc
= 0;
114 char git_dir_buf
[sizeof(GIT_DIR_ENVIRONMENT
) + PATH_MAX
+ 1];
115 const char *helper_env
[] = {
124 helper
= xcalloc(1, sizeof(*helper
));
128 argv_array_pushf(&argv
, "git-remote-%s", data
->name
);
129 argv_array_push(&argv
, transport
->remote
->name
);
130 argv_array_push(&argv
, remove_ext_force(transport
->url
));
131 helper
->argv
= argv_array_detach(&argv
, NULL
);
133 helper
->silent_exec_failure
= 1;
135 snprintf(git_dir_buf
, sizeof(git_dir_buf
), "%s=%s", GIT_DIR_ENVIRONMENT
, get_git_dir());
136 helper
->env
= helper_env
;
138 code
= start_command(helper
);
139 if (code
< 0 && errno
== ENOENT
)
140 die("Unable to find remote helper for '%s'", data
->name
);
144 data
->helper
= helper
;
145 data
->no_disconnect_req
= 0;
148 * Open the output as FILE* so strbuf_getline() can be used.
149 * Do this with duped fd because fclose() will close the fd,
150 * and stuff like taking over will require the fd to remain.
152 duped
= dup(helper
->out
);
154 die_errno("Can't dup helper output fd");
155 data
->out
= xfdopen(duped
, "r");
157 write_constant(helper
->in
, "capabilities\n");
162 recvline(data
, &buf
);
167 if (*buf
.buf
== '*') {
168 capname
= buf
.buf
+ 1;
174 fprintf(stderr
, "Debug: Got cap %s\n", capname
);
175 if (!strcmp(capname
, "fetch"))
177 else if (!strcmp(capname
, "option"))
179 else if (!strcmp(capname
, "push"))
181 else if (!strcmp(capname
, "import"))
183 else if (!strcmp(capname
, "bidi-import"))
184 data
->bidi_import
= 1;
185 else if (!strcmp(capname
, "export"))
187 else if (!data
->refspecs
&& !prefixcmp(capname
, "refspec ")) {
191 refspecs
[refspec_nr
++] = xstrdup(capname
+ strlen("refspec "));
192 } else if (!strcmp(capname
, "connect")) {
194 } else if (!prefixcmp(capname
, "export-marks ")) {
195 struct strbuf arg
= STRBUF_INIT
;
196 strbuf_addstr(&arg
, "--export-marks=");
197 strbuf_addstr(&arg
, capname
+ strlen("export-marks "));
198 data
->export_marks
= strbuf_detach(&arg
, NULL
);
199 } else if (!prefixcmp(capname
, "import-marks")) {
200 struct strbuf arg
= STRBUF_INIT
;
201 strbuf_addstr(&arg
, "--import-marks=");
202 strbuf_addstr(&arg
, capname
+ strlen("import-marks "));
203 data
->import_marks
= strbuf_detach(&arg
, NULL
);
204 } else if (mandatory
) {
205 die("Unknown mandatory capability %s. This remote "
206 "helper probably needs newer version of Git.",
212 data
->refspec_nr
= refspec_nr
;
213 data
->refspecs
= parse_fetch_refspec(refspec_nr
, refspecs
);
214 for (i
= 0; i
< refspec_nr
; i
++) {
215 free((char *)refspecs
[i
]);
219 strbuf_release(&buf
);
221 fprintf(stderr
, "Debug: Capabilities complete.\n");
225 static int disconnect_helper(struct transport
*transport
)
227 struct helper_data
*data
= transport
->data
;
232 fprintf(stderr
, "Debug: Disconnecting.\n");
233 if (!data
->no_disconnect_req
) {
235 * Ignore write errors; there's nothing we can do,
236 * since we're about to close the pipe anyway. And the
237 * most likely error is EPIPE due to the helper dying
238 * to report an error itself.
240 sigchain_push(SIGPIPE
, SIG_IGN
);
241 xwrite(data
->helper
->in
, "\n", 1);
242 sigchain_pop(SIGPIPE
);
244 close(data
->helper
->in
);
245 close(data
->helper
->out
);
247 res
= finish_command(data
->helper
);
248 argv_array_free_detached(data
->helper
->argv
);
255 static const char *unsupported_options
[] = {
256 TRANS_OPT_UPLOADPACK
,
257 TRANS_OPT_RECEIVEPACK
,
261 static const char *boolean_options
[] = {
267 static int set_helper_option(struct transport
*transport
,
268 const char *name
, const char *value
)
270 struct helper_data
*data
= transport
->data
;
271 struct strbuf buf
= STRBUF_INIT
;
272 int i
, ret
, is_bool
= 0;
274 get_helper(transport
);
279 for (i
= 0; i
< ARRAY_SIZE(unsupported_options
); i
++) {
280 if (!strcmp(name
, unsupported_options
[i
]))
284 for (i
= 0; i
< ARRAY_SIZE(boolean_options
); i
++) {
285 if (!strcmp(name
, boolean_options
[i
])) {
291 strbuf_addf(&buf
, "option %s ", name
);
293 strbuf_addstr(&buf
, value
? "true" : "false");
295 quote_c_style(value
, &buf
, NULL
, 0);
296 strbuf_addch(&buf
, '\n');
298 xchgline(data
, &buf
);
300 if (!strcmp(buf
.buf
, "ok"))
302 else if (!prefixcmp(buf
.buf
, "error")) {
304 } else if (!strcmp(buf
.buf
, "unsupported"))
307 warning("%s unexpectedly said: '%s'", data
->name
, buf
.buf
);
310 strbuf_release(&buf
);
314 static void standard_options(struct transport
*t
)
320 set_helper_option(t
, "progress", t
->progress
? "true" : "false");
322 n
= snprintf(buf
, sizeof(buf
), "%d", v
+ 1);
323 if (n
>= sizeof(buf
))
324 die("impossibly large verbosity value");
325 set_helper_option(t
, "verbosity", buf
);
328 static int release_helper(struct transport
*transport
)
331 struct helper_data
*data
= transport
->data
;
332 free_refspec(data
->refspec_nr
, data
->refspecs
);
333 data
->refspecs
= NULL
;
334 res
= disconnect_helper(transport
);
335 free(transport
->data
);
339 static int fetch_with_fetch(struct transport
*transport
,
340 int nr_heads
, struct ref
**to_fetch
)
342 struct helper_data
*data
= transport
->data
;
344 struct strbuf buf
= STRBUF_INIT
;
346 standard_options(transport
);
348 for (i
= 0; i
< nr_heads
; i
++) {
349 const struct ref
*posn
= to_fetch
[i
];
350 if (posn
->status
& REF_STATUS_UPTODATE
)
353 strbuf_addf(&buf
, "fetch %s %s\n",
354 sha1_to_hex(posn
->old_sha1
), posn
->name
);
357 strbuf_addch(&buf
, '\n');
358 sendline(data
, &buf
);
361 recvline(data
, &buf
);
363 if (!prefixcmp(buf
.buf
, "lock ")) {
364 const char *name
= buf
.buf
+ 5;
365 if (transport
->pack_lockfile
)
366 warning("%s also locked %s", data
->name
, name
);
368 transport
->pack_lockfile
= xstrdup(name
);
373 warning("%s unexpectedly said: '%s'", data
->name
, buf
.buf
);
375 strbuf_release(&buf
);
379 static int get_importer(struct transport
*transport
, struct child_process
*fastimport
)
381 struct child_process
*helper
= get_helper(transport
);
382 struct helper_data
*data
= transport
->data
;
383 struct argv_array argv
= ARGV_ARRAY_INIT
;
384 int cat_blob_fd
, code
;
385 memset(fastimport
, 0, sizeof(*fastimport
));
386 fastimport
->in
= helper
->out
;
387 argv_array_push(&argv
, "fast-import");
388 argv_array_push(&argv
, debug
? "--stats" : "--quiet");
390 if (data
->bidi_import
) {
391 cat_blob_fd
= xdup(helper
->in
);
392 argv_array_pushf(&argv
, "--cat-blob-fd=%d", cat_blob_fd
);
394 fastimport
->argv
= argv
.argv
;
395 fastimport
->git_cmd
= 1;
397 code
= start_command(fastimport
);
401 static int get_exporter(struct transport
*transport
,
402 struct child_process
*fastexport
,
403 struct string_list
*revlist_args
)
405 struct helper_data
*data
= transport
->data
;
406 struct child_process
*helper
= get_helper(transport
);
408 memset(fastexport
, 0, sizeof(*fastexport
));
410 /* we need to duplicate helper->in because we want to use it after
411 * fastexport is done with it. */
412 fastexport
->out
= dup(helper
->in
);
413 fastexport
->argv
= xcalloc(5 + revlist_args
->nr
, sizeof(*fastexport
->argv
));
414 fastexport
->argv
[argc
++] = "fast-export";
415 fastexport
->argv
[argc
++] = "--use-done-feature";
416 if (data
->export_marks
)
417 fastexport
->argv
[argc
++] = data
->export_marks
;
418 if (data
->import_marks
)
419 fastexport
->argv
[argc
++] = data
->import_marks
;
421 for (i
= 0; i
< revlist_args
->nr
; i
++)
422 fastexport
->argv
[argc
++] = revlist_args
->items
[i
].string
;
424 fastexport
->git_cmd
= 1;
425 return start_command(fastexport
);
428 static int fetch_with_import(struct transport
*transport
,
429 int nr_heads
, struct ref
**to_fetch
)
431 struct child_process fastimport
;
432 struct helper_data
*data
= transport
->data
;
435 struct strbuf buf
= STRBUF_INIT
;
437 get_helper(transport
);
439 if (get_importer(transport
, &fastimport
))
440 die("Couldn't run fast-import");
442 for (i
= 0; i
< nr_heads
; i
++) {
444 if (posn
->status
& REF_STATUS_UPTODATE
)
447 strbuf_addf(&buf
, "import %s\n", posn
->name
);
448 sendline(data
, &buf
);
452 write_constant(data
->helper
->in
, "\n");
454 * remote-helpers that advertise the bidi-import capability are required to
455 * buffer the complete batch of import commands until this newline before
456 * sending data to fast-import.
457 * These helpers read back data from fast-import on their stdin, which could
458 * be mixed with import commands, otherwise.
461 if (finish_command(&fastimport
))
462 die("Error while running fast-import");
463 argv_array_free_detached(fastimport
.argv
);
466 * The fast-import stream of a remote helper that advertises
467 * the "refspec" capability writes to the refs named after the
468 * right hand side of the first refspec matching each ref we
471 * (If no "refspec" capability was specified, for historical
472 * reasons we default to *:*.)
474 * Store the result in to_fetch[i].old_sha1. Callers such
475 * as "git fetch" can use the value to write feedback to the
476 * terminal, populate FETCH_HEAD, and determine what new value
477 * should be written to peer_ref if the update is a
478 * fast-forward or this is a forced update.
480 for (i
= 0; i
< nr_heads
; i
++) {
483 if (posn
->status
& REF_STATUS_UPTODATE
)
486 private = apply_refspecs(data
->refspecs
, data
->refspec_nr
, posn
->name
);
488 private = xstrdup(posn
->name
);
490 read_ref(private, posn
->old_sha1
);
494 strbuf_release(&buf
);
498 static int process_connect_service(struct transport
*transport
,
499 const char *name
, const char *exec
)
501 struct helper_data
*data
= transport
->data
;
502 struct strbuf cmdbuf
= STRBUF_INIT
;
503 struct child_process
*helper
;
504 int r
, duped
, ret
= 0;
507 helper
= get_helper(transport
);
510 * Yes, dup the pipe another time, as we need unbuffered version
511 * of input pipe as FILE*. fclose() closes the underlying fd and
512 * stream buffering only can be changed before first I/O operation
515 duped
= dup(helper
->out
);
517 die_errno("Can't dup helper output fd");
518 input
= xfdopen(duped
, "r");
519 setvbuf(input
, NULL
, _IONBF
, 0);
522 * Handle --upload-pack and friends. This is fire and forget...
523 * just warn if it fails.
525 if (strcmp(name
, exec
)) {
526 r
= set_helper_option(transport
, "servpath", exec
);
528 warning("Setting remote service path not supported by protocol.");
530 warning("Invalid remote service path.");
534 strbuf_addf(&cmdbuf
, "connect %s\n", name
);
538 sendline(data
, &cmdbuf
);
539 recvline_fh(input
, &cmdbuf
);
540 if (!strcmp(cmdbuf
.buf
, "")) {
541 data
->no_disconnect_req
= 1;
543 fprintf(stderr
, "Debug: Smart transport connection "
546 } else if (!strcmp(cmdbuf
.buf
, "fallback")) {
548 fprintf(stderr
, "Debug: Falling back to dumb "
551 die("Unknown response to connect: %s",
559 static int process_connect(struct transport
*transport
,
562 struct helper_data
*data
= transport
->data
;
566 name
= for_push
? "git-receive-pack" : "git-upload-pack";
568 exec
= data
->transport_options
.receivepack
;
570 exec
= data
->transport_options
.uploadpack
;
572 return process_connect_service(transport
, name
, exec
);
575 static int connect_helper(struct transport
*transport
, const char *name
,
576 const char *exec
, int fd
[2])
578 struct helper_data
*data
= transport
->data
;
580 /* Get_helper so connect is inited. */
581 get_helper(transport
);
583 die("Operation not supported by protocol.");
585 if (!process_connect_service(transport
, name
, exec
))
586 die("Can't connect to subservice %s.", name
);
588 fd
[0] = data
->helper
->out
;
589 fd
[1] = data
->helper
->in
;
593 static int fetch(struct transport
*transport
,
594 int nr_heads
, struct ref
**to_fetch
)
596 struct helper_data
*data
= transport
->data
;
599 if (process_connect(transport
, 0)) {
600 do_take_over(transport
);
601 return transport
->fetch(transport
, nr_heads
, to_fetch
);
605 for (i
= 0; i
< nr_heads
; i
++)
606 if (!(to_fetch
[i
]->status
& REF_STATUS_UPTODATE
))
613 return fetch_with_fetch(transport
, nr_heads
, to_fetch
);
616 return fetch_with_import(transport
, nr_heads
, to_fetch
);
621 static void push_update_ref_status(struct strbuf
*buf
,
623 struct ref
*remote_refs
)
628 if (!prefixcmp(buf
->buf
, "ok ")) {
629 status
= REF_STATUS_OK
;
630 refname
= buf
->buf
+ 3;
631 } else if (!prefixcmp(buf
->buf
, "error ")) {
632 status
= REF_STATUS_REMOTE_REJECT
;
633 refname
= buf
->buf
+ 6;
635 die("expected ok/error, helper said '%s'", buf
->buf
);
637 msg
= strchr(refname
, ' ');
639 struct strbuf msg_buf
= STRBUF_INIT
;
643 if (!unquote_c_style(&msg_buf
, msg
, &end
))
644 msg
= strbuf_detach(&msg_buf
, NULL
);
647 strbuf_release(&msg_buf
);
649 if (!strcmp(msg
, "no match")) {
650 status
= REF_STATUS_NONE
;
654 else if (!strcmp(msg
, "up to date")) {
655 status
= REF_STATUS_UPTODATE
;
659 else if (!strcmp(msg
, "non-fast forward")) {
660 status
= REF_STATUS_REJECT_NONFASTFORWARD
;
664 else if (!strcmp(msg
, "already exists")) {
665 status
= REF_STATUS_REJECT_ALREADY_EXISTS
;
672 *ref
= find_ref_by_name(*ref
, refname
);
674 *ref
= find_ref_by_name(remote_refs
, refname
);
676 warning("helper reported unexpected status of %s", refname
);
680 if ((*ref
)->status
!= REF_STATUS_NONE
) {
682 * Earlier, the ref was marked not to be pushed, so ignore the ref
683 * status reported by the remote helper if the latter is 'no match'.
685 if (status
== REF_STATUS_NONE
)
689 (*ref
)->status
= status
;
690 (*ref
)->remote_status
= msg
;
693 static void push_update_refs_status(struct helper_data
*data
,
694 struct ref
*remote_refs
)
696 struct strbuf buf
= STRBUF_INIT
;
697 struct ref
*ref
= remote_refs
;
699 recvline(data
, &buf
);
703 push_update_ref_status(&buf
, &ref
, remote_refs
);
705 strbuf_release(&buf
);
708 static int push_refs_with_push(struct transport
*transport
,
709 struct ref
*remote_refs
, int flags
)
711 int force_all
= flags
& TRANSPORT_PUSH_FORCE
;
712 int mirror
= flags
& TRANSPORT_PUSH_MIRROR
;
713 struct helper_data
*data
= transport
->data
;
714 struct strbuf buf
= STRBUF_INIT
;
717 get_helper(transport
);
721 for (ref
= remote_refs
; ref
; ref
= ref
->next
) {
722 if (!ref
->peer_ref
&& !mirror
)
725 /* Check for statuses set by set_ref_status_for_push() */
726 switch (ref
->status
) {
727 case REF_STATUS_REJECT_NONFASTFORWARD
:
728 case REF_STATUS_REJECT_ALREADY_EXISTS
:
729 case REF_STATUS_UPTODATE
:
738 strbuf_addstr(&buf
, "push ");
739 if (!ref
->deletion
) {
741 strbuf_addch(&buf
, '+');
743 strbuf_addstr(&buf
, ref
->peer_ref
->name
);
745 strbuf_addstr(&buf
, sha1_to_hex(ref
->new_sha1
));
747 strbuf_addch(&buf
, ':');
748 strbuf_addstr(&buf
, ref
->name
);
749 strbuf_addch(&buf
, '\n');
754 standard_options(transport
);
756 if (flags
& TRANSPORT_PUSH_DRY_RUN
) {
757 if (set_helper_option(transport
, "dry-run", "true") != 0)
758 die("helper %s does not support dry-run", data
->name
);
761 strbuf_addch(&buf
, '\n');
762 sendline(data
, &buf
);
763 strbuf_release(&buf
);
765 push_update_refs_status(data
, remote_refs
);
769 static int push_refs_with_export(struct transport
*transport
,
770 struct ref
*remote_refs
, int flags
)
773 struct child_process
*helper
, exporter
;
774 struct helper_data
*data
= transport
->data
;
775 struct string_list revlist_args
= STRING_LIST_INIT_NODUP
;
776 struct strbuf buf
= STRBUF_INIT
;
778 helper
= get_helper(transport
);
780 write_constant(helper
->in
, "export\n");
784 for (ref
= remote_refs
; ref
; ref
= ref
->next
) {
786 unsigned char sha1
[20];
790 private = apply_refspecs(data
->refspecs
, data
->refspec_nr
, ref
->name
);
791 if (private && !get_sha1(private, sha1
)) {
792 strbuf_addf(&buf
, "^%s", private);
793 string_list_append(&revlist_args
, strbuf_detach(&buf
, NULL
));
798 die("remote-helpers do not support ref deletion");
802 string_list_append(&revlist_args
, ref
->peer_ref
->name
);
806 if (get_exporter(transport
, &exporter
, &revlist_args
))
807 die("Couldn't run fast-export");
809 if (finish_command(&exporter
))
810 die("Error while running fast-export");
811 push_update_refs_status(data
, remote_refs
);
815 static int push_refs(struct transport
*transport
,
816 struct ref
*remote_refs
, int flags
)
818 struct helper_data
*data
= transport
->data
;
820 if (process_connect(transport
, 1)) {
821 do_take_over(transport
);
822 return transport
->push_refs(transport
, remote_refs
, flags
);
826 fprintf(stderr
, "No refs in common and none specified; doing nothing.\n"
827 "Perhaps you should specify a branch such as 'master'.\n");
832 return push_refs_with_push(transport
, remote_refs
, flags
);
835 return push_refs_with_export(transport
, remote_refs
, flags
);
841 static int has_attribute(const char *attrs
, const char *attr
) {
848 const char *space
= strchrnul(attrs
, ' ');
849 if (len
== space
- attrs
&& !strncmp(attrs
, attr
, len
))
857 static struct ref
*get_refs_list(struct transport
*transport
, int for_push
)
859 struct helper_data
*data
= transport
->data
;
860 struct child_process
*helper
;
861 struct ref
*ret
= NULL
;
862 struct ref
**tail
= &ret
;
864 struct strbuf buf
= STRBUF_INIT
;
866 helper
= get_helper(transport
);
868 if (process_connect(transport
, for_push
)) {
869 do_take_over(transport
);
870 return transport
->get_refs_list(transport
, for_push
);
873 if (data
->push
&& for_push
)
874 write_str_in_full(helper
->in
, "list for-push\n");
876 write_str_in_full(helper
->in
, "list\n");
880 recvline(data
, &buf
);
885 eov
= strchr(buf
.buf
, ' ');
887 die("Malformed response in ref list: %s", buf
.buf
);
888 eon
= strchr(eov
+ 1, ' ');
892 *tail
= alloc_ref(eov
+ 1);
893 if (buf
.buf
[0] == '@')
894 (*tail
)->symref
= xstrdup(buf
.buf
+ 1);
895 else if (buf
.buf
[0] != '?')
896 get_sha1_hex(buf
.buf
, (*tail
)->old_sha1
);
898 if (has_attribute(eon
+ 1, "unchanged")) {
899 (*tail
)->status
|= REF_STATUS_UPTODATE
;
900 read_ref((*tail
)->name
, (*tail
)->old_sha1
);
903 tail
= &((*tail
)->next
);
906 fprintf(stderr
, "Debug: Read ref listing.\n");
907 strbuf_release(&buf
);
909 for (posn
= ret
; posn
; posn
= posn
->next
)
910 resolve_remote_symref(posn
, ret
);
915 int transport_helper_init(struct transport
*transport
, const char *name
)
917 struct helper_data
*data
= xcalloc(sizeof(*data
), 1);
920 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
923 transport
->data
= data
;
924 transport
->set_option
= set_helper_option
;
925 transport
->get_refs_list
= get_refs_list
;
926 transport
->fetch
= fetch
;
927 transport
->push_refs
= push_refs
;
928 transport
->disconnect
= release_helper
;
929 transport
->connect
= connect_helper
;
930 transport
->smart_options
= &(data
->transport_options
);
935 * Linux pipes can buffer 65536 bytes at once (and most platforms can
936 * buffer less), so attempt reads and writes with up to that size.
938 #define BUFFERSIZE 65536
939 /* This should be enough to hold debugging message. */
940 #define PBUFFERSIZE 8192
942 /* Print bidirectional transfer loop debug message. */
943 static void transfer_debug(const char *fmt
, ...)
946 char msgbuf
[PBUFFERSIZE
];
947 static int debug_enabled
= -1;
949 if (debug_enabled
< 0)
950 debug_enabled
= getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
955 vsnprintf(msgbuf
, PBUFFERSIZE
, fmt
, args
);
957 fprintf(stderr
, "Transfer loop debugging: %s\n", msgbuf
);
960 /* Stream state: More data may be coming in this direction. */
961 #define SSTATE_TRANSFERING 0
963 * Stream state: No more data coming in this direction, flushing rest of
966 #define SSTATE_FLUSHING 1
967 /* Stream state: Transfer in this direction finished. */
968 #define SSTATE_FINISHED 2
970 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
971 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
972 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
974 /* Unidirectional transfer. */
975 struct unidirectional_transfer
{
980 /* Is source socket? */
982 /* Is destination socket? */
984 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
987 char buf
[BUFFERSIZE
];
990 /* Name of source. */
991 const char *src_name
;
992 /* Name of destination. */
993 const char *dest_name
;
996 /* Closes the target (for writing) if transfer has finished. */
997 static void udt_close_if_finished(struct unidirectional_transfer
*t
)
999 if (STATE_NEEDS_CLOSING(t
->state
) && !t
->bufuse
) {
1000 t
->state
= SSTATE_FINISHED
;
1001 if (t
->dest_is_sock
)
1002 shutdown(t
->dest
, SHUT_WR
);
1005 transfer_debug("Closed %s.", t
->dest_name
);
1010 * Tries to read read data from source into buffer. If buffer is full,
1011 * no data is read. Returns 0 on success, -1 on error.
1013 static int udt_do_read(struct unidirectional_transfer
*t
)
1017 if (t
->bufuse
== BUFFERSIZE
)
1018 return 0; /* No space for more. */
1020 transfer_debug("%s is readable", t
->src_name
);
1021 bytes
= read(t
->src
, t
->buf
+ t
->bufuse
, BUFFERSIZE
- t
->bufuse
);
1022 if (bytes
< 0 && errno
!= EWOULDBLOCK
&& errno
!= EAGAIN
&&
1024 error("read(%s) failed: %s", t
->src_name
, strerror(errno
));
1026 } else if (bytes
== 0) {
1027 transfer_debug("%s EOF (with %i bytes in buffer)",
1028 t
->src_name
, t
->bufuse
);
1029 t
->state
= SSTATE_FLUSHING
;
1030 } else if (bytes
> 0) {
1032 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1033 (int)bytes
, t
->src_name
, (int)t
->bufuse
);
1038 /* Tries to write data from buffer into destination. If buffer is empty,
1039 * no data is written. Returns 0 on success, -1 on error.
1041 static int udt_do_write(struct unidirectional_transfer
*t
)
1046 return 0; /* Nothing to write. */
1048 transfer_debug("%s is writable", t
->dest_name
);
1049 bytes
= write(t
->dest
, t
->buf
, t
->bufuse
);
1050 if (bytes
< 0 && errno
!= EWOULDBLOCK
&& errno
!= EAGAIN
&&
1052 error("write(%s) failed: %s", t
->dest_name
, strerror(errno
));
1054 } else if (bytes
> 0) {
1057 memmove(t
->buf
, t
->buf
+ bytes
, t
->bufuse
);
1058 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1059 (int)bytes
, t
->dest_name
, (int)t
->bufuse
);
1065 /* State of bidirectional transfer loop. */
1066 struct bidirectional_transfer_state
{
1067 /* Direction from program to git. */
1068 struct unidirectional_transfer ptg
;
1069 /* Direction from git to program. */
1070 struct unidirectional_transfer gtp
;
1073 static void *udt_copy_task_routine(void *udt
)
1075 struct unidirectional_transfer
*t
= (struct unidirectional_transfer
*)udt
;
1076 while (t
->state
!= SSTATE_FINISHED
) {
1077 if (STATE_NEEDS_READING(t
->state
))
1080 if (STATE_NEEDS_WRITING(t
->state
))
1081 if (udt_do_write(t
))
1083 if (STATE_NEEDS_CLOSING(t
->state
))
1084 udt_close_if_finished(t
);
1086 return udt
; /* Just some non-NULL value. */
1092 * Join thread, with apporiate errors on failure. Name is name for the
1093 * thread (for error messages). Returns 0 on success, 1 on failure.
1095 static int tloop_join(pthread_t thread
, const char *name
)
1099 err
= pthread_join(thread
, &tret
);
1101 error("%s thread failed", name
);
1105 error("%s thread failed to join: %s", name
, strerror(err
));
1112 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1115 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state
*s
)
1117 pthread_t gtp_thread
;
1118 pthread_t ptg_thread
;
1121 err
= pthread_create(>p_thread
, NULL
, udt_copy_task_routine
,
1124 die("Can't start thread for copying data: %s", strerror(err
));
1125 err
= pthread_create(&ptg_thread
, NULL
, udt_copy_task_routine
,
1128 die("Can't start thread for copying data: %s", strerror(err
));
1130 ret
|= tloop_join(gtp_thread
, "Git to program copy");
1131 ret
|= tloop_join(ptg_thread
, "Program to git copy");
1136 /* Close the source and target (for writing) for transfer. */
1137 static void udt_kill_transfer(struct unidirectional_transfer
*t
)
1139 t
->state
= SSTATE_FINISHED
;
1141 * Socket read end left open isn't a disaster if nobody
1142 * attempts to read from it (mingw compat headers do not
1145 * We can't fully close the socket since otherwise gtp
1146 * task would first close the socket it sends data to
1147 * while closing the ptg file descriptors.
1149 if (!t
->src_is_sock
)
1151 if (t
->dest_is_sock
)
1152 shutdown(t
->dest
, SHUT_WR
);
1158 * Join process, with apporiate errors on failure. Name is name for the
1159 * process (for error messages). Returns 0 on success, 1 on failure.
1161 static int tloop_join(pid_t pid
, const char *name
)
1164 if (waitpid(pid
, &tret
, 0) < 0) {
1165 error("%s process failed to wait: %s", name
, strerror(errno
));
1168 if (!WIFEXITED(tret
) || WEXITSTATUS(tret
)) {
1169 error("%s process failed", name
);
1176 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1179 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state
*s
)
1184 /* Fork thread #1: git to program. */
1187 die_errno("Can't start thread for copying data");
1188 else if (pid1
== 0) {
1189 udt_kill_transfer(&s
->ptg
);
1190 exit(udt_copy_task_routine(&s
->gtp
) ? 0 : 1);
1193 /* Fork thread #2: program to git. */
1196 die_errno("Can't start thread for copying data");
1197 else if (pid2
== 0) {
1198 udt_kill_transfer(&s
->gtp
);
1199 exit(udt_copy_task_routine(&s
->ptg
) ? 0 : 1);
1203 * Close both streams in parent as to not interfere with
1204 * end of file detection and wait for both tasks to finish.
1206 udt_kill_transfer(&s
->gtp
);
1207 udt_kill_transfer(&s
->ptg
);
1208 ret
|= tloop_join(pid1
, "Git to program copy");
1209 ret
|= tloop_join(pid2
, "Program to git copy");
1215 * Copies data from stdin to output and from input to stdout simultaneously.
1216 * Additionally filtering through given filter. If filter is NULL, uses
1219 int bidirectional_transfer_loop(int input
, int output
)
1221 struct bidirectional_transfer_state state
;
1223 /* Fill the state fields. */
1224 state
.ptg
.src
= input
;
1226 state
.ptg
.src_is_sock
= (input
== output
);
1227 state
.ptg
.dest_is_sock
= 0;
1228 state
.ptg
.state
= SSTATE_TRANSFERING
;
1229 state
.ptg
.bufuse
= 0;
1230 state
.ptg
.src_name
= "remote input";
1231 state
.ptg
.dest_name
= "stdout";
1234 state
.gtp
.dest
= output
;
1235 state
.gtp
.src_is_sock
= 0;
1236 state
.gtp
.dest_is_sock
= (input
== output
);
1237 state
.gtp
.state
= SSTATE_TRANSFERING
;
1238 state
.gtp
.bufuse
= 0;
1239 state
.gtp
.src_name
= "stdin";
1240 state
.gtp
.dest_name
= "remote output";
1242 return tloop_spawnwait_tasks(&state
);