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
]);
218 strbuf_release(&buf
);
220 fprintf(stderr
, "Debug: Capabilities complete.\n");
224 static int disconnect_helper(struct transport
*transport
)
226 struct helper_data
*data
= transport
->data
;
231 fprintf(stderr
, "Debug: Disconnecting.\n");
232 if (!data
->no_disconnect_req
) {
234 * Ignore write errors; there's nothing we can do,
235 * since we're about to close the pipe anyway. And the
236 * most likely error is EPIPE due to the helper dying
237 * to report an error itself.
239 sigchain_push(SIGPIPE
, SIG_IGN
);
240 xwrite(data
->helper
->in
, "\n", 1);
241 sigchain_pop(SIGPIPE
);
243 close(data
->helper
->in
);
244 close(data
->helper
->out
);
246 res
= finish_command(data
->helper
);
247 argv_array_free_detached(data
->helper
->argv
);
254 static const char *unsupported_options
[] = {
255 TRANS_OPT_UPLOADPACK
,
256 TRANS_OPT_RECEIVEPACK
,
260 static const char *boolean_options
[] = {
266 static int set_helper_option(struct transport
*transport
,
267 const char *name
, const char *value
)
269 struct helper_data
*data
= transport
->data
;
270 struct strbuf buf
= STRBUF_INIT
;
271 int i
, ret
, is_bool
= 0;
273 get_helper(transport
);
278 for (i
= 0; i
< ARRAY_SIZE(unsupported_options
); i
++) {
279 if (!strcmp(name
, unsupported_options
[i
]))
283 for (i
= 0; i
< ARRAY_SIZE(boolean_options
); i
++) {
284 if (!strcmp(name
, boolean_options
[i
])) {
290 strbuf_addf(&buf
, "option %s ", name
);
292 strbuf_addstr(&buf
, value
? "true" : "false");
294 quote_c_style(value
, &buf
, NULL
, 0);
295 strbuf_addch(&buf
, '\n');
297 xchgline(data
, &buf
);
299 if (!strcmp(buf
.buf
, "ok"))
301 else if (!prefixcmp(buf
.buf
, "error")) {
303 } else if (!strcmp(buf
.buf
, "unsupported"))
306 warning("%s unexpectedly said: '%s'", data
->name
, buf
.buf
);
309 strbuf_release(&buf
);
313 static void standard_options(struct transport
*t
)
319 set_helper_option(t
, "progress", t
->progress
? "true" : "false");
321 n
= snprintf(buf
, sizeof(buf
), "%d", v
+ 1);
322 if (n
>= sizeof(buf
))
323 die("impossibly large verbosity value");
324 set_helper_option(t
, "verbosity", buf
);
327 static int release_helper(struct transport
*transport
)
330 struct helper_data
*data
= transport
->data
;
331 free_refspec(data
->refspec_nr
, data
->refspecs
);
332 data
->refspecs
= NULL
;
333 res
= disconnect_helper(transport
);
334 free(transport
->data
);
338 static int fetch_with_fetch(struct transport
*transport
,
339 int nr_heads
, struct ref
**to_fetch
)
341 struct helper_data
*data
= transport
->data
;
343 struct strbuf buf
= STRBUF_INIT
;
345 standard_options(transport
);
347 for (i
= 0; i
< nr_heads
; i
++) {
348 const struct ref
*posn
= to_fetch
[i
];
349 if (posn
->status
& REF_STATUS_UPTODATE
)
352 strbuf_addf(&buf
, "fetch %s %s\n",
353 sha1_to_hex(posn
->old_sha1
), posn
->name
);
356 strbuf_addch(&buf
, '\n');
357 sendline(data
, &buf
);
360 recvline(data
, &buf
);
362 if (!prefixcmp(buf
.buf
, "lock ")) {
363 const char *name
= buf
.buf
+ 5;
364 if (transport
->pack_lockfile
)
365 warning("%s also locked %s", data
->name
, name
);
367 transport
->pack_lockfile
= xstrdup(name
);
372 warning("%s unexpectedly said: '%s'", data
->name
, buf
.buf
);
374 strbuf_release(&buf
);
378 static int get_importer(struct transport
*transport
, struct child_process
*fastimport
)
380 struct child_process
*helper
= get_helper(transport
);
381 struct helper_data
*data
= transport
->data
;
382 struct argv_array argv
= ARGV_ARRAY_INIT
;
383 int cat_blob_fd
, code
;
384 memset(fastimport
, 0, sizeof(*fastimport
));
385 fastimport
->in
= helper
->out
;
386 argv_array_push(&argv
, "fast-import");
387 argv_array_push(&argv
, debug
? "--stats" : "--quiet");
389 if (data
->bidi_import
) {
390 cat_blob_fd
= xdup(helper
->in
);
391 argv_array_pushf(&argv
, "--cat-blob-fd=%d", cat_blob_fd
);
393 fastimport
->argv
= argv
.argv
;
394 fastimport
->git_cmd
= 1;
396 code
= start_command(fastimport
);
400 static int get_exporter(struct transport
*transport
,
401 struct child_process
*fastexport
,
402 struct string_list
*revlist_args
)
404 struct helper_data
*data
= transport
->data
;
405 struct child_process
*helper
= get_helper(transport
);
407 memset(fastexport
, 0, sizeof(*fastexport
));
409 /* we need to duplicate helper->in because we want to use it after
410 * fastexport is done with it. */
411 fastexport
->out
= dup(helper
->in
);
412 fastexport
->argv
= xcalloc(5 + revlist_args
->nr
, sizeof(*fastexport
->argv
));
413 fastexport
->argv
[argc
++] = "fast-export";
414 fastexport
->argv
[argc
++] = "--use-done-feature";
415 if (data
->export_marks
)
416 fastexport
->argv
[argc
++] = data
->export_marks
;
417 if (data
->import_marks
)
418 fastexport
->argv
[argc
++] = data
->import_marks
;
420 for (i
= 0; i
< revlist_args
->nr
; i
++)
421 fastexport
->argv
[argc
++] = revlist_args
->items
[i
].string
;
423 fastexport
->git_cmd
= 1;
424 return start_command(fastexport
);
427 static int fetch_with_import(struct transport
*transport
,
428 int nr_heads
, struct ref
**to_fetch
)
430 struct child_process fastimport
;
431 struct helper_data
*data
= transport
->data
;
434 struct strbuf buf
= STRBUF_INIT
;
436 get_helper(transport
);
438 if (get_importer(transport
, &fastimport
))
439 die("Couldn't run fast-import");
441 for (i
= 0; i
< nr_heads
; i
++) {
443 if (posn
->status
& REF_STATUS_UPTODATE
)
446 strbuf_addf(&buf
, "import %s\n", posn
->name
);
447 sendline(data
, &buf
);
451 write_constant(data
->helper
->in
, "\n");
453 * remote-helpers that advertise the bidi-import capability are required to
454 * buffer the complete batch of import commands until this newline before
455 * sending data to fast-import.
456 * These helpers read back data from fast-import on their stdin, which could
457 * be mixed with import commands, otherwise.
460 if (finish_command(&fastimport
))
461 die("Error while running fast-import");
462 argv_array_free_detached(fastimport
.argv
);
465 * The fast-import stream of a remote helper that advertises
466 * the "refspec" capability writes to the refs named after the
467 * right hand side of the first refspec matching each ref we
470 * (If no "refspec" capability was specified, for historical
471 * reasons we default to *:*.)
473 * Store the result in to_fetch[i].old_sha1. Callers such
474 * as "git fetch" can use the value to write feedback to the
475 * terminal, populate FETCH_HEAD, and determine what new value
476 * should be written to peer_ref if the update is a
477 * fast-forward or this is a forced update.
479 for (i
= 0; i
< nr_heads
; i
++) {
482 if (posn
->status
& REF_STATUS_UPTODATE
)
485 private = apply_refspecs(data
->refspecs
, data
->refspec_nr
, posn
->name
);
487 private = xstrdup(posn
->name
);
489 read_ref(private, posn
->old_sha1
);
493 strbuf_release(&buf
);
497 static int process_connect_service(struct transport
*transport
,
498 const char *name
, const char *exec
)
500 struct helper_data
*data
= transport
->data
;
501 struct strbuf cmdbuf
= STRBUF_INIT
;
502 struct child_process
*helper
;
503 int r
, duped
, ret
= 0;
506 helper
= get_helper(transport
);
509 * Yes, dup the pipe another time, as we need unbuffered version
510 * of input pipe as FILE*. fclose() closes the underlying fd and
511 * stream buffering only can be changed before first I/O operation
514 duped
= dup(helper
->out
);
516 die_errno("Can't dup helper output fd");
517 input
= xfdopen(duped
, "r");
518 setvbuf(input
, NULL
, _IONBF
, 0);
521 * Handle --upload-pack and friends. This is fire and forget...
522 * just warn if it fails.
524 if (strcmp(name
, exec
)) {
525 r
= set_helper_option(transport
, "servpath", exec
);
527 warning("Setting remote service path not supported by protocol.");
529 warning("Invalid remote service path.");
533 strbuf_addf(&cmdbuf
, "connect %s\n", name
);
537 sendline(data
, &cmdbuf
);
538 recvline_fh(input
, &cmdbuf
);
539 if (!strcmp(cmdbuf
.buf
, "")) {
540 data
->no_disconnect_req
= 1;
542 fprintf(stderr
, "Debug: Smart transport connection "
545 } else if (!strcmp(cmdbuf
.buf
, "fallback")) {
547 fprintf(stderr
, "Debug: Falling back to dumb "
550 die("Unknown response to connect: %s",
558 static int process_connect(struct transport
*transport
,
561 struct helper_data
*data
= transport
->data
;
565 name
= for_push
? "git-receive-pack" : "git-upload-pack";
567 exec
= data
->transport_options
.receivepack
;
569 exec
= data
->transport_options
.uploadpack
;
571 return process_connect_service(transport
, name
, exec
);
574 static int connect_helper(struct transport
*transport
, const char *name
,
575 const char *exec
, int fd
[2])
577 struct helper_data
*data
= transport
->data
;
579 /* Get_helper so connect is inited. */
580 get_helper(transport
);
582 die("Operation not supported by protocol.");
584 if (!process_connect_service(transport
, name
, exec
))
585 die("Can't connect to subservice %s.", name
);
587 fd
[0] = data
->helper
->out
;
588 fd
[1] = data
->helper
->in
;
592 static int fetch(struct transport
*transport
,
593 int nr_heads
, struct ref
**to_fetch
)
595 struct helper_data
*data
= transport
->data
;
598 if (process_connect(transport
, 0)) {
599 do_take_over(transport
);
600 return transport
->fetch(transport
, nr_heads
, to_fetch
);
604 for (i
= 0; i
< nr_heads
; i
++)
605 if (!(to_fetch
[i
]->status
& REF_STATUS_UPTODATE
))
612 return fetch_with_fetch(transport
, nr_heads
, to_fetch
);
615 return fetch_with_import(transport
, nr_heads
, to_fetch
);
620 static void push_update_ref_status(struct strbuf
*buf
,
622 struct ref
*remote_refs
)
627 if (!prefixcmp(buf
->buf
, "ok ")) {
628 status
= REF_STATUS_OK
;
629 refname
= buf
->buf
+ 3;
630 } else if (!prefixcmp(buf
->buf
, "error ")) {
631 status
= REF_STATUS_REMOTE_REJECT
;
632 refname
= buf
->buf
+ 6;
634 die("expected ok/error, helper said '%s'", buf
->buf
);
636 msg
= strchr(refname
, ' ');
638 struct strbuf msg_buf
= STRBUF_INIT
;
642 if (!unquote_c_style(&msg_buf
, msg
, &end
))
643 msg
= strbuf_detach(&msg_buf
, NULL
);
646 strbuf_release(&msg_buf
);
648 if (!strcmp(msg
, "no match")) {
649 status
= REF_STATUS_NONE
;
653 else if (!strcmp(msg
, "up to date")) {
654 status
= REF_STATUS_UPTODATE
;
658 else if (!strcmp(msg
, "non-fast forward")) {
659 status
= REF_STATUS_REJECT_NONFASTFORWARD
;
663 else if (!strcmp(msg
, "already exists")) {
664 status
= REF_STATUS_REJECT_ALREADY_EXISTS
;
668 else if (!strcmp(msg
, "fetch first")) {
669 status
= REF_STATUS_REJECT_FETCH_FIRST
;
673 else if (!strcmp(msg
, "needs force")) {
674 status
= REF_STATUS_REJECT_NEEDS_FORCE
;
681 *ref
= find_ref_by_name(*ref
, refname
);
683 *ref
= find_ref_by_name(remote_refs
, refname
);
685 warning("helper reported unexpected status of %s", refname
);
689 if ((*ref
)->status
!= REF_STATUS_NONE
) {
691 * Earlier, the ref was marked not to be pushed, so ignore the ref
692 * status reported by the remote helper if the latter is 'no match'.
694 if (status
== REF_STATUS_NONE
)
698 (*ref
)->status
= status
;
699 (*ref
)->remote_status
= msg
;
702 static void push_update_refs_status(struct helper_data
*data
,
703 struct ref
*remote_refs
)
705 struct strbuf buf
= STRBUF_INIT
;
706 struct ref
*ref
= remote_refs
;
708 recvline(data
, &buf
);
712 push_update_ref_status(&buf
, &ref
, remote_refs
);
714 strbuf_release(&buf
);
717 static int push_refs_with_push(struct transport
*transport
,
718 struct ref
*remote_refs
, int flags
)
720 int force_all
= flags
& TRANSPORT_PUSH_FORCE
;
721 int mirror
= flags
& TRANSPORT_PUSH_MIRROR
;
722 struct helper_data
*data
= transport
->data
;
723 struct strbuf buf
= STRBUF_INIT
;
726 get_helper(transport
);
730 for (ref
= remote_refs
; ref
; ref
= ref
->next
) {
731 if (!ref
->peer_ref
&& !mirror
)
734 /* Check for statuses set by set_ref_status_for_push() */
735 switch (ref
->status
) {
736 case REF_STATUS_REJECT_NONFASTFORWARD
:
737 case REF_STATUS_REJECT_ALREADY_EXISTS
:
738 case REF_STATUS_UPTODATE
:
747 strbuf_addstr(&buf
, "push ");
748 if (!ref
->deletion
) {
750 strbuf_addch(&buf
, '+');
752 strbuf_addstr(&buf
, ref
->peer_ref
->name
);
754 strbuf_addstr(&buf
, sha1_to_hex(ref
->new_sha1
));
756 strbuf_addch(&buf
, ':');
757 strbuf_addstr(&buf
, ref
->name
);
758 strbuf_addch(&buf
, '\n');
763 standard_options(transport
);
765 if (flags
& TRANSPORT_PUSH_DRY_RUN
) {
766 if (set_helper_option(transport
, "dry-run", "true") != 0)
767 die("helper %s does not support dry-run", data
->name
);
770 strbuf_addch(&buf
, '\n');
771 sendline(data
, &buf
);
772 strbuf_release(&buf
);
774 push_update_refs_status(data
, remote_refs
);
778 static int push_refs_with_export(struct transport
*transport
,
779 struct ref
*remote_refs
, int flags
)
782 struct child_process
*helper
, exporter
;
783 struct helper_data
*data
= transport
->data
;
784 struct string_list revlist_args
= STRING_LIST_INIT_NODUP
;
785 struct strbuf buf
= STRBUF_INIT
;
787 helper
= get_helper(transport
);
789 write_constant(helper
->in
, "export\n");
793 for (ref
= remote_refs
; ref
; ref
= ref
->next
) {
795 unsigned char sha1
[20];
799 private = apply_refspecs(data
->refspecs
, data
->refspec_nr
, ref
->name
);
800 if (private && !get_sha1(private, sha1
)) {
801 strbuf_addf(&buf
, "^%s", private);
802 string_list_append(&revlist_args
, strbuf_detach(&buf
, NULL
));
807 die("remote-helpers do not support ref deletion");
811 string_list_append(&revlist_args
, ref
->peer_ref
->name
);
815 if (get_exporter(transport
, &exporter
, &revlist_args
))
816 die("Couldn't run fast-export");
818 if (finish_command(&exporter
))
819 die("Error while running fast-export");
820 push_update_refs_status(data
, remote_refs
);
824 static int push_refs(struct transport
*transport
,
825 struct ref
*remote_refs
, int flags
)
827 struct helper_data
*data
= transport
->data
;
829 if (process_connect(transport
, 1)) {
830 do_take_over(transport
);
831 return transport
->push_refs(transport
, remote_refs
, flags
);
835 fprintf(stderr
, "No refs in common and none specified; doing nothing.\n"
836 "Perhaps you should specify a branch such as 'master'.\n");
841 return push_refs_with_push(transport
, remote_refs
, flags
);
844 return push_refs_with_export(transport
, remote_refs
, flags
);
850 static int has_attribute(const char *attrs
, const char *attr
) {
857 const char *space
= strchrnul(attrs
, ' ');
858 if (len
== space
- attrs
&& !strncmp(attrs
, attr
, len
))
866 static struct ref
*get_refs_list(struct transport
*transport
, int for_push
)
868 struct helper_data
*data
= transport
->data
;
869 struct child_process
*helper
;
870 struct ref
*ret
= NULL
;
871 struct ref
**tail
= &ret
;
873 struct strbuf buf
= STRBUF_INIT
;
875 helper
= get_helper(transport
);
877 if (process_connect(transport
, for_push
)) {
878 do_take_over(transport
);
879 return transport
->get_refs_list(transport
, for_push
);
882 if (data
->push
&& for_push
)
883 write_str_in_full(helper
->in
, "list for-push\n");
885 write_str_in_full(helper
->in
, "list\n");
889 recvline(data
, &buf
);
894 eov
= strchr(buf
.buf
, ' ');
896 die("Malformed response in ref list: %s", buf
.buf
);
897 eon
= strchr(eov
+ 1, ' ');
901 *tail
= alloc_ref(eov
+ 1);
902 if (buf
.buf
[0] == '@')
903 (*tail
)->symref
= xstrdup(buf
.buf
+ 1);
904 else if (buf
.buf
[0] != '?')
905 get_sha1_hex(buf
.buf
, (*tail
)->old_sha1
);
907 if (has_attribute(eon
+ 1, "unchanged")) {
908 (*tail
)->status
|= REF_STATUS_UPTODATE
;
909 read_ref((*tail
)->name
, (*tail
)->old_sha1
);
912 tail
= &((*tail
)->next
);
915 fprintf(stderr
, "Debug: Read ref listing.\n");
916 strbuf_release(&buf
);
918 for (posn
= ret
; posn
; posn
= posn
->next
)
919 resolve_remote_symref(posn
, ret
);
924 int transport_helper_init(struct transport
*transport
, const char *name
)
926 struct helper_data
*data
= xcalloc(sizeof(*data
), 1);
929 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
932 transport
->data
= data
;
933 transport
->set_option
= set_helper_option
;
934 transport
->get_refs_list
= get_refs_list
;
935 transport
->fetch
= fetch
;
936 transport
->push_refs
= push_refs
;
937 transport
->disconnect
= release_helper
;
938 transport
->connect
= connect_helper
;
939 transport
->smart_options
= &(data
->transport_options
);
944 * Linux pipes can buffer 65536 bytes at once (and most platforms can
945 * buffer less), so attempt reads and writes with up to that size.
947 #define BUFFERSIZE 65536
948 /* This should be enough to hold debugging message. */
949 #define PBUFFERSIZE 8192
951 /* Print bidirectional transfer loop debug message. */
952 static void transfer_debug(const char *fmt
, ...)
955 char msgbuf
[PBUFFERSIZE
];
956 static int debug_enabled
= -1;
958 if (debug_enabled
< 0)
959 debug_enabled
= getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
964 vsnprintf(msgbuf
, PBUFFERSIZE
, fmt
, args
);
966 fprintf(stderr
, "Transfer loop debugging: %s\n", msgbuf
);
969 /* Stream state: More data may be coming in this direction. */
970 #define SSTATE_TRANSFERING 0
972 * Stream state: No more data coming in this direction, flushing rest of
975 #define SSTATE_FLUSHING 1
976 /* Stream state: Transfer in this direction finished. */
977 #define SSTATE_FINISHED 2
979 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
980 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
981 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
983 /* Unidirectional transfer. */
984 struct unidirectional_transfer
{
989 /* Is source socket? */
991 /* Is destination socket? */
993 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
996 char buf
[BUFFERSIZE
];
999 /* Name of source. */
1000 const char *src_name
;
1001 /* Name of destination. */
1002 const char *dest_name
;
1005 /* Closes the target (for writing) if transfer has finished. */
1006 static void udt_close_if_finished(struct unidirectional_transfer
*t
)
1008 if (STATE_NEEDS_CLOSING(t
->state
) && !t
->bufuse
) {
1009 t
->state
= SSTATE_FINISHED
;
1010 if (t
->dest_is_sock
)
1011 shutdown(t
->dest
, SHUT_WR
);
1014 transfer_debug("Closed %s.", t
->dest_name
);
1019 * Tries to read read data from source into buffer. If buffer is full,
1020 * no data is read. Returns 0 on success, -1 on error.
1022 static int udt_do_read(struct unidirectional_transfer
*t
)
1026 if (t
->bufuse
== BUFFERSIZE
)
1027 return 0; /* No space for more. */
1029 transfer_debug("%s is readable", t
->src_name
);
1030 bytes
= read(t
->src
, t
->buf
+ t
->bufuse
, BUFFERSIZE
- t
->bufuse
);
1031 if (bytes
< 0 && errno
!= EWOULDBLOCK
&& errno
!= EAGAIN
&&
1033 error("read(%s) failed: %s", t
->src_name
, strerror(errno
));
1035 } else if (bytes
== 0) {
1036 transfer_debug("%s EOF (with %i bytes in buffer)",
1037 t
->src_name
, t
->bufuse
);
1038 t
->state
= SSTATE_FLUSHING
;
1039 } else if (bytes
> 0) {
1041 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1042 (int)bytes
, t
->src_name
, (int)t
->bufuse
);
1047 /* Tries to write data from buffer into destination. If buffer is empty,
1048 * no data is written. Returns 0 on success, -1 on error.
1050 static int udt_do_write(struct unidirectional_transfer
*t
)
1055 return 0; /* Nothing to write. */
1057 transfer_debug("%s is writable", t
->dest_name
);
1058 bytes
= write(t
->dest
, t
->buf
, t
->bufuse
);
1059 if (bytes
< 0 && errno
!= EWOULDBLOCK
&& errno
!= EAGAIN
&&
1061 error("write(%s) failed: %s", t
->dest_name
, strerror(errno
));
1063 } else if (bytes
> 0) {
1066 memmove(t
->buf
, t
->buf
+ bytes
, t
->bufuse
);
1067 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1068 (int)bytes
, t
->dest_name
, (int)t
->bufuse
);
1074 /* State of bidirectional transfer loop. */
1075 struct bidirectional_transfer_state
{
1076 /* Direction from program to git. */
1077 struct unidirectional_transfer ptg
;
1078 /* Direction from git to program. */
1079 struct unidirectional_transfer gtp
;
1082 static void *udt_copy_task_routine(void *udt
)
1084 struct unidirectional_transfer
*t
= (struct unidirectional_transfer
*)udt
;
1085 while (t
->state
!= SSTATE_FINISHED
) {
1086 if (STATE_NEEDS_READING(t
->state
))
1089 if (STATE_NEEDS_WRITING(t
->state
))
1090 if (udt_do_write(t
))
1092 if (STATE_NEEDS_CLOSING(t
->state
))
1093 udt_close_if_finished(t
);
1095 return udt
; /* Just some non-NULL value. */
1101 * Join thread, with apporiate errors on failure. Name is name for the
1102 * thread (for error messages). Returns 0 on success, 1 on failure.
1104 static int tloop_join(pthread_t thread
, const char *name
)
1108 err
= pthread_join(thread
, &tret
);
1110 error("%s thread failed", name
);
1114 error("%s thread failed to join: %s", name
, strerror(err
));
1121 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1124 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state
*s
)
1126 pthread_t gtp_thread
;
1127 pthread_t ptg_thread
;
1130 err
= pthread_create(>p_thread
, NULL
, udt_copy_task_routine
,
1133 die("Can't start thread for copying data: %s", strerror(err
));
1134 err
= pthread_create(&ptg_thread
, NULL
, udt_copy_task_routine
,
1137 die("Can't start thread for copying data: %s", strerror(err
));
1139 ret
|= tloop_join(gtp_thread
, "Git to program copy");
1140 ret
|= tloop_join(ptg_thread
, "Program to git copy");
1145 /* Close the source and target (for writing) for transfer. */
1146 static void udt_kill_transfer(struct unidirectional_transfer
*t
)
1148 t
->state
= SSTATE_FINISHED
;
1150 * Socket read end left open isn't a disaster if nobody
1151 * attempts to read from it (mingw compat headers do not
1154 * We can't fully close the socket since otherwise gtp
1155 * task would first close the socket it sends data to
1156 * while closing the ptg file descriptors.
1158 if (!t
->src_is_sock
)
1160 if (t
->dest_is_sock
)
1161 shutdown(t
->dest
, SHUT_WR
);
1167 * Join process, with apporiate errors on failure. Name is name for the
1168 * process (for error messages). Returns 0 on success, 1 on failure.
1170 static int tloop_join(pid_t pid
, const char *name
)
1173 if (waitpid(pid
, &tret
, 0) < 0) {
1174 error("%s process failed to wait: %s", name
, strerror(errno
));
1177 if (!WIFEXITED(tret
) || WEXITSTATUS(tret
)) {
1178 error("%s process failed", name
);
1185 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1188 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state
*s
)
1193 /* Fork thread #1: git to program. */
1196 die_errno("Can't start thread for copying data");
1197 else if (pid1
== 0) {
1198 udt_kill_transfer(&s
->ptg
);
1199 exit(udt_copy_task_routine(&s
->gtp
) ? 0 : 1);
1202 /* Fork thread #2: program to git. */
1205 die_errno("Can't start thread for copying data");
1206 else if (pid2
== 0) {
1207 udt_kill_transfer(&s
->gtp
);
1208 exit(udt_copy_task_routine(&s
->ptg
) ? 0 : 1);
1212 * Close both streams in parent as to not interfere with
1213 * end of file detection and wait for both tasks to finish.
1215 udt_kill_transfer(&s
->gtp
);
1216 udt_kill_transfer(&s
->ptg
);
1217 ret
|= tloop_join(pid1
, "Git to program copy");
1218 ret
|= tloop_join(pid2
, "Program to git copy");
1224 * Copies data from stdin to output and from input to stdout simultaneously.
1225 * Additionally filtering through given filter. If filter is NULL, uses
1228 int bidirectional_transfer_loop(int input
, int output
)
1230 struct bidirectional_transfer_state state
;
1232 /* Fill the state fields. */
1233 state
.ptg
.src
= input
;
1235 state
.ptg
.src_is_sock
= (input
== output
);
1236 state
.ptg
.dest_is_sock
= 0;
1237 state
.ptg
.state
= SSTATE_TRANSFERING
;
1238 state
.ptg
.bufuse
= 0;
1239 state
.ptg
.src_name
= "remote input";
1240 state
.ptg
.dest_name
= "stdout";
1243 state
.gtp
.dest
= output
;
1244 state
.gtp
.src_is_sock
= 0;
1245 state
.gtp
.dest_is_sock
= (input
== output
);
1246 state
.gtp
.state
= SSTATE_TRANSFERING
;
1247 state
.gtp
.bufuse
= 0;
1248 state
.gtp
.src_name
= "stdin";
1249 state
.gtp
.dest_name
= "remote output";
1251 return tloop_spawnwait_tasks(&state
);