Merge branch 'jk/t9001-deflake'
[git/gitster.git] / remote-curl.c
blob4adcf25ed6eeb57136961235b10fc8c03a39f3ba
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "git-curl-compat.h"
5 #include "config.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "hex.h"
9 #include "remote.h"
10 #include "connect.h"
11 #include "strbuf.h"
12 #include "walker.h"
13 #include "http.h"
14 #include "run-command.h"
15 #include "pkt-line.h"
16 #include "string-list.h"
17 #include "strvec.h"
18 #include "credential.h"
19 #include "oid-array.h"
20 #include "send-pack.h"
21 #include "setup.h"
22 #include "protocol.h"
23 #include "quote.h"
24 #include "trace2.h"
25 #include "transport.h"
26 #include "url.h"
27 #include "write-or-die.h"
29 static struct remote *remote;
30 /* always ends with a trailing slash */
31 static struct strbuf url = STRBUF_INIT;
33 struct options {
34 int verbosity;
35 unsigned long depth;
36 char *deepen_since;
37 struct string_list deepen_not;
38 struct string_list push_options;
39 char *filter;
40 unsigned progress : 1,
41 check_self_contained_and_connected : 1,
42 cloning : 1,
43 update_shallow : 1,
44 followtags : 1,
45 dry_run : 1,
46 thin : 1,
47 /* One of the SEND_PACK_PUSH_CERT_* constants. */
48 push_cert : 2,
49 deepen_relative : 1,
51 /* see documentation of corresponding flag in fetch-pack.h */
52 from_promisor : 1,
54 refetch : 1,
55 atomic : 1,
56 object_format : 1,
57 force_if_includes : 1;
58 const struct git_hash_algo *hash_algo;
60 static struct options options;
61 static struct string_list cas_options = STRING_LIST_INIT_DUP;
63 static int set_option(const char *name, size_t namelen, const char *value)
65 if (!strncmp(name, "verbosity", namelen)) {
66 char *end;
67 int v = strtol(value, &end, 10);
68 if (value == end || *end)
69 return -1;
70 options.verbosity = v;
71 return 0;
73 else if (!strncmp(name, "progress", namelen)) {
74 if (!strcmp(value, "true"))
75 options.progress = 1;
76 else if (!strcmp(value, "false"))
77 options.progress = 0;
78 else
79 return -1;
80 return 0;
82 else if (!strncmp(name, "depth", namelen)) {
83 char *end;
84 unsigned long v = strtoul(value, &end, 10);
85 if (value == end || *end)
86 return -1;
87 options.depth = v;
88 return 0;
90 else if (!strncmp(name, "deepen-since", namelen)) {
91 options.deepen_since = xstrdup(value);
92 return 0;
94 else if (!strncmp(name, "deepen-not", namelen)) {
95 string_list_append(&options.deepen_not, value);
96 return 0;
98 else if (!strncmp(name, "deepen-relative", namelen)) {
99 if (!strcmp(value, "true"))
100 options.deepen_relative = 1;
101 else if (!strcmp(value, "false"))
102 options.deepen_relative = 0;
103 else
104 return -1;
105 return 0;
107 else if (!strncmp(name, "followtags", namelen)) {
108 if (!strcmp(value, "true"))
109 options.followtags = 1;
110 else if (!strcmp(value, "false"))
111 options.followtags = 0;
112 else
113 return -1;
114 return 0;
116 else if (!strncmp(name, "dry-run", namelen)) {
117 if (!strcmp(value, "true"))
118 options.dry_run = 1;
119 else if (!strcmp(value, "false"))
120 options.dry_run = 0;
121 else
122 return -1;
123 return 0;
125 else if (!strncmp(name, "check-connectivity", namelen)) {
126 if (!strcmp(value, "true"))
127 options.check_self_contained_and_connected = 1;
128 else if (!strcmp(value, "false"))
129 options.check_self_contained_and_connected = 0;
130 else
131 return -1;
132 return 0;
134 else if (!strncmp(name, "cas", namelen)) {
135 struct strbuf val = STRBUF_INIT;
136 strbuf_addstr(&val, "--force-with-lease=");
137 if (*value != '"')
138 strbuf_addstr(&val, value);
139 else if (unquote_c_style(&val, value, NULL))
140 return -1;
141 string_list_append(&cas_options, val.buf);
142 strbuf_release(&val);
143 return 0;
144 } else if (!strncmp(name, TRANS_OPT_FORCE_IF_INCLUDES, namelen)) {
145 if (!strcmp(value, "true"))
146 options.force_if_includes = 1;
147 else if (!strcmp(value, "false"))
148 options.force_if_includes = 0;
149 else
150 return -1;
151 return 0;
152 } else if (!strncmp(name, "cloning", namelen)) {
153 if (!strcmp(value, "true"))
154 options.cloning = 1;
155 else if (!strcmp(value, "false"))
156 options.cloning = 0;
157 else
158 return -1;
159 return 0;
160 } else if (!strncmp(name, "update-shallow", namelen)) {
161 if (!strcmp(value, "true"))
162 options.update_shallow = 1;
163 else if (!strcmp(value, "false"))
164 options.update_shallow = 0;
165 else
166 return -1;
167 return 0;
168 } else if (!strncmp(name, "pushcert", namelen)) {
169 if (!strcmp(value, "true"))
170 options.push_cert = SEND_PACK_PUSH_CERT_ALWAYS;
171 else if (!strcmp(value, "false"))
172 options.push_cert = SEND_PACK_PUSH_CERT_NEVER;
173 else if (!strcmp(value, "if-asked"))
174 options.push_cert = SEND_PACK_PUSH_CERT_IF_ASKED;
175 else
176 return -1;
177 return 0;
178 } else if (!strncmp(name, "atomic", namelen)) {
179 if (!strcmp(value, "true"))
180 options.atomic = 1;
181 else if (!strcmp(value, "false"))
182 options.atomic = 0;
183 else
184 return -1;
185 return 0;
186 } else if (!strncmp(name, "push-option", namelen)) {
187 if (*value != '"')
188 string_list_append(&options.push_options, value);
189 else {
190 struct strbuf unquoted = STRBUF_INIT;
191 if (unquote_c_style(&unquoted, value, NULL) < 0)
192 die(_("invalid quoting in push-option value: '%s'"), value);
193 string_list_append_nodup(&options.push_options,
194 strbuf_detach(&unquoted, NULL));
196 return 0;
197 } else if (!strncmp(name, "family", namelen)) {
198 if (!strcmp(value, "ipv4"))
199 git_curl_ipresolve = CURL_IPRESOLVE_V4;
200 else if (!strcmp(value, "ipv6"))
201 git_curl_ipresolve = CURL_IPRESOLVE_V6;
202 else if (!strcmp(value, "all"))
203 git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
204 else
205 return -1;
206 return 0;
207 } else if (!strncmp(name, "from-promisor", namelen)) {
208 options.from_promisor = 1;
209 return 0;
210 } else if (!strncmp(name, "refetch", namelen)) {
211 options.refetch = 1;
212 return 0;
213 } else if (!strncmp(name, "filter", namelen)) {
214 options.filter = xstrdup(value);
215 return 0;
216 } else if (!strncmp(name, "object-format", namelen)) {
217 options.object_format = 1;
218 if (strcmp(value, "true"))
219 die(_("unknown value for object-format: %s"), value);
220 return 0;
221 } else {
222 return 1 /* unsupported */;
226 struct discovery {
227 char *service;
228 char *buf_alloc;
229 char *buf;
230 size_t len;
231 struct ref *refs;
232 struct oid_array shallow;
233 enum protocol_version version;
234 unsigned proto_git : 1;
236 static struct discovery *last_discovery;
238 static struct ref *parse_git_refs(struct discovery *heads, int for_push)
240 struct ref *list = NULL;
241 struct packet_reader reader;
243 packet_reader_init(&reader, -1, heads->buf, heads->len,
244 PACKET_READ_CHOMP_NEWLINE |
245 PACKET_READ_GENTLE_ON_EOF |
246 PACKET_READ_DIE_ON_ERR_PACKET);
248 heads->version = discover_version(&reader);
249 switch (heads->version) {
250 case protocol_v2:
252 * Do nothing. This isn't a list of refs but rather a
253 * capability advertisement. Client would have run
254 * 'stateless-connect' so we'll dump this capability listing
255 * and let them request the refs themselves.
257 break;
258 case protocol_v1:
259 case protocol_v0:
260 get_remote_heads(&reader, &list, for_push ? REF_NORMAL : 0,
261 NULL, &heads->shallow);
262 options.hash_algo = reader.hash_algo;
263 break;
264 case protocol_unknown_version:
265 BUG("unknown protocol version");
268 return list;
272 * Try to detect the hash algorithm used by the remote repository when using
273 * the dumb HTTP transport. As dumb transports cannot tell us the object hash
274 * directly have to derive it from the advertised ref lengths.
276 static const struct git_hash_algo *detect_hash_algo(struct discovery *heads)
278 const char *p = memchr(heads->buf, '\t', heads->len);
279 int algo;
282 * In case the remote has no refs we have no way to reliably determine
283 * the object hash used by that repository. In that case we simply fall
284 * back to SHA1, which may or may not be correct.
286 if (!p)
287 return &hash_algos[GIT_HASH_SHA1];
289 algo = hash_algo_by_length((p - heads->buf) / 2);
290 if (algo == GIT_HASH_UNKNOWN)
291 return NULL;
292 return &hash_algos[algo];
295 static struct ref *parse_info_refs(struct discovery *heads)
297 char *data, *start, *mid;
298 char *ref_name;
299 int i = 0;
301 struct ref *refs = NULL;
302 struct ref *ref = NULL;
303 struct ref *last_ref = NULL;
305 options.hash_algo = detect_hash_algo(heads);
306 if (!options.hash_algo)
307 die("%sinfo/refs not valid: could not determine hash algorithm; "
308 "is this a git repository?",
309 transport_anonymize_url(url.buf));
312 * Set the repository's hash algo to whatever we have just detected.
313 * This ensures that we can correctly parse the remote references.
315 repo_set_hash_algo(the_repository, hash_algo_by_ptr(options.hash_algo));
317 data = heads->buf;
318 start = NULL;
319 mid = data;
320 while (i < heads->len) {
321 if (!start) {
322 start = &data[i];
324 if (data[i] == '\t')
325 mid = &data[i];
326 if (data[i] == '\n') {
327 if (mid - start != options.hash_algo->hexsz)
328 die(_("%sinfo/refs not valid: is this a git repository?"),
329 transport_anonymize_url(url.buf));
330 data[i] = 0;
331 ref_name = mid + 1;
332 ref = alloc_ref(ref_name);
333 get_oid_hex_algop(start, &ref->old_oid, options.hash_algo);
334 if (!refs)
335 refs = ref;
336 if (last_ref)
337 last_ref->next = ref;
338 last_ref = ref;
339 start = NULL;
341 i++;
344 ref = alloc_ref("HEAD");
345 if (!http_fetch_ref(url.buf, ref) &&
346 !resolve_remote_symref(ref, refs)) {
347 ref->next = refs;
348 refs = ref;
349 } else {
350 free(ref);
353 return refs;
356 static void free_discovery(struct discovery *d)
358 if (d) {
359 if (d == last_discovery)
360 last_discovery = NULL;
361 free(d->shallow.oid);
362 free(d->buf_alloc);
363 free_refs(d->refs);
364 free(d->service);
365 free(d);
369 static int show_http_message(struct strbuf *type, struct strbuf *charset,
370 struct strbuf *msg)
372 const char *p, *eol;
375 * We only show text/plain parts, as other types are likely
376 * to be ugly to look at on the user's terminal.
378 if (strcmp(type->buf, "text/plain"))
379 return -1;
380 if (charset->len)
381 strbuf_reencode(msg, charset->buf, get_log_output_encoding());
383 strbuf_trim(msg);
384 if (!msg->len)
385 return -1;
387 p = msg->buf;
388 do {
389 eol = strchrnul(p, '\n');
390 fprintf(stderr, "remote: %.*s\n", (int)(eol - p), p);
391 p = eol + 1;
392 } while(*eol);
393 return 0;
396 static int get_protocol_http_header(enum protocol_version version,
397 struct strbuf *header)
399 if (version > 0) {
400 strbuf_addf(header, GIT_PROTOCOL_HEADER ": version=%d",
401 version);
403 return 1;
406 return 0;
409 static void check_smart_http(struct discovery *d, const char *service,
410 struct strbuf *type)
412 const char *p;
413 struct packet_reader reader;
416 * If we don't see x-$service-advertisement, then it's not smart-http.
417 * But once we do, we commit to it and assume any other protocol
418 * violations are hard errors.
420 if (!skip_prefix(type->buf, "application/x-", &p) ||
421 !skip_prefix(p, service, &p) ||
422 strcmp(p, "-advertisement"))
423 return;
425 packet_reader_init(&reader, -1, d->buf, d->len,
426 PACKET_READ_CHOMP_NEWLINE |
427 PACKET_READ_DIE_ON_ERR_PACKET);
428 if (packet_reader_read(&reader) != PACKET_READ_NORMAL)
429 die(_("invalid server response; expected service, got flush packet"));
431 if (skip_prefix(reader.line, "# service=", &p) && !strcmp(p, service)) {
433 * The header can include additional metadata lines, up
434 * until a packet flush marker. Ignore these now, but
435 * in the future we might start to scan them.
437 for (;;) {
438 packet_reader_read(&reader);
439 if (reader.pktlen <= 0) {
440 break;
445 * v0 smart http; callers expect us to soak up the
446 * service and header packets
448 d->buf = reader.src_buffer;
449 d->len = reader.src_len;
450 d->proto_git = 1;
452 } else if (!strcmp(reader.line, "version 2")) {
454 * v2 smart http; do not consume version packet, which will
455 * be handled elsewhere.
457 d->proto_git = 1;
459 } else {
460 die(_("invalid server response; got '%s'"), reader.line);
464 static struct discovery *discover_refs(const char *service, int for_push)
466 struct strbuf type = STRBUF_INIT;
467 struct strbuf charset = STRBUF_INIT;
468 struct strbuf buffer = STRBUF_INIT;
469 struct strbuf refs_url = STRBUF_INIT;
470 struct strbuf effective_url = STRBUF_INIT;
471 struct strbuf protocol_header = STRBUF_INIT;
472 struct string_list extra_headers = STRING_LIST_INIT_DUP;
473 struct discovery *last = last_discovery;
474 int http_ret, maybe_smart = 0;
475 struct http_get_options http_options;
476 enum protocol_version version = get_protocol_version_config();
478 if (last && !strcmp(service, last->service))
479 return last;
480 free_discovery(last);
482 strbuf_addf(&refs_url, "%sinfo/refs", url.buf);
483 if ((starts_with(url.buf, "http://") || starts_with(url.buf, "https://")) &&
484 git_env_bool("GIT_SMART_HTTP", 1)) {
485 maybe_smart = 1;
486 if (!strchr(url.buf, '?'))
487 strbuf_addch(&refs_url, '?');
488 else
489 strbuf_addch(&refs_url, '&');
490 strbuf_addf(&refs_url, "service=%s", service);
494 * NEEDSWORK: If we are trying to use protocol v2 and we are planning
495 * to perform any operation that doesn't involve upload-pack (i.e., a
496 * fetch, ls-remote, etc), then fallback to v0 since we don't know how
497 * to do anything else (like push or remote archive) via v2.
499 if (version == protocol_v2 && strcmp("git-upload-pack", service))
500 version = protocol_v0;
502 /* Add the extra Git-Protocol header */
503 if (get_protocol_http_header(version, &protocol_header))
504 string_list_append(&extra_headers, protocol_header.buf);
506 memset(&http_options, 0, sizeof(http_options));
507 http_options.content_type = &type;
508 http_options.charset = &charset;
509 http_options.effective_url = &effective_url;
510 http_options.base_url = &url;
511 http_options.extra_headers = &extra_headers;
512 http_options.initial_request = 1;
513 http_options.no_cache = 1;
515 http_ret = http_get_strbuf(refs_url.buf, &buffer, &http_options);
516 switch (http_ret) {
517 case HTTP_OK:
518 break;
519 case HTTP_MISSING_TARGET:
520 show_http_message(&type, &charset, &buffer);
521 die(_("repository '%s' not found"),
522 transport_anonymize_url(url.buf));
523 case HTTP_NOAUTH:
524 show_http_message(&type, &charset, &buffer);
525 die(_("Authentication failed for '%s'"),
526 transport_anonymize_url(url.buf));
527 case HTTP_NOMATCHPUBLICKEY:
528 show_http_message(&type, &charset, &buffer);
529 die(_("unable to access '%s' with http.pinnedPubkey configuration: %s"),
530 transport_anonymize_url(url.buf), curl_errorstr);
531 default:
532 show_http_message(&type, &charset, &buffer);
533 die(_("unable to access '%s': %s"),
534 transport_anonymize_url(url.buf), curl_errorstr);
537 if (options.verbosity && !starts_with(refs_url.buf, url.buf)) {
538 char *u = transport_anonymize_url(url.buf);
539 warning(_("redirecting to %s"), u);
540 free(u);
543 last= xcalloc(1, sizeof(*last_discovery));
544 last->service = xstrdup(service);
545 last->buf_alloc = strbuf_detach(&buffer, &last->len);
546 last->buf = last->buf_alloc;
548 if (maybe_smart)
549 check_smart_http(last, service, &type);
551 if (last->proto_git)
552 last->refs = parse_git_refs(last, for_push);
553 else
554 last->refs = parse_info_refs(last);
556 strbuf_release(&refs_url);
557 strbuf_release(&type);
558 strbuf_release(&charset);
559 strbuf_release(&effective_url);
560 strbuf_release(&buffer);
561 strbuf_release(&protocol_header);
562 string_list_clear(&extra_headers, 0);
563 last_discovery = last;
564 return last;
567 static struct ref *get_refs(int for_push)
569 struct discovery *heads;
571 if (for_push)
572 heads = discover_refs("git-receive-pack", for_push);
573 else
574 heads = discover_refs("git-upload-pack", for_push);
576 return heads->refs;
579 static void output_refs(struct ref *refs)
581 struct ref *posn;
582 if (options.object_format && options.hash_algo) {
583 printf(":object-format %s\n", options.hash_algo->name);
584 repo_set_hash_algo(the_repository,
585 hash_algo_by_ptr(options.hash_algo));
587 for (posn = refs; posn; posn = posn->next) {
588 if (posn->symref)
589 printf("@%s %s\n", posn->symref, posn->name);
590 else
591 printf("%s %s\n", hash_to_hex_algop(posn->old_oid.hash,
592 options.hash_algo),
593 posn->name);
595 printf("\n");
596 fflush(stdout);
599 struct rpc_state {
600 const char *service_name;
601 char *service_url;
602 char *hdr_content_type;
603 char *hdr_accept;
604 char *hdr_accept_language;
605 char *protocol_header;
606 char *buf;
607 size_t alloc;
608 size_t len;
609 size_t pos;
610 int in;
611 int out;
612 int any_written;
613 unsigned gzip_request : 1;
614 unsigned initial_buffer : 1;
617 * Whenever a pkt-line is read into buf, append the 4 characters
618 * denoting its length before appending the payload.
620 unsigned write_line_lengths : 1;
623 * Used by rpc_out; initialize to 0. This is true if a flush has been
624 * read, but the corresponding line length (if write_line_lengths is
625 * true) and EOF have not been sent to libcurl. Since each flush marks
626 * the end of a request, each flush must be completely sent before any
627 * further reading occurs.
629 unsigned flush_read_but_not_sent : 1;
632 #define RPC_STATE_INIT { 0 }
635 * Appends the result of reading from rpc->out to the string represented by
636 * rpc->buf and rpc->len if there is enough space. Returns 1 if there was
637 * enough space, 0 otherwise.
639 * If rpc->write_line_lengths is true, appends the line length as a 4-byte
640 * hexadecimal string before appending the result described above.
642 * Writes the total number of bytes appended into appended.
644 static int rpc_read_from_out(struct rpc_state *rpc, int options,
645 size_t *appended,
646 enum packet_read_status *status) {
647 size_t left;
648 char *buf;
649 int pktlen_raw;
651 if (rpc->write_line_lengths) {
652 left = rpc->alloc - rpc->len - 4;
653 buf = rpc->buf + rpc->len + 4;
654 } else {
655 left = rpc->alloc - rpc->len;
656 buf = rpc->buf + rpc->len;
659 if (left < LARGE_PACKET_MAX)
660 return 0;
662 *status = packet_read_with_status(rpc->out, NULL, NULL, buf,
663 left, &pktlen_raw, options);
664 if (*status != PACKET_READ_EOF) {
665 *appended = pktlen_raw + (rpc->write_line_lengths ? 4 : 0);
666 rpc->len += *appended;
669 if (rpc->write_line_lengths) {
670 switch (*status) {
671 case PACKET_READ_EOF:
672 if (!(options & PACKET_READ_GENTLE_ON_EOF))
673 die(_("shouldn't have EOF when not gentle on EOF"));
674 break;
675 case PACKET_READ_NORMAL:
676 set_packet_header(buf - 4, *appended);
677 break;
678 case PACKET_READ_DELIM:
679 memcpy(buf - 4, "0001", 4);
680 break;
681 case PACKET_READ_FLUSH:
682 memcpy(buf - 4, "0000", 4);
683 break;
684 case PACKET_READ_RESPONSE_END:
685 die(_("remote server sent unexpected response end packet"));
689 return 1;
692 static size_t rpc_out(void *ptr, size_t eltsize,
693 size_t nmemb, void *buffer_)
695 size_t max = eltsize * nmemb;
696 struct rpc_state *rpc = buffer_;
697 size_t avail = rpc->len - rpc->pos;
698 enum packet_read_status status;
700 if (!avail) {
701 rpc->initial_buffer = 0;
702 rpc->len = 0;
703 rpc->pos = 0;
704 if (!rpc->flush_read_but_not_sent) {
705 if (!rpc_read_from_out(rpc, 0, &avail, &status))
706 BUG("The entire rpc->buf should be larger than LARGE_PACKET_MAX");
707 if (status == PACKET_READ_FLUSH)
708 rpc->flush_read_but_not_sent = 1;
711 * If flush_read_but_not_sent is true, we have already read one
712 * full request but have not fully sent it + EOF, which is why
713 * we need to refrain from reading.
716 if (rpc->flush_read_but_not_sent) {
717 if (!avail) {
719 * The line length either does not need to be sent at
720 * all or has already been completely sent. Now we can
721 * return 0, indicating EOF, meaning that the flush has
722 * been fully sent.
724 rpc->flush_read_but_not_sent = 0;
725 return 0;
728 * If avail is non-zero, the line length for the flush still
729 * hasn't been fully sent. Proceed with sending the line
730 * length.
734 if (max < avail)
735 avail = max;
736 memcpy(ptr, rpc->buf + rpc->pos, avail);
737 rpc->pos += avail;
738 return avail;
741 static int rpc_seek(void *clientp, curl_off_t offset, int origin)
743 struct rpc_state *rpc = clientp;
745 if (origin != SEEK_SET)
746 BUG("rpc_seek only handles SEEK_SET, not %d", origin);
748 if (rpc->initial_buffer) {
749 if (offset < 0 || offset > rpc->len) {
750 error("curl seek would be outside of rpc buffer");
751 return CURL_SEEKFUNC_FAIL;
753 rpc->pos = offset;
754 return CURL_SEEKFUNC_OK;
756 error(_("unable to rewind rpc post data - try increasing http.postBuffer"));
757 return CURL_SEEKFUNC_FAIL;
760 struct check_pktline_state {
761 char len_buf[4];
762 int len_filled;
763 int remaining;
766 static void check_pktline(struct check_pktline_state *state, const char *ptr, size_t size)
768 while (size) {
769 if (!state->remaining) {
770 int digits_remaining = 4 - state->len_filled;
771 if (digits_remaining > size)
772 digits_remaining = size;
773 memcpy(&state->len_buf[state->len_filled], ptr, digits_remaining);
774 state->len_filled += digits_remaining;
775 ptr += digits_remaining;
776 size -= digits_remaining;
778 if (state->len_filled == 4) {
779 state->remaining = packet_length(state->len_buf,
780 sizeof(state->len_buf));
781 if (state->remaining < 0) {
782 die(_("remote-curl: bad line length character: %.4s"), state->len_buf);
783 } else if (state->remaining == 2) {
784 die(_("remote-curl: unexpected response end packet"));
785 } else if (state->remaining < 4) {
786 state->remaining = 0;
787 } else {
788 state->remaining -= 4;
790 state->len_filled = 0;
794 if (state->remaining) {
795 int remaining = state->remaining;
796 if (remaining > size)
797 remaining = size;
798 ptr += remaining;
799 size -= remaining;
800 state->remaining -= remaining;
805 struct rpc_in_data {
806 struct rpc_state *rpc;
807 struct active_request_slot *slot;
808 int check_pktline;
809 struct check_pktline_state pktline_state;
813 * A callback for CURLOPT_WRITEFUNCTION. The return value is the bytes consumed
814 * from ptr.
816 static size_t rpc_in(char *ptr, size_t eltsize,
817 size_t nmemb, void *buffer_)
819 size_t size = eltsize * nmemb;
820 struct rpc_in_data *data = buffer_;
821 long response_code;
823 if (curl_easy_getinfo(data->slot->curl, CURLINFO_RESPONSE_CODE,
824 &response_code) != CURLE_OK)
825 return size;
826 if (response_code >= 300)
827 return size;
828 if (size)
829 data->rpc->any_written = 1;
830 if (data->check_pktline)
831 check_pktline(&data->pktline_state, ptr, size);
832 write_or_die(data->rpc->in, ptr, size);
833 return size;
836 static int run_slot(struct active_request_slot *slot,
837 struct slot_results *results)
839 int err;
840 struct slot_results results_buf;
842 if (!results)
843 results = &results_buf;
845 err = run_one_slot(slot, results);
847 if (err != HTTP_OK && err != HTTP_REAUTH) {
848 struct strbuf msg = STRBUF_INIT;
849 if (results->http_code && results->http_code != 200)
850 strbuf_addf(&msg, "HTTP %ld", results->http_code);
851 if (results->curl_result != CURLE_OK) {
852 if (msg.len)
853 strbuf_addch(&msg, ' ');
854 strbuf_addf(&msg, "curl %d", results->curl_result);
855 if (curl_errorstr[0]) {
856 strbuf_addch(&msg, ' ');
857 strbuf_addstr(&msg, curl_errorstr);
860 error(_("RPC failed; %s"), msg.buf);
861 strbuf_release(&msg);
864 return err;
867 static int probe_rpc(struct rpc_state *rpc, struct slot_results *results)
869 struct active_request_slot *slot;
870 struct curl_slist *headers = http_copy_default_headers();
871 struct strbuf buf = STRBUF_INIT;
872 int err;
874 slot = get_active_slot();
876 headers = curl_slist_append(headers, rpc->hdr_content_type);
877 headers = curl_slist_append(headers, rpc->hdr_accept);
879 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
880 curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
881 curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
882 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, NULL);
883 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, "0000");
884 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, 4);
885 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
886 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
887 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &buf);
889 err = run_slot(slot, results);
891 curl_slist_free_all(headers);
892 strbuf_release(&buf);
893 return err;
896 static curl_off_t xcurl_off_t(size_t len)
898 uintmax_t size = len;
899 if (size > maximum_signed_value_of_type(curl_off_t))
900 die(_("cannot handle pushes this big"));
901 return (curl_off_t)size;
905 * If flush_received is true, do not attempt to read any more; just use what's
906 * in rpc->buf.
908 static int post_rpc(struct rpc_state *rpc, int stateless_connect, int flush_received)
910 struct active_request_slot *slot;
911 struct curl_slist *headers = NULL;
912 int use_gzip = rpc->gzip_request;
913 char *gzip_body = NULL;
914 size_t gzip_size = 0;
915 int err, large_request = 0;
916 int needs_100_continue = 0;
917 struct rpc_in_data rpc_in_data;
919 /* Try to load the entire request, if we can fit it into the
920 * allocated buffer space we can use HTTP/1.0 and avoid the
921 * chunked encoding mess.
923 if (!flush_received) {
924 while (1) {
925 size_t n;
926 enum packet_read_status status;
928 if (!rpc_read_from_out(rpc, 0, &n, &status)) {
929 large_request = 1;
930 use_gzip = 0;
931 break;
933 if (status == PACKET_READ_FLUSH)
934 break;
938 if (large_request) {
939 struct slot_results results;
941 do {
942 err = probe_rpc(rpc, &results);
943 if (err == HTTP_REAUTH)
944 credential_fill(&http_auth, 0);
945 } while (err == HTTP_REAUTH);
946 if (err != HTTP_OK)
947 return -1;
949 if (results.auth_avail & CURLAUTH_GSSNEGOTIATE || http_auth.authtype)
950 needs_100_continue = 1;
953 retry:
954 headers = http_copy_default_headers();
955 headers = curl_slist_append(headers, rpc->hdr_content_type);
956 headers = curl_slist_append(headers, rpc->hdr_accept);
957 headers = curl_slist_append(headers, needs_100_continue ?
958 "Expect: 100-continue" : "Expect:");
960 headers = http_append_auth_header(&http_auth, headers);
962 /* Add Accept-Language header */
963 if (rpc->hdr_accept_language)
964 headers = curl_slist_append(headers, rpc->hdr_accept_language);
966 /* Add the extra Git-Protocol header */
967 if (rpc->protocol_header)
968 headers = curl_slist_append(headers, rpc->protocol_header);
970 slot = get_active_slot();
972 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
973 curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
974 curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
975 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
977 if (large_request) {
978 /* The request body is large and the size cannot be predicted.
979 * We must use chunked encoding to send it.
981 #ifdef GIT_CURL_NEED_TRANSFER_ENCODING_HEADER
982 headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
983 #endif
984 rpc->initial_buffer = 1;
985 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, rpc_out);
986 curl_easy_setopt(slot->curl, CURLOPT_INFILE, rpc);
987 curl_easy_setopt(slot->curl, CURLOPT_SEEKFUNCTION, rpc_seek);
988 curl_easy_setopt(slot->curl, CURLOPT_SEEKDATA, rpc);
989 if (options.verbosity > 1) {
990 fprintf(stderr, "POST %s (chunked)\n", rpc->service_name);
991 fflush(stderr);
994 } else if (gzip_body) {
996 * If we are looping to retry authentication, then the previous
997 * run will have set up the headers and gzip buffer already,
998 * and we just need to send it.
1000 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
1001 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
1003 } else if (use_gzip && 1024 < rpc->len) {
1004 /* The client backend isn't giving us compressed data so
1005 * we can try to deflate it ourselves, this may save on
1006 * the transfer time.
1008 git_zstream stream;
1009 int ret;
1011 git_deflate_init_gzip(&stream, Z_BEST_COMPRESSION);
1012 gzip_size = git_deflate_bound(&stream, rpc->len);
1013 gzip_body = xmalloc(gzip_size);
1015 stream.next_in = (unsigned char *)rpc->buf;
1016 stream.avail_in = rpc->len;
1017 stream.next_out = (unsigned char *)gzip_body;
1018 stream.avail_out = gzip_size;
1020 ret = git_deflate(&stream, Z_FINISH);
1021 if (ret != Z_STREAM_END)
1022 die(_("cannot deflate request; zlib deflate error %d"), ret);
1024 ret = git_deflate_end_gently(&stream);
1025 if (ret != Z_OK)
1026 die(_("cannot deflate request; zlib end error %d"), ret);
1028 gzip_size = stream.total_out;
1030 headers = curl_slist_append(headers, "Content-Encoding: gzip");
1031 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
1032 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
1034 if (options.verbosity > 1) {
1035 fprintf(stderr, "POST %s (gzip %lu to %lu bytes)\n",
1036 rpc->service_name,
1037 (unsigned long)rpc->len, (unsigned long)gzip_size);
1038 fflush(stderr);
1040 } else {
1041 /* We know the complete request size in advance, use the
1042 * more normal Content-Length approach.
1044 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, rpc->buf);
1045 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(rpc->len));
1046 if (options.verbosity > 1) {
1047 fprintf(stderr, "POST %s (%lu bytes)\n",
1048 rpc->service_name, (unsigned long)rpc->len);
1049 fflush(stderr);
1053 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1054 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, rpc_in);
1055 rpc_in_data.rpc = rpc;
1056 rpc_in_data.slot = slot;
1057 rpc_in_data.check_pktline = stateless_connect;
1058 memset(&rpc_in_data.pktline_state, 0, sizeof(rpc_in_data.pktline_state));
1059 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &rpc_in_data);
1060 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1063 rpc->any_written = 0;
1064 err = run_slot(slot, NULL);
1065 if (err == HTTP_REAUTH && !large_request) {
1066 credential_fill(&http_auth, 0);
1067 curl_slist_free_all(headers);
1068 goto retry;
1070 if (err != HTTP_OK)
1071 err = -1;
1073 if (!rpc->any_written)
1074 err = -1;
1076 if (rpc_in_data.pktline_state.len_filled)
1077 err = error(_("%d bytes of length header were received"), rpc_in_data.pktline_state.len_filled);
1078 if (rpc_in_data.pktline_state.remaining)
1079 err = error(_("%d bytes of body are still expected"), rpc_in_data.pktline_state.remaining);
1081 if (stateless_connect)
1082 packet_response_end(rpc->in);
1084 curl_slist_free_all(headers);
1085 free(gzip_body);
1086 return err;
1089 static int rpc_service(struct rpc_state *rpc, struct discovery *heads,
1090 const char **client_argv, const struct strbuf *preamble,
1091 struct strbuf *rpc_result)
1093 const char *svc = rpc->service_name;
1094 struct strbuf buf = STRBUF_INIT;
1095 struct child_process client = CHILD_PROCESS_INIT;
1096 int err = 0;
1098 client.in = -1;
1099 client.out = -1;
1100 client.git_cmd = 1;
1101 strvec_pushv(&client.args, client_argv);
1102 if (start_command(&client))
1103 exit(1);
1104 write_or_die(client.in, preamble->buf, preamble->len);
1105 if (heads)
1106 write_or_die(client.in, heads->buf, heads->len);
1108 rpc->alloc = http_post_buffer;
1109 rpc->buf = xmalloc(rpc->alloc);
1110 rpc->in = client.in;
1111 rpc->out = client.out;
1113 strbuf_addf(&buf, "%s%s", url.buf, svc);
1114 rpc->service_url = strbuf_detach(&buf, NULL);
1116 rpc->hdr_accept_language = xstrdup_or_null(http_get_accept_language_header());
1118 strbuf_addf(&buf, "Content-Type: application/x-%s-request", svc);
1119 rpc->hdr_content_type = strbuf_detach(&buf, NULL);
1121 strbuf_addf(&buf, "Accept: application/x-%s-result", svc);
1122 rpc->hdr_accept = strbuf_detach(&buf, NULL);
1124 if (get_protocol_http_header(heads->version, &buf))
1125 rpc->protocol_header = strbuf_detach(&buf, NULL);
1126 else
1127 rpc->protocol_header = NULL;
1129 while (!err) {
1130 int n = packet_read(rpc->out, rpc->buf, rpc->alloc, 0);
1131 if (!n)
1132 break;
1133 rpc->pos = 0;
1134 rpc->len = n;
1135 err |= post_rpc(rpc, 0, 0);
1138 close(client.in);
1139 client.in = -1;
1140 if (!err) {
1141 strbuf_read(rpc_result, client.out, 0);
1142 } else {
1143 char buf[4096];
1144 for (;;)
1145 if (xread(client.out, buf, sizeof(buf)) <= 0)
1146 break;
1149 close(client.out);
1150 client.out = -1;
1152 err |= finish_command(&client);
1153 free(rpc->service_url);
1154 free(rpc->hdr_content_type);
1155 free(rpc->hdr_accept);
1156 free(rpc->hdr_accept_language);
1157 free(rpc->protocol_header);
1158 free(rpc->buf);
1159 strbuf_release(&buf);
1160 return err;
1163 static int fetch_dumb(int nr_heads, struct ref **to_fetch)
1165 struct walker *walker;
1166 char **targets;
1167 int ret, i;
1169 ALLOC_ARRAY(targets, nr_heads);
1170 if (options.depth || options.deepen_since)
1171 die(_("dumb http transport does not support shallow capabilities"));
1172 for (i = 0; i < nr_heads; i++)
1173 targets[i] = xstrdup(oid_to_hex(&to_fetch[i]->old_oid));
1175 walker = get_http_walker(url.buf);
1176 walker->get_verbosely = options.verbosity >= 3;
1177 walker->get_progress = options.progress;
1178 walker->get_recover = 0;
1179 ret = walker_fetch(walker, nr_heads, targets, NULL, NULL);
1180 walker_free(walker);
1182 for (i = 0; i < nr_heads; i++)
1183 free(targets[i]);
1184 free(targets);
1186 return ret ? error(_("fetch failed.")) : 0;
1189 static int fetch_git(struct discovery *heads,
1190 int nr_heads, struct ref **to_fetch)
1192 struct rpc_state rpc = RPC_STATE_INIT;
1193 struct strbuf preamble = STRBUF_INIT;
1194 int i, err;
1195 struct strvec args = STRVEC_INIT;
1196 struct strbuf rpc_result = STRBUF_INIT;
1198 strvec_pushl(&args, "fetch-pack", "--stateless-rpc",
1199 "--stdin", "--lock-pack", NULL);
1200 if (options.followtags)
1201 strvec_push(&args, "--include-tag");
1202 if (options.thin)
1203 strvec_push(&args, "--thin");
1204 if (options.verbosity >= 3)
1205 strvec_pushl(&args, "-v", "-v", NULL);
1206 if (options.check_self_contained_and_connected)
1207 strvec_push(&args, "--check-self-contained-and-connected");
1208 if (options.cloning)
1209 strvec_push(&args, "--cloning");
1210 if (options.update_shallow)
1211 strvec_push(&args, "--update-shallow");
1212 if (!options.progress)
1213 strvec_push(&args, "--no-progress");
1214 if (options.depth)
1215 strvec_pushf(&args, "--depth=%lu", options.depth);
1216 if (options.deepen_since)
1217 strvec_pushf(&args, "--shallow-since=%s", options.deepen_since);
1218 for (i = 0; i < options.deepen_not.nr; i++)
1219 strvec_pushf(&args, "--shallow-exclude=%s",
1220 options.deepen_not.items[i].string);
1221 if (options.deepen_relative && options.depth)
1222 strvec_push(&args, "--deepen-relative");
1223 if (options.from_promisor)
1224 strvec_push(&args, "--from-promisor");
1225 if (options.refetch)
1226 strvec_push(&args, "--refetch");
1227 if (options.filter)
1228 strvec_pushf(&args, "--filter=%s", options.filter);
1229 strvec_push(&args, url.buf);
1231 for (i = 0; i < nr_heads; i++) {
1232 struct ref *ref = to_fetch[i];
1233 if (!*ref->name)
1234 die(_("cannot fetch by sha1 over smart http"));
1235 packet_buf_write(&preamble, "%s %s\n",
1236 oid_to_hex(&ref->old_oid), ref->name);
1238 packet_buf_flush(&preamble);
1240 memset(&rpc, 0, sizeof(rpc));
1241 rpc.service_name = "git-upload-pack",
1242 rpc.gzip_request = 1;
1244 err = rpc_service(&rpc, heads, args.v, &preamble, &rpc_result);
1245 if (rpc_result.len)
1246 write_or_die(1, rpc_result.buf, rpc_result.len);
1247 strbuf_release(&rpc_result);
1248 strbuf_release(&preamble);
1249 strvec_clear(&args);
1250 return err;
1253 static int fetch(int nr_heads, struct ref **to_fetch)
1255 struct discovery *d = discover_refs("git-upload-pack", 0);
1256 if (d->proto_git)
1257 return fetch_git(d, nr_heads, to_fetch);
1258 else
1259 return fetch_dumb(nr_heads, to_fetch);
1262 static void parse_fetch(struct strbuf *buf)
1264 struct ref **to_fetch = NULL;
1265 struct ref *list_head = NULL;
1266 struct ref **list = &list_head;
1267 int alloc_heads = 0, nr_heads = 0;
1269 do {
1270 const char *p;
1271 if (skip_prefix(buf->buf, "fetch ", &p)) {
1272 const char *name;
1273 struct ref *ref;
1274 struct object_id old_oid;
1275 const char *q;
1277 if (parse_oid_hex(p, &old_oid, &q))
1278 die(_("protocol error: expected sha/ref, got '%s'"), p);
1279 if (*q == ' ')
1280 name = q + 1;
1281 else if (!*q)
1282 name = "";
1283 else
1284 die(_("protocol error: expected sha/ref, got '%s'"), p);
1286 ref = alloc_ref(name);
1287 oidcpy(&ref->old_oid, &old_oid);
1289 *list = ref;
1290 list = &ref->next;
1292 ALLOC_GROW(to_fetch, nr_heads + 1, alloc_heads);
1293 to_fetch[nr_heads++] = ref;
1295 else
1296 die(_("http transport does not support %s"), buf->buf);
1298 strbuf_reset(buf);
1299 if (strbuf_getline_lf(buf, stdin) == EOF)
1300 return;
1301 if (!*buf->buf)
1302 break;
1303 } while (1);
1305 if (fetch(nr_heads, to_fetch))
1306 exit(128); /* error already reported */
1307 free_refs(list_head);
1308 free(to_fetch);
1310 printf("\n");
1311 fflush(stdout);
1312 strbuf_reset(buf);
1315 static void parse_get(const char *arg)
1317 struct strbuf url = STRBUF_INIT;
1318 struct strbuf path = STRBUF_INIT;
1319 const char *space;
1321 space = strchr(arg, ' ');
1323 if (!space)
1324 die(_("protocol error: expected '<url> <path>', missing space"));
1326 strbuf_add(&url, arg, space - arg);
1327 strbuf_addstr(&path, space + 1);
1329 if (http_get_file(url.buf, path.buf, NULL))
1330 die(_("failed to download file at URL '%s'"), url.buf);
1332 strbuf_release(&url);
1333 strbuf_release(&path);
1334 printf("\n");
1335 fflush(stdout);
1338 static int push_dav(int nr_spec, const char **specs)
1340 struct child_process child = CHILD_PROCESS_INIT;
1341 size_t i;
1343 child.git_cmd = 1;
1344 strvec_push(&child.args, "http-push");
1345 strvec_push(&child.args, "--helper-status");
1346 if (options.dry_run)
1347 strvec_push(&child.args, "--dry-run");
1348 if (options.verbosity > 1)
1349 strvec_push(&child.args, "--verbose");
1350 strvec_push(&child.args, url.buf);
1351 for (i = 0; i < nr_spec; i++)
1352 strvec_push(&child.args, specs[i]);
1354 if (run_command(&child))
1355 die(_("git-http-push failed"));
1356 return 0;
1359 static int push_git(struct discovery *heads, int nr_spec, const char **specs)
1361 struct rpc_state rpc = RPC_STATE_INIT;
1362 int i, err;
1363 struct strvec args;
1364 struct string_list_item *cas_option;
1365 struct strbuf preamble = STRBUF_INIT;
1366 struct strbuf rpc_result = STRBUF_INIT;
1368 strvec_init(&args);
1369 strvec_pushl(&args, "send-pack", "--stateless-rpc", "--helper-status",
1370 NULL);
1372 if (options.thin)
1373 strvec_push(&args, "--thin");
1374 if (options.dry_run)
1375 strvec_push(&args, "--dry-run");
1376 if (options.push_cert == SEND_PACK_PUSH_CERT_ALWAYS)
1377 strvec_push(&args, "--signed=yes");
1378 else if (options.push_cert == SEND_PACK_PUSH_CERT_IF_ASKED)
1379 strvec_push(&args, "--signed=if-asked");
1380 if (options.atomic)
1381 strvec_push(&args, "--atomic");
1382 if (options.verbosity == 0)
1383 strvec_push(&args, "--quiet");
1384 else if (options.verbosity > 1)
1385 strvec_push(&args, "--verbose");
1386 for (i = 0; i < options.push_options.nr; i++)
1387 strvec_pushf(&args, "--push-option=%s",
1388 options.push_options.items[i].string);
1389 strvec_push(&args, options.progress ? "--progress" : "--no-progress");
1390 for_each_string_list_item(cas_option, &cas_options)
1391 strvec_push(&args, cas_option->string);
1392 strvec_push(&args, url.buf);
1394 if (options.force_if_includes)
1395 strvec_push(&args, "--force-if-includes");
1397 strvec_push(&args, "--stdin");
1398 for (i = 0; i < nr_spec; i++)
1399 packet_buf_write(&preamble, "%s\n", specs[i]);
1400 packet_buf_flush(&preamble);
1402 memset(&rpc, 0, sizeof(rpc));
1403 rpc.service_name = "git-receive-pack",
1405 err = rpc_service(&rpc, heads, args.v, &preamble, &rpc_result);
1406 if (rpc_result.len)
1407 write_or_die(1, rpc_result.buf, rpc_result.len);
1408 strbuf_release(&rpc_result);
1409 strbuf_release(&preamble);
1410 strvec_clear(&args);
1411 return err;
1414 static int push(int nr_spec, const char **specs)
1416 struct discovery *heads = discover_refs("git-receive-pack", 1);
1417 int ret;
1419 if (heads->proto_git)
1420 ret = push_git(heads, nr_spec, specs);
1421 else
1422 ret = push_dav(nr_spec, specs);
1423 free_discovery(heads);
1424 return ret;
1427 static void parse_push(struct strbuf *buf)
1429 struct strvec specs = STRVEC_INIT;
1430 int ret;
1432 do {
1433 const char *arg;
1434 if (skip_prefix(buf->buf, "push ", &arg))
1435 strvec_push(&specs, arg);
1436 else
1437 die(_("http transport does not support %s"), buf->buf);
1439 strbuf_reset(buf);
1440 if (strbuf_getline_lf(buf, stdin) == EOF)
1441 goto free_specs;
1442 if (!*buf->buf)
1443 break;
1444 } while (1);
1446 ret = push(specs.nr, specs.v);
1447 printf("\n");
1448 fflush(stdout);
1450 if (ret)
1451 exit(128); /* error already reported */
1453 free_specs:
1454 strvec_clear(&specs);
1457 static int stateless_connect(const char *service_name)
1459 struct discovery *discover;
1460 struct rpc_state rpc = RPC_STATE_INIT;
1461 struct strbuf buf = STRBUF_INIT;
1462 const char *accept_language;
1465 * Run the info/refs request and see if the server supports protocol
1466 * v2. If and only if the server supports v2 can we successfully
1467 * establish a stateless connection, otherwise we need to tell the
1468 * client to fallback to using other transport helper functions to
1469 * complete their request.
1471 * The "git-upload-archive" service is a read-only operation. Fallback
1472 * to use "git-upload-pack" service to discover protocol version.
1474 if (!strcmp(service_name, "git-upload-archive"))
1475 discover = discover_refs("git-upload-pack", 0);
1476 else
1477 discover = discover_refs(service_name, 0);
1478 if (discover->version != protocol_v2) {
1479 printf("fallback\n");
1480 fflush(stdout);
1481 return -1;
1482 } else {
1483 /* Stateless Connection established */
1484 printf("\n");
1485 fflush(stdout);
1487 accept_language = http_get_accept_language_header();
1488 if (accept_language)
1489 rpc.hdr_accept_language = xstrfmt("%s", accept_language);
1491 rpc.service_name = service_name;
1492 rpc.service_url = xstrfmt("%s%s", url.buf, rpc.service_name);
1493 rpc.hdr_content_type = xstrfmt("Content-Type: application/x-%s-request", rpc.service_name);
1494 rpc.hdr_accept = xstrfmt("Accept: application/x-%s-result", rpc.service_name);
1495 if (get_protocol_http_header(discover->version, &buf)) {
1496 rpc.protocol_header = strbuf_detach(&buf, NULL);
1497 } else {
1498 rpc.protocol_header = NULL;
1499 strbuf_release(&buf);
1501 rpc.buf = xmalloc(http_post_buffer);
1502 rpc.alloc = http_post_buffer;
1503 rpc.len = 0;
1504 rpc.pos = 0;
1505 rpc.in = 1;
1506 rpc.out = 0;
1507 rpc.any_written = 0;
1508 rpc.gzip_request = 1;
1509 rpc.initial_buffer = 0;
1510 rpc.write_line_lengths = 1;
1511 rpc.flush_read_but_not_sent = 0;
1514 * Dump the capability listing that we got from the server earlier
1515 * during the info/refs request. This does not work with the
1516 * "git-upload-archive" service.
1518 if (strcmp(service_name, "git-upload-archive"))
1519 write_or_die(rpc.in, discover->buf, discover->len);
1521 /* Until we see EOF keep sending POSTs */
1522 while (1) {
1523 size_t avail;
1524 enum packet_read_status status;
1526 if (!rpc_read_from_out(&rpc, PACKET_READ_GENTLE_ON_EOF, &avail,
1527 &status))
1528 BUG("The entire rpc->buf should be larger than LARGE_PACKET_MAX");
1529 if (status == PACKET_READ_EOF)
1530 break;
1531 if (post_rpc(&rpc, 1, status == PACKET_READ_FLUSH))
1532 /* We would have an err here */
1533 break;
1534 /* Reset the buffer for next request */
1535 rpc.len = 0;
1538 free(rpc.service_url);
1539 free(rpc.hdr_content_type);
1540 free(rpc.hdr_accept);
1541 free(rpc.hdr_accept_language);
1542 free(rpc.protocol_header);
1543 free(rpc.buf);
1544 strbuf_release(&buf);
1546 return 0;
1549 int cmd_main(int argc, const char **argv)
1551 struct strbuf buf = STRBUF_INIT;
1552 int nongit;
1553 int ret = 1;
1555 setup_git_directory_gently(&nongit);
1556 if (argc < 2) {
1557 error(_("remote-curl: usage: git remote-curl <remote> [<url>]"));
1558 goto cleanup;
1561 options.verbosity = 1;
1562 options.progress = !!isatty(2);
1563 options.thin = 1;
1564 string_list_init_dup(&options.deepen_not);
1565 string_list_init_dup(&options.push_options);
1568 * Just report "remote-curl" here (folding all the various aliases
1569 * ("git-remote-http", "git-remote-https", and etc.) here since they
1570 * are all just copies of the same actual executable.
1572 trace2_cmd_name("remote-curl");
1574 remote = remote_get(argv[1]);
1576 if (argc > 2) {
1577 end_url_with_slash(&url, argv[2]);
1578 } else {
1579 end_url_with_slash(&url, remote->url.v[0]);
1582 http_init(remote, url.buf, 0);
1584 do {
1585 const char *arg;
1587 if (strbuf_getline_lf(&buf, stdin) == EOF) {
1588 if (ferror(stdin))
1589 error(_("remote-curl: error reading command stream from git"));
1590 goto cleanup;
1592 if (buf.len == 0)
1593 break;
1594 if (starts_with(buf.buf, "fetch ")) {
1595 if (nongit) {
1596 setup_git_directory_gently(&nongit);
1597 if (nongit)
1598 die(_("remote-curl: fetch attempted without a local repo"));
1600 parse_fetch(&buf);
1602 } else if (!strcmp(buf.buf, "list") || starts_with(buf.buf, "list ")) {
1603 int for_push = !!strstr(buf.buf + 4, "for-push");
1604 output_refs(get_refs(for_push));
1606 } else if (starts_with(buf.buf, "push ")) {
1607 parse_push(&buf);
1609 } else if (skip_prefix(buf.buf, "option ", &arg)) {
1610 const char *value = strchrnul(arg, ' ');
1611 size_t arglen = value - arg;
1612 int result;
1614 if (*value)
1615 value++; /* skip over SP */
1616 else
1617 value = "true";
1619 result = set_option(arg, arglen, value);
1620 if (!result)
1621 printf("ok\n");
1622 else if (result < 0)
1623 printf("error invalid value\n");
1624 else
1625 printf("unsupported\n");
1626 fflush(stdout);
1628 } else if (skip_prefix(buf.buf, "get ", &arg)) {
1629 parse_get(arg);
1630 fflush(stdout);
1632 } else if (!strcmp(buf.buf, "capabilities")) {
1633 printf("stateless-connect\n");
1634 printf("fetch\n");
1635 printf("get\n");
1636 printf("option\n");
1637 printf("push\n");
1638 printf("check-connectivity\n");
1639 printf("object-format\n");
1640 printf("\n");
1641 fflush(stdout);
1642 } else if (skip_prefix(buf.buf, "stateless-connect ", &arg)) {
1643 if (!stateless_connect(arg))
1644 break;
1645 } else {
1646 error(_("remote-curl: unknown command '%s' from git"), buf.buf);
1647 goto cleanup;
1649 strbuf_reset(&buf);
1650 } while (1);
1652 http_cleanup();
1653 ret = 0;
1654 cleanup:
1655 strbuf_release(&buf);
1657 return ret;