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