pkt-line: define PACKET_READ_RESPONSE_END
[git] / remote-curl.c
1 #include "cache.h"
2 #include "config.h"
3 #include "remote.h"
4 #include "connect.h"
5 #include "strbuf.h"
6 #include "walker.h"
7 #include "http.h"
8 #include "exec-cmd.h"
9 #include "run-command.h"
10 #include "pkt-line.h"
11 #include "string-list.h"
12 #include "sideband.h"
13 #include "argv-array.h"
14 #include "credential.h"
15 #include "oid-array.h"
16 #include "send-pack.h"
17 #include "protocol.h"
18 #include "quote.h"
19 #include "transport.h"
20
21 static struct remote *remote;
22 /* always ends with a trailing slash */
23 static struct strbuf url = STRBUF_INIT;
24
25 struct options {
26         int verbosity;
27         unsigned long depth;
28         char *deepen_since;
29         struct string_list deepen_not;
30         struct string_list push_options;
31         char *filter;
32         unsigned progress : 1,
33                 check_self_contained_and_connected : 1,
34                 cloning : 1,
35                 update_shallow : 1,
36                 followtags : 1,
37                 dry_run : 1,
38                 thin : 1,
39                 /* One of the SEND_PACK_PUSH_CERT_* constants. */
40                 push_cert : 2,
41                 deepen_relative : 1,
42                 from_promisor : 1,
43                 no_dependents : 1,
44                 atomic : 1;
45 };
46 static struct options options;
47 static struct string_list cas_options = STRING_LIST_INIT_DUP;
48
49 static int set_option(const char *name, const char *value)
50 {
51         if (!strcmp(name, "verbosity")) {
52                 char *end;
53                 int v = strtol(value, &end, 10);
54                 if (value == end || *end)
55                         return -1;
56                 options.verbosity = v;
57                 return 0;
58         }
59         else if (!strcmp(name, "progress")) {
60                 if (!strcmp(value, "true"))
61                         options.progress = 1;
62                 else if (!strcmp(value, "false"))
63                         options.progress = 0;
64                 else
65                         return -1;
66                 return 0;
67         }
68         else if (!strcmp(name, "depth")) {
69                 char *end;
70                 unsigned long v = strtoul(value, &end, 10);
71                 if (value == end || *end)
72                         return -1;
73                 options.depth = v;
74                 return 0;
75         }
76         else if (!strcmp(name, "deepen-since")) {
77                 options.deepen_since = xstrdup(value);
78                 return 0;
79         }
80         else if (!strcmp(name, "deepen-not")) {
81                 string_list_append(&options.deepen_not, value);
82                 return 0;
83         }
84         else if (!strcmp(name, "deepen-relative")) {
85                 if (!strcmp(value, "true"))
86                         options.deepen_relative = 1;
87                 else if (!strcmp(value, "false"))
88                         options.deepen_relative = 0;
89                 else
90                         return -1;
91                 return 0;
92         }
93         else if (!strcmp(name, "followtags")) {
94                 if (!strcmp(value, "true"))
95                         options.followtags = 1;
96                 else if (!strcmp(value, "false"))
97                         options.followtags = 0;
98                 else
99                         return -1;
100                 return 0;
101         }
102         else if (!strcmp(name, "dry-run")) {
103                 if (!strcmp(value, "true"))
104                         options.dry_run = 1;
105                 else if (!strcmp(value, "false"))
106                         options.dry_run = 0;
107                 else
108                         return -1;
109                 return 0;
110         }
111         else if (!strcmp(name, "check-connectivity")) {
112                 if (!strcmp(value, "true"))
113                         options.check_self_contained_and_connected = 1;
114                 else if (!strcmp(value, "false"))
115                         options.check_self_contained_and_connected = 0;
116                 else
117                         return -1;
118                 return 0;
119         }
120         else if (!strcmp(name, "cas")) {
121                 struct strbuf val = STRBUF_INIT;
122                 strbuf_addf(&val, "--" CAS_OPT_NAME "=%s", value);
123                 string_list_append(&cas_options, val.buf);
124                 strbuf_release(&val);
125                 return 0;
126         } else if (!strcmp(name, "cloning")) {
127                 if (!strcmp(value, "true"))
128                         options.cloning = 1;
129                 else if (!strcmp(value, "false"))
130                         options.cloning = 0;
131                 else
132                         return -1;
133                 return 0;
134         } else if (!strcmp(name, "update-shallow")) {
135                 if (!strcmp(value, "true"))
136                         options.update_shallow = 1;
137                 else if (!strcmp(value, "false"))
138                         options.update_shallow = 0;
139                 else
140                         return -1;
141                 return 0;
142         } else if (!strcmp(name, "pushcert")) {
143                 if (!strcmp(value, "true"))
144                         options.push_cert = SEND_PACK_PUSH_CERT_ALWAYS;
145                 else if (!strcmp(value, "false"))
146                         options.push_cert = SEND_PACK_PUSH_CERT_NEVER;
147                 else if (!strcmp(value, "if-asked"))
148                         options.push_cert = SEND_PACK_PUSH_CERT_IF_ASKED;
149                 else
150                         return -1;
151                 return 0;
152         } else if (!strcmp(name, "atomic")) {
153                 if (!strcmp(value, "true"))
154                         options.atomic = 1;
155                 else if (!strcmp(value, "false"))
156                         options.atomic = 0;
157                 else
158                         return -1;
159                 return 0;
160         } else if (!strcmp(name, "push-option")) {
161                 if (*value != '"')
162                         string_list_append(&options.push_options, value);
163                 else {
164                         struct strbuf unquoted = STRBUF_INIT;
165                         if (unquote_c_style(&unquoted, value, NULL) < 0)
166                                 die(_("invalid quoting in push-option value: '%s'"), value);
167                         string_list_append_nodup(&options.push_options,
168                                                  strbuf_detach(&unquoted, NULL));
169                 }
170                 return 0;
171
172 #if LIBCURL_VERSION_NUM >= 0x070a08
173         } else if (!strcmp(name, "family")) {
174                 if (!strcmp(value, "ipv4"))
175                         git_curl_ipresolve = CURL_IPRESOLVE_V4;
176                 else if (!strcmp(value, "ipv6"))
177                         git_curl_ipresolve = CURL_IPRESOLVE_V6;
178                 else if (!strcmp(value, "all"))
179                         git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
180                 else
181                         return -1;
182                 return 0;
183 #endif /* LIBCURL_VERSION_NUM >= 0x070a08 */
184         } else if (!strcmp(name, "from-promisor")) {
185                 options.from_promisor = 1;
186                 return 0;
187         } else if (!strcmp(name, "no-dependents")) {
188                 options.no_dependents = 1;
189                 return 0;
190         } else if (!strcmp(name, "filter")) {
191                 options.filter = xstrdup(value);
192                 return 0;
193         } else {
194                 return 1 /* unsupported */;
195         }
196 }
197
198 struct discovery {
199         char *service;
200         char *buf_alloc;
201         char *buf;
202         size_t len;
203         struct ref *refs;
204         struct oid_array shallow;
205         enum protocol_version version;
206         unsigned proto_git : 1;
207 };
208 static struct discovery *last_discovery;
209
210 static struct ref *parse_git_refs(struct discovery *heads, int for_push)
211 {
212         struct ref *list = NULL;
213         struct packet_reader reader;
214
215         packet_reader_init(&reader, -1, heads->buf, heads->len,
216                            PACKET_READ_CHOMP_NEWLINE |
217                            PACKET_READ_GENTLE_ON_EOF |
218                            PACKET_READ_DIE_ON_ERR_PACKET);
219
220         heads->version = discover_version(&reader);
221         switch (heads->version) {
222         case protocol_v2:
223                 /*
224                  * Do nothing.  This isn't a list of refs but rather a
225                  * capability advertisement.  Client would have run
226                  * 'stateless-connect' so we'll dump this capability listing
227                  * and let them request the refs themselves.
228                  */
229                 break;
230         case protocol_v1:
231         case protocol_v0:
232                 get_remote_heads(&reader, &list, for_push ? REF_NORMAL : 0,
233                                  NULL, &heads->shallow);
234                 break;
235         case protocol_unknown_version:
236                 BUG("unknown protocol version");
237         }
238
239         return list;
240 }
241
242 static struct ref *parse_info_refs(struct discovery *heads)
243 {
244         char *data, *start, *mid;
245         char *ref_name;
246         int i = 0;
247
248         struct ref *refs = NULL;
249         struct ref *ref = NULL;
250         struct ref *last_ref = NULL;
251
252         data = heads->buf;
253         start = NULL;
254         mid = data;
255         while (i < heads->len) {
256                 if (!start) {
257                         start = &data[i];
258                 }
259                 if (data[i] == '\t')
260                         mid = &data[i];
261                 if (data[i] == '\n') {
262                         if (mid - start != the_hash_algo->hexsz)
263                                 die(_("%sinfo/refs not valid: is this a git repository?"),
264                                     transport_anonymize_url(url.buf));
265                         data[i] = 0;
266                         ref_name = mid + 1;
267                         ref = alloc_ref(ref_name);
268                         get_oid_hex(start, &ref->old_oid);
269                         if (!refs)
270                                 refs = ref;
271                         if (last_ref)
272                                 last_ref->next = ref;
273                         last_ref = ref;
274                         start = NULL;
275                 }
276                 i++;
277         }
278
279         ref = alloc_ref("HEAD");
280         if (!http_fetch_ref(url.buf, ref) &&
281             !resolve_remote_symref(ref, refs)) {
282                 ref->next = refs;
283                 refs = ref;
284         } else {
285                 free(ref);
286         }
287
288         return refs;
289 }
290
291 static void free_discovery(struct discovery *d)
292 {
293         if (d) {
294                 if (d == last_discovery)
295                         last_discovery = NULL;
296                 free(d->shallow.oid);
297                 free(d->buf_alloc);
298                 free_refs(d->refs);
299                 free(d->service);
300                 free(d);
301         }
302 }
303
304 static int show_http_message(struct strbuf *type, struct strbuf *charset,
305                              struct strbuf *msg)
306 {
307         const char *p, *eol;
308
309         /*
310          * We only show text/plain parts, as other types are likely
311          * to be ugly to look at on the user's terminal.
312          */
313         if (strcmp(type->buf, "text/plain"))
314                 return -1;
315         if (charset->len)
316                 strbuf_reencode(msg, charset->buf, get_log_output_encoding());
317
318         strbuf_trim(msg);
319         if (!msg->len)
320                 return -1;
321
322         p = msg->buf;
323         do {
324                 eol = strchrnul(p, '\n');
325                 fprintf(stderr, "remote: %.*s\n", (int)(eol - p), p);
326                 p = eol + 1;
327         } while(*eol);
328         return 0;
329 }
330
331 static int get_protocol_http_header(enum protocol_version version,
332                                     struct strbuf *header)
333 {
334         if (version > 0) {
335                 strbuf_addf(header, GIT_PROTOCOL_HEADER ": version=%d",
336                             version);
337
338                 return 1;
339         }
340
341         return 0;
342 }
343
344 static void check_smart_http(struct discovery *d, const char *service,
345                              struct strbuf *type)
346 {
347         const char *p;
348         struct packet_reader reader;
349
350         /*
351          * If we don't see x-$service-advertisement, then it's not smart-http.
352          * But once we do, we commit to it and assume any other protocol
353          * violations are hard errors.
354          */
355         if (!skip_prefix(type->buf, "application/x-", &p) ||
356             !skip_prefix(p, service, &p) ||
357             strcmp(p, "-advertisement"))
358                 return;
359
360         packet_reader_init(&reader, -1, d->buf, d->len,
361                            PACKET_READ_CHOMP_NEWLINE |
362                            PACKET_READ_DIE_ON_ERR_PACKET);
363         if (packet_reader_read(&reader) != PACKET_READ_NORMAL)
364                 die(_("invalid server response; expected service, got flush packet"));
365
366         if (skip_prefix(reader.line, "# service=", &p) && !strcmp(p, service)) {
367                 /*
368                  * The header can include additional metadata lines, up
369                  * until a packet flush marker.  Ignore these now, but
370                  * in the future we might start to scan them.
371                  */
372                 for (;;) {
373                         packet_reader_read(&reader);
374                         if (reader.pktlen <= 0) {
375                                 break;
376                         }
377                 }
378
379                 /*
380                  * v0 smart http; callers expect us to soak up the
381                  * service and header packets
382                  */
383                 d->buf = reader.src_buffer;
384                 d->len = reader.src_len;
385                 d->proto_git = 1;
386
387         } else if (!strcmp(reader.line, "version 2")) {
388                 /*
389                  * v2 smart http; do not consume version packet, which will
390                  * be handled elsewhere.
391                  */
392                 d->proto_git = 1;
393
394         } else {
395                 die(_("invalid server response; got '%s'"), reader.line);
396         }
397 }
398
399 static struct discovery *discover_refs(const char *service, int for_push)
400 {
401         struct strbuf type = STRBUF_INIT;
402         struct strbuf charset = STRBUF_INIT;
403         struct strbuf buffer = STRBUF_INIT;
404         struct strbuf refs_url = STRBUF_INIT;
405         struct strbuf effective_url = STRBUF_INIT;
406         struct strbuf protocol_header = STRBUF_INIT;
407         struct string_list extra_headers = STRING_LIST_INIT_DUP;
408         struct discovery *last = last_discovery;
409         int http_ret, maybe_smart = 0;
410         struct http_get_options http_options;
411         enum protocol_version version = get_protocol_version_config();
412
413         if (last && !strcmp(service, last->service))
414                 return last;
415         free_discovery(last);
416
417         strbuf_addf(&refs_url, "%sinfo/refs", url.buf);
418         if ((starts_with(url.buf, "http://") || starts_with(url.buf, "https://")) &&
419              git_env_bool("GIT_SMART_HTTP", 1)) {
420                 maybe_smart = 1;
421                 if (!strchr(url.buf, '?'))
422                         strbuf_addch(&refs_url, '?');
423                 else
424                         strbuf_addch(&refs_url, '&');
425                 strbuf_addf(&refs_url, "service=%s", service);
426         }
427
428         /*
429          * NEEDSWORK: If we are trying to use protocol v2 and we are planning
430          * to perform a push, then fallback to v0 since the client doesn't know
431          * how to push yet using v2.
432          */
433         if (version == protocol_v2 && !strcmp("git-receive-pack", service))
434                 version = protocol_v0;
435
436         /* Add the extra Git-Protocol header */
437         if (get_protocol_http_header(version, &protocol_header))
438                 string_list_append(&extra_headers, protocol_header.buf);
439
440         memset(&http_options, 0, sizeof(http_options));
441         http_options.content_type = &type;
442         http_options.charset = &charset;
443         http_options.effective_url = &effective_url;
444         http_options.base_url = &url;
445         http_options.extra_headers = &extra_headers;
446         http_options.initial_request = 1;
447         http_options.no_cache = 1;
448
449         http_ret = http_get_strbuf(refs_url.buf, &buffer, &http_options);
450         switch (http_ret) {
451         case HTTP_OK:
452                 break;
453         case HTTP_MISSING_TARGET:
454                 show_http_message(&type, &charset, &buffer);
455                 die(_("repository '%s' not found"),
456                     transport_anonymize_url(url.buf));
457         case HTTP_NOAUTH:
458                 show_http_message(&type, &charset, &buffer);
459                 die(_("Authentication failed for '%s'"),
460                     transport_anonymize_url(url.buf));
461         default:
462                 show_http_message(&type, &charset, &buffer);
463                 die(_("unable to access '%s': %s"),
464                     transport_anonymize_url(url.buf), curl_errorstr);
465         }
466
467         if (options.verbosity && !starts_with(refs_url.buf, url.buf)) {
468                 char *u = transport_anonymize_url(url.buf);
469                 warning(_("redirecting to %s"), u);
470                 free(u);
471         }
472
473         last= xcalloc(1, sizeof(*last_discovery));
474         last->service = xstrdup(service);
475         last->buf_alloc = strbuf_detach(&buffer, &last->len);
476         last->buf = last->buf_alloc;
477
478         if (maybe_smart)
479                 check_smart_http(last, service, &type);
480
481         if (last->proto_git)
482                 last->refs = parse_git_refs(last, for_push);
483         else
484                 last->refs = parse_info_refs(last);
485
486         strbuf_release(&refs_url);
487         strbuf_release(&type);
488         strbuf_release(&charset);
489         strbuf_release(&effective_url);
490         strbuf_release(&buffer);
491         strbuf_release(&protocol_header);
492         string_list_clear(&extra_headers, 0);
493         last_discovery = last;
494         return last;
495 }
496
497 static struct ref *get_refs(int for_push)
498 {
499         struct discovery *heads;
500
501         if (for_push)
502                 heads = discover_refs("git-receive-pack", for_push);
503         else
504                 heads = discover_refs("git-upload-pack", for_push);
505
506         return heads->refs;
507 }
508
509 static void output_refs(struct ref *refs)
510 {
511         struct ref *posn;
512         for (posn = refs; posn; posn = posn->next) {
513                 if (posn->symref)
514                         printf("@%s %s\n", posn->symref, posn->name);
515                 else
516                         printf("%s %s\n", oid_to_hex(&posn->old_oid), posn->name);
517         }
518         printf("\n");
519         fflush(stdout);
520 }
521
522 struct rpc_state {
523         const char *service_name;
524         char *service_url;
525         char *hdr_content_type;
526         char *hdr_accept;
527         char *protocol_header;
528         char *buf;
529         size_t alloc;
530         size_t len;
531         size_t pos;
532         int in;
533         int out;
534         int any_written;
535         unsigned gzip_request : 1;
536         unsigned initial_buffer : 1;
537
538         /*
539          * Whenever a pkt-line is read into buf, append the 4 characters
540          * denoting its length before appending the payload.
541          */
542         unsigned write_line_lengths : 1;
543
544         /*
545          * Used by rpc_out; initialize to 0. This is true if a flush has been
546          * read, but the corresponding line length (if write_line_lengths is
547          * true) and EOF have not been sent to libcurl. Since each flush marks
548          * the end of a request, each flush must be completely sent before any
549          * further reading occurs.
550          */
551         unsigned flush_read_but_not_sent : 1;
552 };
553
554 /*
555  * Appends the result of reading from rpc->out to the string represented by
556  * rpc->buf and rpc->len if there is enough space. Returns 1 if there was
557  * enough space, 0 otherwise.
558  *
559  * If rpc->write_line_lengths is true, appends the line length as a 4-byte
560  * hexadecimal string before appending the result described above.
561  *
562  * Writes the total number of bytes appended into appended.
563  */
564 static int rpc_read_from_out(struct rpc_state *rpc, int options,
565                              size_t *appended,
566                              enum packet_read_status *status) {
567         size_t left;
568         char *buf;
569         int pktlen_raw;
570
571         if (rpc->write_line_lengths) {
572                 left = rpc->alloc - rpc->len - 4;
573                 buf = rpc->buf + rpc->len + 4;
574         } else {
575                 left = rpc->alloc - rpc->len;
576                 buf = rpc->buf + rpc->len;
577         }
578
579         if (left < LARGE_PACKET_MAX)
580                 return 0;
581
582         *status = packet_read_with_status(rpc->out, NULL, NULL, buf,
583                         left, &pktlen_raw, options);
584         if (*status != PACKET_READ_EOF) {
585                 *appended = pktlen_raw + (rpc->write_line_lengths ? 4 : 0);
586                 rpc->len += *appended;
587         }
588
589         if (rpc->write_line_lengths) {
590                 switch (*status) {
591                 case PACKET_READ_EOF:
592                         if (!(options & PACKET_READ_GENTLE_ON_EOF))
593                                 die(_("shouldn't have EOF when not gentle on EOF"));
594                         break;
595                 case PACKET_READ_NORMAL:
596                         set_packet_header(buf - 4, *appended);
597                         break;
598                 case PACKET_READ_DELIM:
599                         memcpy(buf - 4, "0001", 4);
600                         break;
601                 case PACKET_READ_FLUSH:
602                         memcpy(buf - 4, "0000", 4);
603                         break;
604                 case PACKET_READ_RESPONSE_END:
605                         die(_("remote server sent stateless separator"));
606                 }
607         }
608
609         return 1;
610 }
611
612 static size_t rpc_out(void *ptr, size_t eltsize,
613                 size_t nmemb, void *buffer_)
614 {
615         size_t max = eltsize * nmemb;
616         struct rpc_state *rpc = buffer_;
617         size_t avail = rpc->len - rpc->pos;
618         enum packet_read_status status;
619
620         if (!avail) {
621                 rpc->initial_buffer = 0;
622                 rpc->len = 0;
623                 rpc->pos = 0;
624                 if (!rpc->flush_read_but_not_sent) {
625                         if (!rpc_read_from_out(rpc, 0, &avail, &status))
626                                 BUG("The entire rpc->buf should be larger than LARGE_PACKET_MAX");
627                         if (status == PACKET_READ_FLUSH)
628                                 rpc->flush_read_but_not_sent = 1;
629                 }
630                 /*
631                  * If flush_read_but_not_sent is true, we have already read one
632                  * full request but have not fully sent it + EOF, which is why
633                  * we need to refrain from reading.
634                  */
635         }
636         if (rpc->flush_read_but_not_sent) {
637                 if (!avail) {
638                         /*
639                          * The line length either does not need to be sent at
640                          * all or has already been completely sent. Now we can
641                          * return 0, indicating EOF, meaning that the flush has
642                          * been fully sent.
643                          */
644                         rpc->flush_read_but_not_sent = 0;
645                         return 0;
646                 }
647                 /*
648                  * If avail is non-zero, the line length for the flush still
649                  * hasn't been fully sent. Proceed with sending the line
650                  * length.
651                  */
652         }
653
654         if (max < avail)
655                 avail = max;
656         memcpy(ptr, rpc->buf + rpc->pos, avail);
657         rpc->pos += avail;
658         return avail;
659 }
660
661 #ifndef NO_CURL_IOCTL
662 static curlioerr rpc_ioctl(CURL *handle, int cmd, void *clientp)
663 {
664         struct rpc_state *rpc = clientp;
665
666         switch (cmd) {
667         case CURLIOCMD_NOP:
668                 return CURLIOE_OK;
669
670         case CURLIOCMD_RESTARTREAD:
671                 if (rpc->initial_buffer) {
672                         rpc->pos = 0;
673                         return CURLIOE_OK;
674                 }
675                 error(_("unable to rewind rpc post data - try increasing http.postBuffer"));
676                 return CURLIOE_FAILRESTART;
677
678         default:
679                 return CURLIOE_UNKNOWNCMD;
680         }
681 }
682 #endif
683
684 struct check_pktline_state {
685         char len_buf[4];
686         int len_filled;
687         int remaining;
688 };
689
690 static void check_pktline(struct check_pktline_state *state, const char *ptr, size_t size)
691 {
692         while (size) {
693                 if (!state->remaining) {
694                         int digits_remaining = 4 - state->len_filled;
695                         if (digits_remaining > size)
696                                 digits_remaining = size;
697                         memcpy(&state->len_buf[state->len_filled], ptr, digits_remaining);
698                         state->len_filled += digits_remaining;
699                         ptr += digits_remaining;
700                         size -= digits_remaining;
701
702                         if (state->len_filled == 4) {
703                                 state->remaining = packet_length(state->len_buf);
704                                 if (state->remaining < 0) {
705                                         die(_("remote-curl: bad line length character: %.4s"), state->len_buf);
706                                 } else if (state->remaining < 4) {
707                                         state->remaining = 0;
708                                 } else {
709                                         state->remaining -= 4;
710                                 }
711                                 state->len_filled = 0;
712                         }
713                 }
714
715                 if (state->remaining) {
716                         int remaining = state->remaining;
717                         if (remaining > size)
718                                 remaining = size;
719                         ptr += remaining;
720                         size -= remaining;
721                         state->remaining -= remaining;
722                 }
723         }
724 }
725
726 struct rpc_in_data {
727         struct rpc_state *rpc;
728         struct active_request_slot *slot;
729         int check_pktline;
730         struct check_pktline_state pktline_state;
731 };
732
733 /*
734  * A callback for CURLOPT_WRITEFUNCTION. The return value is the bytes consumed
735  * from ptr.
736  */
737 static size_t rpc_in(char *ptr, size_t eltsize,
738                 size_t nmemb, void *buffer_)
739 {
740         size_t size = eltsize * nmemb;
741         struct rpc_in_data *data = buffer_;
742         long response_code;
743
744         if (curl_easy_getinfo(data->slot->curl, CURLINFO_RESPONSE_CODE,
745                               &response_code) != CURLE_OK)
746                 return size;
747         if (response_code >= 300)
748                 return size;
749         if (size)
750                 data->rpc->any_written = 1;
751         if (data->check_pktline)
752                 check_pktline(&data->pktline_state, ptr, size);
753         write_or_die(data->rpc->in, ptr, size);
754         return size;
755 }
756
757 static int run_slot(struct active_request_slot *slot,
758                     struct slot_results *results)
759 {
760         int err;
761         struct slot_results results_buf;
762
763         if (!results)
764                 results = &results_buf;
765
766         err = run_one_slot(slot, results);
767
768         if (err != HTTP_OK && err != HTTP_REAUTH) {
769                 struct strbuf msg = STRBUF_INIT;
770                 if (results->http_code && results->http_code != 200)
771                         strbuf_addf(&msg, "HTTP %ld", results->http_code);
772                 if (results->curl_result != CURLE_OK) {
773                         if (msg.len)
774                                 strbuf_addch(&msg, ' ');
775                         strbuf_addf(&msg, "curl %d", results->curl_result);
776                         if (curl_errorstr[0]) {
777                                 strbuf_addch(&msg, ' ');
778                                 strbuf_addstr(&msg, curl_errorstr);
779                         }
780                 }
781                 error(_("RPC failed; %s"), msg.buf);
782                 strbuf_release(&msg);
783         }
784
785         return err;
786 }
787
788 static int probe_rpc(struct rpc_state *rpc, struct slot_results *results)
789 {
790         struct active_request_slot *slot;
791         struct curl_slist *headers = http_copy_default_headers();
792         struct strbuf buf = STRBUF_INIT;
793         int err;
794
795         slot = get_active_slot();
796
797         headers = curl_slist_append(headers, rpc->hdr_content_type);
798         headers = curl_slist_append(headers, rpc->hdr_accept);
799
800         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
801         curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
802         curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
803         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, NULL);
804         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, "0000");
805         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, 4);
806         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
807         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
808         curl_easy_setopt(slot->curl, CURLOPT_FILE, &buf);
809
810         err = run_slot(slot, results);
811
812         curl_slist_free_all(headers);
813         strbuf_release(&buf);
814         return err;
815 }
816
817 static curl_off_t xcurl_off_t(size_t len)
818 {
819         uintmax_t size = len;
820         if (size > maximum_signed_value_of_type(curl_off_t))
821                 die(_("cannot handle pushes this big"));
822         return (curl_off_t)size;
823 }
824
825 /*
826  * If flush_received is true, do not attempt to read any more; just use what's
827  * in rpc->buf.
828  */
829 static int post_rpc(struct rpc_state *rpc, int stateless_connect, int flush_received)
830 {
831         struct active_request_slot *slot;
832         struct curl_slist *headers = http_copy_default_headers();
833         int use_gzip = rpc->gzip_request;
834         char *gzip_body = NULL;
835         size_t gzip_size = 0;
836         int err, large_request = 0;
837         int needs_100_continue = 0;
838         struct rpc_in_data rpc_in_data;
839
840         /* Try to load the entire request, if we can fit it into the
841          * allocated buffer space we can use HTTP/1.0 and avoid the
842          * chunked encoding mess.
843          */
844         if (!flush_received) {
845                 while (1) {
846                         size_t n;
847                         enum packet_read_status status;
848
849                         if (!rpc_read_from_out(rpc, 0, &n, &status)) {
850                                 large_request = 1;
851                                 use_gzip = 0;
852                                 break;
853                         }
854                         if (status == PACKET_READ_FLUSH)
855                                 break;
856                 }
857         }
858
859         if (large_request) {
860                 struct slot_results results;
861
862                 do {
863                         err = probe_rpc(rpc, &results);
864                         if (err == HTTP_REAUTH)
865                                 credential_fill(&http_auth);
866                 } while (err == HTTP_REAUTH);
867                 if (err != HTTP_OK)
868                         return -1;
869
870                 if (results.auth_avail & CURLAUTH_GSSNEGOTIATE)
871                         needs_100_continue = 1;
872         }
873
874         headers = curl_slist_append(headers, rpc->hdr_content_type);
875         headers = curl_slist_append(headers, rpc->hdr_accept);
876         headers = curl_slist_append(headers, needs_100_continue ?
877                 "Expect: 100-continue" : "Expect:");
878
879         /* Add the extra Git-Protocol header */
880         if (rpc->protocol_header)
881                 headers = curl_slist_append(headers, rpc->protocol_header);
882
883 retry:
884         slot = get_active_slot();
885
886         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
887         curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
888         curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
889         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
890
891         if (large_request) {
892                 /* The request body is large and the size cannot be predicted.
893                  * We must use chunked encoding to send it.
894                  */
895                 headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
896                 rpc->initial_buffer = 1;
897                 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, rpc_out);
898                 curl_easy_setopt(slot->curl, CURLOPT_INFILE, rpc);
899 #ifndef NO_CURL_IOCTL
900                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, rpc_ioctl);
901                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, rpc);
902 #endif
903                 if (options.verbosity > 1) {
904                         fprintf(stderr, "POST %s (chunked)\n", rpc->service_name);
905                         fflush(stderr);
906                 }
907
908         } else if (gzip_body) {
909                 /*
910                  * If we are looping to retry authentication, then the previous
911                  * run will have set up the headers and gzip buffer already,
912                  * and we just need to send it.
913                  */
914                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
915                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
916
917         } else if (use_gzip && 1024 < rpc->len) {
918                 /* The client backend isn't giving us compressed data so
919                  * we can try to deflate it ourselves, this may save on
920                  * the transfer time.
921                  */
922                 git_zstream stream;
923                 int ret;
924
925                 git_deflate_init_gzip(&stream, Z_BEST_COMPRESSION);
926                 gzip_size = git_deflate_bound(&stream, rpc->len);
927                 gzip_body = xmalloc(gzip_size);
928
929                 stream.next_in = (unsigned char *)rpc->buf;
930                 stream.avail_in = rpc->len;
931                 stream.next_out = (unsigned char *)gzip_body;
932                 stream.avail_out = gzip_size;
933
934                 ret = git_deflate(&stream, Z_FINISH);
935                 if (ret != Z_STREAM_END)
936                         die(_("cannot deflate request; zlib deflate error %d"), ret);
937
938                 ret = git_deflate_end_gently(&stream);
939                 if (ret != Z_OK)
940                         die(_("cannot deflate request; zlib end error %d"), ret);
941
942                 gzip_size = stream.total_out;
943
944                 headers = curl_slist_append(headers, "Content-Encoding: gzip");
945                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
946                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
947
948                 if (options.verbosity > 1) {
949                         fprintf(stderr, "POST %s (gzip %lu to %lu bytes)\n",
950                                 rpc->service_name,
951                                 (unsigned long)rpc->len, (unsigned long)gzip_size);
952                         fflush(stderr);
953                 }
954         } else {
955                 /* We know the complete request size in advance, use the
956                  * more normal Content-Length approach.
957                  */
958                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, rpc->buf);
959                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(rpc->len));
960                 if (options.verbosity > 1) {
961                         fprintf(stderr, "POST %s (%lu bytes)\n",
962                                 rpc->service_name, (unsigned long)rpc->len);
963                         fflush(stderr);
964                 }
965         }
966
967         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
968         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, rpc_in);
969         rpc_in_data.rpc = rpc;
970         rpc_in_data.slot = slot;
971         rpc_in_data.check_pktline = stateless_connect;
972         memset(&rpc_in_data.pktline_state, 0, sizeof(rpc_in_data.pktline_state));
973         curl_easy_setopt(slot->curl, CURLOPT_FILE, &rpc_in_data);
974         curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
975
976
977         rpc->any_written = 0;
978         err = run_slot(slot, NULL);
979         if (err == HTTP_REAUTH && !large_request) {
980                 credential_fill(&http_auth);
981                 goto retry;
982         }
983         if (err != HTTP_OK)
984                 err = -1;
985
986         if (!rpc->any_written)
987                 err = -1;
988
989         if (rpc_in_data.pktline_state.len_filled)
990                 err = error(_("%d bytes of length header were received"), rpc_in_data.pktline_state.len_filled);
991         if (rpc_in_data.pktline_state.remaining)
992                 err = error(_("%d bytes of body are still expected"), rpc_in_data.pktline_state.remaining);
993
994         curl_slist_free_all(headers);
995         free(gzip_body);
996         return err;
997 }
998
999 static int rpc_service(struct rpc_state *rpc, struct discovery *heads,
1000                        const char **client_argv, const struct strbuf *preamble,
1001                        struct strbuf *rpc_result)
1002 {
1003         const char *svc = rpc->service_name;
1004         struct strbuf buf = STRBUF_INIT;
1005         struct child_process client = CHILD_PROCESS_INIT;
1006         int err = 0;
1007
1008         client.in = -1;
1009         client.out = -1;
1010         client.git_cmd = 1;
1011         client.argv = client_argv;
1012         if (start_command(&client))
1013                 exit(1);
1014         write_or_die(client.in, preamble->buf, preamble->len);
1015         if (heads)
1016                 write_or_die(client.in, heads->buf, heads->len);
1017
1018         rpc->alloc = http_post_buffer;
1019         rpc->buf = xmalloc(rpc->alloc);
1020         rpc->in = client.in;
1021         rpc->out = client.out;
1022
1023         strbuf_addf(&buf, "%s%s", url.buf, svc);
1024         rpc->service_url = strbuf_detach(&buf, NULL);
1025
1026         strbuf_addf(&buf, "Content-Type: application/x-%s-request", svc);
1027         rpc->hdr_content_type = strbuf_detach(&buf, NULL);
1028
1029         strbuf_addf(&buf, "Accept: application/x-%s-result", svc);
1030         rpc->hdr_accept = strbuf_detach(&buf, NULL);
1031
1032         if (get_protocol_http_header(heads->version, &buf))
1033                 rpc->protocol_header = strbuf_detach(&buf, NULL);
1034         else
1035                 rpc->protocol_header = NULL;
1036
1037         while (!err) {
1038                 int n = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
1039                 if (!n)
1040                         break;
1041                 rpc->pos = 0;
1042                 rpc->len = n;
1043                 err |= post_rpc(rpc, 0, 0);
1044         }
1045
1046         close(client.in);
1047         client.in = -1;
1048         if (!err) {
1049                 strbuf_read(rpc_result, client.out, 0);
1050         } else {
1051                 char buf[4096];
1052                 for (;;)
1053                         if (xread(client.out, buf, sizeof(buf)) <= 0)
1054                                 break;
1055         }
1056
1057         close(client.out);
1058         client.out = -1;
1059
1060         err |= finish_command(&client);
1061         free(rpc->service_url);
1062         free(rpc->hdr_content_type);
1063         free(rpc->hdr_accept);
1064         free(rpc->protocol_header);
1065         free(rpc->buf);
1066         strbuf_release(&buf);
1067         return err;
1068 }
1069
1070 static int fetch_dumb(int nr_heads, struct ref **to_fetch)
1071 {
1072         struct walker *walker;
1073         char **targets;
1074         int ret, i;
1075
1076         ALLOC_ARRAY(targets, nr_heads);
1077         if (options.depth || options.deepen_since)
1078                 die(_("dumb http transport does not support shallow capabilities"));
1079         for (i = 0; i < nr_heads; i++)
1080                 targets[i] = xstrdup(oid_to_hex(&to_fetch[i]->old_oid));
1081
1082         walker = get_http_walker(url.buf);
1083         walker->get_verbosely = options.verbosity >= 3;
1084         walker->get_progress = options.progress;
1085         walker->get_recover = 0;
1086         ret = walker_fetch(walker, nr_heads, targets, NULL, NULL);
1087         walker_free(walker);
1088
1089         for (i = 0; i < nr_heads; i++)
1090                 free(targets[i]);
1091         free(targets);
1092
1093         return ret ? error(_("fetch failed.")) : 0;
1094 }
1095
1096 static int fetch_git(struct discovery *heads,
1097         int nr_heads, struct ref **to_fetch)
1098 {
1099         struct rpc_state rpc;
1100         struct strbuf preamble = STRBUF_INIT;
1101         int i, err;
1102         struct argv_array args = ARGV_ARRAY_INIT;
1103         struct strbuf rpc_result = STRBUF_INIT;
1104
1105         argv_array_pushl(&args, "fetch-pack", "--stateless-rpc",
1106                          "--stdin", "--lock-pack", NULL);
1107         if (options.followtags)
1108                 argv_array_push(&args, "--include-tag");
1109         if (options.thin)
1110                 argv_array_push(&args, "--thin");
1111         if (options.verbosity >= 3)
1112                 argv_array_pushl(&args, "-v", "-v", NULL);
1113         if (options.check_self_contained_and_connected)
1114                 argv_array_push(&args, "--check-self-contained-and-connected");
1115         if (options.cloning)
1116                 argv_array_push(&args, "--cloning");
1117         if (options.update_shallow)
1118                 argv_array_push(&args, "--update-shallow");
1119         if (!options.progress)
1120                 argv_array_push(&args, "--no-progress");
1121         if (options.depth)
1122                 argv_array_pushf(&args, "--depth=%lu", options.depth);
1123         if (options.deepen_since)
1124                 argv_array_pushf(&args, "--shallow-since=%s", options.deepen_since);
1125         for (i = 0; i < options.deepen_not.nr; i++)
1126                 argv_array_pushf(&args, "--shallow-exclude=%s",
1127                                  options.deepen_not.items[i].string);
1128         if (options.deepen_relative && options.depth)
1129                 argv_array_push(&args, "--deepen-relative");
1130         if (options.from_promisor)
1131                 argv_array_push(&args, "--from-promisor");
1132         if (options.no_dependents)
1133                 argv_array_push(&args, "--no-dependents");
1134         if (options.filter)
1135                 argv_array_pushf(&args, "--filter=%s", options.filter);
1136         argv_array_push(&args, url.buf);
1137
1138         for (i = 0; i < nr_heads; i++) {
1139                 struct ref *ref = to_fetch[i];
1140                 if (!*ref->name)
1141                         die(_("cannot fetch by sha1 over smart http"));
1142                 packet_buf_write(&preamble, "%s %s\n",
1143                                  oid_to_hex(&ref->old_oid), ref->name);
1144         }
1145         packet_buf_flush(&preamble);
1146
1147         memset(&rpc, 0, sizeof(rpc));
1148         rpc.service_name = "git-upload-pack",
1149         rpc.gzip_request = 1;
1150
1151         err = rpc_service(&rpc, heads, args.argv, &preamble, &rpc_result);
1152         if (rpc_result.len)
1153                 write_or_die(1, rpc_result.buf, rpc_result.len);
1154         strbuf_release(&rpc_result);
1155         strbuf_release(&preamble);
1156         argv_array_clear(&args);
1157         return err;
1158 }
1159
1160 static int fetch(int nr_heads, struct ref **to_fetch)
1161 {
1162         struct discovery *d = discover_refs("git-upload-pack", 0);
1163         if (d->proto_git)
1164                 return fetch_git(d, nr_heads, to_fetch);
1165         else
1166                 return fetch_dumb(nr_heads, to_fetch);
1167 }
1168
1169 static void parse_fetch(struct strbuf *buf)
1170 {
1171         struct ref **to_fetch = NULL;
1172         struct ref *list_head = NULL;
1173         struct ref **list = &list_head;
1174         int alloc_heads = 0, nr_heads = 0;
1175
1176         do {
1177                 const char *p;
1178                 if (skip_prefix(buf->buf, "fetch ", &p)) {
1179                         const char *name;
1180                         struct ref *ref;
1181                         struct object_id old_oid;
1182                         const char *q;
1183
1184                         if (parse_oid_hex(p, &old_oid, &q))
1185                                 die(_("protocol error: expected sha/ref, got '%s'"), p);
1186                         if (*q == ' ')
1187                                 name = q + 1;
1188                         else if (!*q)
1189                                 name = "";
1190                         else
1191                                 die(_("protocol error: expected sha/ref, got '%s'"), p);
1192
1193                         ref = alloc_ref(name);
1194                         oidcpy(&ref->old_oid, &old_oid);
1195
1196                         *list = ref;
1197                         list = &ref->next;
1198
1199                         ALLOC_GROW(to_fetch, nr_heads + 1, alloc_heads);
1200                         to_fetch[nr_heads++] = ref;
1201                 }
1202                 else
1203                         die(_("http transport does not support %s"), buf->buf);
1204
1205                 strbuf_reset(buf);
1206                 if (strbuf_getline_lf(buf, stdin) == EOF)
1207                         return;
1208                 if (!*buf->buf)
1209                         break;
1210         } while (1);
1211
1212         if (fetch(nr_heads, to_fetch))
1213                 exit(128); /* error already reported */
1214         free_refs(list_head);
1215         free(to_fetch);
1216
1217         printf("\n");
1218         fflush(stdout);
1219         strbuf_reset(buf);
1220 }
1221
1222 static int push_dav(int nr_spec, const char **specs)
1223 {
1224         struct child_process child = CHILD_PROCESS_INIT;
1225         size_t i;
1226
1227         child.git_cmd = 1;
1228         argv_array_push(&child.args, "http-push");
1229         argv_array_push(&child.args, "--helper-status");
1230         if (options.dry_run)
1231                 argv_array_push(&child.args, "--dry-run");
1232         if (options.verbosity > 1)
1233                 argv_array_push(&child.args, "--verbose");
1234         argv_array_push(&child.args, url.buf);
1235         for (i = 0; i < nr_spec; i++)
1236                 argv_array_push(&child.args, specs[i]);
1237
1238         if (run_command(&child))
1239                 die(_("git-http-push failed"));
1240         return 0;
1241 }
1242
1243 static int push_git(struct discovery *heads, int nr_spec, const char **specs)
1244 {
1245         struct rpc_state rpc;
1246         int i, err;
1247         struct argv_array args;
1248         struct string_list_item *cas_option;
1249         struct strbuf preamble = STRBUF_INIT;
1250         struct strbuf rpc_result = STRBUF_INIT;
1251
1252         argv_array_init(&args);
1253         argv_array_pushl(&args, "send-pack", "--stateless-rpc", "--helper-status",
1254                          NULL);
1255
1256         if (options.thin)
1257                 argv_array_push(&args, "--thin");
1258         if (options.dry_run)
1259                 argv_array_push(&args, "--dry-run");
1260         if (options.push_cert == SEND_PACK_PUSH_CERT_ALWAYS)
1261                 argv_array_push(&args, "--signed=yes");
1262         else if (options.push_cert == SEND_PACK_PUSH_CERT_IF_ASKED)
1263                 argv_array_push(&args, "--signed=if-asked");
1264         if (options.atomic)
1265                 argv_array_push(&args, "--atomic");
1266         if (options.verbosity == 0)
1267                 argv_array_push(&args, "--quiet");
1268         else if (options.verbosity > 1)
1269                 argv_array_push(&args, "--verbose");
1270         for (i = 0; i < options.push_options.nr; i++)
1271                 argv_array_pushf(&args, "--push-option=%s",
1272                                  options.push_options.items[i].string);
1273         argv_array_push(&args, options.progress ? "--progress" : "--no-progress");
1274         for_each_string_list_item(cas_option, &cas_options)
1275                 argv_array_push(&args, cas_option->string);
1276         argv_array_push(&args, url.buf);
1277
1278         argv_array_push(&args, "--stdin");
1279         for (i = 0; i < nr_spec; i++)
1280                 packet_buf_write(&preamble, "%s\n", specs[i]);
1281         packet_buf_flush(&preamble);
1282
1283         memset(&rpc, 0, sizeof(rpc));
1284         rpc.service_name = "git-receive-pack",
1285
1286         err = rpc_service(&rpc, heads, args.argv, &preamble, &rpc_result);
1287         if (rpc_result.len)
1288                 write_or_die(1, rpc_result.buf, rpc_result.len);
1289         strbuf_release(&rpc_result);
1290         strbuf_release(&preamble);
1291         argv_array_clear(&args);
1292         return err;
1293 }
1294
1295 static int push(int nr_spec, const char **specs)
1296 {
1297         struct discovery *heads = discover_refs("git-receive-pack", 1);
1298         int ret;
1299
1300         if (heads->proto_git)
1301                 ret = push_git(heads, nr_spec, specs);
1302         else
1303                 ret = push_dav(nr_spec, specs);
1304         free_discovery(heads);
1305         return ret;
1306 }
1307
1308 static void parse_push(struct strbuf *buf)
1309 {
1310         struct argv_array specs = ARGV_ARRAY_INIT;
1311         int ret;
1312
1313         do {
1314                 const char *arg;
1315                 if (skip_prefix(buf->buf, "push ", &arg))
1316                         argv_array_push(&specs, arg);
1317                 else
1318                         die(_("http transport does not support %s"), buf->buf);
1319
1320                 strbuf_reset(buf);
1321                 if (strbuf_getline_lf(buf, stdin) == EOF)
1322                         goto free_specs;
1323                 if (!*buf->buf)
1324                         break;
1325         } while (1);
1326
1327         ret = push(specs.argc, specs.argv);
1328         printf("\n");
1329         fflush(stdout);
1330
1331         if (ret)
1332                 exit(128); /* error already reported */
1333
1334 free_specs:
1335         argv_array_clear(&specs);
1336 }
1337
1338 static int stateless_connect(const char *service_name)
1339 {
1340         struct discovery *discover;
1341         struct rpc_state rpc;
1342         struct strbuf buf = STRBUF_INIT;
1343
1344         /*
1345          * Run the info/refs request and see if the server supports protocol
1346          * v2.  If and only if the server supports v2 can we successfully
1347          * establish a stateless connection, otherwise we need to tell the
1348          * client to fallback to using other transport helper functions to
1349          * complete their request.
1350          */
1351         discover = discover_refs(service_name, 0);
1352         if (discover->version != protocol_v2) {
1353                 printf("fallback\n");
1354                 fflush(stdout);
1355                 return -1;
1356         } else {
1357                 /* Stateless Connection established */
1358                 printf("\n");
1359                 fflush(stdout);
1360         }
1361
1362         rpc.service_name = service_name;
1363         rpc.service_url = xstrfmt("%s%s", url.buf, rpc.service_name);
1364         rpc.hdr_content_type = xstrfmt("Content-Type: application/x-%s-request", rpc.service_name);
1365         rpc.hdr_accept = xstrfmt("Accept: application/x-%s-result", rpc.service_name);
1366         if (get_protocol_http_header(discover->version, &buf)) {
1367                 rpc.protocol_header = strbuf_detach(&buf, NULL);
1368         } else {
1369                 rpc.protocol_header = NULL;
1370                 strbuf_release(&buf);
1371         }
1372         rpc.buf = xmalloc(http_post_buffer);
1373         rpc.alloc = http_post_buffer;
1374         rpc.len = 0;
1375         rpc.pos = 0;
1376         rpc.in = 1;
1377         rpc.out = 0;
1378         rpc.any_written = 0;
1379         rpc.gzip_request = 1;
1380         rpc.initial_buffer = 0;
1381         rpc.write_line_lengths = 1;
1382         rpc.flush_read_but_not_sent = 0;
1383
1384         /*
1385          * Dump the capability listing that we got from the server earlier
1386          * during the info/refs request.
1387          */
1388         write_or_die(rpc.in, discover->buf, discover->len);
1389
1390         /* Until we see EOF keep sending POSTs */
1391         while (1) {
1392                 size_t avail;
1393                 enum packet_read_status status;
1394
1395                 if (!rpc_read_from_out(&rpc, PACKET_READ_GENTLE_ON_EOF, &avail,
1396                                        &status))
1397                         BUG("The entire rpc->buf should be larger than LARGE_PACKET_MAX");
1398                 if (status == PACKET_READ_EOF)
1399                         break;
1400                 if (post_rpc(&rpc, 1, status == PACKET_READ_FLUSH))
1401                         /* We would have an err here */
1402                         break;
1403                 /* Reset the buffer for next request */
1404                 rpc.len = 0;
1405         }
1406
1407         free(rpc.service_url);
1408         free(rpc.hdr_content_type);
1409         free(rpc.hdr_accept);
1410         free(rpc.protocol_header);
1411         free(rpc.buf);
1412         strbuf_release(&buf);
1413
1414         return 0;
1415 }
1416
1417 int cmd_main(int argc, const char **argv)
1418 {
1419         struct strbuf buf = STRBUF_INIT;
1420         int nongit;
1421
1422         setup_git_directory_gently(&nongit);
1423         if (argc < 2) {
1424                 error(_("remote-curl: usage: git remote-curl <remote> [<url>]"));
1425                 return 1;
1426         }
1427
1428         options.verbosity = 1;
1429         options.progress = !!isatty(2);
1430         options.thin = 1;
1431         string_list_init(&options.deepen_not, 1);
1432         string_list_init(&options.push_options, 1);
1433
1434         /*
1435          * Just report "remote-curl" here (folding all the various aliases
1436          * ("git-remote-http", "git-remote-https", and etc.) here since they
1437          * are all just copies of the same actual executable.
1438          */
1439         trace2_cmd_name("remote-curl");
1440
1441         remote = remote_get(argv[1]);
1442
1443         if (argc > 2) {
1444                 end_url_with_slash(&url, argv[2]);
1445         } else {
1446                 end_url_with_slash(&url, remote->url[0]);
1447         }
1448
1449         http_init(remote, url.buf, 0);
1450
1451         do {
1452                 const char *arg;
1453
1454                 if (strbuf_getline_lf(&buf, stdin) == EOF) {
1455                         if (ferror(stdin))
1456                                 error(_("remote-curl: error reading command stream from git"));
1457                         return 1;
1458                 }
1459                 if (buf.len == 0)
1460                         break;
1461                 if (starts_with(buf.buf, "fetch ")) {
1462                         if (nongit)
1463                                 die(_("remote-curl: fetch attempted without a local repo"));
1464                         parse_fetch(&buf);
1465
1466                 } else if (!strcmp(buf.buf, "list") || starts_with(buf.buf, "list ")) {
1467                         int for_push = !!strstr(buf.buf + 4, "for-push");
1468                         output_refs(get_refs(for_push));
1469
1470                 } else if (starts_with(buf.buf, "push ")) {
1471                         parse_push(&buf);
1472
1473                 } else if (skip_prefix(buf.buf, "option ", &arg)) {
1474                         char *value = strchr(arg, ' ');
1475                         int result;
1476
1477                         if (value)
1478                                 *value++ = '\0';
1479                         else
1480                                 value = "true";
1481
1482                         result = set_option(arg, value);
1483                         if (!result)
1484                                 printf("ok\n");
1485                         else if (result < 0)
1486                                 printf("error invalid value\n");
1487                         else
1488                                 printf("unsupported\n");
1489                         fflush(stdout);
1490
1491                 } else if (!strcmp(buf.buf, "capabilities")) {
1492                         printf("stateless-connect\n");
1493                         printf("fetch\n");
1494                         printf("option\n");
1495                         printf("push\n");
1496                         printf("check-connectivity\n");
1497                         printf("\n");
1498                         fflush(stdout);
1499                 } else if (skip_prefix(buf.buf, "stateless-connect ", &arg)) {
1500                         if (!stateless_connect(arg))
1501                                 break;
1502                 } else {
1503                         error(_("remote-curl: unknown command '%s' from git"), buf.buf);
1504                         return 1;
1505                 }
1506                 strbuf_reset(&buf);
1507         } while (1);
1508
1509         http_cleanup();
1510
1511         return 0;
1512 }