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