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