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