Merge branch 'sb/submodule-config-cleanup' into next
[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 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(&options, 0, sizeof(options));
295         options.content_type = &type;
296         options.charset = &charset;
297         options.effective_url = &effective_url;
298         options.base_url = &url;
299         options.no_cache = 1;
300         options.keep_error = 1;
301
302         http_ret = http_get_strbuf(refs_url.buf, &buffer, &options);
303         switch (http_ret) {
304         case HTTP_OK:
305                 break;
306         case HTTP_MISSING_TARGET:
307                 show_http_message(&type, &charset, &buffer);
308                 die("repository '%s' not found", url.buf);
309         case HTTP_NOAUTH:
310                 show_http_message(&type, &charset, &buffer);
311                 die("Authentication failed for '%s'", url.buf);
312         default:
313                 show_http_message(&type, &charset, &buffer);
314                 die("unable to access '%s': %s", url.buf, curl_errorstr);
315         }
316
317         last= xcalloc(1, sizeof(*last_discovery));
318         last->service = service;
319         last->buf_alloc = strbuf_detach(&buffer, &last->len);
320         last->buf = last->buf_alloc;
321
322         strbuf_addf(&exp, "application/x-%s-advertisement", service);
323         if (maybe_smart &&
324             (5 <= last->len && last->buf[4] == '#') &&
325             !strbuf_cmp(&exp, &type)) {
326                 char *line;
327
328                 /*
329                  * smart HTTP response; validate that the service
330                  * pkt-line matches our request.
331                  */
332                 line = packet_read_line_buf(&last->buf, &last->len, NULL);
333
334                 strbuf_reset(&exp);
335                 strbuf_addf(&exp, "# service=%s", service);
336                 if (strcmp(line, exp.buf))
337                         die("invalid server response; got '%s'", line);
338                 strbuf_release(&exp);
339
340                 /* The header can include additional metadata lines, up
341                  * until a packet flush marker.  Ignore these now, but
342                  * in the future we might start to scan them.
343                  */
344                 while (packet_read_line_buf(&last->buf, &last->len, NULL))
345                         ;
346
347                 last->proto_git = 1;
348         }
349
350         if (last->proto_git)
351                 last->refs = parse_git_refs(last, for_push);
352         else
353                 last->refs = parse_info_refs(last);
354
355         strbuf_release(&refs_url);
356         strbuf_release(&exp);
357         strbuf_release(&type);
358         strbuf_release(&charset);
359         strbuf_release(&effective_url);
360         strbuf_release(&buffer);
361         last_discovery = last;
362         return last;
363 }
364
365 static struct ref *get_refs(int for_push)
366 {
367         struct discovery *heads;
368
369         if (for_push)
370                 heads = discover_refs("git-receive-pack", for_push);
371         else
372                 heads = discover_refs("git-upload-pack", for_push);
373
374         return heads->refs;
375 }
376
377 static void output_refs(struct ref *refs)
378 {
379         struct ref *posn;
380         for (posn = refs; posn; posn = posn->next) {
381                 if (posn->symref)
382                         printf("@%s %s\n", posn->symref, posn->name);
383                 else
384                         printf("%s %s\n", oid_to_hex(&posn->old_oid), posn->name);
385         }
386         printf("\n");
387         fflush(stdout);
388 }
389
390 struct rpc_state {
391         const char *service_name;
392         const char **argv;
393         struct strbuf *stdin_preamble;
394         char *service_url;
395         char *hdr_content_type;
396         char *hdr_accept;
397         char *buf;
398         size_t alloc;
399         size_t len;
400         size_t pos;
401         int in;
402         int out;
403         int any_written;
404         struct strbuf result;
405         unsigned gzip_request : 1;
406         unsigned initial_buffer : 1;
407 };
408
409 static size_t rpc_out(void *ptr, size_t eltsize,
410                 size_t nmemb, void *buffer_)
411 {
412         size_t max = eltsize * nmemb;
413         struct rpc_state *rpc = buffer_;
414         size_t avail = rpc->len - rpc->pos;
415
416         if (!avail) {
417                 rpc->initial_buffer = 0;
418                 avail = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
419                 if (!avail)
420                         return 0;
421                 rpc->pos = 0;
422                 rpc->len = avail;
423         }
424
425         if (max < avail)
426                 avail = max;
427         memcpy(ptr, rpc->buf + rpc->pos, avail);
428         rpc->pos += avail;
429         return avail;
430 }
431
432 #ifndef NO_CURL_IOCTL
433 static curlioerr rpc_ioctl(CURL *handle, int cmd, void *clientp)
434 {
435         struct rpc_state *rpc = clientp;
436
437         switch (cmd) {
438         case CURLIOCMD_NOP:
439                 return CURLIOE_OK;
440
441         case CURLIOCMD_RESTARTREAD:
442                 if (rpc->initial_buffer) {
443                         rpc->pos = 0;
444                         return CURLIOE_OK;
445                 }
446                 error("unable to rewind rpc post data - try increasing http.postBuffer");
447                 return CURLIOE_FAILRESTART;
448
449         default:
450                 return CURLIOE_UNKNOWNCMD;
451         }
452 }
453 #endif
454
455 static size_t rpc_in(char *ptr, size_t eltsize,
456                 size_t nmemb, void *buffer_)
457 {
458         size_t size = eltsize * nmemb;
459         struct rpc_state *rpc = buffer_;
460         if (size)
461                 rpc->any_written = 1;
462         write_or_die(rpc->in, ptr, size);
463         return size;
464 }
465
466 static int run_slot(struct active_request_slot *slot,
467                     struct slot_results *results)
468 {
469         int err;
470         struct slot_results results_buf;
471
472         if (!results)
473                 results = &results_buf;
474
475         err = run_one_slot(slot, results);
476
477         if (err != HTTP_OK && err != HTTP_REAUTH) {
478                 struct strbuf msg = STRBUF_INIT;
479                 if (results->http_code && results->http_code != 200)
480                         strbuf_addf(&msg, "HTTP %ld", results->http_code);
481                 if (results->curl_result != CURLE_OK) {
482                         if (msg.len)
483                                 strbuf_addch(&msg, ' ');
484                         strbuf_addf(&msg, "curl %d", results->curl_result);
485                         if (curl_errorstr[0]) {
486                                 strbuf_addch(&msg, ' ');
487                                 strbuf_addstr(&msg, curl_errorstr);
488                         }
489                 }
490                 error("RPC failed; %s", msg.buf);
491                 strbuf_release(&msg);
492         }
493
494         return err;
495 }
496
497 static int probe_rpc(struct rpc_state *rpc, struct slot_results *results)
498 {
499         struct active_request_slot *slot;
500         struct curl_slist *headers = http_copy_default_headers();
501         struct strbuf buf = STRBUF_INIT;
502         int err;
503
504         slot = get_active_slot();
505
506         headers = curl_slist_append(headers, rpc->hdr_content_type);
507         headers = curl_slist_append(headers, rpc->hdr_accept);
508
509         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
510         curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
511         curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
512         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, NULL);
513         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, "0000");
514         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, 4);
515         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
516         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
517         curl_easy_setopt(slot->curl, CURLOPT_FILE, &buf);
518
519         err = run_slot(slot, results);
520
521         curl_slist_free_all(headers);
522         strbuf_release(&buf);
523         return err;
524 }
525
526 static int post_rpc(struct rpc_state *rpc)
527 {
528         struct active_request_slot *slot;
529         struct curl_slist *headers = http_copy_default_headers();
530         int use_gzip = rpc->gzip_request;
531         char *gzip_body = NULL;
532         size_t gzip_size = 0;
533         int err, large_request = 0;
534         int needs_100_continue = 0;
535
536         /* Try to load the entire request, if we can fit it into the
537          * allocated buffer space we can use HTTP/1.0 and avoid the
538          * chunked encoding mess.
539          */
540         while (1) {
541                 size_t left = rpc->alloc - rpc->len;
542                 char *buf = rpc->buf + rpc->len;
543                 int n;
544
545                 if (left < LARGE_PACKET_MAX) {
546                         large_request = 1;
547                         use_gzip = 0;
548                         break;
549                 }
550
551                 n = packet_read(rpc->out, NULL, NULL, buf, left, 0);
552                 if (!n)
553                         break;
554                 rpc->len += n;
555         }
556
557         if (large_request) {
558                 struct slot_results results;
559
560                 do {
561                         err = probe_rpc(rpc, &results);
562                         if (err == HTTP_REAUTH)
563                                 credential_fill(&http_auth);
564                 } while (err == HTTP_REAUTH);
565                 if (err != HTTP_OK)
566                         return -1;
567
568                 if (results.auth_avail & CURLAUTH_GSSNEGOTIATE)
569                         needs_100_continue = 1;
570         }
571
572         headers = curl_slist_append(headers, rpc->hdr_content_type);
573         headers = curl_slist_append(headers, rpc->hdr_accept);
574         headers = curl_slist_append(headers, needs_100_continue ?
575                 "Expect: 100-continue" : "Expect:");
576
577 retry:
578         slot = get_active_slot();
579
580         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
581         curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
582         curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
583         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
584
585         if (large_request) {
586                 /* The request body is large and the size cannot be predicted.
587                  * We must use chunked encoding to send it.
588                  */
589                 headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
590                 rpc->initial_buffer = 1;
591                 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, rpc_out);
592                 curl_easy_setopt(slot->curl, CURLOPT_INFILE, rpc);
593 #ifndef NO_CURL_IOCTL
594                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, rpc_ioctl);
595                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, rpc);
596 #endif
597                 if (options.verbosity > 1) {
598                         fprintf(stderr, "POST %s (chunked)\n", rpc->service_name);
599                         fflush(stderr);
600                 }
601
602         } else if (gzip_body) {
603                 /*
604                  * If we are looping to retry authentication, then the previous
605                  * run will have set up the headers and gzip buffer already,
606                  * and we just need to send it.
607                  */
608                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
609                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, gzip_size);
610
611         } else if (use_gzip && 1024 < rpc->len) {
612                 /* The client backend isn't giving us compressed data so
613                  * we can try to deflate it ourselves, this may save on.
614                  * the transfer time.
615                  */
616                 git_zstream stream;
617                 int ret;
618
619                 git_deflate_init_gzip(&stream, Z_BEST_COMPRESSION);
620                 gzip_size = git_deflate_bound(&stream, rpc->len);
621                 gzip_body = xmalloc(gzip_size);
622
623                 stream.next_in = (unsigned char *)rpc->buf;
624                 stream.avail_in = rpc->len;
625                 stream.next_out = (unsigned char *)gzip_body;
626                 stream.avail_out = gzip_size;
627
628                 ret = git_deflate(&stream, Z_FINISH);
629                 if (ret != Z_STREAM_END)
630                         die("cannot deflate request; zlib deflate error %d", ret);
631
632                 ret = git_deflate_end_gently(&stream);
633                 if (ret != Z_OK)
634                         die("cannot deflate request; zlib end error %d", ret);
635
636                 gzip_size = stream.total_out;
637
638                 headers = curl_slist_append(headers, "Content-Encoding: gzip");
639                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
640                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, gzip_size);
641
642                 if (options.verbosity > 1) {
643                         fprintf(stderr, "POST %s (gzip %lu to %lu bytes)\n",
644                                 rpc->service_name,
645                                 (unsigned long)rpc->len, (unsigned long)gzip_size);
646                         fflush(stderr);
647                 }
648         } else {
649                 /* We know the complete request size in advance, use the
650                  * more normal Content-Length approach.
651                  */
652                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, rpc->buf);
653                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, rpc->len);
654                 if (options.verbosity > 1) {
655                         fprintf(stderr, "POST %s (%lu bytes)\n",
656                                 rpc->service_name, (unsigned long)rpc->len);
657                         fflush(stderr);
658                 }
659         }
660
661         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
662         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, rpc_in);
663         curl_easy_setopt(slot->curl, CURLOPT_FILE, rpc);
664
665
666         rpc->any_written = 0;
667         err = run_slot(slot, NULL);
668         if (err == HTTP_REAUTH && !large_request) {
669                 credential_fill(&http_auth);
670                 goto retry;
671         }
672         if (err != HTTP_OK)
673                 err = -1;
674
675         if (!rpc->any_written)
676                 err = -1;
677
678         curl_slist_free_all(headers);
679         free(gzip_body);
680         return err;
681 }
682
683 static int rpc_service(struct rpc_state *rpc, struct discovery *heads)
684 {
685         const char *svc = rpc->service_name;
686         struct strbuf buf = STRBUF_INIT;
687         struct strbuf *preamble = rpc->stdin_preamble;
688         struct child_process client = CHILD_PROCESS_INIT;
689         int err = 0;
690
691         client.in = -1;
692         client.out = -1;
693         client.git_cmd = 1;
694         client.argv = rpc->argv;
695         if (start_command(&client))
696                 exit(1);
697         if (preamble)
698                 write_or_die(client.in, preamble->buf, preamble->len);
699         if (heads)
700                 write_or_die(client.in, heads->buf, heads->len);
701
702         rpc->alloc = http_post_buffer;
703         rpc->buf = xmalloc(rpc->alloc);
704         rpc->in = client.in;
705         rpc->out = client.out;
706         strbuf_init(&rpc->result, 0);
707
708         strbuf_addf(&buf, "%s%s", url.buf, svc);
709         rpc->service_url = strbuf_detach(&buf, NULL);
710
711         strbuf_addf(&buf, "Content-Type: application/x-%s-request", svc);
712         rpc->hdr_content_type = strbuf_detach(&buf, NULL);
713
714         strbuf_addf(&buf, "Accept: application/x-%s-result", svc);
715         rpc->hdr_accept = strbuf_detach(&buf, NULL);
716
717         while (!err) {
718                 int n = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
719                 if (!n)
720                         break;
721                 rpc->pos = 0;
722                 rpc->len = n;
723                 err |= post_rpc(rpc);
724         }
725
726         close(client.in);
727         client.in = -1;
728         if (!err) {
729                 strbuf_read(&rpc->result, client.out, 0);
730         } else {
731                 char buf[4096];
732                 for (;;)
733                         if (xread(client.out, buf, sizeof(buf)) <= 0)
734                                 break;
735         }
736
737         close(client.out);
738         client.out = -1;
739
740         err |= finish_command(&client);
741         free(rpc->service_url);
742         free(rpc->hdr_content_type);
743         free(rpc->hdr_accept);
744         free(rpc->buf);
745         strbuf_release(&buf);
746         return err;
747 }
748
749 static int fetch_dumb(int nr_heads, struct ref **to_fetch)
750 {
751         struct walker *walker;
752         char **targets;
753         int ret, i;
754
755         ALLOC_ARRAY(targets, nr_heads);
756         if (options.depth || options.deepen_since)
757                 die("dumb http transport does not support shallow capabilities");
758         for (i = 0; i < nr_heads; i++)
759                 targets[i] = xstrdup(oid_to_hex(&to_fetch[i]->old_oid));
760
761         walker = get_http_walker(url.buf);
762         walker->get_all = 1;
763         walker->get_tree = 1;
764         walker->get_history = 1;
765         walker->get_verbosely = options.verbosity >= 3;
766         walker->get_recover = 0;
767         ret = walker_fetch(walker, nr_heads, targets, NULL, NULL);
768         walker_free(walker);
769
770         for (i = 0; i < nr_heads; i++)
771                 free(targets[i]);
772         free(targets);
773
774         return ret ? error("fetch failed.") : 0;
775 }
776
777 static int fetch_git(struct discovery *heads,
778         int nr_heads, struct ref **to_fetch)
779 {
780         struct rpc_state rpc;
781         struct strbuf preamble = STRBUF_INIT;
782         int i, err;
783         struct argv_array args = ARGV_ARRAY_INIT;
784
785         argv_array_pushl(&args, "fetch-pack", "--stateless-rpc",
786                          "--stdin", "--lock-pack", NULL);
787         if (options.followtags)
788                 argv_array_push(&args, "--include-tag");
789         if (options.thin)
790                 argv_array_push(&args, "--thin");
791         if (options.verbosity >= 3)
792                 argv_array_pushl(&args, "-v", "-v", NULL);
793         if (options.check_self_contained_and_connected)
794                 argv_array_push(&args, "--check-self-contained-and-connected");
795         if (options.cloning)
796                 argv_array_push(&args, "--cloning");
797         if (options.update_shallow)
798                 argv_array_push(&args, "--update-shallow");
799         if (!options.progress)
800                 argv_array_push(&args, "--no-progress");
801         if (options.depth)
802                 argv_array_pushf(&args, "--depth=%lu", options.depth);
803         if (options.deepen_since)
804                 argv_array_pushf(&args, "--shallow-since=%s", options.deepen_since);
805         for (i = 0; i < options.deepen_not.nr; i++)
806                 argv_array_pushf(&args, "--shallow-exclude=%s",
807                                  options.deepen_not.items[i].string);
808         if (options.deepen_relative && options.depth)
809                 argv_array_push(&args, "--deepen-relative");
810         argv_array_push(&args, url.buf);
811
812         for (i = 0; i < nr_heads; i++) {
813                 struct ref *ref = to_fetch[i];
814                 if (!*ref->name)
815                         die("cannot fetch by sha1 over smart http");
816                 packet_buf_write(&preamble, "%s %s\n",
817                                  oid_to_hex(&ref->old_oid), ref->name);
818         }
819         packet_buf_flush(&preamble);
820
821         memset(&rpc, 0, sizeof(rpc));
822         rpc.service_name = "git-upload-pack",
823         rpc.argv = args.argv;
824         rpc.stdin_preamble = &preamble;
825         rpc.gzip_request = 1;
826
827         err = rpc_service(&rpc, heads);
828         if (rpc.result.len)
829                 write_or_die(1, rpc.result.buf, rpc.result.len);
830         strbuf_release(&rpc.result);
831         strbuf_release(&preamble);
832         argv_array_clear(&args);
833         return err;
834 }
835
836 static int fetch(int nr_heads, struct ref **to_fetch)
837 {
838         struct discovery *d = discover_refs("git-upload-pack", 0);
839         if (d->proto_git)
840                 return fetch_git(d, nr_heads, to_fetch);
841         else
842                 return fetch_dumb(nr_heads, to_fetch);
843 }
844
845 static void parse_fetch(struct strbuf *buf)
846 {
847         struct ref **to_fetch = NULL;
848         struct ref *list_head = NULL;
849         struct ref **list = &list_head;
850         int alloc_heads = 0, nr_heads = 0;
851
852         do {
853                 const char *p;
854                 if (skip_prefix(buf->buf, "fetch ", &p)) {
855                         const char *name;
856                         struct ref *ref;
857                         struct object_id old_oid;
858
859                         if (get_oid_hex(p, &old_oid))
860                                 die("protocol error: expected sha/ref, got %s'", p);
861                         if (p[GIT_SHA1_HEXSZ] == ' ')
862                                 name = p + GIT_SHA1_HEXSZ + 1;
863                         else if (!p[GIT_SHA1_HEXSZ])
864                                 name = "";
865                         else
866                                 die("protocol error: expected sha/ref, got %s'", p);
867
868                         ref = alloc_ref(name);
869                         oidcpy(&ref->old_oid, &old_oid);
870
871                         *list = ref;
872                         list = &ref->next;
873
874                         ALLOC_GROW(to_fetch, nr_heads + 1, alloc_heads);
875                         to_fetch[nr_heads++] = ref;
876                 }
877                 else
878                         die("http transport does not support %s", buf->buf);
879
880                 strbuf_reset(buf);
881                 if (strbuf_getline_lf(buf, stdin) == EOF)
882                         return;
883                 if (!*buf->buf)
884                         break;
885         } while (1);
886
887         if (fetch(nr_heads, to_fetch))
888                 exit(128); /* error already reported */
889         free_refs(list_head);
890         free(to_fetch);
891
892         printf("\n");
893         fflush(stdout);
894         strbuf_reset(buf);
895 }
896
897 static int push_dav(int nr_spec, char **specs)
898 {
899         struct child_process child = CHILD_PROCESS_INIT;
900         size_t i;
901
902         child.git_cmd = 1;
903         argv_array_push(&child.args, "http-push");
904         argv_array_push(&child.args, "--helper-status");
905         if (options.dry_run)
906                 argv_array_push(&child.args, "--dry-run");
907         if (options.verbosity > 1)
908                 argv_array_push(&child.args, "--verbose");
909         argv_array_push(&child.args, url.buf);
910         for (i = 0; i < nr_spec; i++)
911                 argv_array_push(&child.args, specs[i]);
912
913         if (run_command(&child))
914                 die("git-http-push failed");
915         return 0;
916 }
917
918 static int push_git(struct discovery *heads, int nr_spec, char **specs)
919 {
920         struct rpc_state rpc;
921         int i, err;
922         struct argv_array args;
923         struct string_list_item *cas_option;
924         struct strbuf preamble = STRBUF_INIT;
925
926         argv_array_init(&args);
927         argv_array_pushl(&args, "send-pack", "--stateless-rpc", "--helper-status",
928                          NULL);
929
930         if (options.thin)
931                 argv_array_push(&args, "--thin");
932         if (options.dry_run)
933                 argv_array_push(&args, "--dry-run");
934         if (options.push_cert == SEND_PACK_PUSH_CERT_ALWAYS)
935                 argv_array_push(&args, "--signed=yes");
936         else if (options.push_cert == SEND_PACK_PUSH_CERT_IF_ASKED)
937                 argv_array_push(&args, "--signed=if-asked");
938         if (options.verbosity == 0)
939                 argv_array_push(&args, "--quiet");
940         else if (options.verbosity > 1)
941                 argv_array_push(&args, "--verbose");
942         argv_array_push(&args, options.progress ? "--progress" : "--no-progress");
943         for_each_string_list_item(cas_option, &cas_options)
944                 argv_array_push(&args, cas_option->string);
945         argv_array_push(&args, url.buf);
946
947         argv_array_push(&args, "--stdin");
948         for (i = 0; i < nr_spec; i++)
949                 packet_buf_write(&preamble, "%s\n", specs[i]);
950         packet_buf_flush(&preamble);
951
952         memset(&rpc, 0, sizeof(rpc));
953         rpc.service_name = "git-receive-pack",
954         rpc.argv = args.argv;
955         rpc.stdin_preamble = &preamble;
956
957         err = rpc_service(&rpc, heads);
958         if (rpc.result.len)
959                 write_or_die(1, rpc.result.buf, rpc.result.len);
960         strbuf_release(&rpc.result);
961         strbuf_release(&preamble);
962         argv_array_clear(&args);
963         return err;
964 }
965
966 static int push(int nr_spec, char **specs)
967 {
968         struct discovery *heads = discover_refs("git-receive-pack", 1);
969         int ret;
970
971         if (heads->proto_git)
972                 ret = push_git(heads, nr_spec, specs);
973         else
974                 ret = push_dav(nr_spec, specs);
975         free_discovery(heads);
976         return ret;
977 }
978
979 static void parse_push(struct strbuf *buf)
980 {
981         char **specs = NULL;
982         int alloc_spec = 0, nr_spec = 0, i, ret;
983
984         do {
985                 if (starts_with(buf->buf, "push ")) {
986                         ALLOC_GROW(specs, nr_spec + 1, alloc_spec);
987                         specs[nr_spec++] = xstrdup(buf->buf + 5);
988                 }
989                 else
990                         die("http transport does not support %s", buf->buf);
991
992                 strbuf_reset(buf);
993                 if (strbuf_getline_lf(buf, stdin) == EOF)
994                         goto free_specs;
995                 if (!*buf->buf)
996                         break;
997         } while (1);
998
999         ret = push(nr_spec, specs);
1000         printf("\n");
1001         fflush(stdout);
1002
1003         if (ret)
1004                 exit(128); /* error already reported */
1005
1006  free_specs:
1007         for (i = 0; i < nr_spec; i++)
1008                 free(specs[i]);
1009         free(specs);
1010 }
1011
1012 int cmd_main(int argc, const char **argv)
1013 {
1014         struct strbuf buf = STRBUF_INIT;
1015         int nongit;
1016
1017         setup_git_directory_gently(&nongit);
1018         if (argc < 2) {
1019                 error("remote-curl: usage: git remote-curl <remote> [<url>]");
1020                 return 1;
1021         }
1022
1023         options.verbosity = 1;
1024         options.progress = !!isatty(2);
1025         options.thin = 1;
1026         string_list_init(&options.deepen_not, 1);
1027
1028         remote = remote_get(argv[1]);
1029
1030         if (argc > 2) {
1031                 end_url_with_slash(&url, argv[2]);
1032         } else {
1033                 end_url_with_slash(&url, remote->url[0]);
1034         }
1035
1036         http_init(remote, url.buf, 0);
1037
1038         do {
1039                 const char *arg;
1040
1041                 if (strbuf_getline_lf(&buf, stdin) == EOF) {
1042                         if (ferror(stdin))
1043                                 error("remote-curl: error reading command stream from git");
1044                         return 1;
1045                 }
1046                 if (buf.len == 0)
1047                         break;
1048                 if (starts_with(buf.buf, "fetch ")) {
1049                         if (nongit)
1050                                 die("remote-curl: fetch attempted without a local repo");
1051                         parse_fetch(&buf);
1052
1053                 } else if (!strcmp(buf.buf, "list") || starts_with(buf.buf, "list ")) {
1054                         int for_push = !!strstr(buf.buf + 4, "for-push");
1055                         output_refs(get_refs(for_push));
1056
1057                 } else if (starts_with(buf.buf, "push ")) {
1058                         parse_push(&buf);
1059
1060                 } else if (skip_prefix(buf.buf, "option ", &arg)) {
1061                         char *value = strchr(arg, ' ');
1062                         int result;
1063
1064                         if (value)
1065                                 *value++ = '\0';
1066                         else
1067                                 value = "true";
1068
1069                         result = set_option(arg, value);
1070                         if (!result)
1071                                 printf("ok\n");
1072                         else if (result < 0)
1073                                 printf("error invalid value\n");
1074                         else
1075                                 printf("unsupported\n");
1076                         fflush(stdout);
1077
1078                 } else if (!strcmp(buf.buf, "capabilities")) {
1079                         printf("fetch\n");
1080                         printf("option\n");
1081                         printf("push\n");
1082                         printf("check-connectivity\n");
1083                         printf("\n");
1084                         fflush(stdout);
1085                 } else {
1086                         error("remote-curl: unknown command '%s' from git", buf.buf);
1087                         return 1;
1088                 }
1089                 strbuf_reset(&buf);
1090         } while (1);
1091
1092         http_cleanup();
1093
1094         return 0;
1095 }