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