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