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