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