Add argv_array_detach and argv_array_free_detached
[git/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"
ef08ef9e 8#include "quote.h"
72ff8943 9#include "remote.h"
73b49a75 10#include "string-list.h"
7851b1e6 11#include "thread-utils.h"
c34fe630 12#include "sigchain.h"
7851b1e6 13
bf3c523c
IL
14static int debug;
15
9cba13ca 16struct helper_data {
6eb996b5
DB
17 const char *name;
18 struct child_process *helper;
292ce46b 19 FILE *out;
ef08ef9e 20 unsigned fetch : 1,
a24a32dd 21 import : 1,
73b49a75 22 export : 1,
ae4efe19 23 option : 1,
fa8c097c
IL
24 push : 1,
25 connect : 1,
26 no_disconnect_req : 1;
a515ebe9
SR
27 char *export_marks;
28 char *import_marks;
72ff8943
DB
29 /* These go from remote name (as in "list") to private name */
30 struct refspec *refspecs;
31 int refspec_nr;
61b075bd
IL
32 /* Transport options for fetch-pack/send-pack (should one of
33 * those be invoked).
34 */
35 struct git_transport_options transport_options;
6eb996b5
DB
36};
37
bf3c523c
IL
38static void sendline(struct helper_data *helper, struct strbuf *buffer)
39{
40 if (debug)
41 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
42 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
43 != buffer->len)
44 die_errno("Full write to remote helper failed");
45}
46
fa8c097c 47static int recvline_fh(FILE *helper, struct strbuf *buffer)
bf3c523c
IL
48{
49 strbuf_reset(buffer);
50 if (debug)
51 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
fa8c097c 52 if (strbuf_getline(buffer, helper, '\n') == EOF) {
bf3c523c
IL
53 if (debug)
54 fprintf(stderr, "Debug: Remote helper quit.\n");
55 exit(128);
56 }
57
58 if (debug)
59 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
60 return 0;
61}
62
fa8c097c
IL
63static int recvline(struct helper_data *helper, struct strbuf *buffer)
64{
65 return recvline_fh(helper->out, buffer);
66}
67
bf3c523c
IL
68static void xchgline(struct helper_data *helper, struct strbuf *buffer)
69{
70 sendline(helper, buffer);
71 recvline(helper, buffer);
72}
73
74static void write_constant(int fd, const char *str)
75{
76 if (debug)
77 fprintf(stderr, "Debug: Remote helper: -> %s", str);
78 if (write_in_full(fd, str, strlen(str)) != strlen(str))
79 die_errno("Full write to remote helper failed");
80}
81
c2e86add 82static const char *remove_ext_force(const char *url)
25d5cc48
IL
83{
84 if (url) {
85 const char *colon = strchr(url, ':');
86 if (colon && colon[1] == ':')
87 return colon + 2;
88 }
89 return url;
90}
91
fa8c097c
IL
92static void do_take_over(struct transport *transport)
93{
94 struct helper_data *data;
95 data = (struct helper_data *)transport->data;
96 transport_take_over(transport, data->helper);
97 fclose(data->out);
98 free(data);
99}
100
6eb996b5
DB
101static struct child_process *get_helper(struct transport *transport)
102{
103 struct helper_data *data = transport->data;
104 struct strbuf buf = STRBUF_INIT;
105 struct child_process *helper;
72ff8943
DB
106 const char **refspecs = NULL;
107 int refspec_nr = 0;
108 int refspec_alloc = 0;
61b075bd 109 int duped;
6b02de3b 110 int code;
e1735872
DI
111 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
112 const char *helper_env[] = {
113 git_dir_buf,
114 NULL
115 };
116
6eb996b5
DB
117
118 if (data->helper)
119 return data->helper;
120
121 helper = xcalloc(1, sizeof(*helper));
122 helper->in = -1;
123 helper->out = -1;
124 helper->err = 0;
125 helper->argv = xcalloc(4, sizeof(*helper->argv));
6b02de3b 126 strbuf_addf(&buf, "git-remote-%s", data->name);
6eb996b5
DB
127 helper->argv[0] = strbuf_detach(&buf, NULL);
128 helper->argv[1] = transport->remote->name;
25d5cc48 129 helper->argv[2] = remove_ext_force(transport->url);
6b02de3b
IL
130 helper->git_cmd = 0;
131 helper->silent_exec_failure = 1;
e1735872
DI
132
133 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
134 helper->env = helper_env;
135
6b02de3b
IL
136 code = start_command(helper);
137 if (code < 0 && errno == ENOENT)
138 die("Unable to find remote helper for '%s'", data->name);
139 else if (code != 0)
140 exit(code);
141
6eb996b5 142 data->helper = helper;
fa8c097c 143 data->no_disconnect_req = 0;
6eb996b5 144
61b075bd
IL
145 /*
146 * Open the output as FILE* so strbuf_getline() can be used.
147 * Do this with duped fd because fclose() will close the fd,
148 * and stuff like taking over will require the fd to remain.
61b075bd
IL
149 */
150 duped = dup(helper->out);
151 if (duped < 0)
152 die_errno("Can't dup helper output fd");
153 data->out = xfdopen(duped, "r");
154
bf3c523c 155 write_constant(helper->in, "capabilities\n");
2d14d65c 156
6eb996b5 157 while (1) {
28ed5b35
IL
158 const char *capname;
159 int mandatory = 0;
bf3c523c 160 recvline(data, &buf);
6eb996b5
DB
161
162 if (!*buf.buf)
163 break;
28ed5b35
IL
164
165 if (*buf.buf == '*') {
166 capname = buf.buf + 1;
167 mandatory = 1;
168 } else
169 capname = buf.buf;
170
bf3c523c 171 if (debug)
28ed5b35
IL
172 fprintf(stderr, "Debug: Got cap %s\n", capname);
173 if (!strcmp(capname, "fetch"))
6eb996b5 174 data->fetch = 1;
28ed5b35 175 else if (!strcmp(capname, "option"))
ef08ef9e 176 data->option = 1;
28ed5b35 177 else if (!strcmp(capname, "push"))
ae4efe19 178 data->push = 1;
28ed5b35 179 else if (!strcmp(capname, "import"))
e65e91ed 180 data->import = 1;
73b49a75
SR
181 else if (!strcmp(capname, "export"))
182 data->export = 1;
28ed5b35 183 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
72ff8943
DB
184 ALLOC_GROW(refspecs,
185 refspec_nr + 1,
186 refspec_alloc);
c28cce55 187 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
fa8c097c
IL
188 } else if (!strcmp(capname, "connect")) {
189 data->connect = 1;
a515ebe9
SR
190 } else if (!prefixcmp(capname, "export-marks ")) {
191 struct strbuf arg = STRBUF_INIT;
192 strbuf_addstr(&arg, "--export-marks=");
193 strbuf_addstr(&arg, capname + strlen("export-marks "));
194 data->export_marks = strbuf_detach(&arg, NULL);
195 } else if (!prefixcmp(capname, "import-marks")) {
196 struct strbuf arg = STRBUF_INIT;
197 strbuf_addstr(&arg, "--import-marks=");
198 strbuf_addstr(&arg, capname + strlen("import-marks "));
199 data->import_marks = strbuf_detach(&arg, NULL);
28ed5b35 200 } else if (mandatory) {
9517e6b8 201 die("Unknown mandatory capability %s. This remote "
82247e9b 202 "helper probably needs newer version of Git.",
28ed5b35 203 capname);
72ff8943
DB
204 }
205 }
206 if (refspecs) {
207 int i;
208 data->refspec_nr = refspec_nr;
209 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
210 for (i = 0; i < refspec_nr; i++) {
211 free((char *)refspecs[i]);
212 }
213 free(refspecs);
6eb996b5 214 }
b962dbdc 215 strbuf_release(&buf);
bf3c523c
IL
216 if (debug)
217 fprintf(stderr, "Debug: Capabilities complete.\n");
6eb996b5
DB
218 return data->helper;
219}
220
221static int disconnect_helper(struct transport *transport)
222{
223 struct helper_data *data = transport->data;
cc567322 224 int res = 0;
bf3c523c 225
6eb996b5 226 if (data->helper) {
bf3c523c
IL
227 if (debug)
228 fprintf(stderr, "Debug: Disconnecting.\n");
fa8c097c 229 if (!data->no_disconnect_req) {
c34fe630
JK
230 /*
231 * Ignore write errors; there's nothing we can do,
232 * since we're about to close the pipe anyway. And the
233 * most likely error is EPIPE due to the helper dying
234 * to report an error itself.
235 */
236 sigchain_push(SIGPIPE, SIG_IGN);
237 xwrite(data->helper->in, "\n", 1);
238 sigchain_pop(SIGPIPE);
fa8c097c 239 }
6eb996b5 240 close(data->helper->in);
61b075bd 241 close(data->helper->out);
292ce46b 242 fclose(data->out);
cc567322 243 res = finish_command(data->helper);
6eb996b5
DB
244 free((char *)data->helper->argv[0]);
245 free(data->helper->argv);
246 free(data->helper);
247 data->helper = NULL;
248 }
cc567322 249 return res;
6eb996b5
DB
250}
251
ef08ef9e
SP
252static const char *unsupported_options[] = {
253 TRANS_OPT_UPLOADPACK,
254 TRANS_OPT_RECEIVEPACK,
255 TRANS_OPT_THIN,
256 TRANS_OPT_KEEP
257 };
258static const char *boolean_options[] = {
259 TRANS_OPT_THIN,
260 TRANS_OPT_KEEP,
261 TRANS_OPT_FOLLOWTAGS
262 };
263
264static int set_helper_option(struct transport *transport,
265 const char *name, const char *value)
266{
267 struct helper_data *data = transport->data;
ef08ef9e
SP
268 struct strbuf buf = STRBUF_INIT;
269 int i, ret, is_bool = 0;
270
bf3c523c
IL
271 get_helper(transport);
272
ef08ef9e
SP
273 if (!data->option)
274 return 1;
275
276 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
277 if (!strcmp(name, unsupported_options[i]))
278 return 1;
279 }
280
281 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
282 if (!strcmp(name, boolean_options[i])) {
283 is_bool = 1;
284 break;
285 }
286 }
287
288 strbuf_addf(&buf, "option %s ", name);
289 if (is_bool)
290 strbuf_addstr(&buf, value ? "true" : "false");
291 else
292 quote_c_style(value, &buf, NULL, 0);
293 strbuf_addch(&buf, '\n');
294
bf3c523c 295 xchgline(data, &buf);
ef08ef9e
SP
296
297 if (!strcmp(buf.buf, "ok"))
298 ret = 0;
299 else if (!prefixcmp(buf.buf, "error")) {
300 ret = -1;
301 } else if (!strcmp(buf.buf, "unsupported"))
302 ret = 1;
303 else {
304 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
305 ret = 1;
306 }
307 strbuf_release(&buf);
308 return ret;
309}
310
311static void standard_options(struct transport *t)
312{
313 char buf[16];
314 int n;
315 int v = t->verbose;
ef08ef9e 316
d01b3c02 317 set_helper_option(t, "progress", t->progress ? "true" : "false");
ef08ef9e
SP
318
319 n = snprintf(buf, sizeof(buf), "%d", v + 1);
320 if (n >= sizeof(buf))
321 die("impossibly large verbosity value");
322 set_helper_option(t, "verbosity", buf);
323}
324
f2a37151
DB
325static int release_helper(struct transport *transport)
326{
cc567322 327 int res = 0;
72ff8943
DB
328 struct helper_data *data = transport->data;
329 free_refspec(data->refspec_nr, data->refspecs);
330 data->refspecs = NULL;
cc567322 331 res = disconnect_helper(transport);
f2a37151 332 free(transport->data);
cc567322 333 return res;
f2a37151
DB
334}
335
6eb996b5 336static int fetch_with_fetch(struct transport *transport,
37148311 337 int nr_heads, struct ref **to_fetch)
6eb996b5 338{
292ce46b 339 struct helper_data *data = transport->data;
6eb996b5
DB
340 int i;
341 struct strbuf buf = STRBUF_INIT;
342
ef08ef9e
SP
343 standard_options(transport);
344
6eb996b5 345 for (i = 0; i < nr_heads; i++) {
1088261f 346 const struct ref *posn = to_fetch[i];
6eb996b5
DB
347 if (posn->status & REF_STATUS_UPTODATE)
348 continue;
2d14d65c
DB
349
350 strbuf_addf(&buf, "fetch %s %s\n",
351 sha1_to_hex(posn->old_sha1), posn->name);
292ce46b 352 }
2d14d65c 353
292ce46b 354 strbuf_addch(&buf, '\n');
bf3c523c 355 sendline(data, &buf);
292ce46b
SP
356
357 while (1) {
bf3c523c 358 recvline(data, &buf);
292ce46b
SP
359
360 if (!prefixcmp(buf.buf, "lock ")) {
361 const char *name = buf.buf + 5;
362 if (transport->pack_lockfile)
363 warning("%s also locked %s", data->name, name);
364 else
365 transport->pack_lockfile = xstrdup(name);
366 }
367 else if (!buf.len)
368 break;
369 else
370 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
6eb996b5 371 }
292ce46b 372 strbuf_release(&buf);
6eb996b5
DB
373 return 0;
374}
375
e65e91ed
DB
376static int get_importer(struct transport *transport, struct child_process *fastimport)
377{
378 struct child_process *helper = get_helper(transport);
379 memset(fastimport, 0, sizeof(*fastimport));
380 fastimport->in = helper->out;
381 fastimport->argv = xcalloc(5, sizeof(*fastimport->argv));
382 fastimport->argv[0] = "fast-import";
383 fastimport->argv[1] = "--quiet";
384
385 fastimport->git_cmd = 1;
386 return start_command(fastimport);
387}
388
73b49a75
SR
389static int get_exporter(struct transport *transport,
390 struct child_process *fastexport,
73b49a75
SR
391 struct string_list *revlist_args)
392{
a515ebe9 393 struct helper_data *data = transport->data;
73b49a75
SR
394 struct child_process *helper = get_helper(transport);
395 int argc = 0, i;
396 memset(fastexport, 0, sizeof(*fastexport));
397
398 /* we need to duplicate helper->in because we want to use it after
399 * fastexport is done with it. */
400 fastexport->out = dup(helper->in);
1f25c504 401 fastexport->argv = xcalloc(5 + revlist_args->nr, sizeof(*fastexport->argv));
73b49a75 402 fastexport->argv[argc++] = "fast-export";
1f25c504 403 fastexport->argv[argc++] = "--use-done-feature";
a515ebe9
SR
404 if (data->export_marks)
405 fastexport->argv[argc++] = data->export_marks;
406 if (data->import_marks)
407 fastexport->argv[argc++] = data->import_marks;
73b49a75
SR
408
409 for (i = 0; i < revlist_args->nr; i++)
410 fastexport->argv[argc++] = revlist_args->items[i].string;
411
412 fastexport->git_cmd = 1;
413 return start_command(fastexport);
414}
415
e65e91ed
DB
416static int fetch_with_import(struct transport *transport,
417 int nr_heads, struct ref **to_fetch)
418{
419 struct child_process fastimport;
72ff8943 420 struct helper_data *data = transport->data;
e65e91ed
DB
421 int i;
422 struct ref *posn;
423 struct strbuf buf = STRBUF_INIT;
424
bf3c523c
IL
425 get_helper(transport);
426
e65e91ed
DB
427 if (get_importer(transport, &fastimport))
428 die("Couldn't run fast-import");
429
430 for (i = 0; i < nr_heads; i++) {
431 posn = to_fetch[i];
432 if (posn->status & REF_STATUS_UPTODATE)
433 continue;
434
435 strbuf_addf(&buf, "import %s\n", posn->name);
bf3c523c 436 sendline(data, &buf);
e65e91ed
DB
437 strbuf_reset(&buf);
438 }
9504bc9d
SR
439
440 write_constant(data->helper->in, "\n");
441
cc567322
SR
442 if (finish_command(&fastimport))
443 die("Error while running fast-import");
b962dbdc
SR
444 free(fastimport.argv);
445 fastimport.argv = NULL;
e65e91ed 446
dff9d65d
FA
447 /*
448 * The fast-import stream of a remote helper that advertises
449 * the "refspec" capability writes to the refs named after the
450 * right hand side of the first refspec matching each ref we
451 * were fetching.
452 *
453 * (If no "refspec" capability was specified, for historical
454 * reasons we default to *:*.)
455 *
456 * Store the result in to_fetch[i].old_sha1. Callers such
457 * as "git fetch" can use the value to write feedback to the
458 * terminal, populate FETCH_HEAD, and determine what new value
459 * should be written to peer_ref if the update is a
460 * fast-forward or this is a forced update.
461 */
e65e91ed 462 for (i = 0; i < nr_heads; i++) {
72ff8943 463 char *private;
e65e91ed
DB
464 posn = to_fetch[i];
465 if (posn->status & REF_STATUS_UPTODATE)
466 continue;
72ff8943
DB
467 if (data->refspecs)
468 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
469 else
c28cce55 470 private = xstrdup(posn->name);
d51b720f
MH
471 if (private) {
472 read_ref(private, posn->old_sha1);
473 free(private);
474 }
e65e91ed 475 }
b962dbdc 476 strbuf_release(&buf);
e65e91ed
DB
477 return 0;
478}
479
fa8c097c
IL
480static int process_connect_service(struct transport *transport,
481 const char *name, const char *exec)
482{
483 struct helper_data *data = transport->data;
484 struct strbuf cmdbuf = STRBUF_INIT;
485 struct child_process *helper;
486 int r, duped, ret = 0;
487 FILE *input;
488
489 helper = get_helper(transport);
490
491 /*
492 * Yes, dup the pipe another time, as we need unbuffered version
493 * of input pipe as FILE*. fclose() closes the underlying fd and
494 * stream buffering only can be changed before first I/O operation
495 * on it.
496 */
497 duped = dup(helper->out);
498 if (duped < 0)
499 die_errno("Can't dup helper output fd");
500 input = xfdopen(duped, "r");
501 setvbuf(input, NULL, _IONBF, 0);
502
503 /*
504 * Handle --upload-pack and friends. This is fire and forget...
505 * just warn if it fails.
506 */
507 if (strcmp(name, exec)) {
508 r = set_helper_option(transport, "servpath", exec);
509 if (r > 0)
510 warning("Setting remote service path not supported by protocol.");
511 else if (r < 0)
512 warning("Invalid remote service path.");
513 }
514
515 if (data->connect)
516 strbuf_addf(&cmdbuf, "connect %s\n", name);
517 else
518 goto exit;
519
520 sendline(data, &cmdbuf);
521 recvline_fh(input, &cmdbuf);
522 if (!strcmp(cmdbuf.buf, "")) {
523 data->no_disconnect_req = 1;
524 if (debug)
525 fprintf(stderr, "Debug: Smart transport connection "
526 "ready.\n");
527 ret = 1;
528 } else if (!strcmp(cmdbuf.buf, "fallback")) {
529 if (debug)
530 fprintf(stderr, "Debug: Falling back to dumb "
531 "transport.\n");
532 } else
533 die("Unknown response to connect: %s",
534 cmdbuf.buf);
535
536exit:
537 fclose(input);
538 return ret;
539}
540
541static int process_connect(struct transport *transport,
542 int for_push)
543{
544 struct helper_data *data = transport->data;
545 const char *name;
546 const char *exec;
547
548 name = for_push ? "git-receive-pack" : "git-upload-pack";
549 if (for_push)
550 exec = data->transport_options.receivepack;
551 else
552 exec = data->transport_options.uploadpack;
553
554 return process_connect_service(transport, name, exec);
555}
556
b236752a
IL
557static int connect_helper(struct transport *transport, const char *name,
558 const char *exec, int fd[2])
559{
560 struct helper_data *data = transport->data;
561
562 /* Get_helper so connect is inited. */
563 get_helper(transport);
564 if (!data->connect)
565 die("Operation not supported by protocol.");
566
567 if (!process_connect_service(transport, name, exec))
568 die("Can't connect to subservice %s.", name);
569
570 fd[0] = data->helper->out;
571 fd[1] = data->helper->in;
572 return 0;
573}
574
6eb996b5 575static int fetch(struct transport *transport,
37148311 576 int nr_heads, struct ref **to_fetch)
6eb996b5
DB
577{
578 struct helper_data *data = transport->data;
579 int i, count;
580
fa8c097c
IL
581 if (process_connect(transport, 0)) {
582 do_take_over(transport);
583 return transport->fetch(transport, nr_heads, to_fetch);
584 }
585
6eb996b5
DB
586 count = 0;
587 for (i = 0; i < nr_heads; i++)
588 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
589 count++;
590
591 if (!count)
592 return 0;
593
594 if (data->fetch)
595 return fetch_with_fetch(transport, nr_heads, to_fetch);
596
e65e91ed
DB
597 if (data->import)
598 return fetch_with_import(transport, nr_heads, to_fetch);
599
6eb996b5
DB
600 return -1;
601}
602
d2e73c6f
SR
603static void push_update_ref_status(struct strbuf *buf,
604 struct ref **ref,
605 struct ref *remote_refs)
606{
607 char *refname, *msg;
608 int status;
609
610 if (!prefixcmp(buf->buf, "ok ")) {
611 status = REF_STATUS_OK;
612 refname = buf->buf + 3;
613 } else if (!prefixcmp(buf->buf, "error ")) {
614 status = REF_STATUS_REMOTE_REJECT;
615 refname = buf->buf + 6;
616 } else
82247e9b 617 die("expected ok/error, helper said '%s'", buf->buf);
d2e73c6f
SR
618
619 msg = strchr(refname, ' ');
620 if (msg) {
621 struct strbuf msg_buf = STRBUF_INIT;
622 const char *end;
623
624 *msg++ = '\0';
625 if (!unquote_c_style(&msg_buf, msg, &end))
626 msg = strbuf_detach(&msg_buf, NULL);
627 else
628 msg = xstrdup(msg);
629 strbuf_release(&msg_buf);
630
631 if (!strcmp(msg, "no match")) {
632 status = REF_STATUS_NONE;
633 free(msg);
634 msg = NULL;
635 }
636 else if (!strcmp(msg, "up to date")) {
637 status = REF_STATUS_UPTODATE;
638 free(msg);
639 msg = NULL;
640 }
641 else if (!strcmp(msg, "non-fast forward")) {
642 status = REF_STATUS_REJECT_NONFASTFORWARD;
643 free(msg);
644 msg = NULL;
645 }
646 }
647
648 if (*ref)
649 *ref = find_ref_by_name(*ref, refname);
650 if (!*ref)
651 *ref = find_ref_by_name(remote_refs, refname);
652 if (!*ref) {
653 warning("helper reported unexpected status of %s", refname);
654 return;
655 }
656
657 if ((*ref)->status != REF_STATUS_NONE) {
658 /*
659 * Earlier, the ref was marked not to be pushed, so ignore the ref
660 * status reported by the remote helper if the latter is 'no match'.
661 */
662 if (status == REF_STATUS_NONE)
663 return;
664 }
665
666 (*ref)->status = status;
667 (*ref)->remote_status = msg;
668}
669
670static void push_update_refs_status(struct helper_data *data,
671 struct ref *remote_refs)
672{
673 struct strbuf buf = STRBUF_INIT;
674 struct ref *ref = remote_refs;
675 for (;;) {
676 recvline(data, &buf);
677 if (!buf.len)
678 break;
679
680 push_update_ref_status(&buf, &ref, remote_refs);
681 }
682 strbuf_release(&buf);
683}
684
73b49a75 685static int push_refs_with_push(struct transport *transport,
ae4efe19
SP
686 struct ref *remote_refs, int flags)
687{
688 int force_all = flags & TRANSPORT_PUSH_FORCE;
689 int mirror = flags & TRANSPORT_PUSH_MIRROR;
690 struct helper_data *data = transport->data;
691 struct strbuf buf = STRBUF_INIT;
ae4efe19
SP
692 struct ref *ref;
693
c0aa335c 694 get_helper(transport);
ae4efe19
SP
695 if (!data->push)
696 return 1;
697
698 for (ref = remote_refs; ref; ref = ref->next) {
20e8b465 699 if (!ref->peer_ref && !mirror)
ae4efe19
SP
700 continue;
701
20e8b465
TRC
702 /* Check for statuses set by set_ref_status_for_push() */
703 switch (ref->status) {
704 case REF_STATUS_REJECT_NONFASTFORWARD:
705 case REF_STATUS_UPTODATE:
ae4efe19 706 continue;
20e8b465
TRC
707 default:
708 ; /* do nothing */
ae4efe19
SP
709 }
710
711 if (force_all)
712 ref->force = 1;
713
714 strbuf_addstr(&buf, "push ");
715 if (!ref->deletion) {
716 if (ref->force)
717 strbuf_addch(&buf, '+');
718 if (ref->peer_ref)
719 strbuf_addstr(&buf, ref->peer_ref->name);
720 else
721 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
722 }
723 strbuf_addch(&buf, ':');
724 strbuf_addstr(&buf, ref->name);
725 strbuf_addch(&buf, '\n');
726 }
d8f67d20
CB
727 if (buf.len == 0)
728 return 0;
ae4efe19 729
ae4efe19
SP
730 standard_options(transport);
731
732 if (flags & TRANSPORT_PUSH_DRY_RUN) {
733 if (set_helper_option(transport, "dry-run", "true") != 0)
734 die("helper %s does not support dry-run", data->name);
735 }
736
737 strbuf_addch(&buf, '\n');
bf3c523c 738 sendline(data, &buf);
ae4efe19 739 strbuf_release(&buf);
d2e73c6f
SR
740
741 push_update_refs_status(data, remote_refs);
ae4efe19
SP
742 return 0;
743}
744
73b49a75
SR
745static int push_refs_with_export(struct transport *transport,
746 struct ref *remote_refs, int flags)
747{
748 struct ref *ref;
749 struct child_process *helper, exporter;
750 struct helper_data *data = transport->data;
183113a5 751 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
73b49a75
SR
752 struct strbuf buf = STRBUF_INIT;
753
754 helper = get_helper(transport);
755
756 write_constant(helper->in, "export\n");
757
73b49a75
SR
758 strbuf_reset(&buf);
759
760 for (ref = remote_refs; ref; ref = ref->next) {
761 char *private;
762 unsigned char sha1[20];
763
764 if (!data->refspecs)
765 continue;
766 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
767 if (private && !get_sha1(private, sha1)) {
768 strbuf_addf(&buf, "^%s", private);
1d2f80fa 769 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
73b49a75 770 }
2faa1527 771 free(private);
73b49a75 772
105fe3e4
SR
773 if (ref->deletion) {
774 die("remote-helpers do not support ref deletion");
775 }
776
3ea7d094
JK
777 if (ref->peer_ref)
778 string_list_append(&revlist_args, ref->peer_ref->name);
73b49a75
SR
779
780 }
781
a515ebe9 782 if (get_exporter(transport, &exporter, &revlist_args))
73b49a75
SR
783 die("Couldn't run fast-export");
784
cc567322
SR
785 if (finish_command(&exporter))
786 die("Error while running fast-export");
6c8151a3 787 push_update_refs_status(data, remote_refs);
73b49a75
SR
788 return 0;
789}
790
791static int push_refs(struct transport *transport,
792 struct ref *remote_refs, int flags)
793{
794 struct helper_data *data = transport->data;
795
796 if (process_connect(transport, 1)) {
797 do_take_over(transport);
798 return transport->push_refs(transport, remote_refs, flags);
799 }
800
801 if (!remote_refs) {
802 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
803 "Perhaps you should specify a branch such as 'master'.\n");
804 return 0;
805 }
806
807 if (data->push)
808 return push_refs_with_push(transport, remote_refs, flags);
809
810 if (data->export)
811 return push_refs_with_export(transport, remote_refs, flags);
812
813 return -1;
814}
815
816
f8ec9167
DB
817static int has_attribute(const char *attrs, const char *attr) {
818 int len;
819 if (!attrs)
820 return 0;
821
822 len = strlen(attr);
823 for (;;) {
824 const char *space = strchrnul(attrs, ' ');
825 if (len == space - attrs && !strncmp(attrs, attr, len))
826 return 1;
827 if (!*space)
828 return 0;
829 attrs = space + 1;
830 }
831}
832
6eb996b5
DB
833static struct ref *get_refs_list(struct transport *transport, int for_push)
834{
292ce46b 835 struct helper_data *data = transport->data;
6eb996b5
DB
836 struct child_process *helper;
837 struct ref *ret = NULL;
838 struct ref **tail = &ret;
839 struct ref *posn;
840 struct strbuf buf = STRBUF_INIT;
6eb996b5
DB
841
842 helper = get_helper(transport);
2d14d65c 843
fa8c097c
IL
844 if (process_connect(transport, for_push)) {
845 do_take_over(transport);
846 return transport->get_refs_list(transport, for_push);
847 }
848
ae4efe19
SP
849 if (data->push && for_push)
850 write_str_in_full(helper->in, "list for-push\n");
851 else
852 write_str_in_full(helper->in, "list\n");
6eb996b5 853
6eb996b5
DB
854 while (1) {
855 char *eov, *eon;
bf3c523c 856 recvline(data, &buf);
6eb996b5
DB
857
858 if (!*buf.buf)
859 break;
860
861 eov = strchr(buf.buf, ' ');
862 if (!eov)
863 die("Malformed response in ref list: %s", buf.buf);
864 eon = strchr(eov + 1, ' ');
865 *eov = '\0';
866 if (eon)
867 *eon = '\0';
868 *tail = alloc_ref(eov + 1);
869 if (buf.buf[0] == '@')
870 (*tail)->symref = xstrdup(buf.buf + 1);
871 else if (buf.buf[0] != '?')
872 get_sha1_hex(buf.buf, (*tail)->old_sha1);
f8ec9167
DB
873 if (eon) {
874 if (has_attribute(eon + 1, "unchanged")) {
875 (*tail)->status |= REF_STATUS_UPTODATE;
876 read_ref((*tail)->name, (*tail)->old_sha1);
877 }
878 }
6eb996b5
DB
879 tail = &((*tail)->next);
880 }
bf3c523c
IL
881 if (debug)
882 fprintf(stderr, "Debug: Read ref listing.\n");
6eb996b5
DB
883 strbuf_release(&buf);
884
885 for (posn = ret; posn; posn = posn->next)
886 resolve_remote_symref(posn, ret);
887
888 return ret;
889}
890
c9e388bb 891int transport_helper_init(struct transport *transport, const char *name)
6eb996b5
DB
892{
893 struct helper_data *data = xcalloc(sizeof(*data), 1);
c9e388bb 894 data->name = name;
6eb996b5 895
bf3c523c
IL
896 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
897 debug = 1;
898
6eb996b5 899 transport->data = data;
ef08ef9e 900 transport->set_option = set_helper_option;
6eb996b5
DB
901 transport->get_refs_list = get_refs_list;
902 transport->fetch = fetch;
ae4efe19 903 transport->push_refs = push_refs;
f2a37151 904 transport->disconnect = release_helper;
b236752a 905 transport->connect = connect_helper;
61b075bd 906 transport->smart_options = &(data->transport_options);
6eb996b5
DB
907 return 0;
908}
419f37db
IL
909
910/*
911 * Linux pipes can buffer 65536 bytes at once (and most platforms can
912 * buffer less), so attempt reads and writes with up to that size.
913 */
914#define BUFFERSIZE 65536
915/* This should be enough to hold debugging message. */
916#define PBUFFERSIZE 8192
917
918/* Print bidirectional transfer loop debug message. */
919static void transfer_debug(const char *fmt, ...)
920{
921 va_list args;
922 char msgbuf[PBUFFERSIZE];
923 static int debug_enabled = -1;
924
925 if (debug_enabled < 0)
926 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
927 if (!debug_enabled)
928 return;
929
930 va_start(args, fmt);
931 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
932 va_end(args);
933 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
934}
935
936/* Stream state: More data may be coming in this direction. */
937#define SSTATE_TRANSFERING 0
938/*
939 * Stream state: No more data coming in this direction, flushing rest of
940 * data.
941 */
942#define SSTATE_FLUSHING 1
943/* Stream state: Transfer in this direction finished. */
944#define SSTATE_FINISHED 2
945
946#define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
947#define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
948#define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
949
950/* Unidirectional transfer. */
951struct unidirectional_transfer {
952 /* Source */
953 int src;
954 /* Destination */
955 int dest;
956 /* Is source socket? */
957 int src_is_sock;
958 /* Is destination socket? */
959 int dest_is_sock;
960 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
961 int state;
962 /* Buffer. */
963 char buf[BUFFERSIZE];
964 /* Buffer used. */
965 size_t bufuse;
966 /* Name of source. */
967 const char *src_name;
968 /* Name of destination. */
969 const char *dest_name;
970};
971
972/* Closes the target (for writing) if transfer has finished. */
973static void udt_close_if_finished(struct unidirectional_transfer *t)
974{
975 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
976 t->state = SSTATE_FINISHED;
977 if (t->dest_is_sock)
978 shutdown(t->dest, SHUT_WR);
979 else
980 close(t->dest);
981 transfer_debug("Closed %s.", t->dest_name);
982 }
983}
984
985/*
986 * Tries to read read data from source into buffer. If buffer is full,
987 * no data is read. Returns 0 on success, -1 on error.
988 */
989static int udt_do_read(struct unidirectional_transfer *t)
990{
991 ssize_t bytes;
992
993 if (t->bufuse == BUFFERSIZE)
994 return 0; /* No space for more. */
995
996 transfer_debug("%s is readable", t->src_name);
997 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
998 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
999 errno != EINTR) {
1000 error("read(%s) failed: %s", t->src_name, strerror(errno));
1001 return -1;
1002 } else if (bytes == 0) {
1003 transfer_debug("%s EOF (with %i bytes in buffer)",
1004 t->src_name, t->bufuse);
1005 t->state = SSTATE_FLUSHING;
1006 } else if (bytes > 0) {
1007 t->bufuse += bytes;
1008 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1009 (int)bytes, t->src_name, (int)t->bufuse);
1010 }
1011 return 0;
1012}
1013
1014/* Tries to write data from buffer into destination. If buffer is empty,
1015 * no data is written. Returns 0 on success, -1 on error.
1016 */
1017static int udt_do_write(struct unidirectional_transfer *t)
1018{
803dbdb9 1019 ssize_t bytes;
419f37db
IL
1020
1021 if (t->bufuse == 0)
1022 return 0; /* Nothing to write. */
1023
1024 transfer_debug("%s is writable", t->dest_name);
1025 bytes = write(t->dest, t->buf, t->bufuse);
1026 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1027 errno != EINTR) {
1028 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1029 return -1;
1030 } else if (bytes > 0) {
1031 t->bufuse -= bytes;
1032 if (t->bufuse)
1033 memmove(t->buf, t->buf + bytes, t->bufuse);
1034 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1035 (int)bytes, t->dest_name, (int)t->bufuse);
1036 }
1037 return 0;
1038}
1039
1040
1041/* State of bidirectional transfer loop. */
1042struct bidirectional_transfer_state {
1043 /* Direction from program to git. */
1044 struct unidirectional_transfer ptg;
1045 /* Direction from git to program. */
1046 struct unidirectional_transfer gtp;
1047};
1048
1049static void *udt_copy_task_routine(void *udt)
1050{
1051 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1052 while (t->state != SSTATE_FINISHED) {
1053 if (STATE_NEEDS_READING(t->state))
1054 if (udt_do_read(t))
1055 return NULL;
1056 if (STATE_NEEDS_WRITING(t->state))
1057 if (udt_do_write(t))
1058 return NULL;
1059 if (STATE_NEEDS_CLOSING(t->state))
1060 udt_close_if_finished(t);
1061 }
1062 return udt; /* Just some non-NULL value. */
1063}
1064
1065#ifndef NO_PTHREADS
1066
1067/*
1068 * Join thread, with apporiate errors on failure. Name is name for the
1069 * thread (for error messages). Returns 0 on success, 1 on failure.
1070 */
1071static int tloop_join(pthread_t thread, const char *name)
1072{
1073 int err;
1074 void *tret;
1075 err = pthread_join(thread, &tret);
1076 if (!tret) {
1077 error("%s thread failed", name);
1078 return 1;
1079 }
1080 if (err) {
1081 error("%s thread failed to join: %s", name, strerror(err));
1082 return 1;
1083 }
1084 return 0;
1085}
1086
1087/*
1088 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1089 * -1 on failure.
1090 */
1091static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1092{
1093 pthread_t gtp_thread;
1094 pthread_t ptg_thread;
1095 int err;
1096 int ret = 0;
1097 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1098 &s->gtp);
1099 if (err)
1100 die("Can't start thread for copying data: %s", strerror(err));
1101 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1102 &s->ptg);
1103 if (err)
1104 die("Can't start thread for copying data: %s", strerror(err));
1105
1106 ret |= tloop_join(gtp_thread, "Git to program copy");
1107 ret |= tloop_join(ptg_thread, "Program to git copy");
1108 return ret;
1109}
1110#else
1111
1112/* Close the source and target (for writing) for transfer. */
1113static void udt_kill_transfer(struct unidirectional_transfer *t)
1114{
1115 t->state = SSTATE_FINISHED;
1116 /*
1117 * Socket read end left open isn't a disaster if nobody
1118 * attempts to read from it (mingw compat headers do not
1119 * have SHUT_RD)...
1120 *
1121 * We can't fully close the socket since otherwise gtp
1122 * task would first close the socket it sends data to
1123 * while closing the ptg file descriptors.
1124 */
1125 if (!t->src_is_sock)
1126 close(t->src);
1127 if (t->dest_is_sock)
1128 shutdown(t->dest, SHUT_WR);
1129 else
1130 close(t->dest);
1131}
1132
1133/*
1134 * Join process, with apporiate errors on failure. Name is name for the
1135 * process (for error messages). Returns 0 on success, 1 on failure.
1136 */
1137static int tloop_join(pid_t pid, const char *name)
1138{
1139 int tret;
1140 if (waitpid(pid, &tret, 0) < 0) {
1141 error("%s process failed to wait: %s", name, strerror(errno));
1142 return 1;
1143 }
1144 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1145 error("%s process failed", name);
1146 return 1;
1147 }
1148 return 0;
1149}
1150
1151/*
1152 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1153 * -1 on failure.
1154 */
1155static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1156{
1157 pid_t pid1, pid2;
1158 int ret = 0;
1159
1160 /* Fork thread #1: git to program. */
1161 pid1 = fork();
1162 if (pid1 < 0)
1163 die_errno("Can't start thread for copying data");
1164 else if (pid1 == 0) {
1165 udt_kill_transfer(&s->ptg);
1166 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1167 }
1168
1169 /* Fork thread #2: program to git. */
1170 pid2 = fork();
1171 if (pid2 < 0)
1172 die_errno("Can't start thread for copying data");
1173 else if (pid2 == 0) {
1174 udt_kill_transfer(&s->gtp);
1175 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1176 }
1177
1178 /*
1179 * Close both streams in parent as to not interfere with
1180 * end of file detection and wait for both tasks to finish.
1181 */
1182 udt_kill_transfer(&s->gtp);
1183 udt_kill_transfer(&s->ptg);
1184 ret |= tloop_join(pid1, "Git to program copy");
1185 ret |= tloop_join(pid2, "Program to git copy");
1186 return ret;
1187}
1188#endif
1189
1190/*
1191 * Copies data from stdin to output and from input to stdout simultaneously.
1192 * Additionally filtering through given filter. If filter is NULL, uses
1193 * identity filter.
1194 */
1195int bidirectional_transfer_loop(int input, int output)
1196{
1197 struct bidirectional_transfer_state state;
1198
1199 /* Fill the state fields. */
1200 state.ptg.src = input;
1201 state.ptg.dest = 1;
1202 state.ptg.src_is_sock = (input == output);
1203 state.ptg.dest_is_sock = 0;
1204 state.ptg.state = SSTATE_TRANSFERING;
1205 state.ptg.bufuse = 0;
1206 state.ptg.src_name = "remote input";
1207 state.ptg.dest_name = "stdout";
1208
1209 state.gtp.src = 0;
1210 state.gtp.dest = output;
1211 state.gtp.src_is_sock = 0;
1212 state.gtp.dest_is_sock = (input == output);
1213 state.gtp.state = SSTATE_TRANSFERING;
1214 state.gtp.bufuse = 0;
1215 state.gtp.src_name = "stdin";
1216 state.gtp.dest_name = "remote output";
1217
1218 return tloop_spawnwait_tasks(&state);
1219}