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