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