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