]> git.ipfire.org Git - thirdparty/git.git/blame - transport-helper.c
Documentation: mention more worktree-specific exceptions
[thirdparty/git.git] / transport-helper.c
CommitLineData
6eb996b5
DB
1#include "cache.h"
2#include "transport.h"
ae4efe19 3#include "quote.h"
6eb996b5
DB
4#include "run-command.h"
5#include "commit.h"
6#include "diff.h"
7#include "revision.h"
72ff8943 8#include "remote.h"
73b49a75 9#include "string-list.h"
7851b1e6 10#include "thread-utils.h"
c34fe630 11#include "sigchain.h"
bfc366d9 12#include "argv-array.h"
664059fb 13#include "refs.h"
ec0cb496 14#include "refspec.h"
e967ca38 15#include "transport-internal.h"
edc9caf7 16#include "protocol.h"
7851b1e6 17
bf3c523c
IL
18static int debug;
19
9cba13ca 20struct helper_data {
6eb996b5
DB
21 const char *name;
22 struct child_process *helper;
292ce46b 23 FILE *out;
ef08ef9e 24 unsigned fetch : 1,
a24a32dd 25 import : 1,
bfc366d9 26 bidi_import : 1,
73b49a75 27 export : 1,
ae4efe19 28 option : 1,
fa8c097c
IL
29 push : 1,
30 connect : 1,
edc9caf7 31 stateless_connect : 1,
0d957a4d 32 signed_tags : 1,
9ba38048 33 check_connectivity : 1,
597b831a
MM
34 no_disconnect_req : 1,
35 no_private_update : 1;
a515ebe9
SR
36 char *export_marks;
37 char *import_marks;
72ff8943 38 /* These go from remote name (as in "list") to private name */
57f32ac2 39 struct refspec rs;
61b075bd
IL
40 /* Transport options for fetch-pack/send-pack (should one of
41 * those be invoked).
42 */
43 struct git_transport_options transport_options;
6eb996b5
DB
44};
45
bf3c523c
IL
46static void sendline(struct helper_data *helper, struct strbuf *buffer)
47{
48 if (debug)
49 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
06f46f23 50 if (write_in_full(helper->helper->in, buffer->buf, buffer->len) < 0)
6b5b309f 51 die_errno(_("full write to remote helper failed"));
bf3c523c
IL
52}
53
b1c2edfc 54static int recvline_fh(FILE *helper, struct strbuf *buffer)
bf3c523c
IL
55{
56 strbuf_reset(buffer);
57 if (debug)
58 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
692dfdfa 59 if (strbuf_getline(buffer, helper) == EOF) {
bf3c523c
IL
60 if (debug)
61 fprintf(stderr, "Debug: Remote helper quit.\n");
5931b33e 62 return 1;
bf3c523c
IL
63 }
64
65 if (debug)
66 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
67 return 0;
68}
69
fa8c097c
IL
70static int recvline(struct helper_data *helper, struct strbuf *buffer)
71{
b1c2edfc 72 return recvline_fh(helper->out, buffer);
fa8c097c
IL
73}
74
bf3c523c
IL
75static void write_constant(int fd, const char *str)
76{
77 if (debug)
78 fprintf(stderr, "Debug: Remote helper: -> %s", str);
06f46f23 79 if (write_in_full(fd, str, strlen(str)) < 0)
6b5b309f 80 die_errno(_("full write to remote helper failed"));
bf3c523c
IL
81}
82
c2e86add 83static const char *remove_ext_force(const char *url)
25d5cc48
IL
84{
85 if (url) {
86 const char *colon = strchr(url, ':');
87 if (colon && colon[1] == ':')
88 return colon + 2;
89 }
90 return url;
91}
92
fa8c097c
IL
93static void do_take_over(struct transport *transport)
94{
95 struct helper_data *data;
96 data = (struct helper_data *)transport->data;
97 transport_take_over(transport, data->helper);
98 fclose(data->out);
99 free(data);
100}
101
2879bc3b
MH
102static void standard_options(struct transport *t);
103
6eb996b5
DB
104static struct child_process *get_helper(struct transport *transport)
105{
106 struct helper_data *data = transport->data;
107 struct strbuf buf = STRBUF_INIT;
108 struct child_process *helper;
61b075bd 109 int duped;
6b02de3b 110 int code;
6eb996b5
DB
111
112 if (data->helper)
113 return data->helper;
114
483bbd4e
RS
115 helper = xmalloc(sizeof(*helper));
116 child_process_init(helper);
6eb996b5
DB
117 helper->in = -1;
118 helper->out = -1;
119 helper->err = 0;
e0ab2ac6
JK
120 argv_array_pushf(&helper->args, "git-remote-%s", data->name);
121 argv_array_push(&helper->args, transport->remote->name);
122 argv_array_push(&helper->args, remove_ext_force(transport->url));
6b02de3b
IL
123 helper->git_cmd = 0;
124 helper->silent_exec_failure = 1;
e1735872 125
4b0c3c77
JN
126 if (have_git_dir())
127 argv_array_pushf(&helper->env_array, "%s=%s",
128 GIT_DIR_ENVIRONMENT, get_git_dir());
e1735872 129
abd81a3d
JH
130 helper->trace2_child_class = helper->args.argv[0]; /* "remote-<name>" */
131
6b02de3b
IL
132 code = start_command(helper);
133 if (code < 0 && errno == ENOENT)
6b5b309f 134 die(_("unable to find remote helper for '%s'"), data->name);
6b02de3b
IL
135 else if (code != 0)
136 exit(code);
137
6eb996b5 138 data->helper = helper;
fa8c097c 139 data->no_disconnect_req = 0;
57f32ac2 140 refspec_init(&data->rs, REFSPEC_FETCH);
6eb996b5 141
61b075bd 142 /*
1a0c8dfd
JH
143 * Open the output as FILE* so strbuf_getline_*() family of
144 * functions can be used.
61b075bd
IL
145 * Do this with duped fd because fclose() will close the fd,
146 * and stuff like taking over will require the fd to remain.
61b075bd
IL
147 */
148 duped = dup(helper->out);
149 if (duped < 0)
6b5b309f 150 die_errno(_("can't dup helper output fd"));
61b075bd
IL
151 data->out = xfdopen(duped, "r");
152
bf3c523c 153 write_constant(helper->in, "capabilities\n");
2d14d65c 154
6eb996b5 155 while (1) {
21a2d4ad 156 const char *capname, *arg;
28ed5b35 157 int mandatory = 0;
5931b33e
FC
158 if (recvline(data, &buf))
159 exit(128);
6eb996b5
DB
160
161 if (!*buf.buf)
162 break;
28ed5b35
IL
163
164 if (*buf.buf == '*') {
165 capname = buf.buf + 1;
166 mandatory = 1;
167 } else
168 capname = buf.buf;
169
bf3c523c 170 if (debug)
28ed5b35
IL
171 fprintf(stderr, "Debug: Got cap %s\n", capname);
172 if (!strcmp(capname, "fetch"))
6eb996b5 173 data->fetch = 1;
28ed5b35 174 else if (!strcmp(capname, "option"))
ef08ef9e 175 data->option = 1;
28ed5b35 176 else if (!strcmp(capname, "push"))
ae4efe19 177 data->push = 1;
28ed5b35 178 else if (!strcmp(capname, "import"))
e65e91ed 179 data->import = 1;
bfc366d9
FA
180 else if (!strcmp(capname, "bidi-import"))
181 data->bidi_import = 1;
73b49a75
SR
182 else if (!strcmp(capname, "export"))
183 data->export = 1;
9ba38048
NTND
184 else if (!strcmp(capname, "check-connectivity"))
185 data->check_connectivity = 1;
57f32ac2
BW
186 else if (skip_prefix(capname, "refspec ", &arg)) {
187 refspec_append(&data->rs, arg);
fa8c097c
IL
188 } else if (!strcmp(capname, "connect")) {
189 data->connect = 1;
edc9caf7
BW
190 } else if (!strcmp(capname, "stateless-connect")) {
191 data->stateless_connect = 1;
0d957a4d
JK
192 } else if (!strcmp(capname, "signed-tags")) {
193 data->signed_tags = 1;
21a2d4ad
JK
194 } else if (skip_prefix(capname, "export-marks ", &arg)) {
195 data->export_marks = xstrdup(arg);
196 } else if (skip_prefix(capname, "import-marks ", &arg)) {
197 data->import_marks = xstrdup(arg);
59556548 198 } else if (starts_with(capname, "no-private-update")) {
597b831a 199 data->no_private_update = 1;
28ed5b35 200 } else if (mandatory) {
6b5b309f
NTND
201 die(_("unknown mandatory capability %s; this remote "
202 "helper probably needs newer version of Git"),
28ed5b35 203 capname);
72ff8943
DB
204 }
205 }
57f32ac2 206 if (!data->rs.nr && (data->import || data->bidi_import || data->export)) {
6b5b309f 207 warning(_("this remote helper should implement refspec capability"));
6eb996b5 208 }
b962dbdc 209 strbuf_release(&buf);
bf3c523c
IL
210 if (debug)
211 fprintf(stderr, "Debug: Capabilities complete.\n");
2879bc3b 212 standard_options(transport);
6eb996b5
DB
213 return data->helper;
214}
215
216static int disconnect_helper(struct transport *transport)
217{
218 struct helper_data *data = transport->data;
cc567322 219 int res = 0;
bf3c523c 220
6eb996b5 221 if (data->helper) {
bf3c523c
IL
222 if (debug)
223 fprintf(stderr, "Debug: Disconnecting.\n");
fa8c097c 224 if (!data->no_disconnect_req) {
c34fe630
JK
225 /*
226 * Ignore write errors; there's nothing we can do,
227 * since we're about to close the pipe anyway. And the
228 * most likely error is EPIPE due to the helper dying
229 * to report an error itself.
230 */
231 sigchain_push(SIGPIPE, SIG_IGN);
232 xwrite(data->helper->in, "\n", 1);
233 sigchain_pop(SIGPIPE);
fa8c097c 234 }
6eb996b5 235 close(data->helper->in);
61b075bd 236 close(data->helper->out);
292ce46b 237 fclose(data->out);
cc567322 238 res = finish_command(data->helper);
6a83d902 239 FREE_AND_NULL(data->helper);
6eb996b5 240 }
cc567322 241 return res;
6eb996b5
DB
242}
243
ef08ef9e
SP
244static const char *unsupported_options[] = {
245 TRANS_OPT_UPLOADPACK,
246 TRANS_OPT_RECEIVEPACK,
247 TRANS_OPT_THIN,
248 TRANS_OPT_KEEP
249 };
23cd01ec 250
ef08ef9e
SP
251static const char *boolean_options[] = {
252 TRANS_OPT_THIN,
253 TRANS_OPT_KEEP,
0ea47f9d 254 TRANS_OPT_FOLLOWTAGS,
cccf74e2 255 TRANS_OPT_DEEPEN_RELATIVE
ef08ef9e
SP
256 };
257
9318c5dd
NTND
258static int strbuf_set_helper_option(struct helper_data *data,
259 struct strbuf *buf)
260{
261 int ret;
262
263 sendline(data, buf);
264 if (recvline(data, buf))
265 exit(128);
266
267 if (!strcmp(buf->buf, "ok"))
268 ret = 0;
269 else if (starts_with(buf->buf, "error"))
270 ret = -1;
271 else if (!strcmp(buf->buf, "unsupported"))
272 ret = 1;
273 else {
6b5b309f 274 warning(_("%s unexpectedly said: '%s'"), data->name, buf->buf);
9318c5dd
NTND
275 ret = 1;
276 }
277 return ret;
278}
279
a45a2600
NTND
280static int string_list_set_helper_option(struct helper_data *data,
281 const char *name,
282 struct string_list *list)
283{
284 struct strbuf buf = STRBUF_INIT;
285 int i, ret = 0;
286
287 for (i = 0; i < list->nr; i++) {
288 strbuf_addf(&buf, "option %s ", name);
289 quote_c_style(list->items[i].string, &buf, NULL, 0);
290 strbuf_addch(&buf, '\n');
291
292 if ((ret = strbuf_set_helper_option(data, &buf)))
293 break;
294 strbuf_reset(&buf);
295 }
296 strbuf_release(&buf);
297 return ret;
298}
299
ef08ef9e
SP
300static int set_helper_option(struct transport *transport,
301 const char *name, const char *value)
302{
303 struct helper_data *data = transport->data;
ef08ef9e
SP
304 struct strbuf buf = STRBUF_INIT;
305 int i, ret, is_bool = 0;
306
bf3c523c
IL
307 get_helper(transport);
308
ef08ef9e
SP
309 if (!data->option)
310 return 1;
311
a45a2600
NTND
312 if (!strcmp(name, "deepen-not"))
313 return string_list_set_helper_option(data, name,
314 (struct string_list *)value);
315
ef08ef9e
SP
316 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
317 if (!strcmp(name, unsupported_options[i]))
318 return 1;
319 }
320
321 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
322 if (!strcmp(name, boolean_options[i])) {
323 is_bool = 1;
324 break;
325 }
326 }
327
328 strbuf_addf(&buf, "option %s ", name);
329 if (is_bool)
330 strbuf_addstr(&buf, value ? "true" : "false");
331 else
332 quote_c_style(value, &buf, NULL, 0);
333 strbuf_addch(&buf, '\n');
334
9318c5dd 335 ret = strbuf_set_helper_option(data, &buf);
ef08ef9e
SP
336 strbuf_release(&buf);
337 return ret;
338}
339
340static void standard_options(struct transport *t)
341{
342 char buf[16];
ef08ef9e 343 int v = t->verbose;
ef08ef9e 344
d01b3c02 345 set_helper_option(t, "progress", t->progress ? "true" : "false");
ef08ef9e 346
8c5acfb9 347 xsnprintf(buf, sizeof(buf), "%d", v + 1);
ef08ef9e 348 set_helper_option(t, "verbosity", buf);
c915f11e
EW
349
350 switch (t->family) {
351 case TRANSPORT_FAMILY_ALL:
352 /*
353 * this is already the default,
354 * do not break old remote helpers by setting "all" here
355 */
356 break;
357 case TRANSPORT_FAMILY_IPV4:
358 set_helper_option(t, "family", "ipv4");
359 break;
360 case TRANSPORT_FAMILY_IPV6:
361 set_helper_option(t, "family", "ipv6");
362 break;
363 }
ef08ef9e
SP
364}
365
f2a37151
DB
366static int release_helper(struct transport *transport)
367{
cc567322 368 int res = 0;
72ff8943 369 struct helper_data *data = transport->data;
57f32ac2 370 refspec_clear(&data->rs);
cc567322 371 res = disconnect_helper(transport);
f2a37151 372 free(transport->data);
cc567322 373 return res;
f2a37151
DB
374}
375
6eb996b5 376static int fetch_with_fetch(struct transport *transport,
37148311 377 int nr_heads, struct ref **to_fetch)
6eb996b5 378{
292ce46b 379 struct helper_data *data = transport->data;
6eb996b5
DB
380 int i;
381 struct strbuf buf = STRBUF_INIT;
382
383 for (i = 0; i < nr_heads; i++) {
1088261f 384 const struct ref *posn = to_fetch[i];
6eb996b5
DB
385 if (posn->status & REF_STATUS_UPTODATE)
386 continue;
2d14d65c
DB
387
388 strbuf_addf(&buf, "fetch %s %s\n",
f4e54d02 389 oid_to_hex(&posn->old_oid),
33cae542 390 posn->symref ? posn->symref : posn->name);
292ce46b 391 }
2d14d65c 392
292ce46b 393 strbuf_addch(&buf, '\n');
bf3c523c 394 sendline(data, &buf);
292ce46b
SP
395
396 while (1) {
5931b33e
FC
397 if (recvline(data, &buf))
398 exit(128);
292ce46b 399
59556548 400 if (starts_with(buf.buf, "lock ")) {
292ce46b
SP
401 const char *name = buf.buf + 5;
402 if (transport->pack_lockfile)
6b5b309f 403 warning(_("%s also locked %s"), data->name, name);
292ce46b
SP
404 else
405 transport->pack_lockfile = xstrdup(name);
406 }
9ba38048
NTND
407 else if (data->check_connectivity &&
408 data->transport_options.check_self_contained_and_connected &&
409 !strcmp(buf.buf, "connectivity-ok"))
410 data->transport_options.self_contained_and_connected = 1;
292ce46b
SP
411 else if (!buf.len)
412 break;
413 else
6b5b309f 414 warning(_("%s unexpectedly said: '%s'"), data->name, buf.buf);
6eb996b5 415 }
292ce46b 416 strbuf_release(&buf);
6eb996b5
DB
417 return 0;
418}
419
e65e91ed
DB
420static int get_importer(struct transport *transport, struct child_process *fastimport)
421{
422 struct child_process *helper = get_helper(transport);
bfc366d9 423 struct helper_data *data = transport->data;
bfc366d9 424 int cat_blob_fd, code;
483bbd4e 425 child_process_init(fastimport);
8b355427 426 fastimport->in = xdup(helper->out);
173fd1a1
JK
427 argv_array_push(&fastimport->args, "fast-import");
428 argv_array_push(&fastimport->args, debug ? "--stats" : "--quiet");
e65e91ed 429
bfc366d9
FA
430 if (data->bidi_import) {
431 cat_blob_fd = xdup(helper->in);
173fd1a1 432 argv_array_pushf(&fastimport->args, "--cat-blob-fd=%d", cat_blob_fd);
bfc366d9 433 }
e65e91ed 434 fastimport->git_cmd = 1;
bfc366d9
FA
435
436 code = start_command(fastimport);
437 return code;
e65e91ed
DB
438}
439
73b49a75
SR
440static int get_exporter(struct transport *transport,
441 struct child_process *fastexport,
73b49a75
SR
442 struct string_list *revlist_args)
443{
a515ebe9 444 struct helper_data *data = transport->data;
73b49a75 445 struct child_process *helper = get_helper(transport);
2aeae40a 446 int i;
852e54bc 447
8828f298 448 child_process_init(fastexport);
73b49a75
SR
449
450 /* we need to duplicate helper->in because we want to use it after
451 * fastexport is done with it. */
452 fastexport->out = dup(helper->in);
2aeae40a
JK
453 argv_array_push(&fastexport->args, "fast-export");
454 argv_array_push(&fastexport->args, "--use-done-feature");
455 argv_array_push(&fastexport->args, data->signed_tags ?
456 "--signed-tags=verbatim" : "--signed-tags=warn-strip");
457 if (data->export_marks)
458 argv_array_pushf(&fastexport->args, "--export-marks=%s.tmp", data->export_marks);
459 if (data->import_marks)
460 argv_array_pushf(&fastexport->args, "--import-marks=%s", data->import_marks);
73b49a75
SR
461
462 for (i = 0; i < revlist_args->nr; i++)
2aeae40a 463 argv_array_push(&fastexport->args, revlist_args->items[i].string);
73b49a75
SR
464
465 fastexport->git_cmd = 1;
466 return start_command(fastexport);
467}
468
e65e91ed
DB
469static int fetch_with_import(struct transport *transport,
470 int nr_heads, struct ref **to_fetch)
471{
472 struct child_process fastimport;
72ff8943 473 struct helper_data *data = transport->data;
e65e91ed
DB
474 int i;
475 struct ref *posn;
476 struct strbuf buf = STRBUF_INIT;
477
bf3c523c
IL
478 get_helper(transport);
479
e65e91ed 480 if (get_importer(transport, &fastimport))
6b5b309f 481 die(_("couldn't run fast-import"));
e65e91ed
DB
482
483 for (i = 0; i < nr_heads; i++) {
484 posn = to_fetch[i];
485 if (posn->status & REF_STATUS_UPTODATE)
486 continue;
487
33cae542
MH
488 strbuf_addf(&buf, "import %s\n",
489 posn->symref ? posn->symref : posn->name);
bf3c523c 490 sendline(data, &buf);
e65e91ed
DB
491 strbuf_reset(&buf);
492 }
9504bc9d
SR
493
494 write_constant(data->helper->in, "\n");
bfc366d9
FA
495 /*
496 * remote-helpers that advertise the bidi-import capability are required to
497 * buffer the complete batch of import commands until this newline before
498 * sending data to fast-import.
499 * These helpers read back data from fast-import on their stdin, which could
500 * be mixed with import commands, otherwise.
501 */
9504bc9d 502
cc567322 503 if (finish_command(&fastimport))
6b5b309f 504 die(_("error while running fast-import"));
e65e91ed 505
dff9d65d
FA
506 /*
507 * The fast-import stream of a remote helper that advertises
508 * the "refspec" capability writes to the refs named after the
509 * right hand side of the first refspec matching each ref we
510 * were fetching.
511 *
512 * (If no "refspec" capability was specified, for historical
7a43c554 513 * reasons we default to the equivalent of *:*.)
dff9d65d
FA
514 *
515 * Store the result in to_fetch[i].old_sha1. Callers such
516 * as "git fetch" can use the value to write feedback to the
517 * terminal, populate FETCH_HEAD, and determine what new value
518 * should be written to peer_ref if the update is a
519 * fast-forward or this is a forced update.
520 */
e65e91ed 521 for (i = 0; i < nr_heads; i++) {
33cae542 522 char *private, *name;
e65e91ed
DB
523 posn = to_fetch[i];
524 if (posn->status & REF_STATUS_UPTODATE)
525 continue;
33cae542 526 name = posn->symref ? posn->symref : posn->name;
57f32ac2 527 if (data->rs.nr)
d000414e 528 private = apply_refspecs(&data->rs, name);
72ff8943 529 else
33cae542 530 private = xstrdup(name);
d51b720f 531 if (private) {
34c290a6 532 if (read_ref(private, &posn->old_oid) < 0)
6b5b309f 533 die(_("could not read ref %s"), private);
d51b720f
MH
534 free(private);
535 }
e65e91ed 536 }
b962dbdc 537 strbuf_release(&buf);
e65e91ed
DB
538 return 0;
539}
540
176e85c1 541static int run_connect(struct transport *transport, struct strbuf *cmdbuf)
fa8c097c
IL
542{
543 struct helper_data *data = transport->data;
176e85c1
BW
544 int ret = 0;
545 int duped;
fa8c097c 546 FILE *input;
176e85c1 547 struct child_process *helper;
fa8c097c
IL
548
549 helper = get_helper(transport);
550
551 /*
552 * Yes, dup the pipe another time, as we need unbuffered version
553 * of input pipe as FILE*. fclose() closes the underlying fd and
554 * stream buffering only can be changed before first I/O operation
555 * on it.
556 */
557 duped = dup(helper->out);
558 if (duped < 0)
6b5b309f 559 die_errno(_("can't dup helper output fd"));
fa8c097c
IL
560 input = xfdopen(duped, "r");
561 setvbuf(input, NULL, _IONBF, 0);
562
176e85c1
BW
563 sendline(data, cmdbuf);
564 if (recvline_fh(input, cmdbuf))
565 exit(128);
566
567 if (!strcmp(cmdbuf->buf, "")) {
568 data->no_disconnect_req = 1;
569 if (debug)
570 fprintf(stderr, "Debug: Smart transport connection "
571 "ready.\n");
572 ret = 1;
573 } else if (!strcmp(cmdbuf->buf, "fallback")) {
574 if (debug)
575 fprintf(stderr, "Debug: Falling back to dumb "
576 "transport.\n");
577 } else {
739fb716 578 die(_("unknown response to connect: %s"),
6b5b309f 579 cmdbuf->buf);
176e85c1
BW
580 }
581
582 fclose(input);
583 return ret;
584}
585
586static int process_connect_service(struct transport *transport,
587 const char *name, const char *exec)
588{
589 struct helper_data *data = transport->data;
590 struct strbuf cmdbuf = STRBUF_INIT;
591 int ret = 0;
592
fa8c097c
IL
593 /*
594 * Handle --upload-pack and friends. This is fire and forget...
595 * just warn if it fails.
596 */
597 if (strcmp(name, exec)) {
176e85c1 598 int r = set_helper_option(transport, "servpath", exec);
fa8c097c 599 if (r > 0)
6b5b309f 600 warning(_("setting remote service path not supported by protocol"));
fa8c097c 601 else if (r < 0)
6b5b309f 602 warning(_("invalid remote service path"));
fa8c097c
IL
603 }
604
176e85c1 605 if (data->connect) {
fa8c097c 606 strbuf_addf(&cmdbuf, "connect %s\n", name);
176e85c1 607 ret = run_connect(transport, &cmdbuf);
edc9caf7
BW
608 } else if (data->stateless_connect &&
609 (get_protocol_version_config() == protocol_v2) &&
610 !strcmp("git-upload-pack", name)) {
611 strbuf_addf(&cmdbuf, "stateless-connect %s\n", name);
612 ret = run_connect(transport, &cmdbuf);
613 if (ret)
614 transport->stateless_rpc = 1;
176e85c1 615 }
fa8c097c 616
4168be8e 617 strbuf_release(&cmdbuf);
fa8c097c
IL
618 return ret;
619}
620
621static int process_connect(struct transport *transport,
622 int for_push)
623{
624 struct helper_data *data = transport->data;
625 const char *name;
626 const char *exec;
627
628 name = for_push ? "git-receive-pack" : "git-upload-pack";
629 if (for_push)
630 exec = data->transport_options.receivepack;
631 else
632 exec = data->transport_options.uploadpack;
633
634 return process_connect_service(transport, name, exec);
635}
636
b236752a
IL
637static int connect_helper(struct transport *transport, const char *name,
638 const char *exec, int fd[2])
639{
640 struct helper_data *data = transport->data;
641
642 /* Get_helper so connect is inited. */
643 get_helper(transport);
644 if (!data->connect)
6b5b309f 645 die(_("operation not supported by protocol"));
b236752a
IL
646
647 if (!process_connect_service(transport, name, exec))
6b5b309f 648 die(_("can't connect to subservice %s"), name);
b236752a
IL
649
650 fd[0] = data->helper->out;
651 fd[1] = data->helper->in;
652 return 0;
653}
654
6eb996b5 655static int fetch(struct transport *transport,
e2842b39 656 int nr_heads, struct ref **to_fetch)
6eb996b5
DB
657{
658 struct helper_data *data = transport->data;
659 int i, count;
660
fa8c097c
IL
661 if (process_connect(transport, 0)) {
662 do_take_over(transport);
e2842b39 663 return transport->vtable->fetch(transport, nr_heads, to_fetch);
fa8c097c
IL
664 }
665
6eb996b5
DB
666 count = 0;
667 for (i = 0; i < nr_heads; i++)
668 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
669 count++;
670
671 if (!count)
672 return 0;
673
aab1beb0
MH
674 if (data->check_connectivity &&
675 data->transport_options.check_self_contained_and_connected)
676 set_helper_option(transport, "check-connectivity", "true");
677
678 if (transport->cloning)
679 set_helper_option(transport, "cloning", "true");
680
681 if (data->transport_options.update_shallow)
682 set_helper_option(transport, "update-shallow", "true");
683
87c2d9d3
JS
684 if (data->transport_options.filter_options.choice) {
685 struct strbuf expanded_filter_spec = STRBUF_INIT;
686 expand_list_objects_filter_spec(
687 &data->transport_options.filter_options,
688 &expanded_filter_spec);
689 set_helper_option(transport, "filter",
690 expanded_filter_spec.buf);
691 strbuf_release(&expanded_filter_spec);
692 }
640d8b72 693
3390e42a
JT
694 if (data->transport_options.negotiation_tips)
695 warning("Ignoring --negotiation-tip because the protocol does not support it.");
696
6eb996b5
DB
697 if (data->fetch)
698 return fetch_with_fetch(transport, nr_heads, to_fetch);
699
e65e91ed
DB
700 if (data->import)
701 return fetch_with_import(transport, nr_heads, to_fetch);
702
6eb996b5
DB
703 return -1;
704}
705
664059fb 706static int push_update_ref_status(struct strbuf *buf,
d2e73c6f
SR
707 struct ref **ref,
708 struct ref *remote_refs)
709{
710 char *refname, *msg;
f9e3c6be 711 int status, forced = 0;
d2e73c6f 712
59556548 713 if (starts_with(buf->buf, "ok ")) {
d2e73c6f
SR
714 status = REF_STATUS_OK;
715 refname = buf->buf + 3;
59556548 716 } else if (starts_with(buf->buf, "error ")) {
d2e73c6f
SR
717 status = REF_STATUS_REMOTE_REJECT;
718 refname = buf->buf + 6;
719 } else
6b5b309f 720 die(_("expected ok/error, helper said '%s'"), buf->buf);
d2e73c6f
SR
721
722 msg = strchr(refname, ' ');
723 if (msg) {
724 struct strbuf msg_buf = STRBUF_INIT;
725 const char *end;
726
727 *msg++ = '\0';
728 if (!unquote_c_style(&msg_buf, msg, &end))
729 msg = strbuf_detach(&msg_buf, NULL);
730 else
731 msg = xstrdup(msg);
732 strbuf_release(&msg_buf);
733
734 if (!strcmp(msg, "no match")) {
735 status = REF_STATUS_NONE;
6a83d902 736 FREE_AND_NULL(msg);
d2e73c6f
SR
737 }
738 else if (!strcmp(msg, "up to date")) {
739 status = REF_STATUS_UPTODATE;
6a83d902 740 FREE_AND_NULL(msg);
d2e73c6f
SR
741 }
742 else if (!strcmp(msg, "non-fast forward")) {
743 status = REF_STATUS_REJECT_NONFASTFORWARD;
6a83d902 744 FREE_AND_NULL(msg);
d2e73c6f 745 }
dbfeddb1
CR
746 else if (!strcmp(msg, "already exists")) {
747 status = REF_STATUS_REJECT_ALREADY_EXISTS;
6a83d902 748 FREE_AND_NULL(msg);
dbfeddb1 749 }
75e5c0dc
JH
750 else if (!strcmp(msg, "fetch first")) {
751 status = REF_STATUS_REJECT_FETCH_FIRST;
6a83d902 752 FREE_AND_NULL(msg);
75e5c0dc
JH
753 }
754 else if (!strcmp(msg, "needs force")) {
755 status = REF_STATUS_REJECT_NEEDS_FORCE;
6a83d902 756 FREE_AND_NULL(msg);
75e5c0dc 757 }
631b5ef2
JH
758 else if (!strcmp(msg, "stale info")) {
759 status = REF_STATUS_REJECT_STALE;
6a83d902 760 FREE_AND_NULL(msg);
631b5ef2 761 }
f9e3c6be
FC
762 else if (!strcmp(msg, "forced update")) {
763 forced = 1;
6a83d902 764 FREE_AND_NULL(msg);
f9e3c6be 765 }
d2e73c6f
SR
766 }
767
768 if (*ref)
769 *ref = find_ref_by_name(*ref, refname);
770 if (!*ref)
771 *ref = find_ref_by_name(remote_refs, refname);
772 if (!*ref) {
6b5b309f 773 warning(_("helper reported unexpected status of %s"), refname);
664059fb 774 return 1;
d2e73c6f
SR
775 }
776
777 if ((*ref)->status != REF_STATUS_NONE) {
778 /*
779 * Earlier, the ref was marked not to be pushed, so ignore the ref
780 * status reported by the remote helper if the latter is 'no match'.
781 */
782 if (status == REF_STATUS_NONE)
664059fb 783 return 1;
d2e73c6f
SR
784 }
785
786 (*ref)->status = status;
cf31f70c 787 (*ref)->forced_update |= forced;
d2e73c6f 788 (*ref)->remote_status = msg;
126aac5c 789 return !(status == REF_STATUS_OK);
d2e73c6f
SR
790}
791
0551a06c 792static int push_update_refs_status(struct helper_data *data,
5a75353f
FC
793 struct ref *remote_refs,
794 int flags)
d2e73c6f
SR
795{
796 struct strbuf buf = STRBUF_INIT;
797 struct ref *ref = remote_refs;
0551a06c
FC
798 int ret = 0;
799
d2e73c6f 800 for (;;) {
664059fb
FC
801 char *private;
802
0551a06c
FC
803 if (recvline(data, &buf)) {
804 ret = 1;
805 break;
806 }
807
d2e73c6f
SR
808 if (!buf.len)
809 break;
810
664059fb
FC
811 if (push_update_ref_status(&buf, &ref, remote_refs))
812 continue;
813
57f32ac2 814 if (flags & TRANSPORT_PUSH_DRY_RUN || !data->rs.nr || data->no_private_update)
664059fb
FC
815 continue;
816
817 /* propagate back the update to the remote namespace */
d000414e 818 private = apply_refspecs(&data->rs, ref->name);
664059fb
FC
819 if (!private)
820 continue;
ae077771 821 update_ref("update by helper", private, &ref->new_oid, NULL,
822 0, 0);
664059fb 823 free(private);
d2e73c6f
SR
824 }
825 strbuf_release(&buf);
0551a06c 826 return ret;
d2e73c6f
SR
827}
828
30261094
DB
829static void set_common_push_options(struct transport *transport,
830 const char *name, int flags)
831{
832 if (flags & TRANSPORT_PUSH_DRY_RUN) {
833 if (set_helper_option(transport, "dry-run", "true") != 0)
6b5b309f 834 die(_("helper %s does not support dry-run"), name);
30261094
DB
835 } else if (flags & TRANSPORT_PUSH_CERT_ALWAYS) {
836 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "true") != 0)
6b5b309f 837 die(_("helper %s does not support --signed"), name);
30261094
DB
838 } else if (flags & TRANSPORT_PUSH_CERT_IF_ASKED) {
839 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "if-asked") != 0)
6b5b309f 840 die(_("helper %s does not support --signed=if-asked"), name);
30261094 841 }
438fc684
SB
842
843 if (flags & TRANSPORT_PUSH_OPTIONS) {
844 struct string_list_item *item;
845 for_each_string_list_item(item, transport->push_options)
846 if (set_helper_option(transport, "push-option", item->string) != 0)
6b5b309f 847 die(_("helper %s does not support 'push-option'"), name);
438fc684 848 }
30261094
DB
849}
850
73b49a75 851static int push_refs_with_push(struct transport *transport,
05c1eb10 852 struct ref *remote_refs, int flags)
ae4efe19
SP
853{
854 int force_all = flags & TRANSPORT_PUSH_FORCE;
855 int mirror = flags & TRANSPORT_PUSH_MIRROR;
3bca1e7f 856 int atomic = flags & TRANSPORT_PUSH_ATOMIC;
ae4efe19
SP
857 struct helper_data *data = transport->data;
858 struct strbuf buf = STRBUF_INIT;
ae4efe19 859 struct ref *ref;
05c1eb10
JH
860 struct string_list cas_options = STRING_LIST_INIT_DUP;
861 struct string_list_item *cas_option;
ae4efe19 862
c0aa335c 863 get_helper(transport);
ae4efe19
SP
864 if (!data->push)
865 return 1;
866
867 for (ref = remote_refs; ref; ref = ref->next) {
20e8b465 868 if (!ref->peer_ref && !mirror)
ae4efe19
SP
869 continue;
870
20e8b465
TRC
871 /* Check for statuses set by set_ref_status_for_push() */
872 switch (ref->status) {
873 case REF_STATUS_REJECT_NONFASTFORWARD:
631b5ef2 874 case REF_STATUS_REJECT_STALE:
dbfeddb1 875 case REF_STATUS_REJECT_ALREADY_EXISTS:
3bca1e7f
ES
876 if (atomic) {
877 string_list_clear(&cas_options, 0);
878 return 0;
879 } else
880 continue;
20e8b465 881 case REF_STATUS_UPTODATE:
ae4efe19 882 continue;
20e8b465
TRC
883 default:
884 ; /* do nothing */
ae4efe19
SP
885 }
886
887 if (force_all)
888 ref->force = 1;
889
890 strbuf_addstr(&buf, "push ");
891 if (!ref->deletion) {
892 if (ref->force)
893 strbuf_addch(&buf, '+');
894 if (ref->peer_ref)
895 strbuf_addstr(&buf, ref->peer_ref->name);
896 else
f4e54d02 897 strbuf_addstr(&buf, oid_to_hex(&ref->new_oid));
ae4efe19
SP
898 }
899 strbuf_addch(&buf, ':');
900 strbuf_addstr(&buf, ref->name);
901 strbuf_addch(&buf, '\n');
05c1eb10
JH
902
903 /*
904 * The "--force-with-lease" options without explicit
905 * values to expect have already been expanded into
f4e54d02 906 * the ref->old_oid_expect[] field; we can ignore
05c1eb10
JH
907 * transport->smart_options->cas altogether and instead
908 * can enumerate them from the refs.
909 */
910 if (ref->expect_old_sha1) {
911 struct strbuf cas = STRBUF_INIT;
912 strbuf_addf(&cas, "%s:%s",
f4e54d02 913 ref->name, oid_to_hex(&ref->old_oid_expect));
176cb979
RS
914 string_list_append_nodup(&cas_options,
915 strbuf_detach(&cas, NULL));
05c1eb10 916 }
ae4efe19 917 }
05c1eb10
JH
918 if (buf.len == 0) {
919 string_list_clear(&cas_options, 0);
d8f67d20 920 return 0;
05c1eb10 921 }
ae4efe19 922
05c1eb10
JH
923 for_each_string_list_item(cas_option, &cas_options)
924 set_helper_option(transport, "cas", cas_option->string);
30261094 925 set_common_push_options(transport, data->name, flags);
ae4efe19
SP
926
927 strbuf_addch(&buf, '\n');
bf3c523c 928 sendline(data, &buf);
ae4efe19 929 strbuf_release(&buf);
176cb979 930 string_list_clear(&cas_options, 0);
d2e73c6f 931
0551a06c 932 return push_update_refs_status(data, remote_refs, flags);
ae4efe19
SP
933}
934
73b49a75
SR
935static int push_refs_with_export(struct transport *transport,
936 struct ref *remote_refs, int flags)
937{
938 struct ref *ref;
939 struct child_process *helper, exporter;
940 struct helper_data *data = transport->data;
d98c8153 941 struct string_list revlist_args = STRING_LIST_INIT_DUP;
73b49a75
SR
942 struct strbuf buf = STRBUF_INIT;
943
57f32ac2 944 if (!data->rs.nr)
6b5b309f 945 die(_("remote-helper doesn't support push; refspec needed"));
21610d82 946
30261094 947 set_common_push_options(transport, data->name, flags);
510fa6f5
FC
948 if (flags & TRANSPORT_PUSH_FORCE) {
949 if (set_helper_option(transport, "force", "true") != 0)
6b5b309f 950 warning(_("helper %s does not support 'force'"), data->name);
510fa6f5
FC
951 }
952
73b49a75
SR
953 helper = get_helper(transport);
954
955 write_constant(helper->in, "export\n");
956
73b49a75
SR
957 for (ref = remote_refs; ref; ref = ref->next) {
958 char *private;
27912a03 959 struct object_id oid;
73b49a75 960
d000414e 961 private = apply_refspecs(&data->rs, ref->name);
e82caf38 962 if (private && !get_oid(private, &oid)) {
73b49a75 963 strbuf_addf(&buf, "^%s", private);
176cb979
RS
964 string_list_append_nodup(&revlist_args,
965 strbuf_detach(&buf, NULL));
27912a03 966 oidcpy(&ref->old_oid, &oid);
73b49a75 967 }
2faa1527 968 free(private);
73b49a75 969
67c9c782 970 if (ref->peer_ref) {
d98c8153 971 if (strcmp(ref->name, ref->peer_ref->name)) {
f3d03763
FC
972 if (!ref->deletion) {
973 const char *name;
974 int flag;
975
976 /* Follow symbolic refs (mainly for HEAD). */
49e61479 977 name = resolve_ref_unsafe(ref->peer_ref->name,
978 RESOLVE_REF_READING,
979 &oid, &flag);
f3d03763
FC
980 if (!name || !(flag & REF_ISSYMREF))
981 name = ref->peer_ref->name;
9193f742 982
f3d03763
FC
983 strbuf_addf(&buf, "%s:%s", name, ref->name);
984 } else
985 strbuf_addf(&buf, ":%s", ref->name);
9193f742 986
d98c8153
FC
987 string_list_append(&revlist_args, "--refspec");
988 string_list_append(&revlist_args, buf.buf);
989 strbuf_release(&buf);
990 }
f3d03763
FC
991 if (!ref->deletion)
992 string_list_append(&revlist_args, ref->peer_ref->name);
67c9c782 993 }
73b49a75
SR
994 }
995
a515ebe9 996 if (get_exporter(transport, &exporter, &revlist_args))
6b5b309f 997 die(_("couldn't run fast-export"));
73b49a75 998
d98c8153
FC
999 string_list_clear(&revlist_args, 1);
1000
cc567322 1001 if (finish_command(&exporter))
6b5b309f 1002 die(_("error while running fast-export"));
3994e64d
FC
1003 if (push_update_refs_status(data, remote_refs, flags))
1004 return 1;
1005
1006 if (data->export_marks) {
1007 strbuf_addf(&buf, "%s.tmp", data->export_marks);
1008 rename(buf.buf, data->export_marks);
1009 strbuf_release(&buf);
1010 }
1011
1012 return 0;
73b49a75
SR
1013}
1014
1015static int push_refs(struct transport *transport,
1016 struct ref *remote_refs, int flags)
1017{
1018 struct helper_data *data = transport->data;
1019
1020 if (process_connect(transport, 1)) {
1021 do_take_over(transport);
e967ca38 1022 return transport->vtable->push_refs(transport, remote_refs, flags);
73b49a75
SR
1023 }
1024
1025 if (!remote_refs) {
6b5b309f
NTND
1026 fprintf(stderr,
1027 _("No refs in common and none specified; doing nothing.\n"
1028 "Perhaps you should specify a branch such as 'master'.\n"));
73b49a75
SR
1029 return 0;
1030 }
1031
1032 if (data->push)
1033 return push_refs_with_push(transport, remote_refs, flags);
1034
1035 if (data->export)
1036 return push_refs_with_export(transport, remote_refs, flags);
1037
1038 return -1;
1039}
1040
1041
3b335762
NTND
1042static int has_attribute(const char *attrs, const char *attr)
1043{
f8ec9167
DB
1044 int len;
1045 if (!attrs)
1046 return 0;
1047
1048 len = strlen(attr);
1049 for (;;) {
1050 const char *space = strchrnul(attrs, ' ');
1051 if (len == space - attrs && !strncmp(attrs, attr, len))
1052 return 1;
1053 if (!*space)
1054 return 0;
1055 attrs = space + 1;
1056 }
1057}
1058
834cf34b
BW
1059static struct ref *get_refs_list(struct transport *transport, int for_push,
1060 const struct argv_array *ref_prefixes)
6eb996b5 1061{
292ce46b 1062 struct helper_data *data = transport->data;
6eb996b5
DB
1063 struct child_process *helper;
1064 struct ref *ret = NULL;
1065 struct ref **tail = &ret;
1066 struct ref *posn;
1067 struct strbuf buf = STRBUF_INIT;
6eb996b5
DB
1068
1069 helper = get_helper(transport);
2d14d65c 1070
fa8c097c
IL
1071 if (process_connect(transport, for_push)) {
1072 do_take_over(transport);
834cf34b 1073 return transport->vtable->get_refs_list(transport, for_push, ref_prefixes);
fa8c097c
IL
1074 }
1075
ae4efe19
SP
1076 if (data->push && for_push)
1077 write_str_in_full(helper->in, "list for-push\n");
1078 else
1079 write_str_in_full(helper->in, "list\n");
6eb996b5 1080
6eb996b5
DB
1081 while (1) {
1082 char *eov, *eon;
5931b33e
FC
1083 if (recvline(data, &buf))
1084 exit(128);
6eb996b5
DB
1085
1086 if (!*buf.buf)
1087 break;
1088
1089 eov = strchr(buf.buf, ' ');
1090 if (!eov)
6b5b309f 1091 die(_("malformed response in ref list: %s"), buf.buf);
6eb996b5
DB
1092 eon = strchr(eov + 1, ' ');
1093 *eov = '\0';
1094 if (eon)
1095 *eon = '\0';
1096 *tail = alloc_ref(eov + 1);
1097 if (buf.buf[0] == '@')
1098 (*tail)->symref = xstrdup(buf.buf + 1);
1099 else if (buf.buf[0] != '?')
f4e54d02 1100 get_oid_hex(buf.buf, &(*tail)->old_oid);
f8ec9167
DB
1101 if (eon) {
1102 if (has_attribute(eon + 1, "unchanged")) {
1103 (*tail)->status |= REF_STATUS_UPTODATE;
34c290a6 1104 if (read_ref((*tail)->name, &(*tail)->old_oid) < 0)
1a07e59c 1105 die(_("could not read ref %s"),
ae25fd39 1106 (*tail)->name);
f8ec9167
DB
1107 }
1108 }
6eb996b5
DB
1109 tail = &((*tail)->next);
1110 }
bf3c523c
IL
1111 if (debug)
1112 fprintf(stderr, "Debug: Read ref listing.\n");
6eb996b5
DB
1113 strbuf_release(&buf);
1114
1115 for (posn = ret; posn; posn = posn->next)
1116 resolve_remote_symref(posn, ret);
1117
1118 return ret;
1119}
1120
e967ca38 1121static struct transport_vtable vtable = {
6ab40557 1122 0,
e967ca38
JT
1123 set_helper_option,
1124 get_refs_list,
1125 fetch,
1126 push_refs,
1127 connect_helper,
1128 release_helper
1129};
1130
c9e388bb 1131int transport_helper_init(struct transport *transport, const char *name)
6eb996b5 1132{
92e25b6b 1133 struct helper_data *data = xcalloc(1, sizeof(*data));
c9e388bb 1134 data->name = name;
6eb996b5 1135
a5adaced
JK
1136 transport_check_allowed(name);
1137
bf3c523c
IL
1138 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1139 debug = 1;
1140
6eb996b5 1141 transport->data = data;
e967ca38 1142 transport->vtable = &vtable;
61b075bd 1143 transport->smart_options = &(data->transport_options);
6eb996b5
DB
1144 return 0;
1145}
419f37db
IL
1146
1147/*
1148 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1149 * buffer less), so attempt reads and writes with up to that size.
1150 */
1151#define BUFFERSIZE 65536
1152/* This should be enough to hold debugging message. */
1153#define PBUFFERSIZE 8192
1154
1155/* Print bidirectional transfer loop debug message. */
4621085b 1156__attribute__((format (printf, 1, 2)))
419f37db
IL
1157static void transfer_debug(const char *fmt, ...)
1158{
6cdf8a79
1159 /*
1160 * NEEDSWORK: This function is sometimes used from multiple threads, and
1161 * we end up using debug_enabled racily. That "should not matter" since
1162 * we always write the same value, but it's still wrong. This function
1163 * is listed in .tsan-suppressions for the time being.
1164 */
1165
419f37db
IL
1166 va_list args;
1167 char msgbuf[PBUFFERSIZE];
1168 static int debug_enabled = -1;
1169
1170 if (debug_enabled < 0)
1171 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1172 if (!debug_enabled)
1173 return;
1174
1175 va_start(args, fmt);
1176 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1177 va_end(args);
1178 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1179}
1180
1181/* Stream state: More data may be coming in this direction. */
2e3a16b2 1182#define SSTATE_TRANSFERRING 0
419f37db
IL
1183/*
1184 * Stream state: No more data coming in this direction, flushing rest of
1185 * data.
1186 */
1187#define SSTATE_FLUSHING 1
1188/* Stream state: Transfer in this direction finished. */
1189#define SSTATE_FINISHED 2
1190
2e3a16b2 1191#define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERRING)
419f37db
IL
1192#define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1193#define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1194
1195/* Unidirectional transfer. */
1196struct unidirectional_transfer {
1197 /* Source */
1198 int src;
1199 /* Destination */
1200 int dest;
1201 /* Is source socket? */
1202 int src_is_sock;
1203 /* Is destination socket? */
1204 int dest_is_sock;
41ccfdd9 1205 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
419f37db
IL
1206 int state;
1207 /* Buffer. */
1208 char buf[BUFFERSIZE];
1209 /* Buffer used. */
1210 size_t bufuse;
1211 /* Name of source. */
1212 const char *src_name;
1213 /* Name of destination. */
1214 const char *dest_name;
1215};
1216
1217/* Closes the target (for writing) if transfer has finished. */
1218static void udt_close_if_finished(struct unidirectional_transfer *t)
1219{
1220 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1221 t->state = SSTATE_FINISHED;
1222 if (t->dest_is_sock)
1223 shutdown(t->dest, SHUT_WR);
1224 else
1225 close(t->dest);
1226 transfer_debug("Closed %s.", t->dest_name);
1227 }
1228}
1229
1230/*
832c0e5e 1231 * Tries to read data from source into buffer. If buffer is full,
419f37db
IL
1232 * no data is read. Returns 0 on success, -1 on error.
1233 */
1234static int udt_do_read(struct unidirectional_transfer *t)
1235{
1236 ssize_t bytes;
1237
1238 if (t->bufuse == BUFFERSIZE)
1239 return 0; /* No space for more. */
1240
1241 transfer_debug("%s is readable", t->src_name);
c14e5a1a 1242 bytes = xread(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
d4c81368 1243 if (bytes < 0) {
6b5b309f 1244 error_errno(_("read(%s) failed"), t->src_name);
419f37db
IL
1245 return -1;
1246 } else if (bytes == 0) {
1247 transfer_debug("%s EOF (with %i bytes in buffer)",
4621085b 1248 t->src_name, (int)t->bufuse);
419f37db
IL
1249 t->state = SSTATE_FLUSHING;
1250 } else if (bytes > 0) {
1251 t->bufuse += bytes;
1252 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1253 (int)bytes, t->src_name, (int)t->bufuse);
1254 }
1255 return 0;
1256}
1257
1258/* Tries to write data from buffer into destination. If buffer is empty,
1259 * no data is written. Returns 0 on success, -1 on error.
1260 */
1261static int udt_do_write(struct unidirectional_transfer *t)
1262{
803dbdb9 1263 ssize_t bytes;
419f37db
IL
1264
1265 if (t->bufuse == 0)
1266 return 0; /* Nothing to write. */
1267
1268 transfer_debug("%s is writable", t->dest_name);
7edc02f4 1269 bytes = xwrite(t->dest, t->buf, t->bufuse);
d4c81368 1270 if (bytes < 0) {
6b5b309f 1271 error_errno(_("write(%s) failed"), t->dest_name);
419f37db
IL
1272 return -1;
1273 } else if (bytes > 0) {
1274 t->bufuse -= bytes;
1275 if (t->bufuse)
1276 memmove(t->buf, t->buf + bytes, t->bufuse);
1277 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1278 (int)bytes, t->dest_name, (int)t->bufuse);
1279 }
1280 return 0;
1281}
1282
1283
1284/* State of bidirectional transfer loop. */
1285struct bidirectional_transfer_state {
1286 /* Direction from program to git. */
1287 struct unidirectional_transfer ptg;
1288 /* Direction from git to program. */
1289 struct unidirectional_transfer gtp;
1290};
1291
1292static void *udt_copy_task_routine(void *udt)
1293{
1294 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1295 while (t->state != SSTATE_FINISHED) {
1296 if (STATE_NEEDS_READING(t->state))
1297 if (udt_do_read(t))
1298 return NULL;
1299 if (STATE_NEEDS_WRITING(t->state))
1300 if (udt_do_write(t))
1301 return NULL;
1302 if (STATE_NEEDS_CLOSING(t->state))
1303 udt_close_if_finished(t);
1304 }
1305 return udt; /* Just some non-NULL value. */
1306}
1307
1308#ifndef NO_PTHREADS
1309
1310/*
98e023de 1311 * Join thread, with appropriate errors on failure. Name is name for the
419f37db
IL
1312 * thread (for error messages). Returns 0 on success, 1 on failure.
1313 */
1314static int tloop_join(pthread_t thread, const char *name)
1315{
1316 int err;
1317 void *tret;
1318 err = pthread_join(thread, &tret);
1319 if (!tret) {
6b5b309f 1320 error(_("%s thread failed"), name);
419f37db
IL
1321 return 1;
1322 }
1323 if (err) {
6b5b309f 1324 error(_("%s thread failed to join: %s"), name, strerror(err));
419f37db
IL
1325 return 1;
1326 }
1327 return 0;
1328}
1329
1330/*
1331 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1332 * -1 on failure.
1333 */
1334static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1335{
1336 pthread_t gtp_thread;
1337 pthread_t ptg_thread;
1338 int err;
1339 int ret = 0;
1340 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1341 &s->gtp);
1342 if (err)
6b5b309f 1343 die(_("can't start thread for copying data: %s"), strerror(err));
419f37db
IL
1344 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1345 &s->ptg);
1346 if (err)
6b5b309f 1347 die(_("can't start thread for copying data: %s"), strerror(err));
419f37db
IL
1348
1349 ret |= tloop_join(gtp_thread, "Git to program copy");
1350 ret |= tloop_join(ptg_thread, "Program to git copy");
1351 return ret;
1352}
1353#else
1354
1355/* Close the source and target (for writing) for transfer. */
1356static void udt_kill_transfer(struct unidirectional_transfer *t)
1357{
1358 t->state = SSTATE_FINISHED;
1359 /*
1360 * Socket read end left open isn't a disaster if nobody
1361 * attempts to read from it (mingw compat headers do not
1362 * have SHUT_RD)...
1363 *
1364 * We can't fully close the socket since otherwise gtp
1365 * task would first close the socket it sends data to
1366 * while closing the ptg file descriptors.
1367 */
1368 if (!t->src_is_sock)
1369 close(t->src);
1370 if (t->dest_is_sock)
1371 shutdown(t->dest, SHUT_WR);
1372 else
1373 close(t->dest);
1374}
1375
1376/*
98e023de 1377 * Join process, with appropriate errors on failure. Name is name for the
419f37db
IL
1378 * process (for error messages). Returns 0 on success, 1 on failure.
1379 */
1380static int tloop_join(pid_t pid, const char *name)
1381{
1382 int tret;
1383 if (waitpid(pid, &tret, 0) < 0) {
6b5b309f 1384 error_errno(_("%s process failed to wait"), name);
419f37db
IL
1385 return 1;
1386 }
1387 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
6b5b309f 1388 error(_("%s process failed"), name);
419f37db
IL
1389 return 1;
1390 }
1391 return 0;
1392}
1393
1394/*
1395 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1396 * -1 on failure.
1397 */
1398static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1399{
1400 pid_t pid1, pid2;
1401 int ret = 0;
1402
1403 /* Fork thread #1: git to program. */
1404 pid1 = fork();
1405 if (pid1 < 0)
6b5b309f 1406 die_errno(_("can't start thread for copying data"));
419f37db
IL
1407 else if (pid1 == 0) {
1408 udt_kill_transfer(&s->ptg);
1409 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1410 }
1411
1412 /* Fork thread #2: program to git. */
1413 pid2 = fork();
1414 if (pid2 < 0)
6b5b309f 1415 die_errno(_("can't start thread for copying data"));
419f37db
IL
1416 else if (pid2 == 0) {
1417 udt_kill_transfer(&s->gtp);
1418 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1419 }
1420
1421 /*
1422 * Close both streams in parent as to not interfere with
1423 * end of file detection and wait for both tasks to finish.
1424 */
1425 udt_kill_transfer(&s->gtp);
1426 udt_kill_transfer(&s->ptg);
1427 ret |= tloop_join(pid1, "Git to program copy");
1428 ret |= tloop_join(pid2, "Program to git copy");
1429 return ret;
1430}
1431#endif
1432
1433/*
1434 * Copies data from stdin to output and from input to stdout simultaneously.
1435 * Additionally filtering through given filter. If filter is NULL, uses
1436 * identity filter.
1437 */
1438int bidirectional_transfer_loop(int input, int output)
1439{
1440 struct bidirectional_transfer_state state;
1441
1442 /* Fill the state fields. */
1443 state.ptg.src = input;
1444 state.ptg.dest = 1;
1445 state.ptg.src_is_sock = (input == output);
1446 state.ptg.dest_is_sock = 0;
2e3a16b2 1447 state.ptg.state = SSTATE_TRANSFERRING;
419f37db
IL
1448 state.ptg.bufuse = 0;
1449 state.ptg.src_name = "remote input";
1450 state.ptg.dest_name = "stdout";
1451
1452 state.gtp.src = 0;
1453 state.gtp.dest = output;
1454 state.gtp.src_is_sock = 0;
1455 state.gtp.dest_is_sock = (input == output);
2e3a16b2 1456 state.gtp.state = SSTATE_TRANSFERRING;
419f37db
IL
1457 state.gtp.bufuse = 0;
1458 state.gtp.src_name = "stdin";
1459 state.gtp.dest_name = "remote output";
1460
1461 return tloop_spawnwait_tasks(&state);
1462}