t/lib-httpd: pass GIT_TEST_SIDEBAND_ALL through Apache
[git/raj.git] / remote-curl.c
blob10b50869c5841d8443d4b94ffb3e1e3ce5187bae
1 #include "cache.h"
2 #include "config.h"
3 #include "remote.h"
4 #include "connect.h"
5 #include "strbuf.h"
6 #include "walker.h"
7 #include "http.h"
8 #include "exec-cmd.h"
9 #include "run-command.h"
10 #include "pkt-line.h"
11 #include "string-list.h"
12 #include "sideband.h"
13 #include "argv-array.h"
14 #include "credential.h"
15 #include "sha1-array.h"
16 #include "send-pack.h"
17 #include "protocol.h"
18 #include "quote.h"
20 static struct remote *remote;
21 /* always ends with a trailing slash */
22 static struct strbuf url = STRBUF_INIT;
24 struct options {
25 int verbosity;
26 unsigned long depth;
27 char *deepen_since;
28 struct string_list deepen_not;
29 struct string_list push_options;
30 char *filter;
31 unsigned progress : 1,
32 check_self_contained_and_connected : 1,
33 cloning : 1,
34 update_shallow : 1,
35 followtags : 1,
36 dry_run : 1,
37 thin : 1,
38 /* One of the SEND_PACK_PUSH_CERT_* constants. */
39 push_cert : 2,
40 deepen_relative : 1,
41 from_promisor : 1,
42 no_dependents : 1;
44 static struct options options;
45 static struct string_list cas_options = STRING_LIST_INIT_DUP;
47 static int set_option(const char *name, const char *value)
49 if (!strcmp(name, "verbosity")) {
50 char *end;
51 int v = strtol(value, &end, 10);
52 if (value == end || *end)
53 return -1;
54 options.verbosity = v;
55 return 0;
57 else if (!strcmp(name, "progress")) {
58 if (!strcmp(value, "true"))
59 options.progress = 1;
60 else if (!strcmp(value, "false"))
61 options.progress = 0;
62 else
63 return -1;
64 return 0;
66 else if (!strcmp(name, "depth")) {
67 char *end;
68 unsigned long v = strtoul(value, &end, 10);
69 if (value == end || *end)
70 return -1;
71 options.depth = v;
72 return 0;
74 else if (!strcmp(name, "deepen-since")) {
75 options.deepen_since = xstrdup(value);
76 return 0;
78 else if (!strcmp(name, "deepen-not")) {
79 string_list_append(&options.deepen_not, value);
80 return 0;
82 else if (!strcmp(name, "deepen-relative")) {
83 if (!strcmp(value, "true"))
84 options.deepen_relative = 1;
85 else if (!strcmp(value, "false"))
86 options.deepen_relative = 0;
87 else
88 return -1;
89 return 0;
91 else if (!strcmp(name, "followtags")) {
92 if (!strcmp(value, "true"))
93 options.followtags = 1;
94 else if (!strcmp(value, "false"))
95 options.followtags = 0;
96 else
97 return -1;
98 return 0;
100 else if (!strcmp(name, "dry-run")) {
101 if (!strcmp(value, "true"))
102 options.dry_run = 1;
103 else if (!strcmp(value, "false"))
104 options.dry_run = 0;
105 else
106 return -1;
107 return 0;
109 else if (!strcmp(name, "check-connectivity")) {
110 if (!strcmp(value, "true"))
111 options.check_self_contained_and_connected = 1;
112 else if (!strcmp(value, "false"))
113 options.check_self_contained_and_connected = 0;
114 else
115 return -1;
116 return 0;
118 else if (!strcmp(name, "cas")) {
119 struct strbuf val = STRBUF_INIT;
120 strbuf_addf(&val, "--" CAS_OPT_NAME "=%s", value);
121 string_list_append(&cas_options, val.buf);
122 strbuf_release(&val);
123 return 0;
124 } else if (!strcmp(name, "cloning")) {
125 if (!strcmp(value, "true"))
126 options.cloning = 1;
127 else if (!strcmp(value, "false"))
128 options.cloning = 0;
129 else
130 return -1;
131 return 0;
132 } else if (!strcmp(name, "update-shallow")) {
133 if (!strcmp(value, "true"))
134 options.update_shallow = 1;
135 else if (!strcmp(value, "false"))
136 options.update_shallow = 0;
137 else
138 return -1;
139 return 0;
140 } else if (!strcmp(name, "pushcert")) {
141 if (!strcmp(value, "true"))
142 options.push_cert = SEND_PACK_PUSH_CERT_ALWAYS;
143 else if (!strcmp(value, "false"))
144 options.push_cert = SEND_PACK_PUSH_CERT_NEVER;
145 else if (!strcmp(value, "if-asked"))
146 options.push_cert = SEND_PACK_PUSH_CERT_IF_ASKED;
147 else
148 return -1;
149 return 0;
150 } else if (!strcmp(name, "push-option")) {
151 if (*value != '"')
152 string_list_append(&options.push_options, value);
153 else {
154 struct strbuf unquoted = STRBUF_INIT;
155 if (unquote_c_style(&unquoted, value, NULL) < 0)
156 die("invalid quoting in push-option value");
157 string_list_append_nodup(&options.push_options,
158 strbuf_detach(&unquoted, NULL));
160 return 0;
162 #if LIBCURL_VERSION_NUM >= 0x070a08
163 } else if (!strcmp(name, "family")) {
164 if (!strcmp(value, "ipv4"))
165 git_curl_ipresolve = CURL_IPRESOLVE_V4;
166 else if (!strcmp(value, "ipv6"))
167 git_curl_ipresolve = CURL_IPRESOLVE_V6;
168 else if (!strcmp(value, "all"))
169 git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
170 else
171 return -1;
172 return 0;
173 #endif /* LIBCURL_VERSION_NUM >= 0x070a08 */
174 } else if (!strcmp(name, "from-promisor")) {
175 options.from_promisor = 1;
176 return 0;
177 } else if (!strcmp(name, "no-dependents")) {
178 options.no_dependents = 1;
179 return 0;
180 } else if (!strcmp(name, "filter")) {
181 options.filter = xstrdup(value);
182 return 0;
183 } else {
184 return 1 /* unsupported */;
188 struct discovery {
189 char *service;
190 char *buf_alloc;
191 char *buf;
192 size_t len;
193 struct ref *refs;
194 struct oid_array shallow;
195 enum protocol_version version;
196 unsigned proto_git : 1;
198 static struct discovery *last_discovery;
200 static struct ref *parse_git_refs(struct discovery *heads, int for_push)
202 struct ref *list = NULL;
203 struct packet_reader reader;
205 packet_reader_init(&reader, -1, heads->buf, heads->len,
206 PACKET_READ_CHOMP_NEWLINE |
207 PACKET_READ_GENTLE_ON_EOF |
208 PACKET_READ_DIE_ON_ERR_PACKET);
210 heads->version = discover_version(&reader);
211 switch (heads->version) {
212 case protocol_v2:
214 * Do nothing. This isn't a list of refs but rather a
215 * capability advertisement. Client would have run
216 * 'stateless-connect' so we'll dump this capability listing
217 * and let them request the refs themselves.
219 break;
220 case protocol_v1:
221 case protocol_v0:
222 get_remote_heads(&reader, &list, for_push ? REF_NORMAL : 0,
223 NULL, &heads->shallow);
224 break;
225 case protocol_unknown_version:
226 BUG("unknown protocol version");
229 return list;
232 static struct ref *parse_info_refs(struct discovery *heads)
234 char *data, *start, *mid;
235 char *ref_name;
236 int i = 0;
238 struct ref *refs = NULL;
239 struct ref *ref = NULL;
240 struct ref *last_ref = NULL;
242 data = heads->buf;
243 start = NULL;
244 mid = data;
245 while (i < heads->len) {
246 if (!start) {
247 start = &data[i];
249 if (data[i] == '\t')
250 mid = &data[i];
251 if (data[i] == '\n') {
252 if (mid - start != 40)
253 die("%sinfo/refs not valid: is this a git repository?",
254 url.buf);
255 data[i] = 0;
256 ref_name = mid + 1;
257 ref = alloc_ref(ref_name);
258 get_oid_hex(start, &ref->old_oid);
259 if (!refs)
260 refs = ref;
261 if (last_ref)
262 last_ref->next = ref;
263 last_ref = ref;
264 start = NULL;
266 i++;
269 ref = alloc_ref("HEAD");
270 if (!http_fetch_ref(url.buf, ref) &&
271 !resolve_remote_symref(ref, refs)) {
272 ref->next = refs;
273 refs = ref;
274 } else {
275 free(ref);
278 return refs;
281 static void free_discovery(struct discovery *d)
283 if (d) {
284 if (d == last_discovery)
285 last_discovery = NULL;
286 free(d->shallow.oid);
287 free(d->buf_alloc);
288 free_refs(d->refs);
289 free(d->service);
290 free(d);
294 static int show_http_message(struct strbuf *type, struct strbuf *charset,
295 struct strbuf *msg)
297 const char *p, *eol;
300 * We only show text/plain parts, as other types are likely
301 * to be ugly to look at on the user's terminal.
303 if (strcmp(type->buf, "text/plain"))
304 return -1;
305 if (charset->len)
306 strbuf_reencode(msg, charset->buf, get_log_output_encoding());
308 strbuf_trim(msg);
309 if (!msg->len)
310 return -1;
312 p = msg->buf;
313 do {
314 eol = strchrnul(p, '\n');
315 fprintf(stderr, "remote: %.*s\n", (int)(eol - p), p);
316 p = eol + 1;
317 } while(*eol);
318 return 0;
321 static int get_protocol_http_header(enum protocol_version version,
322 struct strbuf *header)
324 if (version > 0) {
325 strbuf_addf(header, GIT_PROTOCOL_HEADER ": version=%d",
326 version);
328 return 1;
331 return 0;
334 static struct discovery *discover_refs(const char *service, int for_push)
336 struct strbuf exp = STRBUF_INIT;
337 struct strbuf type = STRBUF_INIT;
338 struct strbuf charset = STRBUF_INIT;
339 struct strbuf buffer = STRBUF_INIT;
340 struct strbuf refs_url = STRBUF_INIT;
341 struct strbuf effective_url = STRBUF_INIT;
342 struct strbuf protocol_header = STRBUF_INIT;
343 struct string_list extra_headers = STRING_LIST_INIT_DUP;
344 struct discovery *last = last_discovery;
345 int http_ret, maybe_smart = 0;
346 struct http_get_options http_options;
347 enum protocol_version version = get_protocol_version_config();
349 if (last && !strcmp(service, last->service))
350 return last;
351 free_discovery(last);
353 strbuf_addf(&refs_url, "%sinfo/refs", url.buf);
354 if ((starts_with(url.buf, "http://") || starts_with(url.buf, "https://")) &&
355 git_env_bool("GIT_SMART_HTTP", 1)) {
356 maybe_smart = 1;
357 if (!strchr(url.buf, '?'))
358 strbuf_addch(&refs_url, '?');
359 else
360 strbuf_addch(&refs_url, '&');
361 strbuf_addf(&refs_url, "service=%s", service);
365 * NEEDSWORK: If we are trying to use protocol v2 and we are planning
366 * to perform a push, then fallback to v0 since the client doesn't know
367 * how to push yet using v2.
369 if (version == protocol_v2 && !strcmp("git-receive-pack", service))
370 version = protocol_v0;
372 /* Add the extra Git-Protocol header */
373 if (get_protocol_http_header(version, &protocol_header))
374 string_list_append(&extra_headers, protocol_header.buf);
376 memset(&http_options, 0, sizeof(http_options));
377 http_options.content_type = &type;
378 http_options.charset = &charset;
379 http_options.effective_url = &effective_url;
380 http_options.base_url = &url;
381 http_options.extra_headers = &extra_headers;
382 http_options.initial_request = 1;
383 http_options.no_cache = 1;
384 http_options.keep_error = 1;
386 http_ret = http_get_strbuf(refs_url.buf, &buffer, &http_options);
387 switch (http_ret) {
388 case HTTP_OK:
389 break;
390 case HTTP_MISSING_TARGET:
391 show_http_message(&type, &charset, &buffer);
392 die("repository '%s' not found", url.buf);
393 case HTTP_NOAUTH:
394 show_http_message(&type, &charset, &buffer);
395 die("Authentication failed for '%s'", url.buf);
396 default:
397 show_http_message(&type, &charset, &buffer);
398 die("unable to access '%s': %s", url.buf, curl_errorstr);
401 if (options.verbosity && !starts_with(refs_url.buf, url.buf))
402 warning(_("redirecting to %s"), url.buf);
404 last= xcalloc(1, sizeof(*last_discovery));
405 last->service = xstrdup(service);
406 last->buf_alloc = strbuf_detach(&buffer, &last->len);
407 last->buf = last->buf_alloc;
409 strbuf_addf(&exp, "application/x-%s-advertisement", service);
410 if (maybe_smart &&
411 (5 <= last->len && last->buf[4] == '#') &&
412 !strbuf_cmp(&exp, &type)) {
413 struct packet_reader reader;
414 packet_reader_init(&reader, -1, last->buf, last->len,
415 PACKET_READ_CHOMP_NEWLINE |
416 PACKET_READ_DIE_ON_ERR_PACKET);
419 * smart HTTP response; validate that the service
420 * pkt-line matches our request.
422 if (packet_reader_read(&reader) != PACKET_READ_NORMAL)
423 die("invalid server response; expected service, got flush packet");
425 strbuf_reset(&exp);
426 strbuf_addf(&exp, "# service=%s", service);
427 if (strcmp(reader.line, exp.buf))
428 die("invalid server response; got '%s'", reader.line);
429 strbuf_release(&exp);
431 /* The header can include additional metadata lines, up
432 * until a packet flush marker. Ignore these now, but
433 * in the future we might start to scan them.
435 for (;;) {
436 packet_reader_read(&reader);
437 if (reader.pktlen <= 0) {
438 break;
442 last->buf = reader.src_buffer;
443 last->len = reader.src_len;
445 last->proto_git = 1;
446 } else if (maybe_smart &&
447 last->len > 5 && starts_with(last->buf + 4, "version 2")) {
448 last->proto_git = 1;
451 if (last->proto_git)
452 last->refs = parse_git_refs(last, for_push);
453 else
454 last->refs = parse_info_refs(last);
456 strbuf_release(&refs_url);
457 strbuf_release(&exp);
458 strbuf_release(&type);
459 strbuf_release(&charset);
460 strbuf_release(&effective_url);
461 strbuf_release(&buffer);
462 strbuf_release(&protocol_header);
463 string_list_clear(&extra_headers, 0);
464 last_discovery = last;
465 return last;
468 static struct ref *get_refs(int for_push)
470 struct discovery *heads;
472 if (for_push)
473 heads = discover_refs("git-receive-pack", for_push);
474 else
475 heads = discover_refs("git-upload-pack", for_push);
477 return heads->refs;
480 static void output_refs(struct ref *refs)
482 struct ref *posn;
483 for (posn = refs; posn; posn = posn->next) {
484 if (posn->symref)
485 printf("@%s %s\n", posn->symref, posn->name);
486 else
487 printf("%s %s\n", oid_to_hex(&posn->old_oid), posn->name);
489 printf("\n");
490 fflush(stdout);
493 struct rpc_state {
494 const char *service_name;
495 const char **argv;
496 struct strbuf *stdin_preamble;
497 char *service_url;
498 char *hdr_content_type;
499 char *hdr_accept;
500 char *protocol_header;
501 char *buf;
502 size_t alloc;
503 size_t len;
504 size_t pos;
505 int in;
506 int out;
507 int any_written;
508 struct strbuf result;
509 unsigned gzip_request : 1;
510 unsigned initial_buffer : 1;
513 static size_t rpc_out(void *ptr, size_t eltsize,
514 size_t nmemb, void *buffer_)
516 size_t max = eltsize * nmemb;
517 struct rpc_state *rpc = buffer_;
518 size_t avail = rpc->len - rpc->pos;
520 if (!avail) {
521 rpc->initial_buffer = 0;
522 avail = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
523 if (!avail)
524 return 0;
525 rpc->pos = 0;
526 rpc->len = avail;
529 if (max < avail)
530 avail = max;
531 memcpy(ptr, rpc->buf + rpc->pos, avail);
532 rpc->pos += avail;
533 return avail;
536 #ifndef NO_CURL_IOCTL
537 static curlioerr rpc_ioctl(CURL *handle, int cmd, void *clientp)
539 struct rpc_state *rpc = clientp;
541 switch (cmd) {
542 case CURLIOCMD_NOP:
543 return CURLIOE_OK;
545 case CURLIOCMD_RESTARTREAD:
546 if (rpc->initial_buffer) {
547 rpc->pos = 0;
548 return CURLIOE_OK;
550 error("unable to rewind rpc post data - try increasing http.postBuffer");
551 return CURLIOE_FAILRESTART;
553 default:
554 return CURLIOE_UNKNOWNCMD;
557 #endif
559 static size_t rpc_in(char *ptr, size_t eltsize,
560 size_t nmemb, void *buffer_)
562 size_t size = eltsize * nmemb;
563 struct rpc_state *rpc = buffer_;
564 if (size)
565 rpc->any_written = 1;
566 write_or_die(rpc->in, ptr, size);
567 return size;
570 static int run_slot(struct active_request_slot *slot,
571 struct slot_results *results)
573 int err;
574 struct slot_results results_buf;
576 if (!results)
577 results = &results_buf;
579 err = run_one_slot(slot, results);
581 if (err != HTTP_OK && err != HTTP_REAUTH) {
582 struct strbuf msg = STRBUF_INIT;
583 if (results->http_code && results->http_code != 200)
584 strbuf_addf(&msg, "HTTP %ld", results->http_code);
585 if (results->curl_result != CURLE_OK) {
586 if (msg.len)
587 strbuf_addch(&msg, ' ');
588 strbuf_addf(&msg, "curl %d", results->curl_result);
589 if (curl_errorstr[0]) {
590 strbuf_addch(&msg, ' ');
591 strbuf_addstr(&msg, curl_errorstr);
594 error("RPC failed; %s", msg.buf);
595 strbuf_release(&msg);
598 return err;
601 static int probe_rpc(struct rpc_state *rpc, struct slot_results *results)
603 struct active_request_slot *slot;
604 struct curl_slist *headers = http_copy_default_headers();
605 struct strbuf buf = STRBUF_INIT;
606 int err;
608 slot = get_active_slot();
610 headers = curl_slist_append(headers, rpc->hdr_content_type);
611 headers = curl_slist_append(headers, rpc->hdr_accept);
613 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
614 curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
615 curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
616 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, NULL);
617 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, "0000");
618 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, 4);
619 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
620 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
621 curl_easy_setopt(slot->curl, CURLOPT_FILE, &buf);
623 err = run_slot(slot, results);
625 curl_slist_free_all(headers);
626 strbuf_release(&buf);
627 return err;
630 static curl_off_t xcurl_off_t(size_t len) {
631 uintmax_t size = len;
632 if (size > maximum_signed_value_of_type(curl_off_t))
633 die("cannot handle pushes this big");
634 return (curl_off_t)size;
637 static int post_rpc(struct rpc_state *rpc)
639 struct active_request_slot *slot;
640 struct curl_slist *headers = http_copy_default_headers();
641 int use_gzip = rpc->gzip_request;
642 char *gzip_body = NULL;
643 size_t gzip_size = 0;
644 int err, large_request = 0;
645 int needs_100_continue = 0;
647 /* Try to load the entire request, if we can fit it into the
648 * allocated buffer space we can use HTTP/1.0 and avoid the
649 * chunked encoding mess.
651 while (1) {
652 size_t left = rpc->alloc - rpc->len;
653 char *buf = rpc->buf + rpc->len;
654 int n;
656 if (left < LARGE_PACKET_MAX) {
657 large_request = 1;
658 use_gzip = 0;
659 break;
662 n = packet_read(rpc->out, NULL, NULL, buf, left, 0);
663 if (!n)
664 break;
665 rpc->len += n;
668 if (large_request) {
669 struct slot_results results;
671 do {
672 err = probe_rpc(rpc, &results);
673 if (err == HTTP_REAUTH)
674 credential_fill(&http_auth);
675 } while (err == HTTP_REAUTH);
676 if (err != HTTP_OK)
677 return -1;
679 if (results.auth_avail & CURLAUTH_GSSNEGOTIATE)
680 needs_100_continue = 1;
683 headers = curl_slist_append(headers, rpc->hdr_content_type);
684 headers = curl_slist_append(headers, rpc->hdr_accept);
685 headers = curl_slist_append(headers, needs_100_continue ?
686 "Expect: 100-continue" : "Expect:");
688 /* Add the extra Git-Protocol header */
689 if (rpc->protocol_header)
690 headers = curl_slist_append(headers, rpc->protocol_header);
692 retry:
693 slot = get_active_slot();
695 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
696 curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
697 curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
698 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
700 if (large_request) {
701 /* The request body is large and the size cannot be predicted.
702 * We must use chunked encoding to send it.
704 headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
705 rpc->initial_buffer = 1;
706 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, rpc_out);
707 curl_easy_setopt(slot->curl, CURLOPT_INFILE, rpc);
708 #ifndef NO_CURL_IOCTL
709 curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, rpc_ioctl);
710 curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, rpc);
711 #endif
712 if (options.verbosity > 1) {
713 fprintf(stderr, "POST %s (chunked)\n", rpc->service_name);
714 fflush(stderr);
717 } else if (gzip_body) {
719 * If we are looping to retry authentication, then the previous
720 * run will have set up the headers and gzip buffer already,
721 * and we just need to send it.
723 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
724 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
726 } else if (use_gzip && 1024 < rpc->len) {
727 /* The client backend isn't giving us compressed data so
728 * we can try to deflate it ourselves, this may save on
729 * the transfer time.
731 git_zstream stream;
732 int ret;
734 git_deflate_init_gzip(&stream, Z_BEST_COMPRESSION);
735 gzip_size = git_deflate_bound(&stream, rpc->len);
736 gzip_body = xmalloc(gzip_size);
738 stream.next_in = (unsigned char *)rpc->buf;
739 stream.avail_in = rpc->len;
740 stream.next_out = (unsigned char *)gzip_body;
741 stream.avail_out = gzip_size;
743 ret = git_deflate(&stream, Z_FINISH);
744 if (ret != Z_STREAM_END)
745 die("cannot deflate request; zlib deflate error %d", ret);
747 ret = git_deflate_end_gently(&stream);
748 if (ret != Z_OK)
749 die("cannot deflate request; zlib end error %d", ret);
751 gzip_size = stream.total_out;
753 headers = curl_slist_append(headers, "Content-Encoding: gzip");
754 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
755 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
757 if (options.verbosity > 1) {
758 fprintf(stderr, "POST %s (gzip %lu to %lu bytes)\n",
759 rpc->service_name,
760 (unsigned long)rpc->len, (unsigned long)gzip_size);
761 fflush(stderr);
763 } else {
764 /* We know the complete request size in advance, use the
765 * more normal Content-Length approach.
767 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, rpc->buf);
768 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(rpc->len));
769 if (options.verbosity > 1) {
770 fprintf(stderr, "POST %s (%lu bytes)\n",
771 rpc->service_name, (unsigned long)rpc->len);
772 fflush(stderr);
776 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
777 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, rpc_in);
778 curl_easy_setopt(slot->curl, CURLOPT_FILE, rpc);
781 rpc->any_written = 0;
782 err = run_slot(slot, NULL);
783 if (err == HTTP_REAUTH && !large_request) {
784 credential_fill(&http_auth);
785 goto retry;
787 if (err != HTTP_OK)
788 err = -1;
790 if (!rpc->any_written)
791 err = -1;
793 curl_slist_free_all(headers);
794 free(gzip_body);
795 return err;
798 static int rpc_service(struct rpc_state *rpc, struct discovery *heads)
800 const char *svc = rpc->service_name;
801 struct strbuf buf = STRBUF_INIT;
802 struct strbuf *preamble = rpc->stdin_preamble;
803 struct child_process client = CHILD_PROCESS_INIT;
804 int err = 0;
806 client.in = -1;
807 client.out = -1;
808 client.git_cmd = 1;
809 client.argv = rpc->argv;
810 if (start_command(&client))
811 exit(1);
812 if (preamble)
813 write_or_die(client.in, preamble->buf, preamble->len);
814 if (heads)
815 write_or_die(client.in, heads->buf, heads->len);
817 rpc->alloc = http_post_buffer;
818 rpc->buf = xmalloc(rpc->alloc);
819 rpc->in = client.in;
820 rpc->out = client.out;
821 strbuf_init(&rpc->result, 0);
823 strbuf_addf(&buf, "%s%s", url.buf, svc);
824 rpc->service_url = strbuf_detach(&buf, NULL);
826 strbuf_addf(&buf, "Content-Type: application/x-%s-request", svc);
827 rpc->hdr_content_type = strbuf_detach(&buf, NULL);
829 strbuf_addf(&buf, "Accept: application/x-%s-result", svc);
830 rpc->hdr_accept = strbuf_detach(&buf, NULL);
832 if (get_protocol_http_header(heads->version, &buf))
833 rpc->protocol_header = strbuf_detach(&buf, NULL);
834 else
835 rpc->protocol_header = NULL;
837 while (!err) {
838 int n = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
839 if (!n)
840 break;
841 rpc->pos = 0;
842 rpc->len = n;
843 err |= post_rpc(rpc);
846 close(client.in);
847 client.in = -1;
848 if (!err) {
849 strbuf_read(&rpc->result, client.out, 0);
850 } else {
851 char buf[4096];
852 for (;;)
853 if (xread(client.out, buf, sizeof(buf)) <= 0)
854 break;
857 close(client.out);
858 client.out = -1;
860 err |= finish_command(&client);
861 free(rpc->service_url);
862 free(rpc->hdr_content_type);
863 free(rpc->hdr_accept);
864 free(rpc->protocol_header);
865 free(rpc->buf);
866 strbuf_release(&buf);
867 return err;
870 static int fetch_dumb(int nr_heads, struct ref **to_fetch)
872 struct walker *walker;
873 char **targets;
874 int ret, i;
876 ALLOC_ARRAY(targets, nr_heads);
877 if (options.depth || options.deepen_since)
878 die("dumb http transport does not support shallow capabilities");
879 for (i = 0; i < nr_heads; i++)
880 targets[i] = xstrdup(oid_to_hex(&to_fetch[i]->old_oid));
882 walker = get_http_walker(url.buf);
883 walker->get_verbosely = options.verbosity >= 3;
884 walker->get_recover = 0;
885 ret = walker_fetch(walker, nr_heads, targets, NULL, NULL);
886 walker_free(walker);
888 for (i = 0; i < nr_heads; i++)
889 free(targets[i]);
890 free(targets);
892 return ret ? error("fetch failed.") : 0;
895 static int fetch_git(struct discovery *heads,
896 int nr_heads, struct ref **to_fetch)
898 struct rpc_state rpc;
899 struct strbuf preamble = STRBUF_INIT;
900 int i, err;
901 struct argv_array args = ARGV_ARRAY_INIT;
903 argv_array_pushl(&args, "fetch-pack", "--stateless-rpc",
904 "--stdin", "--lock-pack", NULL);
905 if (options.followtags)
906 argv_array_push(&args, "--include-tag");
907 if (options.thin)
908 argv_array_push(&args, "--thin");
909 if (options.verbosity >= 3)
910 argv_array_pushl(&args, "-v", "-v", NULL);
911 if (options.check_self_contained_and_connected)
912 argv_array_push(&args, "--check-self-contained-and-connected");
913 if (options.cloning)
914 argv_array_push(&args, "--cloning");
915 if (options.update_shallow)
916 argv_array_push(&args, "--update-shallow");
917 if (!options.progress)
918 argv_array_push(&args, "--no-progress");
919 if (options.depth)
920 argv_array_pushf(&args, "--depth=%lu", options.depth);
921 if (options.deepen_since)
922 argv_array_pushf(&args, "--shallow-since=%s", options.deepen_since);
923 for (i = 0; i < options.deepen_not.nr; i++)
924 argv_array_pushf(&args, "--shallow-exclude=%s",
925 options.deepen_not.items[i].string);
926 if (options.deepen_relative && options.depth)
927 argv_array_push(&args, "--deepen-relative");
928 if (options.from_promisor)
929 argv_array_push(&args, "--from-promisor");
930 if (options.no_dependents)
931 argv_array_push(&args, "--no-dependents");
932 if (options.filter)
933 argv_array_pushf(&args, "--filter=%s", options.filter);
934 argv_array_push(&args, url.buf);
936 for (i = 0; i < nr_heads; i++) {
937 struct ref *ref = to_fetch[i];
938 if (!*ref->name)
939 die("cannot fetch by sha1 over smart http");
940 packet_buf_write(&preamble, "%s %s\n",
941 oid_to_hex(&ref->old_oid), ref->name);
943 packet_buf_flush(&preamble);
945 memset(&rpc, 0, sizeof(rpc));
946 rpc.service_name = "git-upload-pack",
947 rpc.argv = args.argv;
948 rpc.stdin_preamble = &preamble;
949 rpc.gzip_request = 1;
951 err = rpc_service(&rpc, heads);
952 if (rpc.result.len)
953 write_or_die(1, rpc.result.buf, rpc.result.len);
954 strbuf_release(&rpc.result);
955 strbuf_release(&preamble);
956 argv_array_clear(&args);
957 return err;
960 static int fetch(int nr_heads, struct ref **to_fetch)
962 struct discovery *d = discover_refs("git-upload-pack", 0);
963 if (d->proto_git)
964 return fetch_git(d, nr_heads, to_fetch);
965 else
966 return fetch_dumb(nr_heads, to_fetch);
969 static void parse_fetch(struct strbuf *buf)
971 struct ref **to_fetch = NULL;
972 struct ref *list_head = NULL;
973 struct ref **list = &list_head;
974 int alloc_heads = 0, nr_heads = 0;
976 do {
977 const char *p;
978 if (skip_prefix(buf->buf, "fetch ", &p)) {
979 const char *name;
980 struct ref *ref;
981 struct object_id old_oid;
983 if (get_oid_hex(p, &old_oid))
984 die("protocol error: expected sha/ref, got %s'", p);
985 if (p[GIT_SHA1_HEXSZ] == ' ')
986 name = p + GIT_SHA1_HEXSZ + 1;
987 else if (!p[GIT_SHA1_HEXSZ])
988 name = "";
989 else
990 die("protocol error: expected sha/ref, got %s'", p);
992 ref = alloc_ref(name);
993 oidcpy(&ref->old_oid, &old_oid);
995 *list = ref;
996 list = &ref->next;
998 ALLOC_GROW(to_fetch, nr_heads + 1, alloc_heads);
999 to_fetch[nr_heads++] = ref;
1001 else
1002 die("http transport does not support %s", buf->buf);
1004 strbuf_reset(buf);
1005 if (strbuf_getline_lf(buf, stdin) == EOF)
1006 return;
1007 if (!*buf->buf)
1008 break;
1009 } while (1);
1011 if (fetch(nr_heads, to_fetch))
1012 exit(128); /* error already reported */
1013 free_refs(list_head);
1014 free(to_fetch);
1016 printf("\n");
1017 fflush(stdout);
1018 strbuf_reset(buf);
1021 static int push_dav(int nr_spec, char **specs)
1023 struct child_process child = CHILD_PROCESS_INIT;
1024 size_t i;
1026 child.git_cmd = 1;
1027 argv_array_push(&child.args, "http-push");
1028 argv_array_push(&child.args, "--helper-status");
1029 if (options.dry_run)
1030 argv_array_push(&child.args, "--dry-run");
1031 if (options.verbosity > 1)
1032 argv_array_push(&child.args, "--verbose");
1033 argv_array_push(&child.args, url.buf);
1034 for (i = 0; i < nr_spec; i++)
1035 argv_array_push(&child.args, specs[i]);
1037 if (run_command(&child))
1038 die("git-http-push failed");
1039 return 0;
1042 static int push_git(struct discovery *heads, int nr_spec, char **specs)
1044 struct rpc_state rpc;
1045 int i, err;
1046 struct argv_array args;
1047 struct string_list_item *cas_option;
1048 struct strbuf preamble = STRBUF_INIT;
1050 argv_array_init(&args);
1051 argv_array_pushl(&args, "send-pack", "--stateless-rpc", "--helper-status",
1052 NULL);
1054 if (options.thin)
1055 argv_array_push(&args, "--thin");
1056 if (options.dry_run)
1057 argv_array_push(&args, "--dry-run");
1058 if (options.push_cert == SEND_PACK_PUSH_CERT_ALWAYS)
1059 argv_array_push(&args, "--signed=yes");
1060 else if (options.push_cert == SEND_PACK_PUSH_CERT_IF_ASKED)
1061 argv_array_push(&args, "--signed=if-asked");
1062 if (options.verbosity == 0)
1063 argv_array_push(&args, "--quiet");
1064 else if (options.verbosity > 1)
1065 argv_array_push(&args, "--verbose");
1066 for (i = 0; i < options.push_options.nr; i++)
1067 argv_array_pushf(&args, "--push-option=%s",
1068 options.push_options.items[i].string);
1069 argv_array_push(&args, options.progress ? "--progress" : "--no-progress");
1070 for_each_string_list_item(cas_option, &cas_options)
1071 argv_array_push(&args, cas_option->string);
1072 argv_array_push(&args, url.buf);
1074 argv_array_push(&args, "--stdin");
1075 for (i = 0; i < nr_spec; i++)
1076 packet_buf_write(&preamble, "%s\n", specs[i]);
1077 packet_buf_flush(&preamble);
1079 memset(&rpc, 0, sizeof(rpc));
1080 rpc.service_name = "git-receive-pack",
1081 rpc.argv = args.argv;
1082 rpc.stdin_preamble = &preamble;
1084 err = rpc_service(&rpc, heads);
1085 if (rpc.result.len)
1086 write_or_die(1, rpc.result.buf, rpc.result.len);
1087 strbuf_release(&rpc.result);
1088 strbuf_release(&preamble);
1089 argv_array_clear(&args);
1090 return err;
1093 static int push(int nr_spec, char **specs)
1095 struct discovery *heads = discover_refs("git-receive-pack", 1);
1096 int ret;
1098 if (heads->proto_git)
1099 ret = push_git(heads, nr_spec, specs);
1100 else
1101 ret = push_dav(nr_spec, specs);
1102 free_discovery(heads);
1103 return ret;
1106 static void parse_push(struct strbuf *buf)
1108 char **specs = NULL;
1109 int alloc_spec = 0, nr_spec = 0, i, ret;
1111 do {
1112 if (starts_with(buf->buf, "push ")) {
1113 ALLOC_GROW(specs, nr_spec + 1, alloc_spec);
1114 specs[nr_spec++] = xstrdup(buf->buf + 5);
1116 else
1117 die("http transport does not support %s", buf->buf);
1119 strbuf_reset(buf);
1120 if (strbuf_getline_lf(buf, stdin) == EOF)
1121 goto free_specs;
1122 if (!*buf->buf)
1123 break;
1124 } while (1);
1126 ret = push(nr_spec, specs);
1127 printf("\n");
1128 fflush(stdout);
1130 if (ret)
1131 exit(128); /* error already reported */
1133 free_specs:
1134 for (i = 0; i < nr_spec; i++)
1135 free(specs[i]);
1136 free(specs);
1140 * Used to represent the state of a connection to an HTTP server when
1141 * communicating using git's wire-protocol version 2.
1143 struct proxy_state {
1144 char *service_name;
1145 char *service_url;
1146 struct curl_slist *headers;
1147 struct strbuf request_buffer;
1148 int in;
1149 int out;
1150 struct packet_reader reader;
1151 size_t pos;
1152 int seen_flush;
1155 static void proxy_state_init(struct proxy_state *p, const char *service_name,
1156 enum protocol_version version)
1158 struct strbuf buf = STRBUF_INIT;
1160 memset(p, 0, sizeof(*p));
1161 p->service_name = xstrdup(service_name);
1163 p->in = 0;
1164 p->out = 1;
1165 strbuf_init(&p->request_buffer, 0);
1167 strbuf_addf(&buf, "%s%s", url.buf, p->service_name);
1168 p->service_url = strbuf_detach(&buf, NULL);
1170 p->headers = http_copy_default_headers();
1172 strbuf_addf(&buf, "Content-Type: application/x-%s-request", p->service_name);
1173 p->headers = curl_slist_append(p->headers, buf.buf);
1174 strbuf_reset(&buf);
1176 strbuf_addf(&buf, "Accept: application/x-%s-result", p->service_name);
1177 p->headers = curl_slist_append(p->headers, buf.buf);
1178 strbuf_reset(&buf);
1180 p->headers = curl_slist_append(p->headers, "Transfer-Encoding: chunked");
1182 /* Add the Git-Protocol header */
1183 if (get_protocol_http_header(version, &buf))
1184 p->headers = curl_slist_append(p->headers, buf.buf);
1186 packet_reader_init(&p->reader, p->in, NULL, 0,
1187 PACKET_READ_GENTLE_ON_EOF |
1188 PACKET_READ_DIE_ON_ERR_PACKET);
1190 strbuf_release(&buf);
1193 static void proxy_state_clear(struct proxy_state *p)
1195 free(p->service_name);
1196 free(p->service_url);
1197 curl_slist_free_all(p->headers);
1198 strbuf_release(&p->request_buffer);
1202 * CURLOPT_READFUNCTION callback function.
1203 * Attempts to copy over a single packet-line at a time into the
1204 * curl provided buffer.
1206 static size_t proxy_in(char *buffer, size_t eltsize,
1207 size_t nmemb, void *userdata)
1209 size_t max;
1210 struct proxy_state *p = userdata;
1211 size_t avail = p->request_buffer.len - p->pos;
1214 if (eltsize != 1)
1215 BUG("curl read callback called with size = %"PRIuMAX" != 1",
1216 (uintmax_t)eltsize);
1217 max = nmemb;
1219 if (!avail) {
1220 if (p->seen_flush) {
1221 p->seen_flush = 0;
1222 return 0;
1225 strbuf_reset(&p->request_buffer);
1226 switch (packet_reader_read(&p->reader)) {
1227 case PACKET_READ_EOF:
1228 die("unexpected EOF when reading from parent process");
1229 case PACKET_READ_NORMAL:
1230 packet_buf_write_len(&p->request_buffer, p->reader.line,
1231 p->reader.pktlen);
1232 break;
1233 case PACKET_READ_DELIM:
1234 packet_buf_delim(&p->request_buffer);
1235 break;
1236 case PACKET_READ_FLUSH:
1237 packet_buf_flush(&p->request_buffer);
1238 p->seen_flush = 1;
1239 break;
1241 p->pos = 0;
1242 avail = p->request_buffer.len;
1245 if (max < avail)
1246 avail = max;
1247 memcpy(buffer, p->request_buffer.buf + p->pos, avail);
1248 p->pos += avail;
1249 return avail;
1252 static size_t proxy_out(char *buffer, size_t eltsize,
1253 size_t nmemb, void *userdata)
1255 size_t size;
1256 struct proxy_state *p = userdata;
1258 if (eltsize != 1)
1259 BUG("curl read callback called with size = %"PRIuMAX" != 1",
1260 (uintmax_t)eltsize);
1261 size = nmemb;
1263 write_or_die(p->out, buffer, size);
1264 return size;
1267 /* Issues a request to the HTTP server configured in `p` */
1268 static int proxy_request(struct proxy_state *p)
1270 struct active_request_slot *slot;
1272 slot = get_active_slot();
1274 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
1275 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1276 curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
1277 curl_easy_setopt(slot->curl, CURLOPT_URL, p->service_url);
1278 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, p->headers);
1280 /* Setup function to read request from client */
1281 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, proxy_in);
1282 curl_easy_setopt(slot->curl, CURLOPT_READDATA, p);
1284 /* Setup function to write server response to client */
1285 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, proxy_out);
1286 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, p);
1288 if (run_slot(slot, NULL) != HTTP_OK)
1289 return -1;
1291 return 0;
1294 static int stateless_connect(const char *service_name)
1296 struct discovery *discover;
1297 struct proxy_state p;
1300 * Run the info/refs request and see if the server supports protocol
1301 * v2. If and only if the server supports v2 can we successfully
1302 * establish a stateless connection, otherwise we need to tell the
1303 * client to fallback to using other transport helper functions to
1304 * complete their request.
1306 discover = discover_refs(service_name, 0);
1307 if (discover->version != protocol_v2) {
1308 printf("fallback\n");
1309 fflush(stdout);
1310 return -1;
1311 } else {
1312 /* Stateless Connection established */
1313 printf("\n");
1314 fflush(stdout);
1317 proxy_state_init(&p, service_name, discover->version);
1320 * Dump the capability listing that we got from the server earlier
1321 * during the info/refs request.
1323 write_or_die(p.out, discover->buf, discover->len);
1325 /* Peek the next packet line. Until we see EOF keep sending POSTs */
1326 while (packet_reader_peek(&p.reader) != PACKET_READ_EOF) {
1327 if (proxy_request(&p)) {
1328 /* We would have an err here */
1329 break;
1333 proxy_state_clear(&p);
1334 return 0;
1337 int cmd_main(int argc, const char **argv)
1339 struct strbuf buf = STRBUF_INIT;
1340 int nongit;
1342 setup_git_directory_gently(&nongit);
1343 if (argc < 2) {
1344 error("remote-curl: usage: git remote-curl <remote> [<url>]");
1345 return 1;
1348 options.verbosity = 1;
1349 options.progress = !!isatty(2);
1350 options.thin = 1;
1351 string_list_init(&options.deepen_not, 1);
1352 string_list_init(&options.push_options, 1);
1354 remote = remote_get(argv[1]);
1356 if (argc > 2) {
1357 end_url_with_slash(&url, argv[2]);
1358 } else {
1359 end_url_with_slash(&url, remote->url[0]);
1362 http_init(remote, url.buf, 0);
1364 do {
1365 const char *arg;
1367 if (strbuf_getline_lf(&buf, stdin) == EOF) {
1368 if (ferror(stdin))
1369 error("remote-curl: error reading command stream from git");
1370 return 1;
1372 if (buf.len == 0)
1373 break;
1374 if (starts_with(buf.buf, "fetch ")) {
1375 if (nongit)
1376 die("remote-curl: fetch attempted without a local repo");
1377 parse_fetch(&buf);
1379 } else if (!strcmp(buf.buf, "list") || starts_with(buf.buf, "list ")) {
1380 int for_push = !!strstr(buf.buf + 4, "for-push");
1381 output_refs(get_refs(for_push));
1383 } else if (starts_with(buf.buf, "push ")) {
1384 parse_push(&buf);
1386 } else if (skip_prefix(buf.buf, "option ", &arg)) {
1387 char *value = strchr(arg, ' ');
1388 int result;
1390 if (value)
1391 *value++ = '\0';
1392 else
1393 value = "true";
1395 result = set_option(arg, value);
1396 if (!result)
1397 printf("ok\n");
1398 else if (result < 0)
1399 printf("error invalid value\n");
1400 else
1401 printf("unsupported\n");
1402 fflush(stdout);
1404 } else if (!strcmp(buf.buf, "capabilities")) {
1405 printf("stateless-connect\n");
1406 printf("fetch\n");
1407 printf("option\n");
1408 printf("push\n");
1409 printf("check-connectivity\n");
1410 printf("\n");
1411 fflush(stdout);
1412 } else if (skip_prefix(buf.buf, "stateless-connect ", &arg)) {
1413 if (!stateless_connect(arg))
1414 break;
1415 } else {
1416 error("remote-curl: unknown command '%s' from git", buf.buf);
1417 return 1;
1419 strbuf_reset(&buf);
1420 } while (1);
1422 http_cleanup();
1424 return 0;