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