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