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