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