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